@ikonai/sdk 0.0.28 → 0.0.31

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.
Files changed (32) hide show
  1. package/assets/audio-capture-worker-DINNsNmH.js +933 -0
  2. package/assets/audio-playback-worker-C4Eyhfrh.js +1323 -0
  3. package/assets/protocol-worker-E7o-6_bZ.js +1422 -0
  4. package/assets/video-capture-worker-CTRX9PKp.js +843 -0
  5. package/assets/video-playback-worker-CIuL9Crw.js +875 -0
  6. package/channel/channel-manager.d.ts +1 -1
  7. package/channel/channel.d.ts +1 -1
  8. package/client/endpoint-selector.d.ts +1 -1
  9. package/client/ikon-client-config.d.ts +4 -9
  10. package/client/ikon-client.d.ts +5 -1
  11. package/connection/authenticator.d.ts +1 -1
  12. package/functions/function-registry.d.ts +1 -1
  13. package/functions/index.d.ts +1 -1
  14. package/functions/types.d.ts +1 -1
  15. package/index.d.ts +8 -8
  16. package/index.js +3884 -15843
  17. package/media/audio-constants.d.ts +20 -0
  18. package/media/ikon-audio-playback.d.ts +1 -1
  19. package/media/ikon-video-playback.d.ts +0 -8
  20. package/package.json +2 -1
  21. package/transport/transport.d.ts +1 -1
  22. package/transport/web-socket-transport.d.ts +6 -1
  23. package/transport/web-transport-transport.d.ts +17 -2
  24. package/{media/audio-worker-messages.d.ts → worker/audio-playback-worker.d.ts} +10 -10
  25. package/worker/video-playback-worker.d.ts +59 -0
  26. package/assets/audio-capture-worker-C5hNMTF7.js +0 -14835
  27. package/assets/audio-worker-Ci3tYX2B.js +0 -15121
  28. package/assets/protocol-worker-DXLojSe-.js +0 -15288
  29. package/assets/video-capture-worker-OBl3bsvx.js +0 -14733
  30. package/assets/video-worker-BoOfB8qz.js +0 -14761
  31. package/worker/audio-worker.d.ts +0 -1
  32. package/worker/video-worker.d.ts +0 -1
