@talkjs/core
Version:
Lets you connect to your TalkJS chat as a user and read, subscribe to, and update your chat data.
1,193 lines • 196 kB
JavaScript
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a2, b2) => {
for (var prop in b2 || (b2 = {}))
if (__hasOwnProp.call(b2, prop))
__defNormalProp(a2, prop, b2[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b2)) {
if (__propIsEnum.call(b2, prop))
__defNormalProp(a2, prop, b2[prop]);
}
return a2;
};
var __spreadProps = (a2, b2) => __defProps(a2, __getOwnPropDescs(b2));
var __objRest = (source, exclude) => {
var target = {};
for (var prop in source)
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
target[prop] = source[prop];
if (source != null && __getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(source)) {
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
target[prop] = source[prop];
}
return target;
};
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e2) {
reject(e2);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e2) {
reject(e2);
}
};
var step = (x2) => x2.done ? resolve(x2.value) : Promise.resolve(x2.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
var _a;
function e(e2, s2) {
if (s2.ok) return s2.value.data;
if ("SESSION_DESTROYED" === s2.value) throw new Error(`${e2} failed because the session was destroyed`);
if ("server" === s2.where) throw new Error(t(e2, s2.value));
throw "unreachable";
}
function t(e2, t2) {
let s2;
return s2 = Array.isArray(t2.reasons) ? t2.reasons.join() : JSON.stringify(t2.reasons), `${e2} failed, got status ${t2.status} ${t2.errorCode}, reasons: ${s2}`;
}
function s(e2, t2) {
if (e2.length !== t2.length) return false;
for (let s2 = 0; s2 < e2.length; s2++) if ("*" !== t2[s2] && e2[s2] !== t2[s2]) return false;
return true;
}
function n(e2) {
return e2 <= 0 ? Promise.resolve() : new Promise((t2) => setTimeout(t2, e2));
}
function r(e2, t2) {
return e2 * (1 - t2 + 2 * Math.random() * t2);
}
const i = () => true;
function a(_0, _1, _2) {
return __async(this, arguments, function* (e2, t2, { initialDelay: s2, maxDelay: o2, log: u2, shouldRetry: c2 = i }) {
return t2().catch((i2) => __async(this, null, function* () {
if (0 === e2) throw i2;
if (!(yield c2(i2))) throw i2;
const l2 = 1e3 * s2 * 1.2, h2 = r(o2 ? Math.min(1e3 * o2, l2) : l2, 0.05);
return n(h2).then(() => a(e2 - 1, t2, { initialDelay: h2 / 1e3, maxDelay: o2, log: u2, shouldRetry: c2 }));
}));
});
}
function o() {
const e2 = {}, t2 = new Promise(function(t3, s2) {
e2.resolve = t3, e2.reject = s2;
});
return e2.promise = t2, e2;
}
class u {
constructor(e2, t2, s2) {
this.layer = e2, this.states = t2, this.transitions = s2, this._state = t2[0];
}
get state() {
return this._state;
}
transition(e2) {
const t2 = this.transitions[e2];
if (!t2) return;
if (!this.canTransition(e2)) return;
const s2 = this.state;
this._state = t2.to, t2.afterTransition({ from: s2, to: this.state });
}
canTransition(e2) {
const t2 = this.transitions[e2];
return !!t2 && ("ANY" === t2.from || t2.from.includes(this.state));
}
}
function c(e2) {
return { ok: true, value: e2 };
}
function l(e2) {
return { ok: false, where: "client", value: e2 };
}
function h(e2) {
return { ok: false, where: "server", value: e2 };
}
function d() {
const e2 = {}, t2 = new Promise((t3) => {
e2.ok = (e3) => __async(this, null, function* () {
return t3(c(e3));
}), e2.clientErr = (e3) => t3(l(e3)), e2.serverErr = (e3) => t3(h(e3)), e2.resolve = (e3) => t3(e3);
});
return e2.promise = t2, e2;
}
let p = null;
function f({ WebSocket: e2 }) {
p = e2;
}
class m {
constructor(e2, t2) {
this.realtimeUrl = e2, this.handlers = t2, this.socket = null, this.stateMachine = new u("ReconnectingSocket", ["STOPPED", "CONNECTING", "READY", "DISCONNECTED", "TERMINATED"], { startWs: { from: ["STOPPED", "DISCONNECTED"], to: "CONNECTING", afterTransition: () => {
const e3 = new (function() {
if (p) return p;
if (globalThis.WebSocket) return globalThis.WebSocket;
throw new Error("Missing WebSocket implementation");
}())(this.realtimeUrl + "&talkjs-time=" + Date.now());
this.socket = e3, e3.addEventListener("open", () => {
this.socket === e3 && this.stateMachine.transition("onOpen");
}), e3.addEventListener("close", () => {
this.socket === e3 && this.stateMachine.transition("onClose");
}), e3.addEventListener("message", (t3) => {
this.socket === e3 && this.handlers.onMessage(t3);
});
} }, onOpen: { from: ["CONNECTING"], to: "READY", afterTransition: () => {
this.handlers.onOpen();
} }, onClose: { from: ["CONNECTING", "READY"], to: "DISCONNECTED", afterTransition: (_0) => __async(this, [_0], function* ({ from: e3 }) {
"READY" === e3 && this.handlers.onClose(), this.socket = null;
const t3 = r(1e4, 0.5);
setTimeout(() => {
"DISCONNECTED" === this.stateMachine.state && this.stateMachine.transition("startWs");
}, t3);
}) }, stopWs: { from: ["CONNECTING", "DISCONNECTED", "READY"], to: "STOPPED", afterTransition: ({ from: e3 }) => {
"READY" === e3 && this.handlers.onClose();
const t3 = this.socket;
this.socket = null, t3 == null ? void 0 : t3.close(1e3);
} }, destroy: { from: "ANY", to: "TERMINATED", afterTransition: () => {
const e3 = this.socket;
this.socket = null, e3 == null ? void 0 : e3.close(1e3);
} } });
}
stopWs() {
this.stateMachine.transition("stopWs");
}
startWs() {
this.stateMachine.transition("startWs");
}
send(e2) {
return "READY" === this.stateMachine.state ? (this.socket.send(e2), c(void 0)) : l("SOCKET_NOT_READY");
}
terminate() {
const e2 = this.socket;
this.stateMachine.canTransition("onClose") && this.stateMachine.transition("onClose"), e2 && ("terminate" in e2 ? e2.terminate() : e2.close(1e3));
}
destroy() {
this.stateMachine.transition("destroy");
}
}
class g {
constructor(e2, t2) {
this.handlers = t2, this.socket = new m(e2, { onOpen: () => this.handlers.onOpen(), onClose: () => this.handlers.onClose(), onMessage: (e3) => this.onWebSocketMessage(e3) });
}
call(e2, t2, s2, n2) {
const r2 = `/${s2.map((e3) => encodeURIComponent(e3)).join("/")}`, i2 = JSON.stringify([e2, t2, r2, n2]);
return this.socket.send(i2);
}
stopWs() {
this.socket.stopWs();
}
startWs() {
this.socket.startWs();
}
destroy() {
this.socket.destroy();
}
terminate() {
this.socket.terminate();
}
onWebSocketMessage(e2) {
if ("Auth token expired" !== e2.data) try {
const t2 = JSON.parse(e2.data);
if ("PUBLISH" === t2[1]) {
const e3 = t2[0], s2 = JSON.stringify([e3, "ACK"]);
this.socket.send(s2);
const n2 = t2.slice(2), r2 = [];
n2.forEach((e4) => {
"session.expired" === e4.type ? this.handlers.onAuthExpired() : "upstream.restarting" === e4.type ? this.handlers.onUpstreamRestarting() : r2.push(e4);
}), r2.length > 0 && this.handlers.onPublish(e3, r2);
} else {
const e3 = t2[0], s2 = t2[1], n2 = t2[2];
this.handlers.onResponse(e3, s2, n2);
}
} catch (e3) {
}
else this.handlers.onAuthExpired();
}
}
class v {
constructor(e2) {
this.delayMs = e2, this.timeout = void 0;
}
schedule(e2) {
this.stop(), this.timeout = setTimeout(() => {
void 0 !== this.timeout && (this.stop(), e2());
}, this.delayMs);
}
stop() {
void 0 !== this.timeout && (clearTimeout(this.timeout), this.timeout = void 0);
}
}
class w {
constructor() {
this.i = -1;
}
next() {
return this.i++, this.i;
}
reset() {
this.i = -1;
}
}
class b {
constructor(e2, t2) {
this.handlers = t2, this.seqCounter = new w(), this.responseHandlers = {}, this.heartbeats = new y(this), this.socket = new g(e2, { onUpstreamRestarting: () => {
this.heartbeats.serverActive(), this.handlers.onUpstreamRestarting();
}, onOpen: () => {
this.heartbeats.clientActive(), this.heartbeats.serverActive(), this.handlers.onReady();
}, onClose: () => {
this.heartbeats.stop(), Object.values(this.responseHandlers).forEach((e3) => {
e3.clientErr("WEBSOCKET_DISCONNECTED");
}), this.responseHandlers = {}, this.seqCounter.reset(), this.handlers.onNotReady();
}, onResponse: (e3, t3, s2) => {
this.heartbeats.serverActive(), this.onResponse(e3, t3, s2);
}, onPublish: (e3, t3) => {
this.heartbeats.serverActive(), this.handlers.onPublish(e3, t3), this.heartbeats.clientActive();
}, onAuthExpired: () => {
this.heartbeats.serverActive(), this.handlers.onAuthExpired();
} });
}
call(e2, t2, s2) {
const n2 = this.seqCounter.next(), r2 = d();
this.responseHandlers[n2] = r2;
const i2 = this.socket.call(n2, e2, t2, s2);
return i2.ok || r2.resolve(i2), this.heartbeats.clientActive(), r2.promise;
}
onResponse(e2, t2, s2) {
return __async(this, null, function* () {
const n2 = this.responseHandlers[e2];
n2 && (200 === t2 ? n2.ok({ status: t2, data: s2 }) : n2.serverErr({ status: t2, errorCode: s2.errorCode, reasons: s2.reasons }), delete this.responseHandlers[e2]);
});
}
stopWs() {
this.socket.stopWs();
}
startWs() {
this.socket.startWs();
}
destroy() {
this.heartbeats.stop(), Object.values(this.responseHandlers).forEach((e2) => {
e2.clientErr("WEBSOCKET_DISCONNECTED");
}), this.responseHandlers = {}, this.socket.destroy();
}
terminate() {
this.socket.terminate();
}
}
class y {
constructor(e2) {
this.connection = e2, this.clientInactivityTimer = new v(25e3), this.serverInactivityTimer = new v(1e4), this.serverTimeoutTimer = new v(5e3);
}
clientActive() {
this.clientInactivityTimer.schedule(() => {
this.sendHeartbeat();
});
}
serverActive() {
this.serverTimeoutTimer.stop(), this.serverInactivityTimer.schedule(() => {
this.sendHeartbeat(), this.serverTimeoutTimer.schedule(() => {
this.connection.terminate();
});
});
}
stop() {
this.clientInactivityTimer.stop(), this.serverInactivityTimer.stop(), this.serverTimeoutTimer.stop();
}
sendHeartbeat() {
this.connection.call("GET", ["ping"], {}).catch(() => {
});
}
}
class C {
constructor(e2, t2, s2) {
this.authProvider = t2, this.handlers = s2, this.stateMachine = new u("AuthenticatedConnection", ["WAITING_FOR_WS", "LOGGING_IN", "RENEWING_SESSION", "READY", "TERMINATED"], { logIn: { from: ["WAITING_FOR_WS"], to: "LOGGING_IN", afterTransition: () => __async(this, null, function* () {
yield this.renewSession();
}) }, logInFailed: { from: ["LOGGING_IN"], to: "LOGGING_IN", afterTransition: () => __async(this, null, function* () {
this.authProvider.refreshToken(), yield this.renewSession();
}) }, scheduledReauth: { from: ["READY"], to: "RENEWING_SESSION", afterTransition: () => __async(this, null, function* () {
yield this.renewSession();
}) }, scheduledReauthFailed: { from: ["RENEWING_SESSION"], to: "RENEWING_SESSION", afterTransition: () => __async(this, null, function* () {
this.authProvider.refreshToken(), yield this.renewSession();
}) }, authenticated: { from: ["LOGGING_IN", "RENEWING_SESSION"], to: "READY", afterTransition: ({ from: e3 }) => {
"LOGGING_IN" === e3 && this.handlers.onReady();
} }, authExpired: { from: ["READY", "RENEWING_SESSION"], to: "LOGGING_IN", afterTransition: () => __async(this, null, function* () {
this.handlers.onNotReady(), this.authProvider.refreshToken(), yield this.renewSession();
}) }, wsDisconnected: { from: ["READY", "LOGGING_IN", "RENEWING_SESSION"], to: "WAITING_FOR_WS", afterTransition: ({ from: e3 }) => {
"READY" !== e3 && "RENEWING_SESSION" !== e3 || this.handlers.onNotReady(), this.authProvider.clearScheduledRefresh();
} }, destroy: { from: "ANY", to: "TERMINATED", afterTransition: () => {
this.authProvider.clearScheduledRefresh(), this.connection.destroy();
} } }), this.connection = new b(e2, { onUpstreamRestarting: () => this.handlers.onUpstreamRestarting(), onReady: () => this.stateMachine.transition("logIn"), onNotReady: () => {
this.stateMachine.transition("wsDisconnected");
}, onAuthExpired: () => {
this.stateMachine.transition("authExpired");
}, onPublish: (e3, t3) => {
this.handlers.onPublish(e3, t3);
} }), t2.onTokenChanged(() => {
"READY" === this.stateMachine.state && this.stateMachine.transition("scheduledReauth");
});
}
call(e2, t2, s2) {
const n2 = this.connection.call(e2, t2, s2);
return n2.then((e3) => {
e3.ok || "server" !== e3.where || 401 !== e3.value.status || "READY" !== this.stateMachine.state && "RENEWING_SESSION" !== this.stateMachine.state || this.stateMachine.transition("authExpired");
}), n2;
}
stopWs() {
this.connection.stopWs();
}
startWs() {
this.connection.startWs();
}
destroy() {
this.stateMachine.transition("destroy");
}
renewSession() {
return __async(this, null, function* () {
const e2 = yield this.authProvider.getToken(), s2 = yield this.connection.call("POST", ["session", "renew"], { token: e2 });
if (!s2.ok && "client" === s2.where) return;
const n2 = s2.value;
if (n2.status, 200 === n2.status) {
const t2 = n2.data.expiresInSeconds;
return void (null !== t2 && t2 < 120 ? (console.warn(`[TalkJS] Authenticated with a token that expires in ${t2}s. Treating it as already expired and refreshing. Newly generated tokens should last at least 10 minutes.`), "LOGGING_IN" === this.stateMachine.state ? this.stateMachine.transition("logInFailed") : "RENEWING_SESSION" === this.stateMachine.state && this.stateMachine.transition("scheduledReauthFailed")) : (this.authProvider.scheduleRefresh(t2), this.authProvider.emitTokenAccepted(e2), this.stateMachine.canTransition("authenticated") && this.stateMachine.transition("authenticated")));
}
if (401 === n2.status) return void ("LOGGING_IN" === this.stateMachine.state ? this.stateMachine.transition("logInFailed") : "RENEWING_SESSION" === this.stateMachine.state && this.stateMachine.transition("scheduledReauthFailed"));
if (400 === n2.status) return void this.authProvider.emitTokenRefreshFailed(t("Authentication", n2));
if (402 === n2.status) return void this.authProvider.emitTokenRefreshFailed(t("Authentication", n2));
const r2 = 5e3 * Math.random() + 5e3;
setTimeout(() => {
this.call("POST", ["session", "renew"], { token: e2 }).catch(() => {
});
}, r2);
});
}
}
class A {
constructor(e2, t2, s2) {
this.handlers = s2, this.stateMachine = new u("StopStartConnection", ["STOPPED", "WAITING_FOR_WS", "READY", "TERMINATED"], { unexpectedDisconnect: { from: ["READY"], to: "WAITING_FOR_WS", afterTransition: () => {
this.inactivityTimer.stop(), this.handlers.onNotReady();
} }, stop: { from: ["WAITING_FOR_WS", "READY"], to: "STOPPED", afterTransition: () => {
this.connection.stopWs(), this.inactivityTimer.stop(), this.handlers.onNotReady();
} }, start: { from: ["STOPPED"], to: "WAITING_FOR_WS", afterTransition: () => {
this.connection.startWs();
} }, ready: { from: ["WAITING_FOR_WS"], to: "READY", afterTransition: () => {
this.pendingCalls = 0, this.activeSubscriptions = 0, this.inactivityTimer.schedule(() => {
this.stateMachine.transition("stop");
}), this.handlers.onReady();
} }, destroy: { from: "ANY", to: "TERMINATED", afterTransition: () => {
this.inactivityTimer.stop(), this.connection.destroy();
} } }), this.pendingCalls = 0, this.activeSubscriptions = 0, this.inactivityTimer = new v(3e3), this.connection = new C(e2, t2, { onUpstreamRestarting: () => {
this.handlers.onUpstreamRestarting();
}, onReady: () => {
this.stateMachine.transition("ready");
}, onNotReady: () => {
"READY" === this.stateMachine.state && this.stateMachine.transition("unexpectedDisconnect");
}, onPublish: (e3, t3) => {
this.handlers.onPublish(e3, t3);
} });
}
get inactive() {
return 0 === this.pendingCalls && 0 === this.activeSubscriptions;
}
ensureStarted() {
this.stateMachine.canTransition("start") && this.stateMachine.transition("start");
}
call(e2, t2, s2) {
return __async(this, null, function* () {
this.inactivityTimer.stop(), this.pendingCalls++;
const n2 = yield this.connection.call(e2, t2, s2);
return this.pendingCalls--, "SUBSCRIBE" === e2 && n2.ok ? this.activeSubscriptions++ : "UNSUBSCRIBE" === e2 && n2.ok && this.activeSubscriptions--, this.inactive && this.inactivityTimer.schedule(() => {
this.stateMachine.transition("stop");
}), n2;
});
}
destroy() {
this.stateMachine.transition("destroy");
}
isConnected() {
return "READY" === this.stateMachine.state;
}
}
class E {
constructor(e2, t2, s2) {
this.handlers = s2, this.stateMachine = new u("QueuedConnection", ["NOT_READY", "PROCESSING_QUEUE", "READY", "TERMINATED"], { processQueue: { from: ["NOT_READY"], to: "PROCESSING_QUEUE", afterTransition: () => {
this.sendQueuedCalls();
} }, ready: { from: ["PROCESSING_QUEUE"], to: "READY", afterTransition: () => {
this.handlers.onReady();
} }, notReady: { from: ["PROCESSING_QUEUE", "READY"], to: "NOT_READY", afterTransition: () => {
Object.values(this.subscribeQueue).forEach((e3) => e3.deferred.ok({ status: 200, data: {} })), this.subscribeQueue = {}, this.handlers.onSubscriptionsLost();
} }, destroy: { from: "ANY", to: "TERMINATED", afterTransition: () => {
var _a2;
for (; this.callQueue.length; ) {
const e3 = (_a2 = this.callQueue.shift()) == null ? void 0 : _a2.deferred;
e3 == null ? void 0 : e3.clientErr("SESSION_DESTROYED");
}
this.connection.destroy();
} } }), this.subscribeQueue = {}, this.callQueue = [], this.connection = new A(e2, t2, { onUpstreamRestarting: () => {
this.handlers.onUpstreamRestarting();
}, onReady: () => {
this.stateMachine.transition("processQueue");
}, onNotReady: () => {
this.stateMachine.transition("notReady");
}, onPublish: (e3, t3) => {
this.handlers.onPublish(e3, t3);
} });
}
call(e2, t2, s2) {
return "READY" === this.stateMachine.state ? this.connection.call(e2, t2, s2) : ("NOT_READY" === this.stateMachine.state && this.connection.ensureStarted(), "SUBSCRIBE" === e2 || "UNSUBSCRIBE" === e2 ? this._subscribe(e2, t2, s2) : this._call(e2, t2, s2));
}
_subscribe(e2, t2, s2) {
const n2 = t2.join("/"), r2 = this.subscribeQueue[n2];
if (r2 && r2.method === e2) return r2.deferred.promise;
r2 && r2.method !== e2 && (r2.deferred.ok({ status: 200, data: {} }), delete this.subscribeQueue[n2]);
const i2 = { deferred: d(), method: e2, path: t2, data: s2 };
return this.subscribeQueue[n2] = i2, i2.deferred.promise;
}
_call(e2, t2, s2) {
const n2 = { deferred: d(), method: e2, path: t2, data: s2 };
return this.callQueue.push(n2), n2.deferred.promise;
}
dequeue() {
for (const e2 in this.subscribeQueue) {
const t2 = this.subscribeQueue[e2];
return delete this.subscribeQueue[e2], t2;
}
return this.callQueue.shift();
}
destroy() {
this.stateMachine.transition("destroy");
}
sendQueuedCalls() {
return __async(this, null, function* () {
let e2 = 0;
for (; "PROCESSING_QUEUE" === this.stateMachine.state; ) {
e2++;
const t2 = this.dequeue();
if (!t2) return void this.stateMachine.transition("ready");
this.connection.call(t2.method, t2.path, t2.data).then((e3) => {
t2.deferred.resolve(e3);
}), e2 > 50 && (yield new Promise((e3) => setTimeout(e3, 100)));
}
});
}
isConnected() {
return "READY" === this.stateMachine.state || "PROCESSING_QUEUE" === this.stateMachine.state;
}
}
const k = "undefined" != typeof window ? (_a = window.queueMicrotask) != null ? _a : setTimeout : setTimeout;
class x {
constructor(e2, t2) {
this.clearPendingBatch = e2, this.sendCalls = t2, this.sent = false, k(() => this.send());
}
send() {
this.sent || (this.sent = true, this.clearPendingBatch(), this.sendCalls());
}
destroy() {
this.sent = true;
}
}
class T extends x {
constructor(e2, t2) {
super(t2, () => {
this.sendSubscribe(), this.sendGet();
}), this.connection = e2, this.getCalls = [], this.subscribeCalls = [];
}
canPush(e2, t2) {
return T.isCorrectBatchTypeFor(e2, t2);
}
static isCorrectBatchTypeFor(e2, t2) {
return s(t2, ["users", "*"]) && ("GET" === e2 || "SUBSCRIBE" === e2);
}
push(e2, t2, s2) {
const n2 = t2[1], r2 = d();
return "GET" === e2 ? this.getCalls.push({ userId: n2, deferred: r2 }) : this.subscribeCalls.push({ userId: n2, deferred: r2 }), 1e3 !== this.getCalls.length && 1e3 !== this.subscribeCalls.length || this.send(), r2.promise;
}
sendGet() {
return __async(this, null, function* () {
if (0 === this.getCalls.length) return;
const e2 = [...new Set(this.getCalls.map((e3) => e3.userId))], t2 = yield this.connection.call("GET", ["users"], { ids: e2, includePrivateFields: false });
if (t2.ok) for (const e3 of this.getCalls) {
const s2 = t2.value.data[e3.userId];
s2 ? e3.deferred.ok({ status: 200, data: s2 }) : e3.deferred.serverErr({ status: 404, errorCode: "NOT_FOUND", reasons: ["No user with that ID exists"] });
}
else this.getCalls.forEach((e3) => e3.deferred.resolve(t2));
});
}
sendSubscribe() {
if (0 === this.subscribeCalls.length) return;
const e2 = [...new Set(this.subscribeCalls.map((e3) => e3.userId))];
this.connection.call("SUBSCRIBE", ["users"], { ids: e2 }).then((e3) => this.subscribeCalls.forEach((t2) => t2.deferred.resolve(e3)));
}
}
class S extends x {
constructor(e2, t2, s2) {
super(s2, () => this.sendMutate()), this.conversationId = e2, this.connection = t2, this.calls = [];
}
canPush(e2, t2) {
return !!S.isCorrectBatchTypeFor(e2, t2) && t2[1] === this.conversationId;
}
static isCorrectBatchTypeFor(e2, t2) {
return s(t2, ["conversations", "*", "participants", "*"]) && ("PUT" === e2 || "POST" === e2 || "PATCH" === e2);
}
push(e2, t2, s2) {
const n2 = t2[3], r2 = d();
return this.calls.push({ action: { id: n2, method: e2, params: s2 }, deferred: r2 }), 100 === this.calls.length && this.send(), r2.promise;
}
sendMutate() {
return __async(this, null, function* () {
const e2 = this.calls.map((e3) => e3.action), t2 = yield this.connection.call("POST", ["conversations", this.conversationId, "participants"], { actions: e2 });
if (!t2.ok) return void this.calls.forEach((e3) => e3.deferred.resolve(t2));
const s2 = t2.value.data.responses;
for (let e3 = 0; e3 < s2.length; e3++) {
const t3 = this.calls[e3].deferred, n2 = s2[e3];
200 === n2.status ? t3.ok(__spreadProps(__spreadValues({}, n2), { data: {} })) : t3.serverErr(n2);
}
});
}
}
class I {
constructor(e2, t2, s2) {
this.pendingBatch = null, this.connection = new E(e2, t2, s2);
}
call(e2, t2, s2) {
return __async(this, null, function* () {
var _a2;
if ((_a2 = this.pendingBatch) == null ? void 0 : _a2.canPush(e2, t2)) return this.pendingBatch.push(e2, t2, s2);
this.pendingBatch && this.pendingBatch.send();
const n2 = this.createEmptyBatchFor(e2, t2);
return n2 ? (this.pendingBatch = n2, n2.push(e2, t2, s2)) : this.connection.call(e2, t2, s2);
});
}
destroy() {
var _a2;
this.connection.destroy(), (_a2 = this.pendingBatch) == null ? void 0 : _a2.destroy();
}
isConnected() {
return this.connection.isConnected();
}
createEmptyBatchFor(e2, t2) {
if (T.isCorrectBatchTypeFor(e2, t2)) return new T(this.connection, () => this.pendingBatch = null);
if (S.isCorrectBatchTypeFor(e2, t2)) {
const e3 = t2[1];
return new S(e3, this.connection, () => this.pendingBatch = null);
}
return null;
}
}
const D = { 200: "RESOLVE", 400: "RESOLVE", 401: "RETRY", 402: "RESOLVE", 403: "RESOLVE", 404: "RESOLVE", 405: "RESOLVE", 409: "RESOLVE", 429: "DELAY", 500: "DELAY" };
class M {
constructor(e2, t2, s2) {
this.throttler = new F(), this.alive = true, this.connection = new I(e2, t2, s2);
}
call(e2, t2, s2) {
return __async(this, null, function* () {
let n2 = 0;
for (; this.alive; ) {
const r2 = yield this.connection.call(e2, t2, s2);
if ((r2.ok || "client" !== r2.where || "SOCKET_NOT_READY" !== r2.value) && (r2.ok || "server" !== r2.where || 500 !== r2.value.status) || n2++, 10 === n2) return r2;
if (r2.ok || "client" !== r2.where) {
const e3 = r2.value, t3 = e3.status, s3 = D[t3];
if ("RESOLVE" === s3) return this.throttler.resetDelay(), r2;
if ("RETRY" === s3) continue;
if ("DELAY" === s3) {
yield this.throttler.wait();
continue;
}
return console.warn("[TalkJS] Unexpected status code", t3), e3;
}
if ("SESSION_DESTROYED" === r2.value) return l("SESSION_DESTROYED");
"WEBSOCKET_DISCONNECTED" !== r2.value && ("SOCKET_NOT_READY" !== r2.value ? r2.value : yield this.throttler.wait());
}
return l("SESSION_DESTROYED");
});
}
destroy() {
this.alive = false, this.connection.destroy();
}
isConnected() {
return this.connection.isConnected();
}
}
class F {
constructor() {
this.initialDelayMs = 200, this.exponentialFactor = 1.2, this.maxDelayMs = 3e4, this.currentDelayMs = this.initialDelayMs, this.lastCall = 0;
}
getCurrentDelay() {
return this.currentDelayMs;
}
wait() {
const e2 = (/* @__PURE__ */ new Date()).getTime(), t2 = r(this.currentDelayMs, 0.05), s2 = this.lastCall + t2, i2 = Math.max(0, s2 - e2);
return this.lastCall = e2 + i2, this.currentDelayMs = Math.min(t2 * this.exponentialFactor, this.maxDelayMs), n(i2);
}
resetDelay() {
this.currentDelayMs = this.initialDelayMs;
}
}
function B(e2) {
return e2.map((e3) => encodeURIComponent(e3)).join();
}
class R {
constructor() {
this.paths = {};
}
add(e2) {
this.paths[B(e2)] = e2;
}
delete(e2) {
delete this.paths[B(e2)];
}
has(e2) {
return Object.hasOwnProperty.call(this.paths, B(e2));
}
clear() {
this.paths = {};
}
forEach(e2) {
Object.values(this.paths).forEach((t2) => e2(t2));
}
}
class N {
constructor(e2, t2, s2) {
this.handlers = s2, this.targetSubscriptions = new R(), this.connection = new M(e2, t2, { onUpstreamRestarting: () => this.handlers.onUpstreamRestarting(), onSubscriptionsLost: () => {
this.targetSubscriptions.forEach((e3) => {
this.resubscribe(e3);
}), this.handlers.onResubscribeSent();
}, onReady: () => this.handlers.onReady(), onPublish: (e3, t3) => {
this.handlers.onPublish(e3, t3);
} });
}
call(e2, t2, s2) {
return this.connection.call(e2, t2, s2);
}
subscribe(e2) {
return __async(this, null, function* () {
return this.targetSubscriptions.add(e2), this.connection.call("SUBSCRIBE", e2, {});
});
}
unsubscribe(e2) {
return __async(this, null, function* () {
return this.targetSubscriptions.delete(e2), this.connection.call("UNSUBSCRIBE", e2, {});
});
}
resubscribe(e2) {
return __async(this, null, function* () {
const t2 = yield this.connection.call("SUBSCRIBE", e2, {});
t2.ok || this.handlers.onResubscribeError(e2, t2);
});
}
destroy() {
this.targetSubscriptions.clear(), this.connection.destroy();
}
isConnected() {
return this.connection.isConnected();
}
}
function P(e2, t2) {
return void 0 === t2 ? e2 : t2;
}
function _(e2, t2) {
if (void 0 === t2) return e2;
if (null === t2) return {};
const s2 = __spreadValues({}, e2);
for (const e3 in t2) {
const n2 = t2[e3];
null === n2 ? delete s2[e3] : s2[e3] = n2;
}
return s2;
}
function O(e2, t2) {
if (e2 === t2) return true;
if (!e2 || !t2) return false;
if ("object" != typeof e2 || "object" != typeof t2) return false;
if (e2.constructor !== t2.constructor) return false;
if (Array.isArray(e2) && Array.isArray(t2)) {
if (e2.length !== t2.length) return false;
for (let s2 = 0; s2 < e2.length; s2++) if (!O(e2[s2], t2[s2])) return false;
} else {
const s2 = Object.keys(e2);
if (s2.length !== Object.keys(t2).length) return false;
for (const n2 of s2) {
if (!Object.hasOwnProperty.call(t2, n2)) return false;
if (!O(e2[n2], t2[n2])) return false;
}
}
return true;
}
class U {
constructor() {
this.prev = Promise.resolve();
}
runExclusive(e2) {
return __async(this, null, function* () {
const t2 = this.prev.then(() => e2());
return this.prev = t2, t2;
});
}
}
class j {
constructor(e2) {
this.initialised = false, this.getPointer = void 0, this.pendingStates = [e2], e2.resultPromise.then(() => this.initialised = true);
}
get pendingPointer() {
if (0 !== this.pendingStates.length) return this.pendingStates[this.pendingStates.length - 1];
}
get mostRecentState() {
var _a2;
return (_a2 = this.pendingPointer) != null ? _a2 : this.getPointer;
}
canAppendState(e2) {
var _a2, _b;
const t2 = (_a2 = this.getPointer) == null ? void 0 : _a2.seq;
if (void 0 !== t2 && e2 <= t2) return false;
const s2 = (_b = this.pendingPointer) == null ? void 0 : _b.seq;
return !(void 0 !== s2 && e2 < s2);
}
set(e2) {
if (!this.canAppendState(e2.seq)) throw "Appending in the past";
this.pendingStates.push(e2);
}
mutate(e2, t2) {
if (!this.initialised) return;
if (!this.canAppendState(e2)) throw "Mutating in the past";
const s2 = this.mostRecentState.resultPromise.then((e3) => e3.ok ? t2(e3) : e3);
this.pendingStates.push({ seq: e2, resultPromise: s2 });
}
get(e2) {
if (void 0 !== this.getPointer && e2 < this.getPointer.seq) throw `Trying to load state ${e2} when we have previously loaded ${this.getPointer.seq}`;
for (; this.pendingStates.length > 0 && this.pendingStates[0].seq <= e2; ) this.getPointer = this.pendingStates.shift();
return this.getPointer;
}
}
class $ extends j {
constructor(e2, t2) {
super(e2), this.onTeardown = t2, this._error = null, this._lastGoodState = Promise.resolve(void 0);
}
get error() {
return this._error;
}
get lastGoodState() {
return this._lastGoodState;
}
mutate(e2, t2) {
super.mutate(e2, t2), this.registerNewState(this.mostRecentState.resultPromise);
}
set(e2) {
super.set(e2), this.registerNewState(this.mostRecentState.resultPromise);
}
registerNewState(e2) {
const t2 = this.lastGoodState;
this._lastGoodState = e2.then((e3) => e3.ok ? e3.value : t2), e2.then((e3) => {
e3.ok || this.setError(e3);
});
}
setError(e2) {
var _a2;
this._error || (this._error = e2, (_a2 = this.onTeardown) == null ? void 0 : _a2.call(this, e2), this.lastGoodState.then((e3) => {
void 0 !== e3 && this.teardownNested(e3);
}));
}
}
class W extends $ {
constructor(e2) {
super({ seq: 0, resultPromise: new Promise((e3) => setTimeout(e3)).then(() => this.fetchInitial(0)) }, e2), this.getDeepMutex = new U(), this.lastDeep = void 0;
}
refetchInitial(e2) {
return __async(this, null, function* () {
const t2 = this.mostRecentState.resultPromise, s2 = this.fetchInitial(e2), [n2, r2] = yield Promise.all([t2, s2]);
if (void 0 === n2 || !n2.ok) return r2;
if (!r2.ok) return r2;
return this.equal(n2.value, r2.value) ? n2 : r2;
});
}
refetch(e2) {
if (null !== this.error) return;
const t2 = { seq: e2, resultPromise: this.refetchInitial(e2) };
this.set(t2);
}
changedBetween(e2, t2) {
return __async(this, null, function* () {
if (e2 >= t2) return false;
const s2 = this.get(t2), n2 = yield s2.resultPromise;
if (!n2.ok) return false;
if (n2.value.lastChanged > e2) return true;
return yield this.anyChildChanged(e2, t2, n2.value);
});
}
getDeep(e2) {
return __async(this, null, function* () {
return this.getDeepMutex.runExclusive(() => __async(this, null, function* () {
var _a2;
if (null !== this.error) return this.error;
const t2 = (_a2 = this.lastDeep) == null ? void 0 : _a2.seq;
if (e2 === t2) return this.lastDeep.deep;
if (void 0 !== t2) {
if (e2 < t2) throw `Trying to load seq ${e2} when we have previously loaded seq ${t2}`;
if (!(yield this.changedBetween(t2, e2))) return this.lastDeep.seq = e2, this.lastDeep.deep;
}
const s2 = this.get(e2).resultPromise, n2 = s2.then((t3) => t3.ok ? this.loadNested(e2, t3.value) : t3);
this.lastDeep = { seq: e2, shallow: s2, deep: n2 };
const r2 = yield n2;
return r2.ok || this.setError(r2), r2;
}));
});
}
}
class q extends W {
constructor(e2, t2) {
super(t2), this.emitMutex = e2, this.unsubscribeTimer = new H(), this.referencedByOtherStores = 0, this.listeners = [], this.lastEmitSeq = void 0, this.lastEmitResult = void 0, e2.runExclusive(() => __async(this, null, function* () {
yield this.emit(0);
}));
}
registerInternalSubscription() {
this.referencedByOtherStores++;
let e2 = true;
return () => {
e2 && (e2 = false, this.referencedByOtherStores--, this.startUnsubscribeTimerIfOrphan());
};
}
get onlyUsedInternally() {
return 0 === this.listeners.length;
}
listen(e2) {
return this.unsubscribeTimer.stop(), this.listeners.push(e2), void 0 !== this.lastEmitResult && e2(this.lastEmitResult), () => {
this.listeners = this.listeners.filter((t2) => t2 !== e2), this.startUnsubscribeTimerIfOrphan();
};
}
startUnsubscribeTimerIfOrphan() {
0 === this.referencedByOtherStores && 0 === this.listeners.length && this.unsubscribeTimer.restart(() => {
this.setError(l("UNSUBSCRIBED"));
}, this.unsubscribeDebounceMs);
}
getLoadMoreSeq() {
var _a2;
const e2 = (_a2 = this.lastEmitSeq) != null ? _a2 : 0, t2 = this.mostRecentState.seq;
return Math.max(e2, t2) + 1e-6;
}
emit(e2) {
return __async(this, null, function* () {
var _a2;
if (this.onlyUsedInternally) return;
if (this.lastEmitSeq && this.lastEmitSeq >= e2) return;
if (false === ((_a2 = this.lastEmitResult) == null ? void 0 : _a2.ok)) return;
this.lastEmitSeq = e2;
const t2 = yield this.getDeep(e2);
t2 !== this.lastEmitResult && (this.lastEmitResult = t2, this.listeners.forEach((e3) => e3(t2)));
});
}
}
class H {
constructor() {
this.timerId = void 0;
}
restart(e2, t2) {
void 0 !== this.timerId && clearTimeout(this.timerId), this.timerId = setTimeout(() => e2(), t2);
}
stop() {
clearTimeout(this.timerId);
}
}
class G extends q {
constructor(e2, t2, s2, n2) {
super(s2, n2), this.userId = e2, this.realtimeClient = t2, this.unsubscribeDebounceMs = 1e4;
}
fetchInitial(e2) {
return __async(this, null, function* () {
const t2 = yield this.realtimeClient.call("GET", ["users", this.userId], { includePrivateFields: false }, { bypassCache: true });
return t2.ok ? c({ snapshot: this.realtimeClient.createUserSnapshot(t2.value.data), lastChanged: e2 }) : "server" === t2.where && 404 === t2.value.status ? c({ snapshot: null, lastChanged: e2 }) : t2;
});
}
equal(e2, t2) {
return O(e2.snapshot, t2.snapshot);
}
loadNested(e2, t2) {
return __async(this, null, function* () {
return c(t2);
});
}
userCreated(e2, t2) {
this.mutate(e2, (s2) => null !== s2.value.snapshot ? s2 : c({ snapshot: this.realtimeClient.createUserSnapshot(t2.state), lastChanged: e2 }));
}
userEdited(e2, t2) {
this.mutate(e2, (s2) => {
const n2 = s2.value.snapshot;
if (null === n2) return console.warn("[TalkJS] Received a 'used edited' event for a user that we thought didn't exist."), s2;
return c({ snapshot: { id: n2.id, name: P(n2.name, t2.diff.name), custom: _(n2.custom, t2.diff.custom), locale: P(n2.locale, t2.diff.locale), photoUrl: P(n2.photoUrl, t2.diff.photoUrl), role: P(n2.role, t2.diff.role), welcomeMessage: P(n2.welcomeMessage, t2.diff.welcomeMessage) }, lastChanged: e2 });
});
}
getFromCache() {
return __async(this, null, function* () {
const e2 = yield this.mostRecentState.resultPromise;
return e2.ok ? null === e2.value.snapshot ? h({ status: 404, errorCode: "USER_NOT_FOUND", reasons: ["That user does not exist yet"] }) : c({ status: 200, data: { id: e2.value.snapshot.id, name: e2.value.snapshot.name, custom: e2.value.snapshot.custom, locale: e2.value.snapshot.locale, photoUrl: e2.value.snapshot.photoUrl, role: e2.value.snapshot.role, welcomeMessage: e2.value.snapshot.welcomeMessage } }) : l("NOT_IN_CACHE");
});
}
teardownNested(e2) {
}
anyChildChanged(e2, t2, s2) {
return __async(this, null, function* () {
return false;
});
}
}
var L, z = {};
function J(e2, t2) {
const s2 = t2.lastIndex;
let n2;
const r2 = [];
for (; null !== (n2 = t2.exec(e2)); ) r2.push(n2);
return t2.lastIndex = s2, r2;
}
function Y(e2) {
const t2 = e2.replace(/%2F/g, "/").replace(/^.*?\/([^/]+?)(?:\?.*)?$/, "$1");
return decodeURIComponent(t2);
}
function Q(e2, t2) {
if (!e2() && !t2) {
t2 = e2.toString().replace(/^function\s*\(\)\s*\{\s*return\s*(.*);\s*\}\s*$/, "`$1`") + " was not true";
}
}
!function() {
if (L) return z;
function e2(e3) {
return String.fromCharCode(parseInt(e3.slice(1), 16));
}
function t2(e3) {
return `%${`00${e3.charCodeAt(0).toString(16)}`.slice(-2)}`;
}
L = 1, Object.defineProperty(z, "__esModule", { value: true }), z.encode = function(t3) {
return btoa(encodeURIComponent(t3).replace(/%[0-9A-F]{2}/g, e2));
}, z.decode = function(e3) {
return decodeURIComponent(Array.from(atob(e3), t2).join(""));
};
}(), ((e2) => {
function t2(e3) {
}
function s2(e3, t3) {
(function(e4, t4) {
switch (t4) {
case "undefined":
return void 0 === e4;
case String:
return "string" == typeof e4 || e4 instanceof String;
case Boolean:
return "boolean" == typeof e4 || e4 instanceof Boolean;
case Number:
return "number" == typeof e4 || e4 instanceof Number;
default:
return e4 instanceof t4;
}
})(e3, t3) || (t3.name, String(e3));
}
e2.defined = t2, e2.has = function(e3, t3) {
e3[t3];
}, e2.is = s2, e2.equals = function(e3, t3) {
}, e2.oneOf = function(e3, t3) {
t3.includes(e3) || JSON.stringify(t3);
}, e2.isArray = function(e3, t3) {
s2(e3, Array), e3 && e3.length > 0 && s2(e3[0], t3);
}, e2.optional = function(e3, t3) {
void 0 !== e3 && s2(e3, t3);
}, e2.falsy = function(e3) {
}, e2.never = function(e3) {
};
})(Q || (Q = {}));
const V = Q, Z = /^\/.*[^\\]\/[im]*$/;
function K(e2) {
if (!Z.test(e2)) return false;
return !X(e2).test("");
}
function X(e2) {
const t2 = e2.match(/^\/(.*[^\\])\/(.*)$/);
if (!t2) throw new Error(`Expected ${e2} to be a (non-empty) regex`);
let s2 = t2[2] || "";
return s2 = s2.replace(/[^im]/g, "") + "g", new RegExp(t2[1], s2);
}
class ee {
constructor({ mode: e2, allowedHostnames: t2, allowedPhoneNrs: s2, allowedMatches: n2, forbiddenMatches: r2, suppressLinks: i2, suppressEmailAddresses: a2, suppressPhoneNumbers: o2, replacement: u2 }) {
V.oneOf(e2, ["all", "otherOnly", "off"]), this.mode = e2, this.suppressLinks = false !== i2, this.suppressEmailAddresses = false !== a2, this.suppressPhoneNumbers = false !== o2, this.allowedHostnames = t2 || [], this.allowedPhoneNrs = (s2 || []).filter((e3) => e3).map((e3) => e3.replace(/[^0-9]/g, "")), this.allowedMatches = (n2 || []).filter(K).map((e3) => X(e3)), this.forbiddenMatches = (r2 || []).filter(K).map((e3) => X(e3)), V(() => this.allowedMatches.every((e3) => e3.flags.includes("g")), "All regexes in `suppressContactInfo.allowedMatches` must be global. Check `allowedMatches`!"), V(() => this.forbiddenMatches.every((e3) => e3.flags.includes("g")), "All regexes in `suppressContactInfo.forbiddenMatches` must be global. Check `forbiddenMatches`!"), u2 = u2 == null ? void 0 : u2.trim(), this.replacement = u2 && u2.length > 0 ? u2 : void 0;
}
shouldSuppress({ isContentBySender: e2 }) {
return "all" === this.mode || "otherOnly" === this.mode && !e2;
}
}
function te(e2, t2) {
const s2 = e2.map((e3) => function(e4, t3) {
if ("text" === e4.type) return function(e5, t4) {
const s3 = function(e6) {
var _a2, _b, _c, _d, _e2, _f, _g, _h, _i, _j, _k, _l;
let t5 = "";
return e6.t && (t5 = `(${e6.t("CONTACT_INFORMATION_HIDDEN")})`), { formattedLinks: (_a2 = e6.formattedLinks) != null ? _a2 : "plaintext", markup: (_b = e6.markup) != null ? _b : false, useFallbackMentions: (_c = e6.useFallbackMentions) != null ? _c : false, sameTabLinkRules: (_d = e6.sameTabLinkRules) != null ? _d : [], enableEmojiImageFallback: (_e2 = e6.enableEmojiImageFallback) != null ? _e2 : false, highlight: (_f = e6.highlight) != null ? _f : [], contactInfo: (_g = e6.contactInfo) != null ? _g : false, suppression: (_h = e6.suppression) != null ? _h : new ee({ mode: "off" }), contactInfoHiddenText: (_k = (_j = e6.contactInfoHiddenText) != null ? _j : (_i = e6.suppression) == null ? void 0 : _i.replacement) != null ? _k : t5, customEmojiUrls: (_l = e6.customEmojiUrls) != null ? _l : {} };
}(t4);
return se(e5, s3);
}(e4.children, t3);
if ("file" === e4.type && "video" === e4.subtype) return `🎥 ${Y(e4.url)}`;
if ("file" === e4.type && "image" === e4.subtype) return `📷 ${Y(e4.url)}`;
if ("file" === e4.type && "audio" === e4.subtype) return `🎧 ${Y(e4.url)}`;
if ("file" === e4.type && "voice" === e4.subtype) {
const t4 = e4.duration;
if (void 0 === t4) return "🎙️";
return `🎙️ (${Math.floor(t4 / 60)}:${Math.floor(t4 % 60).toString().padStart(2, "0")})`;
}
if ("file" === e4.type) return e4.subtype, `📎 ${Y(e4.url)}`;
if ("location" === e4.type) return "📍";
return "";
}(e3, t2));
return s2.join("\n\n");
}
function se(e2, t2) {
return e2.flatMap((e3) => {
if ("string" == typeof e3) return e3;
switch (e3.type) {
case "blockquote":
case "bold":
case "italic":
case "strikethrough":
case "link":
case "actionlink":
case "actionLink":
case "actionbutton":
case "actionButton":
return se(e3.children, t2);
case "bulletlist":
case "bulletList":
return "\n" + se(e3.children, t2);
case "bulletpoint":
case "bulletPoint":
return "- " + se(e3.children, t2) + "\n";
case "autolink":
case "autoLink":
case "codeblock":
case "codeBlock":
case "codespan":
case "codeSpan":
case "emoji":
case "customemoji":
case "customEmoji":
return e3.text;
case "suppressed":
return t2.contactInfoHiddenText;
case "mention":
return `@${e3.text}`;
}
}).join("");
}
class ne extends W {
constructor(e2, t2, s2) {
super(), this.conversationId = e2, this.message = t2, this.realtimeClient = s2;
}
get messageId() {
return "string" == typeof this.message ? this.message : this.message.id;
}
fetchInitial(e2) {
return __async(this, null, function* () {
let t2;
if ("object" == typeof this.message) t2 = this.message;
else {
const e3 = yield this.realtimeClient.call("GET", ["me", "conversations", this.conversationId, "messages", this.message], {}, { bypassCache: true });
if (!e3.ok) return e3;
t2 = e3.value.data;
}
return c({ lastChanged: e2, sender: null === t2.senderId ? null : this.realtimeClient.internalSubscribe(["users", t2.senderId]), data: { id: t2.id, type: t2.type, custom: t2.custom, createdAt: t2.createdAt, editedAt: t2.editedAt, referencedMessageId: t2.referencedMessageId, origin: t2.origin, plaintext: te(t2.content, {}), content: t2.content } });
});
}
refetch(e2) {
throw "Do not call refetch on message data stores, it can return outdated data. Destroy and remake them instead";
}
equal(e2, t2) {
return O(e2.data, t2.data);
}
teardownNested(e2) {
var _a2;
(_a2 = e2.sender) == null ? void 0 : _a2.unsubscribe();
}
anyChildChanged(e2, t2, s2) {
return __async(this, null, function* () {
var _a2;
const n2 = (_a2 = s2.sender) == null ? void 0 : _a2.store;
return true === (yield n2 == null ? void 0 : n2.changedBetween(e2, t2));
});
}
loadNested(e2, t2) {
return __async(this, null, function* () {
var _a2, _b, _c;
const s2 = yield (_b = (_a2 = t2.sender) == null ? void 0 : _a2.store) == null ? void 0 : _b.getDeep(e2);
if (false === (s2 == null ? void 0 : s2.ok)) return s2;
if (null === t2.data) return c({ snapshot: null });
const n2 = s2 == null ? void 0 : s2.value;
return c({ snapshot: { sender: (_c = n2 == null ? void 0 : n2.snapshot) != null ? _c : null, id: t2.data.id, type: t2.data.type, custom: t2.data.custom, createdAt: t2.data.createdAt, editedAt: t2.data.editedAt, origin: t2.data.origin, plaintext: te(t2.data.content, {}), content: t2.data.content, referencedMessageId: t2.data.referencedMessageId } });
});
}
messageEdited(e2, t2) {
this.mutate(e2, (s2) => {
if (null === s2.value.data) return s2;
return c({ lastChanged: e2, sender: s2.value.sender, data: { id: s2.value.data.id, type: s2.value.data.type, createdAt: s2.value.data.createdAt, origin: s2.value.data.origin, referencedMessageId: s2.value.data.referencedMessageId, editedAt: P(s2.value.data.editedAt, t2.diff.editedAt), custom: _(s2.value.data.custom, t2.diff.custom), content: P(s2.value.data.content, t2.diff.content) } });
});
}
messageDeleted(e2, t2) {
this.mutate(e2, (s2) => null === s2.value.data ? s2 : this.messageId === t2.messageId ? (this.teardownNested(s2.value), c({ lastChanged: e2, sender: null, data: null })) : s2.value.data.referencedMessageId === t2.messageId ? c({ lastChanged: e2, sender: s2.value.sender, data: { id: s2.value.data.id, type: s2.value.data.type, createdAt: s2.value.data.createdAt, origin: s2.value.data.origin, referencedMessageId: null, editedAt: s2.value.data.editedAt, custom: s2.value.data.custom, content: s2.value.data.content } }) : s2);
}
getFromCache() {
return __async(this, null, function* () {
var _b;
const e2 = yield this.mostRecentState.resultPromise;
if (!e2.ok) return l("NOT_IN_CACHE");
if (null === e2.value.data) {
return h({ status: 404, errorCode: "MESSAGE_NOT_FOUND", reasons: ["No message with that ID exists"] });
}
const _a2 = e2.value, { sender: t2 } = _a2, s2 = __objRest(_a2, ["sender"]);
return c({ status: 200, data: __spreadProps(__spreadValues({}, s2.data), { senderId: (_b = t2 == null ? void 0 : t2.store.userId) != null ? _b : null }) });
});
}
}
class re extends W {
constructor(e2, t2, s2) {
super(), this.createdAt = e2, this.dataStore = t2, this.referencedDataStore = s2;
}
get messageId() {
return this.dataStore.messageId;
}
fetchInitial(e2) {
return __async(this, null, function* () {
return c({ lastChanged: e2, dataStore: this.dataStore, referencedDataStore: this.referencedDataStore });
});
}
refetch(e2) {
throw "Do not call refetch on message stores, it can return outdated data. Destroy and remake them instead";
}
equal(e2, t2) {
return true;
}
teardownNested(e2) {
}
anyChildChanged(_0, _1, _2) {
return __async(this, arguments, function* (e2, t2, { dataStore: s2, referencedDataStore: n2 }) {
if (true === (yield s2.changedBetween(e2, t2))) return true;
return true === (yield n2 == null ? void 0 : n2.changedBetween(e2, t2));
});
}
loadNested(e2, t2) {
return __async(this, null, function* () {
var _a2, _b, _c;
const s2 = yield t2.dataStore.getDeep(e2);
if (!s2.ok) return s2;
const n2 = s2.value;
if (null === n2.snapshot) return c({ snapshot: null });
const r2 = yield (_a2 = t2.referencedDataStore) == null ? void 0 : _a2.getDeep(e2);
if (r2 && !r2.ok) return r2;
const i2 = (_b = r2 == null ? void 0 : r2.value) != null ? _b : null, a2 = (_c = i2 == null ? void 0 : i2.snapshot) != null ? _c : null;
return c({ snapshot: { id: n2.snapshot.id, type: n2.snapshot.type, sender: n2.snapshot.sender, custom: n2.snapshot.custom, createdAt: n2.snapshot.createdAt, editedAt: n2.snapshot.editedAt, referencedMessage: a2, origin: n2.snapshot.origin, plaintext: n2.snapshot.plaintext, content: n2.snapshot.content } });
});
}
}
class ie extends q {
constructor(e2, t2, s2, n2) {
super(s2, n2), this.conversationId = e2, this.realtimeClient = t2, this.unsub