@synadia-ai/agent-fabric-claude-code 0.2.0 → 0.3.1
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/.claude-plugin/plugin.json +1 -1
- package/BUILD +3 -3
- package/README.md +4 -2
- package/hooks/hooks.json +22 -0
- package/hooks/session-event.js +12 -9
- package/package.json +1 -1
- package/runtime/chunk-5ke4ws7r.js +38 -0
- package/runtime/fabric.js +5 -5
- package/runtime/server.js +37 -34
- package/skills/scratchpad/SKILL.md +87 -6
- package/skills/scratchpad/scripts/sp +13 -7
- package/runtime/chunk-prncr0vg.js +0 -38
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var Pd=Object.create;var{getPrototypeOf:Td,defineProperty:xn,getOwnPropertyNames:jd}=Object;var Id=Object.prototype.hasOwnProperty;function Nd(e){return this[e]}var Cd,kd,wr=(e,t,r)=>{var s=e!=null&&typeof e==="object";if(s){var n=t?Cd??=new WeakMap:kd??=new WeakMap,o=n.get(e);if(o)return o}r=e!=null?Pd(Td(e)):{};let c=t||!e||!e.__esModule?xn(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let h of jd(e))if(!Id.call(c,h))xn(c,h,{get:Nd.bind(e,h),enumerable:!0})}if(s)n.set(e,c);return c};var H=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Md=(e)=>e;function Rd(e,t){this[e]=Md.bind(null,t)}var qg=(e,t)=>{for(var r in t)xn(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Rd.bind(t,r)})};var Rt=import.meta.require;var Ve=H(function(Ro){Object.defineProperty(Ro,"__esModule",{value:!0});Ro.TD=Ro.TE=Ro.Empty=void 0;Ro.encode=$d;Ro.decode=Ud;Ro.Empty=new Uint8Array(0);Ro.TE=new TextEncoder;Ro.TD=new TextDecoder;function qd(...e){let t=0;for(let n=0;n<e.length;n++)t+=e[n].length;let r=new Uint8Array(t),s=0;for(let n=0;n<e.length;n++)r.set(e[n],s),s+=e[n].length;return r}function $d(...e){let t=[];for(let r=0;r<e.length;r++)t.push(Ro.TE.encode(e[r]));if(t.length===0)return Ro.Empty;if(t.length===1)return t[0];return qd(...t)}function Ud(e){if(!e||e.length===0)return"";return Ro.TD.decode(e)}});var Je=H(function(Uo){Object.defineProperty(Uo,"__esModule",{value:!0});Uo.errors=Uo.PermissionViolationError=Uo.NoRespondersError=Uo.TimeoutError=Uo.RequestError=Uo.ProtocolError=Uo.ConnectionError=Uo.DrainingConnectionError=Uo.ClosedConnectionError=Uo.AuthorizationError=Uo.UserAuthenticationExpiredError=Uo.InvalidOperationError=Uo.InvalidArgumentError=Uo.InvalidSubjectError=void 0;class vn extends Error{constructor(e,t){super(`illegal subject: '${e}'`,t);this.name="InvalidSubjectError"}}Uo.InvalidSubjectError=vn;class es extends Error{constructor(e,t){super(e,t);this.name="InvalidArgumentError"}static format(e,t,r){if(Array.isArray(t)&&t.length>1)t=t[0];if(Array.isArray(e))e=e.map((s)=>`'${s}'`),e=e.join(",");else e=`'${e}'`;return new es(`${e} ${t}`,r)}}Uo.InvalidArgumentError=es;class _n extends Error{constructor(e,t){super(e,t);this.name="InvalidOperationError"}}Uo.InvalidOperationError=_n;class ts extends Error{constructor(e,t){super(e,t);this.name="UserAuthenticationExpiredError"}static parse(e){if(e.toLowerCase().indexOf("user authentication expired")!==-1)return new ts(e);return null}}Uo.UserAuthenticationExpiredError=ts;class rs extends Error{constructor(e,t){super(e,t);this.name="AuthorizationError"}static parse(e){let t=["authorization violation","account authentication expired","authentication timeout"],r=e.toLowerCase();for(let s=0;s<t.length;s++)if(r.indexOf(t[s])!==-1)return new rs(e);return null}}Uo.AuthorizationError=rs;class En extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}Uo.ClosedConnectionError=En;class Sn extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}Uo.DrainingConnectionError=Sn;class An extends Error{constructor(e,t){super(e,t);this.name="ConnectionError"}}Uo.ConnectionError=An;class On extends Error{constructor(e,t){super(e,t);this.name="ProtocolError"}}Uo.ProtocolError=On;class Pn extends Error{constructor(e="",t){super(e,t);this.name="RequestError"}isNoResponders(){return this.cause instanceof ss}}Uo.RequestError=Pn;class Tn extends Error{constructor(e){super("timeout",e);this.name="TimeoutError"}}Uo.TimeoutError=Tn;class ss extends Error{subject;constructor(e,t){super(`no responders: '${e}'`,t);this.subject=e,this.name="NoResponders"}}Uo.NoRespondersError=ss;class ns extends Error{operation;subject;queue;constructor(e,t,r,s,n){super(e,n);this.name="PermissionViolationError",this.operation=t,this.subject=r,this.queue=s}static parse(e){if((e?e.toLowerCase():"").indexOf("permissions violation")===-1)return null;let r="publish",s="",n=void 0,o=e.match(/(Publish|Subscription) to "(\S+)"/);if(o){if(r=o[1].toLowerCase(),s=o[2],r==="subscription"){let c=e.match(/using queue "(\S+)"/);if(c)n=c[1]}}return new ns(e,r,s,n)}}Uo.PermissionViolationError=ns;Uo.errors={AuthorizationError:rs,ClosedConnectionError:En,ConnectionError:An,DrainingConnectionError:Sn,InvalidArgumentError:es,InvalidOperationError:_n,InvalidSubjectError:vn,NoRespondersError:ss,PermissionViolationError:ns,ProtocolError:On,RequestError:Pn,TimeoutError:Tn,UserAuthenticationExpiredError:ts}});var rt=H(function(Ko){Object.defineProperty(Ko,"__esModule",{value:!0});Ko.SimpleMutex=Ko.Perf=void 0;Ko.extend=th;Ko.render=rh;Ko.timeout=sh;Ko.delay=nh;Ko.deadline=ih;Ko.deferred=In;Ko.debugDeferred=oh;Ko.shuffle=ah;Ko.collect=ch;Ko.jitter=Bo;Ko.backoff=uh;Ko.nanos=fh;Ko.millis=dh;Ko.randomToken=ph;var eh=Ve(),jn=Je();function th(e,...t){for(let r=0;r<t.length;r++){let s=t[r];Object.keys(s).forEach(function(n){e[n]=s[n]})}return e}function rh(e){return eh.TD.decode(e).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function sh(e,t=!0){let r=t?new jn.TimeoutError:null,s,n,o=new Promise((c,h)=>{s={cancel:()=>{if(n)clearTimeout(n)}},n=setTimeout(()=>{if(r===null)h(new jn.TimeoutError);else h(r)},e)});return Object.assign(o,s)}function nh(e=0){let t,r=new Promise((s)=>{let n=setTimeout(()=>{s()},e);t={cancel:()=>{if(n)clearTimeout(n),s()}}});return Object.assign(r,t)}async function ih(e,t=1000){let r=In(),s=setTimeout(()=>{r.reject(new jn.TimeoutError)},t);try{return await Promise.race([e,r])}finally{clearTimeout(s)}}function In(){let e={},t=new Promise((r,s)=>{e={resolve:r,reject:s}});return Object.assign(t,e)}function oh(){let e={},t=new Promise((r,s)=>{e={resolve:(n)=>{console.trace("resolve",n),r(n)},reject:(n)=>{console.trace("reject"),s(n)}}});return Object.assign(t,e)}function ah(e){for(let t=e.length-1;t>0;t--){let r=Math.floor(Math.random()*(t+1));[e[t],e[r]]=[e[r],e[t]]}return e}async function ch(e){let t=[];for await(let r of e)t.push(r);return t}class Do{timers;measures;constructor(){this.timers=new Map,this.measures=new Map}mark(e){this.timers.set(e,performance.now())}measure(e,t,r){let s=this.timers.get(t);if(s===void 0)throw Error(`${t} is not defined`);let n=this.timers.get(r);if(n===void 0)throw Error(`${r} is not defined`);this.measures.set(e,n-s)}getEntries(){let e=[];return this.measures.forEach((t,r)=>{e.push({name:r,duration:t})}),e}}Ko.Perf=Do;class Fo{max;current;waiting;constructor(e=1){this.max=e,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let e=In();return this.waiting.push(e),e}unlock(){this.current--,this.waiting.pop()?.resolve()}}Ko.SimpleMutex=Fo;function Bo(e){if(e===0)return 0;return Math.floor(e/2+Math.random()*e)}function uh(e=[0,250,250,500,500,3000,5000]){if(!Array.isArray(e))e=[0,250,250,500,500,3000,5000];let t=e.length-1;return{backoff(r){return Bo(r>t?e[t]:e[r])}}}function fh(e){return e*1e6}function dh(e){return Math.floor(e/1e6)}var hh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",bt=new Uint8Array(62);for(let e=0;e<62;e++)bt[e]=hh.charCodeAt(e);var lh=218340105584896;function ph(){let e=Math.floor(Math.random()*lh),t=e%62,r=bt[t];e=(e-t)/62,t=e%62;let s=bt[t];e=(e-t)/62,t=e%62;let n=bt[t];e=(e-t)/62,t=e%62;let o=bt[t];e=(e-t)/62,t=e%62;let c=bt[t];e=(e-t)/62,t=e%62;let h=bt[t];e=(e-t)/62,t=e%62;let p=bt[t];e=(e-t)/62;let w=bt[e];return String.fromCharCode(r,s,n,o,c,h,p,w)}});var Xo=H(function(Wo){Object.defineProperty(Wo,"__esModule",{value:!0});Wo.nuid=Wo.NuidImpl=void 0;var Ih="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",_t=62,os=12,Vo=10,zo=33,Nh=333,Go=os+Vo,Cn=new Uint8Array(_t);for(let e=0;e<_t;e++)Cn[e]=Ih.charCodeAt(e);var is=4294967296,Jo=BigInt(_t)**BigInt(Vo),vr=Number(Jo/(1n<<32n)),Nn=Number(Jo%(1n<<32n));function Ch(e){for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}function kh(e){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues(e);else Ch(e)}class kn{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(Go),this.cbuf=new Uint8Array(os),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let e=0;do this.seqHi=Math.floor(Math.random()*(vr+1)),this.seqLo=Math.floor(Math.random()*is);while(e++<8&&this.seqHi===vr&&this.seqLo>=Nn);if(this.seqHi===vr&&this.seqLo>=Nn)this.seqLo=0;this.inc=Math.random()*(Nh-zo)+zo|0}setPre(){kh(this.cbuf);for(let e=0;e<os;e++)this.buf[e]=Cn[this.cbuf[e]%_t]}fillSeq(){let e=this.seqHi,t=this.seqLo;for(let r=Go-1;r>=os;r--){let s=Math.floor(e/_t),o=(e-s*_t)*is+t,c=Math.floor(o/_t),h=o-c*_t;this.buf[r]=Cn[h],e=s,t=c}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=is)this.seqLo-=is,this.seqHi+=1;if(this.seqHi>vr||this.seqHi===vr&&this.seqLo>=Nn)this.setPre(),this.initSeqAndInc();this.fillSeq();let e=this.buf;return String.fromCharCode(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15],e[16],e[17],e[18],e[19],e[20],e[21])}reset(){this.init()}}Wo.NuidImpl=kn;Wo.nuid=new kn});var ta=H(function(Qo){Object.defineProperty(Qo,"__esModule",{value:!0});Qo.nuid=Qo.Nuid=void 0;var Zo=Xo();Qo.Nuid=Zo.NuidImpl;Qo.nuid=Zo.nuid});var cs=H(function(as){Object.defineProperty(as,"__esModule",{value:!0});as.nuid=as.Nuid=void 0;var ra=ta();Object.defineProperty(as,"Nuid",{enumerable:!0,get:function(){return ra.Nuid}});Object.defineProperty(as,"nuid",{enumerable:!0,get:function(){return ra.nuid}})});var Et=H(function(sa){Object.defineProperty(sa,"__esModule",{value:!0});sa.DEFAULT_HOST=sa.DEFAULT_PORT=sa.Match=void 0;sa.syncIterator=Lh;sa.createInbox=Dh;var $h=cs(),Uh=Je();sa.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function Lh(e){let t=e[Symbol.asyncIterator]();return{async next(){let r=await t.next();if(r.done)return Promise.resolve(null);return Promise.resolve(r.value)}}}function Dh(e=""){if(e=e||"_INBOX",typeof e!=="string")throw TypeError("prefix must be a string");return e.split(".").forEach((t)=>{if(t==="*"||t===">")throw Uh.InvalidArgumentError.format("prefix",`cannot have wildcards ('${e}')`)}),`${e}.${$h.nuid.next()}`}sa.DEFAULT_PORT=4222;sa.DEFAULT_HOST="127.0.0.1"});var _r=H(function(aa){Object.defineProperty(aa,"__esModule",{value:!0});aa.DataBuffer=void 0;var ia=Ve();class oa{buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...e){let t=0;for(let n=0;n<e.length;n++)t+=e[n].length;let r=new Uint8Array(t),s=0;for(let n=0;n<e.length;n++)r.set(e[n],s),s+=e[n].length;return r}static fromAscii(e){if(!e)e="";return ia.TE.encode(e)}static toAscii(e){return ia.TD.decode(e)}reset(){this.buffers.length=0,this.byteLength=0}pack(){if(this.buffers.length>1){let e=new Uint8Array(this.byteLength),t=0;for(let r=0;r<this.buffers.length;r++)e.set(this.buffers[r],t),t+=this.buffers[r].length;this.buffers.length=0,this.buffers.push(e)}}shift(){if(this.buffers.length){let e=this.buffers.shift();if(e)return this.byteLength-=e.length,e}return new Uint8Array(0)}drain(e){if(this.buffers.length){this.pack();let t=this.buffers.pop();if(t){let r=this.byteLength;if(e===void 0||e>r)e=r;let s=t.subarray(0,e);if(r>e)this.buffers.push(t.subarray(e));return this.byteLength=r-e,s}}return new Uint8Array(0)}fill(e,...t){if(e)this.buffers.push(e),this.byteLength+=e.length;for(let r=0;r<t.length;r++)if(t[r]&&t[r].length)this.buffers.push(t[r]),this.byteLength+=t[r].length}peek(){if(this.buffers.length)return this.pack(),this.buffers[0];return new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}aa.DataBuffer=oa});var qt=H(function(fa){Object.defineProperty(fa,"__esModule",{value:!0});fa.LF=fa.CR=fa.CRLF=fa.CR_LF_LEN=fa.CR_LF=void 0;fa.setTransportFactory=Jh;fa.defaultPort=Wh;fa.getUrlParseFn=Yh;fa.newTransport=Xh;fa.getResolveFn=Zh;fa.protoLen=ua;fa.extractProtocolMessage=Qh;var zh=Ve(),Gh=Et(),Vh=_r(),We;function Jh(e){We=e}function Wh(){return We!==void 0&&We.defaultPort!==void 0?We.defaultPort:Gh.DEFAULT_PORT}function Yh(){return We!==void 0&&We.urlParseFn?We.urlParseFn:void 0}function Xh(){if(!We||typeof We.factory!=="function")throw Error("transport fn is not set");return We.factory()}function Zh(){return We!==void 0&&We.dnsResolveFn?We.dnsResolveFn:void 0}fa.CR_LF=`\r
|
|
3
|
+
`;fa.CR_LF_LEN=fa.CR_LF.length;fa.CRLF=Vh.DataBuffer.fromAscii(fa.CR_LF);fa.CR=new Uint8Array(fa.CRLF)[0];fa.LF=new Uint8Array(fa.CRLF)[1];function ua(e){for(let t=0;t<e.length;t++){let r=t+1;if(e.byteLength>r&&e[t]===fa.CR&&e[r]===fa.LF)return r+1}return 0}function Qh(e){let t=ua(e);if(t>0){let s=new Uint8Array(e).slice(0,t);return zh.TD.decode(s)}return""}});var Un=H(function(ga){Object.defineProperty(ga,"__esModule",{value:!0});ga.ipV4=ya;ga.isIP=fl;ga.parseIP=ba;var Er=4,$t=16,us=48,pa=57,ha=65,cl=70,la=97,ul=102,$n=16777215;function ya(e,t,r,s){let n=new Uint8Array($t);return[0,0,0,0,0,0,0,0,0,0,255,255].forEach((c,h)=>{n[h]=c}),n[12]=e,n[13]=t,n[14]=r,n[15]=s,n}function fl(e){return ba(e)!==void 0}function ba(e){for(let t=0;t<e.length;t++)switch(e[t]){case".":return ma(e);case":":return dl(e)}return}function ma(e){let t=new Uint8Array(Er);for(let r=0;r<Er;r++){if(e.length===0)return;if(r>0){if(e[0]!==".")return;e=e.substring(1)}let{n:s,c:n,ok:o}=hl(e);if(!o||s>255)return;e=e.substring(n),t[r]=s}return ya(t[0],t[1],t[2],t[3])}function dl(e){let t=new Uint8Array($t),r=-1;if(e.length>=2&&e[0]===":"&&e[1]===":"){if(r=0,e=e.substring(2),e.length===0)return t}let s=0;while(s<$t){let{n,c:o,ok:c}=ll(e);if(!c||n>65535)return;if(o<e.length&&e[o]==="."){if(r<0&&s!=$t-Er)return;if(s+Er>$t)return;let h=ma(e);if(h===void 0)return;t[s]=h[12],t[s+1]=h[13],t[s+2]=h[14],t[s+3]=h[15],e="",s+=Er;break}if(t[s]=n>>8,t[s+1]=n,s+=2,e=e.substring(o),e.length===0)break;if(e[0]!==":"||e.length==1)return;if(e=e.substring(1),e[0]===":"){if(r>=0)return;if(r=s,e=e.substring(1),e.length===0)break}}if(e.length!==0)return;if(s<$t){if(r<0)return;let n=$t-s;for(let o=s-1;o>=r;o--)t[o+n]=t[o];for(let o=r+n-1;o>=r;o--)t[o]=0}else if(r>=0)return;return t}function hl(e){let t=0,r=0;for(t=0;t<e.length&&us<=e.charCodeAt(t)&&e.charCodeAt(t)<=pa;t++)if(r=r*10+(e.charCodeAt(t)-us),r>=$n)return{n:$n,c:t,ok:!1};if(t===0)return{n:0,c:0,ok:!1};return{n:r,c:t,ok:!0}}function ll(e){let t=0,r=0;for(r=0;r<e.length;r++){if(us<=e.charCodeAt(r)&&e.charCodeAt(r)<=pa)t*=16,t+=e.charCodeAt(r)-us;else if(la<=e.charCodeAt(r)&&e.charCodeAt(r)<=ul)t*=16,t+=e.charCodeAt(r)-la+10;else if(ha<=e.charCodeAt(r)&&e.charCodeAt(r)<=cl)t*=16,t+=e.charCodeAt(r)-ha+10;else break;if(t>=$n)return{n:0,c:r,ok:!1}}if(r===0)return{n:0,c:r,ok:!1};return{n:t,c:r,ok:!0}}});var Hn=H(function(wa){Object.defineProperty(wa,"__esModule",{value:!0});wa.Servers=wa.ServerImpl=void 0;wa.isIPV4OrHostname=xa;wa.hostPort=Kn;var Ln=qt(),Dn=rt(),Fn=Un(),ml=Et(),gl=Je();function xa(e){if(e.indexOf("[")!==-1||e.indexOf("::")!==-1)return!1;if(e.indexOf(".")!==-1)return!0;if(e.split(":").length<=2)return!0;return!1}function Bn(e){return!xa(e)}function xl(e){let r=e.toUpperCase().indexOf("::FFFF:");if(r!==-1&&e.indexOf(".")!==-1){let s=e.substring(r+7);return s=s.replace("[",""),s.replace("]","")}return e}function Kn(e){if(e=e.trim(),e.match(/^(.*:\/\/)(.*)/m))e=e.replace(/^(.*:\/\/)(.*)/gm,"$2");if(e=xl(e),Bn(e)&&e.indexOf("[")===-1)e=`[${e}]`;let t=Bn(e)?e.match(/(]:)(\d+)/):e.match(/(:)(\d+)/),r=t&&t.length===3&&t[1]&&t[2]?parseInt(t[2]):ml.DEFAULT_PORT,n=new URL(`${r===80?"https":"http"}://${e}`);n.port=`${r}`;let o=n.hostname;if(o.charAt(0)==="[")o=o.substring(1,o.length-1);return{listen:n.host,hostname:o,port:r}}class Qt{src;listen;hostname;port;didConnect;reconnects;lastConnect;gossiped;tlsName;resolves;constructor(e,t=!1){this.src=e,this.tlsName="";let r=Kn(e);this.listen=r.listen,this.hostname=r.hostname,this.port=r.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];let t=[];if((0,Fn.isIP)(this.hostname))return[this];else{let r=await e.fn(this.hostname);if(e.debug)console.log(`resolve ${this.hostname} = ${r.join(",")}`);for(let s of r){let n=this.port===80?"https":"http",o=new URL(`${n}://${Bn(s)?"["+s+"]":s}`);o.port=`${this.port}`;let c=new Qt(o.host,!1);c.tlsName=this.hostname,t.push(c)}}if(e.randomize)(0,Dn.shuffle)(t);return this.resolves=t,t}}wa.ServerImpl=Qt;class fs{firstSelect;servers;currentServer;tlsName;randomize;constructor(e={}){this.firstSelect=!0,this.servers=[],this.tlsName="",this.randomize=e.randomize||!1}setServers(e){if(!Array.isArray(e)||e.length===0)throw gl.InvalidArgumentError.format("servers","cannot be empty");let t=(0,Ln.getUrlParseFn)(),r=new Map;for(let n of this.servers)r.set(n.listen,n);let s=[];for(let n of e){n=t?t(n):n;let{listen:o}=Kn(n),c=r.get(o);if(c)c.gossiped=!1,s.push(c);else s.push(new Qt(n))}if(this.randomize)(0,Dn.shuffle)(s);if(this.servers=s,this.currentServer===void 0||!s.includes(this.currentServer))this.currentServer=s[0],this.firstSelect=!0}clear(){this.servers.length=0}updateTLSName(){let e=this.getCurrentServer();if(!(0,Fn.isIP)(e.hostname))this.tlsName=e.hostname,this.servers.forEach((t)=>{if(t.gossiped)t.tlsName=this.tlsName})}getCurrentServer(){return this.currentServer}addServer(e,t=!1){let r=(0,Ln.getUrlParseFn)();e=r?r(e):e;let s=new Qt(e,t);if((0,Fn.isIP)(s.hostname))s.tlsName=this.tlsName;this.servers.push(s)}selectServer(){if(this.firstSelect)return this.firstSelect=!1,this.currentServer;let e=this.servers.shift();if(e)this.servers.push(e),this.currentServer=e;return e}removeCurrentServer(){this.removeServer(this.currentServer)}removeServer(e){if(e){let t=this.servers.indexOf(e);this.servers.splice(t,1)}}snapshot(){return fs.freezeAll(this.servers)}snapshotForHandler(){let e=this.currentServer;if(!e)return this.snapshot();let t=this.servers.indexOf(e);if(t<=0)return this.snapshot();return fs.freezeAll([e,...this.servers.slice(0,t),...this.servers.slice(t+1)])}static freezeAll(e){return e.map((t)=>Object.freeze({hostname:t.hostname,port:t.port,listen:t.listen,src:t.src,tlsName:t.tlsName,reconnects:t.reconnects,lastConnect:t.lastConnect,gossiped:t.gossiped,didConnect:t.didConnect}))}find(e){return this.servers.find((t)=>t.listen===e.listen)}setCurrent(e){this.currentServer=e}length(){return this.servers.length}next(){return this.servers.length?this.servers[0]:void 0}getServers(){return this.servers}update(e,t){let r=[],s=[],n=(0,Ln.getUrlParseFn)(),o=new Map;if(e.connect_urls&&e.connect_urls.length>0)e.connect_urls.forEach((h)=>{h=n?n(h,t):h;let p=new Qt(h,!0);o.set(h,p)});let c=[];if(this.servers.forEach((h,p)=>{let w=h.listen;if(h.gossiped&&this.currentServer.listen!==w&&o.get(w)===void 0)c.push(p);o.delete(w)}),c.reverse(),c.forEach((h)=>{let p=this.servers.splice(h,1);s=s.concat(p[0].listen)}),o.forEach((h,p)=>{this.servers.push(h),r.push(p)}),this.randomize&&r.length>0){let h=this.currentServer,p=this.servers.filter((w)=>w!==h);(0,Dn.shuffle)(p),this.servers=h?[h,...p]:p}return{added:r,deleted:s}}}wa.Servers=fs});var ds=H(function(Sa){Object.defineProperty(Sa,"__esModule",{value:!0});Sa.QueuedIteratorImpl=void 0;var zn=rt(),_a=Je();class Ea{inflight;processed;received;noIterator;iterClosed;done;signal;yields;filtered;pendingFiltered;ctx;_data;err;time;profile;yielding;didBreak;constructor(){this.inflight=0,this.filtered=0,this.pendingFiltered=0,this.processed=0,this.received=0,this.noIterator=!1,this.done=!1,this.signal=(0,zn.deferred)(),this.yields=[],this.iterClosed=(0,zn.deferred)(),this.time=0,this.yielding=!1,this.didBreak=!1,this.profile=!1}[Symbol.asyncIterator](){return this.iterate()}push(e){if(this.done)return;if(this.didBreak){if(typeof e==="function"){let t=e;try{t()}catch(r){}}return}if(typeof e==="function")this.pendingFiltered++;this.yields.push(e),this.signal.resolve()}async*iterate(){if(this.noIterator)throw new _a.InvalidOperationError("iterator cannot be used when a callback is registered");if(this.yielding)throw new _a.InvalidOperationError("iterator is already yielding");this.yielding=!0;try{while(!0){if(this.yields.length===0)await this.signal;if(this.err)throw this.err;let e=this.yields;this.inflight=e.length,this.yields=[];for(let t=0;t<e.length;t++){if(typeof e[t]==="function"){this.pendingFiltered--;let s=e[t];try{s()}catch(n){throw n}if(this.err)throw this.err;continue}this.processed++,this.inflight--;let r=this.profile?Date.now():0;yield e[t],this.time=this.profile?Date.now()-r:0}if(this.done)break;else if(this.yields.length===0)e.length=0,this.yields=e,this.signal=(0,zn.deferred)()}}finally{this.didBreak=!0,this.stop()}}stop(e){if(this.done)return;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}}Sa.QueuedIteratorImpl=Ea});var Gn=H(function(Ta){Object.defineProperty(Ta,"__esModule",{value:!0});Ta.MuxSubscription=void 0;var El=Et(),Oa=Je();class Pa{baseInbox;reqs;constructor(){this.reqs=new Map}size(){return this.reqs.size}init(e){return this.baseInbox=`${(0,El.createInbox)(e)}.`,this.baseInbox}add(e){if(!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){let t=e.subject||"";if(t.indexOf(this.baseInbox)===0)return t.substring(this.baseInbox.length);return null}all(){return Array.from(this.reqs.values())}handleError(e,t){if(e)return this.all().forEach((r)=>{r.resolver(t,{})}),!0;if(t.operation==="publish"){let r=this.all().find((s)=>s.requestSubject===t.subject);if(r)return r.resolver(t,{}),!0}return!1}dispatcher(){return(e,t)=>{let r=this.getToken(t);if(r){let s=this.get(r);if(s){if(e===null)e=t?.data?.length===0&&t.headers?.code===503?new Oa.NoRespondersError(s.requestSubject):null;s.resolver(e,t)}}}}close(){let e=new Oa.RequestError("connection closed");this.reqs.forEach((t)=>{t.resolver(e,{})})}}Ta.MuxSubscription=Pa});var Vn=H(function(Na){Object.defineProperty(Na,"__esModule",{value:!0});Na.Heartbeat=void 0;var Sl=rt();class Ia{ph;interval;maxOut;timer;pendings;constructor(e,t,r){this.ph=e,this.interval=t,this.maxOut=r,this.pendings=[]}start(){this.cancel(),this._schedule()}cancel(e){if(this.timer)clearTimeout(this.timer),this.timer=void 0;if(this._reset(),e)this.ph.disconnect()}_schedule(){this.timer=setTimeout(()=>{if(this.ph.dispatchStatus({type:"ping",pendingPings:this.pendings.length+1}),this.pendings.length===this.maxOut){this.cancel(!0);return}let e=(0,Sl.deferred)();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))}}Na.Heartbeat=Ia});var Yn=H(function(qa){Object.defineProperty(qa,"__esModule",{value:!0});qa.DenoBuffer=qa.MAX_SIZE=qa.AssertionError=void 0;qa.assert=Ma;qa.concat=Ra;qa.append=Ol;qa.readAll=Pl;qa.writeAll=Tl;var Al=Ve();class Jn extends Error{constructor(e){super(e);this.name="AssertionError"}}qa.AssertionError=Jn;function Ma(e,t="Assertion failed."){if(!e)throw new Jn(t)}var ka=32768;qa.MAX_SIZE=4294967294;function hs(e,t,r=0){let s=t.byteLength-r;if(e.byteLength>s)e=e.subarray(0,s);return t.set(e,r),e.byteLength}function Ra(e,t){if(e===void 0&&t===void 0)return new Uint8Array(0);if(e===void 0)return t;if(t===void 0)return e;let r=new Uint8Array(e.length+t.length);return r.set(e,0),r.set(t,e.length),r}function Ol(e,t){return Ra(e,Uint8Array.of(t))}class Wn{_buf;_off;constructor(e){if(this._off=0,e==null){this._buf=new Uint8Array(0);return}this._buf=new Uint8Array(e)}bytes(e={copy:!0}){if(e.copy===!1)return this._buf.subarray(this._off);return 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){let t=this._buf.byteLength;if(e<=this.capacity-t)return this._reslice(t+e),t;return-1}_reslice(e){Ma(e<=this._buf.buffer.byteLength),this._buf=new Uint8Array(this._buf.buffer,0,e)}readByte(){let e=new Uint8Array(1);if(this.read(e))return e[0];return null}read(e){if(this.empty()){if(this.reset(),e.byteLength===0)return 0;return null}let t=hs(this._buf.subarray(this._off),e);return this._off+=t,t}writeByte(e){return this.write(Uint8Array.of(e))}writeString(e){return this.write(Al.TE.encode(e))}write(e){let t=this._grow(e.byteLength);return hs(e,this._buf,t)}_grow(e){let t=this.length;if(t===0&&this._off!==0)this.reset();let r=this._tryGrowByReslice(e);if(r>=0)return r;let s=this.capacity;if(e<=Math.floor(s/2)-t)hs(this._buf.subarray(this._off),this._buf);else if(s+e>qa.MAX_SIZE)throw Error("The buffer cannot be grown beyond the maximum size.");else{let n=new Uint8Array(Math.min(2*s+e,qa.MAX_SIZE));hs(this._buf.subarray(this._off),n),this._buf=n}return this._off=0,this._reslice(Math.min(t+e,qa.MAX_SIZE)),t}grow(e){if(e<0)throw Error("Buffer._grow: negative count");let t=this._grow(e);this._reslice(t)}readFrom(e){let t=0,r=new Uint8Array(ka);while(!0){let s=this.capacity-this.length<ka,n=s?r:new Uint8Array(this._buf.buffer,this.length),o=e.read(n);if(o===null)return t;if(s)this.write(n.subarray(0,o));else this._reslice(this.length+o);t+=o}}}qa.DenoBuffer=Wn;function Pl(e){let t=new Wn;return t.readFrom(e),t.bytes()}function Tl(e,t){let r=0;while(r<t.length)r+=e.write(t.subarray(r))}});var Qn=H(function(Fa){Object.defineProperty(Fa,"__esModule",{value:!0});Fa.cc=Fa.State=Fa.Parser=Fa.Kind=void 0;Fa.describe=Rl;var Xn=Yn(),Zn=Ve();Fa.Kind={OK:0,ERR:1,MSG:2,INFO:3,PING:4,PONG:5};function Rl(e){let t,r="";switch(e.kind){case Fa.Kind.MSG:t="MSG";break;case Fa.Kind.OK:t="OK";break;case Fa.Kind.ERR:t="ERR",r=Zn.TD.decode(e.data);break;case Fa.Kind.PING:t="PING";break;case Fa.Kind.PONG:t="PONG";break;case Fa.Kind.INFO:t="INFO",r=Zn.TD.decode(e.data)}return`${t}: ${r}`}function Ua(){let e={};return e.sid=-1,e.hdr=-1,e.size=-1,e}var La=48,ql=57,er=67108864;class Da{dispatcher;state;as;drop;hdr;ma;argBuf;msgBuf;constructor(e){this.dispatcher=e,this.state=Fa.State.OP_START,this.as=0,this.drop=0,this.hdr=0}parse(e){let t;for(t=0;t<e.length;t++){let r=e[t];switch(this.state){case Fa.State.OP_START:switch(r){case Fa.cc.M:case Fa.cc.m:this.state=Fa.State.OP_M,this.hdr=-1,this.ma=Ua();break;case Fa.cc.H:case Fa.cc.h:this.state=Fa.State.OP_H,this.hdr=0,this.ma=Ua();break;case Fa.cc.P:case Fa.cc.p:this.state=Fa.State.OP_P;break;case Fa.cc.PLUS:this.state=Fa.State.OP_PLUS;break;case Fa.cc.MINUS:this.state=Fa.State.OP_MINUS;break;case Fa.cc.I:case Fa.cc.i:this.state=Fa.State.OP_I;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_H:switch(r){case Fa.cc.M:case Fa.cc.m:this.state=Fa.State.OP_M;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_M:switch(r){case Fa.cc.S:case Fa.cc.s:this.state=Fa.State.OP_MS;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_MS:switch(r){case Fa.cc.G:case Fa.cc.g:this.state=Fa.State.OP_MSG;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_MSG:switch(r){case Fa.cc.SPACE:case Fa.cc.TAB:this.state=Fa.State.OP_MSG_SPC;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_MSG_SPC:switch(r){case Fa.cc.SPACE:case Fa.cc.TAB:continue;default:this.state=Fa.State.MSG_ARG,this.as=t}break;case Fa.State.MSG_ARG:switch(r){case Fa.cc.CR:this.drop=1;break;case Fa.cc.NL:{let s=this.argBuf?this.argBuf.bytes():e.subarray(this.as,t-this.drop);this.processMsgArgs(s),this.drop=0,this.as=t+1,this.state=Fa.State.MSG_PAYLOAD,t=this.as+this.ma.size-1;break}default:if(this.argBuf)this.argBuf.writeByte(r)}break;case Fa.State.MSG_PAYLOAD:if(this.msgBuf)if(this.msgBuf.length>=this.ma.size){let s=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:Fa.Kind.MSG,msg:this.ma,data:s}),this.argBuf=void 0,this.msgBuf=void 0,this.state=Fa.State.MSG_END}else{let s=this.ma.size-this.msgBuf.length,n=e.length-t;if(n<s)s=n;if(s>0)this.msgBuf.write(e.subarray(t,t+s)),t=t+s-1;else this.msgBuf.writeByte(r)}else if(t-this.as>=this.ma.size)this.dispatcher.push({kind:Fa.Kind.MSG,msg:this.ma,data:e.subarray(this.as,t)}),this.argBuf=void 0,this.msgBuf=void 0,this.state=Fa.State.MSG_END;break;case Fa.State.MSG_END:switch(r){case Fa.cc.NL:this.drop=0,this.as=t+1,this.state=Fa.State.OP_START;break;default:continue}break;case Fa.State.OP_PLUS:switch(r){case Fa.cc.O:case Fa.cc.o:this.state=Fa.State.OP_PLUS_O;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_PLUS_O:switch(r){case Fa.cc.K:case Fa.cc.k:this.state=Fa.State.OP_PLUS_OK;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_PLUS_OK:switch(r){case Fa.cc.NL:this.dispatcher.push({kind:Fa.Kind.OK}),this.drop=0,this.state=Fa.State.OP_START;break}break;case Fa.State.OP_MINUS:switch(r){case Fa.cc.E:case Fa.cc.e:this.state=Fa.State.OP_MINUS_E;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_MINUS_E:switch(r){case Fa.cc.R:case Fa.cc.r:this.state=Fa.State.OP_MINUS_ER;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_MINUS_ER:switch(r){case Fa.cc.R:case Fa.cc.r:this.state=Fa.State.OP_MINUS_ERR;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_MINUS_ERR:switch(r){case Fa.cc.SPACE:case Fa.cc.TAB:this.state=Fa.State.OP_MINUS_ERR_SPC;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_MINUS_ERR_SPC:switch(r){case Fa.cc.SPACE:case Fa.cc.TAB:continue;default:this.state=Fa.State.MINUS_ERR_ARG,this.as=t}break;case Fa.State.MINUS_ERR_ARG:switch(r){case Fa.cc.CR:this.drop=1;break;case Fa.cc.NL:{let s;if(this.argBuf)s=this.argBuf.bytes(),this.argBuf=void 0;else s=e.subarray(this.as,t-this.drop);this.dispatcher.push({kind:Fa.Kind.ERR,data:s}),this.drop=0,this.as=t+1,this.state=Fa.State.OP_START;break}default:if(this.argBuf)this.argBuf.write(Uint8Array.of(r))}break;case Fa.State.OP_P:switch(r){case Fa.cc.I:case Fa.cc.i:this.state=Fa.State.OP_PI;break;case Fa.cc.O:case Fa.cc.o:this.state=Fa.State.OP_PO;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_PO:switch(r){case Fa.cc.N:case Fa.cc.n:this.state=Fa.State.OP_PON;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_PON:switch(r){case Fa.cc.G:case Fa.cc.g:this.state=Fa.State.OP_PONG;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_PONG:switch(r){case Fa.cc.NL:this.dispatcher.push({kind:Fa.Kind.PONG}),this.drop=0,this.state=Fa.State.OP_START;break}break;case Fa.State.OP_PI:switch(r){case Fa.cc.N:case Fa.cc.n:this.state=Fa.State.OP_PIN;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_PIN:switch(r){case Fa.cc.G:case Fa.cc.g:this.state=Fa.State.OP_PING;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_PING:switch(r){case Fa.cc.NL:this.dispatcher.push({kind:Fa.Kind.PING}),this.drop=0,this.state=Fa.State.OP_START;break}break;case Fa.State.OP_I:switch(r){case Fa.cc.N:case Fa.cc.n:this.state=Fa.State.OP_IN;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_IN:switch(r){case Fa.cc.F:case Fa.cc.f:this.state=Fa.State.OP_INF;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_INF:switch(r){case Fa.cc.O:case Fa.cc.o:this.state=Fa.State.OP_INFO;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_INFO:switch(r){case Fa.cc.SPACE:case Fa.cc.TAB:this.state=Fa.State.OP_INFO_SPC;break;default:throw this.fail(e.subarray(t))}break;case Fa.State.OP_INFO_SPC:switch(r){case Fa.cc.SPACE:case Fa.cc.TAB:continue;default:this.state=Fa.State.INFO_ARG,this.as=t}break;case Fa.State.INFO_ARG:switch(r){case Fa.cc.CR:this.drop=1;break;case Fa.cc.NL:{let s;if(this.argBuf)s=this.argBuf.bytes(),this.argBuf=void 0;else s=e.subarray(this.as,t-this.drop);this.dispatcher.push({kind:Fa.Kind.INFO,data:s}),this.drop=0,this.as=t+1,this.state=Fa.State.OP_START;break}default:if(this.argBuf)this.argBuf.writeByte(r)}break;default:throw this.fail(e.subarray(t))}}if((this.state===Fa.State.MSG_ARG||this.state===Fa.State.MINUS_ERR_ARG||this.state===Fa.State.INFO_ARG)&&!this.argBuf)this.argBuf=new Xn.DenoBuffer(e.subarray(this.as,t-this.drop));if(this.state===Fa.State.MSG_PAYLOAD&&!this.msgBuf){if(!this.argBuf)this.cloneMsgArg();this.msgBuf=new Xn.DenoBuffer(e.subarray(this.as))}}cloneMsgArg(){let e=this.ma.subject.length,t=this.ma.reply?this.ma.reply.length:0,r=new Uint8Array(e+t);if(r.set(this.ma.subject),this.ma.reply)r.set(this.ma.reply,e);if(this.argBuf=new Xn.DenoBuffer(r),this.ma.subject=r.subarray(0,e),this.ma.reply)this.ma.reply=r.subarray(e)}processMsgArgs(e){if(this.hdr>=0)return this.processHeaderMsgArgs(e);let t=[],r=-1;for(let s=0;s<e.length;s++)switch(e[s]){case Fa.cc.SPACE:case Fa.cc.TAB:case Fa.cc.CR:case Fa.cc.NL:if(r>=0)t.push(e.subarray(r,s)),r=-1;break;default:if(r<0)r=s}if(r>=0)t.push(e.subarray(r));switch(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],er);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],er);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=""){if(!t)t=`parse error [${this.state}]`;else t=`${t} [${this.state}]`;return Error(`${t}: ${Zn.TD.decode(e)}`)}processHeaderMsgArgs(e){let t=[],r=-1;for(let s=0;s<e.length;s++)switch(e[s]){case Fa.cc.SPACE:case Fa.cc.TAB:case Fa.cc.CR:case Fa.cc.NL:if(r>=0)t.push(e.subarray(r,s)),r=-1;break;default:if(r<0)r=s}if(r>=0)t.push(e.subarray(r));switch(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],er),this.ma.size=this.protoParseInt(t[3],er);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],er),this.ma.size=this.protoParseInt(t[4],er);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,t){if(e.length===0||e.length>15)return-1;let r=0;for(let s=0;s<e.length;s++){if(e[s]<La||e[s]>ql)return-1;r=r*10+(e[s]-La)}return t!==void 0&&r>t?-1:r}}Fa.Parser=Da;Fa.State={OP_START:0,OP_PLUS:1,OP_PLUS_O:2,OP_PLUS_OK:3,OP_MINUS:4,OP_MINUS_E:5,OP_MINUS_ER:6,OP_MINUS_ERR:7,OP_MINUS_ERR_SPC:8,MINUS_ERR_ARG:9,OP_M:10,OP_MS:11,OP_MSG:12,OP_MSG_SPC:13,MSG_ARG:14,MSG_PAYLOAD:15,MSG_END:16,OP_H:17,OP_P:18,OP_PI:19,OP_PIN:20,OP_PING:21,OP_PO:22,OP_PON:23,OP_PONG:24,OP_I:25,OP_IN:26,OP_INF:27,OP_INFO:28,OP_INFO_SPC:29,INFO_ARG:30};Fa.cc={CR:13,E:69,e:101,F:70,f:102,G:71,g:103,H:72,h:104,I:73,i:105,K:75,k:107,M:77,m:109,MINUS:45,N:78,n:110,NL:10,O:79,o:111,P:80,p:112,PLUS:43,R:82,r:114,S:83,s:115,SPACE:32,TAB:9}});var ys=H(function(Ka){Object.defineProperty(Ka,"__esModule",{value:!0});Ka.MsgHdrsImpl=void 0;Ka.canonicalMIMEHeaderKey=ti;Ka.headers=Ll;var Ba=Ve(),st=Et(),ps=Je();function ti(e){let A=!0,j=Array(e.length);for(let O=0;O<e.length;O++){let K=e.charCodeAt(O);if(K===58||K<33||K>126)throw ps.InvalidArgumentError.format("header",`'${e[O]}' is not a valid character in a header name`);if(A&&97<=K&&K<=122)K-=32;else if(!A&&65<=K&&K<=90)K+=32;j[O]=K,A=K==45}return String.fromCharCode(...j)}function Ll(e=0,t=""){if(e===0&&t!=="")throw ps.InvalidArgumentError.format("code","is required");else if(e>0&&t==="")throw ps.InvalidArgumentError.format("description","is required");return new tr(e,t)}var ei="NATS/1.0";class tr{_code;headers;_description;constructor(e=0,t=""){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(let[t,r]of this.headers){let s=e.values(t);if(r.length!==s.length)return!1;let n=[...r].sort(),o=[...s].sort();for(let c=0;c<n.length;c++)if(n[c]!==o[c])return!1}return!0}return!1}static decode(e){let t=new tr,s=Ba.TD.decode(e).split(`\r
|
|
4
|
+
`),n=s[0];if(n!==ei){let o=n.replace(ei,"").trim();if(o.length>0){if(t._code=parseInt(o,10),isNaN(t._code))t._code=0;let c=t._code.toString();o=o.replace(c,""),t._description=o.trim()}}if(s.length>=1)s.slice(1).map((o)=>{if(o){let c=o.indexOf(":");if(c>-1){let h=o.slice(0,c),p=o.slice(c+1).trim();t.append(h,p)}}});return t}toString(){if(this.headers.size===0&&this._code===0)return"";let e=ei;if(this._code>0&&this._description!=="")e+=` ${this._code} ${this._description}`;for(let[t,r]of this.headers)for(let s=0;s<r.length;s++)e=`${e}\r
|
|
5
|
+
${t}: ${r[s]}`;return`${e}\r
|
|
6
|
+
\r
|
|
7
|
+
`}encode(){return Ba.TE.encode(this.toString())}static validHeaderValue(e){if(/[\r\n]/.test(e))throw ps.InvalidArgumentError.format("header","values cannot contain \\r or \\n");return e.trim()}keys(){let e=[];for(let t of this.headers.keys())e.push(t);return e}findKeys(e,t=st.Match.Exact){let r=this.keys();switch(t){case st.Match.Exact:return r.filter((s)=>s===e);case st.Match.CanonicalMIME:return e=ti(e),r.filter((s)=>s===e);default:{let s=e.toLowerCase();return r.filter((n)=>s===n.toLowerCase())}}}get(e,t=st.Match.Exact){let r=this.findKeys(e,t);if(r.length){let s=this.headers.get(r[0]);if(s)return Array.isArray(s)?s[0]:s}return""}last(e,t=st.Match.Exact){let r=this.findKeys(e,t);if(r.length){let s=this.headers.get(r[0]);if(s)return Array.isArray(s)?s[s.length-1]:s}return""}has(e,t=st.Match.Exact){return this.findKeys(e,t).length>0}set(e,t,r=st.Match.Exact){this.delete(e,r),this.append(e,t,r)}append(e,t,r=st.Match.Exact){let s=ti(e);if(r===st.Match.CanonicalMIME)e=s;let n=this.findKeys(e,r);e=n.length>0?n[0]:e;let o=tr.validHeaderValue(t),c=this.headers.get(e);if(!c)c=[],this.headers.set(e,c);c.push(o)}values(e,t=st.Match.Exact){let r=[];return this.findKeys(e,t).forEach((n)=>{let o=this.headers.get(n);if(o)r.push(...o)}),r}delete(e,t=st.Match.Exact){this.findKeys(e,t).forEach((s)=>{this.headers.delete(s)})}get hasError(){return this._code>=300}get status(){return`${this._code} ${this._description}`.trim()}toRecord(){let 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){let t=new tr;for(let r in e){let s=e[r];t.headers.set(r,Array.isArray(s)?s:[`${s}`])}return t}}Ka.MsgHdrsImpl=tr});var ri=H(function(Ga){Object.defineProperty(Ga,"__esModule",{value:!0});Ga.MsgImpl=void 0;var Bl=ys(),bs=Ve();class za{_headers;_msg;_rdata;_reply;_subject;publisher;constructor(e,t,r){this._msg=e,this._rdata=t,this.publisher=r}get subject(){if(this._subject)return this._subject;return this._subject=bs.TD.decode(this._msg.subject),this._subject}get reply(){if(this._reply)return this._reply;return this._reply=bs.TD.decode(this._msg.reply),this._reply}get sid(){return this._msg.sid}get headers(){if(this._msg.hdr>-1&&!this._headers){let e=this._rdata.subarray(0,this._msg.hdr);this._headers=Bl.MsgHdrsImpl.decode(e)}return this._headers}get data(){if(!this._rdata)return new Uint8Array(0);return this._msg.hdr>-1?this._rdata.subarray(this._msg.hdr):this._rdata}respond(e=bs.Empty,t){if(this.reply)return this.publisher.publish(this.reply,e,t),!0;return!1}size(){let e=this._msg.subject.length,t=this._msg.reply?.length||0,r=this._msg.size===-1?0:this._msg.size;return e+t+r}json(e){return JSON.parse(this.string(),e)}string(){return bs.TD.decode(this.data)}requestInfo(){let e=this.headers?.get("Nats-Request-Info");if(e)return JSON.parse(e,function(t,r){if((t==="start"||t==="stop")&&r!=="")return new Date(Date.parse(r));return r});return null}}Ga.MsgImpl=za});var gs=H(function(Wa){Object.defineProperty(Wa,"__esModule",{value:!0});Wa.Features=Wa.Feature=void 0;Wa.parseSemVer=ms;Wa.compare=si;function ms(e=""){let t=e.match(/(\d+).(\d+).(\d+)/);if(t)return{major:parseInt(t[1]),minor:parseInt(t[2]),micro:parseInt(t[3])};throw Error(`'${e}' is not a semver value`)}function si(e,t){if(e.major<t.major)return-1;if(e.major>t.major)return 1;if(e.minor<t.minor)return-1;if(e.minor>t.minor)return 1;if(e.micro<t.micro)return-1;if(e.micro>t.micro)return 1;return 0}Wa.Feature={JS_KV:"js_kv",JS_OBJECTSTORE:"js_objectstore",JS_PULL_MAX_BYTES:"js_pull_max_bytes",JS_NEW_CONSUMER_CREATE_API:"js_new_consumer_create",JS_ALLOW_DIRECT:"js_allow_direct",JS_MULTIPLE_CONSUMER_FILTER:"js_multiple_consumer_filter",JS_SIMPLIFICATION:"js_simplification",JS_STREAM_CONSUMER_METADATA:"js_stream_consumer_metadata",JS_CONSUMER_FILTER_SUBJECTS:"js_consumer_filter_subjects",JS_STREAM_FIRST_SEQ:"js_stream_first_seq",JS_STREAM_SUBJECT_TRANSFORM:"js_stream_subject_transform",JS_STREAM_SOURCE_SUBJECT_TRANSFORM:"js_stream_source_subject_transform",JS_STREAM_COMPRESSION:"js_stream_compression",JS_DEFAULT_CONSUMER_LIMITS:"js_default_consumer_limits",JS_BATCH_DIRECT_GET:"js_batch_direct_get",JS_PRIORITY_GROUPS:"js_priority_groups",JS_CONSUMER_RESET:"js_consumer_reset"};class Ja{server;features;disabled;constructor(e){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){if(typeof e==="string")e=ms(e);this.server=e,this.set(Wa.Feature.JS_KV,"2.6.2"),this.set(Wa.Feature.JS_OBJECTSTORE,"2.6.3"),this.set(Wa.Feature.JS_PULL_MAX_BYTES,"2.8.3"),this.set(Wa.Feature.JS_NEW_CONSUMER_CREATE_API,"2.9.0"),this.set(Wa.Feature.JS_ALLOW_DIRECT,"2.9.0"),this.set(Wa.Feature.JS_MULTIPLE_CONSUMER_FILTER,"2.10.0"),this.set(Wa.Feature.JS_SIMPLIFICATION,"2.9.4"),this.set(Wa.Feature.JS_STREAM_CONSUMER_METADATA,"2.10.0"),this.set(Wa.Feature.JS_CONSUMER_FILTER_SUBJECTS,"2.10.0"),this.set(Wa.Feature.JS_STREAM_FIRST_SEQ,"2.10.0"),this.set(Wa.Feature.JS_STREAM_SUBJECT_TRANSFORM,"2.10.0"),this.set(Wa.Feature.JS_STREAM_SOURCE_SUBJECT_TRANSFORM,"2.10.0"),this.set(Wa.Feature.JS_STREAM_COMPRESSION,"2.10.0"),this.set(Wa.Feature.JS_DEFAULT_CONSUMER_LIMITS,"2.10.0"),this.set(Wa.Feature.JS_BATCH_DIRECT_GET,"2.11.0"),this.set(Wa.Feature.JS_PRIORITY_GROUPS,"2.11.0"),this.set(Wa.Feature.JS_CONSUMER_RESET,"2.14.0"),this.disabled.forEach((t)=>{this.features.delete(t)})}set(e,t){this.features.set(e,{min:t,ok:si(this.server,ms(t))>=0})}get(e){return this.features.get(e)||{min:"unknown",ok:!1}}supports(e){return this.get(e)?.ok||!1}require(e){if(typeof e==="string")e=ms(e);return si(this.server,e)>=0}}Wa.Features=Ja});var ii=H(function(Xa){Object.defineProperty(Xa,"__esModule",{value:!0});Xa.crc16=void 0;var zl=new Uint16Array([0,4129,8258,12387,16516,20645,24774,28903,33032,37161,41290,45419,49548,53677,57806,61935,4657,528,12915,8786,21173,17044,29431,25302,37689,33560,45947,41818,54205,50076,62463,58334,9314,13379,1056,5121,25830,29895,17572,21637,42346,46411,34088,38153,58862,62927,50604,54669,13907,9842,5649,1584,30423,26358,22165,18100,46939,42874,38681,34616,63455,59390,55197,51132,18628,22757,26758,30887,2112,6241,10242,14371,51660,55789,59790,63919,35144,39273,43274,47403,23285,19156,31415,27286,6769,2640,14899,10770,56317,52188,64447,60318,39801,35672,47931,43802,27814,31879,19684,23749,11298,15363,3168,7233,60846,64911,52716,56781,44330,48395,36200,40265,32407,28342,24277,20212,15891,11826,7761,3696,65439,61374,57309,53244,48923,44858,40793,36728,37256,33193,45514,41451,53516,49453,61774,57711,4224,161,12482,8419,20484,16421,28742,24679,33721,37784,41979,46042,49981,54044,58239,62302,689,4752,8947,13010,16949,21012,25207,29270,46570,42443,38312,34185,62830,58703,54572,50445,13538,9411,5280,1153,29798,25671,21540,17413,42971,47098,34713,38840,59231,63358,50973,55100,9939,14066,1681,5808,26199,30326,17941,22068,55628,51565,63758,59695,39368,35305,47498,43435,22596,18533,30726,26663,6336,2273,14466,10403,52093,56156,60223,64286,35833,39896,43963,48026,19061,23124,27191,31254,2801,6864,10931,14994,64814,60687,56684,52557,48554,44427,40424,36297,31782,27655,23652,19525,15522,11395,7392,3265,61215,65342,53085,57212,44955,49082,36825,40952,28183,32310,20053,24180,11923,16050,3793,7920]);class ni{static checksum(e){let t=0;for(let r=0;r<e.byteLength;r++){let s=e[r];t=t<<8&65535^zl[(t>>8^s)&255]}return t}static validate(e,t){return ni.checksum(e)==t}}Xa.crc16=ni});var ai=H(function(ec){Object.defineProperty(ec,"__esModule",{value:!0});ec.base32=void 0;var oi="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";class Qa{static encode(e){let t=0,r=0,s=new Uint8Array(e),n=new Uint8Array(e.byteLength*2),o=0;for(let c=0;c<s.byteLength;c++){r=r<<8|s[c],t+=8;while(t>=5){let h=r>>>t-5&31;n[o++]=oi.charAt(h).charCodeAt(0),t-=5}}if(t>0){let c=r<<5-t&31;n[o++]=oi.charAt(c).charCodeAt(0)}return n.slice(0,o)}static decode(e){let t=0,r=0,s=0,n=new Uint8Array(e),o=new Uint8Array(n.byteLength*5/8|0);for(let c=0;c<n.byteLength;c++){let h=String.fromCharCode(n[c]),p=oi.indexOf(h);if(p===-1)throw Error("Illegal Base32 character: "+n[c]);if(r=r<<5|p,t+=5,t>=8)o[s++]=r>>>t-8&255,t-=8}return o.slice(0,s)}}ec.base32=Qa});var Sr=H(function(nc){Object.defineProperty(nc,"__esModule",{value:!0});nc.Codec=void 0;var rc=ii(),me=Ut(),sc=ai();class St{static encode(e,t){if(!t||!(t instanceof Uint8Array))throw new me.NKeysError(me.NKeysErrorCode.SerializationError);if(!me.Prefixes.isValidPrefix(e))throw new me.NKeysError(me.NKeysErrorCode.InvalidPrefixByte);return St._encode(!1,e,t)}static encodeSeed(e,t){if(!t)throw new me.NKeysError(me.NKeysErrorCode.ApiError);if(!me.Prefixes.isValidPublicPrefix(e))throw new me.NKeysError(me.NKeysErrorCode.InvalidPrefixByte);if(t.byteLength!==32)throw new me.NKeysError(me.NKeysErrorCode.InvalidSeedLen);return St._encode(!0,e,t)}static decode(e,t){if(!me.Prefixes.isValidPrefix(e))throw new me.NKeysError(me.NKeysErrorCode.InvalidPrefixByte);let r=St._decode(t);if(r[0]!==e)throw new me.NKeysError(me.NKeysErrorCode.InvalidPrefixByte);return r.slice(1)}static decodeSeed(e){let t=St._decode(e),r=St._decodePrefix(t);if(r[0]!=me.Prefix.Seed)throw new me.NKeysError(me.NKeysErrorCode.InvalidSeed);if(!me.Prefixes.isValidPublicPrefix(r[1]))throw new me.NKeysError(me.NKeysErrorCode.InvalidPrefixByte);return{buf:t.slice(2),prefix:r[1]}}static _encode(e,t,r){let s=e?2:1,n=r.byteLength,o=2,c=s+n+2,h=s+n,p=new Uint8Array(c);if(e){let j=St._encodePrefix(me.Prefix.Seed,t);p.set(j)}else p[0]=t;p.set(r,s);let w=rc.crc16.checksum(p.slice(0,h));return new DataView(p.buffer).setUint16(h,w,!0),sc.base32.encode(p)}static _decode(e){if(e.byteLength<4)throw new me.NKeysError(me.NKeysErrorCode.InvalidEncoding);let t;try{t=sc.base32.decode(e)}catch(c){throw new me.NKeysError(me.NKeysErrorCode.InvalidEncoding,{cause:c})}let r=t.byteLength-2,n=new DataView(t.buffer).getUint16(r,!0),o=t.slice(0,r);if(!rc.crc16.validate(o,n))throw new me.NKeysError(me.NKeysErrorCode.InvalidChecksum);return o}static _encodePrefix(e,t){let r=e|t>>5,s=(t&31)<<3;return new Uint8Array([r,s])}static _decodePrefix(e){let t=e[0]&248,r=(e[0]&7)<<5|(e[1]&248)>>3;return new Uint8Array([t,r])}}nc.Codec=St});var oc=H(function(ax,xs){(function(e){var t=function(a){var f,u=new Float64Array(16);if(a)for(f=0;f<a.length;f++)u[f]=a[f];return u},r=function(){throw Error("no PRNG")},s=new Uint8Array(16),n=new Uint8Array(32);n[0]=9;var o=t(),c=t([1]),h=t([56129,1]),p=t([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),w=t([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),A=t([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),j=t([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),O=t([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function K(a,f,u,i){a[f]=u>>24&255,a[f+1]=u>>16&255,a[f+2]=u>>8&255,a[f+3]=u&255,a[f+4]=i>>24&255,a[f+5]=i>>16&255,a[f+6]=i>>8&255,a[f+7]=i&255}function N(a,f,u,i,d){var b,m=0;for(b=0;b<d;b++)m|=a[f+b]^u[i+b];return(1&m-1>>>8)-1}function Pe(a,f,u,i){return N(a,f,u,i,16)}function be(a,f,u,i){return N(a,f,u,i,32)}function vt(a,f,u,i){var d=i[0]&255|(i[1]&255)<<8|(i[2]&255)<<16|(i[3]&255)<<24,b=u[0]&255|(u[1]&255)<<8|(u[2]&255)<<16|(u[3]&255)<<24,m=u[4]&255|(u[5]&255)<<8|(u[6]&255)<<16|(u[7]&255)<<24,_=u[8]&255|(u[9]&255)<<8|(u[10]&255)<<16|(u[11]&255)<<24,T=u[12]&255|(u[13]&255)<<8|(u[14]&255)<<16|(u[15]&255)<<24,F=i[4]&255|(i[5]&255)<<8|(i[6]&255)<<16|(i[7]&255)<<24,M=f[0]&255|(f[1]&255)<<8|(f[2]&255)<<16|(f[3]&255)<<24,de=f[4]&255|(f[5]&255)<<8|(f[6]&255)<<16|(f[7]&255)<<24,q=f[8]&255|(f[9]&255)<<8|(f[10]&255)<<16|(f[11]&255)<<24,G=f[12]&255|(f[13]&255)<<8|(f[14]&255)<<16|(f[15]&255)<<24,V=i[8]&255|(i[9]&255)<<8|(i[10]&255)<<16|(i[11]&255)<<24,Z=u[16]&255|(u[17]&255)<<8|(u[18]&255)<<16|(u[19]&255)<<24,X=u[20]&255|(u[21]&255)<<8|(u[22]&255)<<16|(u[23]&255)<<24,J=u[24]&255|(u[25]&255)<<8|(u[26]&255)<<16|(u[27]&255)<<24,Y=u[28]&255|(u[29]&255)<<8|(u[30]&255)<<16|(u[31]&255)<<24,W=i[12]&255|(i[13]&255)<<8|(i[14]&255)<<16|(i[15]&255)<<24,U=d,B=b,R=m,L=_,D=T,k=F,g=M,x=de,S=q,v=G,E=V,P=Z,z=X,Q=J,re=Y,ee=W,l;for(var ie=0;ie<20;ie+=2)l=U+z|0,D^=l<<7|l>>>25,l=D+U|0,S^=l<<9|l>>>23,l=S+D|0,z^=l<<13|l>>>19,l=z+S|0,U^=l<<18|l>>>14,l=k+B|0,v^=l<<7|l>>>25,l=v+k|0,Q^=l<<9|l>>>23,l=Q+v|0,B^=l<<13|l>>>19,l=B+Q|0,k^=l<<18|l>>>14,l=E+g|0,re^=l<<7|l>>>25,l=re+E|0,R^=l<<9|l>>>23,l=R+re|0,g^=l<<13|l>>>19,l=g+R|0,E^=l<<18|l>>>14,l=ee+P|0,L^=l<<7|l>>>25,l=L+ee|0,x^=l<<9|l>>>23,l=x+L|0,P^=l<<13|l>>>19,l=P+x|0,ee^=l<<18|l>>>14,l=U+L|0,B^=l<<7|l>>>25,l=B+U|0,R^=l<<9|l>>>23,l=R+B|0,L^=l<<13|l>>>19,l=L+R|0,U^=l<<18|l>>>14,l=k+D|0,g^=l<<7|l>>>25,l=g+k|0,x^=l<<9|l>>>23,l=x+g|0,D^=l<<13|l>>>19,l=D+x|0,k^=l<<18|l>>>14,l=E+v|0,P^=l<<7|l>>>25,l=P+E|0,S^=l<<9|l>>>23,l=S+P|0,v^=l<<13|l>>>19,l=v+S|0,E^=l<<18|l>>>14,l=ee+re|0,z^=l<<7|l>>>25,l=z+ee|0,Q^=l<<9|l>>>23,l=Q+z|0,re^=l<<13|l>>>19,l=re+Q|0,ee^=l<<18|l>>>14;U=U+d|0,B=B+b|0,R=R+m|0,L=L+_|0,D=D+T|0,k=k+F|0,g=g+M|0,x=x+de|0,S=S+q|0,v=v+G|0,E=E+V|0,P=P+Z|0,z=z+X|0,Q=Q+J|0,re=re+Y|0,ee=ee+W|0,a[0]=U>>>0&255,a[1]=U>>>8&255,a[2]=U>>>16&255,a[3]=U>>>24&255,a[4]=B>>>0&255,a[5]=B>>>8&255,a[6]=B>>>16&255,a[7]=B>>>24&255,a[8]=R>>>0&255,a[9]=R>>>8&255,a[10]=R>>>16&255,a[11]=R>>>24&255,a[12]=L>>>0&255,a[13]=L>>>8&255,a[14]=L>>>16&255,a[15]=L>>>24&255,a[16]=D>>>0&255,a[17]=D>>>8&255,a[18]=D>>>16&255,a[19]=D>>>24&255,a[20]=k>>>0&255,a[21]=k>>>8&255,a[22]=k>>>16&255,a[23]=k>>>24&255,a[24]=g>>>0&255,a[25]=g>>>8&255,a[26]=g>>>16&255,a[27]=g>>>24&255,a[28]=x>>>0&255,a[29]=x>>>8&255,a[30]=x>>>16&255,a[31]=x>>>24&255,a[32]=S>>>0&255,a[33]=S>>>8&255,a[34]=S>>>16&255,a[35]=S>>>24&255,a[36]=v>>>0&255,a[37]=v>>>8&255,a[38]=v>>>16&255,a[39]=v>>>24&255,a[40]=E>>>0&255,a[41]=E>>>8&255,a[42]=E>>>16&255,a[43]=E>>>24&255,a[44]=P>>>0&255,a[45]=P>>>8&255,a[46]=P>>>16&255,a[47]=P>>>24&255,a[48]=z>>>0&255,a[49]=z>>>8&255,a[50]=z>>>16&255,a[51]=z>>>24&255,a[52]=Q>>>0&255,a[53]=Q>>>8&255,a[54]=Q>>>16&255,a[55]=Q>>>24&255,a[56]=re>>>0&255,a[57]=re>>>8&255,a[58]=re>>>16&255,a[59]=re>>>24&255,a[60]=ee>>>0&255,a[61]=ee>>>8&255,a[62]=ee>>>16&255,a[63]=ee>>>24&255}function xd(a,f,u,i){var d=i[0]&255|(i[1]&255)<<8|(i[2]&255)<<16|(i[3]&255)<<24,b=u[0]&255|(u[1]&255)<<8|(u[2]&255)<<16|(u[3]&255)<<24,m=u[4]&255|(u[5]&255)<<8|(u[6]&255)<<16|(u[7]&255)<<24,_=u[8]&255|(u[9]&255)<<8|(u[10]&255)<<16|(u[11]&255)<<24,T=u[12]&255|(u[13]&255)<<8|(u[14]&255)<<16|(u[15]&255)<<24,F=i[4]&255|(i[5]&255)<<8|(i[6]&255)<<16|(i[7]&255)<<24,M=f[0]&255|(f[1]&255)<<8|(f[2]&255)<<16|(f[3]&255)<<24,de=f[4]&255|(f[5]&255)<<8|(f[6]&255)<<16|(f[7]&255)<<24,q=f[8]&255|(f[9]&255)<<8|(f[10]&255)<<16|(f[11]&255)<<24,G=f[12]&255|(f[13]&255)<<8|(f[14]&255)<<16|(f[15]&255)<<24,V=i[8]&255|(i[9]&255)<<8|(i[10]&255)<<16|(i[11]&255)<<24,Z=u[16]&255|(u[17]&255)<<8|(u[18]&255)<<16|(u[19]&255)<<24,X=u[20]&255|(u[21]&255)<<8|(u[22]&255)<<16|(u[23]&255)<<24,J=u[24]&255|(u[25]&255)<<8|(u[26]&255)<<16|(u[27]&255)<<24,Y=u[28]&255|(u[29]&255)<<8|(u[30]&255)<<16|(u[31]&255)<<24,W=i[12]&255|(i[13]&255)<<8|(i[14]&255)<<16|(i[15]&255)<<24,U=d,B=b,R=m,L=_,D=T,k=F,g=M,x=de,S=q,v=G,E=V,P=Z,z=X,Q=J,re=Y,ee=W,l;for(var ie=0;ie<20;ie+=2)l=U+z|0,D^=l<<7|l>>>25,l=D+U|0,S^=l<<9|l>>>23,l=S+D|0,z^=l<<13|l>>>19,l=z+S|0,U^=l<<18|l>>>14,l=k+B|0,v^=l<<7|l>>>25,l=v+k|0,Q^=l<<9|l>>>23,l=Q+v|0,B^=l<<13|l>>>19,l=B+Q|0,k^=l<<18|l>>>14,l=E+g|0,re^=l<<7|l>>>25,l=re+E|0,R^=l<<9|l>>>23,l=R+re|0,g^=l<<13|l>>>19,l=g+R|0,E^=l<<18|l>>>14,l=ee+P|0,L^=l<<7|l>>>25,l=L+ee|0,x^=l<<9|l>>>23,l=x+L|0,P^=l<<13|l>>>19,l=P+x|0,ee^=l<<18|l>>>14,l=U+L|0,B^=l<<7|l>>>25,l=B+U|0,R^=l<<9|l>>>23,l=R+B|0,L^=l<<13|l>>>19,l=L+R|0,U^=l<<18|l>>>14,l=k+D|0,g^=l<<7|l>>>25,l=g+k|0,x^=l<<9|l>>>23,l=x+g|0,D^=l<<13|l>>>19,l=D+x|0,k^=l<<18|l>>>14,l=E+v|0,P^=l<<7|l>>>25,l=P+E|0,S^=l<<9|l>>>23,l=S+P|0,v^=l<<13|l>>>19,l=v+S|0,E^=l<<18|l>>>14,l=ee+re|0,z^=l<<7|l>>>25,l=z+ee|0,Q^=l<<9|l>>>23,l=Q+z|0,re^=l<<13|l>>>19,l=re+Q|0,ee^=l<<18|l>>>14;a[0]=U>>>0&255,a[1]=U>>>8&255,a[2]=U>>>16&255,a[3]=U>>>24&255,a[4]=k>>>0&255,a[5]=k>>>8&255,a[6]=k>>>16&255,a[7]=k>>>24&255,a[8]=E>>>0&255,a[9]=E>>>8&255,a[10]=E>>>16&255,a[11]=E>>>24&255,a[12]=ee>>>0&255,a[13]=ee>>>8&255,a[14]=ee>>>16&255,a[15]=ee>>>24&255,a[16]=g>>>0&255,a[17]=g>>>8&255,a[18]=g>>>16&255,a[19]=g>>>24&255,a[20]=x>>>0&255,a[21]=x>>>8&255,a[22]=x>>>16&255,a[23]=x>>>24&255,a[24]=S>>>0&255,a[25]=S>>>8&255,a[26]=S>>>16&255,a[27]=S>>>24&255,a[28]=v>>>0&255,a[29]=v>>>8&255,a[30]=v>>>16&255,a[31]=v>>>24&255}function Kr(a,f,u,i){vt(a,f,u,i)}function Hr(a,f,u,i){xd(a,f,u,i)}var Ct=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function go(a,f,u,i,d,b,m){var _=new Uint8Array(16),T=new Uint8Array(64),F,M;for(M=0;M<16;M++)_[M]=0;for(M=0;M<8;M++)_[M]=b[M];while(d>=64){Kr(T,_,m,Ct);for(M=0;M<64;M++)a[f+M]=u[i+M]^T[M];F=1;for(M=8;M<16;M++)F=F+(_[M]&255)|0,_[M]=F&255,F>>>=8;d-=64,f+=64,i+=64}if(d>0){Kr(T,_,m,Ct);for(M=0;M<d;M++)a[f+M]=u[i+M]^T[M]}return 0}function xo(a,f,u,i,d){var b=new Uint8Array(16),m=new Uint8Array(64),_,T;for(T=0;T<16;T++)b[T]=0;for(T=0;T<8;T++)b[T]=i[T];while(u>=64){Kr(m,b,d,Ct);for(T=0;T<64;T++)a[f+T]=m[T];_=1;for(T=8;T<16;T++)_=_+(b[T]&255)|0,b[T]=_&255,_>>>=8;u-=64,f+=64}if(u>0){Kr(m,b,d,Ct);for(T=0;T<u;T++)a[f+T]=m[T]}return 0}function wo(a,f,u,i,d){var b=new Uint8Array(32);Hr(b,i,d,Ct);var m=new Uint8Array(8);for(var _=0;_<8;_++)m[_]=i[_+16];return xo(a,f,u,m,b)}function rn(a,f,u,i,d,b,m){var _=new Uint8Array(32);Hr(_,b,m,Ct);var T=new Uint8Array(8);for(var F=0;F<8;F++)T[F]=b[F+16];return go(a,f,u,i,d,T,_)}var zr=function(a){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var f,u,i,d,b,m,_,T;f=a[0]&255|(a[1]&255)<<8,this.r[0]=f&8191,u=a[2]&255|(a[3]&255)<<8,this.r[1]=(f>>>13|u<<3)&8191,i=a[4]&255|(a[5]&255)<<8,this.r[2]=(u>>>10|i<<6)&7939,d=a[6]&255|(a[7]&255)<<8,this.r[3]=(i>>>7|d<<9)&8191,b=a[8]&255|(a[9]&255)<<8,this.r[4]=(d>>>4|b<<12)&255,this.r[5]=b>>>1&8190,m=a[10]&255|(a[11]&255)<<8,this.r[6]=(b>>>14|m<<2)&8191,_=a[12]&255|(a[13]&255)<<8,this.r[7]=(m>>>11|_<<5)&8065,T=a[14]&255|(a[15]&255)<<8,this.r[8]=(_>>>8|T<<8)&8191,this.r[9]=T>>>5&127,this.pad[0]=a[16]&255|(a[17]&255)<<8,this.pad[1]=a[18]&255|(a[19]&255)<<8,this.pad[2]=a[20]&255|(a[21]&255)<<8,this.pad[3]=a[22]&255|(a[23]&255)<<8,this.pad[4]=a[24]&255|(a[25]&255)<<8,this.pad[5]=a[26]&255|(a[27]&255)<<8,this.pad[6]=a[28]&255|(a[29]&255)<<8,this.pad[7]=a[30]&255|(a[31]&255)<<8};zr.prototype.blocks=function(a,f,u){var i=this.fin?0:2048,d,b,m,_,T,F,M,de,q,G,V,Z,X,J,Y,W,U,B,R,L=this.h[0],D=this.h[1],k=this.h[2],g=this.h[3],x=this.h[4],S=this.h[5],v=this.h[6],E=this.h[7],P=this.h[8],z=this.h[9],Q=this.r[0],re=this.r[1],ee=this.r[2],l=this.r[3],ie=this.r[4],he=this.r[5],le=this.r[6],se=this.r[7],ue=this.r[8],fe=this.r[9];while(u>=16)d=a[f+0]&255|(a[f+1]&255)<<8,L+=d&8191,b=a[f+2]&255|(a[f+3]&255)<<8,D+=(d>>>13|b<<3)&8191,m=a[f+4]&255|(a[f+5]&255)<<8,k+=(b>>>10|m<<6)&8191,_=a[f+6]&255|(a[f+7]&255)<<8,g+=(m>>>7|_<<9)&8191,T=a[f+8]&255|(a[f+9]&255)<<8,x+=(_>>>4|T<<12)&8191,S+=T>>>1&8191,F=a[f+10]&255|(a[f+11]&255)<<8,v+=(T>>>14|F<<2)&8191,M=a[f+12]&255|(a[f+13]&255)<<8,E+=(F>>>11|M<<5)&8191,de=a[f+14]&255|(a[f+15]&255)<<8,P+=(M>>>8|de<<8)&8191,z+=de>>>5|i,q=0,G=q,G+=L*Q,G+=D*(5*fe),G+=k*(5*ue),G+=g*(5*se),G+=x*(5*le),q=G>>>13,G&=8191,G+=S*(5*he),G+=v*(5*ie),G+=E*(5*l),G+=P*(5*ee),G+=z*(5*re),q+=G>>>13,G&=8191,V=q,V+=L*re,V+=D*Q,V+=k*(5*fe),V+=g*(5*ue),V+=x*(5*se),q=V>>>13,V&=8191,V+=S*(5*le),V+=v*(5*he),V+=E*(5*ie),V+=P*(5*l),V+=z*(5*ee),q+=V>>>13,V&=8191,Z=q,Z+=L*ee,Z+=D*re,Z+=k*Q,Z+=g*(5*fe),Z+=x*(5*ue),q=Z>>>13,Z&=8191,Z+=S*(5*se),Z+=v*(5*le),Z+=E*(5*he),Z+=P*(5*ie),Z+=z*(5*l),q+=Z>>>13,Z&=8191,X=q,X+=L*l,X+=D*ee,X+=k*re,X+=g*Q,X+=x*(5*fe),q=X>>>13,X&=8191,X+=S*(5*ue),X+=v*(5*se),X+=E*(5*le),X+=P*(5*he),X+=z*(5*ie),q+=X>>>13,X&=8191,J=q,J+=L*ie,J+=D*l,J+=k*ee,J+=g*re,J+=x*Q,q=J>>>13,J&=8191,J+=S*(5*fe),J+=v*(5*ue),J+=E*(5*se),J+=P*(5*le),J+=z*(5*he),q+=J>>>13,J&=8191,Y=q,Y+=L*he,Y+=D*ie,Y+=k*l,Y+=g*ee,Y+=x*re,q=Y>>>13,Y&=8191,Y+=S*Q,Y+=v*(5*fe),Y+=E*(5*ue),Y+=P*(5*se),Y+=z*(5*le),q+=Y>>>13,Y&=8191,W=q,W+=L*le,W+=D*he,W+=k*ie,W+=g*l,W+=x*ee,q=W>>>13,W&=8191,W+=S*re,W+=v*Q,W+=E*(5*fe),W+=P*(5*ue),W+=z*(5*se),q+=W>>>13,W&=8191,U=q,U+=L*se,U+=D*le,U+=k*he,U+=g*ie,U+=x*l,q=U>>>13,U&=8191,U+=S*ee,U+=v*re,U+=E*Q,U+=P*(5*fe),U+=z*(5*ue),q+=U>>>13,U&=8191,B=q,B+=L*ue,B+=D*se,B+=k*le,B+=g*he,B+=x*ie,q=B>>>13,B&=8191,B+=S*l,B+=v*ee,B+=E*re,B+=P*Q,B+=z*(5*fe),q+=B>>>13,B&=8191,R=q,R+=L*fe,R+=D*ue,R+=k*se,R+=g*le,R+=x*he,q=R>>>13,R&=8191,R+=S*ie,R+=v*l,R+=E*ee,R+=P*re,R+=z*Q,q+=R>>>13,R&=8191,q=(q<<2)+q|0,q=q+G|0,G=q&8191,q=q>>>13,V+=q,L=G,D=V,k=Z,g=X,x=J,S=Y,v=W,E=U,P=B,z=R,f+=16,u-=16;this.h[0]=L,this.h[1]=D,this.h[2]=k,this.h[3]=g,this.h[4]=x,this.h[5]=S,this.h[6]=v,this.h[7]=E,this.h[8]=P,this.h[9]=z},zr.prototype.finish=function(a,f){var u=new Uint16Array(10),i,d,b,m;if(this.leftover){m=this.leftover,this.buffer[m++]=1;for(;m<16;m++)this.buffer[m]=0;this.fin=1,this.blocks(this.buffer,0,16)}i=this.h[1]>>>13,this.h[1]&=8191;for(m=2;m<10;m++)this.h[m]+=i,i=this.h[m]>>>13,this.h[m]&=8191;this.h[0]+=i*5,i=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=i,i=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=i,u[0]=this.h[0]+5,i=u[0]>>>13,u[0]&=8191;for(m=1;m<10;m++)u[m]=this.h[m]+i,i=u[m]>>>13,u[m]&=8191;u[9]-=8192,d=(i^1)-1;for(m=0;m<10;m++)u[m]&=d;d=~d;for(m=0;m<10;m++)this.h[m]=this.h[m]&d|u[m];this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,b=this.h[0]+this.pad[0],this.h[0]=b&65535;for(m=1;m<8;m++)b=(this.h[m]+this.pad[m]|0)+(b>>>16)|0,this.h[m]=b&65535;a[f+0]=this.h[0]>>>0&255,a[f+1]=this.h[0]>>>8&255,a[f+2]=this.h[1]>>>0&255,a[f+3]=this.h[1]>>>8&255,a[f+4]=this.h[2]>>>0&255,a[f+5]=this.h[2]>>>8&255,a[f+6]=this.h[3]>>>0&255,a[f+7]=this.h[3]>>>8&255,a[f+8]=this.h[4]>>>0&255,a[f+9]=this.h[4]>>>8&255,a[f+10]=this.h[5]>>>0&255,a[f+11]=this.h[5]>>>8&255,a[f+12]=this.h[6]>>>0&255,a[f+13]=this.h[6]>>>8&255,a[f+14]=this.h[7]>>>0&255,a[f+15]=this.h[7]>>>8&255},zr.prototype.update=function(a,f,u){var i,d;if(this.leftover){if(d=16-this.leftover,d>u)d=u;for(i=0;i<d;i++)this.buffer[this.leftover+i]=a[f+i];if(u-=d,f+=d,this.leftover+=d,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(u>=16)d=u-u%16,this.blocks(a,f,d),f+=d,u-=d;if(u){for(i=0;i<u;i++)this.buffer[this.leftover+i]=a[f+i];this.leftover+=u}};function sn(a,f,u,i,d,b){var m=new zr(b);return m.update(u,i,d),m.finish(a,f),0}function vo(a,f,u,i,d,b){var m=new Uint8Array(16);return sn(m,0,u,i,d,b),Pe(a,f,m,0)}function nn(a,f,u,i,d){var b;if(u<32)return-1;rn(a,0,f,0,u,i,d),sn(a,16,a,32,u-32,a);for(b=0;b<16;b++)a[b]=0;return 0}function on(a,f,u,i,d){var b,m=new Uint8Array(32);if(u<32)return-1;if(wo(m,0,32,i,d),vo(f,16,f,32,u-32,m)!==0)return-1;rn(a,0,f,0,u,i,d);for(b=0;b<32;b++)a[b]=0;return 0}function pt(a,f){var u;for(u=0;u<16;u++)a[u]=f[u]|0}function an(a){var f,u,i=1;for(f=0;f<16;f++)u=a[f]+i+65535,i=Math.floor(u/65536),a[f]=u-i*65536;a[0]+=i-1+37*(i-1)}function Wt(a,f,u){var i,d=~(u-1);for(var b=0;b<16;b++)i=d&(a[b]^f[b]),a[b]^=i,f[b]^=i}function Yt(a,f){var u,i,d,b=t(),m=t();for(u=0;u<16;u++)m[u]=f[u];an(m),an(m),an(m);for(i=0;i<2;i++){b[0]=m[0]-65517;for(u=1;u<15;u++)b[u]=m[u]-65535-(b[u-1]>>16&1),b[u-1]&=65535;b[15]=m[15]-32767-(b[14]>>16&1),d=b[15]>>16&1,b[14]&=65535,Wt(m,b,1-d)}for(u=0;u<16;u++)a[2*u]=m[u]&255,a[2*u+1]=m[u]>>8}function _o(a,f){var u=new Uint8Array(32),i=new Uint8Array(32);return Yt(u,a),Yt(i,f),be(u,0,i,0)}function Eo(a){var f=new Uint8Array(32);return Yt(f,a),f[0]&1}function cn(a,f){var u;for(u=0;u<16;u++)a[u]=f[2*u]+(f[2*u+1]<<8);a[15]&=32767}function et(a,f,u){for(var i=0;i<16;i++)a[i]=f[i]+u[i]}function tt(a,f,u){for(var i=0;i<16;i++)a[i]=f[i]-u[i]}function ce(a,f,u){var i,d,b=0,m=0,_=0,T=0,F=0,M=0,de=0,q=0,G=0,V=0,Z=0,X=0,J=0,Y=0,W=0,U=0,B=0,R=0,L=0,D=0,k=0,g=0,x=0,S=0,v=0,E=0,P=0,z=0,Q=0,re=0,ee=0,l=u[0],ie=u[1],he=u[2],le=u[3],se=u[4],ue=u[5],fe=u[6],Ae=u[7],ge=u[8],ve=u[9],_e=u[10],Ee=u[11],Te=u[12],$e=u[13],Ue=u[14],Le=u[15];i=f[0],b+=i*l,m+=i*ie,_+=i*he,T+=i*le,F+=i*se,M+=i*ue,de+=i*fe,q+=i*Ae,G+=i*ge,V+=i*ve,Z+=i*_e,X+=i*Ee,J+=i*Te,Y+=i*$e,W+=i*Ue,U+=i*Le,i=f[1],m+=i*l,_+=i*ie,T+=i*he,F+=i*le,M+=i*se,de+=i*ue,q+=i*fe,G+=i*Ae,V+=i*ge,Z+=i*ve,X+=i*_e,J+=i*Ee,Y+=i*Te,W+=i*$e,U+=i*Ue,B+=i*Le,i=f[2],_+=i*l,T+=i*ie,F+=i*he,M+=i*le,de+=i*se,q+=i*ue,G+=i*fe,V+=i*Ae,Z+=i*ge,X+=i*ve,J+=i*_e,Y+=i*Ee,W+=i*Te,U+=i*$e,B+=i*Ue,R+=i*Le,i=f[3],T+=i*l,F+=i*ie,M+=i*he,de+=i*le,q+=i*se,G+=i*ue,V+=i*fe,Z+=i*Ae,X+=i*ge,J+=i*ve,Y+=i*_e,W+=i*Ee,U+=i*Te,B+=i*$e,R+=i*Ue,L+=i*Le,i=f[4],F+=i*l,M+=i*ie,de+=i*he,q+=i*le,G+=i*se,V+=i*ue,Z+=i*fe,X+=i*Ae,J+=i*ge,Y+=i*ve,W+=i*_e,U+=i*Ee,B+=i*Te,R+=i*$e,L+=i*Ue,D+=i*Le,i=f[5],M+=i*l,de+=i*ie,q+=i*he,G+=i*le,V+=i*se,Z+=i*ue,X+=i*fe,J+=i*Ae,Y+=i*ge,W+=i*ve,U+=i*_e,B+=i*Ee,R+=i*Te,L+=i*$e,D+=i*Ue,k+=i*Le,i=f[6],de+=i*l,q+=i*ie,G+=i*he,V+=i*le,Z+=i*se,X+=i*ue,J+=i*fe,Y+=i*Ae,W+=i*ge,U+=i*ve,B+=i*_e,R+=i*Ee,L+=i*Te,D+=i*$e,k+=i*Ue,g+=i*Le,i=f[7],q+=i*l,G+=i*ie,V+=i*he,Z+=i*le,X+=i*se,J+=i*ue,Y+=i*fe,W+=i*Ae,U+=i*ge,B+=i*ve,R+=i*_e,L+=i*Ee,D+=i*Te,k+=i*$e,g+=i*Ue,x+=i*Le,i=f[8],G+=i*l,V+=i*ie,Z+=i*he,X+=i*le,J+=i*se,Y+=i*ue,W+=i*fe,U+=i*Ae,B+=i*ge,R+=i*ve,L+=i*_e,D+=i*Ee,k+=i*Te,g+=i*$e,x+=i*Ue,S+=i*Le,i=f[9],V+=i*l,Z+=i*ie,X+=i*he,J+=i*le,Y+=i*se,W+=i*ue,U+=i*fe,B+=i*Ae,R+=i*ge,L+=i*ve,D+=i*_e,k+=i*Ee,g+=i*Te,x+=i*$e,S+=i*Ue,v+=i*Le,i=f[10],Z+=i*l,X+=i*ie,J+=i*he,Y+=i*le,W+=i*se,U+=i*ue,B+=i*fe,R+=i*Ae,L+=i*ge,D+=i*ve,k+=i*_e,g+=i*Ee,x+=i*Te,S+=i*$e,v+=i*Ue,E+=i*Le,i=f[11],X+=i*l,J+=i*ie,Y+=i*he,W+=i*le,U+=i*se,B+=i*ue,R+=i*fe,L+=i*Ae,D+=i*ge,k+=i*ve,g+=i*_e,x+=i*Ee,S+=i*Te,v+=i*$e,E+=i*Ue,P+=i*Le,i=f[12],J+=i*l,Y+=i*ie,W+=i*he,U+=i*le,B+=i*se,R+=i*ue,L+=i*fe,D+=i*Ae,k+=i*ge,g+=i*ve,x+=i*_e,S+=i*Ee,v+=i*Te,E+=i*$e,P+=i*Ue,z+=i*Le,i=f[13],Y+=i*l,W+=i*ie,U+=i*he,B+=i*le,R+=i*se,L+=i*ue,D+=i*fe,k+=i*Ae,g+=i*ge,x+=i*ve,S+=i*_e,v+=i*Ee,E+=i*Te,P+=i*$e,z+=i*Ue,Q+=i*Le,i=f[14],W+=i*l,U+=i*ie,B+=i*he,R+=i*le,L+=i*se,D+=i*ue,k+=i*fe,g+=i*Ae,x+=i*ge,S+=i*ve,v+=i*_e,E+=i*Ee,P+=i*Te,z+=i*$e,Q+=i*Ue,re+=i*Le,i=f[15],U+=i*l,B+=i*ie,R+=i*he,L+=i*le,D+=i*se,k+=i*ue,g+=i*fe,x+=i*Ae,S+=i*ge,v+=i*ve,E+=i*_e,P+=i*Ee,z+=i*Te,Q+=i*$e,re+=i*Ue,ee+=i*Le,b+=38*B,m+=38*R,_+=38*L,T+=38*D,F+=38*k,M+=38*g,de+=38*x,q+=38*S,G+=38*v,V+=38*E,Z+=38*P,X+=38*z,J+=38*Q,Y+=38*re,W+=38*ee,d=1,i=b+d+65535,d=Math.floor(i/65536),b=i-d*65536,i=m+d+65535,d=Math.floor(i/65536),m=i-d*65536,i=_+d+65535,d=Math.floor(i/65536),_=i-d*65536,i=T+d+65535,d=Math.floor(i/65536),T=i-d*65536,i=F+d+65535,d=Math.floor(i/65536),F=i-d*65536,i=M+d+65535,d=Math.floor(i/65536),M=i-d*65536,i=de+d+65535,d=Math.floor(i/65536),de=i-d*65536,i=q+d+65535,d=Math.floor(i/65536),q=i-d*65536,i=G+d+65535,d=Math.floor(i/65536),G=i-d*65536,i=V+d+65535,d=Math.floor(i/65536),V=i-d*65536,i=Z+d+65535,d=Math.floor(i/65536),Z=i-d*65536,i=X+d+65535,d=Math.floor(i/65536),X=i-d*65536,i=J+d+65535,d=Math.floor(i/65536),J=i-d*65536,i=Y+d+65535,d=Math.floor(i/65536),Y=i-d*65536,i=W+d+65535,d=Math.floor(i/65536),W=i-d*65536,i=U+d+65535,d=Math.floor(i/65536),U=i-d*65536,b+=d-1+37*(d-1),d=1,i=b+d+65535,d=Math.floor(i/65536),b=i-d*65536,i=m+d+65535,d=Math.floor(i/65536),m=i-d*65536,i=_+d+65535,d=Math.floor(i/65536),_=i-d*65536,i=T+d+65535,d=Math.floor(i/65536),T=i-d*65536,i=F+d+65535,d=Math.floor(i/65536),F=i-d*65536,i=M+d+65535,d=Math.floor(i/65536),M=i-d*65536,i=de+d+65535,d=Math.floor(i/65536),de=i-d*65536,i=q+d+65535,d=Math.floor(i/65536),q=i-d*65536,i=G+d+65535,d=Math.floor(i/65536),G=i-d*65536,i=V+d+65535,d=Math.floor(i/65536),V=i-d*65536,i=Z+d+65535,d=Math.floor(i/65536),Z=i-d*65536,i=X+d+65535,d=Math.floor(i/65536),X=i-d*65536,i=J+d+65535,d=Math.floor(i/65536),J=i-d*65536,i=Y+d+65535,d=Math.floor(i/65536),Y=i-d*65536,i=W+d+65535,d=Math.floor(i/65536),W=i-d*65536,i=U+d+65535,d=Math.floor(i/65536),U=i-d*65536,b+=d-1+37*(d-1),a[0]=b,a[1]=m,a[2]=_,a[3]=T,a[4]=F,a[5]=M,a[6]=de,a[7]=q,a[8]=G,a[9]=V,a[10]=Z,a[11]=X,a[12]=J,a[13]=Y,a[14]=W,a[15]=U}function Xe(a,f){ce(a,f,f)}function So(a,f){var u=t(),i;for(i=0;i<16;i++)u[i]=f[i];for(i=253;i>=0;i--)if(Xe(u,u),i!==2&&i!==4)ce(u,u,f);for(i=0;i<16;i++)a[i]=u[i]}function Ao(a,f){var u=t(),i;for(i=0;i<16;i++)u[i]=f[i];for(i=250;i>=0;i--)if(Xe(u,u),i!==1)ce(u,u,f);for(i=0;i<16;i++)a[i]=u[i]}function Gr(a,f,u){var i=new Uint8Array(32),d=new Float64Array(80),b,m,_=t(),T=t(),F=t(),M=t(),de=t(),q=t();for(m=0;m<31;m++)i[m]=f[m];i[31]=f[31]&127|64,i[0]&=248,cn(d,u);for(m=0;m<16;m++)T[m]=d[m],M[m]=_[m]=F[m]=0;_[0]=M[0]=1;for(m=254;m>=0;--m)b=i[m>>>3]>>>(m&7)&1,Wt(_,T,b),Wt(F,M,b),et(de,_,F),tt(_,_,F),et(F,T,M),tt(T,T,M),Xe(M,de),Xe(q,_),ce(_,F,_),ce(F,T,de),et(de,_,F),tt(_,_,F),Xe(T,_),tt(F,M,q),ce(_,F,h),et(_,_,M),ce(F,F,_),ce(_,M,q),ce(M,T,d),Xe(T,de),Wt(_,T,b),Wt(F,M,b);for(m=0;m<16;m++)d[m+16]=_[m],d[m+32]=F[m],d[m+48]=T[m],d[m+64]=M[m];var G=d.subarray(32),V=d.subarray(16);return So(G,G),ce(V,V,G),Yt(a,V),0}function Vr(a,f){return Gr(a,f,n)}function Oo(a,f){return r(f,32),Vr(a,f)}function Jr(a,f,u){var i=new Uint8Array(32);return Gr(i,u,f),Hr(a,s,i,Ct)}var Po=nn,wd=on;function vd(a,f,u,i,d,b){var m=new Uint8Array(32);return Jr(m,d,b),Po(a,f,u,i,m)}function _d(a,f,u,i,d,b){var m=new Uint8Array(32);return Jr(m,d,b),wd(a,f,u,i,m)}var To=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function jo(a,f,u,i){var d=new Int32Array(16),b=new Int32Array(16),m,_,T,F,M,de,q,G,V,Z,X,J,Y,W,U,B,R,L,D,k,g,x,S,v,E,P,z=a[0],Q=a[1],re=a[2],ee=a[3],l=a[4],ie=a[5],he=a[6],le=a[7],se=f[0],ue=f[1],fe=f[2],Ae=f[3],ge=f[4],ve=f[5],_e=f[6],Ee=f[7],Te=0;while(i>=128){for(D=0;D<16;D++)k=8*D+Te,d[D]=u[k+0]<<24|u[k+1]<<16|u[k+2]<<8|u[k+3],b[D]=u[k+4]<<24|u[k+5]<<16|u[k+6]<<8|u[k+7];for(D=0;D<80;D++)if(m=z,_=Q,T=re,F=ee,M=l,de=ie,q=he,G=le,V=se,Z=ue,X=fe,J=Ae,Y=ge,W=ve,U=_e,B=Ee,g=le,x=Ee,S=x&65535,v=x>>>16,E=g&65535,P=g>>>16,g=(l>>>14|ge<<18)^(l>>>18|ge<<14)^(ge>>>9|l<<23),x=(ge>>>14|l<<18)^(ge>>>18|l<<14)^(l>>>9|ge<<23),S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,g=l&ie^~l&he,x=ge&ve^~ge&_e,S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,g=To[D*2],x=To[D*2+1],S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,g=d[D%16],x=b[D%16],S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,v+=S>>>16,E+=v>>>16,P+=E>>>16,R=E&65535|P<<16,L=S&65535|v<<16,g=R,x=L,S=x&65535,v=x>>>16,E=g&65535,P=g>>>16,g=(z>>>28|se<<4)^(se>>>2|z<<30)^(se>>>7|z<<25),x=(se>>>28|z<<4)^(z>>>2|se<<30)^(z>>>7|se<<25),S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,g=z&Q^z&re^Q&re,x=se&ue^se&fe^ue&fe,S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,v+=S>>>16,E+=v>>>16,P+=E>>>16,G=E&65535|P<<16,B=S&65535|v<<16,g=F,x=J,S=x&65535,v=x>>>16,E=g&65535,P=g>>>16,g=R,x=L,S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,v+=S>>>16,E+=v>>>16,P+=E>>>16,F=E&65535|P<<16,J=S&65535|v<<16,Q=m,re=_,ee=T,l=F,ie=M,he=de,le=q,z=G,ue=V,fe=Z,Ae=X,ge=J,ve=Y,_e=W,Ee=U,se=B,D%16===15)for(k=0;k<16;k++)g=d[k],x=b[k],S=x&65535,v=x>>>16,E=g&65535,P=g>>>16,g=d[(k+9)%16],x=b[(k+9)%16],S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,R=d[(k+1)%16],L=b[(k+1)%16],g=(R>>>1|L<<31)^(R>>>8|L<<24)^R>>>7,x=(L>>>1|R<<31)^(L>>>8|R<<24)^(L>>>7|R<<25),S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,R=d[(k+14)%16],L=b[(k+14)%16],g=(R>>>19|L<<13)^(L>>>29|R<<3)^R>>>6,x=(L>>>19|R<<13)^(R>>>29|L<<3)^(L>>>6|R<<26),S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,v+=S>>>16,E+=v>>>16,P+=E>>>16,d[k]=E&65535|P<<16,b[k]=S&65535|v<<16;g=z,x=se,S=x&65535,v=x>>>16,E=g&65535,P=g>>>16,g=a[0],x=f[0],S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,v+=S>>>16,E+=v>>>16,P+=E>>>16,a[0]=z=E&65535|P<<16,f[0]=se=S&65535|v<<16,g=Q,x=ue,S=x&65535,v=x>>>16,E=g&65535,P=g>>>16,g=a[1],x=f[1],S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,v+=S>>>16,E+=v>>>16,P+=E>>>16,a[1]=Q=E&65535|P<<16,f[1]=ue=S&65535|v<<16,g=re,x=fe,S=x&65535,v=x>>>16,E=g&65535,P=g>>>16,g=a[2],x=f[2],S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,v+=S>>>16,E+=v>>>16,P+=E>>>16,a[2]=re=E&65535|P<<16,f[2]=fe=S&65535|v<<16,g=ee,x=Ae,S=x&65535,v=x>>>16,E=g&65535,P=g>>>16,g=a[3],x=f[3],S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,v+=S>>>16,E+=v>>>16,P+=E>>>16,a[3]=ee=E&65535|P<<16,f[3]=Ae=S&65535|v<<16,g=l,x=ge,S=x&65535,v=x>>>16,E=g&65535,P=g>>>16,g=a[4],x=f[4],S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,v+=S>>>16,E+=v>>>16,P+=E>>>16,a[4]=l=E&65535|P<<16,f[4]=ge=S&65535|v<<16,g=ie,x=ve,S=x&65535,v=x>>>16,E=g&65535,P=g>>>16,g=a[5],x=f[5],S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,v+=S>>>16,E+=v>>>16,P+=E>>>16,a[5]=ie=E&65535|P<<16,f[5]=ve=S&65535|v<<16,g=he,x=_e,S=x&65535,v=x>>>16,E=g&65535,P=g>>>16,g=a[6],x=f[6],S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,v+=S>>>16,E+=v>>>16,P+=E>>>16,a[6]=he=E&65535|P<<16,f[6]=_e=S&65535|v<<16,g=le,x=Ee,S=x&65535,v=x>>>16,E=g&65535,P=g>>>16,g=a[7],x=f[7],S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,v+=S>>>16,E+=v>>>16,P+=E>>>16,a[7]=le=E&65535|P<<16,f[7]=Ee=S&65535|v<<16,Te+=128,i-=128}return i}function kt(a,f,u){var i=new Int32Array(8),d=new Int32Array(8),b=new Uint8Array(256),m,_=u;i[0]=1779033703,i[1]=3144134277,i[2]=1013904242,i[3]=2773480762,i[4]=1359893119,i[5]=2600822924,i[6]=528734635,i[7]=1541459225,d[0]=4089235720,d[1]=2227873595,d[2]=4271175723,d[3]=1595750129,d[4]=2917565137,d[5]=725511199,d[6]=4215389547,d[7]=327033209,jo(i,d,f,u),u%=128;for(m=0;m<u;m++)b[m]=f[_-u+m];b[u]=128,u=256-128*(u<112?1:0),b[u-9]=0,K(b,u-8,_/536870912|0,_<<3),jo(i,d,b,u);for(m=0;m<8;m++)K(a,8*m,i[m],d[m]);return 0}function Wr(a,f){var u=t(),i=t(),d=t(),b=t(),m=t(),_=t(),T=t(),F=t(),M=t();tt(u,a[1],a[0]),tt(M,f[1],f[0]),ce(u,u,M),et(i,a[0],a[1]),et(M,f[0],f[1]),ce(i,i,M),ce(d,a[3],f[3]),ce(d,d,w),ce(b,a[2],f[2]),et(b,b,b),tt(m,i,u),tt(_,b,d),et(T,b,d),et(F,i,u),ce(a[0],m,_),ce(a[1],F,T),ce(a[2],T,_),ce(a[3],m,F)}function Io(a,f,u){var i;for(i=0;i<4;i++)Wt(a[i],f[i],u)}function un(a,f){var u=t(),i=t(),d=t();So(d,f[2]),ce(u,f[0],d),ce(i,f[1],d),Yt(a,i),a[31]^=Eo(u)<<7}function fn(a,f,u){var i,d;pt(a[0],o),pt(a[1],c),pt(a[2],c),pt(a[3],o);for(d=255;d>=0;--d)i=u[d/8|0]>>(d&7)&1,Io(a,f,i),Wr(f,a),Wr(a,a),Io(a,f,i)}function Yr(a,f){var u=[t(),t(),t(),t()];pt(u[0],A),pt(u[1],j),pt(u[2],c),ce(u[3],A,j),fn(a,u,f)}function dn(a,f,u){var i=new Uint8Array(64),d=[t(),t(),t(),t()],b;if(!u)r(f,32);kt(i,f,32),i[0]&=248,i[31]&=127,i[31]|=64,Yr(d,i),un(a,d);for(b=0;b<32;b++)f[b+32]=a[b];return 0}var Xr=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 hn(a,f){var u,i,d,b;for(i=63;i>=32;--i){u=0;for(d=i-32,b=i-12;d<b;++d)f[d]+=u-16*f[i]*Xr[d-(i-32)],u=Math.floor((f[d]+128)/256),f[d]-=u*256;f[d]+=u,f[i]=0}u=0;for(d=0;d<32;d++)f[d]+=u-(f[31]>>4)*Xr[d],u=f[d]>>8,f[d]&=255;for(d=0;d<32;d++)f[d]-=u*Xr[d];for(i=0;i<32;i++)f[i+1]+=f[i]>>8,a[i]=f[i]&255}function ln(a){var f=new Float64Array(64),u;for(u=0;u<64;u++)f[u]=a[u];for(u=0;u<64;u++)a[u]=0;hn(a,f)}function No(a,f,u,i){var d=new Uint8Array(64),b=new Uint8Array(64),m=new Uint8Array(64),_,T,F=new Float64Array(64),M=[t(),t(),t(),t()];kt(d,i,32),d[0]&=248,d[31]&=127,d[31]|=64;var de=u+64;for(_=0;_<u;_++)a[64+_]=f[_];for(_=0;_<32;_++)a[32+_]=d[32+_];kt(m,a.subarray(32),u+32),ln(m),Yr(M,m),un(a,M);for(_=32;_<64;_++)a[_]=i[_];kt(b,a,u+64),ln(b);for(_=0;_<64;_++)F[_]=0;for(_=0;_<32;_++)F[_]=m[_];for(_=0;_<32;_++)for(T=0;T<32;T++)F[_+T]+=b[_]*d[T];return hn(a.subarray(32),F),de}function Ed(a,f){var u=t(),i=t(),d=t(),b=t(),m=t(),_=t(),T=t();if(pt(a[2],c),cn(a[1],f),Xe(d,a[1]),ce(b,d,p),tt(d,d,a[2]),et(b,a[2],b),Xe(m,b),Xe(_,m),ce(T,_,m),ce(u,T,d),ce(u,u,b),Ao(u,u),ce(u,u,d),ce(u,u,b),ce(u,u,b),ce(a[0],u,b),Xe(i,a[0]),ce(i,i,b),_o(i,d))ce(a[0],a[0],O);if(Xe(i,a[0]),ce(i,i,b),_o(i,d))return-1;if(Eo(a[0])===f[31]>>7)tt(a[0],o,a[0]);return ce(a[3],a[0],a[1]),0}function pn(a,f,u,i){var d,b=new Uint8Array(32),m=new Uint8Array(64),_=[t(),t(),t(),t()],T=[t(),t(),t(),t()];if(u<64)return-1;if(Ed(T,i))return-1;for(d=0;d<u;d++)a[d]=f[d];for(d=0;d<32;d++)a[d+32]=i[d];if(kt(m,a,u),ln(m),fn(_,T,m),Yr(T,f.subarray(32)),Wr(_,T),un(b,_),u-=64,be(f,0,b,0)){for(d=0;d<u;d++)a[d]=0;return-1}for(d=0;d<u;d++)a[d]=f[d+64];return u}var yn=32,Zr=24,br=32,Xt=16,mr=32,Qr=32,gr=32,xr=32,bn=32,Co=Zr,Sd=br,Ad=Xt,yt=64,Mt=32,Zt=64,mn=32,gn=64;e.lowlevel={crypto_core_hsalsa20:Hr,crypto_stream_xor:rn,crypto_stream:wo,crypto_stream_salsa20_xor:go,crypto_stream_salsa20:xo,crypto_onetimeauth:sn,crypto_onetimeauth_verify:vo,crypto_verify_16:Pe,crypto_verify_32:be,crypto_secretbox:nn,crypto_secretbox_open:on,crypto_scalarmult:Gr,crypto_scalarmult_base:Vr,crypto_box_beforenm:Jr,crypto_box_afternm:Po,crypto_box:vd,crypto_box_open:_d,crypto_box_keypair:Oo,crypto_hash:kt,crypto_sign:No,crypto_sign_keypair:dn,crypto_sign_open:pn,crypto_secretbox_KEYBYTES:yn,crypto_secretbox_NONCEBYTES:Zr,crypto_secretbox_ZEROBYTES:br,crypto_secretbox_BOXZEROBYTES:Xt,crypto_scalarmult_BYTES:mr,crypto_scalarmult_SCALARBYTES:Qr,crypto_box_PUBLICKEYBYTES:gr,crypto_box_SECRETKEYBYTES:xr,crypto_box_BEFORENMBYTES:bn,crypto_box_NONCEBYTES:Co,crypto_box_ZEROBYTES:Sd,crypto_box_BOXZEROBYTES:Ad,crypto_sign_BYTES:yt,crypto_sign_PUBLICKEYBYTES:Mt,crypto_sign_SECRETKEYBYTES:Zt,crypto_sign_SEEDBYTES:mn,crypto_hash_BYTES:gn,gf:t,D:p,L:Xr,pack25519:Yt,unpack25519:cn,M:ce,A:et,S:Xe,Z:tt,pow2523:Ao,add:Wr,set25519:pt,modL:hn,scalarmult:fn,scalarbase:Yr};function ko(a,f){if(a.length!==yn)throw Error("bad key size");if(f.length!==Zr)throw Error("bad nonce size")}function Od(a,f){if(a.length!==gr)throw Error("bad public key size");if(f.length!==xr)throw Error("bad secret key size")}function Ge(){for(var a=0;a<arguments.length;a++)if(!(arguments[a]instanceof Uint8Array))throw TypeError("unexpected type, use Uint8Array")}function Mo(a){for(var f=0;f<a.length;f++)a[f]=0}e.randomBytes=function(a){var f=new Uint8Array(a);return r(f,a),f},e.secretbox=function(a,f,u){Ge(a,f,u),ko(u,f);var i=new Uint8Array(br+a.length),d=new Uint8Array(i.length);for(var b=0;b<a.length;b++)i[b+br]=a[b];return nn(d,i,i.length,f,u),d.subarray(Xt)},e.secretbox.open=function(a,f,u){Ge(a,f,u),ko(u,f);var i=new Uint8Array(Xt+a.length),d=new Uint8Array(i.length);for(var b=0;b<a.length;b++)i[b+Xt]=a[b];if(i.length<32)return null;if(on(d,i,i.length,f,u)!==0)return null;return d.subarray(br)},e.secretbox.keyLength=yn,e.secretbox.nonceLength=Zr,e.secretbox.overheadLength=Xt,e.scalarMult=function(a,f){if(Ge(a,f),a.length!==Qr)throw Error("bad n size");if(f.length!==mr)throw Error("bad p size");var u=new Uint8Array(mr);return Gr(u,a,f),u},e.scalarMult.base=function(a){if(Ge(a),a.length!==Qr)throw Error("bad n size");var f=new Uint8Array(mr);return Vr(f,a),f},e.scalarMult.scalarLength=Qr,e.scalarMult.groupElementLength=mr,e.box=function(a,f,u,i){var d=e.box.before(u,i);return e.secretbox(a,f,d)},e.box.before=function(a,f){Ge(a,f),Od(a,f);var u=new Uint8Array(bn);return Jr(u,a,f),u},e.box.after=e.secretbox,e.box.open=function(a,f,u,i){var d=e.box.before(u,i);return e.secretbox.open(a,f,d)},e.box.open.after=e.secretbox.open,e.box.keyPair=function(){var a=new Uint8Array(gr),f=new Uint8Array(xr);return Oo(a,f),{publicKey:a,secretKey:f}},e.box.keyPair.fromSecretKey=function(a){if(Ge(a),a.length!==xr)throw Error("bad secret key size");var f=new Uint8Array(gr);return Vr(f,a),{publicKey:f,secretKey:new Uint8Array(a)}},e.box.publicKeyLength=gr,e.box.secretKeyLength=xr,e.box.sharedKeyLength=bn,e.box.nonceLength=Co,e.box.overheadLength=e.secretbox.overheadLength,e.sign=function(a,f){if(Ge(a,f),f.length!==Zt)throw Error("bad secret key size");var u=new Uint8Array(yt+a.length);return No(u,a,a.length,f),u},e.sign.open=function(a,f){if(Ge(a,f),f.length!==Mt)throw Error("bad public key size");var u=new Uint8Array(a.length),i=pn(u,a,a.length,f);if(i<0)return null;var d=new Uint8Array(i);for(var b=0;b<d.length;b++)d[b]=u[b];return d},e.sign.detached=function(a,f){var u=e.sign(a,f),i=new Uint8Array(yt);for(var d=0;d<i.length;d++)i[d]=u[d];return i},e.sign.detached.verify=function(a,f,u){if(Ge(a,f,u),f.length!==yt)throw Error("bad signature size");if(u.length!==Mt)throw Error("bad public key size");var i=new Uint8Array(yt+a.length),d=new Uint8Array(yt+a.length),b;for(b=0;b<yt;b++)i[b]=f[b];for(b=0;b<a.length;b++)i[b+yt]=a[b];return pn(d,i,i.length,u)>=0},e.sign.keyPair=function(){var a=new Uint8Array(Mt),f=new Uint8Array(Zt);return dn(a,f),{publicKey:a,secretKey:f}},e.sign.keyPair.fromSecretKey=function(a){if(Ge(a),a.length!==Zt)throw Error("bad secret key size");var f=new Uint8Array(Mt);for(var u=0;u<f.length;u++)f[u]=a[32+u];return{publicKey:f,secretKey:new Uint8Array(a)}},e.sign.keyPair.fromSeed=function(a){if(Ge(a),a.length!==mn)throw Error("bad seed size");var f=new Uint8Array(Mt),u=new Uint8Array(Zt);for(var i=0;i<32;i++)u[i]=a[i];return dn(f,u,!0),{publicKey:f,secretKey:u}},e.sign.publicKeyLength=Mt,e.sign.secretKeyLength=Zt,e.sign.seedLength=mn,e.sign.signatureLength=yt,e.hash=function(a){Ge(a);var f=new Uint8Array(gn);return kt(f,a,a.length),f},e.hash.hashLength=gn,e.verify=function(a,f){if(Ge(a,f),a.length===0||f.length===0)return!1;if(a.length!==f.length)return!1;return N(a,0,f,0,a.length)===0?!0:!1},e.setPRNG=function(a){r=a},function(){var a=typeof self<"u"?self.crypto||self.msCrypto:null;if(a&&a.getRandomValues){var f=65536;e.setPRNG(function(u,i){var d,b=new Uint8Array(i);for(d=0;d<i;d+=f)a.getRandomValues(b.subarray(d,d+Math.min(i-d,f)));for(d=0;d<i;d++)u[d]=b[d];Mo(b)})}else if(a=Rt("crypto"),a&&a.randomBytes)e.setPRNG(function(u,i){var d,b=a.randomBytes(i);for(d=0;d<i;d++)u[d]=b[d];Mo(b)})}()})(typeof xs<"u"&&ax?ax:self.nacl=self.nacl||{})});var Or=H(function(Ar){var Gl=Ar&&Ar.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ar,"__esModule",{value:!0});var Vl=Gl(oc());Ar.default=Vl.default});var cc=H(function(sr){var Jl=sr&&sr.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(sr,"__esModule",{value:!0});sr.KP=void 0;var ws=Sr(),Re=Ut(),rr=Jl(Or());class ac{seed;constructor(e){this.seed=e}getRawSeed(){if(!this.seed)throw new Re.NKeysError(Re.NKeysErrorCode.ClearedPair);return ws.Codec.decodeSeed(this.seed).buf}getSeed(){if(!this.seed)throw new Re.NKeysError(Re.NKeysErrorCode.ClearedPair);return this.seed}getPublicKey(){if(!this.seed)throw new Re.NKeysError(Re.NKeysErrorCode.ClearedPair);let e=ws.Codec.decodeSeed(this.seed),t=rr.default.sign.keyPair.fromSeed(this.getRawSeed()),r=ws.Codec.encode(e.prefix,t.publicKey);return new TextDecoder().decode(r)}getPrivateKey(){if(!this.seed)throw new Re.NKeysError(Re.NKeysErrorCode.ClearedPair);let e=rr.default.sign.keyPair.fromSeed(this.getRawSeed());return ws.Codec.encode(Re.Prefix.Private,e.secretKey)}sign(e){if(!this.seed)throw new Re.NKeysError(Re.NKeysErrorCode.ClearedPair);let t=rr.default.sign.keyPair.fromSeed(this.getRawSeed());return rr.default.sign.detached(e,t.secretKey)}verify(e,t){if(!this.seed)throw new Re.NKeysError(Re.NKeysErrorCode.ClearedPair);let r=rr.default.sign.keyPair.fromSeed(this.getRawSeed());return rr.default.sign.detached.verify(e,t,r.publicKey)}clear(){if(!this.seed)return;this.seed.fill(0),this.seed=void 0}seal(e,t,r){throw new Re.NKeysError(Re.NKeysErrorCode.InvalidNKeyOperation)}open(e,t){throw new Re.NKeysError(Re.NKeysErrorCode.InvalidNKeyOperation)}}sr.KP=ac});var fc=H(function(nr){var Wl=nr&&nr.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(nr,"__esModule",{value:!0});nr.PublicKey=void 0;var Yl=Sr(),Oe=Ut(),Xl=Wl(Or());class uc{publicKey;constructor(e){this.publicKey=e}getPublicKey(){if(!this.publicKey)throw new Oe.NKeysError(Oe.NKeysErrorCode.ClearedPair);return new TextDecoder().decode(this.publicKey)}getPrivateKey(){if(!this.publicKey)throw new Oe.NKeysError(Oe.NKeysErrorCode.ClearedPair);throw new Oe.NKeysError(Oe.NKeysErrorCode.PublicKeyOnly)}getSeed(){if(!this.publicKey)throw new Oe.NKeysError(Oe.NKeysErrorCode.ClearedPair);throw new Oe.NKeysError(Oe.NKeysErrorCode.PublicKeyOnly)}sign(e){if(!this.publicKey)throw new Oe.NKeysError(Oe.NKeysErrorCode.ClearedPair);throw new Oe.NKeysError(Oe.NKeysErrorCode.CannotSign)}verify(e,t){if(!this.publicKey)throw new Oe.NKeysError(Oe.NKeysErrorCode.ClearedPair);let r=Yl.Codec._decode(this.publicKey);return Xl.default.sign.detached.verify(e,t,r.slice(1))}clear(){if(!this.publicKey)return;this.publicKey.fill(0),this.publicKey=void 0}seal(e,t,r){throw new Oe.NKeysError(Oe.NKeysErrorCode.InvalidNKeyOperation)}open(e,t){throw new Oe.NKeysError(Oe.NKeysErrorCode.InvalidNKeyOperation)}}nr.PublicKey=uc});var hc=H(function(De){var Zl=De&&De.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(De,"__esModule",{value:!0});De.CurveKP=De.curveNonceLen=De.curveKeyLen=void 0;var we=Ut(),vs=Zl(Or()),ci=Sr(),_s=Ut(),Ql=ai(),ep=ii();De.curveKeyLen=32;var tp=35;De.curveNonceLen=24;var Lt=[120,107,118,49];class dc{seed;constructor(e){this.seed=e}clear(){if(!this.seed)return;this.seed.fill(0),this.seed=void 0}getPrivateKey(){if(!this.seed)throw new we.NKeysError(we.NKeysErrorCode.ClearedPair);return ci.Codec.encode(_s.Prefix.Private,this.seed)}getPublicKey(){if(!this.seed)throw new we.NKeysError(we.NKeysErrorCode.ClearedPair);let e=vs.default.scalarMult.base(this.seed),t=ci.Codec.encode(_s.Prefix.Curve,e);return new TextDecoder().decode(t)}getSeed(){if(!this.seed)throw new we.NKeysError(we.NKeysErrorCode.ClearedPair);return ci.Codec.encodeSeed(_s.Prefix.Curve,this.seed)}sign(){throw new we.NKeysError(we.NKeysErrorCode.InvalidCurveOperation)}verify(){throw new we.NKeysError(we.NKeysErrorCode.InvalidCurveOperation)}decodePubCurveKey(e){try{let t=Ql.base32.decode(new TextEncoder().encode(e));if(t.byteLength!==tp)throw new we.NKeysError(we.NKeysErrorCode.InvalidCurveKey);if(t[0]!==_s.Prefix.Curve)throw new we.NKeysError(we.NKeysErrorCode.InvalidPublicKey);let r=t.byteLength-2,n=new DataView(t.buffer).getUint16(r,!0),o=t.slice(0,r);if(!ep.crc16.validate(o,n))throw new we.NKeysError(we.NKeysErrorCode.InvalidChecksum);return o.slice(1)}catch(t){throw new we.NKeysError(we.NKeysErrorCode.InvalidRecipient,{cause:t})}}seal(e,t,r){if(!this.seed)throw new we.NKeysError(we.NKeysErrorCode.ClearedPair);if(!r)r=vs.default.randomBytes(De.curveNonceLen);let s=this.decodePubCurveKey(t),n=new Uint8Array(Lt.length+De.curveNonceLen);n.set(Lt,0),n.set(r,Lt.length);let o=vs.default.box(e,r,s,this.seed),c=new Uint8Array(n.length+o.length);return c.set(n),c.set(o,n.length),c}open(e,t){if(!this.seed)throw new we.NKeysError(we.NKeysErrorCode.ClearedPair);if(e.length<=De.curveNonceLen+Lt.length)throw new we.NKeysError(we.NKeysErrorCode.InvalidEncrypted);for(let n=0;n<Lt.length;n++)if(e[n]!==Lt[n])throw new we.NKeysError(we.NKeysErrorCode.InvalidEncrypted);let r=this.decodePubCurveKey(t);e=e.slice(Lt.length);let s=e.slice(0,De.curveNonceLen);return e=e.slice(De.curveNonceLen),vs.default.box.open(e,s,r,this.seed)}}De.CurveKP=dc});var Ut=H(function(Se){var rp=Se&&Se.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Se,"__esModule",{value:!0});Se.NKeysError=Se.NKeysErrorCode=Se.Prefixes=Se.Prefix=void 0;Se.createPair=Dt;Se.createOperator=ip;Se.createAccount=op;Se.createUser=ap;Se.createCluster=cp;Se.createServer=up;Se.createCurve=fp;Se.fromPublic=dp;Se.fromCurveSeed=pc;Se.fromSeed=hp;var lc=cc(),sp=fc(),As=Sr(),Es=hc(),np=rp(Or());function Dt(e){let t=e===ae.Curve?Es.curveKeyLen:32,r=np.default.randomBytes(t),s=As.Codec.encodeSeed(e,new Uint8Array(r));return e===ae.Curve?new Es.CurveKP(new Uint8Array(r)):new lc.KP(s)}function ip(){return Dt(ae.Operator)}function op(){return Dt(ae.Account)}function ap(){return Dt(ae.User)}function cp(){return Dt(ae.Cluster)}function up(){return Dt(ae.Server)}function fp(){return Dt(ae.Curve)}function dp(e){let t=new TextEncoder().encode(e),r=As.Codec._decode(t),s=Ss.parsePrefix(r[0]);if(Ss.isValidPublicPrefix(s))return new sp.PublicKey(t);throw new Tr(Pr.InvalidPublicKey)}function pc(e){let t=As.Codec.decodeSeed(e);if(t.prefix!==ae.Curve)throw new Tr(Pr.InvalidCurveSeed);if(t.buf.byteLength!==Es.curveKeyLen)throw new Tr(Pr.InvalidSeedLen);return new Es.CurveKP(t.buf)}function hp(e){if(As.Codec.decodeSeed(e).prefix===ae.Curve)return pc(e);return new lc.KP(e)}var ae;(function(e){e[e.Unknown=-1]="Unknown",e[e.Seed=144]="Seed",e[e.Private=120]="Private",e[e.Operator=112]="Operator",e[e.Server=104]="Server",e[e.Cluster=16]="Cluster",e[e.Account=0]="Account",e[e.User=160]="User",e[e.Curve=184]="Curve"})(ae||(Se.Prefix=ae={}));class Ss{static isValidPublicPrefix(e){return e==ae.Server||e==ae.Operator||e==ae.Cluster||e==ae.Account||e==ae.User||e==ae.Curve}static startsWithValidPrefix(e){let t=e[0];return t=="S"||t=="P"||t=="O"||t=="N"||t=="C"||t=="A"||t=="U"||t=="X"}static isValidPrefix(e){return this.parsePrefix(e)!==ae.Unknown}static parsePrefix(e){switch(e){case ae.Seed:return ae.Seed;case ae.Private:return ae.Private;case ae.Operator:return ae.Operator;case ae.Server:return ae.Server;case ae.Cluster:return ae.Cluster;case ae.Account:return ae.Account;case ae.User:return ae.User;case ae.Curve:return ae.Curve;default:return ae.Unknown}}}Se.Prefixes=Ss;var Pr;(function(e){e.InvalidPrefixByte="nkeys: invalid prefix byte",e.InvalidKey="nkeys: invalid key",e.InvalidPublicKey="nkeys: invalid public key",e.InvalidSeedLen="nkeys: invalid seed length",e.InvalidSeed="nkeys: invalid seed",e.InvalidCurveSeed="nkeys: invalid curve seed",e.InvalidCurveKey="nkeys: not a valid curve key",e.InvalidCurveOperation="nkeys: curve key is not valid for sign/verify",e.InvalidNKeyOperation="keys: only curve key can seal/open",e.InvalidEncoding="nkeys: invalid encoded key",e.InvalidRecipient="nkeys: not a valid recipient public curve key",e.InvalidEncrypted="nkeys: encrypted input is not valid",e.CannotSign="nkeys: cannot sign, no private key available",e.PublicKeyOnly="nkeys: no seed or private key available",e.InvalidChecksum="nkeys: invalid checksum",e.SerializationError="nkeys: serialization error",e.ApiError="nkeys: api error",e.ClearedPair="nkeys: pair is cleared"})(Pr||(Se.NKeysErrorCode=Pr={}));class Tr extends Error{code;constructor(e,t){super(e,t);this.code=e}}Se.NKeysError=Tr});var bc=H(function(yc){Object.defineProperty(yc,"__esModule",{value:!0});yc.encode=lp;yc.decode=pp;yc.dump=yp;function lp(e){return btoa(String.fromCharCode(...e))}function pp(e){let t=atob(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function yp(e,t){if(t)console.log(t);let r=[];for(let s=0;s<e.byteLength;s++){if(s%8===0)r.push(`
|
|
8
|
+
`);let n=e[s].toString(16);if(n.length===1)n="0"+n;r.push(n)}console.log(r.join(" "))}});var xc=H(function(mc){Object.defineProperty(mc,"__esModule",{value:!0});mc.version=void 0;mc.version="2.0.3"});var ui=H(function(je){Object.defineProperty(je,"__esModule",{value:!0});je.version=je.encode=je.decode=je.Prefixes=je.Prefix=je.NKeysErrorCode=je.NKeysError=je.fromSeed=je.fromPublic=je.fromCurveSeed=je.createUser=je.createServer=je.createPair=je.createOperator=je.createCurve=je.createCluster=je.createAccount=void 0;var Be=Ut();Object.defineProperty(je,"createAccount",{enumerable:!0,get:function(){return Be.createAccount}});Object.defineProperty(je,"createCluster",{enumerable:!0,get:function(){return Be.createCluster}});Object.defineProperty(je,"createCurve",{enumerable:!0,get:function(){return Be.createCurve}});Object.defineProperty(je,"createOperator",{enumerable:!0,get:function(){return Be.createOperator}});Object.defineProperty(je,"createPair",{enumerable:!0,get:function(){return Be.createPair}});Object.defineProperty(je,"createServer",{enumerable:!0,get:function(){return Be.createServer}});Object.defineProperty(je,"createUser",{enumerable:!0,get:function(){return Be.createUser}});Object.defineProperty(je,"fromCurveSeed",{enumerable:!0,get:function(){return Be.fromCurveSeed}});Object.defineProperty(je,"fromPublic",{enumerable:!0,get:function(){return Be.fromPublic}});Object.defineProperty(je,"fromSeed",{enumerable:!0,get:function(){return Be.fromSeed}});Object.defineProperty(je,"NKeysError",{enumerable:!0,get:function(){return Be.NKeysError}});Object.defineProperty(je,"NKeysErrorCode",{enumerable:!0,get:function(){return Be.NKeysErrorCode}});Object.defineProperty(je,"Prefix",{enumerable:!0,get:function(){return Be.Prefix}});Object.defineProperty(je,"Prefixes",{enumerable:!0,get:function(){return Be.Prefixes}});var wc=bc();Object.defineProperty(je,"decode",{enumerable:!0,get:function(){return wc.decode}});Object.defineProperty(je,"encode",{enumerable:!0,get:function(){return wc.encode}});var xp=xc();Object.defineProperty(je,"version",{enumerable:!0,get:function(){return xp.version}})});var fi=H(function(ut){var vp=ut&&ut.__createBinding||(Object.create?function(e,t,r,s){if(s===void 0)s=r;var n=Object.getOwnPropertyDescriptor(t,r);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable))n={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,s,n)}:function(e,t,r,s){if(s===void 0)s=r;e[s]=t[r]}),_p=ut&&ut.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ep=ut&&ut.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var s=[];for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n))s[s.length]=n;return s},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null){for(var s=e(t),n=0;n<s.length;n++)if(s[n]!=="default")vp(r,t,s[n])}return _p(r,t),r}}();Object.defineProperty(ut,"__esModule",{value:!0});ut.nkeys=void 0;ut.nkeys=Ep(ui())});var hi=H(function(Sc){Object.defineProperty(Sc,"__esModule",{value:!0});Sc.multiAuthenticator=Sp;Sc.noAuthFn=Ap;Sc.usernamePasswordAuthenticator=Op;Sc.tokenAuthenticator=Pp;Sc.nkeyAuthenticator=_c;Sc.jwtAuthenticator=Ec;Sc.credsAuthenticator=Tp;var vc=fi(),di=Ve();function Sp(e){return(t)=>{let r={};return e.forEach((s)=>{let n=s(t)||{};r=Object.assign(r,n)}),r}}function Ap(){return()=>{return}}function Op(e,t){return()=>{let r=typeof e==="function"?e():e,s=typeof t==="function"?t():t;return{user:r,pass:s}}}function Pp(e){return()=>({auth_token:typeof e==="function"?e():e})}function _c(e){return(t)=>{let r=typeof e==="function"?e():e,s=r?vc.nkeys.fromSeed(r):void 0,n=s?s.getPublicKey():"",o=di.TE.encode(t||""),c=s!==void 0&&t?s.sign(o):void 0,h=c?vc.nkeys.encode(c):"";return{nkey:n,sig:h}}}function Ec(e,t){return(r)=>{let s=typeof e==="function"?e():e,n=_c(t),{nkey:o,sig:c}=n(r);return{jwt:s,nkey:o,sig:c}}}function Tp(e){let t=typeof e!=="function"?()=>e:e,r=()=>{let o=/\s*(?:(?:[-]{3,}[^\n]*[-]{3,}\n)(.+)(?:\n\s*[-]{3,}[^\n]*[-]{3,}\n))/ig,c=di.TD.decode(t()),h=o.exec(c);if(!h)throw Error("unable to parse credentials");let p=h[1].trim();if(h=o.exec(c),!h)throw Error("unable to parse credentials");let w=di.TE.encode(h[1].trim());return{jwt:p,seed:w}};return Ec(()=>{let{jwt:o}=r();return o},()=>{let{seed:o}=r();return o})}});var Ir=H(function(Pc){Object.defineProperty(Pc,"__esModule",{value:!0});Pc.DEFAULT_RECONNECT_TIME_WAIT=Pc.DEFAULT_MAX_PING_OUT=Pc.DEFAULT_PING_INTERVAL=Pc.DEFAULT_JITTER_TLS=Pc.DEFAULT_JITTER=Pc.DEFAULT_MAX_RECONNECT_ATTEMPTS=void 0;Pc.defaultOptions=Ac;Pc.hasWsProtocol=$p;Pc.buildAuthenticator=Oc;Pc.parseOptions=Up;Pc.checkOptions=Lp;Pc.checkUnsupportedOption=Dp;var qp=rt(),li=qt(),pi=Et(),Os=hi(),jr=Je();Pc.DEFAULT_MAX_RECONNECT_ATTEMPTS=10;Pc.DEFAULT_JITTER=100;Pc.DEFAULT_JITTER_TLS=1000;Pc.DEFAULT_PING_INTERVAL=120000;Pc.DEFAULT_MAX_PING_OUT=2;Pc.DEFAULT_RECONNECT_TIME_WAIT=2000;function Ac(){return{maxPingOut:Pc.DEFAULT_MAX_PING_OUT,maxReconnectAttempts:Pc.DEFAULT_MAX_RECONNECT_ATTEMPTS,noRandomize:!1,pedantic:!1,pingInterval:Pc.DEFAULT_PING_INTERVAL,reconnect:!0,reconnectJitter:Pc.DEFAULT_JITTER,reconnectJitterTLS:Pc.DEFAULT_JITTER_TLS,reconnectTimeWait:Pc.DEFAULT_RECONNECT_TIME_WAIT,tls:void 0,verbose:!1,waitOnFirstConnect:!1,ignoreAuthErrorAbort:!1}}function $p(e){if(e){let{servers:t}=e;if(typeof t==="string")t=[t];if(t)for(let r=0;r<t.length;r++){let s=t[r].toLowerCase();if(s.startsWith("ws://")||s.startsWith("wss://"))return!0}}return!1}function Oc(e){let t=[];if(typeof e.authenticator==="function")t.push(e.authenticator);if(Array.isArray(e.authenticator))t.push(...e.authenticator);if(e.token)t.push((0,Os.tokenAuthenticator)(e.token));if(e.user)t.push((0,Os.usernamePasswordAuthenticator)(e.user,e.pass));return t.length===0?(0,Os.noAuthFn)():(0,Os.multiAuthenticator)(t)}function Up(e){let t=`${pi.DEFAULT_HOST}:${(0,li.defaultPort)()}`;if(e=e||{servers:[t]},e.servers=e.servers||[],typeof e.servers==="string")e.servers=[e.servers];if(e.servers.length>0&&e.port)throw jr.InvalidArgumentError.format(["servers","port"],"are mutually exclusive");if(e.servers.length===0&&e.port)e.servers=[`${pi.DEFAULT_HOST}:${e.port}`];if(e.servers&&e.servers.length===0)e.servers=[t];let r=(0,qp.extend)(Ac(),e);if(r.authenticator=Oc(r),["reconnectDelayHandler","authenticator"].forEach((s)=>{if(r[s]&&typeof r[s]!=="function")throw TypeError(`'${s}' must be a function`)}),!r.reconnectDelayHandler)r.reconnectDelayHandler=()=>{let s=r.tls?r.reconnectJitterTLS:r.reconnectJitter;if(s)s++,s=Math.floor(Math.random()*s);return r.reconnectTimeWait+s};if(r.inboxPrefix)(0,pi.createInbox)(r.inboxPrefix);if(r.resolve===void 0)r.resolve=typeof(0,li.getResolveFn)()==="function";if(r.resolve){if(typeof(0,li.getResolveFn)()!=="function")throw jr.InvalidArgumentError.format("resolve","is not supported in the current runtime")}return r}function Lp(e,t){let{proto:r,tls_required:s,tls_available:n}=e;if((r===void 0||r<1)&&t.noEcho)throw new jr.errors.ConnectionError("server does not support 'noEcho'");let o=s||n||!1;if(t.tls&&!o)throw new jr.errors.ConnectionError("server does not support 'tls'")}function Dp(e,t){if(t)throw jr.InvalidArgumentError.format(e,"is not supported")}});var Nr=H(function(qc){Object.defineProperty(qc,"__esModule",{value:!0});qc.ProtocolHandler=qc.Subscriptions=qc.SubscriptionImpl=qc.Connect=qc.INFO=void 0;var ft=Ve(),Ft=qt(),nt=rt(),Vp=_r(),Jp=Hn(),Wp=ds(),Yp=Gn(),Xp=Vn(),At=Qn(),Zp=ri(),kc=gs(),bi=Ir(),ke=Je(),Qp=32768;qc.INFO=/^INFO\s+([^\r\n]+)\r\n/i;var e0=(0,ft.encode)(`PONG\r
|
|
9
|
+
`),Mc=(0,ft.encode)(`PING\r
|
|
10
|
+
`),t0="client option reconnectToServer handler failed",r0="returned server is not in the pool";function s0(e){return e!==null&&typeof e==="object"&&"server"in e&&"delay"in e}class mi{echo;no_responders;protocol;verbose;pedantic;jwt;nkey;sig;user;pass;auth_token;tls_required;name;lang;version;headers;constructor(e,t,r){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;let s=(t&&typeof t.authenticator==="function"?t.authenticator(r):{})||{};(0,nt.extend)(this,s)}}qc.Connect=mi;class Rc{slow;cb;notified;constructor(e,t){this.slow=e,this.cb=t,this.notified=!1}maybeNotify(e){if(e<=this.slow)this.notified=!1;else if(!this.notified)this.cb(e),this.notified=!0}}class gi extends Wp.QueuedIteratorImpl{sid;queue;draining;max;subject;drained;protocol;timer;info;cleanupFn;closed;requestSubject;slow;constructor(e,t,r={}){super();(0,nt.extend)(this,r),this.protocol=e,this.subject=t,this.draining=!1,this.noIterator=typeof r.callback==="function",this.closed=(0,nt.deferred)();let s=!e.options?.noAsyncTraces;if(r.timeout)this.timer=(0,nt.timeout)(r.timeout,s),this.timer.then(()=>{this.timer=void 0}).catch((n)=>{if(this.stop(n),this.noIterator)this.callback(n,{})});if(!this.noIterator)this.iterClosed.then((n)=>{this.closed.resolve(n),this.unsubscribe()})}setSlowNotificationFn(e,t){if(this.slow=void 0,t){if(this.noIterator)throw Error("callbacks don't support slow notifications");this.slow=new Rc(e,t)}}callback(e,t){if(this.cancelTimeout(),e?this.stop(e):this.push(t),!e&&this.slow)this.slow.maybeNotify(this.getPending())}close(e){if(!this.isClosed()){this.cancelTimeout();let t=()=>{if(this.stop(),this.cleanupFn)try{this.cleanupFn(this,this.info)}catch(r){}this.closed.resolve(e)};if(this.noIterator)t();else this.push(t)}}unsubscribe(e){this.protocol.unsubscribe(this,e)}cancelTimeout(){if(this.timer)this.timer.cancel(),this.timer=void 0}drain(){if(this.protocol.isClosed())return Promise.reject(new ke.errors.ClosedConnectionError);if(this.isClosed())return Promise.reject(new ke.errors.InvalidOperationError("subscription is already closed"));if(!this.drained)this.draining=!0,this.protocol.unsub(this),this.drained=this.protocol.flush((0,nt.deferred)()).then(()=>{this.protocol.subscriptions.cancel(this)}).catch(()=>{this.protocol.subscriptions.cancel(this)});return this.drained}async[Symbol.asyncDispose](){if(this.protocol.isClosed()||this.isClosed())return;if(this.drained){await this.drained;return}await this.drain()}isDraining(){return this.draining}isClosed(){return this.done}getSubject(){return this.subject}getMax(){return this.max}getID(){return this.sid}}qc.SubscriptionImpl=gi;class xi{mux;subs;sidCounter;constructor(){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){if(e)e.close(),this.subs.delete(e.sid)}handleError(e){let t=this.all(),r;if(e.operation==="subscription")r=t.find((s)=>s.subject===e.subject&&s.queue===e.queue);else if(e.operation==="publish")r=t.find((s)=>s.requestSubject===e.subject);if(r)return r.callback(e,{}),r.close(e),this.subs.delete(r.sid),r!==this.mux;return!1}close(){this.subs.forEach((e)=>{e.close()})}}qc.Subscriptions=xi;class Ps{connected;connectedOnce;infoReceived;info;muxSubscriptions;options;outbound;pongs;subscriptions;transport;noMorePublishing;connectError;publisher;_closed;closed;listeners;heartbeats;parser;outMsgs;inMsgs;outBytes;inBytes;pendingLimit;lastError;abortReconnect;whyClosed;servers;server;features;connectPromise;dialDelay;raceTimer;constructor(e,t){this._closed=!1,this.connected=!1,this.connectedOnce=!1,this.infoReceived=!1,this.noMorePublishing=!1,this.abortReconnect=!1,this.listeners=[],this.pendingLimit=Qp,this.outMsgs=0,this.inMsgs=0,this.outBytes=0,this.inBytes=0,this.options=e,this.publisher=t,this.subscriptions=new xi,this.muxSubscriptions=new Yp.MuxSubscription,this.outbound=new Vp.DataBuffer,this.pongs=[],this.whyClosed="",this.pendingLimit=e.pendingLimit||this.pendingLimit,this.features=new kc.Features({major:0,minor:0,micro:0}),this.connectPromise=null,this.dialDelay=null;let r=typeof e.servers==="string"?[e.servers]:e.servers;this.servers=new Jp.Servers({randomize:!e.noRandomize}),this.servers.setServers(r),this.closed=(0,nt.deferred)(),this.parser=new At.Parser(this),this.heartbeats=new Xp.Heartbeat(this,this.options.pingInterval||bi.DEFAULT_PING_INTERVAL,this.options.maxPingOut||bi.DEFAULT_MAX_PING_OUT)}resetOutbound(){this.outbound.reset();let e=this.pongs;this.pongs=[];let t=new ke.errors.RequestError("connection disconnected");t.stack="",e.forEach((r)=>{r.reject(t)}),this.parser=new At.Parser(this),this.infoReceived=!1}dispatchStatus(e){this.listeners.forEach((t)=>{t.push(e)})}prepare(){if(this.transport)this.transport.discard();this.info=void 0,this.resetOutbound();let e=(0,nt.deferred)();return e.catch(()=>{}),this.pongs.unshift(e),this.connectError=(t)=>{e.reject(t)},this.transport=(0,Ft.newTransport)(),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:"staleConnection"}),this.transport.disconnect()}reconnect(){if(this.connected)this.dispatchStatus({type:"forceReconnect"}),this.transport.disconnect();return Promise.resolve()}async disconnected(e){if(this.dispatchStatus({type:"disconnect",server:this.servers.getCurrentServer().toString()}),this.options.reconnect)await this.dialLoop().then(()=>{if(this.dispatchStatus({type:"reconnect",server:this.servers.getCurrentServer().toString()}),this.lastError instanceof ke.errors.UserAuthenticationExpiredError)this.lastError=void 0}).catch((t)=>{this.close(t).catch()});else await this.close(e).catch()}async dial(e){let t=this.prepare();try{this.raceTimer=(0,nt.timeout)(this.options.timeout||20000);let r=this.transport.connect(e,this.options);await Promise.race([r,this.raceTimer]),(async()=>{try{for await(let s of this.transport)this.parser.parse(s)}catch(s){console.log("reader closed",s)}})().then()}catch(r){t.reject(r)}try{await Promise.race([this.raceTimer,t]),this.raceTimer?.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(r){throw this.raceTimer?.cancel(),await this.transport.close(r),r}}async _doDial(e){let{resolve:t}=this.options,r=await e.resolve({fn:(0,Ft.getResolveFn)(),debug:this.options.debug,randomize:!this.options.noRandomize,resolve:t}),s=null;for(let n of r)try{s=null,this.dispatchStatus({type:"reconnecting"}),await this.dial(n);return}catch(o){s=o}throw s}dialLoop(){if(this.connectPromise===null)this.connectPromise=this.dodialLoop(),this.connectPromise.then(()=>{}).catch(()=>{}).finally(()=>{this.connectPromise=null});return this.connectPromise}async dodialLoop(){let e;while(!0){if(this._closed)this.servers.clear();let t=this.options.reconnectDelayHandler?this.options.reconnectDelayHandler():bi.DEFAULT_RECONNECT_TIME_WAIT,r=t,s=this.selectServer();if(!s||this.abortReconnect)if(e)throw e;else if(this.lastError)throw this.lastError;else throw new ke.errors.ConnectionError("connection refused");let n=Date.now();if(s.lastConnect===0||s.lastConnect+t<=n){let o=s,c=0;if(this.options.reconnectToServer)try{let h=this.servers.snapshotForHandler(),p=this.options.reconnectToServer(h,this.info??null),w;if(s0(p))w=p.server,c=Number.isFinite(p.delay)&&p.delay>0?Math.floor(p.delay):0;else w=p;if(w!==null){let A=this.servers.find(w);if(!A)throw Error(r0);if(A!==s)o=A,this.servers.setCurrent(o),this.server=o}}catch(h){let p=h instanceof Error?h:Error(String(h));throw new ke.errors.ConnectionError(`${t0}: ${p.message}`,{cause:p})}if(c>0)this.dialDelay=(0,nt.delay)(c),await this.dialDelay;o.lastConnect=Date.now();try{await this._doDial(o);break}catch(h){if(e=h,!this.connectedOnce){if(this.options.waitOnFirstConnect)continue;this.servers.removeCurrentServer()}o.reconnects++;let p=this.options.maxReconnectAttempts||0;if(p!==-1&&o.reconnects>=p)this.servers.removeCurrentServer()}}else r=Math.min(r,s.lastConnect+t-n),this.dialDelay=(0,nt.delay)(r),await this.dialDelay}}static async connect(e,t){let r=new Ps(e,t);return await r.dialLoop(),r}static toError(e){let t=ke.errors.PermissionViolationError.parse(e);if(t)return t;if(t=ke.errors.UserAuthenticationExpiredError.parse(e),t)return t;if(t=ke.errors.AuthorizationError.parse(e),t)return t;return new ke.errors.ProtocolError(e)}processMsg(e,t){if(this.inMsgs++,this.inBytes+=t.length,!this.subscriptions.sidCounter)return;let r=this.subscriptions.get(e.sid);if(!r)return;if(r.received+=1,r.callback)r.callback(null,new Zp.MsgImpl(e,t,this));if(r.max!==void 0&&r.received>=r.max)r.unsubscribe()}processError(e){let t=(0,ft.decode)(e);if(t.startsWith("'")&&t.endsWith("'"))t=t.slice(1,t.length-1);let r=Ps.toError(t);switch(r.constructor){case ke.errors.PermissionViolationError:{let s=r,n=this.subscriptions.getMux(),o=n?s.subject===n.subject:!1;if(this.subscriptions.handleError(s),this.muxSubscriptions.handleError(o,s),o)this.subscriptions.setMux(null)}}this.dispatchStatus({type:"error",error:r}),this.handleError(r)}handleError(e){if(e instanceof ke.errors.UserAuthenticationExpiredError||e instanceof ke.errors.AuthorizationError)this.handleAuthError(e);if(!(e instanceof ke.errors.PermissionViolationError))this.lastError=e}handleAuthError(e){if((this.lastError instanceof ke.errors.UserAuthenticationExpiredError||this.lastError instanceof ke.errors.AuthorizationError)&&this.options.ignoreAuthErrorAbort===!1)this.abortReconnect=!0;if(this.connectError)this.connectError(e);else this.disconnect()}processPing(){this.transport.send(e0)}processPong(){let e=this.pongs.shift();if(e)e.resolve()}processInfo(e){let t=JSON.parse((0,ft.decode)(e));this.info=t;let r=this.options&&this.options.ignoreClusterUpdates?void 0:this.servers.update(t,this.transport.isEncrypted());if(!this.infoReceived){if(this.features.update((0,kc.parseSemVer)(t.version)),this.infoReceived=!0,this.transport.isEncrypted())this.servers.updateTLSName();let{version:n,lang:o}=this.transport;try{let c=new mi({version:n,lang:o},this.options,t.nonce);if(t.headers)c.headers=!0,c.no_responders=!0;let h=JSON.stringify(c);this.transport.send((0,ft.encode)(`CONNECT ${h}${Ft.CR_LF}`)),this.transport.send(Mc)}catch(c){this.close(c).catch()}}if(r){let{added:n,deleted:o}=r;this.dispatchStatus({type:"update",added:n,deleted:o})}if(t.ldm!==void 0?t.ldm:!1)this.dispatchStatus({type:"ldm",server:this.servers.getCurrentServer().toString()})}push(e){switch(e.kind){case At.Kind.MSG:{let{msg:t,data:r}=e;this.processMsg(t,r);break}case At.Kind.OK:break;case At.Kind.ERR:this.processError(e.data);break;case At.Kind.PING:this.processPing();break;case At.Kind.PONG:this.processPong();break;case At.Kind.INFO:this.processInfo(e.data);break}}sendCommand(e,...t){let r=this.outbound.length(),s;if(typeof e==="string")s=(0,ft.encode)(e);else s=e;if(this.outbound.fill(s,...t),r===0)queueMicrotask(()=>{this.flushPending()});else if(this.outbound.size()>=this.pendingLimit)this.flushPending()}publish(e,t=ft.Empty,r){let s;if(t instanceof Uint8Array)s=t;else if(typeof t==="string")s=ft.TE.encode(t);else throw TypeError("payload types can be strings or Uint8Array");let n=s.length;r=r||{},r.reply=r.reply||"";let o=ft.Empty,c=0;if(r.headers){if(this.info&&!this.info.headers)ke.InvalidArgumentError.format("headers","are not available on this server");o=r.headers.encode(),c=o.length,n=s.length+c}if(this.info&&n>this.info.max_payload)throw ke.InvalidArgumentError.format("payload","max_payload size exceeded");this.outBytes+=n,this.outMsgs++;let h;if(r.headers){if(r.reply)h=`HPUB ${e} ${r.reply} ${c} ${n}\r
|
|
11
|
+
`;else h=`HPUB ${e} ${c} ${n}\r
|
|
12
|
+
`;this.sendCommand(h,o,s,Ft.CRLF)}else{if(r.reply)h=`PUB ${e} ${r.reply} ${n}\r
|
|
13
|
+
`;else h=`PUB ${e} ${n}\r
|
|
14
|
+
`;this.sendCommand(h,s,Ft.CRLF)}}request(e){return this.initMux(),this.muxSubscriptions.add(e),e}subscribe(e){return this.subscriptions.add(e),this._subunsub(e),e}_sub(e){if(e.queue)this.sendCommand(`SUB ${e.subject} ${e.queue} ${e.sid}\r
|
|
15
|
+
`);else this.sendCommand(`SUB ${e.subject} ${e.sid}\r
|
|
16
|
+
`)}_subunsub(e){if(this._sub(e),e.max)this.unsubscribe(e,e.max);return e}unsubscribe(e,t){if(this.unsub(e,t),e.max===void 0||e.received>=e.max)this.subscriptions.cancel(e)}unsub(e,t){if(!e||this.isClosed())return;if(t)this.sendCommand(`UNSUB ${e.sid} ${t}\r
|
|
17
|
+
`);else this.sendCommand(`UNSUB ${e.sid}\r
|
|
18
|
+
`);e.max=t}resub(e,t){if(!e||this.isClosed())return;this.unsub(e),e.subject=t,this.subscriptions.resub(e),this._sub(e)}flush(e){if(!e)e=(0,nt.deferred)();return this.pongs.push(e),this.outbound.fill(Mc),this.flushPending(),e}sendSubscriptions(){let e=[];if(this.subscriptions.all().forEach((t)=>{let r=t;if(r.queue)e.push(`SUB ${r.subject} ${r.queue} ${r.sid}${Ft.CR_LF}`);else e.push(`SUB ${r.subject} ${r.sid}${Ft.CR_LF}`)}),e.length)this.transport.send((0,ft.encode)(e.join("")))}async close(e){if(this._closed)return;if(this.whyClosed=Error("close trace").stack||"",this.heartbeats.cancel(),this.connectError)this.connectError(e),this.connectError=void 0;this.muxSubscriptions.close(),this.subscriptions.close();let t=[];for(let r=0;r<this.listeners.length;r++){let s=this.listeners[r];if(s)s.push({type:"close"}),s.stop(),t.push(s.iterClosed)}if(t.length)await Promise.all(t);this._closed=!0,await this.transport.close(e),this.raceTimer?.cancel(),this.dialDelay?.cancel(),this.closed.resolve(e)}isClosed(){return this._closed}async drain(){let e=this.subscriptions.all(),t=[];e.forEach((r)=>{t.push(r.drain())});try{await Promise.allSettled(t)}catch{}finally{this.noMorePublishing=!0,await this.flush()}return this.close()}flushPending(){if(!this.infoReceived||!this.connected)return;if(this.outbound.size()){let e=this.outbound.drain();this.transport.send(e)}}initMux(){if(!this.subscriptions.getMux()){let t=this.muxSubscriptions.init(this.options.inboxPrefix),r=new gi(this,`${t}*`);r.callback=this.muxSubscriptions.dispatcher(),this.subscriptions.setMux(r),this.subscribe(r)}}selectServer(){let e=this.servers.selectServer();if(e===void 0)return;return this.server=e,this.server}getServer(){return this.server}}qc.ProtocolHandler=Ps});var wi=H(function(Dc){Object.defineProperty(Dc,"__esModule",{value:!0});Dc.RequestOne=Dc.RequestMany=Dc.BaseRequest=void 0;var js=rt(),Ts=Je();class Is{token;received;ctx;requestSubject;mux;constructor(e,t,r=!0){if(this.mux=e,this.requestSubject=t,this.received=0,this.token=(0,js.randomToken)(),r)this.ctx=new Ts.RequestError}}Dc.BaseRequest=Is;class Uc extends Is{callback;done;timer;max;opts;constructor(e,t,r={maxWait:1000}){super(e,t);if(this.opts=r,typeof this.opts.callback!=="function")throw TypeError("callback must be a function");this.callback=this.opts.callback,this.max=typeof r.maxMessages==="number"&&r.maxMessages>0?r.maxMessages:-1,this.done=(0,js.deferred)(),this.done.then(()=>{this.callback(null,null)}),this.timer=setTimeout(()=>{this.cancel()},r.maxWait)}cancel(e){if(e)this.callback(e,null);clearTimeout(this.timer),this.mux.cancel(this),this.done.resolve()}resolver(e,t){if(e){if(this.ctx)e.stack+=`
|
|
19
|
+
|
|
20
|
+
${this.ctx.stack}`;this.cancel(e)}else{if(this.callback(null,t),this.opts.strategy==="count"){if(this.max--,this.max===0)this.cancel()}if(this.opts.strategy==="stall")clearTimeout(this.timer),this.timer=setTimeout(()=>{this.cancel()},this.opts.stall||300);if(this.opts.strategy==="sentinel"){if(t&&t.data.length===0)this.cancel()}}}}Dc.RequestMany=Uc;class Lc extends Is{deferred;timer;constructor(e,t,r={timeout:1000},s=!0){super(e,t,s);this.deferred=(0,js.deferred)(),this.timer=(0,js.timeout)(r.timeout,s)}resolver(e,t){if(this.timer)this.timer.cancel();if(e){if(!(e instanceof Ts.TimeoutError))if(this.ctx)this.ctx.message=e.message,this.ctx.cause=e,e=this.ctx;else e=new Ts.errors.RequestError(e.message,{cause:e});this.deferred.reject(e)}else this.deferred.resolve(t);this.cancel()}cancel(e){if(this.timer)this.timer.cancel();this.mux.cancel(this),this.deferred.reject(e?e:new Ts.RequestError("cancelled"))}}Dc.RequestOne=Lc});var _i=H(function(Jc){Object.defineProperty(Jc,"__esModule",{value:!0});Jc.NatsConnectionImpl=void 0;var f0=rt(),Bc=Nr(),d0=Ve(),Kc=ys(),h0=gs(),l0=Ir(),Hc=ds(),zc=wi(),Gc=Et(),Ie=Je(),p0=/[ \n\r\t]/;class vi{options;protocol;draining;closeListeners;constructor(e){this.draining=!1,this.options=(0,l0.parseOptions)(e)}static connect(e={}){return new Promise((t,r)=>{let s=new vi(e);Bc.ProtocolHandler.connect(s.options,s).then((n)=>{s.protocol=n,t(s)}).catch((n)=>{r(n)})})}closed(){return this.protocol.closed}async close(){await this.protocol.close()}_check(e,t,r){if(this.isClosed())throw new Ie.errors.ClosedConnectionError;if(t&&this.isDraining())throw new Ie.errors.DrainingConnectionError;if(r&&this.protocol.noMorePublishing)throw new Ie.errors.DrainingConnectionError;if(e=e||"",e.length===0||p0.test(e))throw new Ie.errors.InvalidSubjectError(e)}publish(e,t,r){if(this._check(e,!1,!0),r?.reply)this._check(r.reply,!1,!0);if(typeof r?.traceOnly==="boolean"){let s=r.headers||(0,Kc.headers)();s.set("Nats-Trace-Only","true"),r.headers=s}if(typeof r?.traceDestination==="string"){let s=r.headers||(0,Kc.headers)();s.set("Nats-Trace-Dest",r.traceDestination),r.headers=s}this.protocol.publish(e,t,r)}publishMessage(e){return this.publish(e.subject,e.data,{reply:e.reply,headers:e.headers})}respondMessage(e){if(e.reply)return this.publish(e.reply,e.data,{reply:e.reply,headers:e.headers}),!0;return!1}subscribe(e,t={}){this._check(e,!0,!1);let r=new Bc.SubscriptionImpl(this.protocol,e,t);if(typeof t.callback!=="function"&&typeof t.slow==="number")r.setSlowNotificationFn(t.slow,(s)=>{this.protocol.dispatchStatus({type:"slowConsumer",sub:r,pending:s})});return this.protocol.subscribe(r),r}_resub(e,t,r){this._check(t,!0,!1);let s=e;if(s.max=r,r)s.max=r+s.received;this.protocol.resub(s,t)}requestMany(e,t=d0.Empty,r={maxWait:1000,maxMessages:-1}){let s=!this.protocol.options.noAsyncTraces;try{this._check(e,!0,!0)}catch(h){return Promise.reject(h)}if(r.strategy=r.strategy||"timer",r.maxWait=r.maxWait||1000,r.maxWait<1)return Promise.reject(Ie.InvalidArgumentError.format("timeout","must be greater than 0"));let n=new Hc.QueuedIteratorImpl;function o(h){n.push(()=>{n.stop(h)})}function c(h,p){if(h||p===null)o(h===null?void 0:h);else n.push(p)}if(r.noMux){let h=s?Error().stack:null,p=typeof r.maxMessages==="number"&&r.maxMessages>0?r.maxMessages:-1,w=this.subscribe((0,Gc.createInbox)(this.options.inboxPrefix),{callback:(be,vt)=>{if(vt?.data?.length===0&&vt?.headers?.status==="503")be=new Ie.errors.NoRespondersError(e);if(be){if(h)be.stack+=`
|
|
21
|
+
|
|
22
|
+
${h}`;A(be);return}if(c(null,vt),r.strategy==="count"){if(p--,p===0)A()}if(r.strategy==="stall")Pe(),N=setTimeout(()=>{A()},300);if(r.strategy==="sentinel"){if(vt&&vt.data.length===0)A()}}});w.requestSubject=e,w.closed.then(()=>{o()}).catch((be)=>{n.stop(be)});let A=(be)=>{if(be)n.push(()=>{throw be});Pe(),w.drain().then(()=>{o()}).catch((vt)=>{o()})};n.iterClosed.then(()=>{Pe(),w?.unsubscribe()}).catch((be)=>{Pe(),w?.unsubscribe()});let{headers:j,traceDestination:O,traceOnly:K}=r;try{this.publish(e,t,{reply:w.getSubject(),headers:j,traceDestination:O,traceOnly:K})}catch(be){A(be)}let N=setTimeout(()=>{A()},r.maxWait),Pe=()=>{if(N)clearTimeout(N)}}else{let h=r;h.callback=c,n.iterClosed.then(()=>{p.cancel()}).catch((O)=>{p.cancel(O)});let p=new zc.RequestMany(this.protocol.muxSubscriptions,e,h);this.protocol.request(p);let{headers:w,traceDestination:A,traceOnly:j}=r;try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${p.token}`,headers:w,traceDestination:A,traceOnly:j})}catch(O){p.cancel(O)}}return Promise.resolve(n)}request(e,t,r={timeout:1000,noMux:!1}){try{this._check(e,!0,!0)}catch(n){return Promise.reject(n)}let s=!this.protocol.options.noAsyncTraces;if(r.timeout=r.timeout||1000,r.timeout<1)return Promise.reject(Ie.InvalidArgumentError.format("timeout","must be greater than 0"));if(!r.noMux&&r.reply)return Promise.reject(Ie.InvalidArgumentError.format(["reply","noMux"],"are mutually exclusive"));if(r.noMux){let n=r.reply?r.reply:(0,Gc.createInbox)(this.options.inboxPrefix),o=(0,f0.deferred)(),c=s?new Ie.errors.RequestError(""):null,h=this.subscribe(n,{max:1,timeout:r.timeout,callback:(p,w)=>{if(w&&w.data?.length===0&&w.headers?.code===503)p=new Ie.errors.NoRespondersError(e);if(p){if(!(p instanceof Ie.TimeoutError))if(c)c.message=p.message,c.cause=p,p=c;else p=new Ie.errors.RequestError(p.message,{cause:p});o.reject(p),h.unsubscribe()}else o.resolve(w)}});return h.requestSubject=e,this.protocol.publish(e,t,{reply:n,headers:r.headers}),o}else{let n=new zc.RequestOne(this.protocol.muxSubscriptions,e,r,s);this.protocol.request(n);let{headers:o,traceDestination:c,traceOnly:h}=r;try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${n.token}`,headers:o,traceDestination:c,traceOnly:h})}catch(w){n.cancel(w)}let p=Promise.race([n.timer,n.deferred]);return p.catch(()=>{n.cancel()}),p}}flush(){if(this.isClosed())return Promise.reject(new Ie.errors.ClosedConnectionError);return this.protocol.flush()}drain(){if(this.isClosed())return Promise.reject(new Ie.errors.ClosedConnectionError);if(this.isDraining())return Promise.reject(new Ie.errors.DrainingConnectionError);return this.draining=!0,this.protocol.drain()}async[Symbol.asyncDispose](){if(this.isClosed())return;if(this.isDraining()){await this.closed();return}await this.drain()}isClosed(){return this.protocol.isClosed()}isDraining(){return this.draining}getServer(){let e=this.protocol.getServer();return e?e.listen:""}setServers(e){this.protocol.servers.setServers(e)}getServers(){return this.protocol.servers.snapshot()}status(){let e=new Hc.QueuedIteratorImpl;return e.iterClosed.then(()=>{let t=this.protocol.listeners.indexOf(e);if(t>-1)this.protocol.listeners.splice(t,1)}),this.protocol.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,r)=>{if(t==="time")return new Date(Date.parse(r));return r})}stats(){return{inBytes:this.protocol.inBytes,outBytes:this.protocol.outBytes,inMsgs:this.protocol.inMsgs,outMsgs:this.protocol.outMsgs}}getServerVersion(){let e=this.info;return e?(0,h0.parseSemVer)(e.version):void 0}async rtt(){if(this.isClosed())throw new Ie.errors.ClosedConnectionError;if(!this.protocol.connected)throw new Ie.errors.RequestError("connection disconnected");let e=Date.now();return await this.flush(),Date.now()-e}get features(){return this.protocol.features}reconnect(){if(this.isClosed())return Promise.reject(new Ie.errors.ClosedConnectionError);if(this.isDraining())return Promise.reject(new Ie.errors.DrainingConnectionError);return this.protocol.reconnect()}addCloseListener(e){if(this.closeListeners===void 0)this.closeListeners=new Vc(this.closed());this.closeListeners.add(e)}removeCloseListener(e){if(this.closeListeners)this.closeListeners.remove(e)}}Jc.NatsConnectionImpl=vi;class Vc{listeners;constructor(e){this.listeners=[],e.then((t)=>{this.notify(t)})}add(e){this.listeners.push(e)}remove(e){this.listeners=this.listeners.filter((t)=>t!==e)}notify(e){this.listeners.forEach((t)=>{if(typeof t.connectionClosedCallback==="function")try{t.connectionClosedCallback(e)}catch(r){}}),this.listeners=[]}}});var Si=H(function(Ei){Object.defineProperty(Ei,"__esModule",{value:!0});Ei.Empty=void 0;var y0=Ve();Object.defineProperty(Ei,"Empty",{enumerable:!0,get:function(){return y0.Empty}})});var tu=H(function(Qc){Object.defineProperty(Qc,"__esModule",{value:!0});Qc.Bench=Qc.Metric=void 0;Qc.throughput=Xc;Qc.msgThroughput=x0;Qc.humanizeBytes=Zc;var m0=Si(),g0=cs(),Ai=rt();class Ot{name;duration;date;payload;msgs;lang;version;bytes;asyncRequests;min;max;constructor(e,t){this.name=e,this.duration=t,this.date=Date.now(),this.payload=0,this.msgs=0,this.bytes=0}toString(){let e=this.duration/1000,t=Math.round(this.msgs/e),r=this.asyncRequests?"asyncRequests":"",s="";if(this.max)s=`${this.min}/${this.max}`;return`${this.name}${r?" [asyncRequests]":""} ${w0(t)} msgs/sec - [${e.toFixed(2)} secs] ~ ${Xc(this.bytes,e)} ${s}`}toCsv(){return`"${this.name}",${new Date(this.date).toISOString()},${this.lang},${this.version},${this.msgs},${this.payload},${this.bytes},${this.duration},${this.asyncRequests?this.asyncRequests:!1}
|
|
23
|
+
`}static header(){return`Test,Date,Lang,Version,Count,MsgPayload,Bytes,Millis,Async
|
|
24
|
+
`}}Qc.Metric=Ot;class Yc{nc;callbacks;msgs;size;subject;asyncRequests;pub;sub;req;rep;perf;payload;constructor(e,t={msgs:1e5,size:128,subject:"",asyncRequests:!1,pub:!1,sub:!1,req:!1,rep:!1}){if(this.nc=e,this.callbacks=t.callbacks||!1,this.msgs=t.msgs||0,this.size=t.size||0,this.subject=t.subject||g0.nuid.next(),this.asyncRequests=t.asyncRequests||!1,this.pub=t.pub||!1,this.sub=t.sub||!1,this.req=t.req||!1,this.rep=t.rep||!1,this.perf=new Ai.Perf,this.payload=this.size?new Uint8Array(this.size):m0.Empty,!this.pub&&!this.sub&&!this.req&&!this.rep)throw Error("no options selected")}async run(){if(this.nc.closed().then((e)=>{if(e)throw e}),this.callbacks)await this.runCallbacks();else await this.runAsync();return this.processMetrics()}processMetrics(){let e=this.nc,{lang:t,version:r}=e.protocol.transport;if(this.pub&&this.sub)this.perf.measure("pubsub","pubStart","subStop");if(this.req&&this.rep)this.perf.measure("reqrep","reqStart","reqStop");let s=this.perf.getEntries(),n=s.find((O)=>O.name==="pubsub"),o=s.find((O)=>O.name==="reqrep"),c=s.find((O)=>O.name==="req"),h=s.find((O)=>O.name==="rep"),p=s.find((O)=>O.name==="pub"),w=s.find((O)=>O.name==="sub"),A=this.nc.stats(),j=[];if(n){let{name:O,duration:K}=n,N=new Ot(O,K);N.msgs=this.msgs*2,N.bytes=A.inBytes+A.outBytes,N.lang=t,N.version=r,N.payload=this.payload.length,j.push(N)}if(o){let{name:O,duration:K}=o,N=new Ot(O,K);N.msgs=this.msgs*2,N.bytes=A.inBytes+A.outBytes,N.lang=t,N.version=r,N.payload=this.payload.length,j.push(N)}if(p){let{name:O,duration:K}=p,N=new Ot(O,K);N.msgs=this.msgs,N.bytes=A.outBytes,N.lang=t,N.version=r,N.payload=this.payload.length,j.push(N)}if(w){let{name:O,duration:K}=w,N=new Ot(O,K);N.msgs=this.msgs,N.bytes=A.inBytes,N.lang=t,N.version=r,N.payload=this.payload.length,j.push(N)}if(h){let{name:O,duration:K}=h,N=new Ot(O,K);N.msgs=this.msgs,N.bytes=A.inBytes+A.outBytes,N.lang=t,N.version=r,N.payload=this.payload.length,j.push(N)}if(c){let{name:O,duration:K}=c,N=new Ot(O,K);N.msgs=this.msgs,N.bytes=A.inBytes+A.outBytes,N.lang=t,N.version=r,N.payload=this.payload.length,j.push(N)}return j}async runCallbacks(){let e=[];if(this.sub){let t=(0,Ai.deferred)();e.push(t);let r=0;this.nc.subscribe(this.subject,{max:this.msgs,callback:()=>{if(r++,r===1)this.perf.mark("subStart");if(r===this.msgs)this.perf.mark("subStop"),this.perf.measure("sub","subStart","subStop"),t.resolve()}})}if(this.rep){let t=(0,Ai.deferred)();e.push(t);let r=0;this.nc.subscribe(this.subject,{max:this.msgs,callback:(s,n)=>{if(n.respond(this.payload),r++,r===1)this.perf.mark("repStart");if(r===this.msgs)this.perf.mark("repStop"),this.perf.measure("rep","repStart","repStop"),t.resolve()}})}if(this.pub){let t=(async()=>{this.perf.mark("pubStart");for(let r=0;r<this.msgs;r++)this.nc.publish(this.subject,this.payload);await this.nc.flush(),this.perf.mark("pubStop"),this.perf.measure("pub","pubStart","pubStop")})();e.push(t)}if(this.req){let t=(async()=>{if(this.asyncRequests){this.perf.mark("reqStart");let r=[];for(let s=0;s<this.msgs;s++)r.push(this.nc.request(this.subject,this.payload,{timeout:20000}));await Promise.all(r),this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}else{this.perf.mark("reqStart");for(let r=0;r<this.msgs;r++)await this.nc.request(this.subject);this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}})();e.push(t)}await Promise.all(e)}async runAsync(){let e=[];if(this.rep){let t=!1,r=this.nc.subscribe(this.subject,{max:this.msgs}),s=(async()=>{for await(let n of r){if(!t)this.perf.mark("repStart"),t=!0;n.respond(this.payload)}await this.nc.flush(),this.perf.mark("repStop"),this.perf.measure("rep","repStart","repStop")})();e.push(s)}if(this.sub){let t=!1,r=this.nc.subscribe(this.subject,{max:this.msgs}),s=(async()=>{for await(let n of r)if(!t)this.perf.mark("subStart"),t=!0;this.perf.mark("subStop"),this.perf.measure("sub","subStart","subStop")})();e.push(s)}if(this.pub){let t=(async()=>{this.perf.mark("pubStart");for(let r=0;r<this.msgs;r++)this.nc.publish(this.subject,this.payload);await this.nc.flush(),this.perf.mark("pubStop"),this.perf.measure("pub","pubStart","pubStop")})();e.push(t)}if(this.req){let t=(async()=>{if(this.asyncRequests){this.perf.mark("reqStart");let r=[];for(let s=0;s<this.msgs;s++)r.push(this.nc.request(this.subject,this.payload,{timeout:20000}));await Promise.all(r),this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}else{this.perf.mark("reqStart");for(let r=0;r<this.msgs;r++)await this.nc.request(this.subject);this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}})();e.push(t)}await Promise.all(e)}}Qc.Bench=Yc;function Xc(e,t){return`${Zc(e/t)}/sec`}function x0(e,t){return`${Math.floor(e/t)} msgs/sec`}function Zc(e,t=!1){let r=t?1000:1024,s=t?["k","M","G","T","P","E"]:["K","M","G","T","P","E"],n=t?"iB":"B";if(e<r)return`${e.toFixed(2)} ${n}`;let o=parseInt(Math.log(e)/Math.log(r)+""),c=parseInt(o-1+"");return`${(e/Math.pow(r,o)).toFixed(2)} ${s[c]}${n}`}function w0(e){return e.toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}});var iu=H(function(su){Object.defineProperty(su,"__esModule",{value:!0});su.IdleHeartbeatMonitor=void 0;class ru{interval;maxOut;cancelAfter;timer;autoCancelTimer;last;missed;count;callback;constructor(e,t,r={maxOut:2}){this.interval=e,this.maxOut=r?.maxOut||2,this.cancelAfter=r?.cancelAfter||0,this.last=Date.now(),this.missed=0,this.count=0,this.callback=t,this._schedule()}cancel(){if(this.autoCancelTimer)clearTimeout(this.autoCancelTimer);if(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,r=2){this.interval=e,this.maxOut=r,this.cancelAfter=t,this.restart()}restart(){this.cancel(),this._schedule()}_schedule(){if(this.cancelAfter>0)this.autoCancelTimer=setTimeout(()=>{this.cancel()},this.cancelAfter);this.timer=setInterval(()=>{if(this.count++,Date.now()-this.last>this.interval)this.missed++;if(this.missed>=this.maxOut)try{if(this.callback(this.missed)===!0)this.cancel()}catch(e){console.log(e)}},this.interval)}}su.IdleHeartbeatMonitor=ru});var cu=H(function(ou){Object.defineProperty(ou,"__esModule",{value:!0});ou.version=void 0;ou.version="3.4.0"});var pu=H(function(hu){Object.defineProperty(hu,"__esModule",{value:!0});hu.WsTransport=void 0;hu.wsUrlParseFn=du;hu.wsconnect=C0;var mt=rt(),uu=qt(),A0=Ir(),O0=_r(),P0=Nr(),T0=_i(),j0=cu(),fu=Je(),I0=j0.version,N0="nats.ws";class Oi{version;lang;closeError;connected;done;socket;options;socketClosed;encrypted;peeked;yields;signal;closedNotification;constructor(){this.version=I0,this.lang=N0,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=(0,mt.deferred)(),this.closedNotification=(0,mt.deferred)()}async connect(e,t){let s=(0,mt.deferred)();this.options=t;let n=e.src;if(t.wsFactory){let{socket:o,encrypted:c}=await t.wsFactory(e.src,t);this.socket=o,this.encrypted=c}else this.encrypted=n.indexOf("wss://")===0,this.socket=new WebSocket(n);return this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{if(this.done)this._closed(Error("aborted"))},this.socket.onmessage=(o)=>{if(this.done)return;if(this.yields.push(new Uint8Array(o.data)),this.peeked){this.signal.resolve();return}let c=O0.DataBuffer.concat(...this.yields),h=(0,uu.extractProtocolMessage)(c);if(h!==""){let p=P0.INFO.exec(h);if(!p){if(t.debug)console.error("!!!",(0,mt.render)(c));s.reject(Error("unexpected response from server"));return}try{let w=JSON.parse(p[1]);(0,A0.checkOptions)(w,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),s.resolve()}catch(w){s.reject(w);return}}},this.socket.onclose=(o)=>{let c;if(!o.wasClean&&o.reason!=="")c=Error(o.reason);this._closed(c),this._cleanup()},this.socket.onerror=(o)=>{if(this.done)return;let c=o,h=new fu.errors.ConnectionError(c.message);s.reject(h),this._cleanup()},s}_cleanup(){if(this.socketClosed===!1)this.socketClosed=!0,this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.closedNotification.resolve(this.closeError)}disconnect(){this._closed(void 0,!0)}async _closed(e,t=!0){if(this.done){try{this.socket.close()}catch(r){}return}if(this.closeError=e,!e)while(!this.socketClosed&&this.socket.bufferedAmount>0)await(0,mt.delay)(100);this.done=!0;try{this.socket.close()}catch(r){}return this.closedNotification}get isClosed(){return this.done}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){while(!0){if(this.done)return;if(this.yields.length===0)await this.signal;let e=this.yields;this.yields=[];for(let t=0;t<e.length;t++){if(this.options.debug)console.info(`> ${(0,mt.render)(e[t])}`);yield e[t]}if(this.done)break;else if(this.yields.length===0)e.length=0,this.yields=e,this.signal=(0,mt.deferred)()}}isEncrypted(){return this.connected&&this.encrypted}send(e){if(this.done)return;try{if(this.socket.send(e.buffer),this.options.debug)console.info(`< ${(0,mt.render)(e)}`);return}catch(t){if(this.options.debug)console.error(`!!! ${(0,mt.render)(e)}: ${t}`)}}close(e){return this._closed(e,!1)}closed(){return this.closedNotification}discard(){this.socket?.close()}}hu.WsTransport=Oi;function du(e,t){if(!/^(.*:\/\/)(.*)/.test(e))if(typeof t==="boolean")e=`${t===!0?"https":"http"}://${e}`;else e=`https://${e}`;let s=new URL(e),n=s.protocol.toLowerCase();if(n==="ws:")t=!1;if(n==="wss:")t=!0;if(n!=="https:"&&n!=="http")e=e.replace(/^(.*:\/\/)(.*)/gm,"$2"),s=new URL(`http://${e}`);let o,c,h=s.hostname,p=s.pathname,w=s.search||"";switch(n){case"http:":case"ws:":case"nats:":c=s.port||"80",o="ws:";break;case"https:":case"wss:":case"tls:":c=s.port||"443",o="wss:";break;default:c=s.port||t===!0?"443":"80",o=t===!0?"wss:":"ws:";break}return`${o}//${h}:${c}${p}${w}`}function C0(e={}){return(0,uu.setTransportFactory)({defaultPort:443,urlParseFn:du,factory:()=>{if(e.tls)throw fu.InvalidArgumentError.format("tls","is not configurable on w3c websocket connections");return new Oi}}),T0.NatsConnectionImpl.connect(e)}});var kr=H(function(y){var R0=y&&y.__createBinding||(Object.create?function(e,t,r,s){if(s===void 0)s=r;var n=Object.getOwnPropertyDescriptor(t,r);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable))n={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,s,n)}:function(e,t,r,s){if(s===void 0)s=r;e[s]=t[r]}),q0=y&&y.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r))R0(t,e,r)};Object.defineProperty(y,"__esModule",{value:!0});y.Metric=y.Bench=y.writeAll=y.readAll=y.MAX_SIZE=y.DenoBuffer=y.State=y.Parser=y.Kind=y.describe=y.QueuedIteratorImpl=y.usernamePasswordAuthenticator=y.tokenAuthenticator=y.nkeyAuthenticator=y.jwtAuthenticator=y.credsAuthenticator=y.RequestOne=y.parseOptions=y.hasWsProtocol=y.defaultOptions=y.DEFAULT_MAX_RECONNECT_ATTEMPTS=y.checkUnsupportedOption=y.checkOptions=y.buildAuthenticator=y.DataBuffer=y.MuxSubscription=y.Heartbeat=y.MsgHdrsImpl=y.headers=y.canonicalMIMEHeaderKey=y.timeout=y.SimpleMutex=y.render=y.nanos=y.millis=y.extend=y.delay=y.deferred=y.deadline=y.collect=y.backoff=y.ProtocolHandler=y.INFO=y.Connect=y.setTransportFactory=y.getResolveFn=y.MsgImpl=y.nuid=y.Nuid=y.NatsConnectionImpl=void 0;y.UserAuthenticationExpiredError=y.TimeoutError=y.RequestError=y.ProtocolError=y.PermissionViolationError=y.NoRespondersError=y.InvalidSubjectError=y.InvalidOperationError=y.InvalidArgumentError=y.errors=y.DrainingConnectionError=y.ConnectionError=y.ClosedConnectionError=y.AuthorizationError=y.wsUrlParseFn=y.wsconnect=y.Servers=y.isIPV4OrHostname=y.IdleHeartbeatMonitor=y.Subscriptions=y.SubscriptionImpl=y.syncIterator=y.Match=y.createInbox=y.protoLen=y.extractProtocolMessage=y.Empty=y.parseSemVer=y.Features=y.Feature=y.compare=y.parseIP=y.isIP=y.ipV4=y.TE=y.TD=void 0;var $0=_i();Object.defineProperty(y,"NatsConnectionImpl",{enumerable:!0,get:function(){return $0.NatsConnectionImpl}});var yu=cs();Object.defineProperty(y,"Nuid",{enumerable:!0,get:function(){return yu.Nuid}});Object.defineProperty(y,"nuid",{enumerable:!0,get:function(){return yu.nuid}});var U0=ri();Object.defineProperty(y,"MsgImpl",{enumerable:!0,get:function(){return U0.MsgImpl}});var bu=qt();Object.defineProperty(y,"getResolveFn",{enumerable:!0,get:function(){return bu.getResolveFn}});Object.defineProperty(y,"setTransportFactory",{enumerable:!0,get:function(){return bu.setTransportFactory}});var Pi=Nr();Object.defineProperty(y,"Connect",{enumerable:!0,get:function(){return Pi.Connect}});Object.defineProperty(y,"INFO",{enumerable:!0,get:function(){return Pi.INFO}});Object.defineProperty(y,"ProtocolHandler",{enumerable:!0,get:function(){return Pi.ProtocolHandler}});var it=rt();Object.defineProperty(y,"backoff",{enumerable:!0,get:function(){return it.backoff}});Object.defineProperty(y,"collect",{enumerable:!0,get:function(){return it.collect}});Object.defineProperty(y,"deadline",{enumerable:!0,get:function(){return it.deadline}});Object.defineProperty(y,"deferred",{enumerable:!0,get:function(){return it.deferred}});Object.defineProperty(y,"delay",{enumerable:!0,get:function(){return it.delay}});Object.defineProperty(y,"extend",{enumerable:!0,get:function(){return it.extend}});Object.defineProperty(y,"millis",{enumerable:!0,get:function(){return it.millis}});Object.defineProperty(y,"nanos",{enumerable:!0,get:function(){return it.nanos}});Object.defineProperty(y,"render",{enumerable:!0,get:function(){return it.render}});Object.defineProperty(y,"SimpleMutex",{enumerable:!0,get:function(){return it.SimpleMutex}});Object.defineProperty(y,"timeout",{enumerable:!0,get:function(){return it.timeout}});var Ti=ys();Object.defineProperty(y,"canonicalMIMEHeaderKey",{enumerable:!0,get:function(){return Ti.canonicalMIMEHeaderKey}});Object.defineProperty(y,"headers",{enumerable:!0,get:function(){return Ti.headers}});Object.defineProperty(y,"MsgHdrsImpl",{enumerable:!0,get:function(){return Ti.MsgHdrsImpl}});var L0=Vn();Object.defineProperty(y,"Heartbeat",{enumerable:!0,get:function(){return L0.Heartbeat}});var D0=Gn();Object.defineProperty(y,"MuxSubscription",{enumerable:!0,get:function(){return D0.MuxSubscription}});var F0=_r();Object.defineProperty(y,"DataBuffer",{enumerable:!0,get:function(){return F0.DataBuffer}});var Bt=Ir();Object.defineProperty(y,"buildAuthenticator",{enumerable:!0,get:function(){return Bt.buildAuthenticator}});Object.defineProperty(y,"checkOptions",{enumerable:!0,get:function(){return Bt.checkOptions}});Object.defineProperty(y,"checkUnsupportedOption",{enumerable:!0,get:function(){return Bt.checkUnsupportedOption}});Object.defineProperty(y,"DEFAULT_MAX_RECONNECT_ATTEMPTS",{enumerable:!0,get:function(){return Bt.DEFAULT_MAX_RECONNECT_ATTEMPTS}});Object.defineProperty(y,"defaultOptions",{enumerable:!0,get:function(){return Bt.defaultOptions}});Object.defineProperty(y,"hasWsProtocol",{enumerable:!0,get:function(){return Bt.hasWsProtocol}});Object.defineProperty(y,"parseOptions",{enumerable:!0,get:function(){return Bt.parseOptions}});var B0=wi();Object.defineProperty(y,"RequestOne",{enumerable:!0,get:function(){return B0.RequestOne}});var Cr=hi();Object.defineProperty(y,"credsAuthenticator",{enumerable:!0,get:function(){return Cr.credsAuthenticator}});Object.defineProperty(y,"jwtAuthenticator",{enumerable:!0,get:function(){return Cr.jwtAuthenticator}});Object.defineProperty(y,"nkeyAuthenticator",{enumerable:!0,get:function(){return Cr.nkeyAuthenticator}});Object.defineProperty(y,"tokenAuthenticator",{enumerable:!0,get:function(){return Cr.tokenAuthenticator}});Object.defineProperty(y,"usernamePasswordAuthenticator",{enumerable:!0,get:function(){return Cr.usernamePasswordAuthenticator}});q0(fi(),y);var K0=ds();Object.defineProperty(y,"QueuedIteratorImpl",{enumerable:!0,get:function(){return K0.QueuedIteratorImpl}});var Ns=Qn();Object.defineProperty(y,"describe",{enumerable:!0,get:function(){return Ns.describe}});Object.defineProperty(y,"Kind",{enumerable:!0,get:function(){return Ns.Kind}});Object.defineProperty(y,"Parser",{enumerable:!0,get:function(){return Ns.Parser}});Object.defineProperty(y,"State",{enumerable:!0,get:function(){return Ns.State}});var Cs=Yn();Object.defineProperty(y,"DenoBuffer",{enumerable:!0,get:function(){return Cs.DenoBuffer}});Object.defineProperty(y,"MAX_SIZE",{enumerable:!0,get:function(){return Cs.MAX_SIZE}});Object.defineProperty(y,"readAll",{enumerable:!0,get:function(){return Cs.readAll}});Object.defineProperty(y,"writeAll",{enumerable:!0,get:function(){return Cs.writeAll}});var mu=tu();Object.defineProperty(y,"Bench",{enumerable:!0,get:function(){return mu.Bench}});Object.defineProperty(y,"Metric",{enumerable:!0,get:function(){return mu.Metric}});var gu=Ve();Object.defineProperty(y,"TD",{enumerable:!0,get:function(){return gu.TD}});Object.defineProperty(y,"TE",{enumerable:!0,get:function(){return gu.TE}});var ji=Un();Object.defineProperty(y,"ipV4",{enumerable:!0,get:function(){return ji.ipV4}});Object.defineProperty(y,"isIP",{enumerable:!0,get:function(){return ji.isIP}});Object.defineProperty(y,"parseIP",{enumerable:!0,get:function(){return ji.parseIP}});var ks=gs();Object.defineProperty(y,"compare",{enumerable:!0,get:function(){return ks.compare}});Object.defineProperty(y,"Feature",{enumerable:!0,get:function(){return ks.Feature}});Object.defineProperty(y,"Features",{enumerable:!0,get:function(){return ks.Features}});Object.defineProperty(y,"parseSemVer",{enumerable:!0,get:function(){return ks.parseSemVer}});var H0=Si();Object.defineProperty(y,"Empty",{enumerable:!0,get:function(){return H0.Empty}});var xu=qt();Object.defineProperty(y,"extractProtocolMessage",{enumerable:!0,get:function(){return xu.extractProtocolMessage}});Object.defineProperty(y,"protoLen",{enumerable:!0,get:function(){return xu.protoLen}});var Ii=Et();Object.defineProperty(y,"createInbox",{enumerable:!0,get:function(){return Ii.createInbox}});Object.defineProperty(y,"Match",{enumerable:!0,get:function(){return Ii.Match}});Object.defineProperty(y,"syncIterator",{enumerable:!0,get:function(){return Ii.syncIterator}});var wu=Nr();Object.defineProperty(y,"SubscriptionImpl",{enumerable:!0,get:function(){return wu.SubscriptionImpl}});Object.defineProperty(y,"Subscriptions",{enumerable:!0,get:function(){return wu.Subscriptions}});var z0=iu();Object.defineProperty(y,"IdleHeartbeatMonitor",{enumerable:!0,get:function(){return z0.IdleHeartbeatMonitor}});var vu=Hn();Object.defineProperty(y,"isIPV4OrHostname",{enumerable:!0,get:function(){return vu.isIPV4OrHostname}});Object.defineProperty(y,"Servers",{enumerable:!0,get:function(){return vu.Servers}});var _u=pu();Object.defineProperty(y,"wsconnect",{enumerable:!0,get:function(){return _u.wsconnect}});Object.defineProperty(y,"wsUrlParseFn",{enumerable:!0,get:function(){return _u.wsUrlParseFn}});var Ke=Je();Object.defineProperty(y,"AuthorizationError",{enumerable:!0,get:function(){return Ke.AuthorizationError}});Object.defineProperty(y,"ClosedConnectionError",{enumerable:!0,get:function(){return Ke.ClosedConnectionError}});Object.defineProperty(y,"ConnectionError",{enumerable:!0,get:function(){return Ke.ConnectionError}});Object.defineProperty(y,"DrainingConnectionError",{enumerable:!0,get:function(){return Ke.DrainingConnectionError}});Object.defineProperty(y,"errors",{enumerable:!0,get:function(){return Ke.errors}});Object.defineProperty(y,"InvalidArgumentError",{enumerable:!0,get:function(){return Ke.InvalidArgumentError}});Object.defineProperty(y,"InvalidOperationError",{enumerable:!0,get:function(){return Ke.InvalidOperationError}});Object.defineProperty(y,"InvalidSubjectError",{enumerable:!0,get:function(){return Ke.InvalidSubjectError}});Object.defineProperty(y,"NoRespondersError",{enumerable:!0,get:function(){return Ke.NoRespondersError}});Object.defineProperty(y,"PermissionViolationError",{enumerable:!0,get:function(){return Ke.PermissionViolationError}});Object.defineProperty(y,"ProtocolError",{enumerable:!0,get:function(){return Ke.ProtocolError}});Object.defineProperty(y,"RequestError",{enumerable:!0,get:function(){return Ke.RequestError}});Object.defineProperty(y,"TimeoutError",{enumerable:!0,get:function(){return Ke.TimeoutError}});Object.defineProperty(y,"UserAuthenticationExpiredError",{enumerable:!0,get:function(){return Ke.UserAuthenticationExpiredError}})});var Mr=H(function(Kt){var G0=Kt&&Kt.__createBinding||(Object.create?function(e,t,r,s){if(s===void 0)s=r;var n=Object.getOwnPropertyDescriptor(t,r);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable))n={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,s,n)}:function(e,t,r,s){if(s===void 0)s=r;e[s]=t[r]}),V0=Kt&&Kt.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r))G0(t,e,r)};Object.defineProperty(Kt,"__esModule",{value:!0});V0(kr(),Kt)});var Au=H(function(Eu){Object.defineProperty(Eu,"__esModule",{value:!0});Eu.version=void 0;Eu.version="3.4.0"});var Tu=H(function(dt){var J0=dt&&dt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(dt,"__esModule",{value:!0});dt.NodeTransport=dt.VERSION=void 0;dt.nodeResolveHost=ey;var xe=Mr(),W0=Rt("net"),Ni=Rt("tls"),Y0=Rt("path"),Ou=Rt("fs"),X0=J0(Rt("dns")),Z0=Au();dt.VERSION=Z0.version;var Q0="nats.js";class Pu{socket;version;lang;yields=[];signal=(0,xe.deferred)();closedNotification=(0,xe.deferred)();options;connected=!1;tlsName="";done=!1;closeError;constructor(){this.lang=Q0,this.version=dt.VERSION}async connect(e,t){this.tlsName=e.tlsName,this.options=t;let{tls:r}=this.options,{handshakeFirst:s}=r||{};try{if(s===!0)this.socket=await this.tlsFirst(e);else this.socket=await this.dial(e);if(this.done)this.socket?.destroy();let n=await this.peekInfo();(0,xe.checkOptions)(n,t);let{tls_required:o,tls_available:c}=n,h=c===!0&&t.tls!==null;if(!s&&(o||h))this.socket=await this.startTLS();if(this.done)this.socket?.destroy();if(o&&this.socket.encrypted!==!0)throw xe.errors.InvalidArgumentError.format("tls","is not available on this server");return this.connected=!0,this.setupHandlers(),this.signal.resolve(),Promise.resolve()}catch(n){let o=n;if(!o)o=new xe.errors.ConnectionError("error connecting - node provided an undefined error");let{code:c}=o,h=c==="ECONNREFUSED"?new xe.errors.ConnectionError("connection refused",{cause:o}):o;throw this.socket?.destroy(),h}}dial(e){let t=(0,xe.deferred)(),r,s=(0,W0.createConnection)(e.port,e.hostname,()=>{t.resolve(s),s.removeAllListeners()});return s.on("error",(n)=>{r=n}),s.on("close",()=>{s.removeAllListeners(),t.reject(r)}),s.setNoDelay(!0),t}get isClosed(){return this.done}close(e){return this._closed(e,!1)}peekInfo(){let e=(0,xe.deferred)(),t;return this.socket.on("data",(r)=>{this.yields.push(r);let s=xe.DataBuffer.concat(...this.yields),n=(0,xe.extractProtocolMessage)(s);if(n!=="")try{let o=xe.INFO.exec(n);if(!o)throw Error("unexpected response from server");let c=JSON.parse(o[1]);e.resolve(c)}catch(o){e.reject(o)}finally{this.socket.removeAllListeners()}}),this.socket.on("error",(r)=>{t=r}),this.socket.on("close",()=>{this.socket.removeAllListeners(),e.reject(t)}),e}loadFile(e){if(!e)return Promise.resolve();let t=(0,xe.deferred)();try{if(e=(0,Y0.resolve)(e),!(0,Ou.existsSync)(e))t.reject(Error(`${e} doesn't exist`));(0,Ou.readFile)(e,(r,s)=>{if(r)return t.reject(r);t.resolve(s)})}catch(r){t.reject(r)}return t}async loadClientCerts(){let e={},{certFile:t,cert:r,caFile:s,ca:n,keyFile:o,key:c}=this.options.tls;try{if(t){let h=await this.loadFile(t);if(h)e.cert=h}else if(r)e.cert=r;if(o){let h=await this.loadFile(o);if(h)e.key=h}else if(c)e.key=c;if(s){let h=await this.loadFile(s);if(h)e.ca=[h]}else if(n)e.ca=n;return Promise.resolve(e)}catch(h){return Promise.reject(h)}}async tlsFirst(e){let t,r={servername:this.tlsName,rejectUnauthorized:!0};if(this.socket)r.socket=this.socket;if(typeof this.options.tls==="object")try{let n=await this.loadClientCerts()||{};r=(0,xe.extend)(r,this.options.tls,n)}catch(n){return Promise.reject(new xe.errors.ConnectionError(n.message,{cause:n}))}let s=(0,xe.deferred)();try{let n=(0,Ni.connect)(e.port,e.hostname,r,()=>{n.removeAllListeners(),s.resolve(n)});n.on("error",(o)=>{t=o}),n.on("secureConnect",()=>{if(r.rejectUnauthorized===!1)return;if(!n.authorized)throw n.authorizationError}),n.on("close",()=>{s.reject(t),n.removeAllListeners()}),n.setNoDelay(!0)}catch(n){s.reject(new xe.errors.ConnectionError(n.message,{cause:n}))}return s}async startTLS(){let e,t={socket:this.socket,servername:this.tlsName,rejectUnauthorized:!0};if(typeof this.options.tls==="object")try{let s=await this.loadClientCerts()||{};t=(0,xe.extend)(t,this.options.tls,s)}catch(s){return Promise.reject(new xe.errors.ConnectionError(s.message,{cause:s}))}let r=(0,xe.deferred)();try{let s=(0,Ni.connect)(t,()=>{s.removeAllListeners(),r.resolve(s)});s.on("error",(n)=>{e=n}),s.on("secureConnect",()=>{if(t.rejectUnauthorized===!1)return;if(!s.authorized)throw s.authorizationError}),s.on("close",()=>{r.reject(e),s.removeAllListeners()})}catch(s){r.reject(new xe.errors.ConnectionError(s.message,{cause:s}))}return r}setupHandlers(){let e;this.socket.on("data",(t)=>(this.yields.push(t),this.signal.resolve())),this.socket.on("error",(t)=>{e=t}),this.socket.on("end",()=>{if(this.socket?.destroyed)return;this.socket?.write(new Uint8Array(0),()=>{this.socket?.end()})}),this.socket.on("close",()=>{this._closed(e,!1)})}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){while(!0){if(this.yields.length===0)await this.signal;let e=this.yields;this.yields=[];for(let t=0;t<e.length;t++){if(this.options.debug)console.info(`> ${(0,xe.render)(e[t])}`);yield e[t]}if(this.done)break;else if(this.yields.length===0)e.length=0,this.yields=e,this.signal=(0,xe.deferred)()}}discard(){if(this.done=!0,this.socket)try{this.socket.removeAllListeners(),this.socket.destroy()}catch{}}disconnect(){this._closed(void 0,!0).then().catch()}isEncrypted(){return this.socket instanceof Ni.TLSSocket}_send(e){if(this.isClosed||this.socket===void 0)return Promise.resolve();if(this.options.debug)console.info(`< ${(0,xe.render)(e)}`);let t=(0,xe.deferred)();try{this.socket.write(e,(r)=>{if(r){if(this.options.debug)console.error(`!!! ${(0,xe.render)(e)}: ${r}`);return t.reject(r)}return t.resolve()})}catch(r){if(this.options.debug)console.error(`!!! ${(0,xe.render)(e)}: ${r}`);t.reject(r)}return t}send(e){this._send(e).catch((r)=>{})}async _closed(e,t=!0){if(!this.connected)return;if(this.done){this.socket?.destroy();return}if(this.closeError=e,!e&&this.socket&&t)try{await this._send(new TextEncoder().encode(""))}catch(r){if(this.options.debug)console.log("transport close terminated with an error",r)}try{if(this.socket)this.socket.removeAllListeners(),this.socket?.destroy(),this.socket=void 0}catch(r){console.log(r)}this.done=!0,this.closedNotification.resolve(this.closeError)}closed(){return this.closedNotification}}dt.NodeTransport=Pu;function ey(e){let t=(0,xe.deferred)();return X0.default.lookup(e,{all:!0},(r,s)=>{if(r){t.reject(r);return}let n=[];for(let o of s)n.push(o.address);if(n.length===0)n.push(e);t.resolve(n)}),t}});var ku=H(function(Cu){Object.defineProperty(Cu,"__esModule",{value:!0});Cu.connect=ty;var ju=Tu(),Iu=Mr(),Nu=Mr();function ty(e={}){if((0,Nu.hasWsProtocol)(e))return Promise.reject(Nu.errors.InvalidArgumentError.format("servers","node client doesn't support websockets, use the 'wsconnect' function instead"));return(0,Iu.setTransportFactory)({factory:()=>new ju.NodeTransport,dnsResolveFn:ju.nodeResolveHost}),Iu.NatsConnectionImpl.connect(e)}});var oy=H(function(gt){var sy=gt&>.__createBinding||(Object.create?function(e,t,r,s){if(s===void 0)s=r;var n=Object.getOwnPropertyDescriptor(t,r);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable))n={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,s,n)}:function(e,t,r,s){if(s===void 0)s=r;e[s]=t[r]}),ny=gt&>.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r))sy(t,e,r)};Object.defineProperty(gt,"__esModule",{value:!0});gt.connect=void 0;var iy=ku();Object.defineProperty(gt,"connect",{enumerable:!0,get:function(){return iy.connect}});ny(Mr(),gt)});var Ci=H(function(te){Object.defineProperty(te,"__esModule",{value:!0});te.wsconnect=te.usernamePasswordAuthenticator=te.UserAuthenticationExpiredError=te.tokenAuthenticator=te.TimeoutError=te.syncIterator=te.RequestError=te.ProtocolError=te.PermissionViolationError=te.nuid=te.Nuid=te.NoRespondersError=te.nkeys=te.nkeyAuthenticator=te.nanos=te.MsgHdrsImpl=te.millis=te.Metric=te.Match=te.jwtAuthenticator=te.InvalidSubjectError=te.InvalidOperationError=te.InvalidArgumentError=te.headers=te.hasWsProtocol=te.errors=te.Empty=te.DrainingConnectionError=te.delay=te.deferred=te.deadline=te.credsAuthenticator=te.createInbox=te.ConnectionError=te.ClosedConnectionError=te.canonicalMIMEHeaderKey=te.buildAuthenticator=te.Bench=te.backoff=te.AuthorizationError=void 0;var ne=kr();Object.defineProperty(te,"AuthorizationError",{enumerable:!0,get:function(){return ne.AuthorizationError}});Object.defineProperty(te,"backoff",{enumerable:!0,get:function(){return ne.backoff}});Object.defineProperty(te,"Bench",{enumerable:!0,get:function(){return ne.Bench}});Object.defineProperty(te,"buildAuthenticator",{enumerable:!0,get:function(){return ne.buildAuthenticator}});Object.defineProperty(te,"canonicalMIMEHeaderKey",{enumerable:!0,get:function(){return ne.canonicalMIMEHeaderKey}});Object.defineProperty(te,"ClosedConnectionError",{enumerable:!0,get:function(){return ne.ClosedConnectionError}});Object.defineProperty(te,"ConnectionError",{enumerable:!0,get:function(){return ne.ConnectionError}});Object.defineProperty(te,"createInbox",{enumerable:!0,get:function(){return ne.createInbox}});Object.defineProperty(te,"credsAuthenticator",{enumerable:!0,get:function(){return ne.credsAuthenticator}});Object.defineProperty(te,"deadline",{enumerable:!0,get:function(){return ne.deadline}});Object.defineProperty(te,"deferred",{enumerable:!0,get:function(){return ne.deferred}});Object.defineProperty(te,"delay",{enumerable:!0,get:function(){return ne.delay}});Object.defineProperty(te,"DrainingConnectionError",{enumerable:!0,get:function(){return ne.DrainingConnectionError}});Object.defineProperty(te,"Empty",{enumerable:!0,get:function(){return ne.Empty}});Object.defineProperty(te,"errors",{enumerable:!0,get:function(){return ne.errors}});Object.defineProperty(te,"hasWsProtocol",{enumerable:!0,get:function(){return ne.hasWsProtocol}});Object.defineProperty(te,"headers",{enumerable:!0,get:function(){return ne.headers}});Object.defineProperty(te,"InvalidArgumentError",{enumerable:!0,get:function(){return ne.InvalidArgumentError}});Object.defineProperty(te,"InvalidOperationError",{enumerable:!0,get:function(){return ne.InvalidOperationError}});Object.defineProperty(te,"InvalidSubjectError",{enumerable:!0,get:function(){return ne.InvalidSubjectError}});Object.defineProperty(te,"jwtAuthenticator",{enumerable:!0,get:function(){return ne.jwtAuthenticator}});Object.defineProperty(te,"Match",{enumerable:!0,get:function(){return ne.Match}});Object.defineProperty(te,"Metric",{enumerable:!0,get:function(){return ne.Metric}});Object.defineProperty(te,"millis",{enumerable:!0,get:function(){return ne.millis}});Object.defineProperty(te,"MsgHdrsImpl",{enumerable:!0,get:function(){return ne.MsgHdrsImpl}});Object.defineProperty(te,"nanos",{enumerable:!0,get:function(){return ne.nanos}});Object.defineProperty(te,"nkeyAuthenticator",{enumerable:!0,get:function(){return ne.nkeyAuthenticator}});Object.defineProperty(te,"nkeys",{enumerable:!0,get:function(){return ne.nkeys}});Object.defineProperty(te,"NoRespondersError",{enumerable:!0,get:function(){return ne.NoRespondersError}});Object.defineProperty(te,"Nuid",{enumerable:!0,get:function(){return ne.Nuid}});Object.defineProperty(te,"nuid",{enumerable:!0,get:function(){return ne.nuid}});Object.defineProperty(te,"PermissionViolationError",{enumerable:!0,get:function(){return ne.PermissionViolationError}});Object.defineProperty(te,"ProtocolError",{enumerable:!0,get:function(){return ne.ProtocolError}});Object.defineProperty(te,"RequestError",{enumerable:!0,get:function(){return ne.RequestError}});Object.defineProperty(te,"syncIterator",{enumerable:!0,get:function(){return ne.syncIterator}});Object.defineProperty(te,"TimeoutError",{enumerable:!0,get:function(){return ne.TimeoutError}});Object.defineProperty(te,"tokenAuthenticator",{enumerable:!0,get:function(){return ne.tokenAuthenticator}});Object.defineProperty(te,"UserAuthenticationExpiredError",{enumerable:!0,get:function(){return ne.UserAuthenticationExpiredError}});Object.defineProperty(te,"usernamePasswordAuthenticator",{enumerable:!0,get:function(){return ne.usernamePasswordAuthenticator}});Object.defineProperty(te,"wsconnect",{enumerable:!0,get:function(){return ne.wsconnect}})});var Rs=H(function(Mu){Object.defineProperty(Mu,"__esModule",{value:!0});Mu.ServiceVerb=Mu.ServiceError=Mu.ServiceErrorCodeHeader=Mu.ServiceErrorHeader=Mu.ServiceResponseType=void 0;Mu.ServiceResponseType={STATS:"io.nats.micro.v1.stats_response",INFO:"io.nats.micro.v1.info_response",PING:"io.nats.micro.v1.ping_response"};Mu.ServiceErrorHeader="Nats-Service-Error";Mu.ServiceErrorCodeHeader="Nats-Service-Error-Code";class Ms extends Error{code;constructor(e,t){super(t);this.code=e}static isServiceError(e){return Ms.toServiceError(e)!==null}static toServiceError(e){let t=e?.headers?.get(Mu.ServiceErrorCodeHeader)||"";if(t!==""){let r=parseInt(t)||400,s=e?.headers?.get(Mu.ServiceErrorHeader)||"";return new Ms(r,s.length?s:t)}return null}}Mu.ServiceError=Ms;Mu.ServiceVerb={PING:"PING",STATS:"STATS",INFO:"INFO"}});var ki=H(function(Lu){Object.defineProperty(Lu,"__esModule",{value:!0});Lu.ServiceImpl=Lu.ServiceGroupImpl=Lu.ServiceMsgImpl=Lu.ServiceApiPrefix=void 0;var xt=kr(),Ye=Rs();function Rr(e,t=""){if(t==="")throw Error(`${e} name required`);let r=fy(t);if(r.length)throw Error(`invalid ${e} name - ${e} name ${r}`)}function fy(e=""){if(!e)throw Error("name required");let t=/^[-\w]+$/g;if(e.match(t)===null){for(let s of e.split(""))if(s.match(t)===null)return`cannot contain '${s}'`}return""}Lu.ServiceApiPrefix="$SRV";class qs{msg;constructor(e){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,r,s){return s=s||{},s.headers=s.headers||(0,xt.headers)(),s.headers?.set(Ye.ServiceErrorCodeHeader,`${e}`),s.headers?.set(Ye.ServiceErrorHeader,t),this.msg.respond(r,s)}json(e){return this.msg.json(e)}string(){return this.msg.string()}}Lu.ServiceMsgImpl=qs;class ir{subject;queue;srv;constructor(e,t="",r=""){if(t!=="")hy("service group",t);let s="";if(e instanceof $s)this.srv=e,s="";else if(e instanceof ir){let n=e;if(this.srv=n.srv,r===void 0)r=n.queue;s=n.subject}else throw Error("unknown ServiceGroup type");this.subject=this.calcSubject(s,t),this.queue=r}calcSubject(e,t=""){if(t==="")return e;return e!==""?`${e}.${t}`:t}addEndpoint(e="",t){t=t||{subject:e};let r=typeof t==="function"?{handler:t,subject:e}:t;Rr("endpoint",e);let{subject:s,handler:n,metadata:o,queue:c}=r;s=s||e,c=c||this.queue,dy("endpoint subject",s),s=this.calcSubject(this.subject,s);let h={name:e,subject:s,queue:c,handler:n,metadata:o};return this.srv._addEndpoint(h)}addGroup(e="",t){if(t===void 0)t=this.queue;return new ir(this,e,t)}}Lu.ServiceGroupImpl=ir;function dy(e,t){if(t==="")throw Error(`${e} cannot be empty`);if(t.indexOf(" ")!==-1)throw Error(`${e} cannot contain spaces: '${t}'`);let r=t.split(".");r.forEach((s,n)=>{if(s===">"&&n!==r.length-1)throw Error(`${e} cannot have internal '>': '${t}'`)})}function hy(e,t){if(t.indexOf(" ")!==-1)throw Error(`${e} cannot contain spaces: '${t}'`);t.split(".").forEach((s)=>{if(s===">")throw Error(`${e} name cannot contain internal '>': '${t}'`)})}class $s{nc;_id;config;handlers;internal;_stopped;_done;started;closeListener;static controlSubject(e,t="",r="",s){let n=s??Lu.ServiceApiPrefix;if(t===""&&r==="")return`${n}.${e}`;if(Rr("control subject name",t),r!=="")return Rr("control subject id",r),`${n}.${e}.${t}.${r}`;return`${n}.${e}.${t}`}constructor(e,t={name:"",version:""}){if(this.nc=e,this.config=Object.assign({},t),this.config.queue===void 0)this.config.queue="q";if(t.metadata=Object.freeze(t.metadata||{}),Rr("name",this.config.name),this.config.queue)Rr("queue",this.config.queue);(0,xt.parseSemVer)(this.config.version),this._id=xt.nuid.next(),this.internal=[],this._done=(0,xt.deferred)(),this._stopped=!1,this.handlers=[],this.started=new Date().toISOString(),this.reset(),this.closeListener={connectionClosedCallback:(r)=>{this.close(r).catch()}},this.nc.addCloseListener(this.closeListener)}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){let t=(0,xt.headers)();if(e instanceof Ye.ServiceError){let r=e;t.set(Ye.ServiceErrorHeader,r.message),t.set(Ye.ServiceErrorCodeHeader,`${r.code}`)}else t.set(Ye.ServiceErrorHeader,e.message),t.set(Ye.ServiceErrorCodeHeader,"500");return t}setupHandler(e,t=!1){let r=t?"":e.queue?e.queue:this.config.queue,{name:s,subject:n,handler:o}=e,c=e;if(c.internal=t,t)this.internal.push(c);c.stats=new Uu(s,n,r),c.queue=r;let h=o?(p,w)=>{if(p){this.close(p);return}let A=Date.now();try{o(p,new qs(w))}catch(j){c.stats.countError(j),w?.respond(xt.Empty,{headers:this.errorToHeader(j)})}finally{c.stats.countLatency(A)}}:void 0;return c.sub=this.nc.subscribe(n,{callback:h,queue:r}),c.sub.closed.then(()=>{if(!this._stopped)this.close(Error(`required subscription ${e.subject} stopped`)).catch()}).catch((p)=>{if(!this._stopped){let w=Error(`required subscription ${e.subject} errored: ${p.message}`);w.stack=p.stack,this.close(w).catch()}}),c}info(){return{type:Ye.ServiceResponseType.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)=>{let{subject:t,metadata:r,name:s,queue:n}=e;return{subject:t,metadata:r,name:s,queue_group:n}})}async stats(){let e=[];for(let t of this.handlers){if(typeof this.config.statsHandler==="function")try{t.stats.data=await this.config.statsHandler(t)}catch(r){t.stats.countError(r)}e.push(t.stats.stats(t.qi))}return{type:Ye.ServiceResponseType.STATS,name:this.name,id:this.id,version:this.version,started:this.started,metadata:this.metadata,endpoints:e}}addInternalHandler(e,t){let r=`${e}`.toUpperCase();this._doAddInternalHandler(`${r}-all`,e,t),this._doAddInternalHandler(`${r}-kind`,e,t,this.name),this._doAddInternalHandler(`${r}`,e,t,this.name,this.id)}_doAddInternalHandler(e,t,r,s="",n=""){let o={};o.name=e,o.subject=$s.controlSubject(t,s,n),o.handler=r,this.setupHandler(o,!0)}start(){let e=(n,o)=>{if(n)return this.close(n),Promise.reject(n);return this.stats().then((c)=>(o?.respond(JSON.stringify(c)),Promise.resolve()))},t=(n,o)=>{if(n)return this.close(n),Promise.reject(n);return o?.respond(JSON.stringify(this.info())),Promise.resolve()},r=JSON.stringify(this.ping()),s=(n,o)=>{if(n)return this.close(n).then().catch(),Promise.reject(n);return o.respond(r),Promise.resolve()};return this.addInternalHandler(Ye.ServiceVerb.PING,s),this.addInternalHandler(Ye.ServiceVerb.STATS,e),this.addInternalHandler(Ye.ServiceVerb.INFO,t),this.handlers.forEach((n)=>{let{subject:o}=n;if(typeof o!=="string")return;if(n.handler===null)return;this.setupHandler(n)}),Promise.resolve(this)}close(e){if(this._stopped)return this._done;this._stopped=!0,this.nc.removeCloseListener(this.closeListener);let t=[];if(!this.nc.isClosed())t=this.handlers.concat(this.internal).map((r)=>r.sub.drain());return Promise.allSettled(t).then(()=>{this._done.resolve(e?e:null)}),this._done}get stopped(){return this._done}get isStopped(){return this._stopped}stop(e){return this.close(e)}ping(){return{type:Ye.ServiceResponseType.PING,name:this.name,id:this.id,version:this.version,metadata:this.metadata}}reset(){if(this.started=new Date().toISOString(),this.handlers)for(let e of this.handlers)e.stats.reset(e.qi)}addGroup(e,t){return new ir(this,e,t)}addEndpoint(e,t){return new ir(this).addEndpoint(e,t)}_addEndpoint(e){let t=new xt.QueuedIteratorImpl;if(t.profile=!0,t.noIterator=typeof e.handler==="function",!t.noIterator)e.handler=(s,n)=>{s?this.stop(s).catch():t.push(new qs(n))},t.iterClosed.then(()=>{this.close().catch()});let r=this.setupHandler(e,!1);return r.sub.closed.then((s)=>{s?this.stop(s):t.stop()}),r.qi=t,this.handlers.push(r),t}}Lu.ServiceImpl=$s;class Uu{name;subject;average_processing_time;num_requests;processing_time;num_errors;last_error;data;metadata;queue;constructor(e,t,r=""){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=r}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;let t=e;if(t)t.time=0,t.processed=0}countLatency(e){this.num_requests++,this.processing_time+=(0,xt.nanos)(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(){let{name:e,subject:t,average_processing_time:r,num_errors:s,num_requests:n,processing_time:o,last_error:c,data:h,queue:p}=this;return{name:e,subject:t,average_processing_time:r,num_errors:s,num_requests:n,processing_time:o,last_error:c,data:h,queue_group:p}}stats(e){let t=e;if(t?.noIterator===!1)this.processing_time=(0,xt.nanos)(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;return this._stats()}}});var Gu=H(function(Hu){Object.defineProperty(Hu,"__esModule",{value:!0});Hu.ServiceClientImpl=void 0;var Bu=kr(),yy=ki(),Mi=Rs();class Ku{nc;prefix;opts;constructor(e,t={strategy:"stall",maxWait:2000},r){this.nc=e,this.prefix=r,this.opts=t}ping(e="",t=""){return this.q(Mi.ServiceVerb.PING,e,t)}stats(e="",t=""){return this.q(Mi.ServiceVerb.STATS,e,t)}info(e="",t=""){return this.q(Mi.ServiceVerb.INFO,e,t)}async q(e,t="",r=""){let s=new Bu.QueuedIteratorImpl,n=yy.ServiceImpl.controlSubject(e,t,r,this.prefix),o=await this.nc.requestMany(n,Bu.Empty,this.opts);return(async()=>{for await(let c of o)try{let h=c.json();s.push(h)}catch(h){s.push(()=>{s.stop(h)})}s.push(()=>{s.stop()})})().catch((c)=>{s.stop(c)}),s}}Hu.ServiceClientImpl=Ku});var Wu=H(function(Ht){Object.defineProperty(Ht,"__esModule",{value:!0});Ht.Svcm=Ht.ServiceVerb=Ht.ServiceResponseType=Ht.ServiceErrorHeader=Ht.ServiceErrorCodeHeader=Ht.ServiceError=void 0;var by=ki(),my=Gu(),qr=Rs();Object.defineProperty(Ht,"ServiceError",{enumerable:!0,get:function(){return qr.ServiceError}});Object.defineProperty(Ht,"ServiceErrorCodeHeader",{enumerable:!0,get:function(){return qr.ServiceErrorCodeHeader}});Object.defineProperty(Ht,"ServiceErrorHeader",{enumerable:!0,get:function(){return qr.ServiceErrorHeader}});Object.defineProperty(Ht,"ServiceResponseType",{enumerable:!0,get:function(){return qr.ServiceResponseType}});Object.defineProperty(Ht,"ServiceVerb",{enumerable:!0,get:function(){return qr.ServiceVerb}});class Vu{nc;constructor(e){this.nc=e}add(e){try{return new by.ServiceImpl(this.nc,e).start()}catch(t){return Promise.reject(t)}}client(e,t){return new my.ServiceClientImpl(this.nc,e,t)}}Ht.Svcm=Vu});var Ri=H(function(Pt){Object.defineProperty(Pt,"__esModule",{value:!0});Pt.Svcm=Pt.ServiceVerb=Pt.ServiceResponseType=Pt.ServiceErrorHeader=Pt.ServiceErrorCodeHeader=Pt.ServiceError=void 0;var or=Wu();Object.defineProperty(Pt,"ServiceError",{enumerable:!0,get:function(){return or.ServiceError}});Object.defineProperty(Pt,"ServiceErrorCodeHeader",{enumerable:!0,get:function(){return or.ServiceErrorCodeHeader}});Object.defineProperty(Pt,"ServiceErrorHeader",{enumerable:!0,get:function(){return or.ServiceErrorHeader}});Object.defineProperty(Pt,"ServiceResponseType",{enumerable:!0,get:function(){return or.ServiceResponseType}});Object.defineProperty(Pt,"ServiceVerb",{enumerable:!0,get:function(){return or.ServiceVerb}});Object.defineProperty(Pt,"Svcm",{enumerable:!0,get:function(){return or.Svcm}})});var oe=wr(Ci(),1),Ji=wr(Ri(),1),fr=wr(ui(),1);import{AsyncResource as Yu,AsyncLocalStorage as xy}from"async_hooks";import{readFile as Fr,mkdir as bf,open as wy,unlink as vy,rm as _y,realpath as Xu,stat as Ey,mkdtemp as Sy}from"fs/promises";import{homedir as Ki,tmpdir as Ay}from"os";import{join as wt,basename as Oy,resolve as Bs,sep as Zu}from"path";import{fileURLToPath as Py}from"url";import{randomBytes as Ty}from"crypto";var ct=class extends Error{constructor(e,t){super(e,t);this.name="NatsAgentError"}},Wi=class extends ct{constructor(e,t){super(e,t);this.name="ValidationError"}},jy=class extends Wi{constructor(){super("prompt must be non-empty (spec \xA75.1)");this.name="PromptEmptyError"}},Iy=class extends Wi{constructor(){super("this agent's prompt endpoint does not accept attachments (attachments_ok=false, spec \xA75.4)");this.name="AttachmentsNotSupportedError"}},Ny=class extends Wi{constructor(e,t,r=0){super(r>0?`payload size ${t} bytes plus Agent-Sender header ${r} bytes exceeds endpoint max_payload of ${e} bytes (spec \xA75.4)`:`payload size ${t} bytes exceeds endpoint max_payload of ${e} bytes (spec \xA75.4)`);this.limit=e,this.actual=t,this.headerBytes=r,this.name="PayloadTooLargeError"}limit;actual;headerBytes},mf=class extends ct{constructor(e,t,r){super(`service error ${e}: ${t}`);this.code=e,this.description=t,this.body=r,this.name="ServiceError"}code;description;body},gf=class extends ct{constructor(e){super(`stream stalled: no chunk received within ${e}ms (spec \xA76.6)`);this.timeoutMs=e,this.name="StreamStalledError"}timeoutMs},xf=class extends ct{constructor(e){super(`stream exceeded maxWait of ${e}ms without terminator`);this.maxWaitMs=e,this.name="StreamMaxWaitExceededError"}maxWaitMs},pe=class extends ct{constructor(e,t){super(e,t);this.name="ProtocolError"}},Ne=class extends ct{constructor(e,t){super(e,t);this.name="NatsContextError"}},ye=class extends ct{constructor(e,t){super(e,t);this.name="IdentityError"}},ar=class extends ye{constructor(e){super(`this connection has no NKEY identity (${e}); configure an nkey user on the server and connect with its seed, or connect with a credentials file`);this.name="NoIdentityError"}},Qe=class extends ye{constructor(e,t){super(`identity unavailable: ${e}`,t);this.name="IdentityUnavailableError"}},ur=class extends ye{constructor(e,t,r,s,n){super(n!==void 0?`identity mismatch: the configured signer holds ${e} but its credentials JWT names user ${n}`:r!==void 0&&s!==void 0?`identity mismatch: the configured signer represents ${r}.${e} but the live connection is ${s}.${t}`:`identity mismatch: the configured signer holds ${e} but the connection's user NKEY is ${t}`);this.signerPublicKey=e,this.identityUser=t,this.signerAccount=r,this.identityAccount=s,this.credentialUser=n,this.name="IdentityMismatchError"}signerPublicKey;identityUser;signerAccount;identityAccount;credentialUser},Tt=class extends ye{constructor(e){super(`invalid agent id: ${e}`);this.name="InvalidAgentIdError"}},qe=class extends ye{constructor(e){super(`malformed Agent-Sender header: ${e}`);this.name="MalformedSenderHeaderError"}},Gs=class extends ye{constructor(e){super(`${e} requires a signed Agent-Sender header (min_sender_trust=signed) but no identity.signer is configured`);this.subject=e,this.name="SenderSignatureRequiredError"}subject;code=401;description="signature required"},Yi=class extends ye{constructor(e,t,r){super(`sender verification failed (${e}): ${r}`);this.code=e,this.description=t,this.detail=r,this.name="SenderVerificationError"}code;description;detail},Cy=new Set(["agent","owner","session","instance_id","ts","interval_s"]);function ky(e){if(typeof e!=="object"||e===null||Array.isArray(e))return;let t={};for(let[r,s]of Object.entries(e)){if(typeof s!=="object"||s===null||Array.isArray(s))return;let n=s;if(typeof n.subject!=="string"||n.subject==="")return;let o=n.metadata??{};if(typeof o!=="object"||o===null||Array.isArray(o))return;let c={};for(let[h,p]of Object.entries(o)){if(typeof p!=="string")return;c[h]=p}t[r]=Object.freeze({subject:n.subject,metadata:Object.freeze(c)})}return Object.freeze(t)}function wf(e){if(typeof e!=="object"||e===null||Array.isArray(e))return null;let t=e;if(typeof t.agent!=="string"||typeof t.owner!=="string"||typeof t.instance_id!=="string"||typeof t.ts!=="string"||typeof t.interval_s!=="number"||!Number.isFinite(t.interval_s)||t.interval_s<=0)return null;let r=typeof t.protocol_version==="string"&&t.protocol_version!==""?t.protocol_version:void 0,s=ky(t.endpoints),n={};for(let[c,h]of Object.entries(t)){if(Cy.has(c))continue;if(c==="protocol_version"&&r!==void 0)continue;if(c==="endpoints"&&s!==void 0)continue;n[c]=h}let o=typeof t.session==="string"&&t.session!==""?t.session:void 0;return Object.freeze({agent:t.agent,owner:t.owner,instanceId:t.instance_id,ts:t.ts,intervalS:t.interval_s,extras:Object.freeze(n),...o!==void 0?{session:o}:{},...r!==void 0?{protocolVersion:r}:{},...s!==void 0?{endpoints:s}:{}})}var My=/^\s*(\d+)\s*(B|KB|MB|GB)\s*$/i,Ry=Object.freeze({B:1,KB:1024,MB:1048576,GB:1073741824}),cr=class extends Error{constructor(e,t){super(`invalid size "${e}": ${t}`);this.input=e,this.name="InvalidSizeError"}input};function Xi(e){let t=My.exec(e);if(!t||t[1]===void 0||t[2]===void 0)throw new cr(e,"expected e.g. '1MB', '512KB', '4GB'");let r=Number(t[1]);if(!Number.isFinite(r)||r<0)throw new cr(e,"non-finite or negative");let s=t[2].toUpperCase(),n=Ry[s];if(n===void 0)throw new cr(e,`unknown unit "${s}"`);let o=r*n;if(!Number.isSafeInteger(o))throw new cr(e,"overflows safe integer range");return o}var qy=[["GB",1073741824],["MB",1048576],["KB",1024]];function Zi(e){if(!Number.isFinite(e)||e<0||!Number.isInteger(e))throw new cr(String(e),"byte count must be a non-negative integer");for(let[t,r]of qy)if(e>=r&&e%r===0)return`${e/r}${t}`;return`${e}B`}var $y=new TextEncoder;function Ws(e){return $y.encode(e).length}var Uy=/^(A[A-Z2-7]{55}|[A-Za-z0-9_-]+|\$G)\.U[A-Z2-7]{55}$/,vf=/^U[A-Z2-7]{55}$/,Ly=/^([A-Za-z0-9_-]+|\$G)$/,Dy=56,Hi=64;function Fy(e){return vf.test(e)}function By(e){return e.length===Dy&&e.startsWith("A")}function _f(e,t){try{fr.fromPublic(t)}catch(r){let s=r instanceof Error?r.message:String(r);throw new Tt(`${e} key fails the nkeys check (${s})`)}}function Ef(e){if(e.length===0)throw new Tt("empty user token");if(!vf.test(e))throw new Tt("user token is not a user public NKEY (U + 55 base32 chars)");_f("user",e)}function Sf(e){if(e.length===0)throw new Tt("empty account token");if(By(e)){_f("account",e);return}if(!Ly.test(e))throw new Tt("account token is neither an account public NKEY nor a subject-safe name ([A-Za-z0-9_-]+ or $G)")}function dr(e,t){return Sf(e),Ef(t),`${e}.${t}`}function Ky(e){if(e.length===0)throw new Tt("empty string");if(!Uy.test(e))throw new Tt("expected {account}.{user} with a U\u2026 user public NKEY");let t=e.indexOf(".");return dr(e.slice(0,t),e.slice(t+1))}function Lr(e){return e.slice(0,e.indexOf("."))}function ht(e){return e.slice(e.indexOf(".")+1)}async function Hy(e){let t=Jy(),r=e==="current"?await Wy(t):e;if(r.includes("/")||r.includes("\\")||r.includes("\x00")||r==="..")throw new Ne(`invalid context name: "${r}"`);let s=wt(t,"context",`${r}.json`),n;try{n=await Fr(s,"utf8")}catch(c){if(c.code==="ENOENT")throw new Ne(`NATS context "${r}" not found at ${s}`);throw c}let o;try{o=JSON.parse(n)}catch(c){throw new Ne(`NATS context "${r}" is not valid JSON: ${c.message}`)}if(typeof o!=="object"||o===null||Array.isArray(o))throw new Ne(`NATS context "${r}" is not a JSON object`);return{name:r,path:s,fields:o}}async function zy(e){let{name:t,fields:r}=await Hy(e),s=Ze(r.url);if(!s)throw new Ne(`NATS context "${t}" is missing \`url\``);let n=Af(s),o=n.user!==void 0||n.pass!==void 0?{kind:"user-password"}:n.token!==void 0?{kind:"token"}:{kind:"none"},c=Ze(r.creds),h=Ze(r.nkey),p=Ze(r.user_jwt),w=Ze(r.user_seed);if(c){Us(n);let O=await Vs("creds",Jt(c)),K=new Uint8Array(O.buffer,O.byteOffset,O.byteLength);n.authenticator=oe.credsAuthenticator(K),o={kind:"creds",bytes:K}}else if(h){Us(n);let O=await Vs("nkey",Jt(h)),K=new Uint8Array(O.buffer,O.byteOffset,O.byteLength);n.authenticator=oe.nkeyAuthenticator(K),o={kind:"nkey",bytes:K}}else if(p)if(Us(n),w){let O=new TextEncoder().encode(w);n.authenticator=oe.jwtAuthenticator(p,O),o={kind:"jwt-seed",jwt:p,seed:O}}else n.authenticator=oe.jwtAuthenticator(p),o={kind:"jwt"};else{let O=Ze(r.token),K=Ze(r.user),N=Ze(r.password);if(O||K||N){if(Us(n),O)n.token=O;if(K)n.user=K;if(N)n.pass=N;o=K||N?{kind:"user-password"}:{kind:"token"}}}try{let O=Ze(r.cert),K=Ze(r.key),N=Ze(r.ca),Pe=r.tls_first;if(O||K||N||Pe===!0){let be={};if(O)be.cert=await qi("cert",Jt(O));if(K)be.key=await qi("key",Jt(K));if(N)be.ca=await qi("ca",Jt(N));if(Pe===!0)be.handshakeFirst=!0;n.tls=be}}catch(O){throw Qu(o),O}let A=Ze(r.inbox_prefix);if(A)n.inboxPrefix=A;let j=!1;return{name:t,connectionOptions:n,auth:o,wipe(){if(j)return;j=!0,Qu(o)}}}function Us(e){delete e.token,delete e.user,delete e.pass}function Qu(e){if(e.kind==="creds"||e.kind==="nkey")e.bytes.fill(0);if(e.kind==="jwt-seed")e.seed.fill(0)}function Jt(e){return e.startsWith("~/")?wt(Ki(),e.slice(2)):e}async function qi(e,t){try{return await Fr(t,"utf8")}catch(r){throw new Ne(`failed to read TLS ${e} file ${t}`,{cause:r})}}async function Vs(e,t){try{return await Fr(t)}catch(r){throw new Ne(`failed to read ${e} file ${t}`,{cause:r})}}function Af(e){let t=e.split(",").map((o)=>o.trim()).filter((o)=>o.length>0);if(t.length===0)throw new Ne("empty NATS URL");let r=t.map((o)=>Gy(o,e)),s=r[0];for(let o of r.slice(1))if(o.token!==s.token||o.user!==s.user||o.pass!==s.pass)throw new Ne(`NATS URL has mixed credentials across server entries: ${Ks(e)}`);let n={servers:r.map((o)=>o.server)};if(s.token!==void 0)n.token=s.token;if(s.user!==void 0)n.user=s.user;if(s.pass!==void 0)n.pass=s.pass;return n}function Gy(e,t){let r=/^[a-z]+:\/\//i.test(e)?e:`nats://${e}`,s;try{s=new URL(r)}catch{throw new Ne(`invalid NATS URL ${Ks(t)}`)}if(!/^(nats|tls|ws|wss):$/.test(s.protocol))throw new Ne(`unsupported scheme "${s.protocol}" in NATS URL ${Ks(t)}`);if(!s.host)throw new Ne(`NATS URL ${Ks(t)} is missing a host`);let n=s.protocol==="ws:"||s.protocol==="wss:"?`${Vy(r)?s.pathname:""}${s.search}`:"",o={server:`${s.protocol}//${s.host}${n}`};if((r.match(/^[a-z]+:\/\/([^/@]*)@/i)?.[1]??"").includes(":"))o.user=decodeURIComponent(s.username),o.pass=decodeURIComponent(s.password);else if(s.username!=="")o.token=decodeURIComponent(s.username);return o}function Vy(e){let t=e.indexOf("://")+3;return/[/?]/.test(e.slice(t))}function Ks(e){return JSON.stringify(e.split(",").map((t)=>{let r=t.trim(),n=r.match(/^[a-z]+:\/\//i)?.[0]?.length??0,o=r.lastIndexOf("@");return o>=n?`${r.slice(0,n)}[redacted]@${r.slice(o+1)}`:r}).join(","))}function Ze(e){return typeof e==="string"&&e.length>0?e:void 0}function Jy(){let e=process.env.NATS_CONFIG_HOME;if(e)return e.startsWith("~/")?wt(Ki(),e.slice(2)):e;let t=process.env.XDG_CONFIG_HOME;if(t)return wt(t,"nats");return wt(Ki(),".config","nats")}async function Wy(e){let t=process.env.NATS_CONTEXT;if(t&&t.length>0)return t;let r=wt(e,"context.txt");try{let s=(await Fr(r,"utf8")).trim();if(s.length===0)throw new Ne(`no NATS context is selected (empty ${r})`);return s}catch(s){if(s.code==="ENOENT")throw new Ne(`no NATS context is selected ($NATS_CONTEXT unset, no ${r})`);throw s}}var ot="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Yy=/^[A-Za-z0-9_-]*$/,Xy=(()=>{let e=new Int8Array(128).fill(-1);for(let t=0;t<ot.length;t++)e[ot.charCodeAt(t)]=t;return e})();function Of(e){let t="",r=0;for(;r+3<=e.length;r+=3){let n=e[r],o=e[r+1],c=e[r+2];t+=ot[n>>2],t+=ot[(n&3)<<4|o>>4],t+=ot[(o&15)<<2|c>>6],t+=ot[c&63]}let s=e.length-r;if(s===1){let n=e[r];t+=ot[n>>2],t+=ot[(n&3)<<4]}else if(s===2){let n=e[r],o=e[r+1];t+=ot[n>>2],t+=ot[(n&3)<<4|o>>4],t+=ot[(o&15)<<2]}return t}function Ys(e){if(!Yy.test(e))throw Error("invalid base64url character");if(e.length%4===1)throw Error("invalid base64url length");let t=new Uint8Array(Math.floor(e.length*6/8)),r=0,s=0,n=0;for(let o=0;o<e.length;o++)if(r=r<<6|(Xy[e.charCodeAt(o)]??0),s+=6,s>=8)s-=8,t[n++]=r>>s&255;return t}async function Zy(e){return new Uint8Array(await crypto.subtle.digest("SHA-256",e))}async function Pf(e){return Qy(await Zy(e))}function Qy(e){let t="";for(let r of e)t+=r.toString(16).padStart(2,"0");return t}var eb=256,zt=new Map;function tb(e){let t=zt.get(e);if(t)return zt.delete(e),zt.set(e,t),t;let r=fr.fromPublic(e);if(zt.set(e,r),zt.size>eb){let s=zt.keys().next().value;if(s!==void 0)zt.delete(s)}return r}function Tf(e,t,r){let s;try{s=tb(e)}catch{return!1}return s.verify(t,r)}var Dr={encode:(e)=>new TextEncoder().encode(e),decode:(e)=>new TextDecoder().decode(e)},rb=/^SU[A-Z2-7]{56}$/,sb=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/,nb=/^-+BEGIN NATS USER JWT-+$/,jf=/^-+BEGIN USER NKEY SEED-+$/,ib=class{#e;#t;publicKey;constructor(e,t){this.#e=e,this.publicKey=e.getPublicKey(),this.#t=t}get jwt(){return this.#t}sign(e){if(this.#e===null)throw new ye("signer has been wiped");return this.#e.sign(e)}wipe(){this.#e?.clear(),this.#e=null,this.#t=void 0}toJSON(){return{publicKey:this.publicKey}}[Symbol.for("nodejs.util.inspect.custom")](){return`SenderSigner(${this.publicKey})`}toString(){return`SenderSigner(${this.publicKey})`}};function Qi(e,t){try{return new ib(fr.fromSeed(e),t)}catch(r){throw e.fill(0),new ye(`invalid nkey seed (${r instanceof Error?r.message:String(r)})`)}}function eo(e){let t=typeof e==="string"?e:Dr.decode(e),r=t.includes("BEGIN")?zi(t,jf,"USER NKEY SEED"):t.trim();if(!rb.test(r))throw new ye("invalid nkey seed: expected a user seed (SU + 56 base32 characters)");let s=Dr.encode(r),n=s.slice(),o,c=!1;try{o=fr.fromSeed(n);let h=o.getPublicKey();if(!h.startsWith("U"))throw new ye(`seed is not a user seed (derives ${h.slice(0,1)}\u2026 public key)`);return c=!0,s}catch(h){if(h instanceof ye)throw h;throw new ye(`invalid nkey seed (${h instanceof Error?h.message:String(h)})`)}finally{if(o?.clear(),n.fill(0),!c)s.fill(0)}}function ob(e){let t=zi(e,nb,"NATS USER JWT");if(!sb.test(t))throw new ye("creds: the user JWT block is not a JWT");let r=zi(e,jf,"USER NKEY SEED");return{jwt:t,seed:r}}function zi(e,t,r){let s=e.split(/\r?\n/);for(let n=0;n<s.length;n++){if(!t.test(s[n].trim()))continue;for(let o=n+1;o<s.length;o++){let c=s[o].trim();if(c.length===0)continue;if(c.startsWith("-"))throw new ye(`creds: empty ${r} block at line ${n+1}`);return c}throw new ye(`creds: ${r} block at line ${n+1} has no content`)}throw new ye(`creds: no -----BEGIN ${r}----- block found`)}function ab(e){let t=e.split(".");if(t.length!==3)throw new ye("JWT does not have three parts");let r;try{r=JSON.parse(Dr.decode(Ys(t[1].replace(/=+$/,""))))}catch{throw new ye("JWT payload is not base64url-encoded JSON")}if(typeof r!=="object"||r===null||Array.isArray(r))throw new ye("JWT payload is not a JSON object");return r}function to(e){let t=ab(e),r=t.sub,s=t.iss,n=t.nats,o=typeof n==="object"&&n!==null&&!Array.isArray(n)?n.issuer_account:void 0,c=typeof o==="string"&&o.length>0?o:s;if(typeof r!=="string"||typeof c!=="string")throw new Qe("credentials JWT lacks a string `sub` or `iss`");try{return dr(c,r)}catch(h){throw new Qe(`credentials JWT does not carry a usable (account, user) pair: ${h instanceof Error?h.message:String(h)}`)}}function If(e){let{jwt:t,seed:r}=ob(e);return cb(r,t)}function cb(e,t){return Nf(eo(e),t)}function Nf(e,t){let r=Qi(e,t);try{let s=ht(to(t));if(s===r.publicKey)return r;throw new ur(r.publicKey,r.publicKey,void 0,void 0,s)}catch(s){throw r.wipe?.(),s}}var lt="$SYS.REQ.USER.INFO",ub=2000,fb=30000,Js=new WeakMap;function ro(e){let t=e.signer;if(!t)return"unsigned";if(t.jwt===void 0)return`signer:${t.publicKey}`;try{return`signer:${t.publicKey}:${to(t.jwt)}`}catch{return`signer:${t.publicKey}:invalid-jwt`}}function db(e){let t=Js.get(e);if(!t)t={sources:new Map,listening:!1},Js.set(e,t);if(!t.listening){t.listening=!0;let r=t;(async()=>{try{for await(let s of e.status())if(s.type==="reconnect")r.sources.clear()}catch{}})()}return t}function Cf(e,t){let r=db(e),s=ro(t),n=r.sources.get(s);if(!n)n={inflight:null,settled:null,failedAt:0},r.sources.set(s,n);return n}function so(e,t){return t-e.failedAt>=fb}function hb(e,t={}){let r=Js.get(e)?.sources.get(ro(t));if(!r?.settled)return;if("error"in r.settled&&so(r,Date.now()))return;return r.settled}function lb(e,t={}){let r=Js.get(e)?.sources.get(ro(t));return r?.settled!==null&&r?.settled!==void 0&&"error"in r.settled&&so(r,Date.now())}function hr(e,t={}){let r=Cf(e,t);if(r.settled){if("id"in r.settled)return Promise.resolve(r.settled.id);if(!so(r,Date.now()))return Promise.reject(r.settled.error)}return Mf(e,r,t)}function kf(e,t={}){let r=Cf(e,t);if(r.inflight)return r.inflight;return r.settled=null,r.failedAt=0,Mf(e,r,t)}function pb(e,t={}){Promise.resolve().then(()=>hr(e,t)).catch(()=>{})}function Mf(e,t,r){if(t.inflight)return t.inflight;let s=yb(e,r).then((n)=>(t.settled={id:n},t.failedAt=0,t.inflight=null,n),(n)=>{let o=n instanceof ye?n:new Qe(n instanceof Error?n.message:String(n),{cause:n});throw t.settled={error:o},t.failedAt=Date.now(),t.inflight=null,o});return t.inflight=s,s.catch(()=>{}),s}async function yb(e,t={}){let r=t.signer,s=await bb(e,t.timeoutMs??ub);if(r&&ht(s)!==r.publicKey)throw new ur(r.publicKey,ht(s));if(r?.jwt!==void 0){let n=to(r.jwt);if(ht(n)!==r.publicKey)throw new ur(r.publicKey,ht(s),void 0,void 0,ht(n));if(n!==s)throw new ur(r.publicKey,ht(s),Lr(n),Lr(s))}return s}async function bb(e,t){let r;try{r=(await e.request(lt,oe.Empty,{timeout:t})).data}catch(n){throw mb(n,t)}let s;try{s=JSON.parse(new TextDecoder().decode(r))}catch{throw new Qe(`${lt} reply is not JSON`)}return gb(s)}function mb(e,t){let r=e instanceof oe.RequestError?e.cause:e;if(r instanceof oe.PermissionViolationError)return new Qe(`publish to ${lt} is a permissions violation for this user`,{cause:e});if(r instanceof oe.NoRespondersError||e instanceof oe.RequestError&&e.isNoResponders())return new Qe(`no responder for ${lt} (server without the system responder?)`,{cause:e});if(r instanceof oe.TimeoutError||e instanceof oe.TimeoutError)return new Qe(`no reply from ${lt} within ${t} ms`,{cause:e});return new Qe(`${lt} request failed: ${e instanceof Error?e.message:String(e)}`,{cause:e})}function gb(e){if(typeof e!=="object"||e===null||Array.isArray(e))throw new Qe(`${lt} reply is not a JSON object`);let t=e;if(t.error!==void 0)throw new Qe(`${lt} answered with an error: ${JSON.stringify(t.error)}`);let r=t.data;if(typeof r!=="object"||r===null||Array.isArray(r))throw new Qe(`${lt} reply has no \`data\` object`);let s=r,n=s.user,o=s.account;if(typeof n!=="string"||typeof o!=="string")throw new Qe(`${lt} reply lacks string \`user\` / \`account\``);if(n.length===0)throw new ar("no authentication \u2014 the server reports an empty user");if(n==="[REDACTED]")throw new ar("token authentication \u2014 the server reports a redacted user");if(!Fy(n))throw new ar(`password authentication \u2014 the server reports the user name ${JSON.stringify(n)}, not an NKEY`);if(Ws(o)>Hi)throw new ar(`the account name is longer than ${Hi} bytes and cannot be carried by the agent-ID form`);try{Sf(o)}catch(c){throw new ar(`the account name ${JSON.stringify(o)} cannot be carried by the agent-ID form (${c instanceof Error?c.message:String(c)})`)}return dr(o,n)}var xb="Nats-Request-Info";function wb(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=="object"||t===null||Array.isArray(t))return null;let r=t,s=r.acc,n=r.user;if(s!==void 0&&typeof s!=="string")return null;if(n!==void 0&&typeof n!=="string")return null;return Object.freeze({...s!==void 0?{account:s}:{},...n!==void 0?{user:n}:{}})}function vb(e){if(!e)return;let t=e.values(xb);if(t.length===0)return;if(t.length>1)return null;return wb(t[0]??"")}var jt="Agent-Sender",Rf=1,_b="AGENT-SENDER-V1",ef=2048,tf=64,Eb=30000,Sb=28,Xs="sender rejected",no="signature required",Ab=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,qf=/^[A-Za-z0-9_-]{1,64}$/,Ob=/^[^\s.\x00-\x1f\x7f]+(\.[^\s.\x00-\x1f\x7f]+)*$/,Pb=64,$f=86,Uf=20,Tb=22,jb=64,Ib=56,Nb=Symbol.for("nodejs.util.inspect.custom");function io(e){for(let r of["nonce","sig"])if(e[r]!==void 0)Object.defineProperty(e,r,{value:e[r],enumerable:!1,configurable:!1,writable:!1});let t=()=>({v:e.v,account:e.account,user:e.user,...e.name!==void 0?{name:e.name}:{},...e.sub!==void 0?{sub:e.sub}:{},...e.ts!==void 0?{ts:e.ts}:{},...e.nonce!==void 0?{nonce:"[redacted]"}:{},...e.sig!==void 0?{sig:"[redacted]"}:{}});return Object.defineProperty(e,"toJSON",{value:t,enumerable:!1}),Object.defineProperty(e,Nb,{value:()=>`AgentSenderHeader(${JSON.stringify(t())})`,enumerable:!1}),Object.freeze(e)}function Lf(e){if(e.length>tf)throw new ye(`identity.name exceeds ${tf} UTF-16 code units`);for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<=31||r>=127&&r<=159||r===8232||r===8233)throw new ye("identity.name contains a control character");if(r>=55296&&r<=56319){let s=t+1<e.length?e.charCodeAt(t+1):0;if(s<56320||s>57343)throw new ye("identity.name contains a lone surrogate");t++}else if(r>=56320&&r<=57343)throw new ye("identity.name contains a lone surrogate")}}function Cb(e){try{return Lf(e),!0}catch{return!1}}function It(e){let t={v:Rf,account:e.account,user:e.user};if(e.name!==void 0)t.name=e.name;if(e.sub!==void 0)t.sub=e.sub;if(e.ts!==void 0)t.ts=e.ts;if(e.nonce!==void 0)t.nonce=e.nonce;if(e.sig!==void 0)t.sig=e.sig;return JSON.stringify(t)}function Df(e){return Sb+Ws(e)}function kb(e,t){let r={account:"A".repeat(Hi),user:"U".repeat(Ib),...t!==void 0?{name:t}:{},sub:e,ts:"T".repeat(Uf),nonce:"N".repeat(jb),sig:"S".repeat($f)};return Df(It(r))}function rf(e){let t=e.id.indexOf("."),r={v:1,account:e.id.slice(0,t),user:e.id.slice(t+1),...e.name!==void 0?{name:e.name}:{}},s=e.signed?{...r,sub:e.sub,ts:"T".repeat(Uf),nonce:"N".repeat(Tb),sig:"S".repeat($f)}:r;return Df(It(s))}function Mb(e){if(!e)return;let t=e.values(jt);if(t.length===0)return;if(t.length>1)throw new qe("more than one Agent-Sender value");return t[0]}function Rb(e){if(Ws(e)>ef)throw new qe(`value exceeds ${ef} bytes`);let t;try{t=JSON.parse(e)}catch{throw new qe("not valid JSON")}if(typeof t!=="object"||t===null||Array.isArray(t))throw new qe("not a JSON object");let r=t,s=r.v;if(typeof s!=="number")throw new qe("`v` must be a JSON number");if(s!==Rf)return null;let{account:n,user:o}=r;if(typeof n!=="string"||typeof o!=="string")throw new qe("`account` and `user` must be strings");try{dr(n,o)}catch(O){if(O instanceof Tt)throw new qe(O.message);throw O}let c={v:1,account:n,user:o},h=r.name;if(h!==void 0){if(typeof h!=="string"||!Cb(h))throw new qe("`name` is not a valid display name");c.name=h}let p=r.sub;if(p!==void 0){if(typeof p!=="string"||!Ob.test(p))throw new qe("`sub` is not a NATS subject");c.sub=p}let w=r.ts;if(w!==void 0){if(typeof w!=="string"||!Ab.test(w)||Number.isNaN(Date.parse(w)))throw new qe("`ts` is not an RFC 3339 UTC timestamp");c.ts=w}let A=r.nonce;if(A!==void 0){if(typeof A!=="string"||!qf.test(A))throw new qe("`nonce` must match [A-Za-z0-9_-]{1,64}");c.nonce=A}let j=r.sig;if(j!==void 0){if(typeof j!=="string")throw new qe("`sig` must be a string");let O;try{O=Ys(j)}catch{throw new qe("`sig` is not base64url")}if(O.length!==Pb)throw new qe("`sig` must decode to 64 bytes");if(c.sub===void 0||c.ts===void 0||c.nonce===void 0)throw new qe("`sig` requires `sub`, `ts` and `nonce`");c.sig=j}return io(c)}function qb(e=Date.now()){return new Date(Math.floor(e/1000)*1000).toISOString().replace(/\.\d{3}Z$/,"Z")}function Zs(e){return Date.parse(e)}function Ff(e){return Dr.encode(`${_b}
|
|
25
|
+
${e.account}
|
|
26
|
+
${e.user}
|
|
27
|
+
${e.subject}
|
|
28
|
+
${e.ts}
|
|
29
|
+
${e.nonce}
|
|
30
|
+
${e.payloadSha256Hex}
|
|
31
|
+
`)}function $b(e){return qf.test(e)}async function oo(e){let t=e.id.indexOf("."),r=e.id.slice(0,t),s=e.id.slice(t+1),n=e.ts??qb(),o=e.nonce??oe.nuid.next(),c=Ff({account:r,user:s,subject:e.sub,ts:n,nonce:o,payloadSha256Hex:await Pf(e.payload)}),h=Of(await e.signer.sign(c));return io({v:1,account:r,user:s,...e.name!==void 0?{name:e.name}:{},sub:e.sub,ts:n,nonce:o,sig:h})}function Ub(e){let t=e.id.indexOf(".");return io({v:1,account:e.id.slice(0,t),user:e.id.slice(t+1),...e.name!==void 0?{name:e.name}:{}})}function Lb(e){if(e===void 0)return;if(!Number.isInteger(e)||e<1)throw new ye("accountTokenPosition must be an integer >= 1 (1-based)");return e}function Db(e,t,r){if(r===void 0)return e.sub===t?null:`sub ${JSON.stringify(e.sub)} is not the arrival subject ${JSON.stringify(t)}`;let s=t.split(".");if(r>s.length)return`accountTokenPosition ${r} is beyond the ${s.length}-token arrival subject`;let n=s[r-1];if(n!==e.account)return`arrival subject token ${JSON.stringify(n)} at position ${r} is not the header account ${JSON.stringify(e.account)}`;let o=[...s.slice(0,r-1),...s.slice(r)].join(".");if(e.sub===t||e.sub===o)return null;return`sub ${JSON.stringify(e.sub)} is neither the arrival subject ${JSON.stringify(t)} nor ${JSON.stringify(o)}`}function Gt(e){throw new Yi(401,Xs,e)}async function Fb(e,t,r,s){if(e.sig===void 0||e.sub===void 0||e.ts===void 0||e.nonce===void 0)return Object.freeze({trust:"claimed",claim:Object.freeze({account:e.account,user:e.user}),...e.name!==void 0?{name:e.name}:{},header:e});let n=Lb(s.accountTokenPosition);if(s.mode==="live"){let A=s.replayWindowMs??Eb,j=s.now??Date.now(),O=Math.abs(j-Zs(e.ts));if(O>A)Gt(`ts ${e.ts} is ${Math.round(O/1000)} s from now (window ${A} ms)`)}let o=Db({account:e.account,sub:e.sub},t,n);if(o!==null)Gt(o);let c=!1;if(s.operatorAttested){let A=vb(s.headers);if(A===null)Gt("Nats-Request-Info is present but is not a server stamp (operator-attested mode)");if(A!==void 0){if(A.account!==void 0&&A.account!==e.account)Gt(`Nats-Request-Info acc ${JSON.stringify(A.account)} disagrees with the signed account ${JSON.stringify(e.account)}`);if(A.user!==void 0&&A.user!==e.user)Gt(`Nats-Request-Info user ${JSON.stringify(A.user)} disagrees with the signed user ${e.user}`)}c=n!==void 0||A?.account!==void 0}if(s.mode==="live"&&s.nonceSeen?.(e.user,e.nonce))Gt(`nonce already seen for ${e.user}`);let h=Ff({account:e.account,user:e.user,subject:e.sub,ts:e.ts,nonce:e.nonce,payloadSha256Hex:await Pf(r)});if(!Tf(e.user,h,Ys(e.sig)))Gt(`signature does not verify for ${e.user}`);let p=dr(e.account,e.user),w=s.resolver;return Object.freeze({trust:"verified",id:p,accountAttested:c,...e.name!==void 0?{name:e.name}:{},header:e,resolve:w?()=>w(p):()=>Promise.resolve(void 0)})}async function Bf(e,t,r={}){let s=Mb(e.headers);if(s===void 0)return;let n=Rb(s);if(n===null)return;return Fb(n,e.subject,e.data,{...r,mode:t,headers:e.headers})}var Bb="Nats-Msg-Id";async function Kf(e,t,r,s){if(!e?.signer)throw new Gs(t);let n=s.nonce;if(n!==void 0&&!$b(n))throw new ye("nonce must match [A-Za-z0-9_-]{1,64}");let o=await e.plan(s.sub??t,!0);if(!o)throw new Gs(t);return o.build(r,n)}async function Gi(e,t,r,s){let n=await Kf(e,t,r,s),o=s.headers??oe.headers();if(o.set(jt,It(n)),n.nonce!==void 0)o.set(Bb,n.nonce);return o}function Hs(e){return typeof e==="string"?new TextEncoder().encode(e):e}function Kb(e){let t=e.filter((s)=>s!==void 0);if(t.length===0)return new AbortController().signal;if(t.length===1)return t[0];for(let s of t)if(s.aborted)return s;let r=new AbortController;for(let s of t)s.addEventListener("abort",()=>{if(!r.signal.aborted)r.abort(s.reason)},{once:!0});return r.signal}function Ls(e){if(e.reason!==void 0)return e.reason;try{return new DOMException("stream aborted","AbortError")}catch{let t=Error("stream aborted");return t.name="AbortError",t}}var lr=Object.freeze({debug:()=>{return},info:()=>{return},warn:()=>{return},error:()=>{return}}),pr="agents",Hf="agents",Qs="status",zf="agents";function Hb(e){return e===pr}async function zb(e){if(typeof e==="string")return sf(e);if(e instanceof URL){if(e.protocol!=="file:")throw TypeError(`attachment URL must use file: protocol (got "${e.protocol}" for ${e.href})`);return sf(Py(e))}if(typeof e==="object"&&e!==null){let{filename:t,content:r}=e;if(typeof t!=="string"||t.length===0)throw TypeError("attachment object must have a non-empty `filename`");if(!(r instanceof Uint8Array))throw TypeError("attachment object `content` must be a Uint8Array");return{filename:t,content:r}}throw TypeError(`unsupported attachment input: ${typeof e}`)}async function Gb(e){return Promise.all(e.map(zb))}async function sf(e){let t=await Fr(e),r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return{filename:Oy(e),content:r}}var ao=new Set(["prompt","attachments"]);function Vb(e){return ao.has(e)}function Vi(e){return new TextEncoder().encode(JSON.stringify(Gf(e)))}function nf(e){return Ws(JSON.stringify(Gf(e)))}function Gf(e){let t={prompt:e.prompt};if(e.attachments&&e.attachments.length>0)t.attachments=e.attachments.map((r)=>({filename:r.filename,content:co(r.content)}));if(e.extras!==void 0){for(let[r,s]of Object.entries(e.extras))if(!ao.has(r)&&s!==void 0)Vf(t,r,s)}return t}var at="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function co(e){let t="",r=e.length,s=0;for(;s+3<=r;s+=3){let o=e[s],c=e[s+1],h=e[s+2];t+=at[o>>2],t+=at[(o&3)<<4|c>>4],t+=at[(c&15)<<2|h>>6],t+=at[h&63]}let n=r-s;if(n===1){let o=e[s];t+=at[o>>2],t+=at[(o&3)<<4],t+="=="}else if(n===2){let o=e[s],c=e[s+1];t+=at[o>>2],t+=at[(o&3)<<4|c>>4],t+=at[(c&15)<<2],t+="="}return t}function uo(e){if(e.length===0)throw new pe("zero-byte request payload (\xA75.3)");let t=new TextDecoder().decode(e);if(!Wb(t))return{prompt:t};let r;try{r=JSON.parse(t)}catch(p){throw new pe(`malformed JSON envelope: ${p.message}`)}if(typeof r!=="object"||r===null||Array.isArray(r))throw new pe("envelope must be a JSON object");let s=r,n=s.prompt;if(typeof n!=="string")throw new pe("envelope missing required string `prompt` field");if(n.length===0)throw new pe("envelope `prompt` must be a non-empty string");let o=Jb(s),c=s.attachments;if(c===void 0)return{prompt:n,...o};if(!Array.isArray(c))throw new pe("envelope `attachments` must be an array");let h=c.map((p,w)=>Yb(p,w));return h.length>0?{prompt:n,attachments:h,...o}:{prompt:n,...o}}function Jb(e){let t;for(let[r,s]of Object.entries(e)){if(ao.has(r))continue;Vf(t??={},r,s)}return t!==void 0?{extras:Object.freeze(t)}:{}}function Vf(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:!0,writable:!0,configurable:!0})}function Wb(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r===9||r===10||r===13||r===32)continue;return r===123}return!1}function Yb(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))throw new pe(`attachment[${t}] must be an object`);let r=e,s=r.filename,n=r.content;if(typeof s!=="string")throw new pe(`attachment[${t}] missing string \`filename\``);if(typeof n!=="string")throw new pe(`attachment[${t}] missing string \`content\``);em(s,t);let o;try{o=Zb(n)}catch(c){throw new pe(`attachment[${t}] has invalid base64 content: ${c.message}`)}return{filename:s,content:o}}var Xb=/^[A-Za-z0-9+/]*={0,2}$/;function Zb(e){if(e.length===0)return new Uint8Array(0);if(e.length%4!==0)throw Error("base64 length must be a multiple of 4 (padded)");if(!Xb.test(e))throw Error("base64 must use standard alphabet, padded, no whitespace");return tm(e)}var Qb=/[/\\\0]/;function em(e,t){if(e.length===0)throw new pe(`attachment[${t}] has empty filename`);if(Qb.test(e))throw new pe(`attachment[${t}] has unsafe filename (path separator or NUL)`);if(e==="."||e===".."||e.startsWith("../")||e.startsWith("./"))throw new pe(`attachment[${t}] has unsafe filename ('.' or '..' component)`)}function tm(e){let t=new Int8Array(128).fill(-1);for(let w=0;w<at.length;w++)t[at.charCodeAt(w)]=w;let r=0;if(e.endsWith("=="))r=2;else if(e.endsWith("="))r=1;let s=r>0?e.slice(0,-r):e,n=Math.floor(s.length*6/8),o=new Uint8Array(n),c=0,h=0,p=0;for(let w=0;w<s.length;w++){let A=s.charCodeAt(w);if(A>=128)throw Error("invalid base64 character");let j=t[A];if(j===-1||j===void 0)throw Error(`invalid base64 character at position ${w}`);if(h=h<<6|j,p+=6,p>=8)p-=8,o[c++]=h>>p&255}return o}var rm=2000,Jf=600000;function sm(e){if(e.length===0)throw new jy}function nm(e,t){if(t.attachmentsOk===!1)throw new Iy}function $r(e,t,r,s=0){let n=t.maxPayloadBytes,o=r!==void 0&&r>0?r:void 0,c;if(n!==void 0&&o!==void 0)c=Math.min(n,o);else c=n??o;if(c===void 0)return;if(e+s>c)throw new Ny(c,e,s)}var im=class extends ct{constructor(e){super(`query "${e}" has already been replied to`);this.id=e,this.name="QueryAlreadyRepliedError"}id};function om(e,t){let r=!1,s=async(n)=>{if(r)throw new im(t.id);r=!0;let o=typeof n==="string"?new TextEncoder().encode(n):Vi(n);e.publish(t.replySubject,o),await e.flush()};return Object.freeze({type:"query",id:t.id,prompt:t.prompt,...t.attachments!==void 0?{attachments:t.attachments}:{},reply:s})}function am(e){let t=new TextDecoder().decode(e),r;try{r=JSON.parse(t)}catch(c){throw new pe(`chunk body is not valid JSON: ${c.message}`)}if(typeof r!=="object"||r===null||Array.isArray(r))throw new pe("chunk body must be a JSON object");let s=r,n=s.type;if(typeof n!=="string")throw new pe("chunk body missing string `type` field");let o=s.data;switch(n){case"response":return cm(o);case"status":return um(o);case"query":return fm(o);default:return null}}function cm(e){if(typeof e==="string")return{type:"response",text:e};if(typeof e!=="object"||e===null||Array.isArray(e))throw new pe("`response` chunk `data` must be a string or object");let t=e,r=t.text;if(typeof r!=="string")throw new pe("`response` chunk `data.text` must be a string");let s=Wf(t.attachments,"response");if(s!==void 0)return{type:"response",text:r,attachments:s};return{type:"response",text:r}}function um(e){if(typeof e!=="string")throw new pe("`status` chunk `data` must be a string");return{type:"status",status:e}}function fm(e){if(typeof e!=="object"||e===null||Array.isArray(e))throw new pe("`query` chunk `data` must be an object");let t=e,r=t.id,s=t.reply_subject,n=t.prompt;if(typeof r!=="string")throw new pe("`query` chunk missing string `id`");if(typeof s!=="string")throw new pe("`query` chunk missing string `reply_subject`");if(typeof n!=="string")throw new pe("`query` chunk missing string `prompt`");let o=Wf(t.attachments,"query");if(o!==void 0)return{type:"query",id:r,replySubject:s,prompt:n,attachments:o};return{type:"query",id:r,replySubject:s,prompt:n}}function Wf(e,t){if(e===void 0)return;if(!Array.isArray(e))throw new pe(`\`${t}\` chunk \`attachments\` must be an array`);return e.map((r,s)=>{if(typeof r!=="object"||r===null||Array.isArray(r))throw new pe(`\`${t}\` chunk attachment #${s} must be an object`);let n=r;if(typeof n.filename!=="string")throw new pe(`\`${t}\` chunk attachment #${s} missing string \`filename\``);if(typeof n.content!=="string")throw new pe(`\`${t}\` chunk attachment #${s} missing string \`content\``);return{filename:n.filename,content:n.content}})}async function*dm(e,t,r){let s=e[Symbol.asyncIterator]();while(!0){let n=null,o=new Promise((h,p)=>{n=setTimeout(()=>p(r()),t)}),c;try{c=await Promise.race([s.next(),o])}finally{if(n)clearTimeout(n)}if(c.done)return;yield c.value}}function hm(e){return e.data.length===0&&!e.headers}function Yf(e){let t=e.headers;if(!t)return!1;if(typeof t.has==="function")return t.has("Nats-Service-Error-Code");if(typeof t.get==="function")try{return(t.get("Nats-Service-Error-Code")??"")!==""}catch{return!1}return!1}var lm=class{#e;#t;#o;#s;#r;#n;#i;#c=null;#u=!1;#a=!1;constructor(e){this.#e=e.nc,this.#t=e.subject,this.#o=e.payload,this.#s=e.prepare,this.#r=e.inactivityTimeoutMs,this.#n=e.maxWaitMs,this.#i=e.signal}get subject(){return this.#t}cancel(){this.#a=!0,this.#c?.stop()}async*[Symbol.asyncIterator](){if(this.#u)throw Error("PromptStream is single-use: a stream cannot be iterated more than once");if(this.#u=!0,this.#a)return;if(this.#i?.aborted)throw Ls(this.#i);let e=this.#s?await this.#s():{payload:this.#o},t=await this.#e.requestMany(this.#t,e.payload,{strategy:"sentinel",maxWait:this.#n,...e.headers?{headers:e.headers}:{}});if(this.#c=t,this.#a){t.stop();return}if(this.#i?.aborted)throw t.stop(),Ls(this.#i);let r;if(this.#i)r=()=>{this.#a=!0,t.stop()},this.#i.addEventListener("abort",r,{once:!0});try{let s=dm(t,this.#r,()=>new gf(this.#r));for await(let n of s){if(this.#i?.aborted)throw Ls(this.#i);if(Yf(n))throw Xf(n);if(hm(n)){yield{type:"status",status:"done"};return}let o;try{o=am(n.data)}catch{continue}if(!o)continue;yield pm(o,this.#e)}if(this.#i?.aborted)throw Ls(this.#i);if(this.#a)return;throw new xf(this.#n)}finally{if(r&&this.#i)this.#i.removeEventListener("abort",r);t.stop(),this.#c=null}}};function pm(e,t){switch(e.type){case"response":return e.attachments!==void 0?{type:"response",text:e.text,attachments:e.attachments}:{type:"response",text:e.text};case"status":return{type:"status",status:e.status};case"query":return om(t,{id:e.id,replySubject:e.replySubject,prompt:e.prompt,...e.attachments!==void 0?{attachments:e.attachments}:{}})}}function Xf(e){let t=e.headers,r=t?.get("Nats-Service-Error-Code")??"500",s=Number(r),n=t?.get("Nats-Service-Error")??"",o;if(e.data.length>0)try{let c=JSON.parse(new TextDecoder().decode(e.data));if(typeof c==="object"&&c!==null&&!Array.isArray(c))o=c}catch{}return new mf(Number.isFinite(s)?s:500,n,o)}var Zf=class{instanceId;agent;owner;name;session;protocolVersion;description;version;promptEndpoint;metadata;endpoints;supportsSenderIdentity;identity;idSigVerified;#e;#t;#o;#s;#r;#n;constructor(e,t,r,s=void 0,n=void 0,o=[],c=lr){this.#e=e,this.#t=r,this.#o=s,this.#s=n,this.#r=Object.freeze([...o]),this.#n=c,this.instanceId=t.instanceId,this.agent=t.agent,this.owner=t.owner,this.name=t.name,this.session=t.session,this.protocolVersion=t.protocolVersion,this.description=t.description,this.version=t.version,this.promptEndpoint=t.promptEndpoint,this.metadata=t.metadata,this.endpoints=t.endpoints,this.supportsSenderIdentity=t.supportsSenderIdentity,this.identity=t.identity,this.idSigVerified=t.idSigVerified}get promptSubject(){return this.promptEndpoint.subject}get minSenderTrust(){return this.promptEndpoint.minSenderTrust}get connection(){return this.#e}get interceptors(){return this.#r}prompt(e,t={}){sm(e);let r=t.attachments??[],s=r.length>0;if(s)nm(!0,this.promptEndpoint);let n=t.subject??this.promptEndpoint.subject,o=t.sub??n,c=this.promptEndpoint.minSenderTrust==="signed",h=this.#u(e,t.context??ym,n),p=this.#s;if(c&&!p?.signer)throw new Gs(n);let w=this.#e.info?.max_payload,A=p?.mayAttachHeader()?kb(o,p.name):0;if(!s){let j={prompt:e};return $r(nf(j),this.promptEndpoint,w,A),this.#i(j,n,o,c,t,h)}return(async()=>{let j=await Gb(r),O={prompt:e,attachments:j};return $r(nf(O),this.promptEndpoint,w,A),this.#i(O,n,o,c,t,h)})()}async#i(e,t,r,s,n,o){let c=Vi(e),h=await this.#d(r,s);if(h)$r(c.length,this.promptEndpoint,this.#e.info?.max_payload,h.wireBytes);let p=this.#s,w=p!==void 0&&(p.signer!==void 0||p.sendUnsignedClaim),A=Kb([n.signal,this.#o]),j=w||o!==void 0?()=>this.#c(e,c,r,s,w,o):void 0;return new lm({nc:this.#e,subject:t,payload:c,...j?{prepare:j}:{},inactivityTimeoutMs:n.inactivityTimeoutMs??this.#t,maxWaitMs:n.maxWaitMs??Jf,signal:A})}async#c(e,t,r,s,n,o){let c=n?await this.#d(r,s):void 0,h=t,p,w;if(o){let A=w=await o.extend();if(A.fields!==void 0){if(h=Vi({...e,extras:A.fields}),!c)$r(h.length,this.promptEndpoint,this.#e.info?.max_payload)}if(A.headers!==void 0){p=oe.headers();for(let[j,O]of Object.entries(A.headers))p.set(j,O)}}if(c)$r(h.length,this.promptEndpoint,this.#e.info?.max_payload,c.wireBytes),p??=oe.headers(),p.set(jt,It(await c.build(h)));if(o&&w)await o.publish(w.results);return p!==void 0?{payload:h,headers:p}:{payload:h}}#u(e,t,r){let s=this.#r;if(s.length===0)return;let n={agent:this,prompt:e,context:t,connection:this.#e,identity:this.#a()},o=this.#n;return{extend:Yu.bind(()=>bm(s,n)),publish:Yu.bind((c)=>mm(s,n,c,o,r))}}#a(){let e=this.#e,t=this.#s;return{canSign:t?.signer!==void 0,selfId:()=>t?.selfId()??hr(e),publishSigned:async(r,s,n={})=>{let o=Hs(s),c=await Gi(t,r,o,n);e.publish(r,o,{headers:c})}}}async status(e={}){let t=this.endpoints.find((w)=>w.name===Qs),r=e.subject??t?.subject;if(r===void 0)throw new ct(`agent ${this.instanceId} declares no status endpoint`);let s=e.sub??r,n=await this.#d(s,!1),o=n?await this.#h(n,oe.Empty):void 0,c=await this.#e.request(r,oe.Empty,{timeout:e.timeoutMs??rm,...o?{headers:o}:{}});if(Yf(c))throw Xf(c);let h;try{h=JSON.parse(c.string())}catch(w){throw new pe("status reply is not JSON",{cause:w})}let p=wf(h);if(!p)throw new pe("status reply is not a \xA78.3 heartbeat payload");return p}async#d(e,t){let r=this.#s;if(!r)return;if(!t&&!r.mayAttachHeader())return;return r.plan(e,t)}async#h(e,t){let r=oe.headers();return r.set(jt,It(await e.build(t))),r}},ym=Object.freeze({});async function bm(e,t){let r=new Map,s=new Map,n=[];for(let o of e){let c=await o.beforePrompt(t);if(n.push(c),c===void 0)continue;for(let[h,p]of Object.entries(c.fields??{})){if(Vb(h))throw new ct(`prompt interceptor: envelope field \`${h}\` is not an extra`);r.set(h,p)}for(let[h,p]of Object.entries(c.headers??{})){if(h.toLowerCase()===jt.toLowerCase())throw new ct(`prompt interceptor: the ${jt} header is the SDK's`);s.set(h,p)}}return{...r.size>0?{fields:Object.fromEntries(r)}:{},...s.size>0?{headers:Object.fromEntries(s)}:{},results:n}}async function mm(e,t,r,s,n){for(let[o,c]of e.entries()){if(c.beforePublish===void 0)continue;try{await c.beforePublish(t,r[o])}catch{s.error("prompt interceptor beforePublish failed; publishing the prompt",{subject:n,interceptor:o,error:"exception"})}}}var gm=/[.*>\s\0]/;var $i=class extends Error{constructor(e,t,r){super(`invalid ${e} token "${t}": ${r}`);this.role=e,this.token=t,this.name="InvalidSubjectTokenError"}role;token};function Ur(e,t){if(e.length===0)throw new $i(t,e,"must not be empty");if(e.startsWith("$"))throw new $i(t,e,"must not begin with '$'");if(gm.test(e))throw new $i(t,e,"must not contain whitespace, '.', '*', '>', or NUL")}var Ui="agents",xm="prompt",wm="hb",vm="status";var Qf=class e{constructor(t,r,s,n){this.agent=t,this.owner=r,this.name=s,this.subjectToken=n}agent;owner;name;subjectToken;static new(t,r,s,n={}){Ur(t,"agent"),Ur(r,"owner"),Ur(s,"name");let o=n.subjectToken??t;if(o!==t)Ur(o,"subjectToken");return new e(t,r,s,o)}get prompt(){return`${Ui}.${xm}.${this.subjectToken}.${this.owner}.${this.name}`}get heartbeat(){return`${Ui}.${wm}.${this.subjectToken}.${this.owner}.${this.name}`}get status(){return`${Ui}.${vm}.${this.subjectToken}.${this.owner}.${this.name}`}};var fo="min_sender_trust";function _m(e){if(e===void 0)return;return e==="any"?"any":"signed"}var yr="prompt";function Em(e){let t=Object.freeze({...e.metadata??{}}),r=e.queue_group??"";if(e.name!==yr)return Object.freeze({name:e.name,subject:e.subject,queueGroup:r,metadata:t});let s,n=t.max_payload;if(n!==void 0)try{s=Xi(n)}catch(p){if(!(p instanceof cr))throw p}let o,c=t.attachments_ok;if(c==="true")o=!0;else if(c==="false")o=!1;let h=_m(t[fo]);return Object.freeze({name:e.name,subject:e.subject,queueGroup:r,metadata:t,...s!==void 0?{maxPayloadBytes:s}:{},...o!==void 0?{attachmentsOk:o}:{},...h!==void 0?{minSenderTrust:h}:{}})}var Sm="AGENT-ID-V1",ze=Object.freeze({userNkey:"user_nkey",account:"account",idSig:"id_sig"});function ed(e){return Dr.encode(`${Sm}
|
|
32
|
+
${e.user}
|
|
33
|
+
${e.account}
|
|
34
|
+
${e.agent}
|
|
35
|
+
${e.owner}
|
|
36
|
+
${e.promptSubject}
|
|
37
|
+
`)}async function td(e){let t=ed({user:ht(e.id),account:Lr(e.id),agent:e.agent,owner:e.owner,promptSubject:e.promptSubject});return Of(await e.signer.sign(t))}function Am(e,t){let r=e[ze.userNkey],s=e[ze.account],n=e.agent,o=e.owner,c=e[ze.idSig];if(r===void 0||s===void 0||n===void 0||o===void 0||c===void 0)return!1;let h;try{Ef(r),h=Ys(c)}catch{return!1}if(h.length!==64)return!1;return Tf(r,ed({user:r,account:s,agent:n,owner:o,promptSubject:t}),h)}function rd(e){if(!Hb(e.name))return null;let t=e.metadata??{},r=t.agent,s=t.owner,n=t.protocol_version;if(r===void 0||s===void 0||n===void 0)return null;let o=e.endpoints.map((N)=>Em(N)),c=o.find((N)=>N.name===yr);if(!c)return null;let p=c.subject.split(".")[4],w=p!==void 0&&p!==""?p:"",A=t.session,j=A!==void 0&&A!==""?A:void 0,O=Om(t),K=t[ze.idSig]!==void 0&&Am(t,c.subject);return Object.freeze({instanceId:e.id,agent:r,owner:s,name:w,protocolVersion:n,description:e.description,version:e.version,metadata:Object.freeze({...t}),endpoints:Object.freeze(o),promptEndpoint:c,supportsSenderIdentity:c.minSenderTrust!==void 0,idSigVerified:K,...O!==void 0?{identity:O}:{},...j!==void 0?{session:j}:{}})}function Om(e){let t=e[ze.userNkey],r=e[ze.account];if(t===void 0||r===void 0)return;try{return dr(r,t)}catch{return}}var sd=2000,nd=750;async function Pm(e,t,r,s={},n,o=[],c){let h=s.timeoutMs!==void 0?{strategy:"timer",maxWait:s.timeoutMs}:{strategy:"stall",maxWait:sd,stall:nd};return(await id(e,h)).filter((w)=>Tm(w,s.filter)).map((w)=>new Zf(e,w,t,r,n,o,c))}async function id(e,t){let s=new Ji.Svcm(e).client(t),n=[];try{let o=await s.info(pr);for await(let c of o){let h=rd(c);if(h)n.push(h)}}catch(o){if(o instanceof oe.NoRespondersError)return[];throw o}return n}function Tm(e,t){if(!t)return!0;if(t.agent!==void 0&&e.agent!==t.agent)return!1;if(t.owner!==void 0&&e.owner!==t.owner)return!1;if(t.name!==void 0&&e.name!==t.name)return!1;if(t.session!==void 0&&e.session!==t.session)return!1;if(t.protocolVersion!==void 0&&e.protocolVersion!==t.protocolVersion)return!1;return!0}async function jm(e,t,r,s,n={},o,c=[],h){let p=n.timeoutMs??2000;try{Ur(t,"instanceId")}catch{return null}let w=`$SRV.INFO.${pr}.${t}`,A;try{let O=await e.request(w,"",{timeout:p});A=JSON.parse(O.string())}catch(O){if(O instanceof oe.NoRespondersError)return null;return null}if(!A||typeof A!=="object")return null;let j=rd(A);if(!j)return null;return new Zf(e,j,r,s,o,c,h)}async function Im(e,t,r={}){let s=r.timeoutMs??2000,o=new Ji.Svcm(e).client({strategy:"timer",maxWait:s});try{let c=await o.ping(pr,t);for await(let h of c)return!0;return!1}catch(c){if(c instanceof oe.NoRespondersError)return!1;throw c}}var Nm=3,Cm="agents.hb.*.*.*",km=class{constructor(e,t=lr){this.nc=e,this.logger=t}nc;logger;entries=new Map;allListeners=new Set;scopedListeners=new Map;subscription=null;get subject(){return Cm}get isStarted(){return this.subscription!==null}async start(){if(this.subscription)return;this.subscription=this.nc.subscribe(this.subject,{callback:(e,t)=>{if(e){this.logger.warn("heartbeat subscription error",{error:String(e)});return}let r;try{r=t.json()}catch{this.logger.debug("dropping non-JSON heartbeat",{subject:t.subject});return}let s=wf(r);if(!s){this.logger.debug("dropping malformed heartbeat",{subject:t.subject});return}this.entries.set(s.instanceId,{payload:s,lastSeen:new Date}),this.dispatch(s)}}),await this.nc.flush()}async stop(){if(!this.subscription)return;let e=this.subscription;this.subscription=null,e.unsubscribe(),await e.closed}liveness(e,t=new Date){let r=this.entries.get(e);if(!r)return null;let n=(t.getTime()-r.lastSeen.getTime())/1000<=Nm*r.payload.intervalS;return Object.freeze({instanceId:e,lastSeen:r.lastSeen,intervalS:r.payload.intervalS,isOnline:n})}onAnyHeartbeat(e){return this.allListeners.add(e),()=>this.allListeners.delete(e)}onHeartbeat(e,t){let r=this.scopedListeners.get(e);if(!r)r=new Set,this.scopedListeners.set(e,r);return r.add(t),()=>{let s=this.scopedListeners.get(e);if(s){if(s.delete(t),s.size===0)this.scopedListeners.delete(e)}}}dispatch(e){for(let r of this.allListeners)try{r(e)}catch(s){this.logger.warn("heartbeat listener threw",{error:String(s)})}let t=this.scopedListeners.get(e.instanceId);if(t)for(let r of t)try{r(e)}catch(s){this.logger.warn("heartbeat listener threw",{error:String(s)})}}},Mm=class{nc;signer;name;sendUnsignedClaim;constructor(e,t={}){if(t.name!==void 0)Lf(t.name);this.nc=e,this.signer=t.signer,this.name=t.name,this.sendUnsignedClaim=t.sendUnsignedClaim??!0}selfId(){return hr(this.nc,this.#e())}refresh(){return kf(this.nc,this.#e())}peek(){return hb(this.nc,this.#e())}kickoff(){if(!this.signer&&!this.sendUnsignedClaim)return;pb(this.nc,this.#e())}mayAttachHeader(){if(this.signer)return!0;if(!this.sendUnsignedClaim)return!1;let e=this.peek();return!(e!==void 0&&("error"in e)&&e.error instanceof ar)}async resolveForRequest(e){let t=e||this.signer!==void 0,r=this.peek();if(r!==void 0){if("id"in r)return r.id;if(r.error instanceof ur||t)throw r.error;return}if(!t&&lb(this.nc,this.#e())){this.kickoff();return}try{return await this.selfId()}catch(s){if(s instanceof ur||t)throw s;return}}async plan(e,t){let r=this.signer;if(t&&!r)throw new Gs(e);if(!r&&!this.sendUnsignedClaim)return;let s=await this.resolveForRequest(t);if(s===void 0)return;let n=this.name,o=n!==void 0?{name:n}:{};if(r)return{id:s,signed:!0,sub:e,wireBytes:rf({id:s,...o,sub:e,signed:!0}),build:(h,p)=>oo({signer:r,id:s,...o,sub:e,payload:h,...p!==void 0?{nonce:p}:{}})};let c=Ub({id:s,...o});return{id:s,signed:!1,sub:e,wireBytes:rf({id:s,...o,sub:e,signed:!1}),build:()=>Promise.resolve(c)}}#e(){return this.signer?{signer:this.signer}:{}}},Rm=1e4;function ho(e){if(e===void 0)return Rm;if(typeof e!=="number"||!Number.isFinite(e)||e<0)throw new ye("resolveTtlMs must be a finite number of milliseconds >= 0");return e}var lo=class{#e;#t;#o;#s=new Map;#r=null;#n=null;constructor(e,t={}){this.#e=e,this.#t=ho(t.ttlMs),this.#o=t.timeoutMs!==void 0?{strategy:"timer",maxWait:t.timeoutMs}:{strategy:"stall",maxWait:t.maxWaitMs??sd,stall:t.stallMs??nd}}get ttlMs(){return this.#t}invalidate(){this.#s=new Map,this.#r=null}async resolve(e){let t=Ky(e);if(this.#r===null||Date.now()-this.#r>=this.#t)await this.#i();return this.#s.get(t)?.[0]}#i(){if(!this.#n){let e=this.#c().finally(()=>{if(this.#n===e)this.#n=null});this.#n=e}return this.#n}async#c(){let e=await id(this.#e,this.#o),t=new Map;for(let r of e)if(r.identity!==void 0&&r.idSigVerified){let s=t.get(r.identity);if(s)s.push(r);else t.set(r.identity,[r])}this.#s=t,this.#r=Date.now()}};var qm=60000,$m=2000,sv=class{#e;#t;#o;#s;#r;#n;#i;#c=new AbortController;#u=!1;constructor(e){this.#e=e.nc,this.#o=e.logger??lr,this.#s=e.streamInactivityTimeoutMs??qm,this.#r=e.identity!==void 0?new Mm(e.nc,e.identity):void 0,this.#n=Object.freeze([...e.interceptors??[]]),this.#i=new lo(e.nc,e.resolveTtlMs!==void 0?{ttlMs:e.resolveTtlMs}:{}),this.#t=new km(e.nc,this.#o)}get connection(){return this.#e}get streamInactivityTimeoutMs(){return this.#s}get interceptors(){return this.#n}get closeSignal(){return this.#c.signal}async discover(e={}){if(this.#a(),this.#r?.kickoff(),!this.#t.isStarted)await this.#t.start();return Pm(this.#e,this.#s,this.#c.signal,e,this.#r,this.#n,this.#o)}async startTracking(){this.#a(),await this.#t.start()}liveness(e){return this.#t.liveness(e)}onHeartbeat(e,t){if(!this.#t.isStarted)this.#t.start();return this.#t.onHeartbeat(e,t)}async ping(e,t={}){return this.#a(),Im(this.#e,e,t)}async lookupInstance(e,t={}){return this.#a(),jm(this.#e,e,this.#s,this.#c.signal,t,this.#r,this.#n,this.#o)}selfId(){return this.#a(),this.#r?.selfId()??hr(this.#e)}refreshSelfId(){return this.#a(),this.#r?.refresh()??kf(this.#e)}async signSender(e,t,r={}){return this.#a(),It(await Kf(this.#r,e,Hs(t),r))}async publishSigned(e,t,r={}){this.#a();let s=Hs(t),n=await Gi(this.#r,e,s,r);this.#e.publish(e,s,{headers:n})}async requestSigned(e,t,r={}){this.#a();let s=Hs(t),n=await Gi(this.#r,e,s,r);return this.#e.request(e,s,{timeout:r.timeoutMs??$m,headers:n})}resolveSender(e){return this.#a(),this.#i.resolve(e)}async close(){if(this.#u)return;this.#u=!0,this.#c.abort(Error("@synadia-ai/agents: Agents is closed")),await this.#t.stop()}get isClosed(){return this.#u}#a(){if(this.#u)throw Error("@synadia-ai/agents: Agents is closed")}},od=67108864,of=200,Um=16,af=1000,Lm=/^[A-Za-z0-9+/]*={0,2}$/,cf=" .\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF",Dm="\uFFFD",Fm='<>:"|?*',Bm=/^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|(?:COM|LPT)[1-9\u00b9\u00b2\u00b3]) *(?:\.|$)/i,Km=384,Hm=448;async function zm(e,t,r={}){let s=r.maxTotalBytes??od;if(Number.isNaN(s)||s<0)throw RangeError(`saveAttachments: maxTotalBytes must be a non-negative number or Infinity (got ${s})`);let n=Bs(t);await bf(n,{recursive:!0,mode:Hm});let o=[],c=0;for(let[h,p]of e.entries()){let{filename:w,content:A}=p,j=typeof w==="string"?w:"",O=typeof A==="string"?Gm(A):null;if(typeof A!=="string"||O===null){o.push({filename:j,sizeBytes:0,path:null,skipped:"invalid_content"});continue}if(c+O>s){o.push({filename:j,sizeBytes:O,path:null,skipped:"over_limit"});continue}let K=Buffer.from(A,"base64"),N=await Jm(n,Vm(j,h+1),K);c+=O,o.push({filename:j,sizeBytes:O,path:N})}return o}function Gm(e){if(e.length%4!==0||!Lm.test(e))return null;let t=e.endsWith("==")?2:e.endsWith("=")?1:0;return e.length/4*3-t}function Vm(e,t){let r=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),s="";for(let n of e.slice(r+1)){let o=n.codePointAt(0);if(o<=31||o>=127&&o<=159)continue;if(o===8206||o===8207)continue;if(o>=8234&&o<=8238||o>=8294&&o<=8297)continue;if(o>=55296&&o<=57343)s+=Dm;else s+=Fm.includes(n)?"_":n}if(s=cd(s),s==="")return`attachment-${t}`;return s=uf(s),Bm.test(s)?uf(`_${s}`):s}function uf(e){if(Li(e)<=of)return e;let[t,r]=ad(e);if([...r].length>Um)t=e,r="";let s=of-Li(r),n="",o=0;for(let c of t){let h=Li(c);if(o+h>s)break;n+=c,o+=h}return cd(n)+r}function ad(e){let t=e.lastIndexOf(".");return t>0?[e.slice(0,t),e.slice(t)]:[e,""]}function cd(e){let t=0,r=e.length;while(t<r&&cf.includes(e[t]))t++;while(r>t&&cf.includes(e[r-1]))r--;return e.slice(t,r)}function Li(e){let t=0;for(let r of e){let s=r.codePointAt(0);t+=s<128?1:s<2048?2:s<65536?3:4}return t}async function Jm(e,t,r){let[s,n]=ad(t);for(let o=1;o<=af;o++){let c=wt(e,o===1?t:`${s} (${o})${n}`),h;try{h=await wy(c,"wx",Km)}catch(p){if(p.code==="EEXIST")continue;throw p}try{await h.writeFile(r),await h.close()}catch(p){throw await h.close().catch(()=>{return}),await vy(c).catch(()=>{return}),p}return c}throw Error(`saveAttachments: no free name for "${t}" in ${e} after ${af} attempts`)}function Nt(e){if(e===void 0)return"(no sender)";if(e.trust==="verified")return e.accountAttested?`${e.id} (verified)`:`${e.id} (verified user, claimed account)`;return`${e.claim.account}.${e.claim.user} (claimed)`}var Me=class{constructor(e){this.error=e}error};function Br(e,t){let r=t;if(r===void 0||r===null||r==="")return{};if(typeof r==="string")try{r=JSON.parse(r)}catch{return new Me(`${e}: the arguments are not valid JSON`)}if(typeof r!=="object"||r===null||Array.isArray(r))return new Me(`${e}: the arguments must be a JSON object`);return r}function Wm(e){let t=Br("discover_agents",e);if(He(t))return t;let r={};for(let s of["agent","owner","name"]){let n=t[s];if(n===void 0)continue;if(typeof n!=="string"||n.length===0)return new Me(`discover_agents: "${s}" must be a non-empty string when given`);r[s]=n}return r}function Ym(e){let t=Br("prompt_agent",e);if(He(t))return t;let{address:r,prompt:s,attachments:n,label:o,wait:c}=t;if(typeof r!=="string"||r.length===0)return new Me('prompt_agent: "address" is required, as discover_agents returned it');if(typeof s!=="string"||s.length===0)return new Me('prompt_agent: "prompt" is required and must not be empty');if(n!==void 0&&(!Array.isArray(n)||!n.every((h)=>typeof h==="string"&&h.length>0)))return new Me('prompt_agent: "attachments" must be a list of file paths');if(o!==void 0&&(typeof o!=="string"||o.length===0))return new Me('prompt_agent: "label" must be a non-empty string when given');if(c!==void 0&&typeof c!=="boolean")return new Me('prompt_agent: "wait" must be true or false');return{address:r,prompt:s,attachments:n??[],...o!==void 0?{label:o}:{},wait:c??!0}}function Xm(e){let t=Br("wait_agent",e);if(He(t))return t;let r=ud("wait_agent",t.call_ids);if(He(r))return r;let s=t.timeout_ms;if(s===void 0)return{callIds:r};if(typeof s!=="number"||!Number.isInteger(s)||s<0)return new Me('wait_agent: "timeout_ms" must be a whole number of milliseconds, 0 or more');return{callIds:r,timeoutMs:s}}function Zm(e){let t=Br("answer_agent",e);if(He(t))return t;let{call_id:r,answer:s,wait:n}=t;if(typeof r!=="string"||r.length===0)return new Me('answer_agent: "call_id" is required, as it came with the question');if(typeof s!=="string"||s.length===0)return new Me('answer_agent: "answer" is required and must not be empty');if(n!==void 0&&typeof n!=="boolean")return new Me('answer_agent: "wait" must be true or false');return{callId:r,answer:s,...n!==void 0?{wait:n}:{}}}function Qm(e){let t=Br("cancel_agent",e);if(He(t))return t;let r=ud("cancel_agent",t.call_ids);return He(r)?r:{callIds:r}}function ud(e,t){if(!Array.isArray(t)||t.length===0||!t.every((r)=>typeof r==="string"&&r.length>0))return new Me(`${e}: "call_ids" must be a non-empty list of call_id strings`);return[...new Set(t)]}function He(e){return e instanceof Me}var zs=["discover_agents","prompt_agent","wait_agent","answer_agent","cancel_agent","list_agent_calls"],nv=["discover_agents","prompt_agent","answer_agent"],eg=[{name:"discover_agents",description:"List the agents you can prompt, one entry per address. Each entry gives the address to use with prompt_agent, the agent's kind, owner and name, what it says it does, its identity and whether that identity is verified, whether it requires signed prompts or accepts attachments, and how many instances answer at the address. The filters are optional, exact and combined, one per token of the address `agents.prompt.<agent>.<owner>.<name>`; an agent known by what it does is found with the `agent` filter, its kind or role, or by calling without filters, which lists every agent. Call it before prompt_agent when you do not already know an address.",parameters:{type:"object",properties:{agent:{type:"string",minLength:1,description:"Only agents whose address has this first token after `agents.prompt`, their kind or role exactly as registered (for example `researcher` or `claude-code`)."},owner:{type:"string",minLength:1,description:"Only agents whose address has this second token after `agents.prompt`, their owner exactly as registered."},name:{type:"string",minLength:1,description:"Only agents whose address has this last token after `agents.prompt`, their instance name (usually `main`); what an agent does or is called in a task is not its name."}},additionalProperties:!1}},{name:"prompt_agent",description:"Send a prompt to one agent and get its reply. Use an address returned by discover_agents. Keep the prompt self-contained: the other agent sees nothing of your conversation. Do not prompt the agent that prompted you; answer it instead. By default the call waits for the complete reply. If the other agent asks a question while it works, you get the question and a call_id instead: answer it with answer_agent. With wait set to false the call returns at once with a call_id while the other agent works, and you collect the result later with wait_agent; use it to have several agents work at once. Calls you start while you are answering a prompt end with that prompt, so collect their results before you answer. The other agent runs on another machine, so never put a local file path in the prompt: attach the file instead (small files only, and only to an agent that accepts attachments). Files the other agent sends back are saved on this machine, and the result gives each file's path.",parameters:{type:"object",properties:{address:{type:"string",minLength:1,description:"The agent's address, exactly as discover_agents returned it."},prompt:{type:"string",minLength:1,description:"The task for the other agent, complete in itself."},attachments:{type:"array",items:{type:"string",minLength:1},description:"Optional paths of local files to send with the prompt, only from the directories you may send from, and only to an agent that accepts attachments (see discover_agents). The files travel inside the message, so keep them small."},label:{type:"string",minLength:1,description:"Optional short name for this call, shown in its results. It is never sent to the other agent."},wait:{type:"boolean",description:"true (the default): wait for the reply or a question. false: return at once with a call_id, and collect the result with wait_agent."}},required:["address","prompt"],additionalProperties:!1}},{name:"wait_agent",description:"Wait for calls you started with prompt_agent. Returns the first of the given calls that finished or asked a question (the earliest, if several have), with remaining: the ids of the other given calls that are still open. A finished call's result can be fetched again, the same each time, until the call is dropped from list_agent_calls. If none of the calls is ready within timeout_ms, returns state running with the call_ids still running. A question is answered with answer_agent.",parameters:{type:"object",properties:{call_ids:{type:"array",items:{type:"string",minLength:1},minItems:1,description:"The calls to wait for, as prompt_agent returned their call_id."},timeout_ms:{type:"integer",minimum:0,description:"How long to wait, in milliseconds; 0 checks without waiting. A longer wait than the configured limit is shortened to it, and the limit is the default."}},required:["call_ids"],additionalProperties:!1}},{name:"answer_agent",description:"Answer the question an agent asked while working on your call, using the call_id that came with the question. Then, by default, it goes on as the call was started: a call started with wait true waits for the reply or the agent's next question; a call started with wait false returns at once, and you collect the result with wait_agent. A permission question asks you to allow or deny an action the other agent wants to take: allow it only if the task you gave needs it; when unsure, deny. Answer promptly: the asking agent waits only so long, and a question still open when the prompt you are answering ends is refused.",parameters:{type:"object",properties:{call_id:{type:"string",minLength:1,description:"The call_id that came with the question."},answer:{type:"string",minLength:1,description:"Your answer, in the form the question asks for (for a permission question, `yes` or `no`)."},wait:{type:"boolean",description:"true: wait for the reply or the next question. false: return at once. Defaults to the way the call was started."}},required:["call_id","answer"],additionalProperties:!1}},{name:"cancel_agent",description:"Stop calls you started. Each open call becomes cancelled, and an open question gets a refusal. The result gives each call's state and the reply text received so far. The other agent is not told and may keep working; whatever it sends later is discarded. A call that already finished keeps its result.",parameters:{type:"object",properties:{call_ids:{type:"array",items:{type:"string",minLength:1},minItems:1,description:"The calls to stop, as prompt_agent returned their call_id."}},required:["call_ids"],additionalProperties:!1}},{name:"list_agent_calls",description:"List the calls you started that are still tracked, oldest first: each with its call_id, label, address, state and times. Open calls are running, or input_required when a question waits for answer_agent. Finished calls are completed, failed, cancelled or expired; they are dropped, the longest finished first, when the list is full.",parameters:{type:"object",properties:{},additionalProperties:!1}}];function tg(){return structuredClone(eg)}var rg={prompt_agent:"Send a prompt to one agent and get its reply. Use an address returned by discover_agents. Keep the prompt self-contained: the other agent sees nothing of your conversation. Do not prompt the agent that prompted you; answer it instead. The call waits for the complete reply. If the other agent asks a question while it works, you get the question and a call_id instead: answer it with answer_agent. Calls you start while you are answering a prompt end with that prompt, so answer their questions before you answer. The other agent runs on another machine, so never put a local file path in the prompt: attach the file instead (small files only, and only to an agent that accepts attachments). Files the other agent sends back are saved on this machine, and the result gives each file's path.",answer_agent:"Answer the question an agent asked while working on your call, using the call_id that came with the question. Then it waits for the reply or the agent's next question. A permission question asks you to allow or deny an action the other agent wants to take: allow it only if the task you gave needs it; when unsure, deny. Answer promptly: the asking agent waits only so long, and a question still open when the prompt you are answering ends is refused."};function sg(e){let t=tg().filter((r)=>e.has(r.name));if(e.has("wait_agent"))return t;return t.map((r)=>{if(delete r.parameters.properties.wait,!r.description.includes("wait_agent"))return r;let s=rg[r.name];if(s===void 0)throw Error(`AgentTools: no blocking-only description for ${r.name}`);return{...r,description:s}})}var ng=256,ig="no: the caller stopped waiting for this prompt and cannot answer",ff=["call_id","state","label","reply","question","error","partial_reply","attachments","remaining","call_ids","open_calls","open_calls_note"],og=["address","agent","owner","name","description","identity","identity_verified","requires_signed_prompts","accepts_attachments","instances"],iv=class{definitions;requestInterceptor;agents;offered;selfAddress;discoverTimeoutMs;maxWaitMs;maxWaitAgentMs;maxCalls;attachmentRoots;stagingOption;maxSavedBytes;onSettled;extensions;logger;cwd;scopeStore;root;served=new Set;known=new Map;staging;ownsStaging=!1;seq=0;closed=!1;constructor(e){if(this.agents=e.agents,this.offered=ug(e.tools),this.selfAddress=e.selfAddress,this.discoverTimeoutMs=Bi("discoverTimeoutMs",e.discoverTimeoutMs),this.maxWaitMs=Bi("maxWaitMs",e.maxWaitMs)??Jf,this.maxWaitAgentMs=pf("maxWaitAgentMs",e.maxWaitAgentMs)??this.maxWaitMs,this.maxCalls=Bi("maxCalls",e.maxCalls)??ng,!Number.isInteger(this.maxCalls))throw RangeError(`AgentTools: maxCalls must be a whole number (got ${this.maxCalls})`);this.cwd=process.cwd(),this.attachmentRoots=(e.attachmentRoots??[]).map((t)=>Bs(this.cwd,t)),this.stagingOption=e.stagingDir!==void 0?Bs(this.cwd,e.stagingDir):void 0,this.maxSavedBytes=pf("maxSavedBytesPerCall",e.maxSavedBytesPerCall)??od,this.onSettled=e.onSettled,this.extensions=[...e.extensions??[]],this.logger=e.logger??lr,this.scopeStore=new xy,this.root=new df(!1,void 0),this.definitions=sg(this.offered),this.requestInterceptor={aroundRequest:(t,r)=>{if(this.closed)return r();let s=t.sender;return this.runInPromptScope(r,s?.trust==="verified"?{caller:s.id}:{})}}}async execute(e,t,r={}){this.ensureOpen();let s=this.scopeStore.getStore()??this.root;if(dd(e)&&!this.offered.has(e))return this.withOpenCalls(s,{error:`the tool "${e}" is not offered; your tools are ${[...this.offered].join(", ")}`});let n;switch(e){case"discover_agents":n=await this.discoverAgents(t);break;case"prompt_agent":n=await this.promptAgent(s,t,r);break;case"wait_agent":n=await this.waitAgent(s,t,r.signal);break;case"answer_agent":n=await this.answerAgent(s,t,r.signal);break;case"cancel_agent":n=await this.cancelAgent(s,t);break;case"list_agent_calls":n=this.listAgentCalls(s);break;default:n={error:`unknown tool "${e}"`}}return this.withOpenCalls(s,n)}async runInPromptScope(e,t={}){this.ensureOpen();let r=new df(!0,t.caller);this.served.add(r);try{return await this.scopeStore.run(r,e)}finally{this.served.delete(r),await this.closeScope(r)}}async close(){if(this.closed)return;if(this.closed=!0,await Promise.all([this.root,...this.served].map((e)=>this.closeScope(e))),this.ownsStaging&&this.staging!==void 0){let e=await this.staging.catch(()=>{return});if(e!==void 0)await _y(e,{recursive:!0,force:!0})}}async discoverAgents(e){let t=Wm(e);if(He(t))return{error:t.error};let r;try{r=await this.discover(t)}catch(o){return{error:`discovery failed: ${Vt(o)}`}}let s=new Map;for(let o of r){let c=o.promptSubject;if(c===this.selfAddress)continue;let h=s.get(c);if(h===void 0)s.set(c,{handle:o,instances:1});else if(h.instances+=1,!h.handle.idSigVerified&&o.idSigVerified)h.handle=o}let n=[];for(let[o,{handle:c,instances:h}]of s){let p={};for(let w of this.extensions){if(w.discoveryFields===void 0)continue;Fi(p,await w.discoveryFields(c),og,"a discovery entry")}n.push({address:o,agent:c.agent,owner:c.owner,name:c.name,description:c.description,identity:c.identity??null,identity_verified:c.idSigVerified,requires_signed_prompts:c.minSenderTrust==="signed",accepts_attachments:c.promptEndpoint.attachmentsOk!==!1,instances:h,...p})}return{agents:n}}async discover(e){let t=await this.agents.discover({...Object.keys(e).length>0?{filter:e}:{},...this.discoverTimeoutMs!==void 0?{timeoutMs:this.discoverTimeoutMs}:{}});for(let r of t){let s=this.known.get(r.promptSubject);if(s===void 0||r.idSigVerified||!s.idSigVerified)this.known.set(r.promptSubject,r)}return t}async lookup(e){let t=this.known.get(e);if(t!==void 0)return t;return await this.discover({}),this.known.get(e)}async promptAgent(e,t,r){let s=Ym(t);if(He(s))return{error:s.error};if(!s.wait&&!this.offered.has("wait_agent"))return{error:'prompt_agent: "wait" cannot be false here; the call waits for the reply or a question'};let{address:n}=s;if(e.closed)return{error:"the prompt you were answering has ended; no call can start in it"};if(n===this.selfAddress)return{error:`"${n}" is your own address; answer the prompt yourself`};let o;try{o=await this.lookup(n)}catch(p){return{error:`could not look up "${n}": ${Vt(p)}`}}if(o===void 0)return{error:this.noAgentAt(n)};if(e.caller!==void 0&&o.identity===e.caller)return{error:`the agent at "${n}" sent the prompt you are answering; answer it rather than prompting it back`};let c=await this.resolveAttachments(s.attachments);if(He(c))return{error:c.error};if(!this.reserve(e)){let{collect:p,stop:w}=this.openCallActions("some","their");return{error:`all ${this.maxCalls} tracked calls are still open; ${w!==void 0?`${p} or ${w}`:p} before you start another`}}let h=!0;try{let p=cg(),w=s.prompt,A={},j={};for(let Pe of this.extensions){if(Pe.beforePrompt===void 0)continue;let be=await Pe.beforePrompt({address:n,prompt:w,attachments:c,target:o,callId:p,label:s.label,toolCallId:r.toolCallId,caller:e.caller});if(!be)continue;if(be.error!==void 0)return{error:be.error};if(be.prompt!==void 0)w=be.prompt;Object.assign(A,be.context),Fi(j,be.fields,ff,"a call's result")}if(r.toolCallId!==void 0)A.toolCallId=r.toolCallId;let O={maxWaitMs:this.maxWaitMs,context:A,...c.length>0?{attachments:c}:{}},K;try{K=await o.prompt(w,O)}catch(Pe){return{error:`the prompt was not sent: ${Vt(Pe)}`}}if(e.closed)return K.cancel(),{error:"the prompt you were answering has ended; no call can start in it"};let N=new ag(p,e,n,o,s.label,!s.wait,j,K);if(e.reserved-=1,h=!1,e.calls.set(p,N),this.read(N),!s.wait)return this.callResult(N);return await this.untilReady(N,r.signal)}finally{if(h)e.reserved-=1}}reserve(e){while(e.calls.size+e.reserved>=this.maxCalls){let t;for(let r of e.calls.values())if(!r.open&&(t===void 0||r.seq<t.seq))t=r;if(t===void 0)return!1;e.calls.delete(t.id)}return e.reserved+=1,!0}async resolveAttachments(e){if(e.length===0)return[];let t=await Promise.all([await this.stagingDir(),...this.attachmentRoots].map((s)=>Xu(s).catch(()=>s))),r=[];for(let s of e){let n;try{n=await Xu(Bs(this.cwd,s))}catch{return new Me(`prompt_agent: the attachment "${s}" does not exist`)}if(!(await Ey(n).catch(()=>{return}))?.isFile())return new Me(`prompt_agent: the attachment "${s}" is not a file`);if(!t.some((c)=>n===c||n.startsWith(fg(c))))return new Me(`prompt_agent: "${s}" is outside the directories you may send files from (${t.join(", ")})`);r.push(n)}return r}async read(e){try{for await(let t of e.stream){if(t.type==="status")continue;if(!e.open){if(t.type==="query")await Di(t);continue}if(t.type==="response"){if(e.text+=t.text,t.attachments!==void 0&&t.attachments.length>0)e.replyFiles.push(...await this.save(e,t.attachments));continue}e.arriving=t;let r=t.attachments!==void 0&&t.attachments.length>0?await this.save(e,t.attachments):[],s=await this.afterReply(e,"question",t.prompt,r);if(!e.open)continue;if(e.arriving=void 0,e.questions.push({event:t,files:r,fields:s}),e.state==="running")this.setState(e,"input_required")}if(e.open)e.replyFields=await this.afterReply(e,"reply",e.text,e.replyFiles),this.finish(e,"completed")}catch(t){if(!e.open)return;let r=t instanceof xf?this.finish(e,"expired",`the call ran past its runtime limit of ${lf(t.maxWaitMs)} and was stopped; the agent may still be working on it`):this.finish(e,"failed",this.failure(e,t));await Promise.all(r.map(Di))}}async save(e,t){let r;try{let s=wt(await this.stagingDir(),e.id);r=await zm(t,s,{maxTotalBytes:Math.max(0,this.maxSavedBytes-e.savedBytes)})}catch(s){throw new Ds(`a file the agent sent could not be saved: ${Vt(s)}`)}return r.map((s)=>{if(s.path!==null)e.savedBytes+=s.sizeBytes;return{filename:s.filename,size_bytes:s.sizeBytes,path:s.path,...s.skipped!==void 0?{skipped:s.skipped}:{}}})}async afterReply(e,t,r,s){let n={};try{for(let o of this.extensions){if(o.afterReply===void 0)continue;let c=await o.afterReply({callId:e.id,address:e.address,target:e.target,kind:t,text:r,attachments:s});Fi(n,c,ff,"a call's result")}}catch(o){if(o instanceof fd)throw this.logger.error(`AgentTools: an extension bug: afterReply set "${o.field}", a field the contract defines; the call fails`,{call_id:e.id,kind:t,field:o.field}),new Ds(`an extension of these tools has a bug (it set "${o.field}" on the ${t}, a field the tools define); the agent at "${e.address}" is not at fault`);throw new Ds(`an extension failed on the ${t}: ${Vt(o)}`)}return n}failure(e,t){if(t instanceof Ds)return t.message;if(t instanceof mf){let r=t.description!==""?` ${t.description}`:"";return`the agent at "${e.address}" answered with an error: ${t.code}${r}`}if(t instanceof gf)return`the agent at "${e.address}" sent nothing for ${lf(t.timeoutMs)}, so the call was given up; the agent may have stopped`;if(t instanceof Error&&t.name==="NoRespondersError")return this.noAgentAt(e.address," any more");if(t instanceof Error&&t.name==="AbortError")return"the client the call ran on was closed";return Vt(t)}setState(e,t){if(e.state=t,t==="input_required")e.seq=++this.seq;e.notify()}finish(e,t,r){if(!e.open)return[];let s=e.awaited;e.state=t,e.error=r,e.endedAt=new Date,e.seq=++this.seq;let n=e.questions.splice(0).map((o)=>o.event);if(e.arriving!==void 0)n.push(e.arriving);if(e.arriving=void 0,e.notify(),e.scope===this.root&&this.onSettled!==void 0){let o=this.onSettled,c=this.callResult(e);(async()=>{try{await o(c,{awaited:s})}catch{this.logger.error("AgentTools onSettled failed",{call_id:e.id})}})()}return n}async cancel(e){if(!e.open)return;let t=this.finish(e,"cancelled");e.stream.cancel(),await Promise.all(t.map(Di))}async closeScope(e){e.closed=!0,await Promise.all([...e.calls.values()].map((t)=>this.cancel(t)))}async untilReady(e,t){while(e.state==="running"){if(t?.aborted){await this.cancel(e);break}await hf([e],void 0,t)}return this.callResult(e)}async waitAgent(e,t,r){let s=Xm(t);if(He(s))return{error:s.error};let n=this.calls(e,s.callIds);if(He(n))return{error:n.error};let o=Date.now()+Math.min(s.timeoutMs??this.maxWaitAgentMs,this.maxWaitAgentMs);for(;;){let c;for(let h of n)if(h.state!=="running"&&(c===void 0||h.seq<c.seq))c=h;if(c!==void 0){let h=c;return{...this.callResult(h),remaining:n.filter((p)=>p!==h&&p.open).map((p)=>p.id)}}if(Date.now()>=o||r?.aborted)return{state:"running",call_ids:n.map((h)=>h.id)};await hf(n,o,r)}}async answerAgent(e,t,r){let s=Zm(t);if(He(s))return{error:s.error};if(s.wait===!1&&!this.offered.has("wait_agent"))return{error:'answer_agent: "wait" cannot be false here; the call waits for the reply or the next question'};let n=e.calls.get(s.callId);if(n===void 0)return{error:this.unknownCalls([s.callId])};let o=n.questions[0];if(n.state!=="input_required"||o===void 0)return{error:`call "${n.id}" has no open question: it is ${n.state}`+(n.open?"":this.ifOffered("wait_agent","; wait_agent returns its result"))};if(n.questions.shift(),n.questions.length>0)this.setState(n,"input_required");else this.setState(n,"running");try{await o.event.reply(s.answer)}catch(c){if(n.open)n.questions.unshift(o),this.setState(n,"input_required");return{error:`the answer could not be sent: ${Vt(c)}`}}if(!(s.wait??!n.detached))return this.callResult(n);return this.untilReady(n,r)}async cancelAgent(e,t){let r=Qm(t);if(He(r))return{error:r.error};let s=[];for(let n of r.callIds){let o=e.calls.get(n);if(o===void 0){s.push({call_id:n,error:this.unknownCalls([n])});continue}await this.cancel(o),s.push(this.callResult(o))}return{calls:s}}listAgentCalls(e){return{calls:[...e.calls.values()].map((t)=>({call_id:t.id,...t.label!==void 0?{label:t.label}:{},address:t.address,state:t.state,started_at:t.startedAt.toISOString(),...t.endedAt!==void 0?{ended_at:t.endedAt.toISOString()}:{}}))}}calls(e,t){let r=t.filter((s)=>!e.calls.has(s));if(r.length>0)return new Me(this.unknownCalls(r));return t.map((s)=>e.calls.get(s))}ifOffered(e,t){return this.offered.has(e)?t:""}unknownCalls(e){return`${e.map((t)=>`"${t}"`).join(", ")}: no such call in your calls`+this.ifOffered("list_agent_calls","; list_agent_calls shows them")}noAgentAt(e,t=""){return`no agent answers at "${e}"${t}`+this.ifOffered("discover_agents","; call discover_agents for the current list")}openCallActions(e,t){return{collect:this.offered.has("wait_agent")?`collect ${e} with wait_agent`:`answer ${t} questions with answer_agent`,stop:this.offered.has("cancel_agent")?`stop ${e} with cancel_agent`:void 0}}callResult(e){let t={...e.fields,call_id:e.id,state:e.state,...e.label!==void 0?{label:e.label}:{}},r=e.text!==""?{partial_reply:e.text}:{},s=e.replyFiles.length>0?{attachments:[...e.replyFiles]}:{};switch(e.state){case"running":return t;case"input_required":{let n=e.questions[0];return{...t,...n.fields,question:n.event.prompt,...n.files.length>0?{attachments:[...n.files]}:{}}}case"completed":return{...t,...e.replyFields,reply:e.text,...s};case"cancelled":return{...t,...r,...s};case"failed":case"expired":return{...t,error:e.error??"the call failed",...r,...s}}}withOpenCalls(e,t){let r=0;for(let h of e.calls.values())if(h.open)r+=1;if(r===0)return t;let s=r===1?"1 call you started is":`${r} calls you started are`,{collect:n,stop:o}=this.openCallActions(r===1?"it":"them",r===1?"its":"their"),c=e.served?`${s} still open. Calls end with the prompt you are answering: ${n} before you answer.`:`${s} still open: ${o!==void 0?`${n}, or ${o}`:n}.`;return{...t,open_calls:r,open_calls_note:c}}stagingDir(){return this.staging??=(async()=>{if(this.stagingOption!==void 0){let t=this.stagingOption;return await bf(t,{recursive:!0,mode:448}),t}let e=await Sy(wt(Ay(),"agent-tools-"));return this.ownsStaging=!0,e})().catch((e)=>{throw this.staging=void 0,e}),this.staging}ensureOpen(){if(this.closed)throw Error("AgentTools: the helper is closed")}},df=class{constructor(e,t){this.served=e,this.caller=t}served;caller;calls=new Map;reserved=0;closed=!1},ag=class{constructor(e,t,r,s,n,o,c,h){this.id=e,this.scope=t,this.address=r,this.target=s,this.label=n,this.detached=o,this.fields=c,this.stream=h,this.startedAt=new Date}id;scope;address;target;label;detached;fields;stream;state="running";seq=0;startedAt;endedAt;text="";replyFiles=[];questions=[];arriving;error;replyFields={};savedBytes=0;waiters=new Set;get open(){return this.state==="running"||this.state==="input_required"}get awaited(){return this.waiters.size>0}watch(e){this.waiters.add(e)}unwatch(e){this.waiters.delete(e)}notify(){let e=[...this.waiters];this.waiters.clear();for(let t of e)t()}},Ds=class extends Error{},fd=class extends Error{constructor(e,t){super(`AgentTools: an extension may not set "${e}" on ${t}`);this.field=e}field};function hf(e,t,r){return new Promise((s)=>{let n,o=()=>{for(let c of e)c.unwatch(o);if(n!==void 0)clearTimeout(n);r?.removeEventListener("abort",o),s()};for(let c of e)c.watch(o);if(t!==void 0)n=setTimeout(o,Math.max(0,t-Date.now()));if(r?.addEventListener("abort",o,{once:!0}),r?.aborted)o()})}async function Di(e){try{await e.reply(ig)}catch{}}function Fi(e,t,r,s){if(t===void 0||t===null)return;for(let[n,o]of Object.entries(t)){if(r.includes(n))throw new fd(n,s);e[n]=o}}function cg(){return`call_${Ty(6).toString("hex")}`}function dd(e){return zs.includes(e)}function ug(e){if(e===void 0)return new Set(zs);for(let s of e)if(!dd(s))throw RangeError(`AgentTools: tools names "${s}", which is not one of ${zs.join(", ")}`);let t=new Set(zs.filter((s)=>e.includes(s)));if(t.size===0)throw RangeError("AgentTools: tools names no tool; a role that must not delegate needs no AgentTools");let r=[...t].filter((s)=>s!=="discover_agents");if(!t.has("prompt_agent")&&r.length>0)throw RangeError(`AgentTools: tools offers ${r.join(", ")} without prompt_agent, which starts the calls `+(r.length===1?"it works on":"they work on"));if(t.has("prompt_agent")&&!t.has("answer_agent"))throw RangeError("AgentTools: tools offers prompt_agent without answer_agent, so a question the prompted agent asks would reach a model with no way to answer it, and the asking agent would wait out its timeout");return t}function Vt(e){return e instanceof Error?e.message:String(e)}function lf(e){if(e>=60000&&e%60000===0){let t=e/60000;return t===1?"1 minute":`${t} minutes`}if(e>=1000&&e%1000===0){let t=e/1000;return t===1?"1 second":`${t} seconds`}return`${e} ms`}function fg(e){return e.endsWith(Zu)?e:e+Zu}function Bi(e,t){if(t===void 0)return;if(!(t>0))throw RangeError(`AgentTools: ${e} must be greater than 0 (got ${t})`);return t}function pf(e,t){if(t===void 0)return;if(!(t>=0))throw RangeError(`AgentTools: ${e} must be 0 or more (got ${t})`);return t}var dg="_INBOX.agents";function po(){return oe.createInbox(dg)}async function ov(e,t={}){if(bg(e),t.identity!==void 0&&t.identity!=="off"&&t.identity!=="signed")throw new ye('connection bundle identity must be "off" or "signed"');let r=e.context;if(typeof r==="string"){let c=await zy(r),h;try{h=yg(c)}catch(p){throw c.wipe(),p}if(t.identity!=="signed")return Fs(h.connectionOptions,void 0,()=>h.wipe());try{let p=hg(c.name,h.auth);return Fs(h.connectionOptions,p,()=>h.wipe())}catch(p){throw h.wipe(),p}}let s=e,n=Af(s.url),o=await lg(s);if(o!==void 0)delete n.token,delete n.user,delete n.pass,n.authenticator=o.kind==="creds"?oe.credsAuthenticator(o.bytes):oe.nkeyAuthenticator(o.bytes);if(t.identity!=="signed")return Fs(n,void 0,()=>o?.bytes.fill(0));if(o===void 0)throw new ye("signed identity requires URL connection credentials with a user seed (`creds` or `nkey`)");try{let c=o.kind==="creds"?If(new TextDecoder().decode(o.bytes)):Qi(o.bytes);return Fs(n,c,()=>o.bytes.fill(0))}catch(c){throw o.bytes.fill(0),c}}function hg(e,t){if(t.kind==="creds")return If(new TextDecoder().decode(t.bytes));if(t.kind==="nkey")return Qi(t.bytes);if(t.kind==="jwt-seed")return Nf(t.seed,t.jwt);throw new ye(`NATS context "${e}" has no user seed; signed identity requires creds, nkey, or user_jwt with user_seed in that same context`)}async function lg(e){if(e.creds!==void 0){let t=await Vs("creds",Jt(e.creds));return{kind:"creds",bytes:new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}}if(e.nkey!==void 0){let t=await Vs("nkey",Jt(e.nkey)),r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);try{return{kind:"nkey",bytes:eo(r)}}finally{r.fill(0)}}return}function Fs(e,t,r){let s=!1,n=()=>{if(s)return;s=!0;try{t?.wipe?.()}finally{try{r()}finally{pg(e)}}},o=t===void 0?"off":"signed",c=Object.create(null);if(Object.defineProperty(c,"connectionOptions",{value:e,enumerable:!1}),t!==void 0)Object.defineProperty(c,"signer",{value:t,enumerable:!1});return Object.defineProperty(c,"wipe",{value:n,enumerable:!1}),Object.defineProperty(c,"toJSON",{value:()=>({identity:o}),enumerable:!1}),Object.defineProperty(c,"toString",{value:()=>`NatsConnectionBundle(${o})`,enumerable:!1}),Object.defineProperty(c,Symbol.for("nodejs.util.inspect.custom"),{value:()=>`NatsConnectionBundle(${o})`,enumerable:!1}),Object.freeze(c)}function pg(e){delete e.authenticator,delete e.token,delete e.user,delete e.pass,delete e.tls}function yg(e){if(e.auth.kind!=="nkey"&&e.auth.kind!=="jwt-seed")return{connectionOptions:e.connectionOptions,auth:e.auth,wipe:()=>e.wipe()};let t=eo(e.auth.kind==="nkey"?e.auth.bytes:e.auth.seed),r=e.auth.kind==="nkey"?{kind:"nkey",bytes:t}:{kind:"jwt-seed",jwt:e.auth.jwt,seed:t};e.connectionOptions.authenticator=r.kind==="nkey"?oe.nkeyAuthenticator(t):oe.jwtAuthenticator(r.jwt,t),e.wipe();let s=!1;return{connectionOptions:e.connectionOptions,auth:r,wipe(){if(s)return;s=!0,t.fill(0)}}}function bg(e){if(typeof e!=="object"||e===null||Array.isArray(e))throw new Ne("connection source must be an object");let t=e;for(let n of["context","url","creds","nkey"]){let o=t[n];if(o!==void 0&&(typeof o!=="string"||o.length===0))throw new Ne(`connection source \`${n}\` must be a non-empty string`)}let r=typeof t.context==="string",s=typeof t.url==="string";if(r===s)throw new Ne("connection source must select exactly one of `context` or `url`");if(r&&(t.creds!==void 0||t.nkey!==void 0))throw new Ne("a context connection cannot also select direct `creds` or `nkey` credentials");if(t.creds!==void 0&&t.nkey!==void 0)throw new Ne("a URL connection must select at most one of `creds` or `nkey`")}var yf=Object.freeze({maxReconnectAttempts:-1,reconnectTimeWait:2000,reconnectJitter:200,waitOnFirstConnect:!0});function av(e={}){let t={...e};for(let r of Object.keys(yf))if(t[r]===void 0)t[r]=yf[r];return t}var yo=Object.freeze({major:0,minor:3});var bd=wr(Ri(),1);var md=wr(Ci(),1);function hd(e,t,r,s={}){return Object.freeze({agent:e.agent,owner:e.owner,instanceId:r,ts:new Date().toISOString(),intervalS:t,extras:Object.freeze({...s.extras??{}}),...s.session!==void 0?{session:s.session}:{},...s.protocolVersion!==void 0?{protocolVersion:s.protocolVersion}:{},...s.endpoints!==void 0?{endpoints:s.endpoints}:{}})}function ld(e){let t={agent:e.agent,owner:e.owner,instance_id:e.instanceId,ts:e.ts,interval_s:e.intervalS,...e.extras};if(e.session!==void 0)t.session=e.session;if(e.protocolVersion!==void 0)t.protocol_version=e.protocolVersion;if(e.endpoints!==void 0){let r={};for(let[s,n]of Object.entries(e.endpoints))r[s]={subject:n.subject,metadata:{...n.metadata}};t.endpoints=r}return new TextEncoder().encode(JSON.stringify(t))}async function mg(e){return oo({signer:e.sender.signer,id:e.sender.id,sub:e.subject,payload:e.data,ts:e.ts,...e.nonce!==void 0?{nonce:e.nonce}:{}})}async function gg(e){let t=md.headers();return t.set(jt,It(await mg(e))),t}var gd="any",mo=30000,xg=1e5,wg=class{#e;#t;#o;#s=new Map;#r=new Map;#n=!1;constructor(e={}){this.#e=e.replayWindowMs??mo,this.#t=e.maxEntries??xg,this.#o=e.logger}get size(){return this.#s.size}has(e,t,r=Date.now()){this.sweep(r);let s=this.#s.get(`${e}.${t}`);return s!==void 0&&s>r}record(e,t,r,s=Date.now()){this.sweep(s);let n=`${e}.${t}`,o=this.#s.get(n);if(o!==void 0&&o>s)return!1;let c=r+this.#e;if(c<=s)return!0;let h=Math.floor(c/1000);this.#s.set(n,c);let p=this.#r.get(h);if(!p)p=new Set,this.#r.set(h,p);return p.add(n),this.#i(),!0}sweep(e=Date.now()){let t=Math.floor(e/1000);for(let[r,s]of this.#r){if(r>=t)continue;for(let n of s)this.#s.delete(n);this.#r.delete(r)}if(this.#n&&this.#s.size<=this.#t/2)this.#n=!1}#i(){if(this.#s.size<=this.#t)return;if(!this.#n)this.#n=!0,this.#o?.warn("nonce cache reached its cap; evicting the oldest entries \u2014 evicted nonces may be replayed within the ts window",{maxEntries:this.#t});let e=[...this.#r.keys()].sort((t,r)=>t-r);for(let t of e){if(this.#s.size<=this.#t)break;let r=this.#r.get(t);if(r)for(let s of r)this.#s.delete(s);this.#r.delete(t)}}},vg=Object.freeze({debug:()=>{return},info:()=>{return},warn:()=>{return},error:()=>{return}}),_g=class{#e;#t;#o;#s;#r;#n;#i;#c;constructor(e={}){this.#e=e.minSenderTrust??gd,this.#t=e.replayWindowMs??mo,this.#o=e.accountTokenPosition,this.#s=e.acceptSender,this.#r=e.logger??vg,this.#n=e.nonceCache??new wg({replayWindowMs:this.#t,logger:this.#r}),this.#i=e.operatorAttested??!1,this.#c=e.resolver}get minSenderTrust(){return this.#e}get nonceCache(){return this.#n}get operatorAttested(){return this.#i}async classify(e){try{return{sender:await Bf(e,"live",{replayWindowMs:this.#t,...this.#o!==void 0?{accountTokenPosition:this.#o}:{},nonceSeen:(r,s)=>this.#n.has(r,s),operatorAttested:this.#i,...this.#c!==void 0?{resolver:this.#c}:{}})}}catch(t){if(t instanceof qe)return{code:400,description:"malformed Agent-Sender header",detail:t.message};if(t instanceof Yi)return{code:t.code,description:t.description,detail:t.detail};throw t}}async admitPrompt(e){let t=await this.classify(e);if("code"in t)return this.#u(e,t);let r=t.sender;if(this.#e==="signed"&&r?.trust!=="verified")return this.#u(e,{code:401,description:no,detail:`endpoint requires a verified sender; got ${Nt(r)}`});if(r?.trust==="verified"){let{user:s,nonce:n,ts:o}=r.header;if(n!==void 0&&o!==void 0&&!this.#n.record(s,n,Zs(o)))return this.#u(e,{code:401,description:Xs,detail:`nonce already seen for ${s}`})}if(this.#s){let s;try{s=await this.#s(r)}catch{return this.#r.error("acceptSender hook threw; request not served",{subject:e.subject,sender:Nt(r),error:"hook error"}),{ok:!1,code:500,description:"server error",detail:"acceptSender hook threw"}}if(!s)return this.#u(e,r?.trust==="verified"?{code:403,description:Xs,detail:`verified sender not accepted: ${Nt(r)}`}:{code:401,description:no,detail:`unauthenticated sender not accepted: ${Nt(r)}`})}return{ok:!0,sender:r}}async classifyStatus(e){let t=await this.classify(e);if("code"in t){this.#r.warn("status request: Agent-Sender rejected (reply sent anyway)",{subject:e.subject,code:t.code,reason:t.detail});return}let r=t.sender;if(r?.trust==="verified"){let{user:s,nonce:n,ts:o}=r.header;if(n!==void 0&&o!==void 0&&!this.#n.record(s,n,Zs(o))){this.#r.warn("status request: nonce replayed (reply sent anyway)",{subject:e.subject,sender:Nt(r)});return}}return r}#u(e,t){return this.#r.warn("prompt request refused on sender identity",{subject:e.subject,code:t.code,reason:t.detail}),{ok:!1,...t}}},Eg=class extends Error{constructor(e,t){if(!Number.isInteger(e)||e<400||e>599)throw RangeError(`RequestRejectedError: code must be an integer in 400\u2013599, got ${e}`);super(`request rejected (${e}): ${t}`);this.code=e,this.description=t,this.name="RequestRejectedError"}code;description};function tn(e){let t;switch(e.type){case"response":t=Sg(e);break;case"status":t={type:"status",data:e.status};break;case"query":t=Ag(e);break}return new TextEncoder().encode(JSON.stringify(t))}function Sg(e){if(e.attachments===void 0||e.attachments.length===0)return{type:"response",data:e.text};return{type:"response",data:{text:e.text,attachments:e.attachments.map((t)=>({filename:t.filename,content:t.content}))}}}function Hv(e,t,r={}){let s=r.reserveBytes??32,n=r.safetyDivisor??2,o=Math.max(64,Math.floor((t-s)/n));if(e.length===0)return[];let c=[],h=new TextEncoder,p="",w=0;for(let A of e){let j=h.encode(A).byteLength;if(w+j>o&&p.length>0)c.push(p),p="",w=0;p+=A,w+=j}if(p.length>0)c.push(p);return c}function Ag(e){let t={id:e.id,reply_subject:e.replySubject,prompt:e.prompt};if(e.attachments!==void 0&&e.attachments.length>0)t.attachments=e.attachments.map((r)=>({filename:r.filename,content:r.content}));return{type:"query",data:t}}var pd=`${yo.major}.${yo.minor}`,Og="1MB",Pg=!0,Tg=30,jg=30,Ig="0.0.1";function Ng(){return crypto.randomUUID().replace(/-/g,"")}var Cg=class{#e;#t;sender;constructor(e,t,r=void 0){this.#e=e,this.#t=t,this.sender=r}send(e){let t=typeof e==="string"?{type:"response",text:e}:e;return this.#e.respond(tn(t)),Promise.resolve()}async ask(e,t){let r=t.signal;r?.throwIfAborted();let s=typeof e==="string"?e:e.prompt,o=[...(typeof e==="string"?void 0:e.attachments)??[],...t.attachments??[]],c=po(),h=this.#t.subscribe(c,{max:1});await this.#t.flush();let p={type:"query",id:Ng(),replySubject:c,prompt:s,...o.length>0?{attachments:o.map((j)=>({filename:j.filename,content:co(j.content)}))}:{}};this.#e.respond(tn(p));let w,A;try{let j=(async()=>{for await(let N of h)return uo(N.data);throw Error(`query ${p.id} reply subscription closed before any reply arrived`)})();j.catch(()=>{});let O=new Promise((N,Pe)=>{w=setTimeout(()=>Pe(Error(`query ${p.id} on ${c} timed out after ${t.timeoutMs}ms`)),t.timeoutMs)}),K=new Promise((N,Pe)=>{if(!r)return;if(A=()=>Pe(r.reason instanceof Error?r.reason:Error("query aborted")),r.aborted)A();else r.addEventListener("abort",A,{once:!0})});return await Promise.race([j,O,K])}finally{if(w!==void 0)clearTimeout(w);if(A)r?.removeEventListener("abort",A);h.unsubscribe()}}async callerListening(e={}){let t=po(),r,s=new Promise((c)=>{r=c}),n=this.#t.subscribe(t,{max:1,callback:(c,h)=>{if(!c&&h.data.length===0&&h.headers?.code===503)r()}}),o;try{await this.#t.flush();let c={type:"status",status:"ack"};this.#e.respond(tn(c),{reply:t});let h=new Promise((p)=>{o=setTimeout(()=>p(!0),e.timeoutMs??500)});return await Promise.race([s.then(()=>!1),h])}catch{return!1}finally{if(o!==void 0)clearTimeout(o);n.unsubscribe()}}},zv=class{#e;#t;#o;#s;#r;#n;#i;#c;#u;#a;#d;#h;#p=null;#f=null;#l=null;#y=null;#b=!1;constructor(e){let t=e.heartbeatIntervalS??Tg;if(t<=0)throw Error("AgentService: heartbeatIntervalS must be > 0 (heartbeat is mandatory in v0.3)");let r=e.keepaliveIntervalS===void 0?jg:e.keepaliveIntervalS;if(r!==null&&r<=0)throw Error("AgentService: keepaliveIntervalS must be > 0 or null (null disables keep-alive)");let s=e.minSenderTrust??gd;if(s!=="any"&&s!=="signed")throw Error('AgentService: minSenderTrust must be "any" or "signed"');let n=e.replayWindowMs??mo;if(!(n>0))throw Error("AgentService: replayWindowMs must be > 0");let o=ho(e.resolveTtlMs);if(e.operatorAttested!==void 0&&typeof e.operatorAttested!=="boolean")throw Error("AgentService: operatorAttested must be a boolean");this.#e=e,this.#t=Qf.new(e.agent,e.owner,e.name,e.subjectToken!==void 0?{subjectToken:e.subjectToken}:{}),this.#o=t,this.#s=r,this.#r=e.logger??lr,this.#n=s,this.#c=new lo(e.nc,{ttlMs:o}),this.#u=Object.freeze([...e.interceptors??[]]),this.#i=new _g({minSenderTrust:s,replayWindowMs:n,...e.acceptSender!==void 0?{acceptSender:e.acceptSender}:{},logger:this.#r,operatorAttested:e.operatorAttested??!1,resolver:(c)=>this.#c.resolve(c)})}get identity(){return this.#a}get minSenderTrust(){return this.#n}get operatorAttested(){return this.#i.operatorAttested}get subject(){return this.#t}get instanceId(){if(!this.#f)throw Error("AgentService.instanceId: service not started");return this.#f.info().id}get service(){if(!this.#f)throw Error("AgentService.service: service not started \u2014 call start() first");return this.#f}onPrompt(e){this.#p=e}#x(){let e=this.#e.nc.info?.max_payload??0;if(this.#e.maxPayload===void 0)return e>0?Zi(e):Og;let t=this.#e.maxPayload,r=Xi(t);if(e<=0||r<=e)return t;let s=Zi(e);return this.#r.warn(`AgentService: maxPayload=${t} (${r} bytes) exceeds server limit ${s} (${e} bytes); clamping advertised value to ${s} \u2014 anything larger would be rejected by the broker before reaching the handler`,{maxPayload:t,serverMaxPayload:e}),s}async start(){if(this.#p===null)throw Error("AgentService.start: register a prompt handler via onPrompt() first");if(this.#f!==null)throw Error("AgentService.start: already started");let e=this.#e.extraEndpoints??[];if(e.length>0){let h=new Set([yr,Qs]);for(let p of e){if(h.has(p.name))throw Error(`AgentService.start: extraEndpoints[].name=${JSON.stringify(p.name)} collides with a protocol-reserved or already-listed endpoint name`);h.add(p.name)}}let t=this.#e.identity?.signer;this.#a=void 0;let r;if(this.#e.identity!==void 0)try{r=await hr(this.#e.nc,t?{signer:t}:{})}catch(h){if(t)throw h;this.#r.warn("AgentService: starting without identity metadata",{reason:h instanceof Error?h.message:String(h)})}this.#a=r,this.#d=r!==void 0&&t?{id:r,signer:t}:void 0;let s=new bd.Svcm(this.#e.nc),n={...this.#e.extraMetadata,agent:this.#t.agent,owner:this.#t.owner,protocol_version:pd};if(this.#e.session!==void 0)n.session=this.#e.session;if(r!==void 0)if(n[ze.userNkey]=ht(r),n[ze.account]=Lr(r),t)n[ze.idSig]=await td({signer:t,id:r,agent:this.#t.agent,owner:this.#t.owner,promptSubject:this.#t.prompt});else delete n[ze.idSig];else delete n[ze.userNkey],delete n[ze.account],delete n[ze.idSig];this.#f=await s.add({name:pr,version:this.#e.version??Ig,description:this.#e.description??`${this.#t.agent} agent ${this.#t.name}`,metadata:n});let c={max_payload:this.#x(),attachments_ok:this.#e.attachmentsOk??Pg?"true":"false",[fo]:this.#n};this.#f.addEndpoint(yr,{subject:this.#t.prompt,queue:Hf,handler:(h,p)=>{if(h)return;this.#E(p)},metadata:c}),this.#h={subject:this.#t.prompt,metadata:{...c}},this.#f.addEndpoint(Qs,{subject:this.#t.status,queue:zf,handler:(h,p)=>{if(h)return;this.#_(p)}});for(let h of e)this.#f.addEndpoint(h.name,{subject:h.subject,...h.queue!==void 0?{queue:h.queue}:{},handler:h.handler,...h.metadata!==void 0?{metadata:h.metadata}:{}});await this.#e.nc.flush(),await this.#v()}async stop(){if(this.#b=!0,this.#l!==null)clearInterval(this.#l),this.#l=null;if(this.#f!==null)await this.#f.stop(),this.#f=null}#m(){let e={protocolVersion:pd};if(this.#e.session!==void 0)e.session=this.#e.session;if(this.#h!==void 0)e.endpoints={[yr]:this.#h};let t=this.#w();if(t!==void 0)e.extras={...t};return e}#w(){let e=this.#e.heartbeatExtras;if(e===void 0)return;let t;try{t=e()}catch{this.#r.error("heartbeatExtras provider failed; publishing without extras",{subject:this.#t.heartbeat,error:"exception"});return}let r=Object.keys(t).filter((s)=>kg.has(s));if(r.length>0){this.#r.error("heartbeatExtras reuse \xA78.3 field names; publishing without extras",{subject:this.#t.heartbeat,fields:r.sort().join(",")});return}try{JSON.stringify(t)}catch{this.#r.error("heartbeatExtras do not serialize; publishing without extras",{subject:this.#t.heartbeat,error:"exception"});return}return t}async#g(){let e=this.#f;if(!e)return;let t=hd(this.#t,this.#o,e.info().id,this.#m()),r=ld(t),s=this.#d,n;if(s!==void 0){try{n=await gg({sender:s,subject:this.#t.heartbeat,ts:t.ts,data:r})}catch(o){this.#r.error("heartbeat signing failed; publishing unsigned",{subject:this.#t.heartbeat,reason:o instanceof Error?o.message:String(o)})}if(this.#b)return}this.#e.nc.publish(this.#t.heartbeat,r,n!==void 0?{headers:n}:{})}async#v(){this.#b=!1;let e=()=>{if(this.#y!==null){this.#r.warn("heartbeat skipped: the previous beat is still being signed",{subject:this.#t.heartbeat});return}this.#y=this.#g().catch((t)=>{this.#r.error("heartbeat publish failed",{subject:this.#t.heartbeat,reason:t instanceof Error?t.message:String(t)})}).finally(()=>{this.#y=null})};await this.#g(),this.#l=setInterval(e,this.#o*1000),this.#l.unref?.()}async#_(e){let t=this.#f;if(!t)return;try{let r=await this.#i.classifyStatus(e);this.#r.debug("status request",{subject:e.subject,sender:Nt(r)});let s=hd(this.#t,this.#o,t.info().id,this.#m());e.respond(ld(s))}catch{this.#r.error("status handler failed",{subject:e.subject,error:"exception"});try{e.respondError(500,"status handler error")}catch{}}}async#E(e){let t=this.#p;if(!t)return;let r;try{r=uo(e.data)}catch(j){let O=j instanceof pe?j.message:"malformed prompt envelope";try{e.respondError(400,bo(O))}catch{}en(e);return}let s;try{let j=await this.#i.admitPrompt(e);if(!j.ok){try{e.respondError(j.code,bo(j.description))}catch{}en(e);return}s=j.sender}catch{this.#r.error("sender classification failed",{subject:e.subject,error:"exception"});try{e.respondError(500,"sender classification error")}catch{}en(e);return}this.#r.debug("prompt request",{subject:e.subject,sender:Nt(s)});let n=new Cg(e,this.#e.nc,s),o=!1,c=!1,h=null,p=()=>{if(h!==null)clearInterval(h),h=null},w=async()=>{if(o)throw Error("request interceptor called next() more than once");o=!0,h=this.#S(e),await t(r,n),c=!0},A={envelope:r,sender:s,subject:e.subject,headers:e.headers};try{if(await Mg(this.#u,A,w),!o)throw Error("request interceptor returned without calling next()")}catch(j){if(p(),c){this.#r.error("request interceptor failed after the handler completed; the reply is kept",{subject:e.subject,error:"exception"});return}let O=Rg(j);if(O===void 0)this.#r.error("prompt handler failed",{subject:e.subject,error:"exception"});else this.#r.warn("prompt request refused",{subject:e.subject,code:O[0]});try{let[K,N]=O??[500,"handler error"];e.respondError(K,bo(N))}catch{}}finally{p(),en(e)}}#S(e){let r=tn({type:"status",status:"ack"});try{e.respond(r)}catch{}if(this.#s===null)return null;let s=this.#s*1000,n=setInterval(()=>{try{e.respond(r)}catch{clearInterval(n)}},s);return n.unref?.(),n}},kg=new Set(["agent","owner","session","instance_id","ts","interval_s","protocol_version","endpoints"]);function Mg(e,t,r){let s=(n)=>{let o=e[n];if(o===void 0)return r();return Promise.resolve(o.aroundRequest(t,()=>s(n+1)))};return s(0)}function Rg(e){if(e instanceof Eg||e instanceof Error&&e.name==="RequestRejectedError"){let{code:t,description:r}=e;return[t,r]}if(e instanceof pe||e instanceof Error&&e.name==="ProtocolError")return[400,e.message];return}function en(e){try{e.respond(new Uint8Array(0))}catch{}}var yd=200;function bo(e){let t=e.split(/\r?\n/).map((r)=>r.trim()).filter((r)=>r.length>0).join(" | ");if(t.length>yd)return t.slice(0,yd-3)+"...";return t}
|
|
38
|
+
export{wr as a,H as b,qg as c,oy as d,Ci as e,ct as f,Ne as g,ye as h,Gs as i,Xi as j,Hy as k,lr as l,Qf as m,ze as n,sv as o,Nt as p,zs as q,nv as r,iv as s,ov as t,av as u,_g as v,Eg as w,Hv as x,Og as y,zv as z};
|