@@ -0,0 +1,1422 @@
1
+ function J(t) {
2
+ if (t.length < 8)
3
+ throw new Error("Protocol message too short");
4
+ return (t[4] | t[5] << 8 | t[6] << 16 | t[7] << 24) >>> 0;
5
+ }
6
+ function k(t) {
7
+ return J(t) & 4294901760;
8
+ }
9
+ function $(t) {
10
+ const e = Et(t), r = new DataView(e.buffer, e.byteOffset, e.byteLength);
11
+ if (e.length < 27)
12
+ throw new Error("Protocol payload too short");
13
+ const s = r.getUint32(0, !0), n = r.getUint32(4, !0), i = r.getUint32(8, !0), o = r.getUint32(12, !0), E = r.getUint32(16, !0), l = r.getUint32(20, !0), a = r.getUint8(24), N = r.getUint8(25), L = r.getUint8(26);
14
+ if (27 + l * 4 > e.length)
15
+ throw new Error("Protocol header exceeds payload length");
16
+ const _ = [];
17
+ let d = 27;
18
+ for (let m = 0; m < l; m++)
19
+ _.push(r.getUint32(d, !0)), d += 4;
20
+ return {
21
+ length: s,
22
+ opcode: n,
23
+ senderId: i,
24
+ trackId: o,
25
+ sequenceId: E,
26
+ targetIds: _,
27
+ payloadVersion: a,
28
+ payloadType: N,
29
+ flags: L
30
+ };
31
+ }
32
+ function nt(t, e, r, s, n) {
33
+ const l = [], N = 27 + l.length * 4, L = N + e.length, P = new Uint8Array(L), _ = new DataView(P.buffer);
34
+ _.setUint32(0, L, !0), _.setUint32(4, t >>> 0, !0), _.setUint32(8, s >>> 0, !0), _.setUint32(12, 0, !0), _.setUint32(16, 0, !0), _.setUint32(20, l.length >>> 0, !0), _.setUint8(24, r & 255), _.setUint8(25, 8), _.setUint8(26, 0);
35
+ let d = 27;
36
+ for (let m = 0; m < l.length; m++)
37
+ _.setUint32(d, l[m] >>> 0, !0), d += 4;
38
+ return P.set(e, N), P;
39
+ }
40
+ var S = /* @__PURE__ */ ((t) => (t[t.Null = 1] = "Null", t[t.Bool = 2] = "Bool", t[t.Int32 = 3] = "Int32", t[t.Int64 = 4] = "Int64", t[t.UInt32 = 5] = "UInt32", t[t.UInt64 = 6] = "UInt64", t[t.Float32 = 7] = "Float32", t[t.Float64 = 8] = "Float64", t[t.Array = 9] = "Array", t[t.Dict = 10] = "Dict", t[t.Object = 11] = "Object", t[t.String = 12] = "String", t[t.Binary = 13] = "Binary", t[t.Guid = 14] = "Guid", t))(S || {});
41
+ const it = 161, at = 162, p = new TextEncoder();
42
+ new TextDecoder("utf-8", { fatal: !0 });
43
+ class B {
44
+ constructor(e = 1) {
45
+ this.version = e, this.buffer.writeByte(it), this.buffer.writeVarUInt(e >>> 0);
46
+ }
47
+ buffer = new D();
48
+ closed = !1;
49
+ cached;
50
+ writeInt32Field(e, r) {
51
+ this.writeFixedField(e, 3, () => this.buffer.writeInt32(r | 0));
52
+ }
53
+ writeUInt32Field(e, r) {
54
+ this.writeFixedField(e, 5, () => this.buffer.writeUInt32(r >>> 0));
55
+ }
56
+ writeInt64Field(e, r) {
57
+ this.writeFixedField(e, 4, () => this.buffer.writeBigInt64(r));
58
+ }
59
+ writeUInt64Field(e, r) {
60
+ this.writeFixedField(e, 6, () => this.buffer.writeBigUInt64(r));
61
+ }
62
+ writeFloat32Field(e, r) {
63
+ this.writeFixedField(e, 7, () => this.buffer.writeFloat32(r));
64
+ }
65
+ writeFloat64Field(e, r) {
66
+ this.writeFixedField(e, 8, () => this.buffer.writeFloat64(r));
67
+ }
68
+ writeBoolField(e, r) {
69
+ this.writeFixedField(e, 2, () => this.buffer.writeByte(r ? 1 : 0));
70
+ }
71
+ writeGuidField(e, r) {
72
+ const s = r instanceof h ? r.asBytes() : r;
73
+ if (s.length !== 16)
74
+ throw new Error("Guid payload must be 16 bytes");
75
+ this.writeFixedField(e, 14, () => this.buffer.writeBytes(s));
76
+ }
77
+ writeStringField(e, r) {
78
+ const s = p.encode(r ?? "");
79
+ this.writeVariableField(e, 12, s);
80
+ }
81
+ writeBinaryField(e, r) {
82
+ this.writeVariableField(e, 13, r);
83
+ }
84
+ writeObjectField(e, r, s) {
85
+ const n = new B(r);
86
+ s(n);
87
+ const i = n.finish();
88
+ this.writeVariableField(e, 11, i);
89
+ }
90
+ writeArrayField(e, r, s) {
91
+ const n = new K(r);
92
+ s(n);
93
+ const i = n.finish();
94
+ this.writeVariableField(e, 9, i);
95
+ }
96
+ writeDictionaryField(e, r, s, n) {
97
+ const i = new X(r, s);
98
+ n(i);
99
+ const o = i.finish();
100
+ this.writeVariableField(e, 10, o);
101
+ }
102
+ finish() {
103
+ return this.closed || (this.buffer.writeByte(at), this.closed = !0, this.cached = this.buffer.toUint8Array()), this.cached;
104
+ }
105
+ writeFixedField(e, r, s) {
106
+ this.writeFieldHeader(e, r, 0), s();
107
+ }
108
+ writeVariableField(e, r, s) {
109
+ this.writeFieldHeader(e, r, s.length), this.buffer.writeBytes(s);
110
+ }
111
+ writeFieldHeader(e, r, s) {
112
+ this.buffer.writeUInt32(e >>> 0), this.buffer.writeByte(G(r)), lt(r) && this.buffer.writeVarUInt(s >>> 0);
113
+ }
114
+ }
115
+ class K {
116
+ constructor(e) {
117
+ this.elementType = e;
118
+ }
119
+ payload = new D();
120
+ count = 0;
121
+ writeInt32(e) {
122
+ this.ensureElementType(
123
+ 3
124
+ /* Int32 */
125
+ ), this.count++, this.payload.writeInt32(e | 0);
126
+ }
127
+ writeUInt32(e) {
128
+ this.ensureElementType(
129
+ 5
130
+ /* UInt32 */
131
+ ), this.count++, this.payload.writeUInt32(e >>> 0);
132
+ }
133
+ writeInt64(e) {
134
+ this.ensureElementType(
135
+ 4
136
+ /* Int64 */
137
+ ), this.count++, this.payload.writeBigInt64(e);
138
+ }
139
+ writeUInt64(e) {
140
+ this.ensureElementType(
141
+ 6
142
+ /* UInt64 */
143
+ ), this.count++, this.payload.writeBigUInt64(e);
144
+ }
145
+ writeFloat32(e) {
146
+ this.ensureElementType(
147
+ 7
148
+ /* Float32 */
149
+ ), this.count++, this.payload.writeFloat32(e);
150
+ }
151
+ writeFloat64(e) {
152
+ this.ensureElementType(
153
+ 8
154
+ /* Float64 */
155
+ ), this.count++, this.payload.writeFloat64(e);
156
+ }
157
+ writeBool(e) {
158
+ this.ensureElementType(
159
+ 2
160
+ /* Bool */
161
+ ), this.count++, this.payload.writeByte(e ? 1 : 0);
162
+ }
163
+ writeGuid(e) {
164
+ this.ensureElementType(
165
+ 14
166
+ /* Guid */
167
+ ), this.count++;
168
+ const r = e instanceof h ? e.asBytes() : e;
169
+ if (r.length !== 16)
170
+ throw new Error("Guid payload must be 16 bytes");
171
+ this.payload.writeBytes(r);
172
+ }
173
+ writeString(e) {
174
+ this.ensureElementType(
175
+ 12
176
+ /* String */
177
+ ), this.count++;
178
+ const r = p.encode(e ?? "");
179
+ this.payload.writeVarUInt(r.length), this.payload.writeBytes(r);
180
+ }
181
+ writeBinary(e) {
182
+ this.ensureElementType(
183
+ 13
184
+ /* Binary */
185
+ ), this.count++, this.payload.writeVarUInt(e.length), this.payload.writeBytes(e);
186
+ }
187
+ writeObject(e, r) {
188
+ this.ensureElementType(
189
+ 11
190
+ /* Object */
191
+ ), this.count++;
192
+ const s = new B(e);
193
+ r(s);
194
+ const n = s.finish();
195
+ this.payload.writeVarUInt(n.length), this.payload.writeBytes(n);
196
+ }
197
+ writeArray(e, r) {
198
+ this.ensureElementType(
199
+ 9
200
+ /* Array */
201
+ ), this.count++;
202
+ const s = new K(e);
203
+ r(s);
204
+ const n = s.finish();
205
+ this.payload.writeBytes(n);
206
+ }
207
+ writeDictionary(e, r, s) {
208
+ this.ensureElementType(
209
+ 10
210
+ /* Dict */
211
+ ), this.count++;
212
+ const n = new X(e, r);
213
+ s(n);
214
+ const i = n.finish();
215
+ this.payload.writeBytes(i);
216
+ }
217
+ finish() {
218
+ const e = new D();
219
+ return e.writeByte(G(this.elementType)), e.writeVarUInt(this.count), e.writeBytes(this.payload.toUint8Array()), e.toUint8Array();
220
+ }
221
+ ensureElementType(e) {
222
+ if (this.elementType !== e)
223
+ throw new Error(`Array element type is ${S[this.elementType]}, expected ${S[e]}`);
224
+ }
225
+ }
226
+ class X {
227
+ constructor(e, r) {
228
+ this.keyType = e, this.valueType = r, ht(e);
229
+ }
230
+ payload = new D();
231
+ count = 0;
232
+ entryOpen = !1;
233
+ beginEntry() {
234
+ if (this.entryOpen)
235
+ throw new Error("Previous dictionary entry not completed");
236
+ return this.count++, this.entryOpen = !0, new ot(this.keyType, this.valueType, this.payload, () => {
237
+ this.entryOpen = !1;
238
+ });
239
+ }
240
+ finish() {
241
+ if (this.entryOpen)
242
+ throw new Error("Dictionary entry not completed");
243
+ const e = new D();
244
+ return e.writeByte(G(this.keyType)), e.writeByte(G(this.valueType)), e.writeVarUInt(this.count), e.writeBytes(this.payload.toUint8Array()), e.toUint8Array();
245
+ }
246
+ }
247
+ class ot {
248
+ constructor(e, r, s, n) {
249
+ this.keyType = e, this.valueType = r, this.payload = s, this.onComplete = n;
250
+ }
251
+ keyWritten = !1;
252
+ valueWritten = !1;
253
+ completed = !1;
254
+ writeKeyInt32(e) {
255
+ this.ensureKeyType(
256
+ 3
257
+ /* Int32 */
258
+ ), this.payload.writeInt32(e | 0), this.keyWritten = !0;
259
+ }
260
+ writeKeyUInt32(e) {
261
+ this.ensureKeyType(
262
+ 5
263
+ /* UInt32 */
264
+ ), this.payload.writeUInt32(e >>> 0), this.keyWritten = !0;
265
+ }
266
+ writeKeyInt64(e) {
267
+ this.ensureKeyType(
268
+ 4
269
+ /* Int64 */
270
+ ), this.payload.writeBigInt64(e), this.keyWritten = !0;
271
+ }
272
+ writeKeyUInt64(e) {
273
+ this.ensureKeyType(
274
+ 6
275
+ /* UInt64 */
276
+ ), this.payload.writeBigUInt64(e), this.keyWritten = !0;
277
+ }
278
+ writeKeyFloat32(e) {
279
+ this.ensureKeyType(
280
+ 7
281
+ /* Float32 */
282
+ ), this.payload.writeFloat32(e), this.keyWritten = !0;
283
+ }
284
+ writeKeyFloat64(e) {
285
+ this.ensureKeyType(
286
+ 8
287
+ /* Float64 */
288
+ ), this.payload.writeFloat64(e), this.keyWritten = !0;
289
+ }
290
+ writeKeyBool(e) {
291
+ this.ensureKeyType(
292
+ 2
293
+ /* Bool */
294
+ ), this.payload.writeByte(e ? 1 : 0), this.keyWritten = !0;
295
+ }
296
+ writeKeyGuid(e) {
297
+ this.ensureKeyType(
298
+ 14
299
+ /* Guid */
300
+ );
301
+ const r = e instanceof h ? e.asBytes() : e;
302
+ if (r.length !== 16)
303
+ throw new Error("Guid payload must be 16 bytes");
304
+ this.payload.writeBytes(r), this.keyWritten = !0;
305
+ }
306
+ writeKeyString(e) {
307
+ this.ensureKeyType(
308
+ 12
309
+ /* String */
310
+ );
311
+ const r = p.encode(e ?? "");
312
+ this.payload.writeVarUInt(r.length), this.payload.writeBytes(r), this.keyWritten = !0;
313
+ }
314
+ writeKeyBinary(e) {
315
+ this.ensureKeyType(
316
+ 13
317
+ /* Binary */
318
+ ), this.payload.writeVarUInt(e.length), this.payload.writeBytes(e), this.keyWritten = !0;
319
+ }
320
+ writeValueInt32(e) {
321
+ this.ensureValueType(
322
+ 3
323
+ /* Int32 */
324
+ ), this.payload.writeInt32(e | 0), this.valueWritten = !0;
325
+ }
326
+ writeValueUInt32(e) {
327
+ this.ensureValueType(
328
+ 5
329
+ /* UInt32 */
330
+ ), this.payload.writeUInt32(e >>> 0), this.valueWritten = !0;
331
+ }
332
+ writeValueInt64(e) {
333
+ this.ensureValueType(
334
+ 4
335
+ /* Int64 */
336
+ ), this.payload.writeBigInt64(e), this.valueWritten = !0;
337
+ }
338
+ writeValueUInt64(e) {
339
+ this.ensureValueType(
340
+ 6
341
+ /* UInt64 */
342
+ ), this.payload.writeBigUInt64(e), this.valueWritten = !0;
343
+ }
344
+ writeValueFloat32(e) {
345
+ this.ensureValueType(
346
+ 7
347
+ /* Float32 */
348
+ ), this.payload.writeFloat32(e), this.valueWritten = !0;
349
+ }
350
+ writeValueFloat64(e) {
351
+ this.ensureValueType(
352
+ 8
353
+ /* Float64 */
354
+ ), this.payload.writeFloat64(e), this.valueWritten = !0;
355
+ }
356
+ writeValueBool(e) {
357
+ this.ensureValueType(
358
+ 2
359
+ /* Bool */
360
+ ), this.payload.writeByte(e ? 1 : 0), this.valueWritten = !0;
361
+ }
362
+ writeValueGuid(e) {
363
+ this.ensureValueType(
364
+ 14
365
+ /* Guid */
366
+ );
367
+ const r = e instanceof h ? e.asBytes() : e;
368
+ if (r.length !== 16)
369
+ throw new Error("Guid payload must be 16 bytes");
370
+ this.payload.writeBytes(r), this.valueWritten = !0;
371
+ }
372
+ writeNullValue() {
373
+ this.ensureValueType(
374
+ 1
375
+ /* Null */
376
+ ), this.valueWritten = !0;
377
+ }
378
+ writeValueBinary(e) {
379
+ this.ensureValueType(
380
+ 13
381
+ /* Binary */
382
+ ), this.payload.writeVarUInt(e.length), this.payload.writeBytes(e), this.valueWritten = !0;
383
+ }
384
+ writeValueString(e) {
385
+ this.ensureValueType(
386
+ 12
387
+ /* String */
388
+ );
389
+ const r = p.encode(e ?? "");
390
+ this.payload.writeVarUInt(r.length), this.payload.writeBytes(r), this.valueWritten = !0;
391
+ }
392
+ writeValueObject(e, r) {
393
+ this.ensureValueType(
394
+ 11
395
+ /* Object */
396
+ );
397
+ const s = new B(e);
398
+ r(s);
399
+ const n = s.finish();
400
+ this.payload.writeVarUInt(n.length), this.payload.writeBytes(n), this.valueWritten = !0;
401
+ }
402
+ writeValueArray(e, r) {
403
+ this.ensureValueType(
404
+ 9
405
+ /* Array */
406
+ );
407
+ const s = new K(e);
408
+ r(s);
409
+ const n = s.finish();
410
+ this.payload.writeBytes(n), this.valueWritten = !0;
411
+ }
412
+ writeValueDictionary(e, r, s) {
413
+ this.ensureValueType(
414
+ 10
415
+ /* Dict */
416
+ );
417
+ const n = new X(e, r);
418
+ s(n);
419
+ const i = n.finish();
420
+ this.payload.writeBytes(i), this.valueWritten = !0;
421
+ }
422
+ complete() {
423
+ if (!this.completed) {
424
+ if (!this.keyWritten || !this.valueWritten)
425
+ throw new Error("Dictionary entry must write both key and value");
426
+ this.completed = !0, this.onComplete();
427
+ }
428
+ }
429
+ ensureKeyType(e) {
430
+ if (this.keyType !== e)
431
+ throw new Error(`Dictionary key type is ${S[this.keyType]}, expected ${S[e]}`);
432
+ }
433
+ ensureValueType(e) {
434
+ if (this.valueType !== e)
435
+ throw new Error(`Dictionary value type is ${S[this.valueType]}, expected ${S[e]}`);
436
+ }
437
+ }
438
+ class h {
439
+ constructor(e) {
440
+ this.bytes = e;
441
+ }
442
+ static fromString(e) {
443
+ if (!e)
444
+ throw new Error("Guid string is empty");
445
+ const r = e.replace(/-/g, "");
446
+ if (r.length !== 32)
447
+ throw new Error("Guid string must be 32 hex characters");
448
+ const s = new Uint8Array(16), n = h.parseHexSlice(r, 0, 8), i = h.parseHexSlice(r, 8, 4), o = h.parseHexSlice(r, 12, 4);
449
+ h.writeUInt32LE(s, 0, n), h.writeUInt16LE(s, 4, i), h.writeUInt16LE(s, 6, o);
450
+ for (let E = 0; E < 8; E++)
451
+ s[8 + E] = h.parseHexSlice(r, 16 + E * 2, 2);
452
+ return new h(s);
453
+ }
454
+ static fromBytes(e) {
455
+ if (e.length !== 16)
456
+ throw new Error("Guid byte array must be 16 bytes");
457
+ return new h(Uint8Array.from(e));
458
+ }
459
+ static createZero() {
460
+ return new h(new Uint8Array(16));
461
+ }
462
+ static createRandom() {
463
+ const e = new Uint8Array(16), r = globalThis.crypto;
464
+ if (r?.getRandomValues)
465
+ r.getRandomValues(e);
466
+ else
467
+ for (let s = 0; s < e.length; s++)
468
+ e[s] = Math.floor(Math.random() * 256);
469
+ return e[6] = e[6] & 15 | 64, e[8] = e[8] & 63 | 128, new h(e);
470
+ }
471
+ toString() {
472
+ const e = this.bytes;
473
+ return [
474
+ h.toHex(h.readUInt32LE(e, 0), 8),
475
+ h.toHex(h.readUInt16LE(e, 4), 4),
476
+ h.toHex(h.readUInt16LE(e, 6), 4),
477
+ z(e.subarray(8, 10)),
478
+ z(e.subarray(10, 16))
479
+ ].join("-");
480
+ }
481
+ asBytes() {
482
+ return this.bytes.slice();
483
+ }
484
+ static parseHexSlice(e, r, s) {
485
+ const n = e.substr(r, s), i = Number.parseInt(n, 16);
486
+ if (Number.isNaN(i))
487
+ throw new Error("Guid string contains invalid characters");
488
+ return i >>> 0;
489
+ }
490
+ static writeUInt32LE(e, r, s) {
491
+ const n = s >>> 0;
492
+ e[r] = n & 255, e[r + 1] = n >>> 8 & 255, e[r + 2] = n >>> 16 & 255, e[r + 3] = n >>> 24 & 255;
493
+ }
494
+ static writeUInt16LE(e, r, s) {
495
+ const n = s & 65535;
496
+ e[r] = n & 255, e[r + 1] = n >>> 8 & 255;
497
+ }
498
+ static readUInt32LE(e, r) {
499
+ return (e[r] | e[r + 1] << 8 | e[r + 2] << 16 | e[r + 3] << 24) >>> 0;
500
+ }
501
+ static readUInt16LE(e, r) {
502
+ return (e[r] | e[r + 1] << 8) & 65535;
503
+ }
504
+ static toHex(e, r) {
505
+ return (e >>> 0).toString(16).padStart(r, "0");
506
+ }
507
+ }
508
+ class D {
509
+ bytes = [];
510
+ writeByte(e) {
511
+ this.bytes.push(e & 255);
512
+ }
513
+ writeBytes(e) {
514
+ for (let r = 0; r < e.length; r++)
515
+ this.bytes.push(e[r]);
516
+ }
517
+ writeUInt32(e) {
518
+ this.bytes.push(e & 255), this.bytes.push(e >>> 8 & 255), this.bytes.push(e >>> 16 & 255), this.bytes.push(e >>> 24 & 255);
519
+ }
520
+ writeInt32(e) {
521
+ this.writeUInt32(e | 0);
522
+ }
523
+ writeFloat32(e) {
524
+ const r = new DataView(new ArrayBuffer(4));
525
+ r.setFloat32(0, e, !0), this.writeBytes(new Uint8Array(r.buffer));
526
+ }
527
+ writeFloat64(e) {
528
+ const r = new DataView(new ArrayBuffer(8));
529
+ r.setFloat64(0, e, !0), this.writeBytes(new Uint8Array(r.buffer));
530
+ }
531
+ writeBigInt64(e) {
532
+ const r = new DataView(new ArrayBuffer(8));
533
+ r.setBigInt64(0, e, !0), this.writeBytes(new Uint8Array(r.buffer));
534
+ }
535
+ writeBigUInt64(e) {
536
+ const r = new DataView(new ArrayBuffer(8));
537
+ r.setBigUint64(0, e, !0), this.writeBytes(new Uint8Array(r.buffer));
538
+ }
539
+ writeVarUInt(e) {
540
+ let r = e >>> 0;
541
+ for (; r >= 128; )
542
+ this.bytes.push(r & 127 | 128), r >>>= 7;
543
+ this.bytes.push(r & 127);
544
+ }
545
+ toUint8Array() {
546
+ return Uint8Array.from(this.bytes);
547
+ }
548
+ }
549
+ function G(t, e = 0) {
550
+ if ((e & 240) !== 0)
551
+ throw new Error("Teleport flags must fit into 4 bits");
552
+ return (t & 15) << 4 | e & 15;
553
+ }
554
+ function lt(t) {
555
+ return t === 12 || t === 13 || t === 9 || t === 11 || t === 10;
556
+ }
557
+ function ht(t) {
558
+ if (t === 9 || t === 11 || t === 10 || t === 1)
559
+ throw new Error("Dictionary keys must be primitive Teleport types");
560
+ }
561
+ function z(t) {
562
+ return Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("");
563
+ }
564
+ function Et(t) {
565
+ return t instanceof Uint8Array ? t : new Uint8Array(t);
566
+ }
567
+ var R = /* @__PURE__ */ ((t) => (t[t.None = 0] = "None", t[t.WebSocket = 1] = "WebSocket", t[t.WebSocketProxy = 2] = "WebSocketProxy", t[t.WebTransport = 4] = "WebTransport", t[t.WebTransportProxy = 8] = "WebTransportProxy", t[t.Tcp = 16] = "Tcp", t[t.TcpProxy = 32] = "TcpProxy", t[t.Https = 64] = "Https", t))(R || {}), W = /* @__PURE__ */ ((t) => (t[t.NONE = 0] = "NONE", t[t.CONSTANT_GROUP_BITS = 15] = "CONSTANT_GROUP_BITS", t[t.CONSTANT_GROUP_OFFSET = 16] = "CONSTANT_GROUP_OFFSET", t[t.GROUP_CORE = 65536] = "GROUP_CORE", t[t.CORE_AUTH_RESPONSE = 65537] = "CORE_AUTH_RESPONSE", t[t.CORE_AUTH_TICKET = 65538] = "CORE_AUTH_TICKET", t[t.CORE_GLOBAL_STATE = 65539] = "CORE_GLOBAL_STATE", t[t.CORE_ON_SERVER_STATUS_PING = 65540] = "CORE_ON_SERVER_STATUS_PING", t[t.CORE_ON_USER_JOINED = 65541] = "CORE_ON_USER_JOINED", t[t.CORE_ON_USER_LEFT = 65542] = "CORE_ON_USER_LEFT", t[t.CORE_ON_CLIENT_JOINED = 65543] = "CORE_ON_CLIENT_JOINED", t[t.CORE_ON_CLIENT_LEFT = 65544] = "CORE_ON_CLIENT_LEFT", t[t.CORE_ON_SERVER_STARTED = 65545] = "CORE_ON_SERVER_STARTED", t[t.CORE_ON_SERVER_STOPPED = 65546] = "CORE_ON_SERVER_STOPPED", t[t.CORE_ON_SERVER_STOPPING = 65547] = "CORE_ON_SERVER_STOPPING", t[t.CORE_ON_CLIENT_READY = 65548] = "CORE_ON_CLIENT_READY", t[t.CORE_CLIENT_READY = 65549] = "CORE_CLIENT_READY", t[t.CORE_SERVER_INIT = 65550] = "CORE_SERVER_INIT", t[t.CORE_ON_PLUGIN_RELOADED = 65551] = "CORE_ON_PLUGIN_RELOADED", t[t.CORE_SERVER_START = 65552] = "CORE_SERVER_START", t[t.CORE_SERVER_STOP = 65553] = "CORE_SERVER_STOP", t[t.CORE_ON_HOSTED_SERVER_EXIT = 65554] = "CORE_ON_HOSTED_SERVER_EXIT", t[t.CORE_DYNAMIC_CONFIG = 65555] = "CORE_DYNAMIC_CONFIG", t[t.CORE_PROXY_RPC_AUTH_TICKET = 65556] = "CORE_PROXY_RPC_AUTH_TICKET", t[t.CORE_SERVER_INIT2 = 65557] = "CORE_SERVER_INIT2", t[t.GROUP_KEEPALIVE = 131072] = "GROUP_KEEPALIVE", t[t.KEEPALIVE_REQUEST = 131073] = "KEEPALIVE_REQUEST", t[t.KEEPALIVE_RESPONSE = 131074] = "KEEPALIVE_RESPONSE", t[t.GROUP_EVENTS = 262144] = "GROUP_EVENTS", t[t.EVENTS_PROFILE_UPDATE = 262145] = "EVENTS_PROFILE_UPDATE", t[t.EVENTS_CHANNEL_COMPLETE = 262146] = "EVENTS_CHANNEL_COMPLETE", t[t.EVENTS_SPEECH_PLAYBACK_COMPLETE = 262147] = "EVENTS_SPEECH_PLAYBACK_COMPLETE", t[t.GROUP_ANALYTICS = 524288] = "GROUP_ANALYTICS", t[t.ANALYTICS_LOGS = 524289] = "ANALYTICS_LOGS", t[t.ANALYTICS_EVENTS = 524290] = "ANALYTICS_EVENTS", t[t.ANALYTICS_USAGES = 524291] = "ANALYTICS_USAGES", t[t.ANALYTICS_USAGE = 524292] = "ANALYTICS_USAGE", t[t.ANALYTICS_SPECIAL_LOG = 524293] = "ANALYTICS_SPECIAL_LOG", t[t.ANALYTICS_PROCESSING_UPDATE = 524294] = "ANALYTICS_PROCESSING_UPDATE", t[t.ANALYTICS_REACTIVE_PROCESSING_UPDATE = 524295] = "ANALYTICS_REACTIVE_PROCESSING_UPDATE", t[t.ANALYTICS_IKON_PROXY_SERVER_STATS = 524296] = "ANALYTICS_IKON_PROXY_SERVER_STATS", t[t.GROUP_ACTIONS = 1048576] = "GROUP_ACTIONS", t[t.ACTION_CALL = 1048577] = "ACTION_CALL", t[t.ACTION_ACTIVE = 1048578] = "ACTION_ACTIVE", t[t.ACTION_TEXT_OUTPUT = 1048579] = "ACTION_TEXT_OUTPUT", t[t.ACTION_TEXT_OUTPUT_DELTA = 1048580] = "ACTION_TEXT_OUTPUT_DELTA", t[t.ACTION_TEXT_OUTPUT_DELTA_FULL = 1048581] = "ACTION_TEXT_OUTPUT_DELTA_FULL", t[t.ACTION_SET_STATE = 1048582] = "ACTION_SET_STATE", t[t.ACTION_TAP = 1048583] = "ACTION_TAP", t[t.ACTION_PAN = 1048584] = "ACTION_PAN", t[t.ACTION_ZOOM = 1048585] = "ACTION_ZOOM", t[t.ACTION_FILE_UPLOAD_BEGIN = 1048586] = "ACTION_FILE_UPLOAD_BEGIN", t[t.ACTION_FILE_UPLOAD_DATA = 1048587] = "ACTION_FILE_UPLOAD_DATA", t[t.ACTION_FILE_UPLOAD_ACK = 1048588] = "ACTION_FILE_UPLOAD_ACK", t[t.ACTION_FILE_UPLOAD_END = 1048589] = "ACTION_FILE_UPLOAD_END", t[t.ACTION_FILE_UPLOAD_RESULT = 1048590] = "ACTION_FILE_UPLOAD_RESULT", t[t.ACTION_OPEN_CHANNEL = 1048591] = "ACTION_OPEN_CHANNEL", t[t.ACTION_OPEN_EXTERNAL_URL = 1048592] = "ACTION_OPEN_EXTERNAL_URL", t[t.ACTION_UI_OPEN_VIEW = 1048593] = "ACTION_UI_OPEN_VIEW", t[t.ACTION_UI_CLOSE_VIEW = 1048594] = "ACTION_UI_CLOSE_VIEW", t[t.ACTION_UI_BLOCKING_BEGIN = 1048595] = "ACTION_UI_BLOCKING_BEGIN", t[t.ACTION_UI_BLOCKING_END = 1048596] = "ACTION_UI_BLOCKING_END", t[t.ACTION_UI_UPDATE_TEXT_DELTA = 1048597] = "ACTION_UI_UPDATE_TEXT_DELTA", t[t.ACTION_UI_DELETE_CONTAINER = 1048598] = "ACTION_UI_DELETE_CONTAINER", t[t.ACTION_UPDATE_GFX_SHADER = 1048599] = "ACTION_UPDATE_GFX_SHADER", t[t.ACTION_FUNCTION_REGISTER = 1048600] = "ACTION_FUNCTION_REGISTER", t[t.ACTION_FUNCTION_CALL = 1048601] = "ACTION_FUNCTION_CALL", t[t.ACTION_FUNCTION_RESULT = 1048602] = "ACTION_FUNCTION_RESULT", t[t.ACTION_GENERATE_ANSWER = 1048603] = "ACTION_GENERATE_ANSWER", t[t.ACTION_REGENERATE_ANSWER = 1048604] = "ACTION_REGENERATE_ANSWER", t[t.ACTION_CLEAR_CHAT_MESSAGE_HISTORY = 1048605] = "ACTION_CLEAR_CHAT_MESSAGE_HISTORY", t[t.ACTION_CLEAR_STATE = 1048606] = "ACTION_CLEAR_STATE", t[t.ACTION_RELOAD_CHANNELS = 1048607] = "ACTION_RELOAD_CHANNELS", t[t.ACTION_RELOAD_PROFILE = 1048608] = "ACTION_RELOAD_PROFILE", t[t.ACTION_CLASSIFICATION_RESULT = 1048609] = "ACTION_CLASSIFICATION_RESULT", t[t.ACTION_AUDIO_STOP = 1048610] = "ACTION_AUDIO_STOP", t[t.ACTION_CALL_TEXT = 1048611] = "ACTION_CALL_TEXT", t[t.ACTION_RELOAD_APPLICATION = 1048612] = "ACTION_RELOAD_APPLICATION", t[t.ACTION_CANCEL_GENERATION = 1048613] = "ACTION_CANCEL_GENERATION", t[t.ACTION_UI_SET_CONTAINER_STABLE = 1048614] = "ACTION_UI_SET_CONTAINER_STABLE", t[t.ACTION_SPEECH_RECOGNIZED = 1048615] = "ACTION_SPEECH_RECOGNIZED", t[t.ACTION_CALL_RESULT = 1048616] = "ACTION_CALL_RESULT", t[t.ACTION_RELOAD_PROVIDER = 1048617] = "ACTION_RELOAD_PROVIDER", t[t.ACTION_DOWNLOAD = 1048618] = "ACTION_DOWNLOAD", t[t.ACTION_SCROLL_TO_CONTAINER = 1048619] = "ACTION_SCROLL_TO_CONTAINER", t[t.ACTION_UI_CLEAR_STREAM = 1048620] = "ACTION_UI_CLEAR_STREAM", t[t.ACTION_PLAY_SOUND = 1048621] = "ACTION_PLAY_SOUND", t[t.ACTION_ENTER_FULLSCREEN = 1048622] = "ACTION_ENTER_FULLSCREEN", t[t.ACTION_STOP_SOUND = 1048623] = "ACTION_STOP_SOUND", t[t.ACTION_START_RECORDING = 1048624] = "ACTION_START_RECORDING", t[t.ACTION_STOP_RECORDING = 1048625] = "ACTION_STOP_RECORDING", t[t.ACTION_OPTIMISTIC_CLIENT_CALLS = 1048626] = "ACTION_OPTIMISTIC_CLIENT_CALLS", t[t.ACTION_FUNCTION_ENUMERATION_ITEM = 1048627] = "ACTION_FUNCTION_ENUMERATION_ITEM", t[t.ACTION_FUNCTION_ENUMERATION_END = 1048628] = "ACTION_FUNCTION_ENUMERATION_END", t[t.ACTION_FUNCTION_CANCEL = 1048629] = "ACTION_FUNCTION_CANCEL", t[t.ACTION_FUNCTION_DISPOSE = 1048630] = "ACTION_FUNCTION_DISPOSE", t[t.ACTION_FUNCTION_ERROR = 1048631] = "ACTION_FUNCTION_ERROR", t[t.ACTION_FUNCTION_ACK = 1048632] = "ACTION_FUNCTION_ACK", t[t.ACTION_FUNCTION_AWAITING_APPROVAL = 1048633] = "ACTION_FUNCTION_AWAITING_APPROVAL", t[t.ACTION_FUNCTION_APPROVAL_REQUIRED = 1048634] = "ACTION_FUNCTION_APPROVAL_REQUIRED", t[t.ACTION_FUNCTION_APPROVAL_RESPONSE = 1048635] = "ACTION_FUNCTION_APPROVAL_RESPONSE", t[t.UI_UPDATE_ACK = 1048636] = "UI_UPDATE_ACK", t[t.ACTION_CALL2 = 1048637] = "ACTION_CALL2", t[t.ACTION_FUNCTION_REGISTER_BATCH = 1048638] = "ACTION_FUNCTION_REGISTER_BATCH", t[t.GROUP_UI = 2097152] = "GROUP_UI", t[t.UI_STREAM_BEGIN = 2097153] = "UI_STREAM_BEGIN", t[t.UI_STREAM_END = 2097154] = "UI_STREAM_END", t[t.UI_CONTAINER_BEGIN = 2097155] = "UI_CONTAINER_BEGIN", t[t.UI_CONTAINER_END = 2097156] = "UI_CONTAINER_END", t[t.UI_SECTION_BEGIN = 2097157] = "UI_SECTION_BEGIN", t[t.UI_SECTION_END = 2097158] = "UI_SECTION_END", t[t.UI_LIST_BEGIN = 2097159] = "UI_LIST_BEGIN", t[t.UI_LIST_ITEM = 2097160] = "UI_LIST_ITEM", t[t.UI_LIST_END = 2097161] = "UI_LIST_END", t[t.UI_TEXT = 2097162] = "UI_TEXT", t[t.UI_HEADER = 2097163] = "UI_HEADER", t[t.UI_SEPARATOR = 2097164] = "UI_SEPARATOR", t[t.UI_BUTTON = 2097165] = "UI_BUTTON", t[t.UI_ICON_BUTTON = 2097166] = "UI_ICON_BUTTON", t[t.UI_IMAGE = 2097167] = "UI_IMAGE", t[t.UI_FILE = 2097168] = "UI_FILE", t[t.UI_BADGE = 2097169] = "UI_BADGE", t[t.UI_CONTENT_LINK = 2097170] = "UI_CONTENT_LINK", t[t.UI_MAP = 2097171] = "UI_MAP", t[t.UI_VEGA_CHART = 2097172] = "UI_VEGA_CHART", t[t.UI_ICON = 2097173] = "UI_ICON", t[t.UI_FILE_UPLOAD_SECTION_BEGIN = 2097174] = "UI_FILE_UPLOAD_SECTION_BEGIN", t[t.UI_FILE_UPLOAD_SECTION_END = 2097175] = "UI_FILE_UPLOAD_SECTION_END", t[t.UI_MATERIAL_SYMBOL = 2097176] = "UI_MATERIAL_SYMBOL", t[t.UI_BUTTON_BEGIN = 2097177] = "UI_BUTTON_BEGIN", t[t.UI_BUTTON_END = 2097178] = "UI_BUTTON_END", t[t.UI_CONTAINER_DELETE = 2097179] = "UI_CONTAINER_DELETE", t[t.UI_INPUT_TEXT = 2097180] = "UI_INPUT_TEXT", t[t.UI_PROGRESS_BAR = 2097181] = "UI_PROGRESS_BAR", t[t.UI_UPDATE_BEGIN = 2097182] = "UI_UPDATE_BEGIN", t[t.UI_UPDATE_END = 2097183] = "UI_UPDATE_END", t[t.UI_AUTOCOMPLETE = 2097184] = "UI_AUTOCOMPLETE", t[t.UI_CHECKBOX = 2097185] = "UI_CHECKBOX", t[t.UI_QS = 2097186] = "UI_QS", t[t.UI_ELEMENT = 2097187] = "UI_ELEMENT", t[t.UI_STYLES = 2097188] = "UI_STYLES", t[t.UI_SVG = 2097189] = "UI_SVG", t[t.UI_UPDATE = 2097190] = "UI_UPDATE", t[t.UI_INIT = 2097191] = "UI_INIT", t[t.UI_STYLES_BATCH = 2097192] = "UI_STYLES_BATCH", t[t.GROUP_COMMON = 4128768] = "GROUP_COMMON", t[t.GROUP_AUDIO = 4194304] = "GROUP_AUDIO", t[t.AUDIO_STREAM_BEGIN = 4194305] = "AUDIO_STREAM_BEGIN", t[t.AUDIO_STREAM_END = 4194306] = "AUDIO_STREAM_END", t[t.AUDIO_FRAME = 4194307] = "AUDIO_FRAME", t[t.AUDIO_FRAME_VOLUME = 4194308] = "AUDIO_FRAME_VOLUME", t[t.AUDIO_FRAME2 = 4194309] = "AUDIO_FRAME2", t[t.GROUP_VIDEO = 8388608] = "GROUP_VIDEO", t[t.VIDEO_STREAM_BEGIN = 8388609] = "VIDEO_STREAM_BEGIN", t[t.VIDEO_STREAM_END = 8388610] = "VIDEO_STREAM_END", t[t.VIDEO_FRAME = 8388611] = "VIDEO_FRAME", t[t.VIDEO_REQUEST_IDR_FRAME = 8388612] = "VIDEO_REQUEST_IDR_FRAME", t[t.VIDEO_INVALIDATE_FRAME = 8388613] = "VIDEO_INVALIDATE_FRAME", t[t.GROUP_TRACKING = 16777216] = "GROUP_TRACKING", t[t.TRACKING_STREAM_BEGIN = 16777217] = "TRACKING_STREAM_BEGIN", t[t.TRACKING_STREAM_END = 16777218] = "TRACKING_STREAM_END", t[t.TRACKING_FRAME = 16777219] = "TRACKING_FRAME", t[t.GROUP_SCENE = 33554432] = "GROUP_SCENE", t[t.SCENE_MESH = 33554433] = "SCENE_MESH", t[t.SCENE_ARRAY = 33554434] = "SCENE_ARRAY", t[t.GROUP_ALL = 67043328] = "GROUP_ALL", t[t.CONSTANT_GROUP_MASK = 2147418112] = "CONSTANT_GROUP_MASK", t))(W || {});
568
+ const Z = 1, _t = 131074;
569
+ function q(t) {
570
+ return {};
571
+ }
572
+ function It(t) {
573
+ return new B(Z).finish();
574
+ }
575
+ function tt(t, e, r) {
576
+ const s = It();
577
+ return nt(_t, s, Z, e);
578
+ }
579
+ class et extends Error {
580
+ constructor(e, r) {
581
+ super(e), this.cause = r, this.name = "ConnectionError";
582
+ }
583
+ }
584
+ class g extends et {
585
+ constructor(e, r) {
586
+ super(e, r), this.name = "TransportError";
587
+ }
588
+ }
589
+ class Q extends g {
590
+ constructor(e) {
591
+ super(`No keepalive received within ${e}ms`), this.name = "KeepaliveTimeoutError";
592
+ }
593
+ }
594
+ class Tt extends et {
595
+ constructor(e) {
596
+ super(`Maximum reconnection attempts (${e}) exceeded`), this.name = "MaxRetriesExceededError";
597
+ }
598
+ }
599
+ function ct(t, e) {
600
+ return new Promise((r, s) => {
601
+ const n = () => {
602
+ clearTimeout(i), s(new Error("Aborted"));
603
+ }, i = setTimeout(() => {
604
+ e?.removeEventListener("abort", n), r();
605
+ }, t);
606
+ if (e?.aborted) {
607
+ clearTimeout(i), s(new Error("Aborted"));
608
+ return;
609
+ }
610
+ e?.addEventListener("abort", n, { once: !0 });
611
+ });
612
+ }
613
+ let ut = 1;
614
+ function At(t, e) {
615
+ return `[${t}] ${e}`;
616
+ }
617
+ function F(t, e, r, s) {
618
+ if ((/* @__PURE__ */ new Date()).toISOString(), ut <= t) {
619
+ const n = At(e, r);
620
+ switch (t) {
621
+ case 0:
622
+ console.debug(n, ...s);
623
+ break;
624
+ case 1:
625
+ console.info(n, ...s);
626
+ break;
627
+ case 2:
628
+ console.warn(n, ...s);
629
+ break;
630
+ case 3:
631
+ console.error(n, ...s);
632
+ break;
633
+ }
634
+ }
635
+ }
636
+ function M(t) {
637
+ return {
638
+ debug(e, ...r) {
639
+ F(0, t, e, r);
640
+ },
641
+ info(e, ...r) {
642
+ F(1, t, e, r);
643
+ },
644
+ warn(e, ...r) {
645
+ F(2, t, e, r);
646
+ },
647
+ error(e, ...r) {
648
+ F(3, t, e, r);
649
+ }
650
+ };
651
+ }
652
+ const V = M("WebSocketTransport"), Nt = 1e4;
653
+ class ft {
654
+ ws = null;
655
+ keepaliveTimeout = null;
656
+ // Pre-allocated keepalive response message to avoid allocation per keepalive
657
+ keepaliveResponseMessage = null;
658
+ keepaliveTimeoutMs;
659
+ callbacks;
660
+ sessionId;
661
+ constructor(e) {
662
+ this.callbacks = e.callbacks, this.sessionId = e.sessionId, this.keepaliveTimeoutMs = e.keepaliveTimeoutMs;
663
+ }
664
+ get isConnected() {
665
+ return this.ws?.readyState === WebSocket.OPEN;
666
+ }
667
+ async connect(e, r) {
668
+ return new Promise((s, n) => {
669
+ try {
670
+ this.ws = new WebSocket(e), this.ws.binaryType = "arraybuffer";
671
+ } catch (a) {
672
+ n(new g(`Failed to create WebSocket: ${a}`, a instanceof Error ? a : void 0));
673
+ return;
674
+ }
675
+ let i = !1, o = !1;
676
+ const E = () => {
677
+ clearTimeout(l), this.ws && (this.ws.onopen = null, this.ws.onerror = null, this.ws.onclose = null, this.ws.onmessage = null);
678
+ }, l = setTimeout(() => {
679
+ o || (o = !0, E(), this.ws?.close(), n(new g("WebSocket connection timeout")));
680
+ }, Nt);
681
+ this.ws.onopen = () => {
682
+ i = !0, clearTimeout(l), this.ws.send(r), this.resetKeepaliveTimeout(), o || (o = !0, s());
683
+ }, this.ws.onerror = () => {
684
+ clearTimeout(l), V.error("WebSocket error"), o || (o = !0, E(), n(new g("WebSocket connection failed")));
685
+ }, this.ws.onclose = (a) => {
686
+ if (this.clearKeepaliveTimeout(), !i && !o) {
687
+ o = !0, E(), n(new g("WebSocket connection closed before opening"));
688
+ return;
689
+ }
690
+ const N = a.wasClean && (a.code === 1e3 || a.code === 1001), L = a.code === 1e3 || a.code === 1001, P = a.reason || `code=${a.code}`;
691
+ this.callbacks.onClose(P, N, L);
692
+ }, this.ws.onmessage = (a) => {
693
+ this.handleProtocolMessage(new Uint8Array(a.data));
694
+ };
695
+ });
696
+ }
697
+ send(e) {
698
+ this.ws?.readyState === WebSocket.OPEN ? this.ws.send(e) : V.warn("Cannot send: WebSocket not connected");
699
+ }
700
+ close() {
701
+ this.clearKeepaliveTimeout(), this.ws && (this.ws.close(1e3, "Client closing"), this.ws = null);
702
+ }
703
+ /**
704
+ * Get or create a cached keepalive response message.
705
+ */
706
+ getKeepaliveResponse() {
707
+ return this.keepaliveResponseMessage || (this.keepaliveResponseMessage = tt(q(), this.sessionId)), this.keepaliveResponseMessage;
708
+ }
709
+ handleProtocolMessage(e) {
710
+ try {
711
+ if ($(e).opcode === W.KEEPALIVE_REQUEST) {
712
+ this.send(this.getKeepaliveResponse()), this.resetKeepaliveTimeout();
713
+ return;
714
+ }
715
+ this.resetKeepaliveTimeout(), this.callbacks.onProtocolMessage(e);
716
+ } catch (r) {
717
+ V.error("Failed to process protocol message:", r), this.callbacks.onError(r instanceof Error ? r : new Error(String(r)));
718
+ }
719
+ }
720
+ resetKeepaliveTimeout() {
721
+ this.clearKeepaliveTimeout(), this.keepaliveTimeout = setTimeout(() => {
722
+ V.error(`No keepalive received in ${this.keepaliveTimeoutMs}ms, closing connection`), this.callbacks.onError(new Q(this.keepaliveTimeoutMs)), this.close();
723
+ }, this.keepaliveTimeoutMs);
724
+ }
725
+ clearKeepaliveTimeout() {
726
+ this.keepaliveTimeout && (clearTimeout(this.keepaliveTimeout), this.keepaliveTimeout = null);
727
+ }
728
+ }
729
+ const f = M("WebTransportTransport"), j = 4, Ct = 65536;
730
+ function rt() {
731
+ return typeof WebTransport < "u";
732
+ }
733
+ class yt {
734
+ transport = null;
735
+ stream = null;
736
+ reader = null;
737
+ writer = null;
738
+ keepaliveTimeout = null;
739
+ readLoopActive = !1;
740
+ // Grow-only receive buffer with offset/length tracking to minimize allocations
741
+ receiveBuffer = new Uint8Array(Ct);
742
+ receiveBufferOffset = 0;
743
+ receiveBufferLength = 0;
744
+ // Cached DataView to avoid allocation per message
745
+ receiveDataView = null;
746
+ receiveDataViewBuffer = null;
747
+ // Pre-allocated keepalive response message
748
+ keepaliveResponseMessage = null;
749
+ keepaliveTimeoutMs;
750
+ callbacks;
751
+ sessionId;
752
+ constructor(e) {
753
+ this.callbacks = e.callbacks, this.sessionId = e.sessionId, this.keepaliveTimeoutMs = e.keepaliveTimeoutMs;
754
+ }
755
+ get isConnected() {
756
+ return this.transport !== null && this.writer !== null;
757
+ }
758
+ async connect(e, r) {
759
+ if (!rt())
760
+ throw new g("WebTransport is not supported in this browser");
761
+ try {
762
+ this.transport = new WebTransport(e), await this.transport.ready, f.debug(`Connected to WebTransport entrypoint: ${e}`), this.transport.closed.then(() => {
763
+ this.handleClose("Connection closed", !0);
764
+ }).catch((s) => {
765
+ f.error("WebTransport connection closed with error:", s), this.handleClose(s.message || "Connection error", !1);
766
+ }), this.stream = await this.transport.createBidirectionalStream(), this.reader = this.stream.readable.getReader(), this.writer = this.stream.writable.getWriter(), await this.writer.write(r), this.resetKeepaliveTimeout(), this.startReadLoop();
767
+ } catch (s) {
768
+ throw this.cleanup(), new g(`Failed to connect WebTransport: ${s}`, s instanceof Error ? s : void 0);
769
+ }
770
+ }
771
+ send(e) {
772
+ if (!this.writer) {
773
+ f.warn("Cannot send: WebTransport not connected");
774
+ return;
775
+ }
776
+ this.writer.write(e).catch((r) => {
777
+ f.error("Failed to send protocol message:", r), this.callbacks.onError(r instanceof Error ? r : new Error(String(r)));
778
+ });
779
+ }
780
+ close() {
781
+ this.clearKeepaliveTimeout(), this.readLoopActive = !1, this.cleanup();
782
+ }
783
+ /**
784
+ * Start the read loop to receive messages.
785
+ */
786
+ async startReadLoop() {
787
+ if (this.reader) {
788
+ this.readLoopActive = !0;
789
+ try {
790
+ for (; this.readLoopActive && this.reader; ) {
791
+ const { value: e, done: r } = await this.reader.read();
792
+ if (r)
793
+ break;
794
+ e && (this.appendToBuffer(e), this.processBufferedMessages());
795
+ }
796
+ } catch (e) {
797
+ this.readLoopActive && (f.error("Read loop error:", e), this.callbacks.onError(e instanceof Error ? e : new Error(String(e))));
798
+ }
799
+ }
800
+ }
801
+ /**
802
+ * Append incoming data to the receive buffer using grow-only strategy.
803
+ * Compacts when offset exceeds half capacity and data is sparse.
804
+ */
805
+ appendToBuffer(e) {
806
+ const r = this.receiveBufferLength + e.length, s = this.receiveBufferOffset + this.receiveBufferLength;
807
+ if (s + e.length > this.receiveBuffer.length)
808
+ if (r > this.receiveBuffer.length) {
809
+ const n = Math.max(r, this.receiveBuffer.length * 2), i = new Uint8Array(n);
810
+ i.set(this.receiveBuffer.subarray(this.receiveBufferOffset, s)), this.receiveBuffer = i, this.receiveBufferOffset = 0, this.receiveDataViewBuffer = null;
811
+ } else
812
+ this.receiveBuffer.copyWithin(0, this.receiveBufferOffset, s), this.receiveBufferOffset = 0;
813
+ this.receiveBuffer.set(e, this.receiveBufferOffset + this.receiveBufferLength), this.receiveBufferLength += e.length;
814
+ }
815
+ /**
816
+ * Get or create a cached DataView for the receive buffer.
817
+ */
818
+ getReceiveDataView() {
819
+ const e = this.receiveBuffer.buffer;
820
+ return this.receiveDataViewBuffer !== e && (this.receiveDataViewBuffer = e, this.receiveDataView = new DataView(e)), this.receiveDataView;
821
+ }
822
+ /**
823
+ * Get or create a cached keepalive response message.
824
+ */
825
+ getKeepaliveResponse() {
826
+ return this.keepaliveResponseMessage || (this.keepaliveResponseMessage = tt(q(), this.sessionId)), this.keepaliveResponseMessage;
827
+ }
828
+ /**
829
+ * Process complete messages from the receive buffer.
830
+ * Protocol messages start with a 4-byte little-endian length field.
831
+ * Uses subarray views to avoid per-message allocations.
832
+ */
833
+ processBufferedMessages() {
834
+ const e = this.getReceiveDataView();
835
+ for (; this.receiveBufferLength >= j; ) {
836
+ const r = e.getUint32(this.receiveBufferOffset, !0);
837
+ if (r < j) {
838
+ f.error(`Invalid message length: ${r}`), this.callbacks.onError(new Error(`Invalid protocol message length: ${r}`)), this.receiveBufferOffset = 0, this.receiveBufferLength = 0;
839
+ return;
840
+ }
841
+ if (this.receiveBufferLength < r)
842
+ return;
843
+ const s = this.receiveBuffer.subarray(this.receiveBufferOffset, this.receiveBufferOffset + r);
844
+ this.receiveBufferOffset += r, this.receiveBufferLength -= r, this.handleProtocolMessage(s);
845
+ }
846
+ this.receiveBufferLength === 0 && (this.receiveBufferOffset = 0);
847
+ }
848
+ /**
849
+ * Handle incoming protocol message.
850
+ */
851
+ handleProtocolMessage(e) {
852
+ try {
853
+ if ($(e).opcode === W.KEEPALIVE_REQUEST) {
854
+ this.send(this.getKeepaliveResponse()), this.resetKeepaliveTimeout();
855
+ return;
856
+ }
857
+ this.resetKeepaliveTimeout(), this.callbacks.onProtocolMessage(e);
858
+ } catch (r) {
859
+ f.error("Failed to process protocol message:", r), this.callbacks.onError(r instanceof Error ? r : new Error(String(r)));
860
+ }
861
+ }
862
+ /**
863
+ * Handle connection close.
864
+ */
865
+ handleClose(e, r) {
866
+ this.clearKeepaliveTimeout(), this.readLoopActive = !1, this.cleanup(), this.callbacks.onClose(e, r, r);
867
+ }
868
+ /**
869
+ * Reset the keepalive timeout.
870
+ */
871
+ resetKeepaliveTimeout() {
872
+ this.clearKeepaliveTimeout(), this.keepaliveTimeout = setTimeout(() => {
873
+ f.error(`No keepalive received in ${this.keepaliveTimeoutMs}ms, closing connection`), this.callbacks.onError(new Q(this.keepaliveTimeoutMs)), this.close();
874
+ }, this.keepaliveTimeoutMs);
875
+ }
876
+ /**
877
+ * Clear the keepalive timeout.
878
+ */
879
+ clearKeepaliveTimeout() {
880
+ this.keepaliveTimeout && (clearTimeout(this.keepaliveTimeout), this.keepaliveTimeout = null);
881
+ }
882
+ /**
883
+ * Clean up resources.
884
+ */
885
+ cleanup() {
886
+ if (this.reader && (this.reader.releaseLock(), this.reader = null), this.writer && (this.writer.releaseLock(), this.writer = null), this.stream = null, this.receiveBufferOffset = 0, this.receiveBufferLength = 0, this.transport) {
887
+ try {
888
+ this.transport.close();
889
+ } catch {
890
+ }
891
+ this.transport = null;
892
+ }
893
+ }
894
+ }
895
+ const O = M("Channel");
896
+ class wt {
897
+ state = "disconnected";
898
+ transport = null;
899
+ config;
900
+ entrypoint;
901
+ constructor(e) {
902
+ this.config = e, this.entrypoint = e.entrypoint;
903
+ }
904
+ /**
905
+ * Get the current channel state.
906
+ */
907
+ get channelState() {
908
+ return this.state;
909
+ }
910
+ /**
911
+ * Get the opcode groups this channel handles.
912
+ */
913
+ get opcodeGroups() {
914
+ return this.entrypoint.OpcodeGroupsFromServer;
915
+ }
916
+ /**
917
+ * Get the entrypoint type.
918
+ */
919
+ get type() {
920
+ return this.entrypoint.Type;
921
+ }
922
+ /**
923
+ * Check if transport is connected.
924
+ */
925
+ get isConnected() {
926
+ return this.transport?.isConnected ?? !1;
927
+ }
928
+ /**
929
+ * Connect to the entrypoint.
930
+ */
931
+ async connect() {
932
+ if (this.state !== "disconnected")
933
+ throw new Error(`Cannot connect: already in state ${this.state}`);
934
+ this.setState("connecting");
935
+ try {
936
+ await this.connectTransport(), this.setState("connected");
937
+ } catch (e) {
938
+ throw O.error("Channel connection failed:", e), this.setState("disconnected"), e;
939
+ }
940
+ }
941
+ /**
942
+ * Disconnect the channel.
943
+ */
944
+ disconnect() {
945
+ this.transport && (this.transport.close(), this.transport = null), this.setState("disconnected");
946
+ }
947
+ /**
948
+ * Send a protocol message through the channel.
949
+ */
950
+ send(e) {
951
+ if (!this.transport?.isConnected) {
952
+ O.warn("Cannot send: channel not connected");
953
+ return;
954
+ }
955
+ this.transport.send(e);
956
+ }
957
+ /**
958
+ * Connect the transport to the entrypoint.
959
+ */
960
+ async connectTransport() {
961
+ const e = this.entrypoint, r = {
962
+ sessionId: this.config.sessionId,
963
+ keepaliveTimeoutMs: this.config.keepaliveTimeoutMs,
964
+ callbacks: {
965
+ onProtocolMessage: (s) => this.handleProtocolMessage(s),
966
+ onClose: (s, n, i) => this.handleClose(s, n, i),
967
+ onError: (s) => this.handleError(s)
968
+ }
969
+ };
970
+ switch (e.Type) {
971
+ case R.WebSocket:
972
+ case R.WebSocketProxy:
973
+ this.transport = new ft(r);
974
+ break;
975
+ case R.WebTransport:
976
+ case R.WebTransportProxy:
977
+ if (!rt())
978
+ throw new Error("WebTransport is not supported in this browser");
979
+ this.transport = new yt(r);
980
+ break;
981
+ default:
982
+ throw new Error(`Unsupported entrypoint type: ${R[e.Type]}`);
983
+ }
984
+ await this.transport.connect(e.Uri, e.AuthTicket);
985
+ }
986
+ /**
987
+ * Handle incoming protocol message.
988
+ */
989
+ handleProtocolMessage(e) {
990
+ try {
991
+ const r = e;
992
+ if (J(r) === W.CORE_ON_SERVER_STOPPING) {
993
+ O.debug("Received server stopping message"), this.setState("stopped"), this.transport?.close();
994
+ return;
995
+ }
996
+ this.config.onProtocolMessage?.(r);
997
+ } catch (r) {
998
+ O.error("Failed to handle protocol message:", r), this.config.onError?.(r instanceof Error ? r : new Error(String(r)));
999
+ }
1000
+ }
1001
+ /**
1002
+ * Handle transport close.
1003
+ */
1004
+ handleClose(e, r, s) {
1005
+ this.transport = null, this.config.onClose?.(e, r, s);
1006
+ }
1007
+ /**
1008
+ * Handle transport error.
1009
+ */
1010
+ handleError(e) {
1011
+ O.error("Channel error:", e), this.config.onError?.(e), e instanceof Q && this.handleClose("Keepalive timeout", !1);
1012
+ }
1013
+ /**
1014
+ * Update and notify state change.
1015
+ */
1016
+ setState(e) {
1017
+ this.state !== e && (this.state = e, this.config.onStateChange?.(e));
1018
+ }
1019
+ }
1020
+ const C = M("ChannelManager");
1021
+ class Rt {
1022
+ channels = /* @__PURE__ */ new Map();
1023
+ // keyed by opcode group
1024
+ activeType = null;
1025
+ state = "idle";
1026
+ reconnectAttempts = 0;
1027
+ shouldReconnect = !0;
1028
+ entrypoints = [];
1029
+ abortController = null;
1030
+ config;
1031
+ constructor(e) {
1032
+ this.config = e;
1033
+ }
1034
+ /**
1035
+ * Get the current state.
1036
+ */
1037
+ get managerState() {
1038
+ return this.state;
1039
+ }
1040
+ /**
1041
+ * Get the active endpoint type.
1042
+ */
1043
+ get activeEndpointType() {
1044
+ return this.activeType;
1045
+ }
1046
+ /**
1047
+ * Connect to the server using the provided entrypoints.
1048
+ */
1049
+ async connect(e) {
1050
+ if (this.state !== "idle" && this.state !== "offline")
1051
+ throw new Error(`Cannot connect: already in state ${this.state}`);
1052
+ this.entrypoints = e, this.shouldReconnect = !0, this.reconnectAttempts = 0, this.abortController = new AbortController(), await this.connectInternal();
1053
+ }
1054
+ /**
1055
+ * Disconnect all channels.
1056
+ */
1057
+ disconnect() {
1058
+ this.shouldReconnect = !1, this.abortController?.abort(), this.abortController = null, this.disconnectAll(), this.setState("idle");
1059
+ }
1060
+ /**
1061
+ * Send a protocol message to the appropriate channel.
1062
+ * The opcode group is extracted from the message automatically.
1063
+ */
1064
+ sendProtocolMessage(e) {
1065
+ const r = k(e);
1066
+ for (const [s, n] of this.channels)
1067
+ if (s & r) {
1068
+ n.send(e);
1069
+ return;
1070
+ }
1071
+ C.warn("No channel found for message");
1072
+ }
1073
+ /**
1074
+ * Send a protocol message to all channels (for broadcast messages).
1075
+ */
1076
+ sendToAll(e) {
1077
+ for (const r of this.channels.values())
1078
+ r.send(e);
1079
+ }
1080
+ /**
1081
+ * Internal connect implementation.
1082
+ * @param isReconnect - If true, don't set offline state on failure (let attemptReconnect handle it)
1083
+ */
1084
+ async connectInternal(e = !1) {
1085
+ this.setState("connecting");
1086
+ const r = this.groupByType(this.entrypoints);
1087
+ if (r.size === 0)
1088
+ throw this.setState("offline"), new Error("No entrypoints available");
1089
+ let s;
1090
+ if (this.config.orderedEndpointTypes && this.config.orderedEndpointTypes.length > 0) {
1091
+ const n = new Set(r.keys());
1092
+ s = this.config.orderedEndpointTypes.filter((i) => n.has(i));
1093
+ } else this.config.endpointSelector ? s = this.config.endpointSelector.getOrderedTypes(r) : s = Array.from(r.keys());
1094
+ for (const n of s) {
1095
+ if (!this.shouldReconnect)
1096
+ return;
1097
+ const i = r.get(n);
1098
+ try {
1099
+ await this.connectAllChannels(i), this.config.endpointSelector?.rememberWorkingType(n), this.config.onRememberWorkingType?.(n), this.activeType = n, this.reconnectAttempts = 0, this.setState("connected");
1100
+ return;
1101
+ } catch (o) {
1102
+ C.warn(`Failed to connect using ${R[n]}: ${o}`), this.disconnectAll();
1103
+ }
1104
+ }
1105
+ throw C.error("All endpoint types failed"), e || this.setState("offline"), new Error("Failed to connect using any endpoint type");
1106
+ }
1107
+ /**
1108
+ * Connect all channels for a given endpoint type in parallel.
1109
+ */
1110
+ async connectAllChannels(e) {
1111
+ if (e.length === 0)
1112
+ throw new Error("No entrypoints to connect");
1113
+ const s = (await Promise.allSettled(e.map((n) => this.connectChannel(n)))).filter((n) => n.status === "rejected");
1114
+ if (s.length > 0) {
1115
+ const n = s.map((i) => i.reason);
1116
+ throw new Error(`${s.length} channel(s) failed: ${n.join(", ")}`);
1117
+ }
1118
+ }
1119
+ /**
1120
+ * Connect a single channel.
1121
+ */
1122
+ async connectChannel(e) {
1123
+ const r = new wt({
1124
+ entrypoint: e,
1125
+ sessionId: this.config.sessionId,
1126
+ keepaliveTimeoutMs: this.config.keepaliveTimeoutMs,
1127
+ onProtocolMessage: (s) => {
1128
+ this.config.onProtocolMessage?.(s);
1129
+ },
1130
+ onStateChange: (s) => {
1131
+ this.handleChannelStateChange(e.OpcodeGroupsFromServer, s);
1132
+ },
1133
+ onClose: (s, n, i) => {
1134
+ this.handleChannelClose(e.OpcodeGroupsFromServer, s, n, i);
1135
+ },
1136
+ onError: (s) => {
1137
+ this.config.onError?.(s);
1138
+ }
1139
+ });
1140
+ await r.connect(), this.channels.set(e.OpcodeGroupsFromServer, r);
1141
+ }
1142
+ /**
1143
+ * Group entrypoints by type.
1144
+ */
1145
+ groupByType(e) {
1146
+ const r = /* @__PURE__ */ new Map();
1147
+ for (const s of e) {
1148
+ const n = r.get(s.Type) ?? [];
1149
+ n.push(s), r.set(s.Type, n);
1150
+ }
1151
+ return r;
1152
+ }
1153
+ /**
1154
+ * Handle channel state change.
1155
+ */
1156
+ handleChannelStateChange(e, r) {
1157
+ r === "stopped" && (this.shouldReconnect = !1, this.disconnectAll(), this.setState("stopped"));
1158
+ }
1159
+ /**
1160
+ * Handle channel close.
1161
+ */
1162
+ handleChannelClose(e, r, s, n) {
1163
+ if (!(this.state === "idle" || this.state === "stopped" || this.state === "offline")) {
1164
+ if (s || n) {
1165
+ C.debug("Channel closed by server"), this.shouldReconnect = !1, this.disconnectAll(), this.setState("stopped");
1166
+ return;
1167
+ }
1168
+ this.state === "connected" && (C.error("Channel closed unexpectedly, attempting reconnect"), this.disconnectAll(), this.attemptReconnect());
1169
+ }
1170
+ }
1171
+ /**
1172
+ * Attempt to reconnect with exponential backoff.
1173
+ */
1174
+ async attemptReconnect() {
1175
+ if (!this.shouldReconnect)
1176
+ return;
1177
+ if (this.reconnectAttempts >= this.config.maxReconnectAttempts) {
1178
+ C.error(`Max reconnect attempts (${this.config.maxReconnectAttempts}) reached`), this.setState("offline"), this.config.onError?.(new Tt(this.config.maxReconnectAttempts));
1179
+ return;
1180
+ }
1181
+ this.setState("reconnecting"), this.reconnectAttempts++;
1182
+ const e = this.config.reconnectBackoffMs * Math.pow(2, this.reconnectAttempts - 1);
1183
+ if (C.info(`Reconnecting in ${e}ms (attempt ${this.reconnectAttempts}/${this.config.maxReconnectAttempts})`), await ct(e, this.abortController?.signal), !!this.shouldReconnect)
1184
+ try {
1185
+ await this.connectInternal(!0);
1186
+ } catch (r) {
1187
+ C.error("Reconnect failed:", r), await this.attemptReconnect();
1188
+ }
1189
+ }
1190
+ /**
1191
+ * Disconnect all channels.
1192
+ */
1193
+ disconnectAll() {
1194
+ for (const e of this.channels.values())
1195
+ e.disconnect();
1196
+ this.channels.clear(), this.activeType = null;
1197
+ }
1198
+ /**
1199
+ * Update and notify state change.
1200
+ */
1201
+ setState(e) {
1202
+ this.state !== e && (this.state = e, this.config.onStateChange?.(e));
1203
+ }
1204
+ }
1205
+ const st = M("ProtocolWorker"), U = (t, e) => {
1206
+ self.postMessage(t, e ?? []);
1207
+ };
1208
+ let u = null, H, c = null;
1209
+ const w = [], A = [], b = /* @__PURE__ */ new Map(), T = [], I = [], y = /* @__PURE__ */ new Map(), x = [];
1210
+ function Y() {
1211
+ try {
1212
+ u?.disconnect();
1213
+ } catch (t) {
1214
+ st.warn(`Failed to disconnect channel manager: ${t}`);
1215
+ }
1216
+ u = null;
1217
+ for (let t = 0; t < A.length; t++)
1218
+ try {
1219
+ A[t].port.close();
1220
+ } catch {
1221
+ }
1222
+ w.length = 0, A.length = 0, b.clear();
1223
+ for (let t = 0; t < I.length; t++)
1224
+ try {
1225
+ I[t].port.close();
1226
+ } catch {
1227
+ }
1228
+ T.length = 0, I.length = 0, y.clear();
1229
+ }
1230
+ function v(t) {
1231
+ const e = t instanceof Error ? t : new Error(String(t));
1232
+ U({ type: "error", error: { name: e.name, message: e.message, stack: e.stack } });
1233
+ }
1234
+ function Ut(t) {
1235
+ return H === void 0 ? !0 : (k(t) & H) !== 0;
1236
+ }
1237
+ function St(t) {
1238
+ x.length = 0;
1239
+ for (let e = 0; e < A.length; e++) {
1240
+ const r = A[e];
1241
+ (r.opcodeGroupsMask & t) !== 0 && x.push(r.port);
1242
+ }
1243
+ return x;
1244
+ }
1245
+ function gt(t, e) {
1246
+ return (k(t) & e) !== 0;
1247
+ }
1248
+ function Lt(t, e) {
1249
+ if (!u || !e || typeof e != "object")
1250
+ return;
1251
+ const r = e;
1252
+ if (!(r.type !== "send" || !(r.message instanceof ArrayBuffer)))
1253
+ try {
1254
+ const s = new Uint8Array(r.message);
1255
+ if (!gt(s, t))
1256
+ return;
1257
+ u.sendProtocolMessage(s), c && c.postMessage({ direction: "sent", message: Array.from(s) });
1258
+ } catch (s) {
1259
+ v(s);
1260
+ }
1261
+ }
1262
+ async function Pt(t) {
1263
+ Y(), u = new Rt({
1264
+ sessionId: t.sessionId,
1265
+ keepaliveTimeoutMs: t.keepaliveTimeoutMs,
1266
+ reconnectBackoffMs: t.reconnectBackoffMs,
1267
+ maxReconnectAttempts: t.maxReconnectAttempts,
1268
+ orderedEndpointTypes: t.orderedEndpointTypes,
1269
+ onStateChange: (e) => {
1270
+ U({ type: "state", state: e, activeType: u?.activeEndpointType ?? void 0 });
1271
+ },
1272
+ onRememberWorkingType: () => {
1273
+ U({ type: "state", state: u?.managerState ?? "idle", activeType: u?.activeEndpointType ?? void 0 });
1274
+ },
1275
+ onError: (e) => {
1276
+ v(e);
1277
+ },
1278
+ onProtocolMessage: (e) => {
1279
+ c && c.postMessage({ direction: "received", message: Array.from(e) });
1280
+ const r = k(e), s = Ut(e), n = St(r);
1281
+ if (!(!s && n.length === 0))
1282
+ try {
1283
+ const i = $(e), o = e.buffer instanceof ArrayBuffer && e.byteOffset === 0 && e.byteLength === e.buffer.byteLength, E = n.length > 0;
1284
+ if (E && !s && n.length === 1 && o) {
1285
+ const l = e.buffer;
1286
+ n[0].postMessage({ type: "protocol", message: l, headers: i }, [l]);
1287
+ return;
1288
+ }
1289
+ if (!E && s && o) {
1290
+ const l = e.buffer;
1291
+ U({ type: "protocol", message: l, headers: i }, [l]);
1292
+ return;
1293
+ }
1294
+ if (E && o) {
1295
+ const l = e.buffer;
1296
+ n[0].postMessage({ type: "protocol", message: l, headers: i }, [l]);
1297
+ for (let a = 1; a < n.length; a++) {
1298
+ const N = e.slice().buffer;
1299
+ n[a].postMessage({ type: "protocol", message: N, headers: i }, [N]);
1300
+ }
1301
+ if (s) {
1302
+ const a = e.slice().buffer;
1303
+ U({ type: "protocol", message: a, headers: i }, [a]);
1304
+ }
1305
+ return;
1306
+ }
1307
+ if (E)
1308
+ for (const l of n) {
1309
+ const a = e.slice().buffer;
1310
+ l.postMessage({ type: "protocol", message: a, headers: i }, [a]);
1311
+ }
1312
+ if (s) {
1313
+ const l = e.slice().buffer;
1314
+ U({ type: "protocol", message: l, headers: i }, [l]);
1315
+ }
1316
+ } catch (i) {
1317
+ v(i);
1318
+ }
1319
+ }
1320
+ }), await u.connect(t.entrypoints);
1321
+ }
1322
+ self.addEventListener("message", (t) => {
1323
+ const e = t.data;
1324
+ if (e.type === "connect") {
1325
+ Pt(e).catch((r) => {
1326
+ st.error(`Failed to connect: ${r}`), v(r), Y();
1327
+ });
1328
+ return;
1329
+ }
1330
+ if (e.type === "disconnect") {
1331
+ Y(), U({ type: "state", state: "idle" });
1332
+ return;
1333
+ }
1334
+ if (e.type === "send") {
1335
+ if (!u)
1336
+ return;
1337
+ try {
1338
+ const r = new Uint8Array(e.message);
1339
+ u.sendProtocolMessage(r), c && c.postMessage({ direction: "sent", message: Array.from(r) });
1340
+ } catch (r) {
1341
+ v(r);
1342
+ }
1343
+ return;
1344
+ }
1345
+ if (e.type === "setInterest") {
1346
+ H = e.opcodeGroupsMask;
1347
+ return;
1348
+ }
1349
+ if (e.type === "enableDevtools") {
1350
+ e.enabled && !c ? c = new BroadcastChannel("ikon:devtools") : !e.enabled && c && (c.close(), c = null);
1351
+ return;
1352
+ }
1353
+ if (e.type === "attachPort") {
1354
+ try {
1355
+ e.port.start?.();
1356
+ } catch {
1357
+ }
1358
+ const r = w.length;
1359
+ w.push(e.portId), A.push({ port: e.port, opcodeGroupsMask: e.opcodeGroupsMask }), b.set(e.portId, r);
1360
+ return;
1361
+ }
1362
+ if (e.type === "detachPort") {
1363
+ const r = b.get(e.portId);
1364
+ if (r !== void 0) {
1365
+ const s = A[r];
1366
+ try {
1367
+ s.port.close();
1368
+ } catch {
1369
+ }
1370
+ const n = w.length - 1;
1371
+ if (r !== n) {
1372
+ const i = w[n];
1373
+ w[r] = i, A[r] = A[n], b.set(i, r);
1374
+ }
1375
+ w.length--, A.length--, b.delete(e.portId);
1376
+ }
1377
+ return;
1378
+ }
1379
+ if (e.type === "attachSendPort") {
1380
+ const r = y.get(e.portId);
1381
+ if (r !== void 0) {
1382
+ const i = I[r];
1383
+ try {
1384
+ i.port.close();
1385
+ } catch {
1386
+ }
1387
+ const o = T.length - 1;
1388
+ if (r !== o) {
1389
+ const E = T[o];
1390
+ T[r] = E, I[r] = I[o], y.set(E, r);
1391
+ }
1392
+ T.length--, I.length--, y.delete(e.portId);
1393
+ }
1394
+ const s = { port: e.port, opcodeGroupsMask: e.opcodeGroupsMask }, n = T.length;
1395
+ T.push(e.portId), I.push(s), y.set(e.portId, n);
1396
+ try {
1397
+ s.port.start?.();
1398
+ } catch {
1399
+ }
1400
+ s.port.addEventListener("message", (i) => {
1401
+ Lt(s.opcodeGroupsMask, i.data);
1402
+ });
1403
+ return;
1404
+ }
1405
+ if (e.type === "detachSendPort") {
1406
+ const r = y.get(e.portId);
1407
+ if (r !== void 0) {
1408
+ const s = I[r];
1409
+ try {
1410
+ s.port.close();
1411
+ } catch {
1412
+ }
1413
+ const n = T.length - 1;
1414
+ if (r !== n) {
1415
+ const i = T[n];
1416
+ T[r] = i, I[r] = I[n], y.set(i, r);
1417
+ }
1418
+ T.length--, I.length--, y.delete(e.portId);
1419
+ }
1420
+ return;
1421
+ }
1422
+ });