@paramms/chat-widget 1.6.2 → 1.7.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.
@@ -0,0 +1,1470 @@
1
+ var ve = Object.defineProperty;
2
+ var Ue = (s, e, t) => e in s ? ve(s, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : s[e] = t;
3
+ var a = (s, e, t) => Ue(s, typeof e != "symbol" ? e + "" : e, t);
4
+ function de(s, e) {
5
+ var d;
6
+ const t = s.trim().replace(/\/+$/, ""), i = (d = t.match(/^(https|http|wss|ws):\/\//)) == null ? void 0 : d[1], n = i ? i === "https" || i === "wss" : !0, r = (i ? t.slice(i.length + 3) : t).replace(/\/ws$/, ""), o = e ? e.trim().replace(/\/+$/, "") : `${n ? "https" : "http"}://${r}`;
7
+ return { wsUrl: `${n ? "wss" : "ws"}://${r}/ws`, httpBase: o };
8
+ }
9
+ function Se(s) {
10
+ return de(s).httpBase;
11
+ }
12
+ function be(s, e, t, i) {
13
+ const n = `beforeSeq=${t}&limit=${i}`;
14
+ return [
15
+ `${s}/conversations/${e}/messages?${n}`,
16
+ `${s}/conversations/${e}/history?${n}`
17
+ ];
18
+ }
19
+ async function ae(s, e, t, i, n = 20) {
20
+ let r, o = !1;
21
+ for (const l of be(s, e, i, n))
22
+ try {
23
+ const d = await fetch(l, { headers: { authorization: `Bearer ${t}` } });
24
+ if (o = !0, !d.ok) continue;
25
+ const v = await d.json();
26
+ return { messages: v.messages ?? [], hasMore: v.hasMore ?? !1 };
27
+ } catch (d) {
28
+ r = d;
29
+ }
30
+ return o ? console.error(`[chat-widget] history request to ${s} was rejected for conversation ${e}.`) : console.error(
31
+ `[chat-widget] could not load history from ${s} — the request never reached the server. This is almost always CORS: add this site's origin to the chatroom's allowed origins (dashboard → chatroom → allowed origins) or to the server's CORS_ORIGINS.`,
32
+ r
33
+ ), null;
34
+ }
35
+ async function bt(s, e, t, i, n, r) {
36
+ const o = r ? r.replace(/\/+$/, "") : Se(s), l = await ae(o, t, e, Number.MAX_SAFE_INTEGER);
37
+ if (!l || (l.messages.length ? (i.apply({ type: "sync", conversationId: t, messages: l.messages }), i.apply({ type: "history", conversationId: t, messages: [], hasMore: l.hasMore }), n.render(i)) : i.apply({ type: "history", conversationId: t, messages: [], hasMore: !1 }), !l.hasMore)) return;
38
+ let d = !1;
39
+ const v = async () => {
40
+ if (d || !i.hasMoreHistory) return;
41
+ d = !0;
42
+ const I = i.messages()[0];
43
+ if (!I) {
44
+ d = !1;
45
+ return;
46
+ }
47
+ const U = await ae(o, t, e, I.seq);
48
+ U && (i.apply({ type: "history", conversationId: t, messages: U.messages, hasMore: U.hasMore }), n.render(i)), d = !1;
49
+ }, b = n.getScrollEl();
50
+ if (!b) return;
51
+ let x = !1;
52
+ setTimeout(() => {
53
+ x = !0;
54
+ }, 300);
55
+ const g = () => {
56
+ x && b.scrollTop < 80 && i.hasMoreHistory && !d && v();
57
+ };
58
+ b.addEventListener("scroll", g, { passive: !0 }), n.setScrollCleanup(() => b.removeEventListener("scroll", g));
59
+ }
60
+ const Ee = {
61
+ accent: "#6c5ce7",
62
+ accent2: "#4c6fff",
63
+ bg: "#f4f3fb",
64
+ card: "#fff",
65
+ tint: "#eeecfb",
66
+ line: "#e6e2f5",
67
+ ink: "#221d3a",
68
+ mut: "#8f8aa8",
69
+ onaccent: "#fff",
70
+ rowhover: "#e7e3f8",
71
+ shadow: "0 12px 32px rgba(108,92,231,.14)"
72
+ }, Be = {
73
+ accent: "#a99cf2",
74
+ accent2: "#6f8cff",
75
+ bg: "#221d3a",
76
+ card: "#2b2550",
77
+ tint: "#2f2853",
78
+ line: "#3a3363",
79
+ ink: "#eceafc",
80
+ mut: "#9b93c9",
81
+ onaccent: "#221d3a",
82
+ rowhover: "#39325e",
83
+ shadow: "0 12px 32px rgba(0,0,0,.4)"
84
+ }, Ie = "'Nunito',-apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif";
85
+ function fe(s, e) {
86
+ return Object.entries(e).map(([t, i]) => `--${s}-${t}:${i};`).join(" ");
87
+ }
88
+ function ke(s) {
89
+ return `${fe(s, Ee)} --${s}-fb:${Ie}; --${s}-fh:'Baloo 2',var(--${s}-fb);`;
90
+ }
91
+ function ce(s) {
92
+ return fe(s, Be);
93
+ }
94
+ const Ae = `
95
+ .ocl { ${ke("ocl")}
96
+ display:flex; flex-direction:column; height:100%; background:var(--ocl-bg);
97
+ font-family:var(--ocl-fb); color:var(--ocl-ink); overflow:hidden; }
98
+ @media (prefers-color-scheme: dark) { .ocl[data-theme="auto"] { ${ce("ocl")} } }
99
+ .ocl[data-theme="dark"] { ${ce("ocl")} }
100
+ .ocl-head { display:flex; align-items:center; padding:16px 16px 10px; background:var(--ocl-bg); }
101
+ .ocl-title { flex:1; display:flex; align-items:center; font-family:var(--ocl-fh); font-weight:700; font-size:18px; color:var(--ocl-ink); }
102
+ .ocl-retry { margin-top:14px; border:none; background:var(--ocl-accent); color:var(--ocl-onaccent); border-radius:20px; padding:8px 20px; font:inherit; font-size:13px; font-weight:600; cursor:pointer; }
103
+ .ocl-search-wrap { padding:4px 12px 8px; background:var(--ocl-bg); }
104
+ .ocl-search { width:100%; box-sizing:border-box; border:none; background:var(--ocl-tint); border-radius:20px; padding:9px 14px; font:inherit; font-size:14px; outline:none; }
105
+ .ocl-body { flex:1; overflow-y:auto; }
106
+ .ocl-section { padding:10px 18px 4px; font-family:var(--ocl-fh); font-size:11px; font-weight:600; color:var(--ocl-mut); text-transform:uppercase; letter-spacing:.5px; background:transparent; }
107
+ .ocl-empty { padding:40px 20px; text-align:center; color:var(--ocl-mut); font-size:14px; }
108
+ .ocl-row { display:flex; align-items:center; gap:12px; padding:10px 12px; margin:6px 12px; background:var(--ocl-tint); border:none; width:calc(100% - 24px); box-sizing:border-box; border-radius:16px; text-align:left; cursor:pointer; transition:background .12s; }
109
+ .ocl-row:hover { background:var(--ocl-rowhover); }
110
+ .ocl-row.unread { background:var(--ocl-rowhover); }
111
+ .ocl-av { width:40px; height:40px; border-radius:50%; background:var(--ocl-accent); color:var(--ocl-onaccent); font-family:var(--ocl-fh); font-size:15px; font-weight:600; display:flex; align-items:center; justify-content:center; flex:none; }
112
+ .ocl-info { flex:1; min-width:0; }
113
+ .ocl-name { font-family:var(--ocl-fh); font-size:14px; font-weight:600; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; margin-bottom:2px; }
114
+ .ocl-row.unread .ocl-name { font-weight:700; }
115
+ .ocl-preview { font-size:11.5px; color:var(--ocl-mut); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
116
+ .ocl-row.unread .ocl-preview { color:var(--ocl-ink); }
117
+ .ocl-right { display:flex; flex-direction:column; align-items:flex-end; gap:4px; flex:none; }
118
+ .ocl-time { font-size:10px; color:var(--ocl-mut); }
119
+ .ocl-row.unread .ocl-time { color:var(--ocl-accent); font-weight:600; }
120
+ .ocl-badge { background:var(--ocl-accent); color:var(--ocl-onaccent); border-radius:999px; font-size:11px; font-weight:700; min-width:20px; height:20px; padding:0 5px; display:flex; align-items:center; justify-content:center; }
121
+ .ocl-status { font-size:10px; font-weight:600; padding:2px 8px; border-radius:20px; white-space:nowrap; }
122
+ .ocl-status.open { background:#dff3e6; color:#2f8a52; }
123
+ .ocl-status.waiting { background:var(--ocl-tint); color:var(--ocl-accent); border:1px solid var(--ocl-accent); }
124
+ .ocl-status.done { background:#eee; color:#777; }
125
+ .ocl[data-theme="dark"] .ocl-status.done { background:#39325e; color:#b3abd6; }
126
+ @media (prefers-color-scheme: dark) { .ocl[data-theme="auto"] .ocl-status.done { background:#39325e; color:#b3abd6; } }
127
+ .ocl-spinner { padding:24px; text-align:center; color:var(--ocl-mut); font-size:13px; }
128
+ .ocl-compose { border:none; background:var(--ocl-accent); color:var(--ocl-onaccent); width:32px; height:32px; border-radius:50%; font-size:18px; line-height:1; cursor:pointer; box-shadow:var(--ocl-shadow); }
129
+ .ocl-compose:hover { filter:brightness(1.08); }
130
+ /* When the HOST overlays a ✕ (ChatApp's onClose / embed's inbox stack), it is
131
+ absolutely positioned at top-right and used to land straight on top of the ✎
132
+ compose button. Reserve the space instead of stacking them. */
133
+ .ocl-has-close .ocl-head { padding-right:52px; }
134
+ .ocl-start { margin-top:12px; border:none; background:var(--ocl-accent); color:var(--ocl-onaccent); border-radius:20px; padding:8px 18px; font:inherit; font-size:13px; font-weight:600; cursor:pointer; }
135
+ /* Compact sizing keyed on the LIST'S OWN width (ResizeObserver toggles
136
+ * .ocl-compact below 400px) — covers phones and narrow desktop embeds alike.
137
+ * Search must be ≥16px in compact or iOS zooms the page on focus. */
138
+ .ocl-compact .ocl-row { padding:13px 14px; }
139
+ .ocl-compact .ocl-search { font-size:16px; }
140
+ .ocl-compact .ocl-compose { width:36px; height:36px; }
141
+ .ocl-row:focus-visible, .ocl button:focus-visible, .ocl input:focus-visible { outline:2px solid var(--ocl-accent); outline-offset:2px; border-radius:12px; }
142
+ `, Te = {
143
+ placeholder: "Message…",
144
+ offline: "We're offline right now",
145
+ online: "Online",
146
+ away: "Away",
147
+ aiAssistant: "AI Assistant",
148
+ resolved: "Marked as resolved",
149
+ reopen: "Reopen conversation",
150
+ sources: "Sources",
151
+ helpful: "Helpful",
152
+ notHelpful: "Not helpful",
153
+ title: "Your conversations",
154
+ newChat: "New conversation",
155
+ startChat: "Start a conversation",
156
+ all: "All conversations",
157
+ empty: "No conversations yet.",
158
+ error: "Could not load conversations.",
159
+ retry: "Retry",
160
+ search: "🔍 Search",
161
+ unread: "Unread",
162
+ close: "Close"
163
+ }, Ce = {
164
+ placeholder: "메시지…",
165
+ offline: "지금은 오프라인입니다",
166
+ online: "온라인",
167
+ away: "자리 비움",
168
+ aiAssistant: "AI 어시스턴트",
169
+ resolved: "해결됨으로 표시됨",
170
+ reopen: "대화 다시 열기",
171
+ sources: "출처",
172
+ helpful: "도움돼요",
173
+ notHelpful: "도움 안돼요",
174
+ title: "내 대화",
175
+ newChat: "새 대화",
176
+ startChat: "대화 시작하기",
177
+ all: "전체 대화",
178
+ empty: "아직 대화가 없습니다.",
179
+ error: "대화를 불러오지 못했습니다.",
180
+ retry: "다시 시도",
181
+ search: "🔍 검색",
182
+ unread: "읽지 않음",
183
+ close: "닫기"
184
+ }, $e = { en: Te, ko: Ce };
185
+ function ze(s) {
186
+ const e = (s ?? (typeof navigator < "u" ? navigator.language : "") ?? "").toLowerCase();
187
+ return e.startsWith("ko") || e.includes("korean") || e.includes("한국") ? "ko" : "en";
188
+ }
189
+ function Le(s, e) {
190
+ const t = $e[ze(s)], i = {};
191
+ for (const [n, r] of Object.entries(e ?? {})) typeof r == "string" && r !== "" && (i[n] = r);
192
+ return { ...t, ...i };
193
+ }
194
+ const R = "oc_uid";
195
+ function Me(s) {
196
+ try {
197
+ const e = document.cookie.match(new RegExp(`(?:^|; )${s}=([^;]*)`));
198
+ return e ? decodeURIComponent(e[1]) : null;
199
+ } catch {
200
+ return null;
201
+ }
202
+ }
203
+ function De(s, e) {
204
+ try {
205
+ const i = location.protocol === "https:" ? "; Secure" : "";
206
+ document.cookie = `${s}=${encodeURIComponent(e)}; Max-Age=31536000; Path=/; SameSite=Lax${i}`;
207
+ } catch {
208
+ }
209
+ }
210
+ function Re() {
211
+ return `g_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
212
+ }
213
+ function _e() {
214
+ let s = null;
215
+ try {
216
+ s = localStorage.getItem(R);
217
+ } catch {
218
+ }
219
+ s || (s = Me(R));
220
+ const e = s ?? Re();
221
+ try {
222
+ localStorage.setItem(R, e);
223
+ } catch {
224
+ }
225
+ return De(R, e), e;
226
+ }
227
+ function Fe(s) {
228
+ const e = s.length;
229
+ let t = 0, i = 0;
230
+ for (; i < e; ) {
231
+ let n = s.charCodeAt(i++);
232
+ if (n & 4294967168)
233
+ if (!(n & 4294965248))
234
+ t += 2;
235
+ else {
236
+ if (n >= 55296 && n <= 56319 && i < e) {
237
+ const r = s.charCodeAt(i);
238
+ (r & 64512) === 56320 && (++i, n = ((n & 1023) << 10) + (r & 1023) + 65536);
239
+ }
240
+ n & 4294901760 ? t += 4 : t += 3;
241
+ }
242
+ else {
243
+ t++;
244
+ continue;
245
+ }
246
+ }
247
+ return t;
248
+ }
249
+ function Pe(s, e, t) {
250
+ const i = s.length;
251
+ let n = t, r = 0;
252
+ for (; r < i; ) {
253
+ let o = s.charCodeAt(r++);
254
+ if (o & 4294967168)
255
+ if (!(o & 4294965248))
256
+ e[n++] = o >> 6 & 31 | 192;
257
+ else {
258
+ if (o >= 55296 && o <= 56319 && r < i) {
259
+ const l = s.charCodeAt(r);
260
+ (l & 64512) === 56320 && (++r, o = ((o & 1023) << 10) + (l & 1023) + 65536);
261
+ }
262
+ o & 4294901760 ? (e[n++] = o >> 18 & 7 | 240, e[n++] = o >> 12 & 63 | 128, e[n++] = o >> 6 & 63 | 128) : (e[n++] = o >> 12 & 15 | 224, e[n++] = o >> 6 & 63 | 128);
263
+ }
264
+ else {
265
+ e[n++] = o;
266
+ continue;
267
+ }
268
+ e[n++] = o & 63 | 128;
269
+ }
270
+ }
271
+ const Ne = new TextEncoder(), He = 50;
272
+ function Ke(s, e, t) {
273
+ Ne.encodeInto(s, e.subarray(t));
274
+ }
275
+ function We(s, e, t) {
276
+ s.length > He ? Ke(s, e, t) : Pe(s, e, t);
277
+ }
278
+ const Oe = 4096;
279
+ function ue(s, e, t) {
280
+ let i = e;
281
+ const n = i + t, r = [];
282
+ let o = "";
283
+ for (; i < n; ) {
284
+ const l = s[i++];
285
+ if (!(l & 128))
286
+ r.push(l);
287
+ else if ((l & 224) === 192) {
288
+ const d = s[i++] & 63;
289
+ r.push((l & 31) << 6 | d);
290
+ } else if ((l & 240) === 224) {
291
+ const d = s[i++] & 63, v = s[i++] & 63;
292
+ r.push((l & 31) << 12 | d << 6 | v);
293
+ } else if ((l & 248) === 240) {
294
+ const d = s[i++] & 63, v = s[i++] & 63, b = s[i++] & 63;
295
+ let x = (l & 7) << 18 | d << 12 | v << 6 | b;
296
+ x > 65535 && (x -= 65536, r.push(x >>> 10 & 1023 | 55296), x = 56320 | x & 1023), r.push(x);
297
+ } else
298
+ r.push(l);
299
+ r.length >= Oe && (o += String.fromCharCode(...r), r.length = 0);
300
+ }
301
+ return r.length > 0 && (o += String.fromCharCode(...r)), o;
302
+ }
303
+ const Ve = new TextDecoder(), Ye = 200;
304
+ function qe(s, e, t) {
305
+ const i = s.subarray(e, e + t);
306
+ return Ve.decode(i);
307
+ }
308
+ function Xe(s, e, t) {
309
+ return t > Ye ? qe(s, e, t) : ue(s, e, t);
310
+ }
311
+ class _ {
312
+ constructor(e, t) {
313
+ a(this, "type");
314
+ a(this, "data");
315
+ this.type = e, this.data = t;
316
+ }
317
+ }
318
+ class y extends Error {
319
+ constructor(e) {
320
+ super(e);
321
+ const t = Object.create(y.prototype);
322
+ Object.setPrototypeOf(this, t), Object.defineProperty(this, "name", {
323
+ configurable: !0,
324
+ enumerable: !1,
325
+ value: y.name
326
+ });
327
+ }
328
+ }
329
+ const $ = 4294967295;
330
+ function Ge(s, e, t) {
331
+ const i = t / 4294967296, n = t;
332
+ s.setUint32(e, i), s.setUint32(e + 4, n);
333
+ }
334
+ function xe(s, e, t) {
335
+ const i = Math.floor(t / 4294967296), n = t;
336
+ s.setUint32(e, i), s.setUint32(e + 4, n);
337
+ }
338
+ function pe(s, e) {
339
+ const t = s.getInt32(e), i = s.getUint32(e + 4);
340
+ return t * 4294967296 + i;
341
+ }
342
+ function Je(s, e) {
343
+ const t = s.getUint32(e), i = s.getUint32(e + 4);
344
+ return t * 4294967296 + i;
345
+ }
346
+ const Ze = -1, Qe = 4294967296 - 1, je = 17179869184 - 1;
347
+ function et({ sec: s, nsec: e }) {
348
+ if (s >= 0 && e >= 0 && s <= je)
349
+ if (e === 0 && s <= Qe) {
350
+ const t = new Uint8Array(4);
351
+ return new DataView(t.buffer).setUint32(0, s), t;
352
+ } else {
353
+ const t = s / 4294967296, i = s & 4294967295, n = new Uint8Array(8), r = new DataView(n.buffer);
354
+ return r.setUint32(0, e << 2 | t & 3), r.setUint32(4, i), n;
355
+ }
356
+ else {
357
+ const t = new Uint8Array(12), i = new DataView(t.buffer);
358
+ return i.setUint32(0, e), xe(i, 4, s), t;
359
+ }
360
+ }
361
+ function tt(s) {
362
+ const e = s.getTime(), t = Math.floor(e / 1e3), i = (e - t * 1e3) * 1e6, n = Math.floor(i / 1e9);
363
+ return {
364
+ sec: t + n,
365
+ nsec: i - n * 1e9
366
+ };
367
+ }
368
+ function st(s) {
369
+ if (s instanceof Date) {
370
+ const e = tt(s);
371
+ return et(e);
372
+ } else
373
+ return null;
374
+ }
375
+ function it(s) {
376
+ const e = new DataView(s.buffer, s.byteOffset, s.byteLength);
377
+ switch (s.byteLength) {
378
+ case 4:
379
+ return { sec: e.getUint32(0), nsec: 0 };
380
+ case 8: {
381
+ const t = e.getUint32(0), i = e.getUint32(4), n = (t & 3) * 4294967296 + i, r = t >>> 2;
382
+ return { sec: n, nsec: r };
383
+ }
384
+ case 12: {
385
+ const t = pe(e, 4), i = e.getUint32(0);
386
+ return { sec: t, nsec: i };
387
+ }
388
+ default:
389
+ throw new y(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${s.length}`);
390
+ }
391
+ }
392
+ function nt(s) {
393
+ const e = it(s);
394
+ return new Date(e.sec * 1e3 + e.nsec / 1e6);
395
+ }
396
+ const rt = {
397
+ type: Ze,
398
+ encode: st,
399
+ decode: nt
400
+ }, P = class P {
401
+ constructor() {
402
+ // ensures ExtensionCodecType<X> matches ExtensionCodec<X>
403
+ // this will make type errors a lot more clear
404
+ // eslint-disable-next-line @typescript-eslint/naming-convention
405
+ a(this, "__brand");
406
+ // built-in extensions
407
+ a(this, "builtInEncoders", []);
408
+ a(this, "builtInDecoders", []);
409
+ // custom extensions
410
+ a(this, "encoders", []);
411
+ a(this, "decoders", []);
412
+ this.register(rt);
413
+ }
414
+ register({ type: e, encode: t, decode: i }) {
415
+ if (e >= 0)
416
+ this.encoders[e] = t, this.decoders[e] = i;
417
+ else {
418
+ const n = -1 - e;
419
+ this.builtInEncoders[n] = t, this.builtInDecoders[n] = i;
420
+ }
421
+ }
422
+ tryToEncode(e, t) {
423
+ for (let i = 0; i < this.builtInEncoders.length; i++) {
424
+ const n = this.builtInEncoders[i];
425
+ if (n != null) {
426
+ const r = n(e, t);
427
+ if (r != null) {
428
+ const o = -1 - i;
429
+ return new _(o, r);
430
+ }
431
+ }
432
+ }
433
+ for (let i = 0; i < this.encoders.length; i++) {
434
+ const n = this.encoders[i];
435
+ if (n != null) {
436
+ const r = n(e, t);
437
+ if (r != null) {
438
+ const o = i;
439
+ return new _(o, r);
440
+ }
441
+ }
442
+ }
443
+ return e instanceof _ ? e : null;
444
+ }
445
+ decode(e, t, i) {
446
+ const n = t < 0 ? this.builtInDecoders[-1 - t] : this.decoders[t];
447
+ return n ? n(e, t, i) : new _(t, e);
448
+ }
449
+ };
450
+ a(P, "defaultCodec", new P());
451
+ let F = P;
452
+ function ot(s) {
453
+ return s instanceof ArrayBuffer || typeof SharedArrayBuffer < "u" && s instanceof SharedArrayBuffer;
454
+ }
455
+ function W(s) {
456
+ return s instanceof Uint8Array ? s : ArrayBuffer.isView(s) ? new Uint8Array(s.buffer, s.byteOffset, s.byteLength) : ot(s) ? new Uint8Array(s) : Uint8Array.from(s);
457
+ }
458
+ const at = 100, ct = 2048;
459
+ class V {
460
+ constructor(e) {
461
+ a(this, "extensionCodec");
462
+ a(this, "context");
463
+ a(this, "useBigInt64");
464
+ a(this, "maxDepth");
465
+ a(this, "initialBufferSize");
466
+ a(this, "sortKeys");
467
+ a(this, "forceFloat32");
468
+ a(this, "ignoreUndefined");
469
+ a(this, "forceIntegerToFloat");
470
+ a(this, "pos");
471
+ a(this, "view");
472
+ a(this, "bytes");
473
+ a(this, "entered", !1);
474
+ this.extensionCodec = (e == null ? void 0 : e.extensionCodec) ?? F.defaultCodec, this.context = e == null ? void 0 : e.context, this.useBigInt64 = (e == null ? void 0 : e.useBigInt64) ?? !1, this.maxDepth = (e == null ? void 0 : e.maxDepth) ?? at, this.initialBufferSize = (e == null ? void 0 : e.initialBufferSize) ?? ct, this.sortKeys = (e == null ? void 0 : e.sortKeys) ?? !1, this.forceFloat32 = (e == null ? void 0 : e.forceFloat32) ?? !1, this.ignoreUndefined = (e == null ? void 0 : e.ignoreUndefined) ?? !1, this.forceIntegerToFloat = (e == null ? void 0 : e.forceIntegerToFloat) ?? !1, this.pos = 0, this.view = new DataView(new ArrayBuffer(this.initialBufferSize)), this.bytes = new Uint8Array(this.view.buffer);
475
+ }
476
+ clone() {
477
+ return new V({
478
+ extensionCodec: this.extensionCodec,
479
+ context: this.context,
480
+ useBigInt64: this.useBigInt64,
481
+ maxDepth: this.maxDepth,
482
+ initialBufferSize: this.initialBufferSize,
483
+ sortKeys: this.sortKeys,
484
+ forceFloat32: this.forceFloat32,
485
+ ignoreUndefined: this.ignoreUndefined,
486
+ forceIntegerToFloat: this.forceIntegerToFloat
487
+ });
488
+ }
489
+ reinitializeState() {
490
+ this.pos = 0;
491
+ }
492
+ /**
493
+ * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.
494
+ *
495
+ * @returns Encodes the object and returns a shared reference the encoder's internal buffer.
496
+ */
497
+ encodeSharedRef(e) {
498
+ if (this.entered)
499
+ return this.clone().encodeSharedRef(e);
500
+ try {
501
+ return this.entered = !0, this.reinitializeState(), this.doEncode(e, 1), this.bytes.subarray(0, this.pos);
502
+ } finally {
503
+ this.entered = !1;
504
+ }
505
+ }
506
+ /**
507
+ * @returns Encodes the object and returns a copy of the encoder's internal buffer.
508
+ */
509
+ encode(e) {
510
+ if (this.entered)
511
+ return this.clone().encode(e);
512
+ try {
513
+ return this.entered = !0, this.reinitializeState(), this.doEncode(e, 1), this.bytes.slice(0, this.pos);
514
+ } finally {
515
+ this.entered = !1;
516
+ }
517
+ }
518
+ doEncode(e, t) {
519
+ if (t > this.maxDepth)
520
+ throw new Error(`Too deep objects in depth ${t}`);
521
+ e == null ? this.encodeNil() : typeof e == "boolean" ? this.encodeBoolean(e) : typeof e == "number" ? this.forceIntegerToFloat ? this.encodeNumberAsFloat(e) : this.encodeNumber(e) : typeof e == "string" ? this.encodeString(e) : this.useBigInt64 && typeof e == "bigint" ? this.encodeBigInt64(e) : this.encodeObject(e, t);
522
+ }
523
+ ensureBufferSizeToWrite(e) {
524
+ const t = this.pos + e;
525
+ this.view.byteLength < t && this.resizeBuffer(t * 2);
526
+ }
527
+ resizeBuffer(e) {
528
+ const t = new ArrayBuffer(e), i = new Uint8Array(t), n = new DataView(t);
529
+ i.set(this.bytes), this.view = n, this.bytes = i;
530
+ }
531
+ encodeNil() {
532
+ this.writeU8(192);
533
+ }
534
+ encodeBoolean(e) {
535
+ e === !1 ? this.writeU8(194) : this.writeU8(195);
536
+ }
537
+ encodeNumber(e) {
538
+ !this.forceIntegerToFloat && Number.isSafeInteger(e) ? e >= 0 ? e < 128 ? this.writeU8(e) : e < 256 ? (this.writeU8(204), this.writeU8(e)) : e < 65536 ? (this.writeU8(205), this.writeU16(e)) : e < 4294967296 ? (this.writeU8(206), this.writeU32(e)) : this.useBigInt64 ? this.encodeNumberAsFloat(e) : (this.writeU8(207), this.writeU64(e)) : e >= -32 ? this.writeU8(224 | e + 32) : e >= -128 ? (this.writeU8(208), this.writeI8(e)) : e >= -32768 ? (this.writeU8(209), this.writeI16(e)) : e >= -2147483648 ? (this.writeU8(210), this.writeI32(e)) : this.useBigInt64 ? this.encodeNumberAsFloat(e) : (this.writeU8(211), this.writeI64(e)) : this.encodeNumberAsFloat(e);
539
+ }
540
+ encodeNumberAsFloat(e) {
541
+ this.forceFloat32 ? (this.writeU8(202), this.writeF32(e)) : (this.writeU8(203), this.writeF64(e));
542
+ }
543
+ encodeBigInt64(e) {
544
+ e >= BigInt(0) ? (this.writeU8(207), this.writeBigUint64(e)) : (this.writeU8(211), this.writeBigInt64(e));
545
+ }
546
+ writeStringHeader(e) {
547
+ if (e < 32)
548
+ this.writeU8(160 + e);
549
+ else if (e < 256)
550
+ this.writeU8(217), this.writeU8(e);
551
+ else if (e < 65536)
552
+ this.writeU8(218), this.writeU16(e);
553
+ else if (e < 4294967296)
554
+ this.writeU8(219), this.writeU32(e);
555
+ else
556
+ throw new Error(`Too long string: ${e} bytes in UTF-8`);
557
+ }
558
+ encodeString(e) {
559
+ const i = Fe(e);
560
+ this.ensureBufferSizeToWrite(5 + i), this.writeStringHeader(i), We(e, this.bytes, this.pos), this.pos += i;
561
+ }
562
+ encodeObject(e, t) {
563
+ const i = this.extensionCodec.tryToEncode(e, this.context);
564
+ if (i != null)
565
+ this.encodeExtension(i);
566
+ else if (Array.isArray(e))
567
+ this.encodeArray(e, t);
568
+ else if (ArrayBuffer.isView(e))
569
+ this.encodeBinary(e);
570
+ else if (typeof e == "object")
571
+ this.encodeMap(e, t);
572
+ else
573
+ throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`);
574
+ }
575
+ encodeBinary(e) {
576
+ const t = e.byteLength;
577
+ if (t < 256)
578
+ this.writeU8(196), this.writeU8(t);
579
+ else if (t < 65536)
580
+ this.writeU8(197), this.writeU16(t);
581
+ else if (t < 4294967296)
582
+ this.writeU8(198), this.writeU32(t);
583
+ else
584
+ throw new Error(`Too large binary: ${t}`);
585
+ const i = W(e);
586
+ this.writeU8a(i);
587
+ }
588
+ encodeArray(e, t) {
589
+ const i = e.length;
590
+ if (i < 16)
591
+ this.writeU8(144 + i);
592
+ else if (i < 65536)
593
+ this.writeU8(220), this.writeU16(i);
594
+ else if (i < 4294967296)
595
+ this.writeU8(221), this.writeU32(i);
596
+ else
597
+ throw new Error(`Too large array: ${i}`);
598
+ for (const n of e)
599
+ this.doEncode(n, t + 1);
600
+ }
601
+ countWithoutUndefined(e, t) {
602
+ let i = 0;
603
+ for (const n of t)
604
+ e[n] !== void 0 && i++;
605
+ return i;
606
+ }
607
+ encodeMap(e, t) {
608
+ const i = Object.keys(e);
609
+ this.sortKeys && i.sort();
610
+ const n = this.ignoreUndefined ? this.countWithoutUndefined(e, i) : i.length;
611
+ if (n < 16)
612
+ this.writeU8(128 + n);
613
+ else if (n < 65536)
614
+ this.writeU8(222), this.writeU16(n);
615
+ else if (n < 4294967296)
616
+ this.writeU8(223), this.writeU32(n);
617
+ else
618
+ throw new Error(`Too large map object: ${n}`);
619
+ for (const r of i) {
620
+ const o = e[r];
621
+ this.ignoreUndefined && o === void 0 || (this.encodeString(r), this.doEncode(o, t + 1));
622
+ }
623
+ }
624
+ encodeExtension(e) {
625
+ if (typeof e.data == "function") {
626
+ const i = e.data(this.pos + 6), n = i.length;
627
+ if (n >= 4294967296)
628
+ throw new Error(`Too large extension object: ${n}`);
629
+ this.writeU8(201), this.writeU32(n), this.writeI8(e.type), this.writeU8a(i);
630
+ return;
631
+ }
632
+ const t = e.data.length;
633
+ if (t === 1)
634
+ this.writeU8(212);
635
+ else if (t === 2)
636
+ this.writeU8(213);
637
+ else if (t === 4)
638
+ this.writeU8(214);
639
+ else if (t === 8)
640
+ this.writeU8(215);
641
+ else if (t === 16)
642
+ this.writeU8(216);
643
+ else if (t < 256)
644
+ this.writeU8(199), this.writeU8(t);
645
+ else if (t < 65536)
646
+ this.writeU8(200), this.writeU16(t);
647
+ else if (t < 4294967296)
648
+ this.writeU8(201), this.writeU32(t);
649
+ else
650
+ throw new Error(`Too large extension object: ${t}`);
651
+ this.writeI8(e.type), this.writeU8a(e.data);
652
+ }
653
+ writeU8(e) {
654
+ this.ensureBufferSizeToWrite(1), this.view.setUint8(this.pos, e), this.pos++;
655
+ }
656
+ writeU8a(e) {
657
+ const t = e.length;
658
+ this.ensureBufferSizeToWrite(t), this.bytes.set(e, this.pos), this.pos += t;
659
+ }
660
+ writeI8(e) {
661
+ this.ensureBufferSizeToWrite(1), this.view.setInt8(this.pos, e), this.pos++;
662
+ }
663
+ writeU16(e) {
664
+ this.ensureBufferSizeToWrite(2), this.view.setUint16(this.pos, e), this.pos += 2;
665
+ }
666
+ writeI16(e) {
667
+ this.ensureBufferSizeToWrite(2), this.view.setInt16(this.pos, e), this.pos += 2;
668
+ }
669
+ writeU32(e) {
670
+ this.ensureBufferSizeToWrite(4), this.view.setUint32(this.pos, e), this.pos += 4;
671
+ }
672
+ writeI32(e) {
673
+ this.ensureBufferSizeToWrite(4), this.view.setInt32(this.pos, e), this.pos += 4;
674
+ }
675
+ writeF32(e) {
676
+ this.ensureBufferSizeToWrite(4), this.view.setFloat32(this.pos, e), this.pos += 4;
677
+ }
678
+ writeF64(e) {
679
+ this.ensureBufferSizeToWrite(8), this.view.setFloat64(this.pos, e), this.pos += 8;
680
+ }
681
+ writeU64(e) {
682
+ this.ensureBufferSizeToWrite(8), Ge(this.view, this.pos, e), this.pos += 8;
683
+ }
684
+ writeI64(e) {
685
+ this.ensureBufferSizeToWrite(8), xe(this.view, this.pos, e), this.pos += 8;
686
+ }
687
+ writeBigUint64(e) {
688
+ this.ensureBufferSizeToWrite(8), this.view.setBigUint64(this.pos, e), this.pos += 8;
689
+ }
690
+ writeBigInt64(e) {
691
+ this.ensureBufferSizeToWrite(8), this.view.setBigInt64(this.pos, e), this.pos += 8;
692
+ }
693
+ }
694
+ function lt(s, e) {
695
+ return new V(e).encodeSharedRef(s);
696
+ }
697
+ function K(s) {
698
+ return `${s < 0 ? "-" : ""}0x${Math.abs(s).toString(16).padStart(2, "0")}`;
699
+ }
700
+ const ht = 16, dt = 16;
701
+ class ft {
702
+ constructor(e = ht, t = dt) {
703
+ a(this, "hit", 0);
704
+ a(this, "miss", 0);
705
+ a(this, "caches");
706
+ a(this, "maxKeyLength");
707
+ a(this, "maxLengthPerKey");
708
+ this.maxKeyLength = e, this.maxLengthPerKey = t, this.caches = [];
709
+ for (let i = 0; i < this.maxKeyLength; i++)
710
+ this.caches.push([]);
711
+ }
712
+ canBeCached(e) {
713
+ return e > 0 && e <= this.maxKeyLength;
714
+ }
715
+ find(e, t, i) {
716
+ const n = this.caches[i - 1];
717
+ e: for (const r of n) {
718
+ const o = r.bytes;
719
+ for (let l = 0; l < i; l++)
720
+ if (o[l] !== e[t + l])
721
+ continue e;
722
+ return r.str;
723
+ }
724
+ return null;
725
+ }
726
+ store(e, t) {
727
+ const i = this.caches[e.length - 1], n = { bytes: e, str: t };
728
+ i.length >= this.maxLengthPerKey ? i[Math.random() * i.length | 0] = n : i.push(n);
729
+ }
730
+ decode(e, t, i) {
731
+ const n = this.find(e, t, i);
732
+ if (n != null)
733
+ return this.hit++, n;
734
+ this.miss++;
735
+ const r = ue(e, t, i), o = Uint8Array.prototype.slice.call(e, t, t + i);
736
+ return this.store(o, r), r;
737
+ }
738
+ }
739
+ const O = "array", L = "map_key", ge = "map_value", ut = (s) => {
740
+ if (typeof s == "string" || typeof s == "number")
741
+ return s;
742
+ throw new y("The type of key must be string or number but " + typeof s);
743
+ };
744
+ class xt {
745
+ constructor() {
746
+ a(this, "stack", []);
747
+ a(this, "stackHeadPosition", -1);
748
+ }
749
+ get length() {
750
+ return this.stackHeadPosition + 1;
751
+ }
752
+ top() {
753
+ return this.stack[this.stackHeadPosition];
754
+ }
755
+ pushArrayState(e) {
756
+ const t = this.getUninitializedStateFromPool();
757
+ t.type = O, t.position = 0, t.size = e, t.array = new Array(e);
758
+ }
759
+ pushMapState(e) {
760
+ const t = this.getUninitializedStateFromPool();
761
+ t.type = L, t.readCount = 0, t.size = e, t.map = {};
762
+ }
763
+ getUninitializedStateFromPool() {
764
+ if (this.stackHeadPosition++, this.stackHeadPosition === this.stack.length) {
765
+ const e = {
766
+ type: void 0,
767
+ size: 0,
768
+ array: void 0,
769
+ position: 0,
770
+ readCount: 0,
771
+ map: void 0,
772
+ key: null
773
+ };
774
+ this.stack.push(e);
775
+ }
776
+ return this.stack[this.stackHeadPosition];
777
+ }
778
+ release(e) {
779
+ if (this.stack[this.stackHeadPosition] !== e)
780
+ throw new Error("Invalid stack state. Released state is not on top of the stack.");
781
+ if (e.type === O) {
782
+ const i = e;
783
+ i.size = 0, i.array = void 0, i.position = 0, i.type = void 0;
784
+ }
785
+ if (e.type === L || e.type === ge) {
786
+ const i = e;
787
+ i.size = 0, i.map = void 0, i.readCount = 0, i.type = void 0;
788
+ }
789
+ this.stackHeadPosition--;
790
+ }
791
+ reset() {
792
+ this.stack.length = 0, this.stackHeadPosition = -1;
793
+ }
794
+ }
795
+ const z = -1, Y = new DataView(new ArrayBuffer(0)), pt = new Uint8Array(Y.buffer);
796
+ try {
797
+ Y.getInt8(0);
798
+ } catch (s) {
799
+ if (!(s instanceof RangeError))
800
+ throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access");
801
+ }
802
+ const le = new RangeError("Insufficient data"), gt = new ft();
803
+ class q {
804
+ constructor(e) {
805
+ a(this, "extensionCodec");
806
+ a(this, "context");
807
+ a(this, "useBigInt64");
808
+ a(this, "rawStrings");
809
+ a(this, "maxStrLength");
810
+ a(this, "maxBinLength");
811
+ a(this, "maxArrayLength");
812
+ a(this, "maxMapLength");
813
+ a(this, "maxExtLength");
814
+ a(this, "keyDecoder");
815
+ a(this, "mapKeyConverter");
816
+ a(this, "totalPos", 0);
817
+ a(this, "pos", 0);
818
+ a(this, "view", Y);
819
+ a(this, "bytes", pt);
820
+ a(this, "headByte", z);
821
+ a(this, "stack", new xt());
822
+ a(this, "entered", !1);
823
+ this.extensionCodec = (e == null ? void 0 : e.extensionCodec) ?? F.defaultCodec, this.context = e == null ? void 0 : e.context, this.useBigInt64 = (e == null ? void 0 : e.useBigInt64) ?? !1, this.rawStrings = (e == null ? void 0 : e.rawStrings) ?? !1, this.maxStrLength = (e == null ? void 0 : e.maxStrLength) ?? $, this.maxBinLength = (e == null ? void 0 : e.maxBinLength) ?? $, this.maxArrayLength = (e == null ? void 0 : e.maxArrayLength) ?? $, this.maxMapLength = (e == null ? void 0 : e.maxMapLength) ?? $, this.maxExtLength = (e == null ? void 0 : e.maxExtLength) ?? $, this.keyDecoder = (e == null ? void 0 : e.keyDecoder) !== void 0 ? e.keyDecoder : gt, this.mapKeyConverter = (e == null ? void 0 : e.mapKeyConverter) ?? ut;
824
+ }
825
+ clone() {
826
+ return new q({
827
+ extensionCodec: this.extensionCodec,
828
+ context: this.context,
829
+ useBigInt64: this.useBigInt64,
830
+ rawStrings: this.rawStrings,
831
+ maxStrLength: this.maxStrLength,
832
+ maxBinLength: this.maxBinLength,
833
+ maxArrayLength: this.maxArrayLength,
834
+ maxMapLength: this.maxMapLength,
835
+ maxExtLength: this.maxExtLength,
836
+ keyDecoder: this.keyDecoder
837
+ });
838
+ }
839
+ reinitializeState() {
840
+ this.totalPos = 0, this.headByte = z, this.stack.reset();
841
+ }
842
+ setBuffer(e) {
843
+ const t = W(e);
844
+ this.bytes = t, this.view = new DataView(t.buffer, t.byteOffset, t.byteLength), this.pos = 0;
845
+ }
846
+ appendBuffer(e) {
847
+ if (this.headByte === z && !this.hasRemaining(1))
848
+ this.setBuffer(e);
849
+ else {
850
+ const t = this.bytes.subarray(this.pos), i = W(e), n = new Uint8Array(t.length + i.length);
851
+ n.set(t), n.set(i, t.length), this.setBuffer(n);
852
+ }
853
+ }
854
+ hasRemaining(e) {
855
+ return this.view.byteLength - this.pos >= e;
856
+ }
857
+ createExtraByteError(e) {
858
+ const { view: t, pos: i } = this;
859
+ return new RangeError(`Extra ${t.byteLength - i} of ${t.byteLength} byte(s) found at buffer[${e}]`);
860
+ }
861
+ /**
862
+ * @throws {@link DecodeError}
863
+ * @throws {@link RangeError}
864
+ */
865
+ decode(e) {
866
+ if (this.entered)
867
+ return this.clone().decode(e);
868
+ try {
869
+ this.entered = !0, this.reinitializeState(), this.setBuffer(e);
870
+ const t = this.doDecodeSync();
871
+ if (this.hasRemaining(1))
872
+ throw this.createExtraByteError(this.pos);
873
+ return t;
874
+ } finally {
875
+ this.entered = !1;
876
+ }
877
+ }
878
+ *decodeMulti(e) {
879
+ if (this.entered) {
880
+ yield* this.clone().decodeMulti(e);
881
+ return;
882
+ }
883
+ try {
884
+ for (this.entered = !0, this.reinitializeState(), this.setBuffer(e); this.hasRemaining(1); )
885
+ yield this.doDecodeSync();
886
+ } finally {
887
+ this.entered = !1;
888
+ }
889
+ }
890
+ async decodeAsync(e) {
891
+ if (this.entered)
892
+ return this.clone().decodeAsync(e);
893
+ try {
894
+ this.entered = !0;
895
+ let t = !1, i;
896
+ for await (const l of e) {
897
+ if (t)
898
+ throw this.entered = !1, this.createExtraByteError(this.totalPos);
899
+ this.appendBuffer(l);
900
+ try {
901
+ i = this.doDecodeSync(), t = !0;
902
+ } catch (d) {
903
+ if (!(d instanceof RangeError))
904
+ throw d;
905
+ }
906
+ this.totalPos += this.pos;
907
+ }
908
+ if (t) {
909
+ if (this.hasRemaining(1))
910
+ throw this.createExtraByteError(this.totalPos);
911
+ return i;
912
+ }
913
+ const { headByte: n, pos: r, totalPos: o } = this;
914
+ throw new RangeError(`Insufficient data in parsing ${K(n)} at ${o} (${r} in the current buffer)`);
915
+ } finally {
916
+ this.entered = !1;
917
+ }
918
+ }
919
+ decodeArrayStream(e) {
920
+ return this.decodeMultiAsync(e, !0);
921
+ }
922
+ decodeStream(e) {
923
+ return this.decodeMultiAsync(e, !1);
924
+ }
925
+ async *decodeMultiAsync(e, t) {
926
+ if (this.entered) {
927
+ yield* this.clone().decodeMultiAsync(e, t);
928
+ return;
929
+ }
930
+ try {
931
+ this.entered = !0;
932
+ let i = t, n = -1;
933
+ for await (const r of e) {
934
+ if (t && n === 0)
935
+ throw this.createExtraByteError(this.totalPos);
936
+ this.appendBuffer(r), i && (n = this.readArraySize(), i = !1, this.complete());
937
+ try {
938
+ for (; yield this.doDecodeSync(), --n !== 0; )
939
+ ;
940
+ } catch (o) {
941
+ if (!(o instanceof RangeError))
942
+ throw o;
943
+ }
944
+ this.totalPos += this.pos;
945
+ }
946
+ } finally {
947
+ this.entered = !1;
948
+ }
949
+ }
950
+ doDecodeSync() {
951
+ e: for (; ; ) {
952
+ const e = this.readHeadByte();
953
+ let t;
954
+ if (e >= 224)
955
+ t = e - 256;
956
+ else if (e < 192)
957
+ if (e < 128)
958
+ t = e;
959
+ else if (e < 144) {
960
+ const n = e - 128;
961
+ if (n !== 0) {
962
+ this.pushMapState(n), this.complete();
963
+ continue e;
964
+ } else
965
+ t = {};
966
+ } else if (e < 160) {
967
+ const n = e - 144;
968
+ if (n !== 0) {
969
+ this.pushArrayState(n), this.complete();
970
+ continue e;
971
+ } else
972
+ t = [];
973
+ } else {
974
+ const n = e - 160;
975
+ t = this.decodeString(n, 0);
976
+ }
977
+ else if (e === 192)
978
+ t = null;
979
+ else if (e === 194)
980
+ t = !1;
981
+ else if (e === 195)
982
+ t = !0;
983
+ else if (e === 202)
984
+ t = this.readF32();
985
+ else if (e === 203)
986
+ t = this.readF64();
987
+ else if (e === 204)
988
+ t = this.readU8();
989
+ else if (e === 205)
990
+ t = this.readU16();
991
+ else if (e === 206)
992
+ t = this.readU32();
993
+ else if (e === 207)
994
+ this.useBigInt64 ? t = this.readU64AsBigInt() : t = this.readU64();
995
+ else if (e === 208)
996
+ t = this.readI8();
997
+ else if (e === 209)
998
+ t = this.readI16();
999
+ else if (e === 210)
1000
+ t = this.readI32();
1001
+ else if (e === 211)
1002
+ this.useBigInt64 ? t = this.readI64AsBigInt() : t = this.readI64();
1003
+ else if (e === 217) {
1004
+ const n = this.lookU8();
1005
+ t = this.decodeString(n, 1);
1006
+ } else if (e === 218) {
1007
+ const n = this.lookU16();
1008
+ t = this.decodeString(n, 2);
1009
+ } else if (e === 219) {
1010
+ const n = this.lookU32();
1011
+ t = this.decodeString(n, 4);
1012
+ } else if (e === 220) {
1013
+ const n = this.readU16();
1014
+ if (n !== 0) {
1015
+ this.pushArrayState(n), this.complete();
1016
+ continue e;
1017
+ } else
1018
+ t = [];
1019
+ } else if (e === 221) {
1020
+ const n = this.readU32();
1021
+ if (n !== 0) {
1022
+ this.pushArrayState(n), this.complete();
1023
+ continue e;
1024
+ } else
1025
+ t = [];
1026
+ } else if (e === 222) {
1027
+ const n = this.readU16();
1028
+ if (n !== 0) {
1029
+ this.pushMapState(n), this.complete();
1030
+ continue e;
1031
+ } else
1032
+ t = {};
1033
+ } else if (e === 223) {
1034
+ const n = this.readU32();
1035
+ if (n !== 0) {
1036
+ this.pushMapState(n), this.complete();
1037
+ continue e;
1038
+ } else
1039
+ t = {};
1040
+ } else if (e === 196) {
1041
+ const n = this.lookU8();
1042
+ t = this.decodeBinary(n, 1);
1043
+ } else if (e === 197) {
1044
+ const n = this.lookU16();
1045
+ t = this.decodeBinary(n, 2);
1046
+ } else if (e === 198) {
1047
+ const n = this.lookU32();
1048
+ t = this.decodeBinary(n, 4);
1049
+ } else if (e === 212)
1050
+ t = this.decodeExtension(1, 0);
1051
+ else if (e === 213)
1052
+ t = this.decodeExtension(2, 0);
1053
+ else if (e === 214)
1054
+ t = this.decodeExtension(4, 0);
1055
+ else if (e === 215)
1056
+ t = this.decodeExtension(8, 0);
1057
+ else if (e === 216)
1058
+ t = this.decodeExtension(16, 0);
1059
+ else if (e === 199) {
1060
+ const n = this.lookU8();
1061
+ t = this.decodeExtension(n, 1);
1062
+ } else if (e === 200) {
1063
+ const n = this.lookU16();
1064
+ t = this.decodeExtension(n, 2);
1065
+ } else if (e === 201) {
1066
+ const n = this.lookU32();
1067
+ t = this.decodeExtension(n, 4);
1068
+ } else
1069
+ throw new y(`Unrecognized type byte: ${K(e)}`);
1070
+ this.complete();
1071
+ const i = this.stack;
1072
+ for (; i.length > 0; ) {
1073
+ const n = i.top();
1074
+ if (n.type === O)
1075
+ if (n.array[n.position] = t, n.position++, n.position === n.size)
1076
+ t = n.array, i.release(n);
1077
+ else
1078
+ continue e;
1079
+ else if (n.type === L) {
1080
+ if (t === "__proto__")
1081
+ throw new y("The key __proto__ is not allowed");
1082
+ n.key = this.mapKeyConverter(t), n.type = ge;
1083
+ continue e;
1084
+ } else if (n.map[n.key] = t, n.readCount++, n.readCount === n.size)
1085
+ t = n.map, i.release(n);
1086
+ else {
1087
+ n.key = null, n.type = L;
1088
+ continue e;
1089
+ }
1090
+ }
1091
+ return t;
1092
+ }
1093
+ }
1094
+ readHeadByte() {
1095
+ return this.headByte === z && (this.headByte = this.readU8()), this.headByte;
1096
+ }
1097
+ complete() {
1098
+ this.headByte = z;
1099
+ }
1100
+ readArraySize() {
1101
+ const e = this.readHeadByte();
1102
+ switch (e) {
1103
+ case 220:
1104
+ return this.readU16();
1105
+ case 221:
1106
+ return this.readU32();
1107
+ default: {
1108
+ if (e < 160)
1109
+ return e - 144;
1110
+ throw new y(`Unrecognized array type byte: ${K(e)}`);
1111
+ }
1112
+ }
1113
+ }
1114
+ pushMapState(e) {
1115
+ if (e > this.maxMapLength)
1116
+ throw new y(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);
1117
+ this.stack.pushMapState(e);
1118
+ }
1119
+ pushArrayState(e) {
1120
+ if (e > this.maxArrayLength)
1121
+ throw new y(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);
1122
+ this.stack.pushArrayState(e);
1123
+ }
1124
+ decodeString(e, t) {
1125
+ return !this.rawStrings || this.stateIsMapKey() ? this.decodeUtf8String(e, t) : this.decodeBinary(e, t);
1126
+ }
1127
+ /**
1128
+ * @throws {@link RangeError}
1129
+ */
1130
+ decodeUtf8String(e, t) {
1131
+ var r;
1132
+ if (e > this.maxStrLength)
1133
+ throw new y(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);
1134
+ if (this.bytes.byteLength < this.pos + t + e)
1135
+ throw le;
1136
+ const i = this.pos + t;
1137
+ let n;
1138
+ return this.stateIsMapKey() && ((r = this.keyDecoder) != null && r.canBeCached(e)) ? n = this.keyDecoder.decode(this.bytes, i, e) : n = Xe(this.bytes, i, e), this.pos += t + e, n;
1139
+ }
1140
+ stateIsMapKey() {
1141
+ return this.stack.length > 0 ? this.stack.top().type === L : !1;
1142
+ }
1143
+ /**
1144
+ * @throws {@link RangeError}
1145
+ */
1146
+ decodeBinary(e, t) {
1147
+ if (e > this.maxBinLength)
1148
+ throw new y(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);
1149
+ if (!this.hasRemaining(e + t))
1150
+ throw le;
1151
+ const i = this.pos + t, n = this.bytes.subarray(i, i + e);
1152
+ return this.pos += t + e, n;
1153
+ }
1154
+ decodeExtension(e, t) {
1155
+ if (e > this.maxExtLength)
1156
+ throw new y(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);
1157
+ const i = this.view.getInt8(this.pos + t), n = this.decodeBinary(
1158
+ e,
1159
+ t + 1
1160
+ /* extType */
1161
+ );
1162
+ return this.extensionCodec.decode(n, i, this.context);
1163
+ }
1164
+ lookU8() {
1165
+ return this.view.getUint8(this.pos);
1166
+ }
1167
+ lookU16() {
1168
+ return this.view.getUint16(this.pos);
1169
+ }
1170
+ lookU32() {
1171
+ return this.view.getUint32(this.pos);
1172
+ }
1173
+ readU8() {
1174
+ const e = this.view.getUint8(this.pos);
1175
+ return this.pos++, e;
1176
+ }
1177
+ readI8() {
1178
+ const e = this.view.getInt8(this.pos);
1179
+ return this.pos++, e;
1180
+ }
1181
+ readU16() {
1182
+ const e = this.view.getUint16(this.pos);
1183
+ return this.pos += 2, e;
1184
+ }
1185
+ readI16() {
1186
+ const e = this.view.getInt16(this.pos);
1187
+ return this.pos += 2, e;
1188
+ }
1189
+ readU32() {
1190
+ const e = this.view.getUint32(this.pos);
1191
+ return this.pos += 4, e;
1192
+ }
1193
+ readI32() {
1194
+ const e = this.view.getInt32(this.pos);
1195
+ return this.pos += 4, e;
1196
+ }
1197
+ readU64() {
1198
+ const e = Je(this.view, this.pos);
1199
+ return this.pos += 8, e;
1200
+ }
1201
+ readI64() {
1202
+ const e = pe(this.view, this.pos);
1203
+ return this.pos += 8, e;
1204
+ }
1205
+ readU64AsBigInt() {
1206
+ const e = this.view.getBigUint64(this.pos);
1207
+ return this.pos += 8, e;
1208
+ }
1209
+ readI64AsBigInt() {
1210
+ const e = this.view.getBigInt64(this.pos);
1211
+ return this.pos += 8, e;
1212
+ }
1213
+ readF32() {
1214
+ const e = this.view.getFloat32(this.pos);
1215
+ return this.pos += 4, e;
1216
+ }
1217
+ readF64() {
1218
+ const e = this.view.getFloat64(this.pos);
1219
+ return this.pos += 8, e;
1220
+ }
1221
+ }
1222
+ function wt(s, e) {
1223
+ return new q(e).decode(s);
1224
+ }
1225
+ const yt = /* @__PURE__ */ new Set([
1226
+ "auth",
1227
+ "open",
1228
+ "send",
1229
+ "sync",
1230
+ "history",
1231
+ "read",
1232
+ "typing",
1233
+ "react",
1234
+ "edit",
1235
+ "delete",
1236
+ "invoke",
1237
+ "pubkey",
1238
+ "ping",
1239
+ "uploadPrekeys",
1240
+ "fetchPrekey",
1241
+ "assign",
1242
+ "tag",
1243
+ "note",
1244
+ "agent_status",
1245
+ "subscribe_inbox",
1246
+ "unsubscribe_inbox"
1247
+ ]);
1248
+ function Et(s) {
1249
+ return yt.has(s.type);
1250
+ }
1251
+ function he(s) {
1252
+ return lt(s);
1253
+ }
1254
+ function mt(s) {
1255
+ let e;
1256
+ try {
1257
+ e = wt(s);
1258
+ } catch {
1259
+ return null;
1260
+ }
1261
+ return typeof e != "object" || e === null || typeof e.type != "string" ? null : e;
1262
+ }
1263
+ function vt(s) {
1264
+ switch (s) {
1265
+ case "open":
1266
+ return { label: "Open", cls: "open" };
1267
+ case "awaiting_staff":
1268
+ return { label: "Waiting on you", cls: "waiting" };
1269
+ case "resolved":
1270
+ return { label: "Resolved", cls: "done" };
1271
+ case "closed":
1272
+ return { label: "Closed", cls: "done" };
1273
+ default:
1274
+ return null;
1275
+ }
1276
+ }
1277
+ function Ut(s) {
1278
+ const e = Math.floor((Date.now() - s) / 1e3);
1279
+ if (e < 60) return "just now";
1280
+ if (e < 3600) return `${Math.floor(e / 60)}m`;
1281
+ if (e < 86400) return `${Math.floor(e / 3600)}h`;
1282
+ const t = Math.floor(e / 86400);
1283
+ if (t <= 7) return `${t}d`;
1284
+ try {
1285
+ return new Date(s).toLocaleDateString(void 0, { month: "short", day: "numeric" });
1286
+ } catch {
1287
+ return `${t}d`;
1288
+ }
1289
+ }
1290
+ function h(s, e, t) {
1291
+ const i = document.createElement(s);
1292
+ return e && (i.className = e), t !== void 0 && (i.textContent = t), i;
1293
+ }
1294
+ function Bt(s) {
1295
+ const e = s.token ?? s.userId ?? _e(), { httpBase: t, wsUrl: i } = de(s.url, s.apiUrl), n = Le(s.locale, s.i18n), r = s.accent ?? "#6c5ce7";
1296
+ if (!document.getElementById("ocl-styles")) {
1297
+ const c = document.createElement("style");
1298
+ c.id = "ocl-styles", c.textContent = Ae, document.head.append(c);
1299
+ }
1300
+ if (s.webfont !== !1 && typeof document < "u" && !document.getElementById("ocw-webfont")) {
1301
+ const c = document.createElement("link");
1302
+ c.id = "ocw-webfont", c.rel = "stylesheet", c.href = "https://fonts.googleapis.com/css2?family=Baloo+2:wght@500;600;700&family=Nunito:wght@400;500;600;700&display=swap", document.head.append(c);
1303
+ }
1304
+ const o = h("div", "ocl");
1305
+ o.style.setProperty("--ocl-accent", r), o.dataset.theme = s.theme ?? "light", s.reserveCloseSpace && o.classList.add("ocl-has-close");
1306
+ const l = h("div", "ocl-head"), d = n.title ?? "Your conversations", v = h("span", "ocl-title", d);
1307
+ if (v.setAttribute("aria-label", d), l.append(v), s.onNewChat) {
1308
+ const c = h("button", "ocl-compose", "✎");
1309
+ c.title = n.newChat ?? "New conversation", c.addEventListener("click", () => s.onNewChat()), l.append(c);
1310
+ }
1311
+ const b = h("div", "ocl-search-wrap"), x = h("input", "ocl-search");
1312
+ x.placeholder = n.search ?? "🔍 Search", x.type = "search", b.append(x);
1313
+ const g = h("div", "ocl-body");
1314
+ g.append(h("div", "ocl-spinner", "Loading…")), o.append(l, b, g), s.el.replaceChildren(o);
1315
+ const I = (c) => {
1316
+ o.classList.toggle("ocl-compact", c > 0 && c < 400);
1317
+ };
1318
+ I(o.clientWidth);
1319
+ let U = null;
1320
+ if (typeof ResizeObserver < "u" && (U = new ResizeObserver((c) => {
1321
+ var u;
1322
+ return I(((u = c[0]) == null ? void 0 : u.contentRect.width) ?? o.clientWidth);
1323
+ }), U.observe(o)), !s.profileId && !s.tenantId) throw new Error("[relay chatlist] provide profileId or tenantId");
1324
+ let X;
1325
+ const G = `ocl_seen_${s.profileId ?? `t_${s.tenantId}`}_${(s.userId ?? e).slice(-8)}`;
1326
+ let k = {};
1327
+ try {
1328
+ k = JSON.parse(localStorage.getItem(G) ?? "{}");
1329
+ } catch {
1330
+ }
1331
+ const we = () => {
1332
+ try {
1333
+ localStorage.setItem(G, JSON.stringify(k));
1334
+ } catch {
1335
+ }
1336
+ };
1337
+ let J = [], B = !1;
1338
+ const ye = async () => {
1339
+ const c = s.profileId ? `profileId=${encodeURIComponent(s.profileId)}${s.scope === "tenant" ? "&scope=tenant" : ""}` : `tenantId=${encodeURIComponent(s.tenantId)}`, u = `${t}/conversations/mine?${c}`, w = { authorization: `Bearer ${e}` };
1340
+ let S;
1341
+ try {
1342
+ S = await fetch(u, { headers: w });
1343
+ } catch {
1344
+ S = await fetch(u, { headers: w });
1345
+ }
1346
+ if (!S.ok) return [];
1347
+ const m = await S.json();
1348
+ return m.defaultProfileId && (X = m.defaultProfileId), (m.conversations ?? []).sort((E, f) => f.updatedAt - E.updatedAt);
1349
+ }, Z = (c, u) => {
1350
+ if (B) return;
1351
+ const w = u ? c.filter(
1352
+ (f) => Q(f).toLowerCase().includes(u) || (f.lastMessage ?? "").toLowerCase().includes(u)
1353
+ ) : c;
1354
+ if (g.replaceChildren(), !w.length) {
1355
+ const f = h("div", "ocl-empty", u ? "No results." : n.empty ?? "No conversations yet.");
1356
+ if (!u && s.onNewChat) {
1357
+ f.append(h("br"));
1358
+ const D = h("button", "ocl-start", n.startChat ?? "Start a conversation");
1359
+ D.addEventListener("click", () => s.onNewChat()), f.append(D);
1360
+ }
1361
+ g.append(f);
1362
+ return;
1363
+ }
1364
+ const S = (f) => (f.lastSeq ?? 0) > (k[f.id] ?? 0), m = w.filter(S), E = w.filter((f) => !S(f));
1365
+ if (m.length) {
1366
+ g.append(h("div", "ocl-section", `${n.unread ?? "Unread"} (${m.length})`));
1367
+ for (const f of m) g.append(j(f, S(f)));
1368
+ }
1369
+ if (E.length) {
1370
+ g.append(h("div", "ocl-section", m.length ? n.all ?? "All conversations" : ""));
1371
+ for (const f of E) g.append(j(f, !1));
1372
+ }
1373
+ }, Q = (c) => c.subjectTitle ?? (c.kind === "direct" ? c.peerId ?? "Direct message" : "General enquiry"), j = (c, u) => {
1374
+ var re;
1375
+ const w = Q(c), S = (((re = w.match(new RegExp("\\p{L}", "u"))) == null ? void 0 : re[0]) ?? w.trim()[0] ?? "?").toUpperCase(), m = c.lastSeq ?? 0, E = u ? Math.max(1, m - (k[c.id] ?? 0)) : 0, f = h("button", `ocl-row${u ? " unread" : ""}`), D = h("div", "ocl-av", S);
1376
+ f.append(D);
1377
+ const N = h("div", "ocl-info");
1378
+ N.append(h("div", "ocl-name", w));
1379
+ const me = {
1380
+ open: "Open",
1381
+ awaiting_staff: "Waiting for reply…",
1382
+ resolved: "Resolved ✓",
1383
+ closed: "Closed"
1384
+ };
1385
+ N.append(h("div", "ocl-preview", c.lastMessage ?? me[c.state] ?? c.state)), f.append(N);
1386
+ const C = h("div", "ocl-right");
1387
+ C.append(h("div", "ocl-time", Ut(c.updatedAt)));
1388
+ const H = vt(c.state);
1389
+ return H && C.append(h("div", `ocl-status ${H.cls}`, H.label)), E > 0 && C.append(h("div", "ocl-badge", String(E > 99 ? "99+" : E))), f.append(C), f.addEventListener("click", () => {
1390
+ var oe;
1391
+ m > 0 && (k[c.id] = m, we()), f.classList.remove("unread"), (oe = C.querySelector(".ocl-badge")) == null || oe.remove(), s.onSelect(c);
1392
+ }), f;
1393
+ }, M = () => {
1394
+ B || ye().then((c) => {
1395
+ B || (J = c, Z(c, x.value.trim().toLowerCase()));
1396
+ }).catch((c) => {
1397
+ if (B) return;
1398
+ console.error(`[chat-widget] failed to load conversations from ${t}/conversations/mine — check the apiUrl/CORS config.`, c);
1399
+ const u = h("div", "ocl-empty", n.error ?? "Could not load conversations.");
1400
+ u.append(h("br"));
1401
+ const w = h("button", "ocl-retry", n.retry ?? "Retry");
1402
+ w.addEventListener("click", () => {
1403
+ g.replaceChildren(h("div", "ocl-spinner", "Loading…")), M();
1404
+ }), u.append(w), g.replaceChildren(u);
1405
+ });
1406
+ };
1407
+ x.addEventListener("input", () => Z(J, x.value.trim().toLowerCase())), M();
1408
+ let p = null, A, T, ee = 0, te = !1;
1409
+ const se = () => {
1410
+ T || (T = setTimeout(() => {
1411
+ T = void 0, M();
1412
+ }, 300));
1413
+ }, ie = () => {
1414
+ if (!B) {
1415
+ try {
1416
+ p = new WebSocket(i);
1417
+ } catch {
1418
+ ne();
1419
+ return;
1420
+ }
1421
+ p.binaryType = "arraybuffer", p.onopen = () => {
1422
+ ee = 0, p.send(he({ type: "auth", token: e })), p.send(he({ type: "subscribe_inbox" })), te && se(), te = !0;
1423
+ }, p.onmessage = (c) => {
1424
+ const u = mt(new Uint8Array(c.data));
1425
+ u && u.type === "inbox_event" && se();
1426
+ }, p.onclose = () => {
1427
+ p = null, ne();
1428
+ }, p.onerror = () => {
1429
+ try {
1430
+ p == null || p.close();
1431
+ } catch {
1432
+ }
1433
+ };
1434
+ }
1435
+ }, ne = () => {
1436
+ if (B || A) return;
1437
+ const c = Math.min(15e3, 500 * 2 ** ee++) + Math.random() * 250;
1438
+ A = setTimeout(() => {
1439
+ A = void 0, ie();
1440
+ }, c);
1441
+ };
1442
+ return ie(), {
1443
+ refresh: M,
1444
+ close() {
1445
+ B = !0, A && clearTimeout(A), T && clearTimeout(T), U == null || U.disconnect(), U = null;
1446
+ try {
1447
+ p == null || p.close();
1448
+ } catch {
1449
+ }
1450
+ p = null, s.el.replaceChildren();
1451
+ },
1452
+ defaultProfileId() {
1453
+ return s.profileId ?? X;
1454
+ }
1455
+ };
1456
+ }
1457
+ export {
1458
+ bt as a,
1459
+ ce as b,
1460
+ Le as c,
1461
+ mt as d,
1462
+ he as e,
1463
+ Se as h,
1464
+ Et as i,
1465
+ ke as l,
1466
+ Bt as m,
1467
+ _e as p,
1468
+ de as r
1469
+ };
1470
+ //# sourceMappingURL=chatlist2.js.map