@synadia-ai/agent-fabric-pi 0.2.0 → 0.3.0
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/BUILD +3 -3
- package/README.md +4 -1
- package/dist/chunk-9jcwbjk5.js +37 -0
- package/dist/fabric.js +4 -4
- package/dist/nats-channel.js +4 -4
- package/package.json +1 -1
- package/skill/scratchpad/SKILL.md +87 -6
- package/skill/scratchpad/scripts/sp +13 -7
- package/dist/chunk-sjpe67s3.js +0 -37
package/dist/chunk-sjpe67s3.js
DELETED
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
import{createRequire as mh}from"node:module";var fh=Object.create;var{getPrototypeOf:hh,defineProperty:Po,getOwnPropertyNames:dh}=Object;var lh=Object.prototype.hasOwnProperty;function ph(e){return this[e]}var bh,yh,br=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var s=t?bh??=new WeakMap:yh??=new WeakMap,o=s.get(e);if(o)return o}r=e!=null?fh(hh(e)):{};let c=t||!e||!e.__esModule?Po(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let d of dh(e))if(!lh.call(c,d))Po(c,d,{get:ph.bind(e,d),enumerable:!0})}if(n)s.set(e,c);return c};var z=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var To=mh(import.meta.url);var Ge=z(function(Io){Object.defineProperty(Io,"__esModule",{value:!0});Io.TD=Io.TE=Io.Empty=void 0;Io.encode=xh;Io.decode=wh;Io.Empty=new Uint8Array(0);Io.TE=new TextEncoder;Io.TD=new TextDecoder;function gh(...e){let t=0;for(let s=0;s<e.length;s++)t+=e[s].length;let r=new Uint8Array(t),n=0;for(let s=0;s<e.length;s++)r.set(e[s],n),n+=e[s].length;return r}function xh(...e){let t=[];for(let r=0;r<e.length;r++)t.push(Io.TE.encode(e[r]));if(t.length===0)return Io.Empty;if(t.length===1)return t[0];return gh(...t)}function wh(e){if(!e||e.length===0)return"";return Io.TD.decode(e)}});var Ve=z(function(Co){Object.defineProperty(Co,"__esModule",{value:!0});Co.errors=Co.PermissionViolationError=Co.NoRespondersError=Co.TimeoutError=Co.RequestError=Co.ProtocolError=Co.ConnectionError=Co.DrainingConnectionError=Co.ClosedConnectionError=Co.AuthorizationError=Co.UserAuthenticationExpiredError=Co.InvalidOperationError=Co.InvalidArgumentError=Co.InvalidSubjectError=void 0;class ps extends Error{constructor(e,t){super(`illegal subject: '${e}'`,t);this.name="InvalidSubjectError"}}Co.InvalidSubjectError=ps;class Vr 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((n)=>`'${n}'`),e=e.join(",");else e=`'${e}'`;return new Vr(`${e} ${t}`,r)}}Co.InvalidArgumentError=Vr;class bs extends Error{constructor(e,t){super(e,t);this.name="InvalidOperationError"}}Co.InvalidOperationError=bs;class Jr extends Error{constructor(e,t){super(e,t);this.name="UserAuthenticationExpiredError"}static parse(e){if(e.toLowerCase().indexOf("user authentication expired")!==-1)return new Jr(e);return null}}Co.UserAuthenticationExpiredError=Jr;class Wr 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 n=0;n<t.length;n++)if(r.indexOf(t[n])!==-1)return new Wr(e);return null}}Co.AuthorizationError=Wr;class ys extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}Co.ClosedConnectionError=ys;class ms extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}Co.DrainingConnectionError=ms;class gs extends Error{constructor(e,t){super(e,t);this.name="ConnectionError"}}Co.ConnectionError=gs;class xs extends Error{constructor(e,t){super(e,t);this.name="ProtocolError"}}Co.ProtocolError=xs;class ws extends Error{constructor(e="",t){super(e,t);this.name="RequestError"}isNoResponders(){return this.cause instanceof Yr}}Co.RequestError=ws;class vs extends Error{constructor(e){super("timeout",e);this.name="TimeoutError"}}Co.TimeoutError=vs;class Yr extends Error{subject;constructor(e,t){super(`no responders: '${e}'`,t);this.subject=e,this.name="NoResponders"}}Co.NoRespondersError=Yr;class Xr extends Error{operation;subject;queue;constructor(e,t,r,n,s){super(e,s);this.name="PermissionViolationError",this.operation=t,this.subject=r,this.queue=n}static parse(e){if((e?e.toLowerCase():"").indexOf("permissions violation")===-1)return null;let r="publish",n="",s=void 0,o=e.match(/(Publish|Subscription) to "(\S+)"/);if(o){if(r=o[1].toLowerCase(),n=o[2],r==="subscription"){let c=e.match(/using queue "(\S+)"/);if(c)s=c[1]}}return new Xr(e,r,n,s)}}Co.PermissionViolationError=Xr;Co.errors={AuthorizationError:Wr,ClosedConnectionError:ys,ConnectionError:gs,DrainingConnectionError:ms,InvalidArgumentError:Vr,InvalidOperationError:bs,InvalidSubjectError:ps,NoRespondersError:Yr,PermissionViolationError:Xr,ProtocolError:xs,RequestError:ws,TimeoutError:vs,UserAuthenticationExpiredError:Jr}});var tt=z(function($o){Object.defineProperty($o,"__esModule",{value:!0});$o.SimpleMutex=$o.Perf=void 0;$o.extend=$h;$o.render=Uh;$o.timeout=Lh;$o.delay=Dh;$o.deadline=Fh;$o.deferred=Es;$o.debugDeferred=Bh;$o.shuffle=Kh;$o.collect=Hh;$o.jitter=qo;$o.backoff=zh;$o.nanos=Gh;$o.millis=Vh;$o.randomToken=Yh;var qh=Ge(),_s=Ve();function $h(e,...t){for(let r=0;r<t.length;r++){let n=t[r];Object.keys(n).forEach(function(s){e[s]=n[s]})}return e}function Uh(e){return qh.TD.decode(e).replace(/\n/g,"␊").replace(/\r/g,"␍")}function Lh(e,t=!0){let r=t?new _s.TimeoutError:null,n,s,o=new Promise((c,d)=>{n={cancel:()=>{if(s)clearTimeout(s)}},s=setTimeout(()=>{if(r===null)d(new _s.TimeoutError);else d(r)},e)});return Object.assign(o,n)}function Dh(e=0){let t,r=new Promise((n)=>{let s=setTimeout(()=>{n()},e);t={cancel:()=>{if(s)clearTimeout(s),n()}}});return Object.assign(r,t)}async function Fh(e,t=1000){let r=Es(),n=setTimeout(()=>{r.reject(new _s.TimeoutError)},t);try{return await Promise.race([e,r])}finally{clearTimeout(n)}}function Es(){let e={},t=new Promise((r,n)=>{e={resolve:r,reject:n}});return Object.assign(t,e)}function Bh(){let e={},t=new Promise((r,n)=>{e={resolve:(s)=>{console.trace("resolve",s),r(s)},reject:(s)=>{console.trace("reject"),n(s)}}});return Object.assign(t,e)}function Kh(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 Hh(e){let t=[];for await(let r of e)t.push(r);return t}class ko{timers;measures;constructor(){this.timers=new Map,this.measures=new Map}mark(e){this.timers.set(e,performance.now())}measure(e,t,r){let n=this.timers.get(t);if(n===void 0)throw Error(`${t} is not defined`);let s=this.timers.get(r);if(s===void 0)throw Error(`${r} is not defined`);this.measures.set(e,s-n)}getEntries(){let e=[];return this.measures.forEach((t,r)=>{e.push({name:r,duration:t})}),e}}$o.Perf=ko;class Ro{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=Es();return this.waiting.push(e),e}unlock(){this.current--,this.waiting.pop()?.resolve()}}$o.SimpleMutex=Ro;function qo(e){if(e===0)return 0;return Math.floor(e/2+Math.random()*e)}function zh(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 qo(r>t?e[t]:e[r])}}}function Gh(e){return e*1e6}function Vh(e){return Math.floor(e/1e6)}var Jh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",pt=new Uint8Array(62);for(let e=0;e<62;e++)pt[e]=Jh.charCodeAt(e);var Wh=218340105584896;function Yh(){let e=Math.floor(Math.random()*Wh),t=e%62,r=pt[t];e=(e-t)/62,t=e%62;let n=pt[t];e=(e-t)/62,t=e%62;let s=pt[t];e=(e-t)/62,t=e%62;let o=pt[t];e=(e-t)/62,t=e%62;let c=pt[t];e=(e-t)/62,t=e%62;let d=pt[t];e=(e-t)/62,t=e%62;let p=pt[t];e=(e-t)/62;let w=pt[e];return String.fromCharCode(r,n,s,o,c,d,p,w)}});var zo=z(function(Ko){Object.defineProperty(Ko,"__esModule",{value:!0});Ko.nuid=Ko.NuidImpl=void 0;var dd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",xt=62,Qr=12,Fo=10,Lo=33,ld=333,Do=Qr+Fo,As=new Uint8Array(xt);for(let e=0;e<xt;e++)As[e]=dd.charCodeAt(e);var Zr=4294967296,Bo=BigInt(xt)**BigInt(Fo),yr=Number(Bo/(1n<<32n)),Ss=Number(Bo%(1n<<32n));function pd(e){for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}function bd(e){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues(e);else pd(e)}class Os{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(Do),this.cbuf=new Uint8Array(Qr),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let e=0;do this.seqHi=Math.floor(Math.random()*(yr+1)),this.seqLo=Math.floor(Math.random()*Zr);while(e++<8&&this.seqHi===yr&&this.seqLo>=Ss);if(this.seqHi===yr&&this.seqLo>=Ss)this.seqLo=0;this.inc=Math.random()*(ld-Lo)+Lo|0}setPre(){bd(this.cbuf);for(let e=0;e<Qr;e++)this.buf[e]=As[this.cbuf[e]%xt]}fillSeq(){let e=this.seqHi,t=this.seqLo;for(let r=Do-1;r>=Qr;r--){let n=Math.floor(e/xt),o=(e-n*xt)*Zr+t,c=Math.floor(o/xt),d=o-c*xt;this.buf[r]=As[d],e=n,t=c}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=Zr)this.seqLo-=Zr,this.seqHi+=1;if(this.seqHi>yr||this.seqHi===yr&&this.seqLo>=Ss)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()}}Ko.NuidImpl=Os;Ko.nuid=new Os});var Wo=z(function(Vo){Object.defineProperty(Vo,"__esModule",{value:!0});Vo.nuid=Vo.Nuid=void 0;var Go=zo();Vo.Nuid=Go.NuidImpl;Vo.nuid=Go.nuid});var tn=z(function(en){Object.defineProperty(en,"__esModule",{value:!0});en.nuid=en.Nuid=void 0;var Yo=Wo();Object.defineProperty(en,"Nuid",{enumerable:!0,get:function(){return Yo.Nuid}});Object.defineProperty(en,"nuid",{enumerable:!0,get:function(){return Yo.nuid}})});var wt=z(function(Xo){Object.defineProperty(Xo,"__esModule",{value:!0});Xo.DEFAULT_HOST=Xo.DEFAULT_PORT=Xo.Match=void 0;Xo.syncIterator=vd;Xo.createInbox=_d;var xd=tn(),wd=Ve();Xo.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function vd(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 _d(e=""){if(e=e||"_INBOX",typeof e!=="string")throw TypeError("prefix must be a string");return e.split(".").forEach((t)=>{if(t==="*"||t===">")throw wd.InvalidArgumentError.format("prefix",`cannot have wildcards ('${e}')`)}),`${e}.${xd.nuid.next()}`}Xo.DEFAULT_PORT=4222;Xo.DEFAULT_HOST="127.0.0.1"});var mr=z(function(ta){Object.defineProperty(ta,"__esModule",{value:!0});ta.DataBuffer=void 0;var Qo=Ge();class ea{buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...e){let t=0;for(let s=0;s<e.length;s++)t+=e[s].length;let r=new Uint8Array(t),n=0;for(let s=0;s<e.length;s++)r.set(e[s],n),n+=e[s].length;return r}static fromAscii(e){if(!e)e="";return Qo.TE.encode(e)}static toAscii(e){return Qo.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 n=t.subarray(0,e);if(r>e)this.buffers.push(t.subarray(e));return this.byteLength=r-e,n}}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}}ta.DataBuffer=ea});var Ct=z(function(sa){Object.defineProperty(sa,"__esModule",{value:!0});sa.LF=sa.CR=sa.CRLF=sa.CR_LF_LEN=sa.CR_LF=void 0;sa.setTransportFactory=jd;sa.defaultPort=Nd;sa.getUrlParseFn=Cd;sa.newTransport=Md;sa.getResolveFn=kd;sa.protoLen=na;sa.extractProtocolMessage=Rd;var Pd=Ge(),Td=wt(),Id=mr(),Je;function jd(e){Je=e}function Nd(){return Je!==void 0&&Je.defaultPort!==void 0?Je.defaultPort:Td.DEFAULT_PORT}function Cd(){return Je!==void 0&&Je.urlParseFn?Je.urlParseFn:void 0}function Md(){if(!Je||typeof Je.factory!=="function")throw Error("transport fn is not set");return Je.factory()}function kd(){return Je!==void 0&&Je.dnsResolveFn?Je.dnsResolveFn:void 0}sa.CR_LF=`\r
|
|
2
|
-
`;sa.CR_LF_LEN=sa.CR_LF.length;sa.CRLF=Id.DataBuffer.fromAscii(sa.CR_LF);sa.CR=new Uint8Array(sa.CRLF)[0];sa.LF=new Uint8Array(sa.CRLF)[1];function na(e){for(let t=0;t<e.length;t++){let r=t+1;if(e.byteLength>r&&e[t]===sa.CR&&e[r]===sa.LF)return r+1}return 0}function Rd(e){let t=na(e);if(t>0){let n=new Uint8Array(e).slice(0,t);return Pd.TD.decode(n)}return""}});var Ns=z(function(da){Object.defineProperty(da,"__esModule",{value:!0});da.ipV4=ua;da.isIP=Gd;da.parseIP=fa;var gr=4,Mt=16,rn=48,ca=57,oa=65,Hd=70,aa=97,zd=102,js=16777215;function ua(e,t,r,n){let s=new Uint8Array(Mt);return[0,0,0,0,0,0,0,0,0,0,255,255].forEach((c,d)=>{s[d]=c}),s[12]=e,s[13]=t,s[14]=r,s[15]=n,s}function Gd(e){return fa(e)!==void 0}function fa(e){for(let t=0;t<e.length;t++)switch(e[t]){case".":return ha(e);case":":return Vd(e)}return}function ha(e){let t=new Uint8Array(gr);for(let r=0;r<gr;r++){if(e.length===0)return;if(r>0){if(e[0]!==".")return;e=e.substring(1)}let{n,c:s,ok:o}=Jd(e);if(!o||n>255)return;e=e.substring(s),t[r]=n}return ua(t[0],t[1],t[2],t[3])}function Vd(e){let t=new Uint8Array(Mt),r=-1;if(e.length>=2&&e[0]===":"&&e[1]===":"){if(r=0,e=e.substring(2),e.length===0)return t}let n=0;while(n<Mt){let{n:s,c:o,ok:c}=Wd(e);if(!c||s>65535)return;if(o<e.length&&e[o]==="."){if(r<0&&n!=Mt-gr)return;if(n+gr>Mt)return;let d=ha(e);if(d===void 0)return;t[n]=d[12],t[n+1]=d[13],t[n+2]=d[14],t[n+3]=d[15],e="",n+=gr;break}if(t[n]=s>>8,t[n+1]=s,n+=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=n,e=e.substring(1),e.length===0)break}}if(e.length!==0)return;if(n<Mt){if(r<0)return;let s=Mt-n;for(let o=n-1;o>=r;o--)t[o+s]=t[o];for(let o=r+s-1;o>=r;o--)t[o]=0}else if(r>=0)return;return t}function Jd(e){let t=0,r=0;for(t=0;t<e.length&&rn<=e.charCodeAt(t)&&e.charCodeAt(t)<=ca;t++)if(r=r*10+(e.charCodeAt(t)-rn),r>=js)return{n:js,c:t,ok:!1};if(t===0)return{n:0,c:0,ok:!1};return{n:r,c:t,ok:!0}}function Wd(e){let t=0,r=0;for(r=0;r<e.length;r++){if(rn<=e.charCodeAt(r)&&e.charCodeAt(r)<=ca)t*=16,t+=e.charCodeAt(r)-rn;else if(aa<=e.charCodeAt(r)&&e.charCodeAt(r)<=zd)t*=16,t+=e.charCodeAt(r)-aa+10;else if(oa<=e.charCodeAt(r)&&e.charCodeAt(r)<=Hd)t*=16,t+=e.charCodeAt(r)-oa+10;else break;if(t>=js)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 $s=z(function(pa){Object.defineProperty(pa,"__esModule",{value:!0});pa.Servers=pa.ServerImpl=void 0;pa.isIPV4OrHostname=la;pa.hostPort=qs;var Cs=Ct(),Ms=tt(),ks=Ns(),Qd=wt(),el=Ve();function la(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 Rs(e){return!la(e)}function tl(e){let r=e.toUpperCase().indexOf("::FFFF:");if(r!==-1&&e.indexOf(".")!==-1){let n=e.substring(r+7);return n=n.replace("[",""),n.replace("]","")}return e}function qs(e){if(e=e.trim(),e.match(/^(.*:\/\/)(.*)/m))e=e.replace(/^(.*:\/\/)(.*)/gm,"$2");if(e=tl(e),Rs(e)&&e.indexOf("[")===-1)e=`[${e}]`;let t=Rs(e)?e.match(/(]:)(\d+)/):e.match(/(:)(\d+)/),r=t&&t.length===3&&t[1]&&t[2]?parseInt(t[2]):Qd.DEFAULT_PORT,s=new URL(`${r===80?"https":"http"}://${e}`);s.port=`${r}`;let o=s.hostname;if(o.charAt(0)==="[")o=o.substring(1,o.length-1);return{listen:s.host,hostname:o,port:r}}class Jt{src;listen;hostname;port;didConnect;reconnects;lastConnect;gossiped;tlsName;resolves;constructor(e,t=!1){this.src=e,this.tlsName="";let r=qs(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,ks.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 n of r){let s=this.port===80?"https":"http",o=new URL(`${s}://${Rs(n)?"["+n+"]":n}`);o.port=`${this.port}`;let c=new Jt(o.host,!1);c.tlsName=this.hostname,t.push(c)}}if(e.randomize)(0,Ms.shuffle)(t);return this.resolves=t,t}}pa.ServerImpl=Jt;class nn{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 el.InvalidArgumentError.format("servers","cannot be empty");let t=(0,Cs.getUrlParseFn)(),r=new Map;for(let s of this.servers)r.set(s.listen,s);let n=[];for(let s of e){s=t?t(s):s;let{listen:o}=qs(s),c=r.get(o);if(c)c.gossiped=!1,n.push(c);else n.push(new Jt(s))}if(this.randomize)(0,Ms.shuffle)(n);if(this.servers=n,this.currentServer===void 0||!n.includes(this.currentServer))this.currentServer=n[0],this.firstSelect=!0}clear(){this.servers.length=0}updateTLSName(){let e=this.getCurrentServer();if(!(0,ks.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,Cs.getUrlParseFn)();e=r?r(e):e;let n=new Jt(e,t);if((0,ks.isIP)(n.hostname))n.tlsName=this.tlsName;this.servers.push(n)}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 nn.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 nn.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=[],n=[],s=(0,Cs.getUrlParseFn)(),o=new Map;if(e.connect_urls&&e.connect_urls.length>0)e.connect_urls.forEach((d)=>{d=s?s(d,t):d;let p=new Jt(d,!0);o.set(d,p)});let c=[];if(this.servers.forEach((d,p)=>{let w=d.listen;if(d.gossiped&&this.currentServer.listen!==w&&o.get(w)===void 0)c.push(p);o.delete(w)}),c.reverse(),c.forEach((d)=>{let p=this.servers.splice(d,1);n=n.concat(p[0].listen)}),o.forEach((d,p)=>{this.servers.push(d),r.push(p)}),this.randomize&&r.length>0){let d=this.currentServer,p=this.servers.filter((w)=>w!==d);(0,Ms.shuffle)(p),this.servers=d?[d,...p]:p}return{added:r,deleted:n}}}pa.Servers=nn});var sn=z(function(ga){Object.defineProperty(ga,"__esModule",{value:!0});ga.QueuedIteratorImpl=void 0;var Us=tt(),ya=Ve();class ma{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,Us.deferred)(),this.yields=[],this.iterClosed=(0,Us.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 ya.InvalidOperationError("iterator cannot be used when a callback is registered");if(this.yielding)throw new ya.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 n=e[t];try{n()}catch(s){throw s}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,Us.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}}ga.QueuedIteratorImpl=ma});var Ls=z(function(_a){Object.defineProperty(_a,"__esModule",{value:!0});_a.MuxSubscription=void 0;var il=wt(),wa=Ve();class va{baseInbox;reqs;constructor(){this.reqs=new Map}size(){return this.reqs.size}init(e){return this.baseInbox=`${(0,il.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((n)=>n.requestSubject===t.subject);if(r)return r.resolver(t,{}),!0}return!1}dispatcher(){return(e,t)=>{let r=this.getToken(t);if(r){let n=this.get(r);if(n){if(e===null)e=t?.data?.length===0&&t.headers?.code===503?new wa.NoRespondersError(n.requestSubject):null;n.resolver(e,t)}}}}close(){let e=new wa.RequestError("connection closed");this.reqs.forEach((t)=>{t.resolver(e,{})})}}_a.MuxSubscription=va});var Ds=z(function(Aa){Object.defineProperty(Aa,"__esModule",{value:!0});Aa.Heartbeat=void 0;var ol=tt();class Sa{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,ol.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))}}Aa.Heartbeat=Sa});var Ks=z(function(ja){Object.defineProperty(ja,"__esModule",{value:!0});ja.DenoBuffer=ja.MAX_SIZE=ja.AssertionError=void 0;ja.assert=Ta;ja.concat=Ia;ja.append=cl;ja.readAll=ul;ja.writeAll=fl;var al=Ge();class Fs extends Error{constructor(e){super(e);this.name="AssertionError"}}ja.AssertionError=Fs;function Ta(e,t="Assertion failed."){if(!e)throw new Fs(t)}var Pa=32768;ja.MAX_SIZE=4294967294;function on(e,t,r=0){let n=t.byteLength-r;if(e.byteLength>n)e=e.subarray(0,n);return t.set(e,r),e.byteLength}function Ia(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 cl(e,t){return Ia(e,Uint8Array.of(t))}class Bs{_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){Ta(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=on(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 on(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 n=this.capacity;if(e<=Math.floor(n/2)-t)on(this._buf.subarray(this._off),this._buf);else if(n+e>ja.MAX_SIZE)throw Error("The buffer cannot be grown beyond the maximum size.");else{let s=new Uint8Array(Math.min(2*n+e,ja.MAX_SIZE));on(this._buf.subarray(this._off),s),this._buf=s}return this._off=0,this._reslice(Math.min(t+e,ja.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(Pa);while(!0){let n=this.capacity-this.length<Pa,s=n?r:new Uint8Array(this._buf.buffer,this.length),o=e.read(s);if(o===null)return t;if(n)this.write(s.subarray(0,o));else this._reslice(this.length+o);t+=o}}}ja.DenoBuffer=Bs;function ul(e){let t=new Bs;return t.readFrom(e),t.bytes()}function fl(e,t){let r=0;while(r<t.length)r+=e.write(t.subarray(r))}});var Gs=z(function(Ra){Object.defineProperty(Ra,"__esModule",{value:!0});Ra.cc=Ra.State=Ra.Parser=Ra.Kind=void 0;Ra.describe=ml;var Hs=Ks(),zs=Ge();Ra.Kind={OK:0,ERR:1,MSG:2,INFO:3,PING:4,PONG:5};function ml(e){let t,r="";switch(e.kind){case Ra.Kind.MSG:t="MSG";break;case Ra.Kind.OK:t="OK";break;case Ra.Kind.ERR:t="ERR",r=zs.TD.decode(e.data);break;case Ra.Kind.PING:t="PING";break;case Ra.Kind.PONG:t="PONG";break;case Ra.Kind.INFO:t="INFO",r=zs.TD.decode(e.data)}return`${t}: ${r}`}function Ca(){let e={};return e.sid=-1,e.hdr=-1,e.size=-1,e}var Ma=48,gl=57,Wt=67108864;class ka{dispatcher;state;as;drop;hdr;ma;argBuf;msgBuf;constructor(e){this.dispatcher=e,this.state=Ra.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 Ra.State.OP_START:switch(r){case Ra.cc.M:case Ra.cc.m:this.state=Ra.State.OP_M,this.hdr=-1,this.ma=Ca();break;case Ra.cc.H:case Ra.cc.h:this.state=Ra.State.OP_H,this.hdr=0,this.ma=Ca();break;case Ra.cc.P:case Ra.cc.p:this.state=Ra.State.OP_P;break;case Ra.cc.PLUS:this.state=Ra.State.OP_PLUS;break;case Ra.cc.MINUS:this.state=Ra.State.OP_MINUS;break;case Ra.cc.I:case Ra.cc.i:this.state=Ra.State.OP_I;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_H:switch(r){case Ra.cc.M:case Ra.cc.m:this.state=Ra.State.OP_M;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_M:switch(r){case Ra.cc.S:case Ra.cc.s:this.state=Ra.State.OP_MS;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_MS:switch(r){case Ra.cc.G:case Ra.cc.g:this.state=Ra.State.OP_MSG;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_MSG:switch(r){case Ra.cc.SPACE:case Ra.cc.TAB:this.state=Ra.State.OP_MSG_SPC;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_MSG_SPC:switch(r){case Ra.cc.SPACE:case Ra.cc.TAB:continue;default:this.state=Ra.State.MSG_ARG,this.as=t}break;case Ra.State.MSG_ARG:switch(r){case Ra.cc.CR:this.drop=1;break;case Ra.cc.NL:{let n=this.argBuf?this.argBuf.bytes():e.subarray(this.as,t-this.drop);this.processMsgArgs(n),this.drop=0,this.as=t+1,this.state=Ra.State.MSG_PAYLOAD,t=this.as+this.ma.size-1;break}default:if(this.argBuf)this.argBuf.writeByte(r)}break;case Ra.State.MSG_PAYLOAD:if(this.msgBuf)if(this.msgBuf.length>=this.ma.size){let n=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:Ra.Kind.MSG,msg:this.ma,data:n}),this.argBuf=void 0,this.msgBuf=void 0,this.state=Ra.State.MSG_END}else{let n=this.ma.size-this.msgBuf.length,s=e.length-t;if(s<n)n=s;if(n>0)this.msgBuf.write(e.subarray(t,t+n)),t=t+n-1;else this.msgBuf.writeByte(r)}else if(t-this.as>=this.ma.size)this.dispatcher.push({kind:Ra.Kind.MSG,msg:this.ma,data:e.subarray(this.as,t)}),this.argBuf=void 0,this.msgBuf=void 0,this.state=Ra.State.MSG_END;break;case Ra.State.MSG_END:switch(r){case Ra.cc.NL:this.drop=0,this.as=t+1,this.state=Ra.State.OP_START;break;default:continue}break;case Ra.State.OP_PLUS:switch(r){case Ra.cc.O:case Ra.cc.o:this.state=Ra.State.OP_PLUS_O;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_PLUS_O:switch(r){case Ra.cc.K:case Ra.cc.k:this.state=Ra.State.OP_PLUS_OK;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_PLUS_OK:switch(r){case Ra.cc.NL:this.dispatcher.push({kind:Ra.Kind.OK}),this.drop=0,this.state=Ra.State.OP_START;break}break;case Ra.State.OP_MINUS:switch(r){case Ra.cc.E:case Ra.cc.e:this.state=Ra.State.OP_MINUS_E;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_MINUS_E:switch(r){case Ra.cc.R:case Ra.cc.r:this.state=Ra.State.OP_MINUS_ER;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_MINUS_ER:switch(r){case Ra.cc.R:case Ra.cc.r:this.state=Ra.State.OP_MINUS_ERR;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_MINUS_ERR:switch(r){case Ra.cc.SPACE:case Ra.cc.TAB:this.state=Ra.State.OP_MINUS_ERR_SPC;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_MINUS_ERR_SPC:switch(r){case Ra.cc.SPACE:case Ra.cc.TAB:continue;default:this.state=Ra.State.MINUS_ERR_ARG,this.as=t}break;case Ra.State.MINUS_ERR_ARG:switch(r){case Ra.cc.CR:this.drop=1;break;case Ra.cc.NL:{let n;if(this.argBuf)n=this.argBuf.bytes(),this.argBuf=void 0;else n=e.subarray(this.as,t-this.drop);this.dispatcher.push({kind:Ra.Kind.ERR,data:n}),this.drop=0,this.as=t+1,this.state=Ra.State.OP_START;break}default:if(this.argBuf)this.argBuf.write(Uint8Array.of(r))}break;case Ra.State.OP_P:switch(r){case Ra.cc.I:case Ra.cc.i:this.state=Ra.State.OP_PI;break;case Ra.cc.O:case Ra.cc.o:this.state=Ra.State.OP_PO;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_PO:switch(r){case Ra.cc.N:case Ra.cc.n:this.state=Ra.State.OP_PON;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_PON:switch(r){case Ra.cc.G:case Ra.cc.g:this.state=Ra.State.OP_PONG;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_PONG:switch(r){case Ra.cc.NL:this.dispatcher.push({kind:Ra.Kind.PONG}),this.drop=0,this.state=Ra.State.OP_START;break}break;case Ra.State.OP_PI:switch(r){case Ra.cc.N:case Ra.cc.n:this.state=Ra.State.OP_PIN;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_PIN:switch(r){case Ra.cc.G:case Ra.cc.g:this.state=Ra.State.OP_PING;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_PING:switch(r){case Ra.cc.NL:this.dispatcher.push({kind:Ra.Kind.PING}),this.drop=0,this.state=Ra.State.OP_START;break}break;case Ra.State.OP_I:switch(r){case Ra.cc.N:case Ra.cc.n:this.state=Ra.State.OP_IN;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_IN:switch(r){case Ra.cc.F:case Ra.cc.f:this.state=Ra.State.OP_INF;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_INF:switch(r){case Ra.cc.O:case Ra.cc.o:this.state=Ra.State.OP_INFO;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_INFO:switch(r){case Ra.cc.SPACE:case Ra.cc.TAB:this.state=Ra.State.OP_INFO_SPC;break;default:throw this.fail(e.subarray(t))}break;case Ra.State.OP_INFO_SPC:switch(r){case Ra.cc.SPACE:case Ra.cc.TAB:continue;default:this.state=Ra.State.INFO_ARG,this.as=t}break;case Ra.State.INFO_ARG:switch(r){case Ra.cc.CR:this.drop=1;break;case Ra.cc.NL:{let n;if(this.argBuf)n=this.argBuf.bytes(),this.argBuf=void 0;else n=e.subarray(this.as,t-this.drop);this.dispatcher.push({kind:Ra.Kind.INFO,data:n}),this.drop=0,this.as=t+1,this.state=Ra.State.OP_START;break}default:if(this.argBuf)this.argBuf.writeByte(r)}break;default:throw this.fail(e.subarray(t))}}if((this.state===Ra.State.MSG_ARG||this.state===Ra.State.MINUS_ERR_ARG||this.state===Ra.State.INFO_ARG)&&!this.argBuf)this.argBuf=new Hs.DenoBuffer(e.subarray(this.as,t-this.drop));if(this.state===Ra.State.MSG_PAYLOAD&&!this.msgBuf){if(!this.argBuf)this.cloneMsgArg();this.msgBuf=new Hs.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 Hs.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 n=0;n<e.length;n++)switch(e[n]){case Ra.cc.SPACE:case Ra.cc.TAB:case Ra.cc.CR:case Ra.cc.NL:if(r>=0)t.push(e.subarray(r,n)),r=-1;break;default:if(r<0)r=n}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],Wt);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],Wt);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}: ${zs.TD.decode(e)}`)}processHeaderMsgArgs(e){let t=[],r=-1;for(let n=0;n<e.length;n++)switch(e[n]){case Ra.cc.SPACE:case Ra.cc.TAB:case Ra.cc.CR:case Ra.cc.NL:if(r>=0)t.push(e.subarray(r,n)),r=-1;break;default:if(r<0)r=n}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],Wt),this.ma.size=this.protoParseInt(t[3],Wt);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],Wt),this.ma.size=this.protoParseInt(t[4],Wt);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 n=0;n<e.length;n++){if(e[n]<Ma||e[n]>gl)return-1;r=r*10+(e[n]-Ma)}return t!==void 0&&r>t?-1:r}}Ra.Parser=ka;Ra.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};Ra.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 un=z(function($a){Object.defineProperty($a,"__esModule",{value:!0});$a.MsgHdrsImpl=void 0;$a.canonicalMIMEHeaderKey=Js;$a.headers=vl;var qa=Ge(),rt=wt(),cn=Ve();function Js(e){let A=!0,I=Array(e.length);for(let O=0;O<e.length;O++){let K=e.charCodeAt(O);if(K===58||K<33||K>126)throw cn.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;I[O]=K,A=K==45}return String.fromCharCode(...I)}function vl(e=0,t=""){if(e===0&&t!=="")throw cn.InvalidArgumentError.format("code","is required");else if(e>0&&t==="")throw cn.InvalidArgumentError.format("description","is required");return new Yt(e,t)}var Vs="NATS/1.0";class Yt{_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 n=e.values(t);if(r.length!==n.length)return!1;let s=[...r].sort(),o=[...n].sort();for(let c=0;c<s.length;c++)if(s[c]!==o[c])return!1}return!0}return!1}static decode(e){let t=new Yt,n=qa.TD.decode(e).split(`\r
|
|
3
|
-
`),s=n[0];if(s!==Vs){let o=s.replace(Vs,"").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(n.length>=1)n.slice(1).map((o)=>{if(o){let c=o.indexOf(":");if(c>-1){let d=o.slice(0,c),p=o.slice(c+1).trim();t.append(d,p)}}});return t}toString(){if(this.headers.size===0&&this._code===0)return"";let e=Vs;if(this._code>0&&this._description!=="")e+=` ${this._code} ${this._description}`;for(let[t,r]of this.headers)for(let n=0;n<r.length;n++)e=`${e}\r
|
|
4
|
-
${t}: ${r[n]}`;return`${e}\r
|
|
5
|
-
\r
|
|
6
|
-
`}encode(){return qa.TE.encode(this.toString())}static validHeaderValue(e){if(/[\r\n]/.test(e))throw cn.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=rt.Match.Exact){let r=this.keys();switch(t){case rt.Match.Exact:return r.filter((n)=>n===e);case rt.Match.CanonicalMIME:return e=Js(e),r.filter((n)=>n===e);default:{let n=e.toLowerCase();return r.filter((s)=>n===s.toLowerCase())}}}get(e,t=rt.Match.Exact){let r=this.findKeys(e,t);if(r.length){let n=this.headers.get(r[0]);if(n)return Array.isArray(n)?n[0]:n}return""}last(e,t=rt.Match.Exact){let r=this.findKeys(e,t);if(r.length){let n=this.headers.get(r[0]);if(n)return Array.isArray(n)?n[n.length-1]:n}return""}has(e,t=rt.Match.Exact){return this.findKeys(e,t).length>0}set(e,t,r=rt.Match.Exact){this.delete(e,r),this.append(e,t,r)}append(e,t,r=rt.Match.Exact){let n=Js(e);if(r===rt.Match.CanonicalMIME)e=n;let s=this.findKeys(e,r);e=s.length>0?s[0]:e;let o=Yt.validHeaderValue(t),c=this.headers.get(e);if(!c)c=[],this.headers.set(e,c);c.push(o)}values(e,t=rt.Match.Exact){let r=[];return this.findKeys(e,t).forEach((s)=>{let o=this.headers.get(s);if(o)r.push(...o)}),r}delete(e,t=rt.Match.Exact){this.findKeys(e,t).forEach((n)=>{this.headers.delete(n)})}get hasError(){return this._code>=300}get status(){return`${this._code} ${this._description}`.trim()}toRecord(){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 Yt;for(let r in e){let n=e[r];t.headers.set(r,Array.isArray(n)?n:[`${n}`])}return t}}$a.MsgHdrsImpl=Yt});var Ws=z(function(Da){Object.defineProperty(Da,"__esModule",{value:!0});Da.MsgImpl=void 0;var Sl=un(),fn=Ge();class La{_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=fn.TD.decode(this._msg.subject),this._subject}get reply(){if(this._reply)return this._reply;return this._reply=fn.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=Sl.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=fn.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 fn.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}}Da.MsgImpl=La});var dn=z(function(Ka){Object.defineProperty(Ka,"__esModule",{value:!0});Ka.Features=Ka.Feature=void 0;Ka.parseSemVer=hn;Ka.compare=Ys;function hn(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 Ys(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}Ka.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 Ba{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=hn(e);this.server=e,this.set(Ka.Feature.JS_KV,"2.6.2"),this.set(Ka.Feature.JS_OBJECTSTORE,"2.6.3"),this.set(Ka.Feature.JS_PULL_MAX_BYTES,"2.8.3"),this.set(Ka.Feature.JS_NEW_CONSUMER_CREATE_API,"2.9.0"),this.set(Ka.Feature.JS_ALLOW_DIRECT,"2.9.0"),this.set(Ka.Feature.JS_MULTIPLE_CONSUMER_FILTER,"2.10.0"),this.set(Ka.Feature.JS_SIMPLIFICATION,"2.9.4"),this.set(Ka.Feature.JS_STREAM_CONSUMER_METADATA,"2.10.0"),this.set(Ka.Feature.JS_CONSUMER_FILTER_SUBJECTS,"2.10.0"),this.set(Ka.Feature.JS_STREAM_FIRST_SEQ,"2.10.0"),this.set(Ka.Feature.JS_STREAM_SUBJECT_TRANSFORM,"2.10.0"),this.set(Ka.Feature.JS_STREAM_SOURCE_SUBJECT_TRANSFORM,"2.10.0"),this.set(Ka.Feature.JS_STREAM_COMPRESSION,"2.10.0"),this.set(Ka.Feature.JS_DEFAULT_CONSUMER_LIMITS,"2.10.0"),this.set(Ka.Feature.JS_BATCH_DIRECT_GET,"2.11.0"),this.set(Ka.Feature.JS_PRIORITY_GROUPS,"2.11.0"),this.set(Ka.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:Ys(this.server,hn(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=hn(e);return Ys(this.server,e)>=0}}Ka.Features=Ba});var Zs=z(function(za){Object.defineProperty(za,"__esModule",{value:!0});za.crc16=void 0;var Pl=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 Xs{static checksum(e){let t=0;for(let r=0;r<e.byteLength;r++){let n=e[r];t=t<<8&65535^Pl[(t>>8^n)&255]}return t}static validate(e,t){return Xs.checksum(e)==t}}za.crc16=Xs});var ei=z(function(Ja){Object.defineProperty(Ja,"__esModule",{value:!0});Ja.base32=void 0;var Qs="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";class Va{static encode(e){let t=0,r=0,n=new Uint8Array(e),s=new Uint8Array(e.byteLength*2),o=0;for(let c=0;c<n.byteLength;c++){r=r<<8|n[c],t+=8;while(t>=5){let d=r>>>t-5&31;s[o++]=Qs.charAt(d).charCodeAt(0),t-=5}}if(t>0){let c=r<<5-t&31;s[o++]=Qs.charAt(c).charCodeAt(0)}return s.slice(0,o)}static decode(e){let t=0,r=0,n=0,s=new Uint8Array(e),o=new Uint8Array(s.byteLength*5/8|0);for(let c=0;c<s.byteLength;c++){let d=String.fromCharCode(s[c]),p=Qs.indexOf(d);if(p===-1)throw Error("Illegal Base32 character: "+s[c]);if(r=r<<5|p,t+=5,t>=8)o[n++]=r>>>t-8&255,t-=8}return o.slice(0,n)}}Ja.base32=Va});var xr=z(function(Za){Object.defineProperty(Za,"__esModule",{value:!0});Za.Codec=void 0;var Ya=Zs(),me=kt(),Xa=ei();class vt{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 vt._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 vt._encode(!0,e,t)}static decode(e,t){if(!me.Prefixes.isValidPrefix(e))throw new me.NKeysError(me.NKeysErrorCode.InvalidPrefixByte);let r=vt._decode(t);if(r[0]!==e)throw new me.NKeysError(me.NKeysErrorCode.InvalidPrefixByte);return r.slice(1)}static decodeSeed(e){let t=vt._decode(e),r=vt._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 n=e?2:1,s=r.byteLength,o=2,c=n+s+2,d=n+s,p=new Uint8Array(c);if(e){let I=vt._encodePrefix(me.Prefix.Seed,t);p.set(I)}else p[0]=t;p.set(r,n);let w=Ya.crc16.checksum(p.slice(0,d));return new DataView(p.buffer).setUint16(d,w,!0),Xa.base32.encode(p)}static _decode(e){if(e.byteLength<4)throw new me.NKeysError(me.NKeysErrorCode.InvalidEncoding);let t;try{t=Xa.base32.decode(e)}catch(c){throw new me.NKeysError(me.NKeysErrorCode.InvalidEncoding,{cause:c})}let r=t.byteLength-2,s=new DataView(t.buffer).getUint16(r,!0),o=t.slice(0,r);if(!Ya.crc16.validate(o,s))throw new me.NKeysError(me.NKeysErrorCode.InvalidChecksum);return o}static _encodePrefix(e,t){let r=e|t>>5,n=(t&31)<<3;return new Uint8Array([r,n])}static _decodePrefix(e){let t=e[0]&248,r=(e[0]&7)<<5|(e[1]&248)>>3;return new Uint8Array([t,r])}}Za.Codec=vt});var ec=z(function(Tg,ln){(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")},n=new Uint8Array(16),s=new Uint8Array(32);s[0]=9;var o=t(),c=t([1]),d=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]),I=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,h){var y,m=0;for(y=0;y<h;y++)m|=a[f+y]^u[i+y];return(1&m-1>>>8)-1}function Oe(a,f,u,i){return N(a,f,u,i,16)}function ye(a,f,u,i){return N(a,f,u,i,32)}function gt(a,f,u,i){var h=i[0]&255|(i[1]&255)<<8|(i[2]&255)<<16|(i[3]&255)<<24,y=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,k=f[0]&255|(f[1]&255)<<8|(f[2]&255)<<16|(f[3]&255)<<24,he=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=h,B=y,R=m,L=_,D=T,M=F,g=k,x=he,S=q,v=G,E=V,P=Z,H=X,Q=J,re=Y,ee=W,l;for(var ie=0;ie<20;ie+=2)l=U+H|0,D^=l<<7|l>>>25,l=D+U|0,S^=l<<9|l>>>23,l=S+D|0,H^=l<<13|l>>>19,l=H+S|0,U^=l<<18|l>>>14,l=M+B|0,v^=l<<7|l>>>25,l=v+M|0,Q^=l<<9|l>>>23,l=Q+v|0,B^=l<<13|l>>>19,l=B+Q|0,M^=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=M+D|0,g^=l<<7|l>>>25,l=g+M|0,x^=l<<9|l>>>23,l=x+g|0,D^=l<<13|l>>>19,l=D+x|0,M^=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,H^=l<<7|l>>>25,l=H+ee|0,Q^=l<<9|l>>>23,l=Q+H|0,re^=l<<13|l>>>19,l=re+Q|0,ee^=l<<18|l>>>14;U=U+h|0,B=B+y|0,R=R+m|0,L=L+_|0,D=D+T|0,M=M+F|0,g=g+k|0,x=x+he|0,S=S+q|0,v=v+G|0,E=E+V|0,P=P+Z|0,H=H+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]=M>>>0&255,a[21]=M>>>8&255,a[22]=M>>>16&255,a[23]=M>>>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]=H>>>0&255,a[49]=H>>>8&255,a[50]=H>>>16&255,a[51]=H>>>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 rh(a,f,u,i){var h=i[0]&255|(i[1]&255)<<8|(i[2]&255)<<16|(i[3]&255)<<24,y=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,k=f[0]&255|(f[1]&255)<<8|(f[2]&255)<<16|(f[3]&255)<<24,he=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=h,B=y,R=m,L=_,D=T,M=F,g=k,x=he,S=q,v=G,E=V,P=Z,H=X,Q=J,re=Y,ee=W,l;for(var ie=0;ie<20;ie+=2)l=U+H|0,D^=l<<7|l>>>25,l=D+U|0,S^=l<<9|l>>>23,l=S+D|0,H^=l<<13|l>>>19,l=H+S|0,U^=l<<18|l>>>14,l=M+B|0,v^=l<<7|l>>>25,l=v+M|0,Q^=l<<9|l>>>23,l=Q+v|0,B^=l<<13|l>>>19,l=B+Q|0,M^=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=M+D|0,g^=l<<7|l>>>25,l=g+M|0,x^=l<<9|l>>>23,l=x+g|0,D^=l<<13|l>>>19,l=D+x|0,M^=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,H^=l<<7|l>>>25,l=H+ee|0,Q^=l<<9|l>>>23,l=Q+H|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]=M>>>0&255,a[5]=M>>>8&255,a[6]=M>>>16&255,a[7]=M>>>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 qr(a,f,u,i){gt(a,f,u,i)}function $r(a,f,u,i){rh(a,f,u,i)}var It=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function uo(a,f,u,i,h,y,m){var _=new Uint8Array(16),T=new Uint8Array(64),F,k;for(k=0;k<16;k++)_[k]=0;for(k=0;k<8;k++)_[k]=y[k];while(h>=64){qr(T,_,m,It);for(k=0;k<64;k++)a[f+k]=u[i+k]^T[k];F=1;for(k=8;k<16;k++)F=F+(_[k]&255)|0,_[k]=F&255,F>>>=8;h-=64,f+=64,i+=64}if(h>0){qr(T,_,m,It);for(k=0;k<h;k++)a[f+k]=u[i+k]^T[k]}return 0}function fo(a,f,u,i,h){var y=new Uint8Array(16),m=new Uint8Array(64),_,T;for(T=0;T<16;T++)y[T]=0;for(T=0;T<8;T++)y[T]=i[T];while(u>=64){qr(m,y,h,It);for(T=0;T<64;T++)a[f+T]=m[T];_=1;for(T=8;T<16;T++)_=_+(y[T]&255)|0,y[T]=_&255,_>>>=8;u-=64,f+=64}if(u>0){qr(m,y,h,It);for(T=0;T<u;T++)a[f+T]=m[T]}return 0}function ho(a,f,u,i,h){var y=new Uint8Array(32);$r(y,i,h,It);var m=new Uint8Array(8);for(var _=0;_<8;_++)m[_]=i[_+16];return fo(a,f,u,m,y)}function Xn(a,f,u,i,h,y,m){var _=new Uint8Array(32);$r(_,y,m,It);var T=new Uint8Array(8);for(var F=0;F<8;F++)T[F]=y[F+16];return uo(a,f,u,i,h,T,_)}var Ur=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,h,y,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,h=a[6]&255|(a[7]&255)<<8,this.r[3]=(i>>>7|h<<9)&8191,y=a[8]&255|(a[9]&255)<<8,this.r[4]=(h>>>4|y<<12)&255,this.r[5]=y>>>1&8190,m=a[10]&255|(a[11]&255)<<8,this.r[6]=(y>>>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};Ur.prototype.blocks=function(a,f,u){var i=this.fin?0:2048,h,y,m,_,T,F,k,he,q,G,V,Z,X,J,Y,W,U,B,R,L=this.h[0],D=this.h[1],M=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],H=this.h[9],Q=this.r[0],re=this.r[1],ee=this.r[2],l=this.r[3],ie=this.r[4],de=this.r[5],le=this.r[6],ne=this.r[7],ue=this.r[8],fe=this.r[9];while(u>=16)h=a[f+0]&255|(a[f+1]&255)<<8,L+=h&8191,y=a[f+2]&255|(a[f+3]&255)<<8,D+=(h>>>13|y<<3)&8191,m=a[f+4]&255|(a[f+5]&255)<<8,M+=(y>>>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,k=a[f+12]&255|(a[f+13]&255)<<8,E+=(F>>>11|k<<5)&8191,he=a[f+14]&255|(a[f+15]&255)<<8,P+=(k>>>8|he<<8)&8191,H+=he>>>5|i,q=0,G=q,G+=L*Q,G+=D*(5*fe),G+=M*(5*ue),G+=g*(5*ne),G+=x*(5*le),q=G>>>13,G&=8191,G+=S*(5*de),G+=v*(5*ie),G+=E*(5*l),G+=P*(5*ee),G+=H*(5*re),q+=G>>>13,G&=8191,V=q,V+=L*re,V+=D*Q,V+=M*(5*fe),V+=g*(5*ue),V+=x*(5*ne),q=V>>>13,V&=8191,V+=S*(5*le),V+=v*(5*de),V+=E*(5*ie),V+=P*(5*l),V+=H*(5*ee),q+=V>>>13,V&=8191,Z=q,Z+=L*ee,Z+=D*re,Z+=M*Q,Z+=g*(5*fe),Z+=x*(5*ue),q=Z>>>13,Z&=8191,Z+=S*(5*ne),Z+=v*(5*le),Z+=E*(5*de),Z+=P*(5*ie),Z+=H*(5*l),q+=Z>>>13,Z&=8191,X=q,X+=L*l,X+=D*ee,X+=M*re,X+=g*Q,X+=x*(5*fe),q=X>>>13,X&=8191,X+=S*(5*ue),X+=v*(5*ne),X+=E*(5*le),X+=P*(5*de),X+=H*(5*ie),q+=X>>>13,X&=8191,J=q,J+=L*ie,J+=D*l,J+=M*ee,J+=g*re,J+=x*Q,q=J>>>13,J&=8191,J+=S*(5*fe),J+=v*(5*ue),J+=E*(5*ne),J+=P*(5*le),J+=H*(5*de),q+=J>>>13,J&=8191,Y=q,Y+=L*de,Y+=D*ie,Y+=M*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*ne),Y+=H*(5*le),q+=Y>>>13,Y&=8191,W=q,W+=L*le,W+=D*de,W+=M*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+=H*(5*ne),q+=W>>>13,W&=8191,U=q,U+=L*ne,U+=D*le,U+=M*de,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+=H*(5*ue),q+=U>>>13,U&=8191,B=q,B+=L*ue,B+=D*ne,B+=M*le,B+=g*de,B+=x*ie,q=B>>>13,B&=8191,B+=S*l,B+=v*ee,B+=E*re,B+=P*Q,B+=H*(5*fe),q+=B>>>13,B&=8191,R=q,R+=L*fe,R+=D*ue,R+=M*ne,R+=g*le,R+=x*de,q=R>>>13,R&=8191,R+=S*ie,R+=v*l,R+=E*ee,R+=P*re,R+=H*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,M=Z,g=X,x=J,S=Y,v=W,E=U,P=B,H=R,f+=16,u-=16;this.h[0]=L,this.h[1]=D,this.h[2]=M,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]=H},Ur.prototype.finish=function(a,f){var u=new Uint16Array(10),i,h,y,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,h=(i^1)-1;for(m=0;m<10;m++)u[m]&=h;h=~h;for(m=0;m<10;m++)this.h[m]=this.h[m]&h|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,y=this.h[0]+this.pad[0],this.h[0]=y&65535;for(m=1;m<8;m++)y=(this.h[m]+this.pad[m]|0)+(y>>>16)|0,this.h[m]=y&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},Ur.prototype.update=function(a,f,u){var i,h;if(this.leftover){if(h=16-this.leftover,h>u)h=u;for(i=0;i<h;i++)this.buffer[this.leftover+i]=a[f+i];if(u-=h,f+=h,this.leftover+=h,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(u>=16)h=u-u%16,this.blocks(a,f,h),f+=h,u-=h;if(u){for(i=0;i<u;i++)this.buffer[this.leftover+i]=a[f+i];this.leftover+=u}};function Zn(a,f,u,i,h,y){var m=new Ur(y);return m.update(u,i,h),m.finish(a,f),0}function lo(a,f,u,i,h,y){var m=new Uint8Array(16);return Zn(m,0,u,i,h,y),Oe(a,f,m,0)}function Qn(a,f,u,i,h){var y;if(u<32)return-1;Xn(a,0,f,0,u,i,h),Zn(a,16,a,32,u-32,a);for(y=0;y<16;y++)a[y]=0;return 0}function es(a,f,u,i,h){var y,m=new Uint8Array(32);if(u<32)return-1;if(ho(m,0,32,i,h),lo(f,16,f,32,u-32,m)!==0)return-1;Xn(a,0,f,0,u,i,h);for(y=0;y<32;y++)a[y]=0;return 0}function dt(a,f){var u;for(u=0;u<16;u++)a[u]=f[u]|0}function ts(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 Ht(a,f,u){var i,h=~(u-1);for(var y=0;y<16;y++)i=h&(a[y]^f[y]),a[y]^=i,f[y]^=i}function zt(a,f){var u,i,h,y=t(),m=t();for(u=0;u<16;u++)m[u]=f[u];ts(m),ts(m),ts(m);for(i=0;i<2;i++){y[0]=m[0]-65517;for(u=1;u<15;u++)y[u]=m[u]-65535-(y[u-1]>>16&1),y[u-1]&=65535;y[15]=m[15]-32767-(y[14]>>16&1),h=y[15]>>16&1,y[14]&=65535,Ht(m,y,1-h)}for(u=0;u<16;u++)a[2*u]=m[u]&255,a[2*u+1]=m[u]>>8}function po(a,f){var u=new Uint8Array(32),i=new Uint8Array(32);return zt(u,a),zt(i,f),ye(u,0,i,0)}function bo(a){var f=new Uint8Array(32);return zt(f,a),f[0]&1}function rs(a,f){var u;for(u=0;u<16;u++)a[u]=f[2*u]+(f[2*u+1]<<8);a[15]&=32767}function Qe(a,f,u){for(var i=0;i<16;i++)a[i]=f[i]+u[i]}function et(a,f,u){for(var i=0;i<16;i++)a[i]=f[i]-u[i]}function ce(a,f,u){var i,h,y=0,m=0,_=0,T=0,F=0,k=0,he=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,M=0,g=0,x=0,S=0,v=0,E=0,P=0,H=0,Q=0,re=0,ee=0,l=u[0],ie=u[1],de=u[2],le=u[3],ne=u[4],ue=u[5],fe=u[6],Se=u[7],ge=u[8],we=u[9],ve=u[10],_e=u[11],Pe=u[12],qe=u[13],$e=u[14],Ue=u[15];i=f[0],y+=i*l,m+=i*ie,_+=i*de,T+=i*le,F+=i*ne,k+=i*ue,he+=i*fe,q+=i*Se,G+=i*ge,V+=i*we,Z+=i*ve,X+=i*_e,J+=i*Pe,Y+=i*qe,W+=i*$e,U+=i*Ue,i=f[1],m+=i*l,_+=i*ie,T+=i*de,F+=i*le,k+=i*ne,he+=i*ue,q+=i*fe,G+=i*Se,V+=i*ge,Z+=i*we,X+=i*ve,J+=i*_e,Y+=i*Pe,W+=i*qe,U+=i*$e,B+=i*Ue,i=f[2],_+=i*l,T+=i*ie,F+=i*de,k+=i*le,he+=i*ne,q+=i*ue,G+=i*fe,V+=i*Se,Z+=i*ge,X+=i*we,J+=i*ve,Y+=i*_e,W+=i*Pe,U+=i*qe,B+=i*$e,R+=i*Ue,i=f[3],T+=i*l,F+=i*ie,k+=i*de,he+=i*le,q+=i*ne,G+=i*ue,V+=i*fe,Z+=i*Se,X+=i*ge,J+=i*we,Y+=i*ve,W+=i*_e,U+=i*Pe,B+=i*qe,R+=i*$e,L+=i*Ue,i=f[4],F+=i*l,k+=i*ie,he+=i*de,q+=i*le,G+=i*ne,V+=i*ue,Z+=i*fe,X+=i*Se,J+=i*ge,Y+=i*we,W+=i*ve,U+=i*_e,B+=i*Pe,R+=i*qe,L+=i*$e,D+=i*Ue,i=f[5],k+=i*l,he+=i*ie,q+=i*de,G+=i*le,V+=i*ne,Z+=i*ue,X+=i*fe,J+=i*Se,Y+=i*ge,W+=i*we,U+=i*ve,B+=i*_e,R+=i*Pe,L+=i*qe,D+=i*$e,M+=i*Ue,i=f[6],he+=i*l,q+=i*ie,G+=i*de,V+=i*le,Z+=i*ne,X+=i*ue,J+=i*fe,Y+=i*Se,W+=i*ge,U+=i*we,B+=i*ve,R+=i*_e,L+=i*Pe,D+=i*qe,M+=i*$e,g+=i*Ue,i=f[7],q+=i*l,G+=i*ie,V+=i*de,Z+=i*le,X+=i*ne,J+=i*ue,Y+=i*fe,W+=i*Se,U+=i*ge,B+=i*we,R+=i*ve,L+=i*_e,D+=i*Pe,M+=i*qe,g+=i*$e,x+=i*Ue,i=f[8],G+=i*l,V+=i*ie,Z+=i*de,X+=i*le,J+=i*ne,Y+=i*ue,W+=i*fe,U+=i*Se,B+=i*ge,R+=i*we,L+=i*ve,D+=i*_e,M+=i*Pe,g+=i*qe,x+=i*$e,S+=i*Ue,i=f[9],V+=i*l,Z+=i*ie,X+=i*de,J+=i*le,Y+=i*ne,W+=i*ue,U+=i*fe,B+=i*Se,R+=i*ge,L+=i*we,D+=i*ve,M+=i*_e,g+=i*Pe,x+=i*qe,S+=i*$e,v+=i*Ue,i=f[10],Z+=i*l,X+=i*ie,J+=i*de,Y+=i*le,W+=i*ne,U+=i*ue,B+=i*fe,R+=i*Se,L+=i*ge,D+=i*we,M+=i*ve,g+=i*_e,x+=i*Pe,S+=i*qe,v+=i*$e,E+=i*Ue,i=f[11],X+=i*l,J+=i*ie,Y+=i*de,W+=i*le,U+=i*ne,B+=i*ue,R+=i*fe,L+=i*Se,D+=i*ge,M+=i*we,g+=i*ve,x+=i*_e,S+=i*Pe,v+=i*qe,E+=i*$e,P+=i*Ue,i=f[12],J+=i*l,Y+=i*ie,W+=i*de,U+=i*le,B+=i*ne,R+=i*ue,L+=i*fe,D+=i*Se,M+=i*ge,g+=i*we,x+=i*ve,S+=i*_e,v+=i*Pe,E+=i*qe,P+=i*$e,H+=i*Ue,i=f[13],Y+=i*l,W+=i*ie,U+=i*de,B+=i*le,R+=i*ne,L+=i*ue,D+=i*fe,M+=i*Se,g+=i*ge,x+=i*we,S+=i*ve,v+=i*_e,E+=i*Pe,P+=i*qe,H+=i*$e,Q+=i*Ue,i=f[14],W+=i*l,U+=i*ie,B+=i*de,R+=i*le,L+=i*ne,D+=i*ue,M+=i*fe,g+=i*Se,x+=i*ge,S+=i*we,v+=i*ve,E+=i*_e,P+=i*Pe,H+=i*qe,Q+=i*$e,re+=i*Ue,i=f[15],U+=i*l,B+=i*ie,R+=i*de,L+=i*le,D+=i*ne,M+=i*ue,g+=i*fe,x+=i*Se,S+=i*ge,v+=i*we,E+=i*ve,P+=i*_e,H+=i*Pe,Q+=i*qe,re+=i*$e,ee+=i*Ue,y+=38*B,m+=38*R,_+=38*L,T+=38*D,F+=38*M,k+=38*g,he+=38*x,q+=38*S,G+=38*v,V+=38*E,Z+=38*P,X+=38*H,J+=38*Q,Y+=38*re,W+=38*ee,h=1,i=y+h+65535,h=Math.floor(i/65536),y=i-h*65536,i=m+h+65535,h=Math.floor(i/65536),m=i-h*65536,i=_+h+65535,h=Math.floor(i/65536),_=i-h*65536,i=T+h+65535,h=Math.floor(i/65536),T=i-h*65536,i=F+h+65535,h=Math.floor(i/65536),F=i-h*65536,i=k+h+65535,h=Math.floor(i/65536),k=i-h*65536,i=he+h+65535,h=Math.floor(i/65536),he=i-h*65536,i=q+h+65535,h=Math.floor(i/65536),q=i-h*65536,i=G+h+65535,h=Math.floor(i/65536),G=i-h*65536,i=V+h+65535,h=Math.floor(i/65536),V=i-h*65536,i=Z+h+65535,h=Math.floor(i/65536),Z=i-h*65536,i=X+h+65535,h=Math.floor(i/65536),X=i-h*65536,i=J+h+65535,h=Math.floor(i/65536),J=i-h*65536,i=Y+h+65535,h=Math.floor(i/65536),Y=i-h*65536,i=W+h+65535,h=Math.floor(i/65536),W=i-h*65536,i=U+h+65535,h=Math.floor(i/65536),U=i-h*65536,y+=h-1+37*(h-1),h=1,i=y+h+65535,h=Math.floor(i/65536),y=i-h*65536,i=m+h+65535,h=Math.floor(i/65536),m=i-h*65536,i=_+h+65535,h=Math.floor(i/65536),_=i-h*65536,i=T+h+65535,h=Math.floor(i/65536),T=i-h*65536,i=F+h+65535,h=Math.floor(i/65536),F=i-h*65536,i=k+h+65535,h=Math.floor(i/65536),k=i-h*65536,i=he+h+65535,h=Math.floor(i/65536),he=i-h*65536,i=q+h+65535,h=Math.floor(i/65536),q=i-h*65536,i=G+h+65535,h=Math.floor(i/65536),G=i-h*65536,i=V+h+65535,h=Math.floor(i/65536),V=i-h*65536,i=Z+h+65535,h=Math.floor(i/65536),Z=i-h*65536,i=X+h+65535,h=Math.floor(i/65536),X=i-h*65536,i=J+h+65535,h=Math.floor(i/65536),J=i-h*65536,i=Y+h+65535,h=Math.floor(i/65536),Y=i-h*65536,i=W+h+65535,h=Math.floor(i/65536),W=i-h*65536,i=U+h+65535,h=Math.floor(i/65536),U=i-h*65536,y+=h-1+37*(h-1),a[0]=y,a[1]=m,a[2]=_,a[3]=T,a[4]=F,a[5]=k,a[6]=he,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 Ye(a,f){ce(a,f,f)}function yo(a,f){var u=t(),i;for(i=0;i<16;i++)u[i]=f[i];for(i=253;i>=0;i--)if(Ye(u,u),i!==2&&i!==4)ce(u,u,f);for(i=0;i<16;i++)a[i]=u[i]}function mo(a,f){var u=t(),i;for(i=0;i<16;i++)u[i]=f[i];for(i=250;i>=0;i--)if(Ye(u,u),i!==1)ce(u,u,f);for(i=0;i<16;i++)a[i]=u[i]}function Lr(a,f,u){var i=new Uint8Array(32),h=new Float64Array(80),y,m,_=t(),T=t(),F=t(),k=t(),he=t(),q=t();for(m=0;m<31;m++)i[m]=f[m];i[31]=f[31]&127|64,i[0]&=248,rs(h,u);for(m=0;m<16;m++)T[m]=h[m],k[m]=_[m]=F[m]=0;_[0]=k[0]=1;for(m=254;m>=0;--m)y=i[m>>>3]>>>(m&7)&1,Ht(_,T,y),Ht(F,k,y),Qe(he,_,F),et(_,_,F),Qe(F,T,k),et(T,T,k),Ye(k,he),Ye(q,_),ce(_,F,_),ce(F,T,he),Qe(he,_,F),et(_,_,F),Ye(T,_),et(F,k,q),ce(_,F,d),Qe(_,_,k),ce(F,F,_),ce(_,k,q),ce(k,T,h),Ye(T,he),Ht(_,T,y),Ht(F,k,y);for(m=0;m<16;m++)h[m+16]=_[m],h[m+32]=F[m],h[m+48]=T[m],h[m+64]=k[m];var G=h.subarray(32),V=h.subarray(16);return yo(G,G),ce(V,V,G),zt(a,V),0}function Dr(a,f){return Lr(a,f,s)}function go(a,f){return r(f,32),Dr(a,f)}function Fr(a,f,u){var i=new Uint8Array(32);return Lr(i,u,f),$r(a,n,i,It)}var xo=Qn,nh=es;function sh(a,f,u,i,h,y){var m=new Uint8Array(32);return Fr(m,h,y),xo(a,f,u,i,m)}function ih(a,f,u,i,h,y){var m=new Uint8Array(32);return Fr(m,h,y),nh(a,f,u,i,m)}var wo=[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 vo(a,f,u,i){var h=new Int32Array(16),y=new Int32Array(16),m,_,T,F,k,he,q,G,V,Z,X,J,Y,W,U,B,R,L,D,M,g,x,S,v,E,P,H=a[0],Q=a[1],re=a[2],ee=a[3],l=a[4],ie=a[5],de=a[6],le=a[7],ne=f[0],ue=f[1],fe=f[2],Se=f[3],ge=f[4],we=f[5],ve=f[6],_e=f[7],Pe=0;while(i>=128){for(D=0;D<16;D++)M=8*D+Pe,h[D]=u[M+0]<<24|u[M+1]<<16|u[M+2]<<8|u[M+3],y[D]=u[M+4]<<24|u[M+5]<<16|u[M+6]<<8|u[M+7];for(D=0;D<80;D++)if(m=H,_=Q,T=re,F=ee,k=l,he=ie,q=de,G=le,V=ne,Z=ue,X=fe,J=Se,Y=ge,W=we,U=ve,B=_e,g=le,x=_e,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&de,x=ge&we^~ge&ve,S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,g=wo[D*2],x=wo[D*2+1],S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,g=h[D%16],x=y[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=(H>>>28|ne<<4)^(ne>>>2|H<<30)^(ne>>>7|H<<25),x=(ne>>>28|H<<4)^(H>>>2|ne<<30)^(H>>>7|ne<<25),S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,g=H&Q^H&re^Q&re,x=ne&ue^ne&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=k,de=he,le=q,H=G,ue=V,fe=Z,Se=X,ge=J,we=Y,ve=W,_e=U,ne=B,D%16===15)for(M=0;M<16;M++)g=h[M],x=y[M],S=x&65535,v=x>>>16,E=g&65535,P=g>>>16,g=h[(M+9)%16],x=y[(M+9)%16],S+=x&65535,v+=x>>>16,E+=g&65535,P+=g>>>16,R=h[(M+1)%16],L=y[(M+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=h[(M+14)%16],L=y[(M+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,h[M]=E&65535|P<<16,y[M]=S&65535|v<<16;g=H,x=ne,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]=H=E&65535|P<<16,f[0]=ne=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=Se,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]=Se=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=we,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]=we=S&65535|v<<16,g=de,x=ve,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]=de=E&65535|P<<16,f[6]=ve=S&65535|v<<16,g=le,x=_e,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]=_e=S&65535|v<<16,Pe+=128,i-=128}return i}function jt(a,f,u){var i=new Int32Array(8),h=new Int32Array(8),y=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,h[0]=4089235720,h[1]=2227873595,h[2]=4271175723,h[3]=1595750129,h[4]=2917565137,h[5]=725511199,h[6]=4215389547,h[7]=327033209,vo(i,h,f,u),u%=128;for(m=0;m<u;m++)y[m]=f[_-u+m];y[u]=128,u=256-128*(u<112?1:0),y[u-9]=0,K(y,u-8,_/536870912|0,_<<3),vo(i,h,y,u);for(m=0;m<8;m++)K(a,8*m,i[m],h[m]);return 0}function Br(a,f){var u=t(),i=t(),h=t(),y=t(),m=t(),_=t(),T=t(),F=t(),k=t();et(u,a[1],a[0]),et(k,f[1],f[0]),ce(u,u,k),Qe(i,a[0],a[1]),Qe(k,f[0],f[1]),ce(i,i,k),ce(h,a[3],f[3]),ce(h,h,w),ce(y,a[2],f[2]),Qe(y,y,y),et(m,i,u),et(_,y,h),Qe(T,y,h),Qe(F,i,u),ce(a[0],m,_),ce(a[1],F,T),ce(a[2],T,_),ce(a[3],m,F)}function _o(a,f,u){var i;for(i=0;i<4;i++)Ht(a[i],f[i],u)}function ns(a,f){var u=t(),i=t(),h=t();yo(h,f[2]),ce(u,f[0],h),ce(i,f[1],h),zt(a,i),a[31]^=bo(u)<<7}function ss(a,f,u){var i,h;dt(a[0],o),dt(a[1],c),dt(a[2],c),dt(a[3],o);for(h=255;h>=0;--h)i=u[h/8|0]>>(h&7)&1,_o(a,f,i),Br(f,a),Br(a,a),_o(a,f,i)}function Kr(a,f){var u=[t(),t(),t(),t()];dt(u[0],A),dt(u[1],I),dt(u[2],c),ce(u[3],A,I),ss(a,u,f)}function is(a,f,u){var i=new Uint8Array(64),h=[t(),t(),t(),t()],y;if(!u)r(f,32);jt(i,f,32),i[0]&=248,i[31]&=127,i[31]|=64,Kr(h,i),ns(a,h);for(y=0;y<32;y++)f[y+32]=a[y];return 0}var Hr=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 os(a,f){var u,i,h,y;for(i=63;i>=32;--i){u=0;for(h=i-32,y=i-12;h<y;++h)f[h]+=u-16*f[i]*Hr[h-(i-32)],u=Math.floor((f[h]+128)/256),f[h]-=u*256;f[h]+=u,f[i]=0}u=0;for(h=0;h<32;h++)f[h]+=u-(f[31]>>4)*Hr[h],u=f[h]>>8,f[h]&=255;for(h=0;h<32;h++)f[h]-=u*Hr[h];for(i=0;i<32;i++)f[i+1]+=f[i]>>8,a[i]=f[i]&255}function as(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;os(a,f)}function Eo(a,f,u,i){var h=new Uint8Array(64),y=new Uint8Array(64),m=new Uint8Array(64),_,T,F=new Float64Array(64),k=[t(),t(),t(),t()];jt(h,i,32),h[0]&=248,h[31]&=127,h[31]|=64;var he=u+64;for(_=0;_<u;_++)a[64+_]=f[_];for(_=0;_<32;_++)a[32+_]=h[32+_];jt(m,a.subarray(32),u+32),as(m),Kr(k,m),ns(a,k);for(_=32;_<64;_++)a[_]=i[_];jt(y,a,u+64),as(y);for(_=0;_<64;_++)F[_]=0;for(_=0;_<32;_++)F[_]=m[_];for(_=0;_<32;_++)for(T=0;T<32;T++)F[_+T]+=y[_]*h[T];return os(a.subarray(32),F),he}function oh(a,f){var u=t(),i=t(),h=t(),y=t(),m=t(),_=t(),T=t();if(dt(a[2],c),rs(a[1],f),Ye(h,a[1]),ce(y,h,p),et(h,h,a[2]),Qe(y,a[2],y),Ye(m,y),Ye(_,m),ce(T,_,m),ce(u,T,h),ce(u,u,y),mo(u,u),ce(u,u,h),ce(u,u,y),ce(u,u,y),ce(a[0],u,y),Ye(i,a[0]),ce(i,i,y),po(i,h))ce(a[0],a[0],O);if(Ye(i,a[0]),ce(i,i,y),po(i,h))return-1;if(bo(a[0])===f[31]>>7)et(a[0],o,a[0]);return ce(a[3],a[0],a[1]),0}function cs(a,f,u,i){var h,y=new Uint8Array(32),m=new Uint8Array(64),_=[t(),t(),t(),t()],T=[t(),t(),t(),t()];if(u<64)return-1;if(oh(T,i))return-1;for(h=0;h<u;h++)a[h]=f[h];for(h=0;h<32;h++)a[h+32]=i[h];if(jt(m,a,u),as(m),ss(_,T,m),Kr(T,f.subarray(32)),Br(_,T),ns(y,_),u-=64,ye(f,0,y,0)){for(h=0;h<u;h++)a[h]=0;return-1}for(h=0;h<u;h++)a[h]=f[h+64];return u}var us=32,zr=24,hr=32,Gt=16,dr=32,Gr=32,lr=32,pr=32,fs=32,So=zr,ah=hr,ch=Gt,lt=64,Nt=32,Vt=64,hs=32,ds=64;e.lowlevel={crypto_core_hsalsa20:$r,crypto_stream_xor:Xn,crypto_stream:ho,crypto_stream_salsa20_xor:uo,crypto_stream_salsa20:fo,crypto_onetimeauth:Zn,crypto_onetimeauth_verify:lo,crypto_verify_16:Oe,crypto_verify_32:ye,crypto_secretbox:Qn,crypto_secretbox_open:es,crypto_scalarmult:Lr,crypto_scalarmult_base:Dr,crypto_box_beforenm:Fr,crypto_box_afternm:xo,crypto_box:sh,crypto_box_open:ih,crypto_box_keypair:go,crypto_hash:jt,crypto_sign:Eo,crypto_sign_keypair:is,crypto_sign_open:cs,crypto_secretbox_KEYBYTES:us,crypto_secretbox_NONCEBYTES:zr,crypto_secretbox_ZEROBYTES:hr,crypto_secretbox_BOXZEROBYTES:Gt,crypto_scalarmult_BYTES:dr,crypto_scalarmult_SCALARBYTES:Gr,crypto_box_PUBLICKEYBYTES:lr,crypto_box_SECRETKEYBYTES:pr,crypto_box_BEFORENMBYTES:fs,crypto_box_NONCEBYTES:So,crypto_box_ZEROBYTES:ah,crypto_box_BOXZEROBYTES:ch,crypto_sign_BYTES:lt,crypto_sign_PUBLICKEYBYTES:Nt,crypto_sign_SECRETKEYBYTES:Vt,crypto_sign_SEEDBYTES:hs,crypto_hash_BYTES:ds,gf:t,D:p,L:Hr,pack25519:zt,unpack25519:rs,M:ce,A:Qe,S:Ye,Z:et,pow2523:mo,add:Br,set25519:dt,modL:os,scalarmult:ss,scalarbase:Kr};function Ao(a,f){if(a.length!==us)throw Error("bad key size");if(f.length!==zr)throw Error("bad nonce size")}function uh(a,f){if(a.length!==lr)throw Error("bad public key size");if(f.length!==pr)throw Error("bad secret key size")}function ze(){for(var a=0;a<arguments.length;a++)if(!(arguments[a]instanceof Uint8Array))throw TypeError("unexpected type, use Uint8Array")}function Oo(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){ze(a,f,u),Ao(u,f);var i=new Uint8Array(hr+a.length),h=new Uint8Array(i.length);for(var y=0;y<a.length;y++)i[y+hr]=a[y];return Qn(h,i,i.length,f,u),h.subarray(Gt)},e.secretbox.open=function(a,f,u){ze(a,f,u),Ao(u,f);var i=new Uint8Array(Gt+a.length),h=new Uint8Array(i.length);for(var y=0;y<a.length;y++)i[y+Gt]=a[y];if(i.length<32)return null;if(es(h,i,i.length,f,u)!==0)return null;return h.subarray(hr)},e.secretbox.keyLength=us,e.secretbox.nonceLength=zr,e.secretbox.overheadLength=Gt,e.scalarMult=function(a,f){if(ze(a,f),a.length!==Gr)throw Error("bad n size");if(f.length!==dr)throw Error("bad p size");var u=new Uint8Array(dr);return Lr(u,a,f),u},e.scalarMult.base=function(a){if(ze(a),a.length!==Gr)throw Error("bad n size");var f=new Uint8Array(dr);return Dr(f,a),f},e.scalarMult.scalarLength=Gr,e.scalarMult.groupElementLength=dr,e.box=function(a,f,u,i){var h=e.box.before(u,i);return e.secretbox(a,f,h)},e.box.before=function(a,f){ze(a,f),uh(a,f);var u=new Uint8Array(fs);return Fr(u,a,f),u},e.box.after=e.secretbox,e.box.open=function(a,f,u,i){var h=e.box.before(u,i);return e.secretbox.open(a,f,h)},e.box.open.after=e.secretbox.open,e.box.keyPair=function(){var a=new Uint8Array(lr),f=new Uint8Array(pr);return go(a,f),{publicKey:a,secretKey:f}},e.box.keyPair.fromSecretKey=function(a){if(ze(a),a.length!==pr)throw Error("bad secret key size");var f=new Uint8Array(lr);return Dr(f,a),{publicKey:f,secretKey:new Uint8Array(a)}},e.box.publicKeyLength=lr,e.box.secretKeyLength=pr,e.box.sharedKeyLength=fs,e.box.nonceLength=So,e.box.overheadLength=e.secretbox.overheadLength,e.sign=function(a,f){if(ze(a,f),f.length!==Vt)throw Error("bad secret key size");var u=new Uint8Array(lt+a.length);return Eo(u,a,a.length,f),u},e.sign.open=function(a,f){if(ze(a,f),f.length!==Nt)throw Error("bad public key size");var u=new Uint8Array(a.length),i=cs(u,a,a.length,f);if(i<0)return null;var h=new Uint8Array(i);for(var y=0;y<h.length;y++)h[y]=u[y];return h},e.sign.detached=function(a,f){var u=e.sign(a,f),i=new Uint8Array(lt);for(var h=0;h<i.length;h++)i[h]=u[h];return i},e.sign.detached.verify=function(a,f,u){if(ze(a,f,u),f.length!==lt)throw Error("bad signature size");if(u.length!==Nt)throw Error("bad public key size");var i=new Uint8Array(lt+a.length),h=new Uint8Array(lt+a.length),y;for(y=0;y<lt;y++)i[y]=f[y];for(y=0;y<a.length;y++)i[y+lt]=a[y];return cs(h,i,i.length,u)>=0},e.sign.keyPair=function(){var a=new Uint8Array(Nt),f=new Uint8Array(Vt);return is(a,f),{publicKey:a,secretKey:f}},e.sign.keyPair.fromSecretKey=function(a){if(ze(a),a.length!==Vt)throw Error("bad secret key size");var f=new Uint8Array(Nt);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(ze(a),a.length!==hs)throw Error("bad seed size");var f=new Uint8Array(Nt),u=new Uint8Array(Vt);for(var i=0;i<32;i++)u[i]=a[i];return is(f,u,!0),{publicKey:f,secretKey:u}},e.sign.publicKeyLength=Nt,e.sign.secretKeyLength=Vt,e.sign.seedLength=hs,e.sign.signatureLength=lt,e.hash=function(a){ze(a);var f=new Uint8Array(ds);return jt(f,a,a.length),f},e.hash.hashLength=ds,e.verify=function(a,f){if(ze(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 h,y=new Uint8Array(i);for(h=0;h<i;h+=f)a.getRandomValues(y.subarray(h,h+Math.min(i-h,f)));for(h=0;h<i;h++)u[h]=y[h];Oo(y)})}else if(a=To("crypto"),a&&a.randomBytes)e.setPRNG(function(u,i){var h,y=a.randomBytes(i);for(h=0;h<i;h++)u[h]=y[h];Oo(y)})}()})(typeof ln<"u"&&Tg?Tg:self.nacl=self.nacl||{})});var vr=z(function(wr){var Tl=wr&&wr.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(wr,"__esModule",{value:!0});var Il=Tl(ec());wr.default=Il.default});var rc=z(function(Zt){var jl=Zt&&Zt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Zt,"__esModule",{value:!0});Zt.KP=void 0;var pn=xr(),ke=kt(),Xt=jl(vr());class tc{seed;constructor(e){this.seed=e}getRawSeed(){if(!this.seed)throw new ke.NKeysError(ke.NKeysErrorCode.ClearedPair);return pn.Codec.decodeSeed(this.seed).buf}getSeed(){if(!this.seed)throw new ke.NKeysError(ke.NKeysErrorCode.ClearedPair);return this.seed}getPublicKey(){if(!this.seed)throw new ke.NKeysError(ke.NKeysErrorCode.ClearedPair);let e=pn.Codec.decodeSeed(this.seed),t=Xt.default.sign.keyPair.fromSeed(this.getRawSeed()),r=pn.Codec.encode(e.prefix,t.publicKey);return new TextDecoder().decode(r)}getPrivateKey(){if(!this.seed)throw new ke.NKeysError(ke.NKeysErrorCode.ClearedPair);let e=Xt.default.sign.keyPair.fromSeed(this.getRawSeed());return pn.Codec.encode(ke.Prefix.Private,e.secretKey)}sign(e){if(!this.seed)throw new ke.NKeysError(ke.NKeysErrorCode.ClearedPair);let t=Xt.default.sign.keyPair.fromSeed(this.getRawSeed());return Xt.default.sign.detached(e,t.secretKey)}verify(e,t){if(!this.seed)throw new ke.NKeysError(ke.NKeysErrorCode.ClearedPair);let r=Xt.default.sign.keyPair.fromSeed(this.getRawSeed());return Xt.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 ke.NKeysError(ke.NKeysErrorCode.InvalidNKeyOperation)}open(e,t){throw new ke.NKeysError(ke.NKeysErrorCode.InvalidNKeyOperation)}}Zt.KP=tc});var sc=z(function(Qt){var Nl=Qt&&Qt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Qt,"__esModule",{value:!0});Qt.PublicKey=void 0;var Cl=xr(),Ae=kt(),Ml=Nl(vr());class nc{publicKey;constructor(e){this.publicKey=e}getPublicKey(){if(!this.publicKey)throw new Ae.NKeysError(Ae.NKeysErrorCode.ClearedPair);return new TextDecoder().decode(this.publicKey)}getPrivateKey(){if(!this.publicKey)throw new Ae.NKeysError(Ae.NKeysErrorCode.ClearedPair);throw new Ae.NKeysError(Ae.NKeysErrorCode.PublicKeyOnly)}getSeed(){if(!this.publicKey)throw new Ae.NKeysError(Ae.NKeysErrorCode.ClearedPair);throw new Ae.NKeysError(Ae.NKeysErrorCode.PublicKeyOnly)}sign(e){if(!this.publicKey)throw new Ae.NKeysError(Ae.NKeysErrorCode.ClearedPair);throw new Ae.NKeysError(Ae.NKeysErrorCode.CannotSign)}verify(e,t){if(!this.publicKey)throw new Ae.NKeysError(Ae.NKeysErrorCode.ClearedPair);let r=Cl.Codec._decode(this.publicKey);return Ml.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 Ae.NKeysError(Ae.NKeysErrorCode.InvalidNKeyOperation)}open(e,t){throw new Ae.NKeysError(Ae.NKeysErrorCode.InvalidNKeyOperation)}}Qt.PublicKey=nc});var oc=z(function(Le){var kl=Le&&Le.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Le,"__esModule",{value:!0});Le.CurveKP=Le.curveNonceLen=Le.curveKeyLen=void 0;var xe=kt(),bn=kl(vr()),ti=xr(),yn=kt(),Rl=ei(),ql=Zs();Le.curveKeyLen=32;var $l=35;Le.curveNonceLen=24;var Rt=[120,107,118,49];class ic{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 xe.NKeysError(xe.NKeysErrorCode.ClearedPair);return ti.Codec.encode(yn.Prefix.Private,this.seed)}getPublicKey(){if(!this.seed)throw new xe.NKeysError(xe.NKeysErrorCode.ClearedPair);let e=bn.default.scalarMult.base(this.seed),t=ti.Codec.encode(yn.Prefix.Curve,e);return new TextDecoder().decode(t)}getSeed(){if(!this.seed)throw new xe.NKeysError(xe.NKeysErrorCode.ClearedPair);return ti.Codec.encodeSeed(yn.Prefix.Curve,this.seed)}sign(){throw new xe.NKeysError(xe.NKeysErrorCode.InvalidCurveOperation)}verify(){throw new xe.NKeysError(xe.NKeysErrorCode.InvalidCurveOperation)}decodePubCurveKey(e){try{let t=Rl.base32.decode(new TextEncoder().encode(e));if(t.byteLength!==$l)throw new xe.NKeysError(xe.NKeysErrorCode.InvalidCurveKey);if(t[0]!==yn.Prefix.Curve)throw new xe.NKeysError(xe.NKeysErrorCode.InvalidPublicKey);let r=t.byteLength-2,s=new DataView(t.buffer).getUint16(r,!0),o=t.slice(0,r);if(!ql.crc16.validate(o,s))throw new xe.NKeysError(xe.NKeysErrorCode.InvalidChecksum);return o.slice(1)}catch(t){throw new xe.NKeysError(xe.NKeysErrorCode.InvalidRecipient,{cause:t})}}seal(e,t,r){if(!this.seed)throw new xe.NKeysError(xe.NKeysErrorCode.ClearedPair);if(!r)r=bn.default.randomBytes(Le.curveNonceLen);let n=this.decodePubCurveKey(t),s=new Uint8Array(Rt.length+Le.curveNonceLen);s.set(Rt,0),s.set(r,Rt.length);let o=bn.default.box(e,r,n,this.seed),c=new Uint8Array(s.length+o.length);return c.set(s),c.set(o,s.length),c}open(e,t){if(!this.seed)throw new xe.NKeysError(xe.NKeysErrorCode.ClearedPair);if(e.length<=Le.curveNonceLen+Rt.length)throw new xe.NKeysError(xe.NKeysErrorCode.InvalidEncrypted);for(let s=0;s<Rt.length;s++)if(e[s]!==Rt[s])throw new xe.NKeysError(xe.NKeysErrorCode.InvalidEncrypted);let r=this.decodePubCurveKey(t);e=e.slice(Rt.length);let n=e.slice(0,Le.curveNonceLen);return e=e.slice(Le.curveNonceLen),bn.default.box.open(e,n,r,this.seed)}}Le.CurveKP=ic});var kt=z(function(Ee){var Ul=Ee&&Ee.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ee,"__esModule",{value:!0});Ee.NKeysError=Ee.NKeysErrorCode=Ee.Prefixes=Ee.Prefix=void 0;Ee.createPair=qt;Ee.createOperator=Fl;Ee.createAccount=Bl;Ee.createUser=Kl;Ee.createCluster=Hl;Ee.createServer=zl;Ee.createCurve=Gl;Ee.fromPublic=Vl;Ee.fromCurveSeed=cc;Ee.fromSeed=Jl;var ac=rc(),Ll=sc(),xn=xr(),mn=oc(),Dl=Ul(vr());function qt(e){let t=e===ae.Curve?mn.curveKeyLen:32,r=Dl.default.randomBytes(t),n=xn.Codec.encodeSeed(e,new Uint8Array(r));return e===ae.Curve?new mn.CurveKP(new Uint8Array(r)):new ac.KP(n)}function Fl(){return qt(ae.Operator)}function Bl(){return qt(ae.Account)}function Kl(){return qt(ae.User)}function Hl(){return qt(ae.Cluster)}function zl(){return qt(ae.Server)}function Gl(){return qt(ae.Curve)}function Vl(e){let t=new TextEncoder().encode(e),r=xn.Codec._decode(t),n=gn.parsePrefix(r[0]);if(gn.isValidPublicPrefix(n))return new Ll.PublicKey(t);throw new Er(_r.InvalidPublicKey)}function cc(e){let t=xn.Codec.decodeSeed(e);if(t.prefix!==ae.Curve)throw new Er(_r.InvalidCurveSeed);if(t.buf.byteLength!==mn.curveKeyLen)throw new Er(_r.InvalidSeedLen);return new mn.CurveKP(t.buf)}function Jl(e){if(xn.Codec.decodeSeed(e).prefix===ae.Curve)return cc(e);return new ac.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||(Ee.Prefix=ae={}));class gn{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}}}Ee.Prefixes=gn;var _r;(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"})(_r||(Ee.NKeysErrorCode=_r={}));class Er extends Error{code;constructor(e,t){super(e,t);this.code=e}}Ee.NKeysError=Er});var fc=z(function(uc){Object.defineProperty(uc,"__esModule",{value:!0});uc.encode=Wl;uc.decode=Yl;uc.dump=Xl;function Wl(e){return btoa(String.fromCharCode(...e))}function Yl(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function Xl(e,t){if(t)console.log(t);let r=[];for(let n=0;n<e.byteLength;n++){if(n%8===0)r.push(`
|
|
7
|
-
`);let s=e[n].toString(16);if(s.length===1)s="0"+s;r.push(s)}console.log(r.join(" "))}});var lc=z(function(hc){Object.defineProperty(hc,"__esModule",{value:!0});hc.version=void 0;hc.version="2.0.3"});var ri=z(function(Te){Object.defineProperty(Te,"__esModule",{value:!0});Te.version=Te.encode=Te.decode=Te.Prefixes=Te.Prefix=Te.NKeysErrorCode=Te.NKeysError=Te.fromSeed=Te.fromPublic=Te.fromCurveSeed=Te.createUser=Te.createServer=Te.createPair=Te.createOperator=Te.createCurve=Te.createCluster=Te.createAccount=void 0;var Fe=kt();Object.defineProperty(Te,"createAccount",{enumerable:!0,get:function(){return Fe.createAccount}});Object.defineProperty(Te,"createCluster",{enumerable:!0,get:function(){return Fe.createCluster}});Object.defineProperty(Te,"createCurve",{enumerable:!0,get:function(){return Fe.createCurve}});Object.defineProperty(Te,"createOperator",{enumerable:!0,get:function(){return Fe.createOperator}});Object.defineProperty(Te,"createPair",{enumerable:!0,get:function(){return Fe.createPair}});Object.defineProperty(Te,"createServer",{enumerable:!0,get:function(){return Fe.createServer}});Object.defineProperty(Te,"createUser",{enumerable:!0,get:function(){return Fe.createUser}});Object.defineProperty(Te,"fromCurveSeed",{enumerable:!0,get:function(){return Fe.fromCurveSeed}});Object.defineProperty(Te,"fromPublic",{enumerable:!0,get:function(){return Fe.fromPublic}});Object.defineProperty(Te,"fromSeed",{enumerable:!0,get:function(){return Fe.fromSeed}});Object.defineProperty(Te,"NKeysError",{enumerable:!0,get:function(){return Fe.NKeysError}});Object.defineProperty(Te,"NKeysErrorCode",{enumerable:!0,get:function(){return Fe.NKeysErrorCode}});Object.defineProperty(Te,"Prefix",{enumerable:!0,get:function(){return Fe.Prefix}});Object.defineProperty(Te,"Prefixes",{enumerable:!0,get:function(){return Fe.Prefixes}});var pc=fc();Object.defineProperty(Te,"decode",{enumerable:!0,get:function(){return pc.decode}});Object.defineProperty(Te,"encode",{enumerable:!0,get:function(){return pc.encode}});var tp=lc();Object.defineProperty(Te,"version",{enumerable:!0,get:function(){return tp.version}})});var ni=z(function(ct){var np=ct&&ct.__createBinding||(Object.create?function(e,t,r,n){if(n===void 0)n=r;var s=Object.getOwnPropertyDescriptor(t,r);if(!s||("get"in s?!t.__esModule:s.writable||s.configurable))s={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,n,s)}:function(e,t,r,n){if(n===void 0)n=r;e[n]=t[r]}),sp=ct&&ct.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ip=ct&&ct.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var s in r)if(Object.prototype.hasOwnProperty.call(r,s))n[n.length]=s;return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null){for(var n=e(t),s=0;s<n.length;s++)if(n[s]!=="default")np(r,t,n[s])}return sp(r,t),r}}();Object.defineProperty(ct,"__esModule",{value:!0});ct.nkeys=void 0;ct.nkeys=ip(ri())});var ii=z(function(gc){Object.defineProperty(gc,"__esModule",{value:!0});gc.multiAuthenticator=op;gc.noAuthFn=ap;gc.usernamePasswordAuthenticator=cp;gc.tokenAuthenticator=up;gc.nkeyAuthenticator=yc;gc.jwtAuthenticator=mc;gc.credsAuthenticator=fp;var bc=ni(),si=Ge();function op(e){return(t)=>{let r={};return e.forEach((n)=>{let s=n(t)||{};r=Object.assign(r,s)}),r}}function ap(){return()=>{return}}function cp(e,t){return()=>{let r=typeof e==="function"?e():e,n=typeof t==="function"?t():t;return{user:r,pass:n}}}function up(e){return()=>({auth_token:typeof e==="function"?e():e})}function yc(e){return(t)=>{let r=typeof e==="function"?e():e,n=r?bc.nkeys.fromSeed(r):void 0,s=n?n.getPublicKey():"",o=si.TE.encode(t||""),c=n!==void 0&&t?n.sign(o):void 0,d=c?bc.nkeys.encode(c):"";return{nkey:s,sig:d}}}function mc(e,t){return(r)=>{let n=typeof e==="function"?e():e,s=yc(t),{nkey:o,sig:c}=s(r);return{jwt:n,nkey:o,sig:c}}}function fp(e){let t=typeof e!=="function"?()=>e:e,r=()=>{let o=/\s*(?:(?:[-]{3,}[^\n]*[-]{3,}\n)(.+)(?:\n\s*[-]{3,}[^\n]*[-]{3,}\n))/ig,c=si.TD.decode(t()),d=o.exec(c);if(!d)throw Error("unable to parse credentials");let p=d[1].trim();if(d=o.exec(c),!d)throw Error("unable to parse credentials");let w=si.TE.encode(d[1].trim());return{jwt:p,seed:w}};return mc(()=>{let{jwt:o}=r();return o},()=>{let{seed:o}=r();return o})}});var Ar=z(function(vc){Object.defineProperty(vc,"__esModule",{value:!0});vc.DEFAULT_RECONNECT_TIME_WAIT=vc.DEFAULT_MAX_PING_OUT=vc.DEFAULT_PING_INTERVAL=vc.DEFAULT_JITTER_TLS=vc.DEFAULT_JITTER=vc.DEFAULT_MAX_RECONNECT_ATTEMPTS=void 0;vc.defaultOptions=xc;vc.hasWsProtocol=xp;vc.buildAuthenticator=wc;vc.parseOptions=wp;vc.checkOptions=vp;vc.checkUnsupportedOption=_p;var gp=tt(),oi=Ct(),ai=wt(),wn=ii(),Sr=Ve();vc.DEFAULT_MAX_RECONNECT_ATTEMPTS=10;vc.DEFAULT_JITTER=100;vc.DEFAULT_JITTER_TLS=1000;vc.DEFAULT_PING_INTERVAL=120000;vc.DEFAULT_MAX_PING_OUT=2;vc.DEFAULT_RECONNECT_TIME_WAIT=2000;function xc(){return{maxPingOut:vc.DEFAULT_MAX_PING_OUT,maxReconnectAttempts:vc.DEFAULT_MAX_RECONNECT_ATTEMPTS,noRandomize:!1,pedantic:!1,pingInterval:vc.DEFAULT_PING_INTERVAL,reconnect:!0,reconnectJitter:vc.DEFAULT_JITTER,reconnectJitterTLS:vc.DEFAULT_JITTER_TLS,reconnectTimeWait:vc.DEFAULT_RECONNECT_TIME_WAIT,tls:void 0,verbose:!1,waitOnFirstConnect:!1,ignoreAuthErrorAbort:!1}}function xp(e){if(e){let{servers:t}=e;if(typeof t==="string")t=[t];if(t)for(let r=0;r<t.length;r++){let n=t[r].toLowerCase();if(n.startsWith("ws://")||n.startsWith("wss://"))return!0}}return!1}function wc(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,wn.tokenAuthenticator)(e.token));if(e.user)t.push((0,wn.usernamePasswordAuthenticator)(e.user,e.pass));return t.length===0?(0,wn.noAuthFn)():(0,wn.multiAuthenticator)(t)}function wp(e){let t=`${ai.DEFAULT_HOST}:${(0,oi.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 Sr.InvalidArgumentError.format(["servers","port"],"are mutually exclusive");if(e.servers.length===0&&e.port)e.servers=[`${ai.DEFAULT_HOST}:${e.port}`];if(e.servers&&e.servers.length===0)e.servers=[t];let r=(0,gp.extend)(xc(),e);if(r.authenticator=wc(r),["reconnectDelayHandler","authenticator"].forEach((n)=>{if(r[n]&&typeof r[n]!=="function")throw TypeError(`'${n}' must be a function`)}),!r.reconnectDelayHandler)r.reconnectDelayHandler=()=>{let n=r.tls?r.reconnectJitterTLS:r.reconnectJitter;if(n)n++,n=Math.floor(Math.random()*n);return r.reconnectTimeWait+n};if(r.inboxPrefix)(0,ai.createInbox)(r.inboxPrefix);if(r.resolve===void 0)r.resolve=typeof(0,oi.getResolveFn)()==="function";if(r.resolve){if(typeof(0,oi.getResolveFn)()!=="function")throw Sr.InvalidArgumentError.format("resolve","is not supported in the current runtime")}return r}function vp(e,t){let{proto:r,tls_required:n,tls_available:s}=e;if((r===void 0||r<1)&&t.noEcho)throw new Sr.errors.ConnectionError("server does not support 'noEcho'");let o=n||s||!1;if(t.tls&&!o)throw new Sr.errors.ConnectionError("server does not support 'tls'")}function _p(e,t){if(t)throw Sr.InvalidArgumentError.format(e,"is not supported")}});var Or=z(function(jc){Object.defineProperty(jc,"__esModule",{value:!0});jc.ProtocolHandler=jc.Subscriptions=jc.SubscriptionImpl=jc.Connect=jc.INFO=void 0;var ut=Ge(),$t=Ct(),nt=tt(),Ip=mr(),jp=$s(),Np=sn(),Cp=Ls(),Mp=Ds(),_t=Gs(),kp=Ws(),Pc=dn(),ui=Ar(),Ce=Ve(),Rp=32768;jc.INFO=/^INFO\s+([^\r\n]+)\r\n/i;var qp=(0,ut.encode)(`PONG\r
|
|
8
|
-
`),Tc=(0,ut.encode)(`PING\r
|
|
9
|
-
`),$p="client option reconnectToServer handler failed",Up="returned server is not in the pool";function Lp(e){return e!==null&&typeof e==="object"&&"server"in e&&"delay"in e}class fi{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 n=(t&&typeof t.authenticator==="function"?t.authenticator(r):{})||{};(0,nt.extend)(this,n)}}jc.Connect=fi;class Ic{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 hi extends Np.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 n=!e.options?.noAsyncTraces;if(r.timeout)this.timer=(0,nt.timeout)(r.timeout,n),this.timer.then(()=>{this.timer=void 0}).catch((s)=>{if(this.stop(s),this.noIterator)this.callback(s,{})});if(!this.noIterator)this.iterClosed.then((s)=>{this.closed.resolve(s),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 Ic(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 Ce.errors.ClosedConnectionError);if(this.isClosed())return Promise.reject(new Ce.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}}jc.SubscriptionImpl=hi;class di{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((n)=>n.subject===e.subject&&n.queue===e.queue);else if(e.operation==="publish")r=t.find((n)=>n.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()})}}jc.Subscriptions=di;class vn{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=Rp,this.outMsgs=0,this.inMsgs=0,this.outBytes=0,this.inBytes=0,this.options=e,this.publisher=t,this.subscriptions=new di,this.muxSubscriptions=new Cp.MuxSubscription,this.outbound=new Ip.DataBuffer,this.pongs=[],this.whyClosed="",this.pendingLimit=e.pendingLimit||this.pendingLimit,this.features=new Pc.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 _t.Parser(this),this.heartbeats=new Mp.Heartbeat(this,this.options.pingInterval||ui.DEFAULT_PING_INTERVAL,this.options.maxPingOut||ui.DEFAULT_MAX_PING_OUT)}resetOutbound(){this.outbound.reset();let e=this.pongs;this.pongs=[];let t=new Ce.errors.RequestError("connection disconnected");t.stack="",e.forEach((r)=>{r.reject(t)}),this.parser=new _t.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,$t.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 Ce.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 n of this.transport)this.parser.parse(n)}catch(n){console.log("reader closed",n)}})().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,$t.getResolveFn)(),debug:this.options.debug,randomize:!this.options.noRandomize,resolve:t}),n=null;for(let s of r)try{n=null,this.dispatchStatus({type:"reconnecting"}),await this.dial(s);return}catch(o){n=o}throw n}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():ui.DEFAULT_RECONNECT_TIME_WAIT,r=t,n=this.selectServer();if(!n||this.abortReconnect)if(e)throw e;else if(this.lastError)throw this.lastError;else throw new Ce.errors.ConnectionError("connection refused");let s=Date.now();if(n.lastConnect===0||n.lastConnect+t<=s){let o=n,c=0;if(this.options.reconnectToServer)try{let d=this.servers.snapshotForHandler(),p=this.options.reconnectToServer(d,this.info??null),w;if(Lp(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(Up);if(A!==n)o=A,this.servers.setCurrent(o),this.server=o}}catch(d){let p=d instanceof Error?d:Error(String(d));throw new Ce.errors.ConnectionError(`${$p}: ${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(d){if(e=d,!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,n.lastConnect+t-s),this.dialDelay=(0,nt.delay)(r),await this.dialDelay}}static async connect(e,t){let r=new vn(e,t);return await r.dialLoop(),r}static toError(e){let t=Ce.errors.PermissionViolationError.parse(e);if(t)return t;if(t=Ce.errors.UserAuthenticationExpiredError.parse(e),t)return t;if(t=Ce.errors.AuthorizationError.parse(e),t)return t;return new Ce.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 kp.MsgImpl(e,t,this));if(r.max!==void 0&&r.received>=r.max)r.unsubscribe()}processError(e){let t=(0,ut.decode)(e);if(t.startsWith("'")&&t.endsWith("'"))t=t.slice(1,t.length-1);let r=vn.toError(t);switch(r.constructor){case Ce.errors.PermissionViolationError:{let n=r,s=this.subscriptions.getMux(),o=s?n.subject===s.subject:!1;if(this.subscriptions.handleError(n),this.muxSubscriptions.handleError(o,n),o)this.subscriptions.setMux(null)}}this.dispatchStatus({type:"error",error:r}),this.handleError(r)}handleError(e){if(e instanceof Ce.errors.UserAuthenticationExpiredError||e instanceof Ce.errors.AuthorizationError)this.handleAuthError(e);if(!(e instanceof Ce.errors.PermissionViolationError))this.lastError=e}handleAuthError(e){if((this.lastError instanceof Ce.errors.UserAuthenticationExpiredError||this.lastError instanceof Ce.errors.AuthorizationError)&&this.options.ignoreAuthErrorAbort===!1)this.abortReconnect=!0;if(this.connectError)this.connectError(e);else this.disconnect()}processPing(){this.transport.send(qp)}processPong(){let e=this.pongs.shift();if(e)e.resolve()}processInfo(e){let t=JSON.parse((0,ut.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,Pc.parseSemVer)(t.version)),this.infoReceived=!0,this.transport.isEncrypted())this.servers.updateTLSName();let{version:s,lang:o}=this.transport;try{let c=new fi({version:s,lang:o},this.options,t.nonce);if(t.headers)c.headers=!0,c.no_responders=!0;let d=JSON.stringify(c);this.transport.send((0,ut.encode)(`CONNECT ${d}${$t.CR_LF}`)),this.transport.send(Tc)}catch(c){this.close(c).catch()}}if(r){let{added:s,deleted:o}=r;this.dispatchStatus({type:"update",added:s,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 _t.Kind.MSG:{let{msg:t,data:r}=e;this.processMsg(t,r);break}case _t.Kind.OK:break;case _t.Kind.ERR:this.processError(e.data);break;case _t.Kind.PING:this.processPing();break;case _t.Kind.PONG:this.processPong();break;case _t.Kind.INFO:this.processInfo(e.data);break}}sendCommand(e,...t){let r=this.outbound.length(),n;if(typeof e==="string")n=(0,ut.encode)(e);else n=e;if(this.outbound.fill(n,...t),r===0)queueMicrotask(()=>{this.flushPending()});else if(this.outbound.size()>=this.pendingLimit)this.flushPending()}publish(e,t=ut.Empty,r){let n;if(t instanceof Uint8Array)n=t;else if(typeof t==="string")n=ut.TE.encode(t);else throw TypeError("payload types can be strings or Uint8Array");let s=n.length;r=r||{},r.reply=r.reply||"";let o=ut.Empty,c=0;if(r.headers){if(this.info&&!this.info.headers)Ce.InvalidArgumentError.format("headers","are not available on this server");o=r.headers.encode(),c=o.length,s=n.length+c}if(this.info&&s>this.info.max_payload)throw Ce.InvalidArgumentError.format("payload","max_payload size exceeded");this.outBytes+=s,this.outMsgs++;let d;if(r.headers){if(r.reply)d=`HPUB ${e} ${r.reply} ${c} ${s}\r
|
|
10
|
-
`;else d=`HPUB ${e} ${c} ${s}\r
|
|
11
|
-
`;this.sendCommand(d,o,n,$t.CRLF)}else{if(r.reply)d=`PUB ${e} ${r.reply} ${s}\r
|
|
12
|
-
`;else d=`PUB ${e} ${s}\r
|
|
13
|
-
`;this.sendCommand(d,n,$t.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
|
|
14
|
-
`);else this.sendCommand(`SUB ${e.subject} ${e.sid}\r
|
|
15
|
-
`)}_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
|
|
16
|
-
`);else this.sendCommand(`UNSUB ${e.sid}\r
|
|
17
|
-
`);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(Tc),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}${$t.CR_LF}`);else e.push(`SUB ${r.subject} ${r.sid}${$t.CR_LF}`)}),e.length)this.transport.send((0,ut.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 n=this.listeners[r];if(n)n.push({type:"close"}),n.stop(),t.push(n.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 hi(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}}jc.ProtocolHandler=vn});var li=z(function(kc){Object.defineProperty(kc,"__esModule",{value:!0});kc.RequestOne=kc.RequestMany=kc.BaseRequest=void 0;var En=tt(),_n=Ve();class Sn{token;received;ctx;requestSubject;mux;constructor(e,t,r=!0){if(this.mux=e,this.requestSubject=t,this.received=0,this.token=(0,En.randomToken)(),r)this.ctx=new _n.RequestError}}kc.BaseRequest=Sn;class Cc extends Sn{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,En.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+=`
|
|
18
|
-
|
|
19
|
-
${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()}}}}kc.RequestMany=Cc;class Mc extends Sn{deferred;timer;constructor(e,t,r={timeout:1000},n=!0){super(e,t,n);this.deferred=(0,En.deferred)(),this.timer=(0,En.timeout)(r.timeout,n)}resolver(e,t){if(this.timer)this.timer.cancel();if(e){if(!(e instanceof _n.TimeoutError))if(this.ctx)this.ctx.message=e.message,this.ctx.cause=e,e=this.ctx;else e=new _n.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 _n.RequestError("cancelled"))}}kc.RequestOne=Mc});var bi=z(function(Bc){Object.defineProperty(Bc,"__esModule",{value:!0});Bc.NatsConnectionImpl=void 0;var Gp=tt(),qc=Or(),Vp=Ge(),$c=un(),Jp=dn(),Wp=Ar(),Uc=sn(),Lc=li(),Dc=wt(),Ie=Ve(),Yp=/[ \n\r\t]/;class pi{options;protocol;draining;closeListeners;constructor(e){this.draining=!1,this.options=(0,Wp.parseOptions)(e)}static connect(e={}){return new Promise((t,r)=>{let n=new pi(e);qc.ProtocolHandler.connect(n.options,n).then((s)=>{n.protocol=s,t(n)}).catch((s)=>{r(s)})})}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||Yp.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 n=r.headers||(0,$c.headers)();n.set("Nats-Trace-Only","true"),r.headers=n}if(typeof r?.traceDestination==="string"){let n=r.headers||(0,$c.headers)();n.set("Nats-Trace-Dest",r.traceDestination),r.headers=n}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 qc.SubscriptionImpl(this.protocol,e,t);if(typeof t.callback!=="function"&&typeof t.slow==="number")r.setSlowNotificationFn(t.slow,(n)=>{this.protocol.dispatchStatus({type:"slowConsumer",sub:r,pending:n})});return this.protocol.subscribe(r),r}_resub(e,t,r){this._check(t,!0,!1);let n=e;if(n.max=r,r)n.max=r+n.received;this.protocol.resub(n,t)}requestMany(e,t=Vp.Empty,r={maxWait:1000,maxMessages:-1}){let n=!this.protocol.options.noAsyncTraces;try{this._check(e,!0,!0)}catch(d){return Promise.reject(d)}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 s=new Uc.QueuedIteratorImpl;function o(d){s.push(()=>{s.stop(d)})}function c(d,p){if(d||p===null)o(d===null?void 0:d);else s.push(p)}if(r.noMux){let d=n?Error().stack:null,p=typeof r.maxMessages==="number"&&r.maxMessages>0?r.maxMessages:-1,w=this.subscribe((0,Dc.createInbox)(this.options.inboxPrefix),{callback:(ye,gt)=>{if(gt?.data?.length===0&>?.headers?.status==="503")ye=new Ie.errors.NoRespondersError(e);if(ye){if(d)ye.stack+=`
|
|
20
|
-
|
|
21
|
-
${d}`;A(ye);return}if(c(null,gt),r.strategy==="count"){if(p--,p===0)A()}if(r.strategy==="stall")Oe(),N=setTimeout(()=>{A()},300);if(r.strategy==="sentinel"){if(gt&>.data.length===0)A()}}});w.requestSubject=e,w.closed.then(()=>{o()}).catch((ye)=>{s.stop(ye)});let A=(ye)=>{if(ye)s.push(()=>{throw ye});Oe(),w.drain().then(()=>{o()}).catch((gt)=>{o()})};s.iterClosed.then(()=>{Oe(),w?.unsubscribe()}).catch((ye)=>{Oe(),w?.unsubscribe()});let{headers:I,traceDestination:O,traceOnly:K}=r;try{this.publish(e,t,{reply:w.getSubject(),headers:I,traceDestination:O,traceOnly:K})}catch(ye){A(ye)}let N=setTimeout(()=>{A()},r.maxWait),Oe=()=>{if(N)clearTimeout(N)}}else{let d=r;d.callback=c,s.iterClosed.then(()=>{p.cancel()}).catch((O)=>{p.cancel(O)});let p=new Lc.RequestMany(this.protocol.muxSubscriptions,e,d);this.protocol.request(p);let{headers:w,traceDestination:A,traceOnly:I}=r;try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${p.token}`,headers:w,traceDestination:A,traceOnly:I})}catch(O){p.cancel(O)}}return Promise.resolve(s)}request(e,t,r={timeout:1000,noMux:!1}){try{this._check(e,!0,!0)}catch(s){return Promise.reject(s)}let n=!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 s=r.reply?r.reply:(0,Dc.createInbox)(this.options.inboxPrefix),o=(0,Gp.deferred)(),c=n?new Ie.errors.RequestError(""):null,d=this.subscribe(s,{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),d.unsubscribe()}else o.resolve(w)}});return d.requestSubject=e,this.protocol.publish(e,t,{reply:s,headers:r.headers}),o}else{let s=new Lc.RequestOne(this.protocol.muxSubscriptions,e,r,n);this.protocol.request(s);let{headers:o,traceDestination:c,traceOnly:d}=r;try{this.publish(e,t,{reply:`${this.protocol.muxSubscriptions.baseInbox}${s.token}`,headers:o,traceDestination:c,traceOnly:d})}catch(w){s.cancel(w)}let p=Promise.race([s.timer,s.deferred]);return p.catch(()=>{s.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 Uc.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,Jp.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 Fc(this.closed());this.closeListeners.add(e)}removeCloseListener(e){if(this.closeListeners)this.closeListeners.remove(e)}}Bc.NatsConnectionImpl=pi;class Fc{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 mi=z(function(yi){Object.defineProperty(yi,"__esModule",{value:!0});yi.Empty=void 0;var Xp=Ge();Object.defineProperty(yi,"Empty",{enumerable:!0,get:function(){return Xp.Empty}})});var Wc=z(function(Vc){Object.defineProperty(Vc,"__esModule",{value:!0});Vc.Bench=Vc.Metric=void 0;Vc.throughput=zc;Vc.msgThroughput=t0;Vc.humanizeBytes=Gc;var Qp=mi(),e0=tn(),gi=tt();class Et{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":"",n="";if(this.max)n=`${this.min}/${this.max}`;return`${this.name}${r?" [asyncRequests]":""} ${r0(t)} msgs/sec - [${e.toFixed(2)} secs] ~ ${zc(this.bytes,e)} ${n}`}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}
|
|
22
|
-
`}static header(){return`Test,Date,Lang,Version,Count,MsgPayload,Bytes,Millis,Async
|
|
23
|
-
`}}Vc.Metric=Et;class Hc{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||e0.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 gi.Perf,this.payload=this.size?new Uint8Array(this.size):Qp.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 n=this.perf.getEntries(),s=n.find((O)=>O.name==="pubsub"),o=n.find((O)=>O.name==="reqrep"),c=n.find((O)=>O.name==="req"),d=n.find((O)=>O.name==="rep"),p=n.find((O)=>O.name==="pub"),w=n.find((O)=>O.name==="sub"),A=this.nc.stats(),I=[];if(s){let{name:O,duration:K}=s,N=new Et(O,K);N.msgs=this.msgs*2,N.bytes=A.inBytes+A.outBytes,N.lang=t,N.version=r,N.payload=this.payload.length,I.push(N)}if(o){let{name:O,duration:K}=o,N=new Et(O,K);N.msgs=this.msgs*2,N.bytes=A.inBytes+A.outBytes,N.lang=t,N.version=r,N.payload=this.payload.length,I.push(N)}if(p){let{name:O,duration:K}=p,N=new Et(O,K);N.msgs=this.msgs,N.bytes=A.outBytes,N.lang=t,N.version=r,N.payload=this.payload.length,I.push(N)}if(w){let{name:O,duration:K}=w,N=new Et(O,K);N.msgs=this.msgs,N.bytes=A.inBytes,N.lang=t,N.version=r,N.payload=this.payload.length,I.push(N)}if(d){let{name:O,duration:K}=d,N=new Et(O,K);N.msgs=this.msgs,N.bytes=A.inBytes+A.outBytes,N.lang=t,N.version=r,N.payload=this.payload.length,I.push(N)}if(c){let{name:O,duration:K}=c,N=new Et(O,K);N.msgs=this.msgs,N.bytes=A.inBytes+A.outBytes,N.lang=t,N.version=r,N.payload=this.payload.length,I.push(N)}return I}async runCallbacks(){let e=[];if(this.sub){let t=(0,gi.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,gi.deferred)();e.push(t);let r=0;this.nc.subscribe(this.subject,{max:this.msgs,callback:(n,s)=>{if(s.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 n=0;n<this.msgs;n++)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}),n=(async()=>{for await(let s of r){if(!t)this.perf.mark("repStart"),t=!0;s.respond(this.payload)}await this.nc.flush(),this.perf.mark("repStop"),this.perf.measure("rep","repStart","repStop")})();e.push(n)}if(this.sub){let t=!1,r=this.nc.subscribe(this.subject,{max:this.msgs}),n=(async()=>{for await(let s of r)if(!t)this.perf.mark("subStart"),t=!0;this.perf.mark("subStop"),this.perf.measure("sub","subStart","subStop")})();e.push(n)}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 n=0;n<this.msgs;n++)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)}}Vc.Bench=Hc;function zc(e,t){return`${Gc(e/t)}/sec`}function t0(e,t){return`${Math.floor(e/t)} msgs/sec`}function Gc(e,t=!1){let r=t?1000:1024,n=t?["k","M","G","T","P","E"]:["K","M","G","T","P","E"],s=t?"iB":"B";if(e<r)return`${e.toFixed(2)} ${s}`;let o=parseInt(Math.log(e)/Math.log(r)+""),c=parseInt(o-1+"");return`${(e/Math.pow(r,o)).toFixed(2)} ${n[c]}${s}`}function r0(e){return e.toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}});var Qc=z(function(Xc){Object.defineProperty(Xc,"__esModule",{value:!0});Xc.IdleHeartbeatMonitor=void 0;class Yc{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)}}Xc.IdleHeartbeatMonitor=Yc});var ru=z(function(eu){Object.defineProperty(eu,"__esModule",{value:!0});eu.version=void 0;eu.version="3.4.0"});var cu=z(function(ou){Object.defineProperty(ou,"__esModule",{value:!0});ou.WsTransport=void 0;ou.wsUrlParseFn=iu;ou.wsconnect=p0;var bt=tt(),nu=Ct(),a0=Ar(),c0=mr(),u0=Or(),f0=bi(),h0=ru(),su=Ve(),d0=h0.version,l0="nats.ws";class xi{version;lang;closeError;connected;done;socket;options;socketClosed;encrypted;peeked;yields;signal;closedNotification;constructor(){this.version=d0,this.lang=l0,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=(0,bt.deferred)(),this.closedNotification=(0,bt.deferred)()}async connect(e,t){let n=(0,bt.deferred)();this.options=t;let s=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=s.indexOf("wss://")===0,this.socket=new WebSocket(s);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=c0.DataBuffer.concat(...this.yields),d=(0,nu.extractProtocolMessage)(c);if(d!==""){let p=u0.INFO.exec(d);if(!p){if(t.debug)console.error("!!!",(0,bt.render)(c));n.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(),n.resolve()}catch(w){n.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,d=new su.errors.ConnectionError(c.message);n.reject(d),this._cleanup()},n}_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,bt.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,bt.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,bt.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,bt.render)(e)}`);return}catch(t){if(this.options.debug)console.error(`!!! ${(0,bt.render)(e)}: ${t}`)}}close(e){return this._closed(e,!1)}closed(){return this.closedNotification}discard(){this.socket?.close()}}ou.WsTransport=xi;function iu(e,t){if(!/^(.*:\/\/)(.*)/.test(e))if(typeof t==="boolean")e=`${t===!0?"https":"http"}://${e}`;else e=`https://${e}`;let n=new URL(e),s=n.protocol.toLowerCase();if(s==="ws:")t=!1;if(s==="wss:")t=!0;if(s!=="https:"&&s!=="http")e=e.replace(/^(.*:\/\/)(.*)/gm,"$2"),n=new URL(`http://${e}`);let o,c,d=n.hostname,p=n.pathname,w=n.search||"";switch(s){case"http:":case"ws:":case"nats:":c=n.port||"80",o="ws:";break;case"https:":case"wss:":case"tls:":c=n.port||"443",o="wss:";break;default:c=n.port||t===!0?"443":"80",o=t===!0?"wss:":"ws:";break}return`${o}//${d}:${c}${p}${w}`}function p0(e={}){return(0,nu.setTransportFactory)({defaultPort:443,urlParseFn:iu,factory:()=>{if(e.tls)throw su.InvalidArgumentError.format("tls","is not configurable on w3c websocket connections");return new xi}}),f0.NatsConnectionImpl.connect(e)}});var Tn=z(function(b){var m0=b&&b.__createBinding||(Object.create?function(e,t,r,n){if(n===void 0)n=r;var s=Object.getOwnPropertyDescriptor(t,r);if(!s||("get"in s?!t.__esModule:s.writable||s.configurable))s={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,n,s)}:function(e,t,r,n){if(n===void 0)n=r;e[n]=t[r]}),g0=b&&b.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r))m0(t,e,r)};Object.defineProperty(b,"__esModule",{value:!0});b.Metric=b.Bench=b.writeAll=b.readAll=b.MAX_SIZE=b.DenoBuffer=b.State=b.Parser=b.Kind=b.describe=b.QueuedIteratorImpl=b.usernamePasswordAuthenticator=b.tokenAuthenticator=b.nkeyAuthenticator=b.jwtAuthenticator=b.credsAuthenticator=b.RequestOne=b.parseOptions=b.hasWsProtocol=b.defaultOptions=b.DEFAULT_MAX_RECONNECT_ATTEMPTS=b.checkUnsupportedOption=b.checkOptions=b.buildAuthenticator=b.DataBuffer=b.MuxSubscription=b.Heartbeat=b.MsgHdrsImpl=b.headers=b.canonicalMIMEHeaderKey=b.timeout=b.SimpleMutex=b.render=b.nanos=b.millis=b.extend=b.delay=b.deferred=b.deadline=b.collect=b.backoff=b.ProtocolHandler=b.INFO=b.Connect=b.setTransportFactory=b.getResolveFn=b.MsgImpl=b.nuid=b.Nuid=b.NatsConnectionImpl=void 0;b.UserAuthenticationExpiredError=b.TimeoutError=b.RequestError=b.ProtocolError=b.PermissionViolationError=b.NoRespondersError=b.InvalidSubjectError=b.InvalidOperationError=b.InvalidArgumentError=b.errors=b.DrainingConnectionError=b.ConnectionError=b.ClosedConnectionError=b.AuthorizationError=b.wsUrlParseFn=b.wsconnect=b.Servers=b.isIPV4OrHostname=b.IdleHeartbeatMonitor=b.Subscriptions=b.SubscriptionImpl=b.syncIterator=b.Match=b.createInbox=b.protoLen=b.extractProtocolMessage=b.Empty=b.parseSemVer=b.Features=b.Feature=b.compare=b.parseIP=b.isIP=b.ipV4=b.TE=b.TD=void 0;var x0=bi();Object.defineProperty(b,"NatsConnectionImpl",{enumerable:!0,get:function(){return x0.NatsConnectionImpl}});var uu=tn();Object.defineProperty(b,"Nuid",{enumerable:!0,get:function(){return uu.Nuid}});Object.defineProperty(b,"nuid",{enumerable:!0,get:function(){return uu.nuid}});var w0=Ws();Object.defineProperty(b,"MsgImpl",{enumerable:!0,get:function(){return w0.MsgImpl}});var fu=Ct();Object.defineProperty(b,"getResolveFn",{enumerable:!0,get:function(){return fu.getResolveFn}});Object.defineProperty(b,"setTransportFactory",{enumerable:!0,get:function(){return fu.setTransportFactory}});var wi=Or();Object.defineProperty(b,"Connect",{enumerable:!0,get:function(){return wi.Connect}});Object.defineProperty(b,"INFO",{enumerable:!0,get:function(){return wi.INFO}});Object.defineProperty(b,"ProtocolHandler",{enumerable:!0,get:function(){return wi.ProtocolHandler}});var st=tt();Object.defineProperty(b,"backoff",{enumerable:!0,get:function(){return st.backoff}});Object.defineProperty(b,"collect",{enumerable:!0,get:function(){return st.collect}});Object.defineProperty(b,"deadline",{enumerable:!0,get:function(){return st.deadline}});Object.defineProperty(b,"deferred",{enumerable:!0,get:function(){return st.deferred}});Object.defineProperty(b,"delay",{enumerable:!0,get:function(){return st.delay}});Object.defineProperty(b,"extend",{enumerable:!0,get:function(){return st.extend}});Object.defineProperty(b,"millis",{enumerable:!0,get:function(){return st.millis}});Object.defineProperty(b,"nanos",{enumerable:!0,get:function(){return st.nanos}});Object.defineProperty(b,"render",{enumerable:!0,get:function(){return st.render}});Object.defineProperty(b,"SimpleMutex",{enumerable:!0,get:function(){return st.SimpleMutex}});Object.defineProperty(b,"timeout",{enumerable:!0,get:function(){return st.timeout}});var vi=un();Object.defineProperty(b,"canonicalMIMEHeaderKey",{enumerable:!0,get:function(){return vi.canonicalMIMEHeaderKey}});Object.defineProperty(b,"headers",{enumerable:!0,get:function(){return vi.headers}});Object.defineProperty(b,"MsgHdrsImpl",{enumerable:!0,get:function(){return vi.MsgHdrsImpl}});var v0=Ds();Object.defineProperty(b,"Heartbeat",{enumerable:!0,get:function(){return v0.Heartbeat}});var _0=Ls();Object.defineProperty(b,"MuxSubscription",{enumerable:!0,get:function(){return _0.MuxSubscription}});var E0=mr();Object.defineProperty(b,"DataBuffer",{enumerable:!0,get:function(){return E0.DataBuffer}});var Ut=Ar();Object.defineProperty(b,"buildAuthenticator",{enumerable:!0,get:function(){return Ut.buildAuthenticator}});Object.defineProperty(b,"checkOptions",{enumerable:!0,get:function(){return Ut.checkOptions}});Object.defineProperty(b,"checkUnsupportedOption",{enumerable:!0,get:function(){return Ut.checkUnsupportedOption}});Object.defineProperty(b,"DEFAULT_MAX_RECONNECT_ATTEMPTS",{enumerable:!0,get:function(){return Ut.DEFAULT_MAX_RECONNECT_ATTEMPTS}});Object.defineProperty(b,"defaultOptions",{enumerable:!0,get:function(){return Ut.defaultOptions}});Object.defineProperty(b,"hasWsProtocol",{enumerable:!0,get:function(){return Ut.hasWsProtocol}});Object.defineProperty(b,"parseOptions",{enumerable:!0,get:function(){return Ut.parseOptions}});var S0=li();Object.defineProperty(b,"RequestOne",{enumerable:!0,get:function(){return S0.RequestOne}});var Pr=ii();Object.defineProperty(b,"credsAuthenticator",{enumerable:!0,get:function(){return Pr.credsAuthenticator}});Object.defineProperty(b,"jwtAuthenticator",{enumerable:!0,get:function(){return Pr.jwtAuthenticator}});Object.defineProperty(b,"nkeyAuthenticator",{enumerable:!0,get:function(){return Pr.nkeyAuthenticator}});Object.defineProperty(b,"tokenAuthenticator",{enumerable:!0,get:function(){return Pr.tokenAuthenticator}});Object.defineProperty(b,"usernamePasswordAuthenticator",{enumerable:!0,get:function(){return Pr.usernamePasswordAuthenticator}});g0(ni(),b);var A0=sn();Object.defineProperty(b,"QueuedIteratorImpl",{enumerable:!0,get:function(){return A0.QueuedIteratorImpl}});var An=Gs();Object.defineProperty(b,"describe",{enumerable:!0,get:function(){return An.describe}});Object.defineProperty(b,"Kind",{enumerable:!0,get:function(){return An.Kind}});Object.defineProperty(b,"Parser",{enumerable:!0,get:function(){return An.Parser}});Object.defineProperty(b,"State",{enumerable:!0,get:function(){return An.State}});var On=Ks();Object.defineProperty(b,"DenoBuffer",{enumerable:!0,get:function(){return On.DenoBuffer}});Object.defineProperty(b,"MAX_SIZE",{enumerable:!0,get:function(){return On.MAX_SIZE}});Object.defineProperty(b,"readAll",{enumerable:!0,get:function(){return On.readAll}});Object.defineProperty(b,"writeAll",{enumerable:!0,get:function(){return On.writeAll}});var hu=Wc();Object.defineProperty(b,"Bench",{enumerable:!0,get:function(){return hu.Bench}});Object.defineProperty(b,"Metric",{enumerable:!0,get:function(){return hu.Metric}});var du=Ge();Object.defineProperty(b,"TD",{enumerable:!0,get:function(){return du.TD}});Object.defineProperty(b,"TE",{enumerable:!0,get:function(){return du.TE}});var _i=Ns();Object.defineProperty(b,"ipV4",{enumerable:!0,get:function(){return _i.ipV4}});Object.defineProperty(b,"isIP",{enumerable:!0,get:function(){return _i.isIP}});Object.defineProperty(b,"parseIP",{enumerable:!0,get:function(){return _i.parseIP}});var Pn=dn();Object.defineProperty(b,"compare",{enumerable:!0,get:function(){return Pn.compare}});Object.defineProperty(b,"Feature",{enumerable:!0,get:function(){return Pn.Feature}});Object.defineProperty(b,"Features",{enumerable:!0,get:function(){return Pn.Features}});Object.defineProperty(b,"parseSemVer",{enumerable:!0,get:function(){return Pn.parseSemVer}});var O0=mi();Object.defineProperty(b,"Empty",{enumerable:!0,get:function(){return O0.Empty}});var lu=Ct();Object.defineProperty(b,"extractProtocolMessage",{enumerable:!0,get:function(){return lu.extractProtocolMessage}});Object.defineProperty(b,"protoLen",{enumerable:!0,get:function(){return lu.protoLen}});var Ei=wt();Object.defineProperty(b,"createInbox",{enumerable:!0,get:function(){return Ei.createInbox}});Object.defineProperty(b,"Match",{enumerable:!0,get:function(){return Ei.Match}});Object.defineProperty(b,"syncIterator",{enumerable:!0,get:function(){return Ei.syncIterator}});var pu=Or();Object.defineProperty(b,"SubscriptionImpl",{enumerable:!0,get:function(){return pu.SubscriptionImpl}});Object.defineProperty(b,"Subscriptions",{enumerable:!0,get:function(){return pu.Subscriptions}});var P0=Qc();Object.defineProperty(b,"IdleHeartbeatMonitor",{enumerable:!0,get:function(){return P0.IdleHeartbeatMonitor}});var bu=$s();Object.defineProperty(b,"isIPV4OrHostname",{enumerable:!0,get:function(){return bu.isIPV4OrHostname}});Object.defineProperty(b,"Servers",{enumerable:!0,get:function(){return bu.Servers}});var yu=cu();Object.defineProperty(b,"wsconnect",{enumerable:!0,get:function(){return yu.wsconnect}});Object.defineProperty(b,"wsUrlParseFn",{enumerable:!0,get:function(){return yu.wsUrlParseFn}});var Be=Ve();Object.defineProperty(b,"AuthorizationError",{enumerable:!0,get:function(){return Be.AuthorizationError}});Object.defineProperty(b,"ClosedConnectionError",{enumerable:!0,get:function(){return Be.ClosedConnectionError}});Object.defineProperty(b,"ConnectionError",{enumerable:!0,get:function(){return Be.ConnectionError}});Object.defineProperty(b,"DrainingConnectionError",{enumerable:!0,get:function(){return Be.DrainingConnectionError}});Object.defineProperty(b,"errors",{enumerable:!0,get:function(){return Be.errors}});Object.defineProperty(b,"InvalidArgumentError",{enumerable:!0,get:function(){return Be.InvalidArgumentError}});Object.defineProperty(b,"InvalidOperationError",{enumerable:!0,get:function(){return Be.InvalidOperationError}});Object.defineProperty(b,"InvalidSubjectError",{enumerable:!0,get:function(){return Be.InvalidSubjectError}});Object.defineProperty(b,"NoRespondersError",{enumerable:!0,get:function(){return Be.NoRespondersError}});Object.defineProperty(b,"PermissionViolationError",{enumerable:!0,get:function(){return Be.PermissionViolationError}});Object.defineProperty(b,"ProtocolError",{enumerable:!0,get:function(){return Be.ProtocolError}});Object.defineProperty(b,"RequestError",{enumerable:!0,get:function(){return Be.RequestError}});Object.defineProperty(b,"TimeoutError",{enumerable:!0,get:function(){return Be.TimeoutError}});Object.defineProperty(b,"UserAuthenticationExpiredError",{enumerable:!0,get:function(){return Be.UserAuthenticationExpiredError}})});var jn=z(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 In extends Error{code;constructor(e,t){super(t);this.code=e}static isServiceError(e){return In.toServiceError(e)!==null}static toServiceError(e){let t=e?.headers?.get(mu.ServiceErrorCodeHeader)||"";if(t!==""){let r=parseInt(t)||400,n=e?.headers?.get(mu.ServiceErrorHeader)||"";return new In(r,n.length?n:t)}return null}}mu.ServiceError=In;mu.ServiceVerb={PING:"PING",STATS:"STATS",INFO:"INFO"}});var Si=z(function(_u){Object.defineProperty(_u,"__esModule",{value:!0});_u.ServiceImpl=_u.ServiceGroupImpl=_u.ServiceMsgImpl=_u.ServiceApiPrefix=void 0;var yt=Tn(),We=jn();function Tr(e,t=""){if(t==="")throw Error(`${e} name required`);let r=j0(t);if(r.length)throw Error(`invalid ${e} name - ${e} name ${r}`)}function j0(e=""){if(!e)throw Error("name required");let t=/^[-\w]+$/g;if(e.match(t)===null){for(let n of e.split(""))if(n.match(t)===null)return`cannot contain '${n}'`}return""}_u.ServiceApiPrefix="$SRV";class Nn{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,n){return n=n||{},n.headers=n.headers||(0,yt.headers)(),n.headers?.set(We.ServiceErrorCodeHeader,`${e}`),n.headers?.set(We.ServiceErrorHeader,t),this.msg.respond(r,n)}json(e){return this.msg.json(e)}string(){return this.msg.string()}}_u.ServiceMsgImpl=Nn;class er{subject;queue;srv;constructor(e,t="",r=""){if(t!=="")C0("service group",t);let n="";if(e instanceof Cn)this.srv=e,n="";else if(e instanceof er){let s=e;if(this.srv=s.srv,r===void 0)r=s.queue;n=s.subject}else throw Error("unknown ServiceGroup type");this.subject=this.calcSubject(n,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;Tr("endpoint",e);let{subject:n,handler:s,metadata:o,queue:c}=r;n=n||e,c=c||this.queue,N0("endpoint subject",n),n=this.calcSubject(this.subject,n);let d={name:e,subject:n,queue:c,handler:s,metadata:o};return this.srv._addEndpoint(d)}addGroup(e="",t){if(t===void 0)t=this.queue;return new er(this,e,t)}}_u.ServiceGroupImpl=er;function N0(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((n,s)=>{if(n===">"&&s!==r.length-1)throw Error(`${e} cannot have internal '>': '${t}'`)})}function C0(e,t){if(t.indexOf(" ")!==-1)throw Error(`${e} cannot contain spaces: '${t}'`);t.split(".").forEach((n)=>{if(n===">")throw Error(`${e} name cannot contain internal '>': '${t}'`)})}class Cn{nc;_id;config;handlers;internal;_stopped;_done;started;closeListener;static controlSubject(e,t="",r="",n){let s=n??_u.ServiceApiPrefix;if(t===""&&r==="")return`${s}.${e}`;if(Tr("control subject name",t),r!=="")return Tr("control subject id",r),`${s}.${e}.${t}.${r}`;return`${s}.${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||{}),Tr("name",this.config.name),this.config.queue)Tr("queue",this.config.queue);(0,yt.parseSemVer)(this.config.version),this._id=yt.nuid.next(),this.internal=[],this._done=(0,yt.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,yt.headers)();if(e instanceof We.ServiceError){let r=e;t.set(We.ServiceErrorHeader,r.message),t.set(We.ServiceErrorCodeHeader,`${r.code}`)}else t.set(We.ServiceErrorHeader,e.message),t.set(We.ServiceErrorCodeHeader,"500");return t}setupHandler(e,t=!1){let r=t?"":e.queue?e.queue:this.config.queue,{name:n,subject:s,handler:o}=e,c=e;if(c.internal=t,t)this.internal.push(c);c.stats=new vu(n,s,r),c.queue=r;let d=o?(p,w)=>{if(p){this.close(p);return}let A=Date.now();try{o(p,new Nn(w))}catch(I){c.stats.countError(I),w?.respond(yt.Empty,{headers:this.errorToHeader(I)})}finally{c.stats.countLatency(A)}}:void 0;return c.sub=this.nc.subscribe(s,{callback:d,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:We.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:n,queue:s}=e;return{subject:t,metadata:r,name:n,queue_group:s}})}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:We.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,n="",s=""){let o={};o.name=e,o.subject=Cn.controlSubject(t,n,s),o.handler=r,this.setupHandler(o,!0)}start(){let e=(s,o)=>{if(s)return this.close(s),Promise.reject(s);return this.stats().then((c)=>(o?.respond(JSON.stringify(c)),Promise.resolve()))},t=(s,o)=>{if(s)return this.close(s),Promise.reject(s);return o?.respond(JSON.stringify(this.info())),Promise.resolve()},r=JSON.stringify(this.ping()),n=(s,o)=>{if(s)return this.close(s).then().catch(),Promise.reject(s);return o.respond(r),Promise.resolve()};return this.addInternalHandler(We.ServiceVerb.PING,n),this.addInternalHandler(We.ServiceVerb.STATS,e),this.addInternalHandler(We.ServiceVerb.INFO,t),this.handlers.forEach((s)=>{let{subject:o}=s;if(typeof o!=="string")return;if(s.handler===null)return;this.setupHandler(s)}),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:We.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 er(this,e,t)}addEndpoint(e,t){return new er(this).addEndpoint(e,t)}_addEndpoint(e){let t=new yt.QueuedIteratorImpl;if(t.profile=!0,t.noIterator=typeof e.handler==="function",!t.noIterator)e.handler=(n,s)=>{n?this.stop(n).catch():t.push(new Nn(s))},t.iterClosed.then(()=>{this.close().catch()});let r=this.setupHandler(e,!1);return r.sub.closed.then((n)=>{n?this.stop(n):t.stop()}),r.qi=t,this.handlers.push(r),t}}_u.ServiceImpl=Cn;class vu{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,yt.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:n,num_requests:s,processing_time:o,last_error:c,data:d,queue:p}=this;return{name:e,subject:t,average_processing_time:r,num_errors:n,num_requests:s,processing_time:o,last_error:c,data:d,queue_group:p}}stats(e){let t=e;if(t?.noIterator===!1)this.processing_time=(0,yt.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 Iu=z(function(Pu){Object.defineProperty(Pu,"__esModule",{value:!0});Pu.ServiceClientImpl=void 0;var Au=Tn(),R0=Si(),Ai=jn();class Ou{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(Ai.ServiceVerb.PING,e,t)}stats(e="",t=""){return this.q(Ai.ServiceVerb.STATS,e,t)}info(e="",t=""){return this.q(Ai.ServiceVerb.INFO,e,t)}async q(e,t="",r=""){let n=new Au.QueuedIteratorImpl,s=R0.ServiceImpl.controlSubject(e,t,r,this.prefix),o=await this.nc.requestMany(s,Au.Empty,this.opts);return(async()=>{for await(let c of o)try{let d=c.json();n.push(d)}catch(d){n.push(()=>{n.stop(d)})}n.push(()=>{n.stop()})})().catch((c)=>{n.stop(c)}),n}}Pu.ServiceClientImpl=Ou});var Cu=z(function(Lt){Object.defineProperty(Lt,"__esModule",{value:!0});Lt.Svcm=Lt.ServiceVerb=Lt.ServiceResponseType=Lt.ServiceErrorHeader=Lt.ServiceErrorCodeHeader=Lt.ServiceError=void 0;var q0=Si(),$0=Iu(),Ir=jn();Object.defineProperty(Lt,"ServiceError",{enumerable:!0,get:function(){return Ir.ServiceError}});Object.defineProperty(Lt,"ServiceErrorCodeHeader",{enumerable:!0,get:function(){return Ir.ServiceErrorCodeHeader}});Object.defineProperty(Lt,"ServiceErrorHeader",{enumerable:!0,get:function(){return Ir.ServiceErrorHeader}});Object.defineProperty(Lt,"ServiceResponseType",{enumerable:!0,get:function(){return Ir.ServiceResponseType}});Object.defineProperty(Lt,"ServiceVerb",{enumerable:!0,get:function(){return Ir.ServiceVerb}});class ju{nc;constructor(e){this.nc=e}add(e){try{return new q0.ServiceImpl(this.nc,e).start()}catch(t){return Promise.reject(t)}}client(e,t){return new $0.ServiceClientImpl(this.nc,e,t)}}Lt.Svcm=ju});var Oi=z(function(St){Object.defineProperty(St,"__esModule",{value:!0});St.Svcm=St.ServiceVerb=St.ServiceResponseType=St.ServiceErrorHeader=St.ServiceErrorCodeHeader=St.ServiceError=void 0;var tr=Cu();Object.defineProperty(St,"ServiceError",{enumerable:!0,get:function(){return tr.ServiceError}});Object.defineProperty(St,"ServiceErrorCodeHeader",{enumerable:!0,get:function(){return tr.ServiceErrorCodeHeader}});Object.defineProperty(St,"ServiceErrorHeader",{enumerable:!0,get:function(){return tr.ServiceErrorHeader}});Object.defineProperty(St,"ServiceResponseType",{enumerable:!0,get:function(){return tr.ServiceResponseType}});Object.defineProperty(St,"ServiceVerb",{enumerable:!0,get:function(){return tr.ServiceVerb}});Object.defineProperty(St,"Svcm",{enumerable:!0,get:function(){return tr.Svcm}})});var Pi=z(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 se=Tn();Object.defineProperty(te,"AuthorizationError",{enumerable:!0,get:function(){return se.AuthorizationError}});Object.defineProperty(te,"backoff",{enumerable:!0,get:function(){return se.backoff}});Object.defineProperty(te,"Bench",{enumerable:!0,get:function(){return se.Bench}});Object.defineProperty(te,"buildAuthenticator",{enumerable:!0,get:function(){return se.buildAuthenticator}});Object.defineProperty(te,"canonicalMIMEHeaderKey",{enumerable:!0,get:function(){return se.canonicalMIMEHeaderKey}});Object.defineProperty(te,"ClosedConnectionError",{enumerable:!0,get:function(){return se.ClosedConnectionError}});Object.defineProperty(te,"ConnectionError",{enumerable:!0,get:function(){return se.ConnectionError}});Object.defineProperty(te,"createInbox",{enumerable:!0,get:function(){return se.createInbox}});Object.defineProperty(te,"credsAuthenticator",{enumerable:!0,get:function(){return se.credsAuthenticator}});Object.defineProperty(te,"deadline",{enumerable:!0,get:function(){return se.deadline}});Object.defineProperty(te,"deferred",{enumerable:!0,get:function(){return se.deferred}});Object.defineProperty(te,"delay",{enumerable:!0,get:function(){return se.delay}});Object.defineProperty(te,"DrainingConnectionError",{enumerable:!0,get:function(){return se.DrainingConnectionError}});Object.defineProperty(te,"Empty",{enumerable:!0,get:function(){return se.Empty}});Object.defineProperty(te,"errors",{enumerable:!0,get:function(){return se.errors}});Object.defineProperty(te,"hasWsProtocol",{enumerable:!0,get:function(){return se.hasWsProtocol}});Object.defineProperty(te,"headers",{enumerable:!0,get:function(){return se.headers}});Object.defineProperty(te,"InvalidArgumentError",{enumerable:!0,get:function(){return se.InvalidArgumentError}});Object.defineProperty(te,"InvalidOperationError",{enumerable:!0,get:function(){return se.InvalidOperationError}});Object.defineProperty(te,"InvalidSubjectError",{enumerable:!0,get:function(){return se.InvalidSubjectError}});Object.defineProperty(te,"jwtAuthenticator",{enumerable:!0,get:function(){return se.jwtAuthenticator}});Object.defineProperty(te,"Match",{enumerable:!0,get:function(){return se.Match}});Object.defineProperty(te,"Metric",{enumerable:!0,get:function(){return se.Metric}});Object.defineProperty(te,"millis",{enumerable:!0,get:function(){return se.millis}});Object.defineProperty(te,"MsgHdrsImpl",{enumerable:!0,get:function(){return se.MsgHdrsImpl}});Object.defineProperty(te,"nanos",{enumerable:!0,get:function(){return se.nanos}});Object.defineProperty(te,"nkeyAuthenticator",{enumerable:!0,get:function(){return se.nkeyAuthenticator}});Object.defineProperty(te,"nkeys",{enumerable:!0,get:function(){return se.nkeys}});Object.defineProperty(te,"NoRespondersError",{enumerable:!0,get:function(){return se.NoRespondersError}});Object.defineProperty(te,"Nuid",{enumerable:!0,get:function(){return se.Nuid}});Object.defineProperty(te,"nuid",{enumerable:!0,get:function(){return se.nuid}});Object.defineProperty(te,"PermissionViolationError",{enumerable:!0,get:function(){return se.PermissionViolationError}});Object.defineProperty(te,"ProtocolError",{enumerable:!0,get:function(){return se.ProtocolError}});Object.defineProperty(te,"RequestError",{enumerable:!0,get:function(){return se.RequestError}});Object.defineProperty(te,"syncIterator",{enumerable:!0,get:function(){return se.syncIterator}});Object.defineProperty(te,"TimeoutError",{enumerable:!0,get:function(){return se.TimeoutError}});Object.defineProperty(te,"tokenAuthenticator",{enumerable:!0,get:function(){return se.tokenAuthenticator}});Object.defineProperty(te,"UserAuthenticationExpiredError",{enumerable:!0,get:function(){return se.UserAuthenticationExpiredError}});Object.defineProperty(te,"usernamePasswordAuthenticator",{enumerable:!0,get:function(){return se.usernamePasswordAuthenticator}});Object.defineProperty(te,"wsconnect",{enumerable:!0,get:function(){return se.wsconnect}})});var oe=br(Pi(),1),Di=br(Oi(),1),ir=br(ri(),1);import{AsyncResource as Mu,AsyncLocalStorage as D0}from"async_hooks";import{readFile as kr,mkdir as Zu,open as F0,unlink as B0,rm as K0,realpath as ku,stat as H0,mkdtemp as z0}from"fs/promises";import{homedir as Ri,tmpdir as G0}from"os";import{join as mt,basename as V0,resolve as $n,sep as Ru}from"path";import{fileURLToPath as J0}from"url";import{randomBytes as W0}from"crypto";var at=class extends Error{constructor(e,t){super(e,t);this.name="NatsAgentError"}},Fi=class extends at{constructor(e,t){super(e,t);this.name="ValidationError"}},Y0=class extends Fi{constructor(){super("prompt must be non-empty (spec §5.1)");this.name="PromptEmptyError"}},X0=class extends Fi{constructor(){super("this agent's prompt endpoint does not accept attachments (attachments_ok=false, spec §5.4)");this.name="AttachmentsNotSupportedError"}},Z0=class extends Fi{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 §5.4)`:`payload size ${t} bytes exceeds endpoint max_payload of ${e} bytes (spec §5.4)`);this.limit=e,this.actual=t,this.headerBytes=r,this.name="PayloadTooLargeError"}limit;actual;headerBytes},Qu=class extends at{constructor(e,t,r){super(`service error ${e}: ${t}`);this.code=e,this.description=t,this.body=r,this.name="ServiceError"}code;description;body},ef=class extends at{constructor(e){super(`stream stalled: no chunk received within ${e}ms (spec §6.6)`);this.timeoutMs=e,this.name="StreamStalledError"}timeoutMs},tf=class extends at{constructor(e){super(`stream exceeded maxWait of ${e}ms without terminator`);this.maxWaitMs=e,this.name="StreamMaxWaitExceededError"}maxWaitMs},pe=class extends at{constructor(e,t){super(e,t);this.name="ProtocolError"}},je=class extends at{constructor(e,t){super(e,t);this.name="NatsContextError"}},be=class extends at{constructor(e,t){super(e,t);this.name="IdentityError"}},rr=class extends be{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"}},Ze=class extends be{constructor(e,t){super(`identity unavailable: ${e}`,t);this.name="IdentityUnavailableError"}},sr=class extends be{constructor(e,t,r,n,s){super(s!==void 0?`identity mismatch: the configured signer holds ${e} but its credentials JWT names user ${s}`:r!==void 0&&n!==void 0?`identity mismatch: the configured signer represents ${r}.${e} but the live connection is ${n}.${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=n,this.credentialUser=s,this.name="IdentityMismatchError"}signerPublicKey;identityUser;signerAccount;identityAccount;credentialUser},At=class extends be{constructor(e){super(`invalid agent id: ${e}`);this.name="InvalidAgentIdError"}},Re=class extends be{constructor(e){super(`malformed Agent-Sender header: ${e}`);this.name="MalformedSenderHeaderError"}},Fn=class extends be{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"},Bi=class extends be{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},Q0=new Set(["agent","owner","session","instance_id","ts","interval_s"]);function eb(e){if(typeof e!=="object"||e===null||Array.isArray(e))return;let t={};for(let[r,n]of Object.entries(e)){if(typeof n!=="object"||n===null||Array.isArray(n))return;let s=n;if(typeof s.subject!=="string"||s.subject==="")return;let o=s.metadata??{};if(typeof o!=="object"||o===null||Array.isArray(o))return;let c={};for(let[d,p]of Object.entries(o)){if(typeof p!=="string")return;c[d]=p}t[r]=Object.freeze({subject:s.subject,metadata:Object.freeze(c)})}return Object.freeze(t)}function rf(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,n=eb(t.endpoints),s={};for(let[c,d]of Object.entries(t)){if(Q0.has(c))continue;if(c==="protocol_version"&&r!==void 0)continue;if(c==="endpoints"&&n!==void 0)continue;s[c]=d}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(s),...o!==void 0?{session:o}:{},...r!==void 0?{protocolVersion:r}:{},...n!==void 0?{endpoints:n}:{}})}var tb=/^\s*(\d+)\s*(B|KB|MB|GB)\s*$/i,rb=Object.freeze({B:1,KB:1024,MB:1048576,GB:1073741824}),nr=class extends Error{constructor(e,t){super(`invalid size "${e}": ${t}`);this.input=e,this.name="InvalidSizeError"}input};function Ki(e){let t=tb.exec(e);if(!t||t[1]===void 0||t[2]===void 0)throw new nr(e,"expected e.g. '1MB', '512KB', '4GB'");let r=Number(t[1]);if(!Number.isFinite(r)||r<0)throw new nr(e,"non-finite or negative");let n=t[2].toUpperCase(),s=rb[n];if(s===void 0)throw new nr(e,`unknown unit "${n}"`);let o=r*s;if(!Number.isSafeInteger(o))throw new nr(e,"overflows safe integer range");return o}var nb=[["GB",1073741824],["MB",1048576],["KB",1024]];function Hi(e){if(!Number.isFinite(e)||e<0||!Number.isInteger(e))throw new nr(String(e),"byte count must be a non-negative integer");for(let[t,r]of nb)if(e>=r&&e%r===0)return`${e/r}${t}`;return`${e}B`}var sb=new TextEncoder;function Hn(e){return sb.encode(e).length}var ib=/^(A[A-Z2-7]{55}|[A-Za-z0-9_-]+|\$G)\.U[A-Z2-7]{55}$/,nf=/^U[A-Z2-7]{55}$/,ob=/^([A-Za-z0-9_-]+|\$G)$/,ab=56,qi=64;function cb(e){return nf.test(e)}function ub(e){return e.length===ab&&e.startsWith("A")}function sf(e,t){try{ir.fromPublic(t)}catch(r){let n=r instanceof Error?r.message:String(r);throw new At(`${e} key fails the nkeys check (${n})`)}}function of(e){if(e.length===0)throw new At("empty user token");if(!nf.test(e))throw new At("user token is not a user public NKEY (U + 55 base32 chars)");sf("user",e)}function af(e){if(e.length===0)throw new At("empty account token");if(ub(e)){sf("account",e);return}if(!ob.test(e))throw new At("account token is neither an account public NKEY nor a subject-safe name ([A-Za-z0-9_-]+ or $G)")}function or(e,t){return af(e),of(t),`${e}.${t}`}function fb(e){if(e.length===0)throw new At("empty string");if(!ib.test(e))throw new At("expected {account}.{user} with a U… user public NKEY");let t=e.indexOf(".");return or(e.slice(0,t),e.slice(t+1))}function Cr(e){return e.slice(0,e.indexOf("."))}function ft(e){return e.slice(e.indexOf(".")+1)}async function hb(e){let t=bb(),r=e==="current"?await yb(t):e;if(r.includes("/")||r.includes("\\")||r.includes("\x00")||r==="..")throw new je(`invalid context name: "${r}"`);let n=mt(t,"context",`${r}.json`),s;try{s=await kr(n,"utf8")}catch(c){if(c.code==="ENOENT")throw new je(`NATS context "${r}" not found at ${n}`);throw c}let o;try{o=JSON.parse(s)}catch(c){throw new je(`NATS context "${r}" is not valid JSON: ${c.message}`)}if(typeof o!=="object"||o===null||Array.isArray(o))throw new je(`NATS context "${r}" is not a JSON object`);return{name:r,path:n,fields:o}}async function db(e){let{name:t,fields:r}=await hb(e),n=Xe(r.url);if(!n)throw new je(`NATS context "${t}" is missing \`url\``);let s=cf(n),o=s.user!==void 0||s.pass!==void 0?{kind:"user-password"}:s.token!==void 0?{kind:"token"}:{kind:"none"},c=Xe(r.creds),d=Xe(r.nkey),p=Xe(r.user_jwt),w=Xe(r.user_seed);if(c){Mn(s);let O=await Bn("creds",Kt(c)),K=new Uint8Array(O.buffer,O.byteOffset,O.byteLength);s.authenticator=oe.credsAuthenticator(K),o={kind:"creds",bytes:K}}else if(d){Mn(s);let O=await Bn("nkey",Kt(d)),K=new Uint8Array(O.buffer,O.byteOffset,O.byteLength);s.authenticator=oe.nkeyAuthenticator(K),o={kind:"nkey",bytes:K}}else if(p)if(Mn(s),w){let O=new TextEncoder().encode(w);s.authenticator=oe.jwtAuthenticator(p,O),o={kind:"jwt-seed",jwt:p,seed:O}}else s.authenticator=oe.jwtAuthenticator(p),o={kind:"jwt"};else{let O=Xe(r.token),K=Xe(r.user),N=Xe(r.password);if(O||K||N){if(Mn(s),O)s.token=O;if(K)s.user=K;if(N)s.pass=N;o=K||N?{kind:"user-password"}:{kind:"token"}}}try{let O=Xe(r.cert),K=Xe(r.key),N=Xe(r.ca),Oe=r.tls_first;if(O||K||N||Oe===!0){let ye={};if(O)ye.cert=await Ti("cert",Kt(O));if(K)ye.key=await Ti("key",Kt(K));if(N)ye.ca=await Ti("ca",Kt(N));if(Oe===!0)ye.handshakeFirst=!0;s.tls=ye}}catch(O){throw qu(o),O}let A=Xe(r.inbox_prefix);if(A)s.inboxPrefix=A;let I=!1;return{name:t,connectionOptions:s,auth:o,wipe(){if(I)return;I=!0,qu(o)}}}function Mn(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 Kt(e){return e.startsWith("~/")?mt(Ri(),e.slice(2)):e}async function Ti(e,t){try{return await kr(t,"utf8")}catch(r){throw new je(`failed to read TLS ${e} file ${t}`,{cause:r})}}async function Bn(e,t){try{return await kr(t)}catch(r){throw new je(`failed to read ${e} file ${t}`,{cause:r})}}function cf(e){let t=e.split(",").map((o)=>o.trim()).filter((o)=>o.length>0);if(t.length===0)throw new je("empty NATS URL");let r=t.map((o)=>lb(o,e)),n=r[0];for(let o of r.slice(1))if(o.token!==n.token||o.user!==n.user||o.pass!==n.pass)throw new je(`NATS URL has mixed credentials across server entries: ${Un(e)}`);let s={servers:r.map((o)=>o.server)};if(n.token!==void 0)s.token=n.token;if(n.user!==void 0)s.user=n.user;if(n.pass!==void 0)s.pass=n.pass;return s}function lb(e,t){let r=/^[a-z]+:\/\//i.test(e)?e:`nats://${e}`,n;try{n=new URL(r)}catch{throw new je(`invalid NATS URL ${Un(t)}`)}if(!/^(nats|tls|ws|wss):$/.test(n.protocol))throw new je(`unsupported scheme "${n.protocol}" in NATS URL ${Un(t)}`);if(!n.host)throw new je(`NATS URL ${Un(t)} is missing a host`);let s=n.protocol==="ws:"||n.protocol==="wss:"?`${pb(r)?n.pathname:""}${n.search}`:"",o={server:`${n.protocol}//${n.host}${s}`};if((r.match(/^[a-z]+:\/\/([^/@]*)@/i)?.[1]??"").includes(":"))o.user=decodeURIComponent(n.username),o.pass=decodeURIComponent(n.password);else if(n.username!=="")o.token=decodeURIComponent(n.username);return o}function pb(e){let t=e.indexOf("://")+3;return/[/?]/.test(e.slice(t))}function Un(e){return JSON.stringify(e.split(",").map((t)=>{let r=t.trim(),s=r.match(/^[a-z]+:\/\//i)?.[0]?.length??0,o=r.lastIndexOf("@");return o>=s?`${r.slice(0,s)}[redacted]@${r.slice(o+1)}`:r}).join(","))}function Xe(e){return typeof e==="string"&&e.length>0?e:void 0}function bb(){let e=process.env.NATS_CONFIG_HOME;if(e)return e.startsWith("~/")?mt(Ri(),e.slice(2)):e;let t=process.env.XDG_CONFIG_HOME;if(t)return mt(t,"nats");return mt(Ri(),".config","nats")}async function yb(e){let t=process.env.NATS_CONTEXT;if(t&&t.length>0)return t;let r=mt(e,"context.txt");try{let n=(await kr(r,"utf8")).trim();if(n.length===0)throw new je(`no NATS context is selected (empty ${r})`);return n}catch(n){if(n.code==="ENOENT")throw new je(`no NATS context is selected ($NATS_CONTEXT unset, no ${r})`);throw n}}var it="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",mb=/^[A-Za-z0-9_-]*$/,gb=(()=>{let e=new Int8Array(128).fill(-1);for(let t=0;t<it.length;t++)e[it.charCodeAt(t)]=t;return e})();function uf(e){let t="",r=0;for(;r+3<=e.length;r+=3){let s=e[r],o=e[r+1],c=e[r+2];t+=it[s>>2],t+=it[(s&3)<<4|o>>4],t+=it[(o&15)<<2|c>>6],t+=it[c&63]}let n=e.length-r;if(n===1){let s=e[r];t+=it[s>>2],t+=it[(s&3)<<4]}else if(n===2){let s=e[r],o=e[r+1];t+=it[s>>2],t+=it[(s&3)<<4|o>>4],t+=it[(o&15)<<2]}return t}function zn(e){if(!mb.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,n=0,s=0;for(let o=0;o<e.length;o++)if(r=r<<6|(gb[e.charCodeAt(o)]??0),n+=6,n>=8)n-=8,t[s++]=r>>n&255;return t}async function xb(e){return new Uint8Array(await crypto.subtle.digest("SHA-256",e))}async function ff(e){return wb(await xb(e))}function wb(e){let t="";for(let r of e)t+=r.toString(16).padStart(2,"0");return t}var vb=256,Dt=new Map;function _b(e){let t=Dt.get(e);if(t)return Dt.delete(e),Dt.set(e,t),t;let r=ir.fromPublic(e);if(Dt.set(e,r),Dt.size>vb){let n=Dt.keys().next().value;if(n!==void 0)Dt.delete(n)}return r}function hf(e,t,r){let n;try{n=_b(e)}catch{return!1}return n.verify(t,r)}var Mr={encode:(e)=>new TextEncoder().encode(e),decode:(e)=>new TextDecoder().decode(e)},Eb=/^SU[A-Z2-7]{56}$/,Sb=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/,Ab=/^-+BEGIN NATS USER JWT-+$/,df=/^-+BEGIN USER NKEY SEED-+$/,Ob=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 be("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 zi(e,t){try{return new Ob(ir.fromSeed(e),t)}catch(r){throw e.fill(0),new be(`invalid nkey seed (${r instanceof Error?r.message:String(r)})`)}}function Gi(e){let t=typeof e==="string"?e:Mr.decode(e),r=t.includes("BEGIN")?$i(t,df,"USER NKEY SEED"):t.trim();if(!Eb.test(r))throw new be("invalid nkey seed: expected a user seed (SU + 56 base32 characters)");let n=Mr.encode(r),s=n.slice(),o,c=!1;try{o=ir.fromSeed(s);let d=o.getPublicKey();if(!d.startsWith("U"))throw new be(`seed is not a user seed (derives ${d.slice(0,1)}… public key)`);return c=!0,n}catch(d){if(d instanceof be)throw d;throw new be(`invalid nkey seed (${d instanceof Error?d.message:String(d)})`)}finally{if(o?.clear(),s.fill(0),!c)n.fill(0)}}function Pb(e){let t=$i(e,Ab,"NATS USER JWT");if(!Sb.test(t))throw new be("creds: the user JWT block is not a JWT");let r=$i(e,df,"USER NKEY SEED");return{jwt:t,seed:r}}function $i(e,t,r){let n=e.split(/\r?\n/);for(let s=0;s<n.length;s++){if(!t.test(n[s].trim()))continue;for(let o=s+1;o<n.length;o++){let c=n[o].trim();if(c.length===0)continue;if(c.startsWith("-"))throw new be(`creds: empty ${r} block at line ${s+1}`);return c}throw new be(`creds: ${r} block at line ${s+1} has no content`)}throw new be(`creds: no -----BEGIN ${r}----- block found`)}function Tb(e){let t=e.split(".");if(t.length!==3)throw new be("JWT does not have three parts");let r;try{r=JSON.parse(Mr.decode(zn(t[1].replace(/=+$/,""))))}catch{throw new be("JWT payload is not base64url-encoded JSON")}if(typeof r!=="object"||r===null||Array.isArray(r))throw new be("JWT payload is not a JSON object");return r}function Vi(e){let t=Tb(e),r=t.sub,n=t.iss,s=t.nats,o=typeof s==="object"&&s!==null&&!Array.isArray(s)?s.issuer_account:void 0,c=typeof o==="string"&&o.length>0?o:n;if(typeof r!=="string"||typeof c!=="string")throw new Ze("credentials JWT lacks a string `sub` or `iss`");try{return or(c,r)}catch(d){throw new Ze(`credentials JWT does not carry a usable (account, user) pair: ${d instanceof Error?d.message:String(d)}`)}}function lf(e){let{jwt:t,seed:r}=Pb(e);return Ib(r,t)}function Ib(e,t){return pf(Gi(e),t)}function pf(e,t){let r=zi(e,t);try{let n=ft(Vi(t));if(n===r.publicKey)return r;throw new sr(r.publicKey,r.publicKey,void 0,void 0,n)}catch(n){throw r.wipe?.(),n}}var ht="$SYS.REQ.USER.INFO",jb=2000,Nb=30000,Kn=new WeakMap;function Ji(e){let t=e.signer;if(!t)return"unsigned";if(t.jwt===void 0)return`signer:${t.publicKey}`;try{return`signer:${t.publicKey}:${Vi(t.jwt)}`}catch{return`signer:${t.publicKey}:invalid-jwt`}}function Cb(e){let t=Kn.get(e);if(!t)t={sources:new Map,listening:!1},Kn.set(e,t);if(!t.listening){t.listening=!0;let r=t;(async()=>{try{for await(let n of e.status())if(n.type==="reconnect")r.sources.clear()}catch{}})()}return t}function bf(e,t){let r=Cb(e),n=Ji(t),s=r.sources.get(n);if(!s)s={inflight:null,settled:null,failedAt:0},r.sources.set(n,s);return s}function Wi(e,t){return t-e.failedAt>=Nb}function Mb(e,t={}){let r=Kn.get(e)?.sources.get(Ji(t));if(!r?.settled)return;if("error"in r.settled&&Wi(r,Date.now()))return;return r.settled}function kb(e,t={}){let r=Kn.get(e)?.sources.get(Ji(t));return r?.settled!==null&&r?.settled!==void 0&&"error"in r.settled&&Wi(r,Date.now())}function ar(e,t={}){let r=bf(e,t);if(r.settled){if("id"in r.settled)return Promise.resolve(r.settled.id);if(!Wi(r,Date.now()))return Promise.reject(r.settled.error)}return mf(e,r,t)}function yf(e,t={}){let r=bf(e,t);if(r.inflight)return r.inflight;return r.settled=null,r.failedAt=0,mf(e,r,t)}function Rb(e,t={}){Promise.resolve().then(()=>ar(e,t)).catch(()=>{})}function mf(e,t,r){if(t.inflight)return t.inflight;let n=qb(e,r).then((s)=>(t.settled={id:s},t.failedAt=0,t.inflight=null,s),(s)=>{let o=s instanceof be?s:new Ze(s instanceof Error?s.message:String(s),{cause:s});throw t.settled={error:o},t.failedAt=Date.now(),t.inflight=null,o});return t.inflight=n,n.catch(()=>{}),n}async function qb(e,t={}){let r=t.signer,n=await $b(e,t.timeoutMs??jb);if(r&&ft(n)!==r.publicKey)throw new sr(r.publicKey,ft(n));if(r?.jwt!==void 0){let s=Vi(r.jwt);if(ft(s)!==r.publicKey)throw new sr(r.publicKey,ft(n),void 0,void 0,ft(s));if(s!==n)throw new sr(r.publicKey,ft(n),Cr(s),Cr(n))}return n}async function $b(e,t){let r;try{r=(await e.request(ht,oe.Empty,{timeout:t})).data}catch(s){throw Ub(s,t)}let n;try{n=JSON.parse(new TextDecoder().decode(r))}catch{throw new Ze(`${ht} reply is not JSON`)}return Lb(n)}function Ub(e,t){let r=e instanceof oe.RequestError?e.cause:e;if(r instanceof oe.PermissionViolationError)return new Ze(`publish to ${ht} is a permissions violation for this user`,{cause:e});if(r instanceof oe.NoRespondersError||e instanceof oe.RequestError&&e.isNoResponders())return new Ze(`no responder for ${ht} (server without the system responder?)`,{cause:e});if(r instanceof oe.TimeoutError||e instanceof oe.TimeoutError)return new Ze(`no reply from ${ht} within ${t} ms`,{cause:e});return new Ze(`${ht} request failed: ${e instanceof Error?e.message:String(e)}`,{cause:e})}function Lb(e){if(typeof e!=="object"||e===null||Array.isArray(e))throw new Ze(`${ht} reply is not a JSON object`);let t=e;if(t.error!==void 0)throw new Ze(`${ht} answered with an error: ${JSON.stringify(t.error)}`);let r=t.data;if(typeof r!=="object"||r===null||Array.isArray(r))throw new Ze(`${ht} reply has no \`data\` object`);let n=r,s=n.user,o=n.account;if(typeof s!=="string"||typeof o!=="string")throw new Ze(`${ht} reply lacks string \`user\` / \`account\``);if(s.length===0)throw new rr("no authentication — the server reports an empty user");if(s==="[REDACTED]")throw new rr("token authentication — the server reports a redacted user");if(!cb(s))throw new rr(`password authentication — the server reports the user name ${JSON.stringify(s)}, not an NKEY`);if(Hn(o)>qi)throw new rr(`the account name is longer than ${qi} bytes and cannot be carried by the agent-ID form`);try{af(o)}catch(c){throw new rr(`the account name ${JSON.stringify(o)} cannot be carried by the agent-ID form (${c instanceof Error?c.message:String(c)})`)}return or(o,s)}var Db="Nats-Request-Info";function Fb(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,n=r.acc,s=r.user;if(n!==void 0&&typeof n!=="string")return null;if(s!==void 0&&typeof s!=="string")return null;return Object.freeze({...n!==void 0?{account:n}:{},...s!==void 0?{user:s}:{}})}function Bb(e){if(!e)return;let t=e.values(Db);if(t.length===0)return;if(t.length>1)return null;return Fb(t[0]??"")}var Ot="Agent-Sender",gf=1,Kb="AGENT-SENDER-V1",$u=2048,Uu=64,Hb=30000,zb=28,Gn="sender rejected",Yi="signature required",Gb=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,xf=/^[A-Za-z0-9_-]{1,64}$/,Vb=/^[^\s.\x00-\x1f\x7f]+(\.[^\s.\x00-\x1f\x7f]+)*$/,Jb=64,wf=86,vf=20,Wb=22,Yb=64,Xb=56,Zb=Symbol.for("nodejs.util.inspect.custom");function Xi(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,Zb,{value:()=>`AgentSenderHeader(${JSON.stringify(t())})`,enumerable:!1}),Object.freeze(e)}function _f(e){if(e.length>Uu)throw new be(`identity.name exceeds ${Uu} 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 be("identity.name contains a control character");if(r>=55296&&r<=56319){let n=t+1<e.length?e.charCodeAt(t+1):0;if(n<56320||n>57343)throw new be("identity.name contains a lone surrogate");t++}else if(r>=56320&&r<=57343)throw new be("identity.name contains a lone surrogate")}}function Qb(e){try{return _f(e),!0}catch{return!1}}function Pt(e){let t={v:gf,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 Ef(e){return zb+Hn(e)}function ey(e,t){let r={account:"A".repeat(qi),user:"U".repeat(Xb),...t!==void 0?{name:t}:{},sub:e,ts:"T".repeat(vf),nonce:"N".repeat(Yb),sig:"S".repeat(wf)};return Ef(Pt(r))}function Lu(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}:{}},n=e.signed?{...r,sub:e.sub,ts:"T".repeat(vf),nonce:"N".repeat(Wb),sig:"S".repeat(wf)}:r;return Ef(Pt(n))}function ty(e){if(!e)return;let t=e.values(Ot);if(t.length===0)return;if(t.length>1)throw new Re("more than one Agent-Sender value");return t[0]}function ry(e){if(Hn(e)>$u)throw new Re(`value exceeds ${$u} bytes`);let t;try{t=JSON.parse(e)}catch{throw new Re("not valid JSON")}if(typeof t!=="object"||t===null||Array.isArray(t))throw new Re("not a JSON object");let r=t,n=r.v;if(typeof n!=="number")throw new Re("`v` must be a JSON number");if(n!==gf)return null;let{account:s,user:o}=r;if(typeof s!=="string"||typeof o!=="string")throw new Re("`account` and `user` must be strings");try{or(s,o)}catch(O){if(O instanceof At)throw new Re(O.message);throw O}let c={v:1,account:s,user:o},d=r.name;if(d!==void 0){if(typeof d!=="string"||!Qb(d))throw new Re("`name` is not a valid display name");c.name=d}let p=r.sub;if(p!==void 0){if(typeof p!=="string"||!Vb.test(p))throw new Re("`sub` is not a NATS subject");c.sub=p}let w=r.ts;if(w!==void 0){if(typeof w!=="string"||!Gb.test(w)||Number.isNaN(Date.parse(w)))throw new Re("`ts` is not an RFC 3339 UTC timestamp");c.ts=w}let A=r.nonce;if(A!==void 0){if(typeof A!=="string"||!xf.test(A))throw new Re("`nonce` must match [A-Za-z0-9_-]{1,64}");c.nonce=A}let I=r.sig;if(I!==void 0){if(typeof I!=="string")throw new Re("`sig` must be a string");let O;try{O=zn(I)}catch{throw new Re("`sig` is not base64url")}if(O.length!==Jb)throw new Re("`sig` must decode to 64 bytes");if(c.sub===void 0||c.ts===void 0||c.nonce===void 0)throw new Re("`sig` requires `sub`, `ts` and `nonce`");c.sig=I}return Xi(c)}function ny(e=Date.now()){return new Date(Math.floor(e/1000)*1000).toISOString().replace(/\.\d{3}Z$/,"Z")}function Vn(e){return Date.parse(e)}function Sf(e){return Mr.encode(`${Kb}
|
|
24
|
-
${e.account}
|
|
25
|
-
${e.user}
|
|
26
|
-
${e.subject}
|
|
27
|
-
${e.ts}
|
|
28
|
-
${e.nonce}
|
|
29
|
-
${e.payloadSha256Hex}
|
|
30
|
-
`)}function sy(e){return xf.test(e)}async function Zi(e){let t=e.id.indexOf("."),r=e.id.slice(0,t),n=e.id.slice(t+1),s=e.ts??ny(),o=e.nonce??oe.nuid.next(),c=Sf({account:r,user:n,subject:e.sub,ts:s,nonce:o,payloadSha256Hex:await ff(e.payload)}),d=uf(await e.signer.sign(c));return Xi({v:1,account:r,user:n,...e.name!==void 0?{name:e.name}:{},sub:e.sub,ts:s,nonce:o,sig:d})}function iy(e){let t=e.id.indexOf(".");return Xi({v:1,account:e.id.slice(0,t),user:e.id.slice(t+1),...e.name!==void 0?{name:e.name}:{}})}function oy(e){if(e===void 0)return;if(!Number.isInteger(e)||e<1)throw new be("accountTokenPosition must be an integer >= 1 (1-based)");return e}function ay(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 n=t.split(".");if(r>n.length)return`accountTokenPosition ${r} is beyond the ${n.length}-token arrival subject`;let s=n[r-1];if(s!==e.account)return`arrival subject token ${JSON.stringify(s)} at position ${r} is not the header account ${JSON.stringify(e.account)}`;let o=[...n.slice(0,r-1),...n.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 Ft(e){throw new Bi(401,Gn,e)}async function cy(e,t,r,n){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 s=oy(n.accountTokenPosition);if(n.mode==="live"){let A=n.replayWindowMs??Hb,I=n.now??Date.now(),O=Math.abs(I-Vn(e.ts));if(O>A)Ft(`ts ${e.ts} is ${Math.round(O/1000)} s from now (window ${A} ms)`)}let o=ay({account:e.account,sub:e.sub},t,s);if(o!==null)Ft(o);let c=!1;if(n.operatorAttested){let A=Bb(n.headers);if(A===null)Ft("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)Ft(`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)Ft(`Nats-Request-Info user ${JSON.stringify(A.user)} disagrees with the signed user ${e.user}`)}c=s!==void 0||A?.account!==void 0}if(n.mode==="live"&&n.nonceSeen?.(e.user,e.nonce))Ft(`nonce already seen for ${e.user}`);let d=Sf({account:e.account,user:e.user,subject:e.sub,ts:e.ts,nonce:e.nonce,payloadSha256Hex:await ff(r)});if(!hf(e.user,d,zn(e.sig)))Ft(`signature does not verify for ${e.user}`);let p=or(e.account,e.user),w=n.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 Af(e,t,r={}){let n=ty(e.headers);if(n===void 0)return;let s=ry(n);if(s===null)return;return cy(s,e.subject,e.data,{...r,mode:t,headers:e.headers})}var uy="Nats-Msg-Id";async function Of(e,t,r,n){if(!e?.signer)throw new Fn(t);let s=n.nonce;if(s!==void 0&&!sy(s))throw new be("nonce must match [A-Za-z0-9_-]{1,64}");let o=await e.plan(n.sub??t,!0);if(!o)throw new Fn(t);return o.build(r,s)}async function Ui(e,t,r,n){let s=await Of(e,t,r,n),o=n.headers??oe.headers();if(o.set(Ot,Pt(s)),s.nonce!==void 0)o.set(uy,s.nonce);return o}function Ln(e){return typeof e==="string"?new TextEncoder().encode(e):e}function fy(e){let t=e.filter((n)=>n!==void 0);if(t.length===0)return new AbortController().signal;if(t.length===1)return t[0];for(let n of t)if(n.aborted)return n;let r=new AbortController;for(let n of t)n.addEventListener("abort",()=>{if(!r.signal.aborted)r.abort(n.reason)},{once:!0});return r.signal}function kn(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 cr=Object.freeze({debug:()=>{return},info:()=>{return},warn:()=>{return},error:()=>{return}}),ur="agents",Pf="agents",Jn="status",Tf="agents";function hy(e){return e===ur}async function dy(e){if(typeof e==="string")return Du(e);if(e instanceof URL){if(e.protocol!=="file:")throw TypeError(`attachment URL must use file: protocol (got "${e.protocol}" for ${e.href})`);return Du(J0(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 ly(e){return Promise.all(e.map(dy))}async function Du(e){let t=await kr(e),r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return{filename:V0(e),content:r}}var Qi=new Set(["prompt","attachments"]);function py(e){return Qi.has(e)}function Li(e){return new TextEncoder().encode(JSON.stringify(If(e)))}function Fu(e){return Hn(JSON.stringify(If(e)))}function If(e){let t={prompt:e.prompt};if(e.attachments&&e.attachments.length>0)t.attachments=e.attachments.map((r)=>({filename:r.filename,content:eo(r.content)}));if(e.extras!==void 0){for(let[r,n]of Object.entries(e.extras))if(!Qi.has(r)&&n!==void 0)jf(t,r,n)}return t}var ot="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function eo(e){let t="",r=e.length,n=0;for(;n+3<=r;n+=3){let o=e[n],c=e[n+1],d=e[n+2];t+=ot[o>>2],t+=ot[(o&3)<<4|c>>4],t+=ot[(c&15)<<2|d>>6],t+=ot[d&63]}let s=r-n;if(s===1){let o=e[n];t+=ot[o>>2],t+=ot[(o&3)<<4],t+="=="}else if(s===2){let o=e[n],c=e[n+1];t+=ot[o>>2],t+=ot[(o&3)<<4|c>>4],t+=ot[(c&15)<<2],t+="="}return t}function to(e){if(e.length===0)throw new pe("zero-byte request payload (§5.3)");let t=new TextDecoder().decode(e);if(!yy(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 n=r,s=n.prompt;if(typeof s!=="string")throw new pe("envelope missing required string `prompt` field");if(s.length===0)throw new pe("envelope `prompt` must be a non-empty string");let o=by(n),c=n.attachments;if(c===void 0)return{prompt:s,...o};if(!Array.isArray(c))throw new pe("envelope `attachments` must be an array");let d=c.map((p,w)=>my(p,w));return d.length>0?{prompt:s,attachments:d,...o}:{prompt:s,...o}}function by(e){let t;for(let[r,n]of Object.entries(e)){if(Qi.has(r))continue;jf(t??={},r,n)}return t!==void 0?{extras:Object.freeze(t)}:{}}function jf(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:!0,writable:!0,configurable:!0})}function yy(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 my(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))throw new pe(`attachment[${t}] must be an object`);let r=e,n=r.filename,s=r.content;if(typeof n!=="string")throw new pe(`attachment[${t}] missing string \`filename\``);if(typeof s!=="string")throw new pe(`attachment[${t}] missing string \`content\``);vy(n,t);let o;try{o=xy(s)}catch(c){throw new pe(`attachment[${t}] has invalid base64 content: ${c.message}`)}return{filename:n,content:o}}var gy=/^[A-Za-z0-9+/]*={0,2}$/;function xy(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(!gy.test(e))throw Error("base64 must use standard alphabet, padded, no whitespace");return _y(e)}var wy=/[/\\\0]/;function vy(e,t){if(e.length===0)throw new pe(`attachment[${t}] has empty filename`);if(wy.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 _y(e){let t=new Int8Array(128).fill(-1);for(let w=0;w<ot.length;w++)t[ot.charCodeAt(w)]=w;let r=0;if(e.endsWith("=="))r=2;else if(e.endsWith("="))r=1;let n=r>0?e.slice(0,-r):e,s=Math.floor(n.length*6/8),o=new Uint8Array(s),c=0,d=0,p=0;for(let w=0;w<n.length;w++){let A=n.charCodeAt(w);if(A>=128)throw Error("invalid base64 character");let I=t[A];if(I===-1||I===void 0)throw Error(`invalid base64 character at position ${w}`);if(d=d<<6|I,p+=6,p>=8)p-=8,o[c++]=d>>p&255}return o}var Ey=2000,Nf=600000;function Sy(e){if(e.length===0)throw new Y0}function Ay(e,t){if(t.attachmentsOk===!1)throw new X0}function jr(e,t,r,n=0){let s=t.maxPayloadBytes,o=r!==void 0&&r>0?r:void 0,c;if(s!==void 0&&o!==void 0)c=Math.min(s,o);else c=s??o;if(c===void 0)return;if(e+n>c)throw new Z0(c,e,n)}var Oy=class extends at{constructor(e){super(`query "${e}" has already been replied to`);this.id=e,this.name="QueryAlreadyRepliedError"}id};function Py(e,t){let r=!1,n=async(s)=>{if(r)throw new Oy(t.id);r=!0;let o=typeof s==="string"?new TextEncoder().encode(s):Li(s);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:n})}function Ty(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 n=r,s=n.type;if(typeof s!=="string")throw new pe("chunk body missing string `type` field");let o=n.data;switch(s){case"response":return Iy(o);case"status":return jy(o);case"query":return Ny(o);default:return null}}function Iy(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 n=Cf(t.attachments,"response");if(n!==void 0)return{type:"response",text:r,attachments:n};return{type:"response",text:r}}function jy(e){if(typeof e!=="string")throw new pe("`status` chunk `data` must be a string");return{type:"status",status:e}}function Ny(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,n=t.reply_subject,s=t.prompt;if(typeof r!=="string")throw new pe("`query` chunk missing string `id`");if(typeof n!=="string")throw new pe("`query` chunk missing string `reply_subject`");if(typeof s!=="string")throw new pe("`query` chunk missing string `prompt`");let o=Cf(t.attachments,"query");if(o!==void 0)return{type:"query",id:r,replySubject:n,prompt:s,attachments:o};return{type:"query",id:r,replySubject:n,prompt:s}}function Cf(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,n)=>{if(typeof r!=="object"||r===null||Array.isArray(r))throw new pe(`\`${t}\` chunk attachment #${n} must be an object`);let s=r;if(typeof s.filename!=="string")throw new pe(`\`${t}\` chunk attachment #${n} missing string \`filename\``);if(typeof s.content!=="string")throw new pe(`\`${t}\` chunk attachment #${n} missing string \`content\``);return{filename:s.filename,content:s.content}})}async function*Cy(e,t,r){let n=e[Symbol.asyncIterator]();while(!0){let s=null,o=new Promise((d,p)=>{s=setTimeout(()=>p(r()),t)}),c;try{c=await Promise.race([n.next(),o])}finally{if(s)clearTimeout(s)}if(c.done)return;yield c.value}}function My(e){return e.data.length===0&&!e.headers}function Mf(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 ky=class{#e;#t;#o;#n;#r;#s;#i;#c=null;#u=!1;#a=!1;constructor(e){this.#e=e.nc,this.#t=e.subject,this.#o=e.payload,this.#n=e.prepare,this.#r=e.inactivityTimeoutMs,this.#s=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 kn(this.#i);let e=this.#n?await this.#n():{payload:this.#o},t=await this.#e.requestMany(this.#t,e.payload,{strategy:"sentinel",maxWait:this.#s,...e.headers?{headers:e.headers}:{}});if(this.#c=t,this.#a){t.stop();return}if(this.#i?.aborted)throw t.stop(),kn(this.#i);let r;if(this.#i)r=()=>{this.#a=!0,t.stop()},this.#i.addEventListener("abort",r,{once:!0});try{let n=Cy(t,this.#r,()=>new ef(this.#r));for await(let s of n){if(this.#i?.aborted)throw kn(this.#i);if(Mf(s))throw kf(s);if(My(s)){yield{type:"status",status:"done"};return}let o;try{o=Ty(s.data)}catch{continue}if(!o)continue;yield Ry(o,this.#e)}if(this.#i?.aborted)throw kn(this.#i);if(this.#a)return;throw new tf(this.#s)}finally{if(r&&this.#i)this.#i.removeEventListener("abort",r);t.stop(),this.#c=null}}};function Ry(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 Py(t,{id:e.id,replySubject:e.replySubject,prompt:e.prompt,...e.attachments!==void 0?{attachments:e.attachments}:{}})}}function kf(e){let t=e.headers,r=t?.get("Nats-Service-Error-Code")??"500",n=Number(r),s=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 Qu(Number.isFinite(n)?n:500,s,o)}var Rf=class{instanceId;agent;owner;name;session;protocolVersion;description;version;promptEndpoint;metadata;endpoints;supportsSenderIdentity;identity;idSigVerified;#e;#t;#o;#n;#r;#s;constructor(e,t,r,n=void 0,s=void 0,o=[],c=cr){this.#e=e,this.#t=r,this.#o=n,this.#n=s,this.#r=Object.freeze([...o]),this.#s=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={}){Sy(e);let r=t.attachments??[],n=r.length>0;if(n)Ay(!0,this.promptEndpoint);let s=t.subject??this.promptEndpoint.subject,o=t.sub??s,c=this.promptEndpoint.minSenderTrust==="signed",d=this.#u(e,t.context??qy,s),p=this.#n;if(c&&!p?.signer)throw new Fn(s);let w=this.#e.info?.max_payload,A=p?.mayAttachHeader()?ey(o,p.name):0;if(!n){let I={prompt:e};return jr(Fu(I),this.promptEndpoint,w,A),this.#i(I,s,o,c,t,d)}return(async()=>{let I=await ly(r),O={prompt:e,attachments:I};return jr(Fu(O),this.promptEndpoint,w,A),this.#i(O,s,o,c,t,d)})()}async#i(e,t,r,n,s,o){let c=Li(e),d=await this.#h(r,n);if(d)jr(c.length,this.promptEndpoint,this.#e.info?.max_payload,d.wireBytes);let p=this.#n,w=p!==void 0&&(p.signer!==void 0||p.sendUnsignedClaim),A=fy([s.signal,this.#o]),I=w||o!==void 0?()=>this.#c(e,c,r,n,w,o):void 0;return new ky({nc:this.#e,subject:t,payload:c,...I?{prepare:I}:{},inactivityTimeoutMs:s.inactivityTimeoutMs??this.#t,maxWaitMs:s.maxWaitMs??Nf,signal:A})}async#c(e,t,r,n,s,o){let c=s?await this.#h(r,n):void 0,d=t,p,w;if(o){let A=w=await o.extend();if(A.fields!==void 0){if(d=Li({...e,extras:A.fields}),!c)jr(d.length,this.promptEndpoint,this.#e.info?.max_payload)}if(A.headers!==void 0){p=oe.headers();for(let[I,O]of Object.entries(A.headers))p.set(I,O)}}if(c)jr(d.length,this.promptEndpoint,this.#e.info?.max_payload,c.wireBytes),p??=oe.headers(),p.set(Ot,Pt(await c.build(d)));if(o&&w)await o.publish(w.results);return p!==void 0?{payload:d,headers:p}:{payload:d}}#u(e,t,r){let n=this.#r;if(n.length===0)return;let s={agent:this,prompt:e,context:t,connection:this.#e,identity:this.#a()},o=this.#s;return{extend:Mu.bind(()=>$y(n,s)),publish:Mu.bind((c)=>Uy(n,s,c,o,r))}}#a(){let e=this.#e,t=this.#n;return{canSign:t?.signer!==void 0,selfId:()=>t?.selfId()??ar(e),publishSigned:async(r,n,s={})=>{let o=Ln(n),c=await Ui(t,r,o,s);e.publish(r,o,{headers:c})}}}async status(e={}){let t=this.endpoints.find((w)=>w.name===Jn),r=e.subject??t?.subject;if(r===void 0)throw new at(`agent ${this.instanceId} declares no status endpoint`);let n=e.sub??r,s=await this.#h(n,!1),o=s?await this.#d(s,oe.Empty):void 0,c=await this.#e.request(r,oe.Empty,{timeout:e.timeoutMs??Ey,...o?{headers:o}:{}});if(Mf(c))throw kf(c);let d;try{d=JSON.parse(c.string())}catch(w){throw new pe("status reply is not JSON",{cause:w})}let p=rf(d);if(!p)throw new pe("status reply is not a §8.3 heartbeat payload");return p}async#h(e,t){let r=this.#n;if(!r)return;if(!t&&!r.mayAttachHeader())return;return r.plan(e,t)}async#d(e,t){let r=oe.headers();return r.set(Ot,Pt(await e.build(t))),r}},qy=Object.freeze({});async function $y(e,t){let r=new Map,n=new Map,s=[];for(let o of e){let c=await o.beforePrompt(t);if(s.push(c),c===void 0)continue;for(let[d,p]of Object.entries(c.fields??{})){if(py(d))throw new at(`prompt interceptor: envelope field \`${d}\` is not an extra`);r.set(d,p)}for(let[d,p]of Object.entries(c.headers??{})){if(d.toLowerCase()===Ot.toLowerCase())throw new at(`prompt interceptor: the ${Ot} header is the SDK's`);n.set(d,p)}}return{...r.size>0?{fields:Object.fromEntries(r)}:{},...n.size>0?{headers:Object.fromEntries(n)}:{},results:s}}async function Uy(e,t,r,n,s){for(let[o,c]of e.entries()){if(c.beforePublish===void 0)continue;try{await c.beforePublish(t,r[o])}catch{n.error("prompt interceptor beforePublish failed; publishing the prompt",{subject:s,interceptor:o,error:"exception"})}}}var Ly=/[.*>\s\0]/;var Ii=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 Nr(e,t){if(e.length===0)throw new Ii(t,e,"must not be empty");if(e.startsWith("$"))throw new Ii(t,e,"must not begin with '$'");if(Ly.test(e))throw new Ii(t,e,"must not contain whitespace, '.', '*', '>', or NUL")}var ji="agents",Dy="prompt",Fy="hb",By="status";var qf=class e{constructor(t,r,n,s){this.agent=t,this.owner=r,this.name=n,this.subjectToken=s}agent;owner;name;subjectToken;static new(t,r,n,s={}){Nr(t,"agent"),Nr(r,"owner"),Nr(n,"name");let o=s.subjectToken??t;if(o!==t)Nr(o,"subjectToken");return new e(t,r,n,o)}get prompt(){return`${ji}.${Dy}.${this.subjectToken}.${this.owner}.${this.name}`}get heartbeat(){return`${ji}.${Fy}.${this.subjectToken}.${this.owner}.${this.name}`}get status(){return`${ji}.${By}.${this.subjectToken}.${this.owner}.${this.name}`}};var ro="min_sender_trust";function Ky(e){if(e===void 0)return;return e==="any"?"any":"signed"}var fr="prompt";function Hy(e){let t=Object.freeze({...e.metadata??{}}),r=e.queue_group??"";if(e.name!==fr)return Object.freeze({name:e.name,subject:e.subject,queueGroup:r,metadata:t});let n,s=t.max_payload;if(s!==void 0)try{n=Ki(s)}catch(p){if(!(p instanceof nr))throw p}let o,c=t.attachments_ok;if(c==="true")o=!0;else if(c==="false")o=!1;let d=Ky(t[ro]);return Object.freeze({name:e.name,subject:e.subject,queueGroup:r,metadata:t,...n!==void 0?{maxPayloadBytes:n}:{},...o!==void 0?{attachmentsOk:o}:{},...d!==void 0?{minSenderTrust:d}:{}})}var zy="AGENT-ID-V1",He=Object.freeze({userNkey:"user_nkey",account:"account",idSig:"id_sig"});function $f(e){return Mr.encode(`${zy}
|
|
31
|
-
${e.user}
|
|
32
|
-
${e.account}
|
|
33
|
-
${e.agent}
|
|
34
|
-
${e.owner}
|
|
35
|
-
${e.promptSubject}
|
|
36
|
-
`)}async function Uf(e){let t=$f({user:ft(e.id),account:Cr(e.id),agent:e.agent,owner:e.owner,promptSubject:e.promptSubject});return uf(await e.signer.sign(t))}function Gy(e,t){let r=e[He.userNkey],n=e[He.account],s=e.agent,o=e.owner,c=e[He.idSig];if(r===void 0||n===void 0||s===void 0||o===void 0||c===void 0)return!1;let d;try{of(r),d=zn(c)}catch{return!1}if(d.length!==64)return!1;return hf(r,$f({user:r,account:n,agent:s,owner:o,promptSubject:t}),d)}function Lf(e){if(!hy(e.name))return null;let t=e.metadata??{},r=t.agent,n=t.owner,s=t.protocol_version;if(r===void 0||n===void 0||s===void 0)return null;let o=e.endpoints.map((N)=>Hy(N)),c=o.find((N)=>N.name===fr);if(!c)return null;let p=c.subject.split(".")[4],w=p!==void 0&&p!==""?p:"",A=t.session,I=A!==void 0&&A!==""?A:void 0,O=Vy(t),K=t[He.idSig]!==void 0&&Gy(t,c.subject);return Object.freeze({instanceId:e.id,agent:r,owner:n,name:w,protocolVersion:s,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}:{},...I!==void 0?{session:I}:{}})}function Vy(e){let t=e[He.userNkey],r=e[He.account];if(t===void 0||r===void 0)return;try{return or(r,t)}catch{return}}var Df=2000,Ff=750;async function Jy(e,t,r,n={},s,o=[],c){let d=n.timeoutMs!==void 0?{strategy:"timer",maxWait:n.timeoutMs}:{strategy:"stall",maxWait:Df,stall:Ff};return(await Bf(e,d)).filter((w)=>Wy(w,n.filter)).map((w)=>new Rf(e,w,t,r,s,o,c))}async function Bf(e,t){let n=new Di.Svcm(e).client(t),s=[];try{let o=await n.info(ur);for await(let c of o){let d=Lf(c);if(d)s.push(d)}}catch(o){if(o instanceof oe.NoRespondersError)return[];throw o}return s}function Wy(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 Yy(e,t,r,n,s={},o,c=[],d){let p=s.timeoutMs??2000;try{Nr(t,"instanceId")}catch{return null}let w=`$SRV.INFO.${ur}.${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 I=Lf(A);if(!I)return null;return new Rf(e,I,r,n,o,c,d)}async function Xy(e,t,r={}){let n=r.timeoutMs??2000,o=new Di.Svcm(e).client({strategy:"timer",maxWait:n});try{let c=await o.ping(ur,t);for await(let d of c)return!0;return!1}catch(c){if(c instanceof oe.NoRespondersError)return!1;throw c}}var Zy=3,Qy="agents.hb.*.*.*",em=class{constructor(e,t=cr){this.nc=e,this.logger=t}nc;logger;entries=new Map;allListeners=new Set;scopedListeners=new Map;subscription=null;get subject(){return Qy}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 n=rf(r);if(!n){this.logger.debug("dropping malformed heartbeat",{subject:t.subject});return}this.entries.set(n.instanceId,{payload:n,lastSeen:new Date}),this.dispatch(n)}}),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 s=(t.getTime()-r.lastSeen.getTime())/1000<=Zy*r.payload.intervalS;return Object.freeze({instanceId:e,lastSeen:r.lastSeen,intervalS:r.payload.intervalS,isOnline:s})}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 n=this.scopedListeners.get(e);if(n){if(n.delete(t),n.size===0)this.scopedListeners.delete(e)}}}dispatch(e){for(let r of this.allListeners)try{r(e)}catch(n){this.logger.warn("heartbeat listener threw",{error:String(n)})}let t=this.scopedListeners.get(e.instanceId);if(t)for(let r of t)try{r(e)}catch(n){this.logger.warn("heartbeat listener threw",{error:String(n)})}}},tm=class{nc;signer;name;sendUnsignedClaim;constructor(e,t={}){if(t.name!==void 0)_f(t.name);this.nc=e,this.signer=t.signer,this.name=t.name,this.sendUnsignedClaim=t.sendUnsignedClaim??!0}selfId(){return ar(this.nc,this.#e())}refresh(){return yf(this.nc,this.#e())}peek(){return Mb(this.nc,this.#e())}kickoff(){if(!this.signer&&!this.sendUnsignedClaim)return;Rb(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 rr)}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 sr||t)throw r.error;return}if(!t&&kb(this.nc,this.#e())){this.kickoff();return}try{return await this.selfId()}catch(n){if(n instanceof sr||t)throw n;return}}async plan(e,t){let r=this.signer;if(t&&!r)throw new Fn(e);if(!r&&!this.sendUnsignedClaim)return;let n=await this.resolveForRequest(t);if(n===void 0)return;let s=this.name,o=s!==void 0?{name:s}:{};if(r)return{id:n,signed:!0,sub:e,wireBytes:Lu({id:n,...o,sub:e,signed:!0}),build:(d,p)=>Zi({signer:r,id:n,...o,sub:e,payload:d,...p!==void 0?{nonce:p}:{}})};let c=iy({id:n,...o});return{id:n,signed:!1,sub:e,wireBytes:Lu({id:n,...o,sub:e,signed:!1}),build:()=>Promise.resolve(c)}}#e(){return this.signer?{signer:this.signer}:{}}},rm=1e4;function no(e){if(e===void 0)return rm;if(typeof e!=="number"||!Number.isFinite(e)||e<0)throw new be("resolveTtlMs must be a finite number of milliseconds >= 0");return e}var so=class{#e;#t;#o;#n=new Map;#r=null;#s=null;constructor(e,t={}){this.#e=e,this.#t=no(t.ttlMs),this.#o=t.timeoutMs!==void 0?{strategy:"timer",maxWait:t.timeoutMs}:{strategy:"stall",maxWait:t.maxWaitMs??Df,stall:t.stallMs??Ff}}get ttlMs(){return this.#t}invalidate(){this.#n=new Map,this.#r=null}async resolve(e){let t=fb(e);if(this.#r===null||Date.now()-this.#r>=this.#t)await this.#i();return this.#n.get(t)?.[0]}#i(){if(!this.#s){let e=this.#c().finally(()=>{if(this.#s===e)this.#s=null});this.#s=e}return this.#s}async#c(){let e=await Bf(this.#e,this.#o),t=new Map;for(let r of e)if(r.identity!==void 0&&r.idSigVerified){let n=t.get(r.identity);if(n)n.push(r);else t.set(r.identity,[r])}this.#n=t,this.#r=Date.now()}};var nm=60000,sm=2000,xw=class{#e;#t;#o;#n;#r;#s;#i;#c=new AbortController;#u=!1;constructor(e){this.#e=e.nc,this.#o=e.logger??cr,this.#n=e.streamInactivityTimeoutMs??nm,this.#r=e.identity!==void 0?new tm(e.nc,e.identity):void 0,this.#s=Object.freeze([...e.interceptors??[]]),this.#i=new so(e.nc,e.resolveTtlMs!==void 0?{ttlMs:e.resolveTtlMs}:{}),this.#t=new em(e.nc,this.#o)}get connection(){return this.#e}get streamInactivityTimeoutMs(){return this.#n}get interceptors(){return this.#s}get closeSignal(){return this.#c.signal}async discover(e={}){if(this.#a(),this.#r?.kickoff(),!this.#t.isStarted)await this.#t.start();return Jy(this.#e,this.#n,this.#c.signal,e,this.#r,this.#s,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(),Xy(this.#e,e,t)}async lookupInstance(e,t={}){return this.#a(),Yy(this.#e,e,this.#n,this.#c.signal,t,this.#r,this.#s,this.#o)}selfId(){return this.#a(),this.#r?.selfId()??ar(this.#e)}refreshSelfId(){return this.#a(),this.#r?.refresh()??yf(this.#e)}async signSender(e,t,r={}){return this.#a(),Pt(await Of(this.#r,e,Ln(t),r))}async publishSigned(e,t,r={}){this.#a();let n=Ln(t),s=await Ui(this.#r,e,n,r);this.#e.publish(e,n,{headers:s})}async requestSigned(e,t,r={}){this.#a();let n=Ln(t),s=await Ui(this.#r,e,n,r);return this.#e.request(e,n,{timeout:r.timeoutMs??sm,headers:s})}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")}},Kf=67108864,Bu=200,im=16,Ku=1000,om=/^[A-Za-z0-9+/]*={0,2}$/,Hu=" . \u2028\u2029 \uFEFF",am="�",cm='<>:"|?*',um=/^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|(?:COM|LPT)[1-9\u00b9\u00b2\u00b3]) *(?:\.|$)/i,fm=384,hm=448;async function dm(e,t,r={}){let n=r.maxTotalBytes??Kf;if(Number.isNaN(n)||n<0)throw RangeError(`saveAttachments: maxTotalBytes must be a non-negative number or Infinity (got ${n})`);let s=$n(t);await Zu(s,{recursive:!0,mode:hm});let o=[],c=0;for(let[d,p]of e.entries()){let{filename:w,content:A}=p,I=typeof w==="string"?w:"",O=typeof A==="string"?lm(A):null;if(typeof A!=="string"||O===null){o.push({filename:I,sizeBytes:0,path:null,skipped:"invalid_content"});continue}if(c+O>n){o.push({filename:I,sizeBytes:O,path:null,skipped:"over_limit"});continue}let K=Buffer.from(A,"base64"),N=await bm(s,pm(I,d+1),K);c+=O,o.push({filename:I,sizeBytes:O,path:N})}return o}function lm(e){if(e.length%4!==0||!om.test(e))return null;let t=e.endsWith("==")?2:e.endsWith("=")?1:0;return e.length/4*3-t}function pm(e,t){let r=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),n="";for(let s of e.slice(r+1)){let o=s.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)n+=am;else n+=cm.includes(s)?"_":s}if(n=zf(n),n==="")return`attachment-${t}`;return n=zu(n),um.test(n)?zu(`_${n}`):n}function zu(e){if(Ni(e)<=Bu)return e;let[t,r]=Hf(e);if([...r].length>im)t=e,r="";let n=Bu-Ni(r),s="",o=0;for(let c of t){let d=Ni(c);if(o+d>n)break;s+=c,o+=d}return zf(s)+r}function Hf(e){let t=e.lastIndexOf(".");return t>0?[e.slice(0,t),e.slice(t)]:[e,""]}function zf(e){let t=0,r=e.length;while(t<r&&Hu.includes(e[t]))t++;while(r>t&&Hu.includes(e[r-1]))r--;return e.slice(t,r)}function Ni(e){let t=0;for(let r of e){let n=r.codePointAt(0);t+=n<128?1:n<2048?2:n<65536?3:4}return t}async function bm(e,t,r){let[n,s]=Hf(t);for(let o=1;o<=Ku;o++){let c=mt(e,o===1?t:`${n} (${o})${s}`),d;try{d=await F0(c,"wx",fm)}catch(p){if(p.code==="EEXIST")continue;throw p}try{await d.writeFile(r),await d.close()}catch(p){throw await d.close().catch(()=>{return}),await B0(c).catch(()=>{return}),p}return c}throw Error(`saveAttachments: no free name for "${t}" in ${e} after ${Ku} attempts`)}function Tt(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 Rr(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 ym(e){let t=Rr("discover_agents",e);if(Ke(t))return t;let r={};for(let n of["agent","owner","name"]){let s=t[n];if(s===void 0)continue;if(typeof s!=="string"||s.length===0)return new Me(`discover_agents: "${n}" must be a non-empty string when given`);r[n]=s}return r}function mm(e){let t=Rr("prompt_agent",e);if(Ke(t))return t;let{address:r,prompt:n,attachments:s,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 n!=="string"||n.length===0)return new Me('prompt_agent: "prompt" is required and must not be empty');if(s!==void 0&&(!Array.isArray(s)||!s.every((d)=>typeof d==="string"&&d.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:n,attachments:s??[],...o!==void 0?{label:o}:{},wait:c??!0}}function gm(e){let t=Rr("wait_agent",e);if(Ke(t))return t;let r=Gf("wait_agent",t.call_ids);if(Ke(r))return r;let n=t.timeout_ms;if(n===void 0)return{callIds:r};if(typeof n!=="number"||!Number.isInteger(n)||n<0)return new Me('wait_agent: "timeout_ms" must be a whole number of milliseconds, 0 or more');return{callIds:r,timeoutMs:n}}function xm(e){let t=Rr("answer_agent",e);if(Ke(t))return t;let{call_id:r,answer:n,wait:s}=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 n!=="string"||n.length===0)return new Me('answer_agent: "answer" is required and must not be empty');if(s!==void 0&&typeof s!=="boolean")return new Me('answer_agent: "wait" must be true or false');return{callId:r,answer:n,...s!==void 0?{wait:s}:{}}}function wm(e){let t=Rr("cancel_agent",e);if(Ke(t))return t;let r=Gf("cancel_agent",t.call_ids);return Ke(r)?r:{callIds:r}}function Gf(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 Ke(e){return e instanceof Me}var Dn=["discover_agents","prompt_agent","wait_agent","answer_agent","cancel_agent","list_agent_calls"],ww=["discover_agents","prompt_agent","answer_agent"],vm=[{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 _m(){return structuredClone(vm)}var Em={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 Sm(e){let t=_m().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 n=Em[r.name];if(n===void 0)throw Error(`AgentTools: no blocking-only description for ${r.name}`);return{...r,description:n}})}var Am=256,Om="no: the caller stopped waiting for this prompt and cannot answer",Gu=["call_id","state","label","reply","question","error","partial_reply","attachments","remaining","call_ids","open_calls","open_calls_note"],Pm=["address","agent","owner","name","description","identity","identity_verified","requires_signed_prompts","accepts_attachments","instances"],vw=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=jm(e.tools),this.selfAddress=e.selfAddress,this.discoverTimeoutMs=ki("discoverTimeoutMs",e.discoverTimeoutMs),this.maxWaitMs=ki("maxWaitMs",e.maxWaitMs)??Nf,this.maxWaitAgentMs=Yu("maxWaitAgentMs",e.maxWaitAgentMs)??this.maxWaitMs,this.maxCalls=ki("maxCalls",e.maxCalls)??Am,!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)=>$n(this.cwd,t)),this.stagingOption=e.stagingDir!==void 0?$n(this.cwd,e.stagingDir):void 0,this.maxSavedBytes=Yu("maxSavedBytesPerCall",e.maxSavedBytesPerCall)??Kf,this.onSettled=e.onSettled,this.extensions=[...e.extensions??[]],this.logger=e.logger??cr,this.scopeStore=new D0,this.root=new Vu(!1,void 0),this.definitions=Sm(this.offered),this.requestInterceptor={aroundRequest:(t,r)=>{if(this.closed)return r();let n=t.sender;return this.runInPromptScope(r,n?.trust==="verified"?{caller:n.id}:{})}}}async execute(e,t,r={}){this.ensureOpen();let n=this.scopeStore.getStore()??this.root;if(Jf(e)&&!this.offered.has(e))return this.withOpenCalls(n,{error:`the tool "${e}" is not offered; your tools are ${[...this.offered].join(", ")}`});let s;switch(e){case"discover_agents":s=await this.discoverAgents(t);break;case"prompt_agent":s=await this.promptAgent(n,t,r);break;case"wait_agent":s=await this.waitAgent(n,t,r.signal);break;case"answer_agent":s=await this.answerAgent(n,t,r.signal);break;case"cancel_agent":s=await this.cancelAgent(n,t);break;case"list_agent_calls":s=this.listAgentCalls(n);break;default:s={error:`unknown tool "${e}"`}}return this.withOpenCalls(n,s)}async runInPromptScope(e,t={}){this.ensureOpen();let r=new Vu(!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 K0(e,{recursive:!0,force:!0})}}async discoverAgents(e){let t=ym(e);if(Ke(t))return{error:t.error};let r;try{r=await this.discover(t)}catch(o){return{error:`discovery failed: ${Bt(o)}`}}let n=new Map;for(let o of r){let c=o.promptSubject;if(c===this.selfAddress)continue;let d=n.get(c);if(d===void 0)n.set(c,{handle:o,instances:1});else if(d.instances+=1,!d.handle.idSigVerified&&o.idSigVerified)d.handle=o}let s=[];for(let[o,{handle:c,instances:d}]of n){let p={};for(let w of this.extensions){if(w.discoveryFields===void 0)continue;Mi(p,await w.discoveryFields(c),Pm,"a discovery entry")}s.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:d,...p})}return{agents:s}}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 n=this.known.get(r.promptSubject);if(n===void 0||r.idSigVerified||!n.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 n=mm(t);if(Ke(n))return{error:n.error};if(!n.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:s}=n;if(e.closed)return{error:"the prompt you were answering has ended; no call can start in it"};if(s===this.selfAddress)return{error:`"${s}" is your own address; answer the prompt yourself`};let o;try{o=await this.lookup(s)}catch(p){return{error:`could not look up "${s}": ${Bt(p)}`}}if(o===void 0)return{error:this.noAgentAt(s)};if(e.caller!==void 0&&o.identity===e.caller)return{error:`the agent at "${s}" sent the prompt you are answering; answer it rather than prompting it back`};let c=await this.resolveAttachments(n.attachments);if(Ke(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 d=!0;try{let p=Im(),w=n.prompt,A={},I={};for(let Oe of this.extensions){if(Oe.beforePrompt===void 0)continue;let ye=await Oe.beforePrompt({address:s,prompt:w,attachments:c,target:o,callId:p,label:n.label,toolCallId:r.toolCallId,caller:e.caller});if(!ye)continue;if(ye.error!==void 0)return{error:ye.error};if(ye.prompt!==void 0)w=ye.prompt;Object.assign(A,ye.context),Mi(I,ye.fields,Gu,"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(Oe){return{error:`the prompt was not sent: ${Bt(Oe)}`}}if(e.closed)return K.cancel(),{error:"the prompt you were answering has ended; no call can start in it"};let N=new Tm(p,e,s,o,n.label,!n.wait,I,K);if(e.reserved-=1,d=!1,e.calls.set(p,N),this.read(N),!n.wait)return this.callResult(N);return await this.untilReady(N,r.signal)}finally{if(d)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((n)=>ku(n).catch(()=>n))),r=[];for(let n of e){let s;try{s=await ku($n(this.cwd,n))}catch{return new Me(`prompt_agent: the attachment "${n}" does not exist`)}if(!(await H0(s).catch(()=>{return}))?.isFile())return new Me(`prompt_agent: the attachment "${n}" is not a file`);if(!t.some((c)=>s===c||s.startsWith(Nm(c))))return new Me(`prompt_agent: "${n}" is outside the directories you may send files from (${t.join(", ")})`);r.push(s)}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 Ci(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):[],n=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:n}),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 tf?this.finish(e,"expired",`the call ran past its runtime limit of ${Wu(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(Ci))}}async save(e,t){let r;try{let n=mt(await this.stagingDir(),e.id);r=await dm(t,n,{maxTotalBytes:Math.max(0,this.maxSavedBytes-e.savedBytes)})}catch(n){throw new Rn(`a file the agent sent could not be saved: ${Bt(n)}`)}return r.map((n)=>{if(n.path!==null)e.savedBytes+=n.sizeBytes;return{filename:n.filename,size_bytes:n.sizeBytes,path:n.path,...n.skipped!==void 0?{skipped:n.skipped}:{}}})}async afterReply(e,t,r,n){let s={};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:n});Mi(s,c,Gu,"a call's result")}}catch(o){if(o instanceof Vf)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 Rn(`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 Rn(`an extension failed on the ${t}: ${Bt(o)}`)}return s}failure(e,t){if(t instanceof Rn)return t.message;if(t instanceof Qu){let r=t.description!==""?` ${t.description}`:"";return`the agent at "${e.address}" answered with an error: ${t.code}${r}`}if(t instanceof ef)return`the agent at "${e.address}" sent nothing for ${Wu(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 Bt(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 n=e.awaited;e.state=t,e.error=r,e.endedAt=new Date,e.seq=++this.seq;let s=e.questions.splice(0).map((o)=>o.event);if(e.arriving!==void 0)s.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:n})}catch{this.logger.error("AgentTools onSettled failed",{call_id:e.id})}})()}return s}async cancel(e){if(!e.open)return;let t=this.finish(e,"cancelled");e.stream.cancel(),await Promise.all(t.map(Ci))}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 Ju([e],void 0,t)}return this.callResult(e)}async waitAgent(e,t,r){let n=gm(t);if(Ke(n))return{error:n.error};let s=this.calls(e,n.callIds);if(Ke(s))return{error:s.error};let o=Date.now()+Math.min(n.timeoutMs??this.maxWaitAgentMs,this.maxWaitAgentMs);for(;;){let c;for(let d of s)if(d.state!=="running"&&(c===void 0||d.seq<c.seq))c=d;if(c!==void 0){let d=c;return{...this.callResult(d),remaining:s.filter((p)=>p!==d&&p.open).map((p)=>p.id)}}if(Date.now()>=o||r?.aborted)return{state:"running",call_ids:s.map((d)=>d.id)};await Ju(s,o,r)}}async answerAgent(e,t,r){let n=xm(t);if(Ke(n))return{error:n.error};if(n.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 s=e.calls.get(n.callId);if(s===void 0)return{error:this.unknownCalls([n.callId])};let o=s.questions[0];if(s.state!=="input_required"||o===void 0)return{error:`call "${s.id}" has no open question: it is ${s.state}`+(s.open?"":this.ifOffered("wait_agent","; wait_agent returns its result"))};if(s.questions.shift(),s.questions.length>0)this.setState(s,"input_required");else this.setState(s,"running");try{await o.event.reply(n.answer)}catch(c){if(s.open)s.questions.unshift(o),this.setState(s,"input_required");return{error:`the answer could not be sent: ${Bt(c)}`}}if(!(n.wait??!s.detached))return this.callResult(s);return this.untilReady(s,r)}async cancelAgent(e,t){let r=wm(t);if(Ke(r))return{error:r.error};let n=[];for(let s of r.callIds){let o=e.calls.get(s);if(o===void 0){n.push({call_id:s,error:this.unknownCalls([s])});continue}await this.cancel(o),n.push(this.callResult(o))}return{calls:n}}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((n)=>!e.calls.has(n));if(r.length>0)return new Me(this.unknownCalls(r));return t.map((n)=>e.calls.get(n))}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}:{},n=e.replyFiles.length>0?{attachments:[...e.replyFiles]}:{};switch(e.state){case"running":return t;case"input_required":{let s=e.questions[0];return{...t,...s.fields,question:s.event.prompt,...s.files.length>0?{attachments:[...s.files]}:{}}}case"completed":return{...t,...e.replyFields,reply:e.text,...n};case"cancelled":return{...t,...r,...n};case"failed":case"expired":return{...t,error:e.error??"the call failed",...r,...n}}}withOpenCalls(e,t){let r=0;for(let d of e.calls.values())if(d.open)r+=1;if(r===0)return t;let n=r===1?"1 call you started is":`${r} calls you started are`,{collect:s,stop:o}=this.openCallActions(r===1?"it":"them",r===1?"its":"their"),c=e.served?`${n} still open. Calls end with the prompt you are answering: ${s} before you answer.`:`${n} still open: ${o!==void 0?`${s}, or ${o}`:s}.`;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 Zu(t,{recursive:!0,mode:448}),t}let e=await z0(mt(G0(),"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")}},Vu=class{constructor(e,t){this.served=e,this.caller=t}served;caller;calls=new Map;reserved=0;closed=!1},Tm=class{constructor(e,t,r,n,s,o,c,d){this.id=e,this.scope=t,this.address=r,this.target=n,this.label=s,this.detached=o,this.fields=c,this.stream=d,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()}},Rn=class extends Error{},Vf=class extends Error{constructor(e,t){super(`AgentTools: an extension may not set "${e}" on ${t}`);this.field=e}field};function Ju(e,t,r){return new Promise((n)=>{let s,o=()=>{for(let c of e)c.unwatch(o);if(s!==void 0)clearTimeout(s);r?.removeEventListener("abort",o),n()};for(let c of e)c.watch(o);if(t!==void 0)s=setTimeout(o,Math.max(0,t-Date.now()));if(r?.addEventListener("abort",o,{once:!0}),r?.aborted)o()})}async function Ci(e){try{await e.reply(Om)}catch{}}function Mi(e,t,r,n){if(t===void 0||t===null)return;for(let[s,o]of Object.entries(t)){if(r.includes(s))throw new Vf(s,n);e[s]=o}}function Im(){return`call_${W0(6).toString("hex")}`}function Jf(e){return Dn.includes(e)}function jm(e){if(e===void 0)return new Set(Dn);for(let n of e)if(!Jf(n))throw RangeError(`AgentTools: tools names "${n}", which is not one of ${Dn.join(", ")}`);let t=new Set(Dn.filter((n)=>e.includes(n)));if(t.size===0)throw RangeError("AgentTools: tools names no tool; a role that must not delegate needs no AgentTools");let r=[...t].filter((n)=>n!=="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 Bt(e){return e instanceof Error?e.message:String(e)}function Wu(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 Nm(e){return e.endsWith(Ru)?e:e+Ru}function ki(e,t){if(t===void 0)return;if(!(t>0))throw RangeError(`AgentTools: ${e} must be greater than 0 (got ${t})`);return t}function Yu(e,t){if(t===void 0)return;if(!(t>=0))throw RangeError(`AgentTools: ${e} must be 0 or more (got ${t})`);return t}var Cm="_INBOX.agents";function io(){return oe.createInbox(Cm)}async function _w(e,t={}){if($m(e),t.identity!==void 0&&t.identity!=="off"&&t.identity!=="signed")throw new be('connection bundle identity must be "off" or "signed"');let r=e.context;if(typeof r==="string"){let c=await db(r),d;try{d=qm(c)}catch(p){throw c.wipe(),p}if(t.identity!=="signed")return qn(d.connectionOptions,void 0,()=>d.wipe());try{let p=Mm(c.name,d.auth);return qn(d.connectionOptions,p,()=>d.wipe())}catch(p){throw d.wipe(),p}}let n=e,s=cf(n.url),o=await km(n);if(o!==void 0)delete s.token,delete s.user,delete s.pass,s.authenticator=o.kind==="creds"?oe.credsAuthenticator(o.bytes):oe.nkeyAuthenticator(o.bytes);if(t.identity!=="signed")return qn(s,void 0,()=>o?.bytes.fill(0));if(o===void 0)throw new be("signed identity requires URL connection credentials with a user seed (`creds` or `nkey`)");try{let c=o.kind==="creds"?lf(new TextDecoder().decode(o.bytes)):zi(o.bytes);return qn(s,c,()=>o.bytes.fill(0))}catch(c){throw o.bytes.fill(0),c}}function Mm(e,t){if(t.kind==="creds")return lf(new TextDecoder().decode(t.bytes));if(t.kind==="nkey")return zi(t.bytes);if(t.kind==="jwt-seed")return pf(t.seed,t.jwt);throw new be(`NATS context "${e}" has no user seed; signed identity requires creds, nkey, or user_jwt with user_seed in that same context`)}async function km(e){if(e.creds!==void 0){let t=await Bn("creds",Kt(e.creds));return{kind:"creds",bytes:new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}}if(e.nkey!==void 0){let t=await Bn("nkey",Kt(e.nkey)),r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);try{return{kind:"nkey",bytes:Gi(r)}}finally{r.fill(0)}}return}function qn(e,t,r){let n=!1,s=()=>{if(n)return;n=!0;try{t?.wipe?.()}finally{try{r()}finally{Rm(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:s,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 Rm(e){delete e.authenticator,delete e.token,delete e.user,delete e.pass,delete e.tls}function qm(e){if(e.auth.kind!=="nkey"&&e.auth.kind!=="jwt-seed")return{connectionOptions:e.connectionOptions,auth:e.auth,wipe:()=>e.wipe()};let t=Gi(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 n=!1;return{connectionOptions:e.connectionOptions,auth:r,wipe(){if(n)return;n=!0,t.fill(0)}}}function $m(e){if(typeof e!=="object"||e===null||Array.isArray(e))throw new je("connection source must be an object");let t=e;for(let s of["context","url","creds","nkey"]){let o=t[s];if(o!==void 0&&(typeof o!=="string"||o.length===0))throw new je(`connection source \`${s}\` must be a non-empty string`)}let r=typeof t.context==="string",n=typeof t.url==="string";if(r===n)throw new je("connection source must select exactly one of `context` or `url`");if(r&&(t.creds!==void 0||t.nkey!==void 0))throw new je("a context connection cannot also select direct `creds` or `nkey` credentials");if(t.creds!==void 0&&t.nkey!==void 0)throw new je("a URL connection must select at most one of `creds` or `nkey`")}var Xu=Object.freeze({maxReconnectAttempts:-1,reconnectTimeWait:2000,reconnectJitter:200,waitOnFirstConnect:!0});function Ew(e={}){let t={...e};for(let r of Object.keys(Xu))if(t[r]===void 0)t[r]=Xu[r];return t}var oo=Object.freeze({major:0,minor:3});var Qf=br(Oi(),1);var eh=br(Pi(),1);function Wf(e,t,r,n={}){return Object.freeze({agent:e.agent,owner:e.owner,instanceId:r,ts:new Date().toISOString(),intervalS:t,extras:Object.freeze({...n.extras??{}}),...n.session!==void 0?{session:n.session}:{},...n.protocolVersion!==void 0?{protocolVersion:n.protocolVersion}:{},...n.endpoints!==void 0?{endpoints:n.endpoints}:{}})}function Yf(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[n,s]of Object.entries(e.endpoints))r[n]={subject:s.subject,metadata:{...s.metadata}};t.endpoints=r}return new TextEncoder().encode(JSON.stringify(t))}async function Um(e){return Zi({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 Lm(e){let t=eh.headers();return t.set(Ot,Pt(await Um(e))),t}var th="any",co=30000,Dm=1e5,Fm=class{#e;#t;#o;#n=new Map;#r=new Map;#s=!1;constructor(e={}){this.#e=e.replayWindowMs??co,this.#t=e.maxEntries??Dm,this.#o=e.logger}get size(){return this.#n.size}has(e,t,r=Date.now()){this.sweep(r);let n=this.#n.get(`${e}.${t}`);return n!==void 0&&n>r}record(e,t,r,n=Date.now()){this.sweep(n);let s=`${e}.${t}`,o=this.#n.get(s);if(o!==void 0&&o>n)return!1;let c=r+this.#e;if(c<=n)return!0;let d=Math.floor(c/1000);this.#n.set(s,c);let p=this.#r.get(d);if(!p)p=new Set,this.#r.set(d,p);return p.add(s),this.#i(),!0}sweep(e=Date.now()){let t=Math.floor(e/1000);for(let[r,n]of this.#r){if(r>=t)continue;for(let s of n)this.#n.delete(s);this.#r.delete(r)}if(this.#s&&this.#n.size<=this.#t/2)this.#s=!1}#i(){if(this.#n.size<=this.#t)return;if(!this.#s)this.#s=!0,this.#o?.warn("nonce cache reached its cap; evicting the oldest entries — 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.#n.size<=this.#t)break;let r=this.#r.get(t);if(r)for(let n of r)this.#n.delete(n);this.#r.delete(t)}}},Bm=Object.freeze({debug:()=>{return},info:()=>{return},warn:()=>{return},error:()=>{return}}),Km=class{#e;#t;#o;#n;#r;#s;#i;#c;constructor(e={}){this.#e=e.minSenderTrust??th,this.#t=e.replayWindowMs??co,this.#o=e.accountTokenPosition,this.#n=e.acceptSender,this.#r=e.logger??Bm,this.#s=e.nonceCache??new Fm({replayWindowMs:this.#t,logger:this.#r}),this.#i=e.operatorAttested??!1,this.#c=e.resolver}get minSenderTrust(){return this.#e}get nonceCache(){return this.#s}get operatorAttested(){return this.#i}async classify(e){try{return{sender:await Af(e,"live",{replayWindowMs:this.#t,...this.#o!==void 0?{accountTokenPosition:this.#o}:{},nonceSeen:(r,n)=>this.#s.has(r,n),operatorAttested:this.#i,...this.#c!==void 0?{resolver:this.#c}:{}})}}catch(t){if(t instanceof Re)return{code:400,description:"malformed Agent-Sender header",detail:t.message};if(t instanceof Bi)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:Yi,detail:`endpoint requires a verified sender; got ${Tt(r)}`});if(r?.trust==="verified"){let{user:n,nonce:s,ts:o}=r.header;if(s!==void 0&&o!==void 0&&!this.#s.record(n,s,Vn(o)))return this.#u(e,{code:401,description:Gn,detail:`nonce already seen for ${n}`})}if(this.#n){let n;try{n=await this.#n(r)}catch{return this.#r.error("acceptSender hook threw; request not served",{subject:e.subject,sender:Tt(r),error:"hook error"}),{ok:!1,code:500,description:"server error",detail:"acceptSender hook threw"}}if(!n)return this.#u(e,r?.trust==="verified"?{code:403,description:Gn,detail:`verified sender not accepted: ${Tt(r)}`}:{code:401,description:Yi,detail:`unauthenticated sender not accepted: ${Tt(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:n,nonce:s,ts:o}=r.header;if(s!==void 0&&o!==void 0&&!this.#s.record(n,s,Vn(o))){this.#r.warn("status request: nonce replayed (reply sent anyway)",{subject:e.subject,sender:Tt(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}}},Hm=class extends Error{constructor(e,t){if(!Number.isInteger(e)||e<400||e>599)throw RangeError(`RequestRejectedError: code must be an integer in 400–599, got ${e}`);super(`request rejected (${e}): ${t}`);this.code=e,this.description=t,this.name="RequestRejectedError"}code;description};function Yn(e){let t;switch(e.type){case"response":t=zm(e);break;case"status":t={type:"status",data:e.status};break;case"query":t=Gm(e);break}return new TextEncoder().encode(JSON.stringify(t))}function zm(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 ov(e,t,r={}){let n=r.reserveBytes??32,s=r.safetyDivisor??2,o=Math.max(64,Math.floor((t-n)/s));if(e.length===0)return[];let c=[],d=new TextEncoder,p="",w=0;for(let A of e){let I=d.encode(A).byteLength;if(w+I>o&&p.length>0)c.push(p),p="",w=0;p+=A,w+=I}if(p.length>0)c.push(p);return c}function Gm(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 Xf=`${oo.major}.${oo.minor}`,Vm="1MB",Jm=!0,Wm=30,Ym=30,Xm="0.0.1";function Zm(){return crypto.randomUUID().replace(/-/g,"")}var Qm=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(Yn(t)),Promise.resolve()}async ask(e,t){let r=t.signal;r?.throwIfAborted();let n=typeof e==="string"?e:e.prompt,o=[...(typeof e==="string"?void 0:e.attachments)??[],...t.attachments??[]],c=io(),d=this.#t.subscribe(c,{max:1});await this.#t.flush();let p={type:"query",id:Zm(),replySubject:c,prompt:n,...o.length>0?{attachments:o.map((I)=>({filename:I.filename,content:eo(I.content)}))}:{}};this.#e.respond(Yn(p));let w,A;try{let I=(async()=>{for await(let N of d)return to(N.data);throw Error(`query ${p.id} reply subscription closed before any reply arrived`)})();I.catch(()=>{});let O=new Promise((N,Oe)=>{w=setTimeout(()=>Oe(Error(`query ${p.id} on ${c} timed out after ${t.timeoutMs}ms`)),t.timeoutMs)}),K=new Promise((N,Oe)=>{if(!r)return;if(A=()=>Oe(r.reason instanceof Error?r.reason:Error("query aborted")),r.aborted)A();else r.addEventListener("abort",A,{once:!0})});return await Promise.race([I,O,K])}finally{if(w!==void 0)clearTimeout(w);if(A)r?.removeEventListener("abort",A);d.unsubscribe()}}async callerListening(e={}){let t=io(),r,n=new Promise((c)=>{r=c}),s=this.#t.subscribe(t,{max:1,callback:(c,d)=>{if(!c&&d.data.length===0&&d.headers?.code===503)r()}}),o;try{await this.#t.flush();let c={type:"status",status:"ack"};this.#e.respond(Yn(c),{reply:t});let d=new Promise((p)=>{o=setTimeout(()=>p(!0),e.timeoutMs??500)});return await Promise.race([n.then(()=>!1),d])}catch{return!1}finally{if(o!==void 0)clearTimeout(o);s.unsubscribe()}}},av=class{#e;#t;#o;#n;#r;#s;#i;#c;#u;#a;#h;#d;#p=null;#f=null;#l=null;#b=null;#y=!1;constructor(e){let t=e.heartbeatIntervalS??Wm;if(t<=0)throw Error("AgentService: heartbeatIntervalS must be > 0 (heartbeat is mandatory in v0.3)");let r=e.keepaliveIntervalS===void 0?Ym:e.keepaliveIntervalS;if(r!==null&&r<=0)throw Error("AgentService: keepaliveIntervalS must be > 0 or null (null disables keep-alive)");let n=e.minSenderTrust??th;if(n!=="any"&&n!=="signed")throw Error('AgentService: minSenderTrust must be "any" or "signed"');let s=e.replayWindowMs??co;if(!(s>0))throw Error("AgentService: replayWindowMs must be > 0");let o=no(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.#n=r,this.#r=e.logger??cr,this.#s=n,this.#c=new so(e.nc,{ttlMs:o}),this.#u=Object.freeze([...e.interceptors??[]]),this.#i=new Km({minSenderTrust:n,replayWindowMs:s,...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.#s}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 — 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?Hi(e):Vm;let t=this.#e.maxPayload,r=Ki(t);if(e<=0||r<=e)return t;let n=Hi(e);return this.#r.warn(`AgentService: maxPayload=${t} (${r} bytes) exceeds server limit ${n} (${e} bytes); clamping advertised value to ${n} — anything larger would be rejected by the broker before reaching the handler`,{maxPayload:t,serverMaxPayload:e}),n}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 d=new Set([fr,Jn]);for(let p of e){if(d.has(p.name))throw Error(`AgentService.start: extraEndpoints[].name=${JSON.stringify(p.name)} collides with a protocol-reserved or already-listed endpoint name`);d.add(p.name)}}let t=this.#e.identity?.signer;this.#a=void 0;let r;if(this.#e.identity!==void 0)try{r=await ar(this.#e.nc,t?{signer:t}:{})}catch(d){if(t)throw d;this.#r.warn("AgentService: starting without identity metadata",{reason:d instanceof Error?d.message:String(d)})}this.#a=r,this.#h=r!==void 0&&t?{id:r,signer:t}:void 0;let n=new Qf.Svcm(this.#e.nc),s={...this.#e.extraMetadata,agent:this.#t.agent,owner:this.#t.owner,protocol_version:Xf};if(this.#e.session!==void 0)s.session=this.#e.session;if(r!==void 0)if(s[He.userNkey]=ft(r),s[He.account]=Cr(r),t)s[He.idSig]=await Uf({signer:t,id:r,agent:this.#t.agent,owner:this.#t.owner,promptSubject:this.#t.prompt});else delete s[He.idSig];else delete s[He.userNkey],delete s[He.account],delete s[He.idSig];this.#f=await n.add({name:ur,version:this.#e.version??Xm,description:this.#e.description??`${this.#t.agent} agent ${this.#t.name}`,metadata:s});let c={max_payload:this.#x(),attachments_ok:this.#e.attachmentsOk??Jm?"true":"false",[ro]:this.#s};this.#f.addEndpoint(fr,{subject:this.#t.prompt,queue:Pf,handler:(d,p)=>{if(d)return;this.#E(p)},metadata:c}),this.#d={subject:this.#t.prompt,metadata:{...c}},this.#f.addEndpoint(Jn,{subject:this.#t.status,queue:Tf,handler:(d,p)=>{if(d)return;this.#_(p)}});for(let d of e)this.#f.addEndpoint(d.name,{subject:d.subject,...d.queue!==void 0?{queue:d.queue}:{},handler:d.handler,...d.metadata!==void 0?{metadata:d.metadata}:{}});await this.#e.nc.flush(),await this.#v()}async stop(){if(this.#y=!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:Xf};if(this.#e.session!==void 0)e.session=this.#e.session;if(this.#d!==void 0)e.endpoints={[fr]:this.#d};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((n)=>eg.has(n));if(r.length>0){this.#r.error("heartbeatExtras reuse §8.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=Wf(this.#t,this.#o,e.info().id,this.#m()),r=Yf(t),n=this.#h,s;if(n!==void 0){try{s=await Lm({sender:n,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.#y)return}this.#e.nc.publish(this.#t.heartbeat,r,s!==void 0?{headers:s}:{})}async#v(){this.#y=!1;let e=()=>{if(this.#b!==null){this.#r.warn("heartbeat skipped: the previous beat is still being signed",{subject:this.#t.heartbeat});return}this.#b=this.#g().catch((t)=>{this.#r.error("heartbeat publish failed",{subject:this.#t.heartbeat,reason:t instanceof Error?t.message:String(t)})}).finally(()=>{this.#b=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:Tt(r)});let n=Wf(this.#t,this.#o,t.info().id,this.#m());e.respond(Yf(n))}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=to(e.data)}catch(I){let O=I instanceof pe?I.message:"malformed prompt envelope";try{e.respondError(400,ao(O))}catch{}Wn(e);return}let n;try{let I=await this.#i.admitPrompt(e);if(!I.ok){try{e.respondError(I.code,ao(I.description))}catch{}Wn(e);return}n=I.sender}catch{this.#r.error("sender classification failed",{subject:e.subject,error:"exception"});try{e.respondError(500,"sender classification error")}catch{}Wn(e);return}this.#r.debug("prompt request",{subject:e.subject,sender:Tt(n)});let s=new Qm(e,this.#e.nc,n),o=!1,c=!1,d=null,p=()=>{if(d!==null)clearInterval(d),d=null},w=async()=>{if(o)throw Error("request interceptor called next() more than once");o=!0,d=this.#S(e),await t(r,s),c=!0},A={envelope:r,sender:n,subject:e.subject,headers:e.headers};try{if(await tg(this.#u,A,w),!o)throw Error("request interceptor returned without calling next()")}catch(I){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(I);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,ao(N))}catch{}}finally{p(),Wn(e)}}#S(e){let r=Yn({type:"status",status:"ack"});try{e.respond(r)}catch{}if(this.#n===null)return null;let n=this.#n*1000,s=setInterval(()=>{try{e.respond(r)}catch{clearInterval(s)}},n);return s.unref?.(),s}},eg=new Set(["agent","owner","session","instance_id","ts","interval_s","protocol_version","endpoints"]);function tg(e,t,r){let n=(s)=>{let o=e[s];if(o===void 0)return r();return Promise.resolve(o.aroundRequest(t,()=>n(s+1)))};return n(0)}function rg(e){if(e instanceof Hm||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 Wn(e){try{e.respond(new Uint8Array(0))}catch{}}var Zf=200;function ao(e){let t=e.split(/\r?\n/).map((r)=>r.trim()).filter((r)=>r.length>0).join(" | ");if(t.length>Zf)return t.slice(0,Zf-3)+"...";return t}
|
|
37
|
-
export{br as a,z as b,To as c,Tn as d,Oi as e,Pi as f,at as g,Ki as h,hb as i,cr as j,ur as k,qf as l,He as m,xw as n,Tt as o,Dn as p,ww as q,vw as r,_w as s,Ew as t,oo as u,Km as v,Hm as w,ov as x,Vm as y,av as z};
|