@paramms/chat-widget 1.0.30 → 1.0.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/e2e.js ADDED
@@ -0,0 +1,1608 @@
1
+ var O = Object.defineProperty;
2
+ var q = (n, e, t) => e in n ? O(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
+ var r = (n, e, t) => q(n, typeof e != "symbol" ? e + "" : e, t);
4
+ const V = (n) => n, Ve = (n) => n, Xe = (n) => n, We = (n) => n, Ye = (n) => n, Je = (n) => n, Ge = (n) => n, Ze = (n) => n, Qe = V("anonymous");
5
+ function X(n) {
6
+ const e = n.length;
7
+ let t = 0, s = 0;
8
+ for (; s < e; ) {
9
+ let i = n.charCodeAt(s++);
10
+ if (i & 4294967168)
11
+ if (!(i & 4294965248))
12
+ t += 2;
13
+ else {
14
+ if (i >= 55296 && i <= 56319 && s < e) {
15
+ const a = n.charCodeAt(s);
16
+ (a & 64512) === 56320 && (++s, i = ((i & 1023) << 10) + (a & 1023) + 65536);
17
+ }
18
+ i & 4294901760 ? t += 4 : t += 3;
19
+ }
20
+ else {
21
+ t++;
22
+ continue;
23
+ }
24
+ }
25
+ return t;
26
+ }
27
+ function W(n, e, t) {
28
+ const s = n.length;
29
+ let i = t, a = 0;
30
+ for (; a < s; ) {
31
+ let o = n.charCodeAt(a++);
32
+ if (o & 4294967168)
33
+ if (!(o & 4294965248))
34
+ e[i++] = o >> 6 & 31 | 192;
35
+ else {
36
+ if (o >= 55296 && o <= 56319 && a < s) {
37
+ const h = n.charCodeAt(a);
38
+ (h & 64512) === 56320 && (++a, o = ((o & 1023) << 10) + (h & 1023) + 65536);
39
+ }
40
+ o & 4294901760 ? (e[i++] = o >> 18 & 7 | 240, e[i++] = o >> 12 & 63 | 128, e[i++] = o >> 6 & 63 | 128) : (e[i++] = o >> 12 & 15 | 224, e[i++] = o >> 6 & 63 | 128);
41
+ }
42
+ else {
43
+ e[i++] = o;
44
+ continue;
45
+ }
46
+ e[i++] = o & 63 | 128;
47
+ }
48
+ }
49
+ const Y = new TextEncoder(), J = 50;
50
+ function G(n, e, t) {
51
+ Y.encodeInto(n, e.subarray(t));
52
+ }
53
+ function Z(n, e, t) {
54
+ n.length > J ? G(n, e, t) : W(n, e, t);
55
+ }
56
+ const Q = 4096;
57
+ function z(n, e, t) {
58
+ let s = e;
59
+ const i = s + t, a = [];
60
+ let o = "";
61
+ for (; s < i; ) {
62
+ const h = n[s++];
63
+ if (!(h & 128))
64
+ a.push(h);
65
+ else if ((h & 224) === 192) {
66
+ const d = n[s++] & 63;
67
+ a.push((h & 31) << 6 | d);
68
+ } else if ((h & 240) === 224) {
69
+ const d = n[s++] & 63, f = n[s++] & 63;
70
+ a.push((h & 31) << 12 | d << 6 | f);
71
+ } else if ((h & 248) === 240) {
72
+ const d = n[s++] & 63, f = n[s++] & 63, x = n[s++] & 63;
73
+ let u = (h & 7) << 18 | d << 12 | f << 6 | x;
74
+ u > 65535 && (u -= 65536, a.push(u >>> 10 & 1023 | 55296), u = 56320 | u & 1023), a.push(u);
75
+ } else
76
+ a.push(h);
77
+ a.length >= Q && (o += String.fromCharCode(...a), a.length = 0);
78
+ }
79
+ return a.length > 0 && (o += String.fromCharCode(...a)), o;
80
+ }
81
+ const j = new TextDecoder(), ee = 200;
82
+ function te(n, e, t) {
83
+ const s = n.subarray(e, e + t);
84
+ return j.decode(s);
85
+ }
86
+ function se(n, e, t) {
87
+ return t > ee ? te(n, e, t) : z(n, e, t);
88
+ }
89
+ class I {
90
+ constructor(e, t) {
91
+ r(this, "type");
92
+ r(this, "data");
93
+ this.type = e, this.data = t;
94
+ }
95
+ }
96
+ class l extends Error {
97
+ constructor(e) {
98
+ super(e);
99
+ const t = Object.create(l.prototype);
100
+ Object.setPrototypeOf(this, t), Object.defineProperty(this, "name", {
101
+ configurable: !0,
102
+ enumerable: !1,
103
+ value: l.name
104
+ });
105
+ }
106
+ }
107
+ const p = 4294967295;
108
+ function ie(n, e, t) {
109
+ const s = t / 4294967296, i = t;
110
+ n.setUint32(e, s), n.setUint32(e + 4, i);
111
+ }
112
+ function H(n, e, t) {
113
+ const s = Math.floor(t / 4294967296), i = t;
114
+ n.setUint32(e, s), n.setUint32(e + 4, i);
115
+ }
116
+ function F(n, e) {
117
+ const t = n.getInt32(e), s = n.getUint32(e + 4);
118
+ return t * 4294967296 + s;
119
+ }
120
+ function ne(n, e) {
121
+ const t = n.getUint32(e), s = n.getUint32(e + 4);
122
+ return t * 4294967296 + s;
123
+ }
124
+ const re = -1, ae = 4294967296 - 1, oe = 17179869184 - 1;
125
+ function he({ sec: n, nsec: e }) {
126
+ if (n >= 0 && e >= 0 && n <= oe)
127
+ if (e === 0 && n <= ae) {
128
+ const t = new Uint8Array(4);
129
+ return new DataView(t.buffer).setUint32(0, n), t;
130
+ } else {
131
+ const t = n / 4294967296, s = n & 4294967295, i = new Uint8Array(8), a = new DataView(i.buffer);
132
+ return a.setUint32(0, e << 2 | t & 3), a.setUint32(4, s), i;
133
+ }
134
+ else {
135
+ const t = new Uint8Array(12), s = new DataView(t.buffer);
136
+ return s.setUint32(0, e), H(s, 4, n), t;
137
+ }
138
+ }
139
+ function ce(n) {
140
+ const e = n.getTime(), t = Math.floor(e / 1e3), s = (e - t * 1e3) * 1e6, i = Math.floor(s / 1e9);
141
+ return {
142
+ sec: t + i,
143
+ nsec: s - i * 1e9
144
+ };
145
+ }
146
+ function de(n) {
147
+ if (n instanceof Date) {
148
+ const e = ce(n);
149
+ return he(e);
150
+ } else
151
+ return null;
152
+ }
153
+ function le(n) {
154
+ const e = new DataView(n.buffer, n.byteOffset, n.byteLength);
155
+ switch (n.byteLength) {
156
+ case 4:
157
+ return { sec: e.getUint32(0), nsec: 0 };
158
+ case 8: {
159
+ const t = e.getUint32(0), s = e.getUint32(4), i = (t & 3) * 4294967296 + s, a = t >>> 2;
160
+ return { sec: i, nsec: a };
161
+ }
162
+ case 12: {
163
+ const t = F(e, 4), s = e.getUint32(0);
164
+ return { sec: t, nsec: s };
165
+ }
166
+ default:
167
+ throw new l(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${n.length}`);
168
+ }
169
+ }
170
+ function ue(n) {
171
+ const e = le(n);
172
+ return new Date(e.sec * 1e3 + e.nsec / 1e6);
173
+ }
174
+ const fe = {
175
+ type: re,
176
+ encode: de,
177
+ decode: ue
178
+ }, k = class k {
179
+ constructor() {
180
+ // ensures ExtensionCodecType<X> matches ExtensionCodec<X>
181
+ // this will make type errors a lot more clear
182
+ // eslint-disable-next-line @typescript-eslint/naming-convention
183
+ r(this, "__brand");
184
+ // built-in extensions
185
+ r(this, "builtInEncoders", []);
186
+ r(this, "builtInDecoders", []);
187
+ // custom extensions
188
+ r(this, "encoders", []);
189
+ r(this, "decoders", []);
190
+ this.register(fe);
191
+ }
192
+ register({ type: e, encode: t, decode: s }) {
193
+ if (e >= 0)
194
+ this.encoders[e] = t, this.decoders[e] = s;
195
+ else {
196
+ const i = -1 - e;
197
+ this.builtInEncoders[i] = t, this.builtInDecoders[i] = s;
198
+ }
199
+ }
200
+ tryToEncode(e, t) {
201
+ for (let s = 0; s < this.builtInEncoders.length; s++) {
202
+ const i = this.builtInEncoders[s];
203
+ if (i != null) {
204
+ const a = i(e, t);
205
+ if (a != null) {
206
+ const o = -1 - s;
207
+ return new I(o, a);
208
+ }
209
+ }
210
+ }
211
+ for (let s = 0; s < this.encoders.length; s++) {
212
+ const i = this.encoders[s];
213
+ if (i != null) {
214
+ const a = i(e, t);
215
+ if (a != null) {
216
+ const o = s;
217
+ return new I(o, a);
218
+ }
219
+ }
220
+ }
221
+ return e instanceof I ? e : null;
222
+ }
223
+ decode(e, t, s) {
224
+ const i = t < 0 ? this.builtInDecoders[-1 - t] : this.decoders[t];
225
+ return i ? i(e, t, s) : new I(t, e);
226
+ }
227
+ };
228
+ r(k, "defaultCodec", new k());
229
+ let v = k;
230
+ function ye(n) {
231
+ return n instanceof ArrayBuffer || typeof SharedArrayBuffer < "u" && n instanceof SharedArrayBuffer;
232
+ }
233
+ function B(n) {
234
+ return n instanceof Uint8Array ? n : ArrayBuffer.isView(n) ? new Uint8Array(n.buffer, n.byteOffset, n.byteLength) : ye(n) ? new Uint8Array(n) : Uint8Array.from(n);
235
+ }
236
+ const we = 100, xe = 2048;
237
+ class P {
238
+ constructor(e) {
239
+ r(this, "extensionCodec");
240
+ r(this, "context");
241
+ r(this, "useBigInt64");
242
+ r(this, "maxDepth");
243
+ r(this, "initialBufferSize");
244
+ r(this, "sortKeys");
245
+ r(this, "forceFloat32");
246
+ r(this, "ignoreUndefined");
247
+ r(this, "forceIntegerToFloat");
248
+ r(this, "pos");
249
+ r(this, "view");
250
+ r(this, "bytes");
251
+ r(this, "entered", !1);
252
+ this.extensionCodec = (e == null ? void 0 : e.extensionCodec) ?? v.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) ?? we, this.initialBufferSize = (e == null ? void 0 : e.initialBufferSize) ?? xe, 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);
253
+ }
254
+ clone() {
255
+ return new P({
256
+ extensionCodec: this.extensionCodec,
257
+ context: this.context,
258
+ useBigInt64: this.useBigInt64,
259
+ maxDepth: this.maxDepth,
260
+ initialBufferSize: this.initialBufferSize,
261
+ sortKeys: this.sortKeys,
262
+ forceFloat32: this.forceFloat32,
263
+ ignoreUndefined: this.ignoreUndefined,
264
+ forceIntegerToFloat: this.forceIntegerToFloat
265
+ });
266
+ }
267
+ reinitializeState() {
268
+ this.pos = 0;
269
+ }
270
+ /**
271
+ * 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}.
272
+ *
273
+ * @returns Encodes the object and returns a shared reference the encoder's internal buffer.
274
+ */
275
+ encodeSharedRef(e) {
276
+ if (this.entered)
277
+ return this.clone().encodeSharedRef(e);
278
+ try {
279
+ return this.entered = !0, this.reinitializeState(), this.doEncode(e, 1), this.bytes.subarray(0, this.pos);
280
+ } finally {
281
+ this.entered = !1;
282
+ }
283
+ }
284
+ /**
285
+ * @returns Encodes the object and returns a copy of the encoder's internal buffer.
286
+ */
287
+ encode(e) {
288
+ if (this.entered)
289
+ return this.clone().encode(e);
290
+ try {
291
+ return this.entered = !0, this.reinitializeState(), this.doEncode(e, 1), this.bytes.slice(0, this.pos);
292
+ } finally {
293
+ this.entered = !1;
294
+ }
295
+ }
296
+ doEncode(e, t) {
297
+ if (t > this.maxDepth)
298
+ throw new Error(`Too deep objects in depth ${t}`);
299
+ 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);
300
+ }
301
+ ensureBufferSizeToWrite(e) {
302
+ const t = this.pos + e;
303
+ this.view.byteLength < t && this.resizeBuffer(t * 2);
304
+ }
305
+ resizeBuffer(e) {
306
+ const t = new ArrayBuffer(e), s = new Uint8Array(t), i = new DataView(t);
307
+ s.set(this.bytes), this.view = i, this.bytes = s;
308
+ }
309
+ encodeNil() {
310
+ this.writeU8(192);
311
+ }
312
+ encodeBoolean(e) {
313
+ e === !1 ? this.writeU8(194) : this.writeU8(195);
314
+ }
315
+ encodeNumber(e) {
316
+ !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);
317
+ }
318
+ encodeNumberAsFloat(e) {
319
+ this.forceFloat32 ? (this.writeU8(202), this.writeF32(e)) : (this.writeU8(203), this.writeF64(e));
320
+ }
321
+ encodeBigInt64(e) {
322
+ e >= BigInt(0) ? (this.writeU8(207), this.writeBigUint64(e)) : (this.writeU8(211), this.writeBigInt64(e));
323
+ }
324
+ writeStringHeader(e) {
325
+ if (e < 32)
326
+ this.writeU8(160 + e);
327
+ else if (e < 256)
328
+ this.writeU8(217), this.writeU8(e);
329
+ else if (e < 65536)
330
+ this.writeU8(218), this.writeU16(e);
331
+ else if (e < 4294967296)
332
+ this.writeU8(219), this.writeU32(e);
333
+ else
334
+ throw new Error(`Too long string: ${e} bytes in UTF-8`);
335
+ }
336
+ encodeString(e) {
337
+ const s = X(e);
338
+ this.ensureBufferSizeToWrite(5 + s), this.writeStringHeader(s), Z(e, this.bytes, this.pos), this.pos += s;
339
+ }
340
+ encodeObject(e, t) {
341
+ const s = this.extensionCodec.tryToEncode(e, this.context);
342
+ if (s != null)
343
+ this.encodeExtension(s);
344
+ else if (Array.isArray(e))
345
+ this.encodeArray(e, t);
346
+ else if (ArrayBuffer.isView(e))
347
+ this.encodeBinary(e);
348
+ else if (typeof e == "object")
349
+ this.encodeMap(e, t);
350
+ else
351
+ throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`);
352
+ }
353
+ encodeBinary(e) {
354
+ const t = e.byteLength;
355
+ if (t < 256)
356
+ this.writeU8(196), this.writeU8(t);
357
+ else if (t < 65536)
358
+ this.writeU8(197), this.writeU16(t);
359
+ else if (t < 4294967296)
360
+ this.writeU8(198), this.writeU32(t);
361
+ else
362
+ throw new Error(`Too large binary: ${t}`);
363
+ const s = B(e);
364
+ this.writeU8a(s);
365
+ }
366
+ encodeArray(e, t) {
367
+ const s = e.length;
368
+ if (s < 16)
369
+ this.writeU8(144 + s);
370
+ else if (s < 65536)
371
+ this.writeU8(220), this.writeU16(s);
372
+ else if (s < 4294967296)
373
+ this.writeU8(221), this.writeU32(s);
374
+ else
375
+ throw new Error(`Too large array: ${s}`);
376
+ for (const i of e)
377
+ this.doEncode(i, t + 1);
378
+ }
379
+ countWithoutUndefined(e, t) {
380
+ let s = 0;
381
+ for (const i of t)
382
+ e[i] !== void 0 && s++;
383
+ return s;
384
+ }
385
+ encodeMap(e, t) {
386
+ const s = Object.keys(e);
387
+ this.sortKeys && s.sort();
388
+ const i = this.ignoreUndefined ? this.countWithoutUndefined(e, s) : s.length;
389
+ if (i < 16)
390
+ this.writeU8(128 + i);
391
+ else if (i < 65536)
392
+ this.writeU8(222), this.writeU16(i);
393
+ else if (i < 4294967296)
394
+ this.writeU8(223), this.writeU32(i);
395
+ else
396
+ throw new Error(`Too large map object: ${i}`);
397
+ for (const a of s) {
398
+ const o = e[a];
399
+ this.ignoreUndefined && o === void 0 || (this.encodeString(a), this.doEncode(o, t + 1));
400
+ }
401
+ }
402
+ encodeExtension(e) {
403
+ if (typeof e.data == "function") {
404
+ const s = e.data(this.pos + 6), i = s.length;
405
+ if (i >= 4294967296)
406
+ throw new Error(`Too large extension object: ${i}`);
407
+ this.writeU8(201), this.writeU32(i), this.writeI8(e.type), this.writeU8a(s);
408
+ return;
409
+ }
410
+ const t = e.data.length;
411
+ if (t === 1)
412
+ this.writeU8(212);
413
+ else if (t === 2)
414
+ this.writeU8(213);
415
+ else if (t === 4)
416
+ this.writeU8(214);
417
+ else if (t === 8)
418
+ this.writeU8(215);
419
+ else if (t === 16)
420
+ this.writeU8(216);
421
+ else if (t < 256)
422
+ this.writeU8(199), this.writeU8(t);
423
+ else if (t < 65536)
424
+ this.writeU8(200), this.writeU16(t);
425
+ else if (t < 4294967296)
426
+ this.writeU8(201), this.writeU32(t);
427
+ else
428
+ throw new Error(`Too large extension object: ${t}`);
429
+ this.writeI8(e.type), this.writeU8a(e.data);
430
+ }
431
+ writeU8(e) {
432
+ this.ensureBufferSizeToWrite(1), this.view.setUint8(this.pos, e), this.pos++;
433
+ }
434
+ writeU8a(e) {
435
+ const t = e.length;
436
+ this.ensureBufferSizeToWrite(t), this.bytes.set(e, this.pos), this.pos += t;
437
+ }
438
+ writeI8(e) {
439
+ this.ensureBufferSizeToWrite(1), this.view.setInt8(this.pos, e), this.pos++;
440
+ }
441
+ writeU16(e) {
442
+ this.ensureBufferSizeToWrite(2), this.view.setUint16(this.pos, e), this.pos += 2;
443
+ }
444
+ writeI16(e) {
445
+ this.ensureBufferSizeToWrite(2), this.view.setInt16(this.pos, e), this.pos += 2;
446
+ }
447
+ writeU32(e) {
448
+ this.ensureBufferSizeToWrite(4), this.view.setUint32(this.pos, e), this.pos += 4;
449
+ }
450
+ writeI32(e) {
451
+ this.ensureBufferSizeToWrite(4), this.view.setInt32(this.pos, e), this.pos += 4;
452
+ }
453
+ writeF32(e) {
454
+ this.ensureBufferSizeToWrite(4), this.view.setFloat32(this.pos, e), this.pos += 4;
455
+ }
456
+ writeF64(e) {
457
+ this.ensureBufferSizeToWrite(8), this.view.setFloat64(this.pos, e), this.pos += 8;
458
+ }
459
+ writeU64(e) {
460
+ this.ensureBufferSizeToWrite(8), ie(this.view, this.pos, e), this.pos += 8;
461
+ }
462
+ writeI64(e) {
463
+ this.ensureBufferSizeToWrite(8), H(this.view, this.pos, e), this.pos += 8;
464
+ }
465
+ writeBigUint64(e) {
466
+ this.ensureBufferSizeToWrite(8), this.view.setBigUint64(this.pos, e), this.pos += 8;
467
+ }
468
+ writeBigInt64(e) {
469
+ this.ensureBufferSizeToWrite(8), this.view.setBigInt64(this.pos, e), this.pos += 8;
470
+ }
471
+ }
472
+ function ge(n, e) {
473
+ return new P(e).encodeSharedRef(n);
474
+ }
475
+ function E(n) {
476
+ return `${n < 0 ? "-" : ""}0x${Math.abs(n).toString(16).padStart(2, "0")}`;
477
+ }
478
+ const pe = 16, me = 16;
479
+ class Se {
480
+ constructor(e = pe, t = me) {
481
+ r(this, "hit", 0);
482
+ r(this, "miss", 0);
483
+ r(this, "caches");
484
+ r(this, "maxKeyLength");
485
+ r(this, "maxLengthPerKey");
486
+ this.maxKeyLength = e, this.maxLengthPerKey = t, this.caches = [];
487
+ for (let s = 0; s < this.maxKeyLength; s++)
488
+ this.caches.push([]);
489
+ }
490
+ canBeCached(e) {
491
+ return e > 0 && e <= this.maxKeyLength;
492
+ }
493
+ find(e, t, s) {
494
+ const i = this.caches[s - 1];
495
+ e: for (const a of i) {
496
+ const o = a.bytes;
497
+ for (let h = 0; h < s; h++)
498
+ if (o[h] !== e[t + h])
499
+ continue e;
500
+ return a.str;
501
+ }
502
+ return null;
503
+ }
504
+ store(e, t) {
505
+ const s = this.caches[e.length - 1], i = { bytes: e, str: t };
506
+ s.length >= this.maxLengthPerKey ? s[Math.random() * s.length | 0] = i : s.push(i);
507
+ }
508
+ decode(e, t, s) {
509
+ const i = this.find(e, t, s);
510
+ if (i != null)
511
+ return this.hit++, i;
512
+ this.miss++;
513
+ const a = z(e, t, s), o = Uint8Array.prototype.slice.call(e, t, t + s);
514
+ return this.store(o, a), a;
515
+ }
516
+ }
517
+ const b = "array", S = "map_key", R = "map_value", Ue = (n) => {
518
+ if (typeof n == "string" || typeof n == "number")
519
+ return n;
520
+ throw new l("The type of key must be string or number but " + typeof n);
521
+ };
522
+ class Ie {
523
+ constructor() {
524
+ r(this, "stack", []);
525
+ r(this, "stackHeadPosition", -1);
526
+ }
527
+ get length() {
528
+ return this.stackHeadPosition + 1;
529
+ }
530
+ top() {
531
+ return this.stack[this.stackHeadPosition];
532
+ }
533
+ pushArrayState(e) {
534
+ const t = this.getUninitializedStateFromPool();
535
+ t.type = b, t.position = 0, t.size = e, t.array = new Array(e);
536
+ }
537
+ pushMapState(e) {
538
+ const t = this.getUninitializedStateFromPool();
539
+ t.type = S, t.readCount = 0, t.size = e, t.map = {};
540
+ }
541
+ getUninitializedStateFromPool() {
542
+ if (this.stackHeadPosition++, this.stackHeadPosition === this.stack.length) {
543
+ const e = {
544
+ type: void 0,
545
+ size: 0,
546
+ array: void 0,
547
+ position: 0,
548
+ readCount: 0,
549
+ map: void 0,
550
+ key: null
551
+ };
552
+ this.stack.push(e);
553
+ }
554
+ return this.stack[this.stackHeadPosition];
555
+ }
556
+ release(e) {
557
+ if (this.stack[this.stackHeadPosition] !== e)
558
+ throw new Error("Invalid stack state. Released state is not on top of the stack.");
559
+ if (e.type === b) {
560
+ const s = e;
561
+ s.size = 0, s.array = void 0, s.position = 0, s.type = void 0;
562
+ }
563
+ if (e.type === S || e.type === R) {
564
+ const s = e;
565
+ s.size = 0, s.map = void 0, s.readCount = 0, s.type = void 0;
566
+ }
567
+ this.stackHeadPosition--;
568
+ }
569
+ reset() {
570
+ this.stack.length = 0, this.stackHeadPosition = -1;
571
+ }
572
+ }
573
+ const m = -1, T = new DataView(new ArrayBuffer(0)), ve = new Uint8Array(T.buffer);
574
+ try {
575
+ T.getInt8(0);
576
+ } catch (n) {
577
+ if (!(n instanceof RangeError))
578
+ throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access");
579
+ }
580
+ const D = new RangeError("Insufficient data"), Ke = new Se();
581
+ class C {
582
+ constructor(e) {
583
+ r(this, "extensionCodec");
584
+ r(this, "context");
585
+ r(this, "useBigInt64");
586
+ r(this, "rawStrings");
587
+ r(this, "maxStrLength");
588
+ r(this, "maxBinLength");
589
+ r(this, "maxArrayLength");
590
+ r(this, "maxMapLength");
591
+ r(this, "maxExtLength");
592
+ r(this, "keyDecoder");
593
+ r(this, "mapKeyConverter");
594
+ r(this, "totalPos", 0);
595
+ r(this, "pos", 0);
596
+ r(this, "view", T);
597
+ r(this, "bytes", ve);
598
+ r(this, "headByte", m);
599
+ r(this, "stack", new Ie());
600
+ r(this, "entered", !1);
601
+ this.extensionCodec = (e == null ? void 0 : e.extensionCodec) ?? v.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) ?? p, this.maxBinLength = (e == null ? void 0 : e.maxBinLength) ?? p, this.maxArrayLength = (e == null ? void 0 : e.maxArrayLength) ?? p, this.maxMapLength = (e == null ? void 0 : e.maxMapLength) ?? p, this.maxExtLength = (e == null ? void 0 : e.maxExtLength) ?? p, this.keyDecoder = (e == null ? void 0 : e.keyDecoder) !== void 0 ? e.keyDecoder : Ke, this.mapKeyConverter = (e == null ? void 0 : e.mapKeyConverter) ?? Ue;
602
+ }
603
+ clone() {
604
+ return new C({
605
+ extensionCodec: this.extensionCodec,
606
+ context: this.context,
607
+ useBigInt64: this.useBigInt64,
608
+ rawStrings: this.rawStrings,
609
+ maxStrLength: this.maxStrLength,
610
+ maxBinLength: this.maxBinLength,
611
+ maxArrayLength: this.maxArrayLength,
612
+ maxMapLength: this.maxMapLength,
613
+ maxExtLength: this.maxExtLength,
614
+ keyDecoder: this.keyDecoder
615
+ });
616
+ }
617
+ reinitializeState() {
618
+ this.totalPos = 0, this.headByte = m, this.stack.reset();
619
+ }
620
+ setBuffer(e) {
621
+ const t = B(e);
622
+ this.bytes = t, this.view = new DataView(t.buffer, t.byteOffset, t.byteLength), this.pos = 0;
623
+ }
624
+ appendBuffer(e) {
625
+ if (this.headByte === m && !this.hasRemaining(1))
626
+ this.setBuffer(e);
627
+ else {
628
+ const t = this.bytes.subarray(this.pos), s = B(e), i = new Uint8Array(t.length + s.length);
629
+ i.set(t), i.set(s, t.length), this.setBuffer(i);
630
+ }
631
+ }
632
+ hasRemaining(e) {
633
+ return this.view.byteLength - this.pos >= e;
634
+ }
635
+ createExtraByteError(e) {
636
+ const { view: t, pos: s } = this;
637
+ return new RangeError(`Extra ${t.byteLength - s} of ${t.byteLength} byte(s) found at buffer[${e}]`);
638
+ }
639
+ /**
640
+ * @throws {@link DecodeError}
641
+ * @throws {@link RangeError}
642
+ */
643
+ decode(e) {
644
+ if (this.entered)
645
+ return this.clone().decode(e);
646
+ try {
647
+ this.entered = !0, this.reinitializeState(), this.setBuffer(e);
648
+ const t = this.doDecodeSync();
649
+ if (this.hasRemaining(1))
650
+ throw this.createExtraByteError(this.pos);
651
+ return t;
652
+ } finally {
653
+ this.entered = !1;
654
+ }
655
+ }
656
+ *decodeMulti(e) {
657
+ if (this.entered) {
658
+ yield* this.clone().decodeMulti(e);
659
+ return;
660
+ }
661
+ try {
662
+ for (this.entered = !0, this.reinitializeState(), this.setBuffer(e); this.hasRemaining(1); )
663
+ yield this.doDecodeSync();
664
+ } finally {
665
+ this.entered = !1;
666
+ }
667
+ }
668
+ async decodeAsync(e) {
669
+ if (this.entered)
670
+ return this.clone().decodeAsync(e);
671
+ try {
672
+ this.entered = !0;
673
+ let t = !1, s;
674
+ for await (const h of e) {
675
+ if (t)
676
+ throw this.entered = !1, this.createExtraByteError(this.totalPos);
677
+ this.appendBuffer(h);
678
+ try {
679
+ s = this.doDecodeSync(), t = !0;
680
+ } catch (d) {
681
+ if (!(d instanceof RangeError))
682
+ throw d;
683
+ }
684
+ this.totalPos += this.pos;
685
+ }
686
+ if (t) {
687
+ if (this.hasRemaining(1))
688
+ throw this.createExtraByteError(this.totalPos);
689
+ return s;
690
+ }
691
+ const { headByte: i, pos: a, totalPos: o } = this;
692
+ throw new RangeError(`Insufficient data in parsing ${E(i)} at ${o} (${a} in the current buffer)`);
693
+ } finally {
694
+ this.entered = !1;
695
+ }
696
+ }
697
+ decodeArrayStream(e) {
698
+ return this.decodeMultiAsync(e, !0);
699
+ }
700
+ decodeStream(e) {
701
+ return this.decodeMultiAsync(e, !1);
702
+ }
703
+ async *decodeMultiAsync(e, t) {
704
+ if (this.entered) {
705
+ yield* this.clone().decodeMultiAsync(e, t);
706
+ return;
707
+ }
708
+ try {
709
+ this.entered = !0;
710
+ let s = t, i = -1;
711
+ for await (const a of e) {
712
+ if (t && i === 0)
713
+ throw this.createExtraByteError(this.totalPos);
714
+ this.appendBuffer(a), s && (i = this.readArraySize(), s = !1, this.complete());
715
+ try {
716
+ for (; yield this.doDecodeSync(), --i !== 0; )
717
+ ;
718
+ } catch (o) {
719
+ if (!(o instanceof RangeError))
720
+ throw o;
721
+ }
722
+ this.totalPos += this.pos;
723
+ }
724
+ } finally {
725
+ this.entered = !1;
726
+ }
727
+ }
728
+ doDecodeSync() {
729
+ e: for (; ; ) {
730
+ const e = this.readHeadByte();
731
+ let t;
732
+ if (e >= 224)
733
+ t = e - 256;
734
+ else if (e < 192)
735
+ if (e < 128)
736
+ t = e;
737
+ else if (e < 144) {
738
+ const i = e - 128;
739
+ if (i !== 0) {
740
+ this.pushMapState(i), this.complete();
741
+ continue e;
742
+ } else
743
+ t = {};
744
+ } else if (e < 160) {
745
+ const i = e - 144;
746
+ if (i !== 0) {
747
+ this.pushArrayState(i), this.complete();
748
+ continue e;
749
+ } else
750
+ t = [];
751
+ } else {
752
+ const i = e - 160;
753
+ t = this.decodeString(i, 0);
754
+ }
755
+ else if (e === 192)
756
+ t = null;
757
+ else if (e === 194)
758
+ t = !1;
759
+ else if (e === 195)
760
+ t = !0;
761
+ else if (e === 202)
762
+ t = this.readF32();
763
+ else if (e === 203)
764
+ t = this.readF64();
765
+ else if (e === 204)
766
+ t = this.readU8();
767
+ else if (e === 205)
768
+ t = this.readU16();
769
+ else if (e === 206)
770
+ t = this.readU32();
771
+ else if (e === 207)
772
+ this.useBigInt64 ? t = this.readU64AsBigInt() : t = this.readU64();
773
+ else if (e === 208)
774
+ t = this.readI8();
775
+ else if (e === 209)
776
+ t = this.readI16();
777
+ else if (e === 210)
778
+ t = this.readI32();
779
+ else if (e === 211)
780
+ this.useBigInt64 ? t = this.readI64AsBigInt() : t = this.readI64();
781
+ else if (e === 217) {
782
+ const i = this.lookU8();
783
+ t = this.decodeString(i, 1);
784
+ } else if (e === 218) {
785
+ const i = this.lookU16();
786
+ t = this.decodeString(i, 2);
787
+ } else if (e === 219) {
788
+ const i = this.lookU32();
789
+ t = this.decodeString(i, 4);
790
+ } else if (e === 220) {
791
+ const i = this.readU16();
792
+ if (i !== 0) {
793
+ this.pushArrayState(i), this.complete();
794
+ continue e;
795
+ } else
796
+ t = [];
797
+ } else if (e === 221) {
798
+ const i = this.readU32();
799
+ if (i !== 0) {
800
+ this.pushArrayState(i), this.complete();
801
+ continue e;
802
+ } else
803
+ t = [];
804
+ } else if (e === 222) {
805
+ const i = this.readU16();
806
+ if (i !== 0) {
807
+ this.pushMapState(i), this.complete();
808
+ continue e;
809
+ } else
810
+ t = {};
811
+ } else if (e === 223) {
812
+ const i = this.readU32();
813
+ if (i !== 0) {
814
+ this.pushMapState(i), this.complete();
815
+ continue e;
816
+ } else
817
+ t = {};
818
+ } else if (e === 196) {
819
+ const i = this.lookU8();
820
+ t = this.decodeBinary(i, 1);
821
+ } else if (e === 197) {
822
+ const i = this.lookU16();
823
+ t = this.decodeBinary(i, 2);
824
+ } else if (e === 198) {
825
+ const i = this.lookU32();
826
+ t = this.decodeBinary(i, 4);
827
+ } else if (e === 212)
828
+ t = this.decodeExtension(1, 0);
829
+ else if (e === 213)
830
+ t = this.decodeExtension(2, 0);
831
+ else if (e === 214)
832
+ t = this.decodeExtension(4, 0);
833
+ else if (e === 215)
834
+ t = this.decodeExtension(8, 0);
835
+ else if (e === 216)
836
+ t = this.decodeExtension(16, 0);
837
+ else if (e === 199) {
838
+ const i = this.lookU8();
839
+ t = this.decodeExtension(i, 1);
840
+ } else if (e === 200) {
841
+ const i = this.lookU16();
842
+ t = this.decodeExtension(i, 2);
843
+ } else if (e === 201) {
844
+ const i = this.lookU32();
845
+ t = this.decodeExtension(i, 4);
846
+ } else
847
+ throw new l(`Unrecognized type byte: ${E(e)}`);
848
+ this.complete();
849
+ const s = this.stack;
850
+ for (; s.length > 0; ) {
851
+ const i = s.top();
852
+ if (i.type === b)
853
+ if (i.array[i.position] = t, i.position++, i.position === i.size)
854
+ t = i.array, s.release(i);
855
+ else
856
+ continue e;
857
+ else if (i.type === S) {
858
+ if (t === "__proto__")
859
+ throw new l("The key __proto__ is not allowed");
860
+ i.key = this.mapKeyConverter(t), i.type = R;
861
+ continue e;
862
+ } else if (i.map[i.key] = t, i.readCount++, i.readCount === i.size)
863
+ t = i.map, s.release(i);
864
+ else {
865
+ i.key = null, i.type = S;
866
+ continue e;
867
+ }
868
+ }
869
+ return t;
870
+ }
871
+ }
872
+ readHeadByte() {
873
+ return this.headByte === m && (this.headByte = this.readU8()), this.headByte;
874
+ }
875
+ complete() {
876
+ this.headByte = m;
877
+ }
878
+ readArraySize() {
879
+ const e = this.readHeadByte();
880
+ switch (e) {
881
+ case 220:
882
+ return this.readU16();
883
+ case 221:
884
+ return this.readU32();
885
+ default: {
886
+ if (e < 160)
887
+ return e - 144;
888
+ throw new l(`Unrecognized array type byte: ${E(e)}`);
889
+ }
890
+ }
891
+ }
892
+ pushMapState(e) {
893
+ if (e > this.maxMapLength)
894
+ throw new l(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);
895
+ this.stack.pushMapState(e);
896
+ }
897
+ pushArrayState(e) {
898
+ if (e > this.maxArrayLength)
899
+ throw new l(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);
900
+ this.stack.pushArrayState(e);
901
+ }
902
+ decodeString(e, t) {
903
+ return !this.rawStrings || this.stateIsMapKey() ? this.decodeUtf8String(e, t) : this.decodeBinary(e, t);
904
+ }
905
+ /**
906
+ * @throws {@link RangeError}
907
+ */
908
+ decodeUtf8String(e, t) {
909
+ var a;
910
+ if (e > this.maxStrLength)
911
+ throw new l(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);
912
+ if (this.bytes.byteLength < this.pos + t + e)
913
+ throw D;
914
+ const s = this.pos + t;
915
+ let i;
916
+ return this.stateIsMapKey() && ((a = this.keyDecoder) != null && a.canBeCached(e)) ? i = this.keyDecoder.decode(this.bytes, s, e) : i = se(this.bytes, s, e), this.pos += t + e, i;
917
+ }
918
+ stateIsMapKey() {
919
+ return this.stack.length > 0 ? this.stack.top().type === S : !1;
920
+ }
921
+ /**
922
+ * @throws {@link RangeError}
923
+ */
924
+ decodeBinary(e, t) {
925
+ if (e > this.maxBinLength)
926
+ throw new l(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);
927
+ if (!this.hasRemaining(e + t))
928
+ throw D;
929
+ const s = this.pos + t, i = this.bytes.subarray(s, s + e);
930
+ return this.pos += t + e, i;
931
+ }
932
+ decodeExtension(e, t) {
933
+ if (e > this.maxExtLength)
934
+ throw new l(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);
935
+ const s = this.view.getInt8(this.pos + t), i = this.decodeBinary(
936
+ e,
937
+ t + 1
938
+ /* extType */
939
+ );
940
+ return this.extensionCodec.decode(i, s, this.context);
941
+ }
942
+ lookU8() {
943
+ return this.view.getUint8(this.pos);
944
+ }
945
+ lookU16() {
946
+ return this.view.getUint16(this.pos);
947
+ }
948
+ lookU32() {
949
+ return this.view.getUint32(this.pos);
950
+ }
951
+ readU8() {
952
+ const e = this.view.getUint8(this.pos);
953
+ return this.pos++, e;
954
+ }
955
+ readI8() {
956
+ const e = this.view.getInt8(this.pos);
957
+ return this.pos++, e;
958
+ }
959
+ readU16() {
960
+ const e = this.view.getUint16(this.pos);
961
+ return this.pos += 2, e;
962
+ }
963
+ readI16() {
964
+ const e = this.view.getInt16(this.pos);
965
+ return this.pos += 2, e;
966
+ }
967
+ readU32() {
968
+ const e = this.view.getUint32(this.pos);
969
+ return this.pos += 4, e;
970
+ }
971
+ readI32() {
972
+ const e = this.view.getInt32(this.pos);
973
+ return this.pos += 4, e;
974
+ }
975
+ readU64() {
976
+ const e = ne(this.view, this.pos);
977
+ return this.pos += 8, e;
978
+ }
979
+ readI64() {
980
+ const e = F(this.view, this.pos);
981
+ return this.pos += 8, e;
982
+ }
983
+ readU64AsBigInt() {
984
+ const e = this.view.getBigUint64(this.pos);
985
+ return this.pos += 8, e;
986
+ }
987
+ readI64AsBigInt() {
988
+ const e = this.view.getBigInt64(this.pos);
989
+ return this.pos += 8, e;
990
+ }
991
+ readF32() {
992
+ const e = this.view.getFloat32(this.pos);
993
+ return this.pos += 4, e;
994
+ }
995
+ readF64() {
996
+ const e = this.view.getFloat64(this.pos);
997
+ return this.pos += 8, e;
998
+ }
999
+ }
1000
+ function ke(n, e) {
1001
+ return new C(e).decode(n);
1002
+ }
1003
+ const Ee = /* @__PURE__ */ new Set([
1004
+ "auth",
1005
+ "open",
1006
+ "send",
1007
+ "sync",
1008
+ "history",
1009
+ "read",
1010
+ "typing",
1011
+ "react",
1012
+ "edit",
1013
+ "delete",
1014
+ "invoke",
1015
+ "pubkey",
1016
+ "ping",
1017
+ "annotate",
1018
+ "annotate_clear",
1019
+ "uploadPrekeys",
1020
+ "fetchPrekey",
1021
+ "assign",
1022
+ "tag",
1023
+ "note",
1024
+ "agent_status",
1025
+ "subscribe_inbox",
1026
+ "unsubscribe_inbox"
1027
+ ]);
1028
+ function Be(n) {
1029
+ return Ee.has(n.type);
1030
+ }
1031
+ function be(n) {
1032
+ return ge(n);
1033
+ }
1034
+ function Ae(n) {
1035
+ let e;
1036
+ try {
1037
+ e = ke(n);
1038
+ } catch {
1039
+ return null;
1040
+ }
1041
+ return typeof e != "object" || e === null || typeof e.type != "string" ? null : e;
1042
+ }
1043
+ class je {
1044
+ constructor(e) {
1045
+ r(this, "socket", null);
1046
+ r(this, "state", "idle");
1047
+ r(this, "authed", !1);
1048
+ r(this, "everAuthed", !1);
1049
+ r(this, "attempt", 0);
1050
+ r(this, "outbox", []);
1051
+ r(this, "stopped", !1);
1052
+ r(this, "timer", null);
1053
+ r(this, "refreshing", !1);
1054
+ this.opts = e;
1055
+ }
1056
+ connect() {
1057
+ var s, i;
1058
+ if (this.state === "connecting" || this.state === "open") return;
1059
+ this.stopped = !1, this.state = "connecting", this.authed = !1, (i = (s = this.opts).onStatusChange) == null || i.call(s, this.attempt > 0 ? "reconnecting" : "connecting");
1060
+ const t = (this.opts.socketFactory ?? Ce)(this.opts.url);
1061
+ t.binaryType = "arraybuffer", this.socket = t, t.onopen = () => {
1062
+ this.raw({ type: "auth", token: this.opts.token });
1063
+ }, t.onmessage = (a) => {
1064
+ const o = Ae(new Uint8Array(a.data));
1065
+ !o || Be(o) || this.handle(o);
1066
+ }, t.onclose = () => this.onClosed(), t.onerror = () => {
1067
+ try {
1068
+ t.close();
1069
+ } catch {
1070
+ }
1071
+ };
1072
+ }
1073
+ /** Queue a frame; sent immediately if open, else flushed on (re)connect.
1074
+ * The outbox is bounded so a prolonged outage can't grow memory without limit
1075
+ * — oldest queued frames are dropped past the cap. */
1076
+ send(e) {
1077
+ if (this.state === "open" && this.authed) {
1078
+ this.raw(e);
1079
+ return;
1080
+ }
1081
+ const t = this.opts.maxOutbox ?? 1e3;
1082
+ this.outbox.length >= t && (this.outbox = this.outbox.slice(this.outbox.length - (t >> 1))), this.outbox.push(e);
1083
+ }
1084
+ close() {
1085
+ var e;
1086
+ this.stopped = !0, this.timer && clearTimeout(this.timer), this.state = "closed";
1087
+ try {
1088
+ (e = this.socket) == null || e.close();
1089
+ } catch {
1090
+ }
1091
+ }
1092
+ handle(e) {
1093
+ var t, s, i, a;
1094
+ if (e.type === "authed" && (this.attempt = 0, this.state = "open", this.authed = !0, this.everAuthed = !0, (s = (t = this.opts).onStatusChange) == null || s.call(t, "open"), this.raw(this.opts.open), this.flush()), e.type === "opened" && this.raw({ type: "sync", conversationId: e.conversation.id, sinceSeq: this.opts.getCursor() }), e.type === "error" && Pe.has(e.code)) {
1095
+ if (e.code === "UNAUTHORIZED" && this.opts.refreshToken && !this.refreshing) {
1096
+ this.refreshing = !0, (a = (i = this.opts).onStatusChange) == null || a.call(i, "reconnecting", "Renewing session…"), this.opts.refreshToken().then((o) => {
1097
+ var h;
1098
+ if (this.refreshing = !1, !o) {
1099
+ this.fatal(e);
1100
+ return;
1101
+ }
1102
+ this.opts.token = o;
1103
+ try {
1104
+ (h = this.socket) == null || h.close();
1105
+ } catch {
1106
+ }
1107
+ }).catch(() => {
1108
+ this.refreshing = !1, this.fatal(e);
1109
+ });
1110
+ return;
1111
+ }
1112
+ this.fatal(e);
1113
+ return;
1114
+ }
1115
+ this.opts.onFrame(e);
1116
+ }
1117
+ fatal(e) {
1118
+ var t, s, i;
1119
+ this.stopped = !0;
1120
+ try {
1121
+ (t = this.socket) == null || t.close();
1122
+ } catch {
1123
+ }
1124
+ this.state = "closed", (i = (s = this.opts).onStatusChange) == null || i.call(s, "error", Te(e.code)), this.opts.onFrame(e);
1125
+ }
1126
+ flush() {
1127
+ const e = this.outbox;
1128
+ this.outbox = [];
1129
+ for (const t of e) this.raw(t);
1130
+ }
1131
+ raw(e) {
1132
+ var t;
1133
+ try {
1134
+ (t = this.socket) == null || t.send(be(e));
1135
+ } catch {
1136
+ this.outbox.push(e);
1137
+ }
1138
+ }
1139
+ onClosed() {
1140
+ var i, a;
1141
+ if (this.authed = !1, this.socket = null, this.stopped) {
1142
+ this.state = "closed";
1143
+ return;
1144
+ }
1145
+ this.state = "idle";
1146
+ const e = this.opts.backoffBaseMs ?? 500, t = this.opts.backoffMaxMs ?? 15e3, s = Math.min(t, e * 2 ** this.attempt) * (0.5 + Math.random() * 0.5);
1147
+ this.attempt++, this.attempt >= 3 && !this.everAuthed && ((a = (i = this.opts).onStatusChange) == null || a.call(i, "reconnecting", "Can't reach chat — retrying…")), this.timer = setTimeout(() => this.connect(), s);
1148
+ }
1149
+ }
1150
+ const Pe = /* @__PURE__ */ new Set(["UNAUTHORIZED"]);
1151
+ function Te(n) {
1152
+ switch (n) {
1153
+ case "UNAUTHORIZED":
1154
+ return "Chat unavailable — sign-in/token was rejected";
1155
+ default:
1156
+ return "Chat unavailable";
1157
+ }
1158
+ }
1159
+ function Ce(n) {
1160
+ return new WebSocket(n);
1161
+ }
1162
+ class et {
1163
+ constructor(e) {
1164
+ r(this, "conversationId");
1165
+ r(this, "state", "");
1166
+ r(this, "version", 0);
1167
+ r(this, "hasMoreHistory", !1);
1168
+ r(this, "lastReadByOthers", 0);
1169
+ r(this, "assignedAgentId");
1170
+ r(this, "accent");
1171
+ r(this, "subject");
1172
+ r(this, "name");
1173
+ r(this, "e2e", !1);
1174
+ r(this, "offline", !1);
1175
+ r(this, "offlineMessage", "");
1176
+ r(this, "whiteLabel", !1);
1177
+ r(this, "typing", /* @__PURE__ */ new Set());
1178
+ r(this, "online", /* @__PURE__ */ new Set());
1179
+ /** Co-browsing: shared whiteboard strokes for this conversation. */
1180
+ r(this, "annotations", []);
1181
+ /** Bumped on any annotation change so the renderer can cheaply detect updates. */
1182
+ r(this, "annotationVersion", 0);
1183
+ /** Live sentiment of the guest's latest message (agent-side only). */
1184
+ r(this, "sentiment");
1185
+ r(this, "sentimentScore");
1186
+ r(this, "actions", []);
1187
+ r(this, "byId", /* @__PURE__ */ new Map());
1188
+ r(this, "keyByClient", /* @__PURE__ */ new Map());
1189
+ r(this, "_maxSeq", 0);
1190
+ r(this, "_sorted", null);
1191
+ this.me = e;
1192
+ }
1193
+ messages() {
1194
+ return this._sorted || (this._sorted = [...this.byId.values()].sort((e, t) => {
1195
+ const s = e.status === "pending", i = t.status === "pending";
1196
+ return s !== i ? s ? 1 : -1 : s && i ? e.ts - t.ts : e.seq - t.seq;
1197
+ })), this._sorted;
1198
+ }
1199
+ visibleActions() {
1200
+ return this.actions.filter((e) => !e.availableInStates || e.availableInStates.includes(this.state));
1201
+ }
1202
+ highestSeq() {
1203
+ return this._maxSeq;
1204
+ }
1205
+ addOptimistic(e, t) {
1206
+ const s = {
1207
+ id: e,
1208
+ conversationId: this.conversationId,
1209
+ seq: 0,
1210
+ senderId: this.me,
1211
+ senderRole: "guest",
1212
+ content: t,
1213
+ ts: Date.now(),
1214
+ clientMsgId: e,
1215
+ status: "pending"
1216
+ };
1217
+ return this.byId.set(e, s), this.keyByClient.set(e, e), this._sorted = null, s;
1218
+ }
1219
+ apply(e) {
1220
+ var t;
1221
+ switch (e.type) {
1222
+ case "opened":
1223
+ this.conversationId = e.conversation.id, this.state = e.conversation.state, e.subject && (this.subject = e.subject), e.annotations && (this.annotations = e.annotations, this.annotationVersion++);
1224
+ return;
1225
+ case "manifest":
1226
+ this.actions = e.actions, this.version = e.version, e.name && (this.name = e.name), (t = e.theme) != null && t.accent && (this.accent = e.theme.accent), e.e2e && (this.e2e = !0), e.offline && (this.offline = !0), e.offlineMessage && (this.offlineMessage = e.offlineMessage), e.whiteLabel && (this.whiteLabel = !0);
1227
+ return;
1228
+ case "message":
1229
+ this.upsert({ ...e.message });
1230
+ return;
1231
+ case "ack": {
1232
+ const s = this.keyByClient.get(e.clientMsgId), i = s ? this.byId.get(s) : void 0;
1233
+ if (i && s) {
1234
+ this.byId.delete(s);
1235
+ const a = { ...i, id: e.messageId, seq: e.seq, ts: e.ts, status: "sent" };
1236
+ this.byId.set(e.messageId, a), this.keyByClient.set(e.clientMsgId, e.messageId), e.seq > this._maxSeq && (this._maxSeq = e.seq);
1237
+ }
1238
+ this._sorted = null;
1239
+ return;
1240
+ }
1241
+ case "delivered":
1242
+ this.markOwnStatus(e.seq, "delivered");
1243
+ return;
1244
+ case "read":
1245
+ e.by !== this.me && (this.lastReadByOthers = Math.max(this.lastReadByOthers, e.seq), this.markOwnStatus(e.seq, "read"));
1246
+ return;
1247
+ case "sync":
1248
+ for (const s of e.messages) this.upsert({ ...s });
1249
+ return;
1250
+ case "history":
1251
+ for (const s of e.messages) this.upsert({ ...s });
1252
+ this.hasMoreHistory = e.hasMore;
1253
+ return;
1254
+ case "typing":
1255
+ e.userId !== this.me && (e.isTyping ? this.typing.add(e.userId) : this.typing.delete(e.userId));
1256
+ return;
1257
+ case "reaction": {
1258
+ const s = this.byId.get(e.messageId);
1259
+ if (!s) return;
1260
+ const i = { ...s.reactions ?? {} }, a = (i[e.emoji] ?? []).filter((o) => o !== e.by);
1261
+ e.removed || a.push(e.by), a.length ? i[e.emoji] = a : delete i[e.emoji], this.byId.set(e.messageId, { ...s, reactions: i }), this._sorted = null;
1262
+ return;
1263
+ }
1264
+ case "edited": {
1265
+ const s = this.byId.get(e.messageId);
1266
+ s && (this.byId.set(e.messageId, { ...s, content: e.content, editedAt: e.editedAt }), this._sorted = null);
1267
+ return;
1268
+ }
1269
+ case "deleted": {
1270
+ const s = this.byId.get(e.messageId);
1271
+ s && (this.byId.set(e.messageId, { ...s, deletedAt: e.ts }), this._sorted = null);
1272
+ return;
1273
+ }
1274
+ case "state":
1275
+ this.state = e.state;
1276
+ return;
1277
+ case "assigned":
1278
+ this.assignedAgentId = e.agentId ?? void 0;
1279
+ return;
1280
+ case "presence":
1281
+ e.status === "online" ? this.online.add(e.userId) : this.online.delete(e.userId);
1282
+ return;
1283
+ case "subjectState":
1284
+ case "invoked":
1285
+ case "authed":
1286
+ case "error":
1287
+ case "pong":
1288
+ return;
1289
+ case "annotation":
1290
+ this.annotations = [...this.annotations, e.stroke], this.annotationVersion++;
1291
+ return;
1292
+ case "annotation_clear":
1293
+ this.annotations = [], this.annotationVersion++;
1294
+ return;
1295
+ case "sentiment":
1296
+ this.sentiment = e.label, this.sentimentScore = e.score;
1297
+ return;
1298
+ default:
1299
+ return;
1300
+ }
1301
+ }
1302
+ upsert(e) {
1303
+ const t = this.byId.get(e.id);
1304
+ this.byId.set(e.id, t ? { ...t, ...e } : e), e.seq > this._maxSeq && (this._maxSeq = e.seq), this._sorted = null;
1305
+ }
1306
+ markOwnStatus(e, t) {
1307
+ const s = M(t);
1308
+ let i = !1;
1309
+ for (const [a, o] of this.byId)
1310
+ o.senderId !== this.me || o.seq <= 0 || o.seq > e || M(o.status) >= s || (this.byId.set(a, { ...o, status: t }), i = !0);
1311
+ i && (this._sorted = null);
1312
+ }
1313
+ }
1314
+ function M(n) {
1315
+ switch (n) {
1316
+ case "read":
1317
+ return 3;
1318
+ case "delivered":
1319
+ return 2;
1320
+ case "sent":
1321
+ return 1;
1322
+ default:
1323
+ return 0;
1324
+ }
1325
+ }
1326
+ const _ = 200, De = 7 * 864e5;
1327
+ class tt {
1328
+ constructor(e) {
1329
+ r(this, "key");
1330
+ this.key = `ocw_outbox_${e}`;
1331
+ }
1332
+ /** All pending items, oldest first, with stale (>7d) entries dropped. */
1333
+ load() {
1334
+ try {
1335
+ const e = localStorage.getItem(this.key);
1336
+ if (!e) return [];
1337
+ const t = JSON.parse(e), s = Date.now() - De, i = t.filter((a) => a.ts >= s);
1338
+ return i.length !== t.length && this.save(i), i;
1339
+ } catch {
1340
+ return [];
1341
+ }
1342
+ }
1343
+ add(e) {
1344
+ try {
1345
+ const t = this.load();
1346
+ t.push(e), this.save(t.length > _ ? t.slice(t.length - _) : t);
1347
+ } catch {
1348
+ }
1349
+ }
1350
+ /** Remove an item once it's been acknowledged by the server. */
1351
+ remove(e) {
1352
+ try {
1353
+ const t = this.load().filter((s) => s.clientMsgId !== e);
1354
+ this.save(t);
1355
+ } catch {
1356
+ }
1357
+ }
1358
+ save(e) {
1359
+ try {
1360
+ localStorage.setItem(this.key, JSON.stringify(e));
1361
+ } catch {
1362
+ }
1363
+ }
1364
+ }
1365
+ const c = () => globalThis.crypto.subtle;
1366
+ function K(n) {
1367
+ const e = n instanceof Uint8Array ? n : new Uint8Array(n);
1368
+ let t = "";
1369
+ for (const s of e) t += String.fromCharCode(s);
1370
+ return btoa(t);
1371
+ }
1372
+ function A(n) {
1373
+ const e = atob(n), t = new ArrayBuffer(e.length), s = new Uint8Array(t);
1374
+ for (let i = 0; i < e.length; i++) s[i] = e.charCodeAt(i);
1375
+ return s;
1376
+ }
1377
+ async function U() {
1378
+ const n = await c().generateKey({ name: "ECDH", namedCurve: "P-256" }, !0, ["deriveKey", "deriveBits"]);
1379
+ return { publicKey: n.publicKey, privateKey: n.privateKey };
1380
+ }
1381
+ async function w(n) {
1382
+ return K(await c().exportKey("raw", n));
1383
+ }
1384
+ async function g(n) {
1385
+ return c().importKey("raw", A(n), { name: "ECDH", namedCurve: "P-256" }, !1, []);
1386
+ }
1387
+ async function Me(n, e) {
1388
+ const t = await g(e);
1389
+ return c().deriveKey(
1390
+ { name: "ECDH", public: t },
1391
+ n,
1392
+ { name: "AES-GCM", length: 256 },
1393
+ !1,
1394
+ ["encrypt", "decrypt"]
1395
+ );
1396
+ }
1397
+ async function _e(n, e) {
1398
+ const t = globalThis.crypto.getRandomValues(new Uint8Array(12)), s = new TextEncoder().encode(e), i = await c().encrypt({ name: "AES-GCM", iv: t }, n, s);
1399
+ return { ct: K(i), iv: K(t) };
1400
+ }
1401
+ async function Le(n, e, t) {
1402
+ const s = await c().decrypt({ name: "AES-GCM", iv: A(t) }, n, A(e));
1403
+ return new TextDecoder().decode(s);
1404
+ }
1405
+ async function ze(n) {
1406
+ var t, s;
1407
+ try {
1408
+ const i = (t = globalThis.localStorage) == null ? void 0 : t.getItem(n);
1409
+ if (i) {
1410
+ const { pub: a, priv: o } = JSON.parse(i), h = await c().importKey("jwk", a, { name: "ECDH", namedCurve: "P-256" }, !0, []), d = await c().importKey("jwk", o, { name: "ECDH", namedCurve: "P-256" }, !0, ["deriveKey", "deriveBits"]);
1411
+ return { publicKey: h, privateKey: d };
1412
+ }
1413
+ } catch {
1414
+ }
1415
+ const e = await U();
1416
+ try {
1417
+ const i = await c().exportKey("jwk", e.publicKey), a = await c().exportKey("jwk", e.privateKey);
1418
+ (s = globalThis.localStorage) == null || s.setItem(n, JSON.stringify({ pub: i, priv: a }));
1419
+ } catch {
1420
+ }
1421
+ return e;
1422
+ }
1423
+ async function He(n, e) {
1424
+ const t = await c().exportKey("raw", e), s = await c().sign({ name: "ECDSA", hash: "SHA-256" }, n, t);
1425
+ return K(s);
1426
+ }
1427
+ async function Fe() {
1428
+ const n = await U(), e = await c().generateKey({ name: "ECDSA", namedCurve: "P-256" }, !0, ["sign", "verify"]);
1429
+ return {
1430
+ ecdhKP: n,
1431
+ ecdsaKP: { publicKey: e.publicKey, privateKey: e.privateKey },
1432
+ publicKeyB64: await w(n.publicKey),
1433
+ sigPublicKeyB64: await w(e.publicKey)
1434
+ };
1435
+ }
1436
+ async function L(n) {
1437
+ var t, s;
1438
+ try {
1439
+ const i = (t = globalThis.localStorage) == null ? void 0 : t.getItem(`${n}-identity`);
1440
+ if (i) {
1441
+ const a = JSON.parse(i), o = await c().importKey("jwk", a.ecdhPub, { name: "ECDH", namedCurve: "P-256" }, !0, []), h = await c().importKey("jwk", a.ecdhPriv, { name: "ECDH", namedCurve: "P-256" }, !0, ["deriveKey", "deriveBits"]), d = await c().importKey("jwk", a.ecdsaPub, { name: "ECDSA", namedCurve: "P-256" }, !0, ["verify"]), f = await c().importKey("jwk", a.ecdsaPriv, { name: "ECDSA", namedCurve: "P-256" }, !0, ["sign"]);
1442
+ return {
1443
+ ecdhKP: { publicKey: o, privateKey: h },
1444
+ ecdsaKP: { publicKey: d, privateKey: f },
1445
+ publicKeyB64: await w(o),
1446
+ sigPublicKeyB64: await w(d)
1447
+ };
1448
+ }
1449
+ } catch {
1450
+ }
1451
+ const e = await Fe();
1452
+ try {
1453
+ const i = await c().exportKey("jwk", e.ecdhKP.publicKey), a = await c().exportKey("jwk", e.ecdhKP.privateKey), o = await c().exportKey("jwk", e.ecdsaKP.publicKey), h = await c().exportKey("jwk", e.ecdsaKP.privateKey);
1454
+ (s = globalThis.localStorage) == null || s.setItem(`${n}-identity`, JSON.stringify({ ecdhPub: i, ecdhPriv: a, ecdsaPub: o, ecdsaPriv: h }));
1455
+ } catch {
1456
+ }
1457
+ return e;
1458
+ }
1459
+ async function Re(n, e) {
1460
+ const t = await U(), s = await w(t.publicKey), i = await g(e.identityKey), a = await g(e.signedPrekey), o = e.oneTimePrekey ? await g(e.oneTimePrekey) : null, h = await y(n.privateKey, a), d = await y(t.privateKey, i), f = await y(t.privateKey, a), x = o ? await y(t.privateKey, o) : null, u = $(h, d, f, ...x ? [x] : []);
1461
+ return { sharedKey: await N(u), ephemeralPublicKey: s };
1462
+ }
1463
+ async function $e(n, e, t, s, i) {
1464
+ const a = await g(t), o = await g(s), h = await y(e.privateKey, a), d = await y(n.privateKey, o), f = await y(e.privateKey, o), x = i ? await y(i.privateKey, o) : null, u = $(h, d, f, ...x ? [x] : []);
1465
+ return N(u);
1466
+ }
1467
+ async function y(n, e) {
1468
+ return c().deriveBits({ name: "ECDH", public: e }, n, 256);
1469
+ }
1470
+ function $(...n) {
1471
+ const e = n.reduce((i, a) => i + a.byteLength, 0), t = new Uint8Array(e);
1472
+ let s = 0;
1473
+ for (const i of n)
1474
+ t.set(new Uint8Array(i), s), s += i.byteLength;
1475
+ return t.buffer;
1476
+ }
1477
+ async function N(n) {
1478
+ const e = await c().importKey("raw", n, "HKDF", !1, ["deriveKey"]);
1479
+ return c().deriveKey(
1480
+ { name: "HKDF", hash: "SHA-256", salt: new Uint8Array(32), info: new TextEncoder().encode("ObjectChat X3DH v1") },
1481
+ e,
1482
+ { name: "AES-GCM", length: 256 },
1483
+ !1,
1484
+ ["encrypt", "decrypt"]
1485
+ );
1486
+ }
1487
+ const Ne = 20;
1488
+ class st {
1489
+ constructor(e) {
1490
+ // Live ECDH mode state
1491
+ r(this, "kp");
1492
+ r(this, "shared");
1493
+ // X3DH async mode state
1494
+ r(this, "identityKP");
1495
+ r(this, "signedPreKP");
1496
+ r(this, "signedPrekeyId");
1497
+ r(this, "otpKeys", []);
1498
+ // one-time prekeys awaiting matching
1499
+ r(this, "x3dhShared");
1500
+ // Queued init messages arriving before we could derive (shouldn't happen, but safe)
1501
+ r(this, "pendingX3DH");
1502
+ this.storageKey = e;
1503
+ }
1504
+ get ready() {
1505
+ return !!(this.shared ?? this.x3dhShared);
1506
+ }
1507
+ /** Live ECDH mode: Generate/restore our keypair and return our public key to publish. */
1508
+ async begin() {
1509
+ return this.kp = await ze(this.storageKey), w(this.kp.publicKey);
1510
+ }
1511
+ /** Live ECDH mode: A peer published their key — derive the shared secret. */
1512
+ async onPeerKey(e) {
1513
+ this.kp && (this.shared = await Me(this.kp.privateKey, e));
1514
+ }
1515
+ // ── X3DH async mode ────────────────────────────────────────────────────────
1516
+ /** X3DH: Generate identity key, signed prekey, and OTP prekeys.
1517
+ * Returns the upload frame payload the caller should send to the server. */
1518
+ async initX3DH() {
1519
+ this.identityKP = await L(this.storageKey), this.signedPreKP = await U(), this.signedPrekeyId = `spk-${Date.now()}-${Math.random().toString(36).slice(2)}`;
1520
+ for (let i = 0; i < Ne; i++) this.otpKeys.push(await U());
1521
+ const e = await w(this.signedPreKP.publicKey), t = await He(this.identityKP.ecdsaKP.privateKey, this.signedPreKP.publicKey), s = await Promise.all(this.otpKeys.map((i) => w(i.publicKey)));
1522
+ return {
1523
+ identityKey: this.identityKP.publicKeyB64,
1524
+ signedPrekey: e,
1525
+ signedPrekeyId: this.signedPrekeyId,
1526
+ signature: t,
1527
+ oneTimePrekeys: s
1528
+ };
1529
+ }
1530
+ /** X3DH sender: given a recipient's prekey bundle, derive the shared key and
1531
+ * return the init message fields to embed in the first encrypted message. */
1532
+ async x3dhSendTo(e) {
1533
+ this.identityKP || (this.identityKP = await L(this.storageKey));
1534
+ const { sharedKey: t, ephemeralPublicKey: s } = await Re(this.identityKP.ecdhKP, e);
1535
+ return this.x3dhShared = t, { ephemeralKey: s, spkId: e.signedPrekeyId, usedOTP: !!e.oneTimePrekey, senderIK: this.identityKP.publicKeyB64 };
1536
+ }
1537
+ /** X3DH recipient: given an init message's sender IK + EK + SPK ID, derive the shared key. */
1538
+ async x3dhReceiveFrom(e, t, s) {
1539
+ if (!this.identityKP || !this.signedPreKP) {
1540
+ this.pendingX3DH = { senderIK: e, ephemeralKey: t, spkId: s };
1541
+ return;
1542
+ }
1543
+ const i = this.otpKeys.shift();
1544
+ this.x3dhShared = await $e(this.identityKP.ecdhKP, this.signedPreKP, e, t, i);
1545
+ }
1546
+ /** Flush pending X3DH derivation after initX3DH() completes. */
1547
+ async flushPendingX3DH() {
1548
+ if (!this.pendingX3DH) return;
1549
+ const { senderIK: e, ephemeralKey: t, spkId: s } = this.pendingX3DH;
1550
+ this.pendingX3DH = void 0, await this.x3dhReceiveFrom(e, t, s);
1551
+ }
1552
+ /** Encrypt outgoing text into a wire content object. For X3DH init messages,
1553
+ * the caller should pass x3dhInit fields to embed in the content. */
1554
+ async sealText(e, t) {
1555
+ const s = this.x3dhShared ?? this.shared;
1556
+ if (!s) throw new Error("secure channel not ready");
1557
+ const { ct: i, iv: a } = await _e(s, e);
1558
+ return {
1559
+ kind: "text",
1560
+ text: i,
1561
+ enc: !0,
1562
+ iv: a,
1563
+ ...t ? { x3dhEK: t.ephemeralKey, x3dhSPK: t.spkId, x3dhIK: t.senderIK } : {}
1564
+ };
1565
+ }
1566
+ /** Decrypt one content object if it is encrypted (otherwise pass through). */
1567
+ async openContent(e) {
1568
+ if (e.kind !== "text" || !e.enc || !e.iv) return e;
1569
+ const t = this.x3dhShared ?? this.shared;
1570
+ if (!t) return { kind: "text", text: "🔒 encrypted" };
1571
+ try {
1572
+ return { kind: "text", text: await Le(t, e.text, e.iv) };
1573
+ } catch {
1574
+ return { kind: "text", text: "🔒 unable to decrypt" };
1575
+ }
1576
+ }
1577
+ /** Decrypt any encrypted message content carried by an incoming frame, in place. */
1578
+ async openFrame(e) {
1579
+ if (e.type === "message") e.message.content = await this.openContent(e.message.content);
1580
+ else if (e.type === "sync")
1581
+ for (const t of e.messages) t.content = await this.openContent(t.content);
1582
+ }
1583
+ }
1584
+ function it(n) {
1585
+ if (n.kind !== "text" || !n.enc) return null;
1586
+ const e = n;
1587
+ return !e.x3dhEK || !e.x3dhSPK || !e.x3dhIK ? null : { x3dhEK: e.x3dhEK, x3dhSPK: e.x3dhSPK, x3dhIK: e.x3dhIK };
1588
+ }
1589
+ export {
1590
+ Qe as A,
1591
+ et as C,
1592
+ st as E,
1593
+ tt as P,
1594
+ Ve as a,
1595
+ je as b,
1596
+ Je as c,
1597
+ Ze as d,
1598
+ Xe as e,
1599
+ Ye as f,
1600
+ Ge as g,
1601
+ We as h,
1602
+ V as i,
1603
+ Ae as j,
1604
+ be as k,
1605
+ Be as l,
1606
+ it as m
1607
+ };
1608
+ //# sourceMappingURL=e2e.js.map