nats.ws
Version:
WebSocket NATS client
1,723 lines • 192 kB
JavaScript
const Empty1 = new Uint8Array(0);
var Events1;
(function(Events1) {
Events1["Disconnect"] = "disconnect";
Events1["Reconnect"] = "reconnect";
Events1["Update"] = "update";
Events1["LDM"] = "ldm";
Events1["Error"] = "error";
})(Events1 || (Events1 = {
}));
var DebugEvents1;
(function(DebugEvents1) {
DebugEvents1["Reconnecting"] = "reconnecting";
DebugEvents1["PingTimer"] = "pingTimer";
DebugEvents1["StaleConnection"] = "staleConnection";
})(DebugEvents1 || (DebugEvents1 = {
}));
const DEFAULT_PORT = 4222;
const DEFAULT_HOST = "127.0.0.1";
const DEFAULT_RECONNECT_TIME_WAIT = 2 * 1000;
const DEFAULT_PING_INTERVAL = 2 * 60 * 1000;
const DEFAULT_MAX_PING_OUT = 2;
var AdvisoryKind1;
(function(AdvisoryKind1) {
AdvisoryKind1["API"] = "api_audit";
AdvisoryKind1["StreamAction"] = "stream_action";
AdvisoryKind1["ConsumerAction"] = "consumer_action";
AdvisoryKind1["SnapshotCreate"] = "snapshot_create";
AdvisoryKind1["SnapshotComplete"] = "snapshot_complete";
AdvisoryKind1["RestoreCreate"] = "restore_create";
AdvisoryKind1["RestoreComplete"] = "restore_complete";
AdvisoryKind1["MaxDeliver"] = "max_deliver";
AdvisoryKind1["Terminated"] = "terminated";
AdvisoryKind1["Ack"] = "consumer_ack";
AdvisoryKind1["StreamLeaderElected"] = "stream_leader_elected";
AdvisoryKind1["StreamQuorumLost"] = "stream_quorum_lost";
AdvisoryKind1["ConsumerLeaderElected"] = "consumer_leader_elected";
AdvisoryKind1["ConsumerQuorumLost"] = "consumer_quorum_lost";
})(AdvisoryKind1 || (AdvisoryKind1 = {
}));
var RetentionPolicy1;
(function(RetentionPolicy1) {
RetentionPolicy1["Limits"] = "limits";
RetentionPolicy1["Interest"] = "interest";
RetentionPolicy1["Workqueue"] = "workqueue";
})(RetentionPolicy1 || (RetentionPolicy1 = {
}));
var DiscardPolicy1;
(function(DiscardPolicy1) {
DiscardPolicy1["Old"] = "old";
DiscardPolicy1["New"] = "new";
})(DiscardPolicy1 || (DiscardPolicy1 = {
}));
var StorageType1;
(function(StorageType1) {
StorageType1["File"] = "file";
StorageType1["Memory"] = "memory";
})(StorageType1 || (StorageType1 = {
}));
var DeliverPolicy1;
(function(DeliverPolicy1) {
DeliverPolicy1["All"] = "all";
DeliverPolicy1["Last"] = "last";
DeliverPolicy1["New"] = "new";
DeliverPolicy1["StartSequence"] = "by_start_sequence";
DeliverPolicy1["StartTime"] = "by_start_time";
})(DeliverPolicy1 || (DeliverPolicy1 = {
}));
var AckPolicy1;
(function(AckPolicy1) {
AckPolicy1["None"] = "none";
AckPolicy1["All"] = "all";
AckPolicy1["Explicit"] = "explicit";
AckPolicy1["NotSet"] = "";
})(AckPolicy1 || (AckPolicy1 = {
}));
var ReplayPolicy1;
(function(ReplayPolicy1) {
ReplayPolicy1["Instant"] = "instant";
ReplayPolicy1["Original"] = "original";
})(ReplayPolicy1 || (ReplayPolicy1 = {
}));
const TE1 = new TextEncoder();
const TD1 = new TextDecoder();
function fastEncoder(...a) {
let len = 0;
for(let i = 0; i < a.length; i++){
len += a[i] ? a[i].length : 0;
}
if (len === 0) {
return Empty1;
}
const buf = new Uint8Array(len);
let c = 0;
for(let i1 = 0; i1 < a.length; i1++){
const s = a[i1];
if (s) {
for(let j = 0; j < s.length; j++){
buf[c] = s.charCodeAt(j);
c++;
}
}
}
return buf;
}
function fastDecoder(a) {
if (!a || a.length === 0) {
return "";
}
return String.fromCharCode(...a);
}
class DataBuffer1 {
constructor(){
this.buffers = [];
this.byteLength = 0;
}
static concat(...bufs) {
let max = 0;
for(let i = 0; i < bufs.length; i++){
max += bufs[i].length;
}
const out = new Uint8Array(max);
let index = 0;
for(let i1 = 0; i1 < bufs.length; i1++){
out.set(bufs[i1], index);
index += bufs[i1].length;
}
return out;
}
static fromAscii(m) {
if (!m) {
m = "";
}
return TE1.encode(m);
}
static toAscii(a) {
return TD1.decode(a);
}
reset() {
this.buffers.length = 0;
this.byteLength = 0;
}
pack() {
if (this.buffers.length > 1) {
const v = new Uint8Array(this.byteLength);
let index = 0;
for(let i = 0; i < this.buffers.length; i++){
v.set(this.buffers[i], index);
index += this.buffers[i].length;
}
this.buffers.length = 0;
this.buffers.push(v);
}
}
drain(n) {
if (this.buffers.length) {
this.pack();
const v = this.buffers.pop();
if (v) {
const max = this.byteLength;
if (n === undefined || n > max) {
n = max;
}
const d = v.subarray(0, n);
if (max > n) {
this.buffers.push(v.subarray(n));
}
this.byteLength = max - n;
return d;
}
}
return new Uint8Array(0);
}
fill(a, ...bufs) {
if (a) {
this.buffers.push(a);
this.byteLength += a.length;
}
for(let i = 0; i < bufs.length; i++){
if (bufs[i] && bufs[i].length) {
this.buffers.push(bufs[i]);
this.byteLength += bufs[i].length;
}
}
}
peek() {
if (this.buffers.length) {
this.pack();
return this.buffers[0];
}
return new Uint8Array(0);
}
size() {
return this.byteLength;
}
length() {
return this.buffers.length;
}
}
var ErrorCode1;
(function(ErrorCode1) {
ErrorCode1["ApiError"] = "BAD API";
ErrorCode1["BadAuthentication"] = "BAD_AUTHENTICATION";
ErrorCode1["BadCreds"] = "BAD_CREDS";
ErrorCode1["BadHeader"] = "BAD_HEADER";
ErrorCode1["BadJson"] = "BAD_JSON";
ErrorCode1["BadPayload"] = "BAD_PAYLOAD";
ErrorCode1["BadSubject"] = "BAD_SUBJECT";
ErrorCode1["Cancelled"] = "CANCELLED";
ErrorCode1["ConnectionClosed"] = "CONNECTION_CLOSED";
ErrorCode1["ConnectionDraining"] = "CONNECTION_DRAINING";
ErrorCode1["ConnectionRefused"] = "CONNECTION_REFUSED";
ErrorCode1["ConnectionTimeout"] = "CONNECTION_TIMEOUT";
ErrorCode1["Disconnect"] = "DISCONNECT";
ErrorCode1["InvalidOption"] = "INVALID_OPTION";
ErrorCode1["InvalidPayload"] = "INVALID_PAYLOAD";
ErrorCode1["MaxPayloadExceeded"] = "MAX_PAYLOAD_EXCEEDED";
ErrorCode1["NoResponders"] = "503";
ErrorCode1["NotFunction"] = "NOT_FUNC";
ErrorCode1["RequestError"] = "REQUEST_ERROR";
ErrorCode1["ServerOptionNotAvailable"] = "SERVER_OPT_NA";
ErrorCode1["SubClosed"] = "SUB_CLOSED";
ErrorCode1["SubDraining"] = "SUB_DRAINING";
ErrorCode1["Timeout"] = "TIMEOUT";
ErrorCode1["Tls"] = "TLS";
ErrorCode1["Unknown"] = "UNKNOWN_ERROR";
ErrorCode1["WssRequired"] = "WSS_REQUIRED";
ErrorCode1["JetStreamInvalidAck"] = "JESTREAM_INVALID_ACK";
ErrorCode1["JetStream404NoMessages"] = "404";
ErrorCode1["JetStream408RequestTimeout"] = "408";
ErrorCode1["JetStream409MaxAckPendingExceeded"] = "409";
ErrorCode1["JetStreamNotEnabled"] = "503";
ErrorCode1["AuthorizationViolation"] = "AUTHORIZATION_VIOLATION";
ErrorCode1["AuthenticationExpired"] = "AUTHENTICATION_EXPIRED";
ErrorCode1["ProtocolError"] = "NATS_PROTOCOL_ERR";
ErrorCode1["PermissionsViolation"] = "PERMISSIONS_VIOLATION";
})(ErrorCode1 || (ErrorCode1 = {
}));
class Messages {
constructor(){
this.messages = new Map();
this.messages.set(ErrorCode1.InvalidPayload, "Invalid payload type - payloads can be 'binary', 'string', or 'json'");
this.messages.set(ErrorCode1.BadJson, "Bad JSON");
this.messages.set(ErrorCode1.WssRequired, "TLS is required, therefore a secure websocket connection is also required");
}
static getMessage(s) {
return messages.getMessage(s);
}
getMessage(s) {
return this.messages.get(s) || s;
}
}
const messages = new Messages();
function isNatsError(err) {
return typeof err.code === "string";
}
class NatsError1 extends Error {
constructor(message, code1, chainedError1){
super(message);
this.name = "NatsError";
this.message = message;
this.code = code1;
this.chainedError = chainedError1;
}
static errorForCode(code, chainedError) {
const m = Messages.getMessage(code);
return new NatsError1(m, code, chainedError);
}
isAuthError() {
return this.code === ErrorCode1.AuthenticationExpired || this.code === ErrorCode1.AuthorizationViolation;
}
isPermissionError() {
return this.code === ErrorCode1.PermissionsViolation;
}
isProtocolError() {
return this.code === ErrorCode1.ProtocolError;
}
}
const CR_LF = "\r\n";
const CRLF = DataBuffer1.fromAscii(CR_LF);
const CR = new Uint8Array(CRLF)[0];
const LF = new Uint8Array(CRLF)[1];
function isUint8Array(a) {
return a instanceof Uint8Array;
}
function protoLen(ba) {
for(let i = 0; i < ba.length; i++){
const n = i + 1;
if (ba.byteLength > n && ba[i] === CR && ba[n] === LF) {
return n + 1;
}
}
return -1;
}
function extractProtocolMessage1(a) {
const len = protoLen(a);
if (len) {
const ba = new Uint8Array(a);
const out = ba.slice(0, len);
return TD1.decode(out);
}
return "";
}
function extend1(a, ...b) {
for(let i = 0; i < b.length; i++){
const o = b[i];
Object.keys(o).forEach(function(k) {
a[k] = o[k];
});
}
return a;
}
function render1(frame) {
const cr = "␍";
const lf = "␊";
return TD1.decode(frame).replace(/\n/g, lf).replace(/\r/g, cr);
}
function timeout2(ms) {
let methods;
let timer;
const p = new Promise((resolve, reject)=>{
const cancel = ()=>{
if (timer) {
clearTimeout(timer);
}
};
methods = {
cancel
};
timer = setTimeout(()=>{
reject(NatsError1.errorForCode(ErrorCode1.Timeout));
}, ms);
});
return Object.assign(p, methods);
}
function delay1(ms = 0) {
return new Promise((resolve)=>{
setTimeout(()=>{
resolve();
}, ms);
});
}
function deferred1() {
let methods = {
};
const p = new Promise((resolve, reject)=>{
methods = {
resolve,
reject
};
});
return Object.assign(p, methods);
}
function shuffle(a) {
for(let i = a.length - 1; i > 0; i--){
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [
a[j],
a[i]
];
}
return a;
}
class Perf {
constructor(){
this.timers = new Map();
this.measures = new Map();
}
mark(key) {
this.timers.set(key, Date.now());
}
measure(key, startKey, endKey) {
const s = this.timers.get(startKey);
if (s === undefined) {
throw new Error(`${startKey} is not defined`);
}
const e = this.timers.get(endKey);
if (e === undefined) {
throw new Error(`${endKey} is not defined`);
}
this.measures.set(key, e - s);
}
getEntries() {
const values = [];
this.measures.forEach((v, k)=>{
values.push({
name: k,
duration: v
});
});
return values;
}
}
function headers1() {
return new MsgHdrsImpl1();
}
const HEADER = "NATS/1.0";
class MsgHdrsImpl1 {
constructor(){
this.code = 0;
this.headers = new Map();
this.description = "";
}
[Symbol.iterator]() {
return this.headers.entries();
}
size() {
let count = 0;
for (const [_, v] of this.headers.entries()){
count += v.length;
}
return count;
}
equals(mh) {
if (mh && this.headers.size === mh.headers.size && this.code === mh.code) {
for (const [k, v] of this.headers){
const a = mh.values(k);
if (v.length !== a.length) {
return false;
}
const vv = [
...v
].sort();
const aa = [
...a
].sort();
for(let i = 0; i < vv.length; i++){
if (vv[i] !== aa[i]) {
return false;
}
}
return true;
}
}
return false;
}
static decode(a) {
const mh = new MsgHdrsImpl1();
const s = TD1.decode(a);
const lines = s.split("\r\n");
const h = lines[0];
if (h !== HEADER) {
let str = h.replace(HEADER, "");
mh.code = parseInt(str, 10);
const scode = mh.code.toString();
mh.set("Status", scode);
str = str.replace(scode, "");
mh.description = str.trim();
if (mh.description) {
mh.set("Description", mh.description);
}
} else {
lines.slice(1).map((s1)=>{
if (s1) {
const idx = s1.indexOf(": ");
const k = s1.slice(0, idx);
const v = s1.slice(idx + 2);
mh.append(k, v);
}
});
}
return mh;
}
toString() {
if (this.headers.size === 0) {
return "";
}
let s = HEADER;
for (const [k, v] of this.headers){
for(let i = 0; i < v.length; i++){
s = `${s}\r\n${k}: ${v[i]}`;
}
}
return `${s}\r\n\r\n`;
}
encode() {
return TE1.encode(this.toString());
}
static canonicalMIMEHeaderKey(k) {
const a = 97;
const A = 65;
const Z = 90;
const z = 122;
const dash = 45;
const colon = 58;
const start = 33;
const end = 126;
const toLower = 97 - 65;
let upper = true;
const buf = new Array(k.length);
for(let i = 0; i < k.length; i++){
let c = k.charCodeAt(i);
if (c === 58 || c < 33 || c > 126) {
throw new NatsError1(`'${k[i]}' is not a valid character for a header key`, ErrorCode1.BadHeader);
}
if (upper && 97 <= c && c <= 122) {
c -= toLower;
} else if (!upper && 65 <= c && c <= 90) {
c += toLower;
}
buf[i] = c;
upper = c == dash;
}
return String.fromCharCode(...buf);
}
static validHeaderValue(k) {
const inv = /[\r\n]/;
if (inv.test(k)) {
throw new NatsError1("invalid header value - \\r and \\n are not allowed.", ErrorCode1.BadHeader);
}
return k.trim();
}
get(k) {
const key = MsgHdrsImpl1.canonicalMIMEHeaderKey(k);
const a = this.headers.get(key);
return a ? a[0] : "";
}
has(k) {
return this.get(k) !== "";
}
set(k, v) {
const key = MsgHdrsImpl1.canonicalMIMEHeaderKey(k);
const value = MsgHdrsImpl1.validHeaderValue(v);
this.headers.set(key, [
value
]);
}
append(k, v) {
const key = MsgHdrsImpl1.canonicalMIMEHeaderKey(k);
const value = MsgHdrsImpl1.validHeaderValue(v);
let a = this.headers.get(key);
if (!a) {
a = [];
this.headers.set(key, a);
}
a.push(value);
}
values(k) {
const key = MsgHdrsImpl1.canonicalMIMEHeaderKey(k);
return this.headers.get(key) || [];
}
delete(k) {
const key = MsgHdrsImpl1.canonicalMIMEHeaderKey(k);
this.headers.delete(key);
}
get hasError() {
return this.code >= 300;
}
get status() {
return `${this.code} ${this.description}`.trim();
}
}
function isRequestError(msg) {
if (msg && msg.headers) {
const headers1 = msg.headers;
if (headers1.hasError) {
if (headers1.status === "503") {
return NatsError1.errorForCode(ErrorCode1.NoResponders);
} else {
let desc = headers1.get("description");
if (desc === "") {
desc = ErrorCode1.RequestError;
}
desc = desc.toLowerCase();
return new NatsError1(desc, headers1.status);
}
}
}
return null;
}
class MsgImpl1 {
constructor(msg1, data1, publisher2){
this._msg = msg1;
this._rdata = data1;
this.publisher = publisher2;
}
get subject() {
if (this._subject) {
return this._subject;
}
this._subject = TD1.decode(this._msg.subject);
return this._subject;
}
get reply() {
if (this._reply) {
return this._reply;
}
this._reply = TD1.decode(this._msg.reply);
return this._reply;
}
get sid() {
return this._msg.sid;
}
get headers() {
if (this._msg.hdr > -1 && !this._headers) {
const buf = this._rdata.subarray(0, this._msg.hdr);
this._headers = MsgHdrsImpl1.decode(buf);
}
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(data = Empty1, opts) {
if (this.reply) {
this.publisher.publish(this.reply, data, opts);
return true;
}
return false;
}
}
let transportConfig;
function setTransportFactory1(config) {
transportConfig = config;
}
function defaultPort() {
return transportConfig !== undefined && transportConfig.defaultPort !== undefined ? transportConfig.defaultPort : 4222;
}
function getUrlParseFn() {
return transportConfig !== undefined && transportConfig.urlParseFn ? transportConfig.urlParseFn : undefined;
}
function newTransport() {
if (!transportConfig || typeof transportConfig.factory !== "function") {
throw new Error("transport fn is not set");
}
return transportConfig.factory();
}
const digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const base = 36;
const maxSeq = 3656158440062976;
const minInc = 33;
const maxInc = 333;
const totalLen = 12 + 10;
const cryptoObj = initCrypto();
function initCrypto() {
let cryptoObj1 = null;
if (typeof globalThis !== "undefined") {
if ("crypto" in globalThis && globalThis.crypto.getRandomValues) {
cryptoObj1 = globalThis.crypto;
}
}
if (!cryptoObj1) {
cryptoObj1 = {
getRandomValues: function(array) {
for(let i = 0; i < array.length; i++){
array[i] = Math.floor(Math.random() * 255);
}
}
};
}
return cryptoObj1;
}
class Nuid1 {
constructor(){
this.buf = new Uint8Array(totalLen);
this.init();
}
init() {
this.setPre();
this.initSeqAndInc();
this.fillSeq();
}
initSeqAndInc() {
this.seq = Math.floor(Math.random() * maxSeq);
this.inc = Math.floor(Math.random() * (maxInc - minInc) + minInc);
}
setPre() {
const cbuf = new Uint8Array(12);
cryptoObj.getRandomValues(cbuf);
for(let i = 0; i < 12; i++){
const di = cbuf[i] % 36;
this.buf[i] = digits.charCodeAt(di);
}
}
fillSeq() {
let n = this.seq;
for(let i = totalLen - 1; i >= 12; i--){
this.buf[i] = digits.charCodeAt(n % base);
n = Math.floor(n / base);
}
}
next() {
this.seq += this.inc;
if (this.seq > 3656158440062976) {
this.setPre();
this.initSeqAndInc();
}
this.fillSeq();
return String.fromCharCode.apply(String, this.buf);
}
reset() {
this.init();
}
}
const nuid1 = new Nuid1();
const IPv4LEN = 4;
const ASCII0 = 48;
const ASCIIA = 65;
const ASCIIa = 97;
function ipV4(a, b, c, d) {
const ip = new Uint8Array(16);
const prefix = [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
255,
255
];
prefix.forEach((v, idx)=>{
ip[idx] = v;
});
ip[12] = a;
ip[13] = b;
ip[14] = c;
ip[15] = d;
return ip;
}
function isIP1(h) {
return parseIP1(h) !== undefined;
}
function parseIP1(h) {
for(let i = 0; i < h.length; i++){
switch(h[i]){
case ".":
return parseIPv4(h);
case ":":
return parseIPv6(h);
}
}
return;
}
function parseIPv4(s) {
const ip = new Uint8Array(4);
for(let i = 0; i < 4; i++){
if (s.length === 0) {
return undefined;
}
if (i > 0) {
if (s[0] !== ".") {
return undefined;
}
s = s.substring(1);
}
const { n , c , ok } = dtoi(s);
if (!ok || n > 255) {
return undefined;
}
s = s.substring(c);
ip[i] = n;
}
return ipV4(ip[0], ip[1], ip[2], ip[3]);
}
function parseIPv6(s) {
const ip = new Uint8Array(16);
let ellipsis = -1;
if (s.length >= 2 && s[0] === ":" && s[1] === ":") {
ellipsis = 0;
s = s.substring(2);
if (s.length === 0) {
return ip;
}
}
let i = 0;
while(i < 16){
const { n , c , ok } = xtoi(s);
if (!ok || n > 65535) {
return undefined;
}
if (c < s.length && s[c] === ".") {
if (ellipsis < 0 && i != 16 - 4) {
return undefined;
}
if (i + 4 > 16) {
return undefined;
}
const ip4 = parseIPv4(s);
if (ip4 === undefined) {
return undefined;
}
ip[i] = ip4[12];
ip[i + 1] = ip4[13];
ip[i + 2] = ip4[14];
ip[i + 3] = ip4[15];
s = "";
i += IPv4LEN;
break;
}
ip[i] = n >> 8;
ip[i + 1] = n;
i += 2;
s = s.substring(c);
if (s.length === 0) {
break;
}
if (s[0] !== ":" || s.length == 1) {
return undefined;
}
s = s.substring(1);
if (s[0] === ":") {
if (ellipsis >= 0) {
return undefined;
}
ellipsis = i;
s = s.substring(1);
if (s.length === 0) {
break;
}
}
}
if (s.length !== 0) {
return undefined;
}
if (i < 16) {
if (ellipsis < 0) {
return undefined;
}
const n = 16 - i;
for(let j = i - 1; j >= ellipsis; j--){
ip[j + n] = ip[j];
}
for(let j1 = ellipsis + n - 1; j1 >= ellipsis; j1--){
ip[j1] = 0;
}
} else if (ellipsis >= 0) {
return undefined;
}
return ip;
}
function dtoi(s) {
let i = 0;
let n = 0;
for(i = 0; i < s.length && 48 <= s.charCodeAt(i) && s.charCodeAt(i) <= 57; i++){
n = n * 10 + (s.charCodeAt(i) - ASCII0);
if (n >= 16777215) {
return {
n: 16777215,
c: i,
ok: false
};
}
}
if (i === 0) {
return {
n: 0,
c: 0,
ok: false
};
}
return {
n: n,
c: i,
ok: true
};
}
function xtoi(s) {
let n = 0;
let i = 0;
for(i = 0; i < s.length; i++){
if (48 <= s.charCodeAt(i) && s.charCodeAt(i) <= 57) {
n *= 16;
n += s.charCodeAt(i) - ASCII0;
} else if (97 <= s.charCodeAt(i) && s.charCodeAt(i) <= 102) {
n *= 16;
n += s.charCodeAt(i) - ASCIIa + 10;
} else if (65 <= s.charCodeAt(i) && s.charCodeAt(i) <= 70) {
n *= 16;
n += s.charCodeAt(i) - ASCIIA + 10;
} else {
break;
}
if (n >= 16777215) {
return {
n: 0,
c: i,
ok: false
};
}
}
if (i === 0) {
return {
n: 0,
c: i,
ok: false
};
}
return {
n: n,
c: i,
ok: true
};
}
class ServerImpl {
constructor(u1, gossiped = false){
this.src = u1;
this.tlsName = "";
if (u1.match(/^(.*:\/\/)(.*)/m)) {
u1 = u1.replace(/^(.*:\/\/)(.*)/gm, "$2");
}
const url = new URL(`http://${u1}`);
if (!url.port) {
url.port = `${DEFAULT_PORT}`;
}
this.listen = url.host;
this.hostname = url.hostname;
this.port = parseInt(url.port, 10);
this.didConnect = false;
this.reconnects = 0;
this.lastConnect = 0;
this.gossiped = gossiped;
}
toString() {
return this.listen;
}
}
class Servers {
constructor(randomize, listens = [], opts5 = {
}){
this.firstSelect = true;
this.servers = [];
this.tlsName = "";
const urlParseFn = getUrlParseFn();
if (listens) {
listens.forEach((hp)=>{
hp = urlParseFn ? urlParseFn(hp) : hp;
this.servers.push(new ServerImpl(hp));
});
if (randomize) {
this.servers = shuffle(this.servers);
}
}
if (this.servers.length === 0) {
this.addServer(`${DEFAULT_HOST}:${defaultPort()}`, false);
}
this.currentServer = this.servers[0];
}
updateTLSName() {
const cs = this.getCurrentServer();
if (!isIP1(cs.hostname)) {
this.tlsName = cs.hostname;
this.servers.forEach((s)=>{
if (s.gossiped) {
s.tlsName = this.tlsName;
}
});
}
}
getCurrentServer() {
return this.currentServer;
}
addServer(u, implicit = false) {
const urlParseFn1 = getUrlParseFn();
u = urlParseFn1 ? urlParseFn1(u) : u;
const s = new ServerImpl(u, implicit);
if (isIP1(s.hostname)) {
s.tlsName = this.tlsName;
}
this.servers.push(s);
}
selectServer() {
if (this.firstSelect) {
this.firstSelect = false;
return this.currentServer;
}
const t = this.servers.shift();
if (t) {
this.servers.push(t);
this.currentServer = t;
}
return t;
}
removeCurrentServer() {
this.removeServer(this.currentServer);
}
removeServer(server) {
if (server) {
const index = this.servers.indexOf(server);
this.servers.splice(index, 1);
}
}
length() {
return this.servers.length;
}
next() {
return this.servers.length ? this.servers[0] : undefined;
}
getServers() {
return this.servers;
}
update(info) {
const added = [];
let deleted = [];
const urlParseFn1 = getUrlParseFn();
const discovered = new Map();
if (info.connect_urls && info.connect_urls.length > 0) {
info.connect_urls.forEach((hp)=>{
hp = urlParseFn1 ? urlParseFn1(hp) : hp;
const s = new ServerImpl(hp, true);
discovered.set(hp, s);
});
}
const toDelete = [];
this.servers.forEach((s, index)=>{
const u2 = s.listen;
if (s.gossiped && this.currentServer.listen !== u2 && discovered.get(u2) === undefined) {
toDelete.push(index);
}
discovered.delete(u2);
});
toDelete.reverse();
toDelete.forEach((index)=>{
const removed = this.servers.splice(index, 1);
deleted = deleted.concat(removed[0].listen);
});
discovered.forEach((v, k, m)=>{
this.servers.push(v);
added.push(k);
});
return {
added,
deleted
};
}
}
class QueuedIteratorImpl {
constructor(){
this.inflight = 0;
this.processed = 0;
this.received = 0;
this.noIterator = false;
this.done = false;
this.signal = deferred1();
this.yields = [];
this.iterClosed = deferred1();
}
[Symbol.asyncIterator]() {
return this.iterate();
}
push(v) {
if (this.done) {
return;
}
this.yields.push(v);
this.signal.resolve();
}
async *iterate() {
if (this.noIterator) {
throw new NatsError1("unsupported iterator", ErrorCode1.ApiError);
}
while(true){
if (this.yields.length === 0) {
await this.signal;
}
if (this.err) {
throw this.err;
}
const yields = this.yields;
this.inflight = yields.length;
this.yields = [];
for(let i = 0; i < yields.length; i++){
this.processed++;
yield yields[i];
if (this.dispatchedFn && yields[i]) {
this.dispatchedFn(yields[i]);
}
this.inflight--;
}
if (this.done) {
break;
} else if (this.yields.length === 0) {
yields.length = 0;
this.yields = yields;
this.signal = deferred1();
}
}
}
stop(err) {
this.err = err;
this.done = true;
this.signal.resolve();
this.iterClosed.resolve();
}
getProcessed() {
return this.noIterator ? this.received : this.processed;
}
getPending() {
return this.yields.length + this.inflight;
}
getReceived() {
return this.received;
}
}
class SubscriptionImpl1 extends QueuedIteratorImpl {
constructor(protocol, subject1, opts1 = {
}){
super();
extend1(this, opts1);
this.protocol = protocol;
this.subject = subject1;
this.draining = false;
this.noIterator = typeof opts1.callback === "function";
this.closed = deferred1();
if (opts1.timeout) {
this.timer = timeout2(opts1.timeout);
this.timer.then(()=>{
this.timer = undefined;
}).catch((err)=>{
this.stop(err);
});
}
}
setDispatchedFn(cb) {
if (this.noIterator) {
const uc = this.callback;
this.callback = (err, msg1)=>{
uc(err, msg1);
cb(msg1);
};
} else {
this.dispatchedFn = cb;
}
}
callback(err, msg) {
this.cancelTimeout();
err ? this.stop(err) : this.push(msg);
}
close() {
if (!this.isClosed()) {
this.cancelTimeout();
this.stop();
if (this.cleanupFn) {
try {
this.cleanupFn(this, this.info);
} catch (err) {
}
}
this.closed.resolve();
}
}
unsubscribe(max) {
this.protocol.unsubscribe(this, max);
}
cancelTimeout() {
if (this.timer) {
this.timer.cancel();
this.timer = undefined;
}
}
drain() {
if (this.protocol.isClosed()) {
throw NatsError1.errorForCode(ErrorCode1.ConnectionClosed);
}
if (this.isClosed()) {
throw NatsError1.errorForCode(ErrorCode1.SubClosed);
}
if (!this.drained) {
this.protocol.unsub(this);
this.drained = this.protocol.flush(deferred1());
this.drained.then(()=>{
this.protocol.subscriptions.cancel(this);
});
}
return this.drained;
}
isDraining() {
return this.draining;
}
isClosed() {
return this.done;
}
getSubject() {
return this.subject;
}
getMax() {
return this.max;
}
getID() {
return this.sid;
}
}
class Subscriptions1 {
constructor(){
this.sidCounter = 0;
this.subs = new Map();
}
size() {
return this.subs.size;
}
add(s) {
this.sidCounter++;
s.sid = this.sidCounter;
this.subs.set(s.sid, s);
return s;
}
setMux(s) {
this.mux = s;
return s;
}
getMux() {
return this.mux;
}
get(sid) {
return this.subs.get(sid);
}
all() {
const buf = [];
for (const s of this.subs.values()){
buf.push(s);
}
return buf;
}
cancel(s) {
if (s) {
s.close();
this.subs.delete(s.sid);
}
}
handleError(err) {
let handled = false;
if (err) {
const re = /^'Permissions Violation for Subscription to "(\S+)"'/i;
const ma = re.exec(err.message);
if (ma) {
const subj = ma[1];
this.subs.forEach((sub)=>{
if (subj == sub.subject) {
sub.callback(err, {
});
sub.close();
handled = sub !== this.mux;
}
});
}
}
return handled;
}
close() {
this.subs.forEach((sub)=>{
sub.close();
});
}
}
class Heartbeat1 {
constructor(ph, interval, maxOut){
this.ph = ph;
this.interval = interval;
this.maxOut = maxOut;
this.pendings = [];
}
start() {
this.cancel();
this._schedule();
}
cancel(stale) {
if (this.timer) {
clearTimeout(this.timer);
this.timer = undefined;
}
this._reset();
if (stale) {
this.ph.disconnect();
}
}
_schedule() {
this.timer = setTimeout(()=>{
this.ph.dispatchStatus({
type: DebugEvents1.PingTimer,
data: `${this.pendings.length + 1}`
});
if (this.pendings.length === this.maxOut) {
this.cancel(true);
return;
}
const ping = deferred1();
this.ph.flush(ping).then(()=>{
this._reset();
}).catch(()=>{
this.cancel();
});
this.pendings.push(ping);
this._schedule();
}, this.interval);
}
_reset() {
this.pendings = this.pendings.filter((p)=>{
const d = p;
d.resolve();
return false;
});
}
}
class AssertionError extends Error {
constructor(msg2){
super(msg2);
this.name = "AssertionError";
}
}
function assert(cond, msg3 = "Assertion failed.") {
if (!cond) {
throw new AssertionError(msg3);
}
}
const MIN_READ = 32 * 1024;
const MAX_SIZE1 = 2 ** 32 - 2;
function copy(src, dst, off = 0) {
const r = dst.byteLength - off;
if (src.byteLength > r) {
src = src.subarray(0, r);
}
dst.set(src, off);
return src.byteLength;
}
class DenoBuffer1 {
constructor(ab){
this._off = 0;
if (ab == null) {
this._buf = new Uint8Array(0);
return;
}
this._buf = new Uint8Array(ab);
}
bytes(options = {
copy: true
}) {
if (options.copy === false) 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(n) {
if (n === 0) {
this.reset();
return;
}
if (n < 0 || n > this.length) {
throw Error("bytes.Buffer: truncation out of range");
}
this._reslice(this._off + n);
}
reset() {
this._reslice(0);
this._off = 0;
}
_tryGrowByReslice(n) {
const l = this._buf.byteLength;
if (n <= this.capacity - l) {
this._reslice(l + n);
return l;
}
return -1;
}
_reslice(len) {
assert(len <= this._buf.buffer.byteLength);
this._buf = new Uint8Array(this._buf.buffer, 0, len);
}
readByte() {
const a = new Uint8Array(1);
if (this.read(a)) {
return a[0];
}
return null;
}
read(p) {
if (this.empty()) {
this.reset();
if (p.byteLength === 0) {
return 0;
}
return null;
}
const nread = copy(this._buf.subarray(this._off), p);
this._off += nread;
return nread;
}
writeByte(n) {
return this.write(Uint8Array.of(n));
}
writeString(s) {
return this.write(TE1.encode(s));
}
write(p) {
const m = this._grow(p.byteLength);
return copy(p, this._buf, m);
}
_grow(n) {
const m = this.length;
if (m === 0 && this._off !== 0) {
this.reset();
}
const i = this._tryGrowByReslice(n);
if (i >= 0) {
return i;
}
const c = this.capacity;
if (n <= Math.floor(c / 2) - m) {
copy(this._buf.subarray(this._off), this._buf);
} else if (c + n > MAX_SIZE1) {
throw new Error("The buffer cannot be grown beyond the maximum size.");
} else {
const buf = new Uint8Array(Math.min(2 * c + n, MAX_SIZE1));
copy(this._buf.subarray(this._off), buf);
this._buf = buf;
}
this._off = 0;
this._reslice(Math.min(m + n, MAX_SIZE1));
return m;
}
grow(n) {
if (n < 0) {
throw Error("Buffer._grow: negative count");
}
const m = this._grow(n);
this._reslice(m);
}
readFrom(r) {
let n = 0;
const tmp = new Uint8Array(MIN_READ);
while(true){
const shouldGrow = this.capacity - this.length < MIN_READ;
const buf = shouldGrow ? tmp : new Uint8Array(this._buf.buffer, this.length);
const nread = r.read(buf);
if (nread === null) {
return n;
}
if (shouldGrow) this.write(buf.subarray(0, nread));
else this._reslice(this.length + nread);
n += nread;
}
}
}
function readAll1(r) {
const buf = new DenoBuffer1();
buf.readFrom(r);
return buf.bytes();
}
function writeAll1(w, arr) {
let nwritten = 0;
while(nwritten < arr.length){
nwritten += w.write(arr.subarray(nwritten));
}
}
var Kind1;
(function(Kind1) {
Kind1[Kind1["OK"] = 0] = "OK";
Kind1[Kind1["ERR"] = 1] = "ERR";
Kind1[Kind1["MSG"] = 2] = "MSG";
Kind1[Kind1["INFO"] = 3] = "INFO";
Kind1[Kind1["PING"] = 4] = "PING";
Kind1[Kind1["PONG"] = 5] = "PONG";
})(Kind1 || (Kind1 = {
}));
function newMsgArg() {
const ma = {
};
ma.sid = -1;
ma.hdr = -1;
ma.size = -1;
return ma;
}
const ASCII_0 = 48;
class Parser1 {
constructor(dispatcher){
this.dispatcher = dispatcher;
this.state = State1.OP_START;
this.as = 0;
this.drop = 0;
this.hdr = 0;
}
parse(buf) {
if (typeof module !== "undefined" && module.exports) {
buf.subarray = buf.slice;
}
let i;
for(i = 0; i < buf.length; i++){
const b = buf[i];
switch(this.state){
case State1.OP_START:
switch(b){
case cc.M:
case cc.m:
this.state = State1.OP_M;
this.hdr = -1;
this.ma = newMsgArg();
break;
case cc.H:
case cc.h:
this.state = State1.OP_H;
this.hdr = 0;
this.ma = newMsgArg();
break;
case cc.P:
case cc.p:
this.state = State1.OP_P;
break;
case cc.PLUS:
this.state = State1.OP_PLUS;
break;
case cc.MINUS:
this.state = State1.OP_MINUS;
break;
case cc.I:
case cc.i:
this.state = State1.OP_I;
break;
default:
throw this.fail(buf.subarray(i));
}
break;
case State1.OP_H:
switch(b){
case cc.M:
case cc.m:
this.state = State1.OP_M;
break;
default:
throw this.fail(buf.subarray(i));
}
break;
case State1.OP_M:
switch(b){
case cc.S:
case cc.s:
this.state = State1.OP_MS;
break;
default:
throw this.fail(buf.subarray(i));
}
break;
case State1.OP_MS:
switch(b){
case cc.G:
case cc.g:
this.state = State1.OP_MSG;
break;
default:
throw this.fail(buf.subarray(i));
}
break;
case State1.OP_MSG:
switch(b){
case cc.SPACE:
case cc.TAB:
this.state = State1.OP_MSG_SPC;
break;
default:
throw this.fail(buf.subarray(i));
}
break;
case State1.OP_MSG_SPC:
switch(b){
case cc.SPACE:
case cc.TAB: continue;
default:
this.state = State1.MSG_ARG;
this.as = i;
}
break;
case State1.MSG_ARG:
switch(b){
case cc.CR:
this.drop = 1;
break;
case cc.NL:
{
const arg = this.argBuf ? this.argBuf.bytes() : buf.subarray(this.as, i - this.drop);
this.processMsgArgs(arg);
this.drop = 0;
this.as = i + 1;
this.state = State1.MSG_PAYLOAD;
i = this.as + this.ma.size - 1;
break;
}
default:
if (this.argBuf) {
this.argBuf.writeByte(b);
}
}
break;
case State1.MSG_PAYLOAD:
if (this.msgBuf) {
if (this.msgBuf.length >= this.ma.size) {
const data2 = this.msgBuf.bytes({
copy: false
});
this.dispatcher.push({
kind: Kind1.MSG,
msg: this.ma,
data: data2
});
this.argBuf = undefined;
this.msgBuf = undefined;
this.state = State1.MSG_END;
} else {
let toCopy = this.ma.size - this.msgBuf.length;
const avail = buf.length - i;
if (avail < toCopy) {
toCopy = avail;
}
if (toCopy > 0) {
this.msgBuf.write(buf.subarray(i, i + toCopy));
i = i + toCopy - 1;
} else {
this.msgBuf.writeByte(b);
}
}
} else if (i - this.as >= this.ma.size) {
this.dispatcher.push({
kind: Kind1.MSG,
msg: this.ma,
data: buf.subarray(this.as, i)
});
this.argBuf = undefined;
this.msgBuf = undefined;
this.state = State1.MSG_END;
}
break;
case State1.MSG_END:
switch(b){
case cc.NL:
this.drop = 0;
this.as = i + 1;
this.state = State1.OP_START;
break;
default: continue;
}
break;
case State1.OP_PLUS:
switch(b){
case cc.O:
case cc.o:
this.state = State1.OP_PLUS_O;
break;
default:
throw this.fail(buf.subarray(i));
}
break;
case State1.OP_PLUS_O:
switch(b){
case cc.K:
case cc.k:
this.state = State1.OP_PLUS_OK;
break;
default:
throw this.fail(buf.subarray(i));
}
break;
case State1.OP_PLUS_OK:
switch(b){
case cc.NL:
this.dispatcher.push({
kind: Kind1.OK
});
this.drop = 0;
this.state = State1.OP_START;
break;
}
break;
case State1.OP_MINUS:
switch(b){
case cc.E:
case cc.e:
this.state = State1.OP_MINUS_E;
break;
default:
throw this.fail(buf.subarray(i));
}
break;
case State1.OP_MINUS_E:
switch(b){
case cc.R:
case cc.r:
this.state = State1.OP_MINUS_ER;
break;
default:
throw this.fail(buf.subarray(i));
}
break;
case State1.OP_MINUS_ER:
switch(b){
case cc.R:
case cc.r:
this.state = State1.OP_MINUS_ERR;
break;
default:
throw this.fail(buf.subarray(i));
}
break;
case State1.OP_MINUS_ERR:
switch(b){
case cc.SPACE:
case cc.TAB:
this.state = State1.OP_MINUS_ERR_SPC;
break;
default:
throw this.fail(buf.subarray(i));
}
break;
case State1.OP_MINUS_ERR_SPC:
switch(b){
case cc.SPACE:
case cc.TAB: continue;
default:
this.state = State1.MINUS_ERR_ARG;
this.as = i;
}
break;
case Stat