@azure/web-pubsub-chat-client 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4754 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+
5
+ // node_modules/@jspm/core/nodelibs/browser/chunk-DtuTasat.js
6
+ var exports$2 = {};
7
+ var _dewExec$2 = false;
8
+ function dew$2() {
9
+ if (_dewExec$2) return exports$2;
10
+ _dewExec$2 = true;
11
+ exports$2.byteLength = byteLength;
12
+ exports$2.toByteArray = toByteArray;
13
+ exports$2.fromByteArray = fromByteArray;
14
+ var lookup = [];
15
+ var revLookup = [];
16
+ var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
17
+ var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
18
+ for (var i = 0, len = code.length; i < len; ++i) {
19
+ lookup[i] = code[i];
20
+ revLookup[code.charCodeAt(i)] = i;
21
+ }
22
+ revLookup["-".charCodeAt(0)] = 62;
23
+ revLookup["_".charCodeAt(0)] = 63;
24
+ function getLens(b64) {
25
+ var len2 = b64.length;
26
+ if (len2 % 4 > 0) {
27
+ throw new Error("Invalid string. Length must be a multiple of 4");
28
+ }
29
+ var validLen = b64.indexOf("=");
30
+ if (validLen === -1) validLen = len2;
31
+ var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
32
+ return [validLen, placeHoldersLen];
33
+ }
34
+ function byteLength(b64) {
35
+ var lens = getLens(b64);
36
+ var validLen = lens[0];
37
+ var placeHoldersLen = lens[1];
38
+ return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
39
+ }
40
+ function _byteLength(b64, validLen, placeHoldersLen) {
41
+ return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
42
+ }
43
+ function toByteArray(b64) {
44
+ var tmp;
45
+ var lens = getLens(b64);
46
+ var validLen = lens[0];
47
+ var placeHoldersLen = lens[1];
48
+ var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
49
+ var curByte = 0;
50
+ var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
51
+ var i2;
52
+ for (i2 = 0; i2 < len2; i2 += 4) {
53
+ tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)];
54
+ arr[curByte++] = tmp >> 16 & 255;
55
+ arr[curByte++] = tmp >> 8 & 255;
56
+ arr[curByte++] = tmp & 255;
57
+ }
58
+ if (placeHoldersLen === 2) {
59
+ tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4;
60
+ arr[curByte++] = tmp & 255;
61
+ }
62
+ if (placeHoldersLen === 1) {
63
+ tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2;
64
+ arr[curByte++] = tmp >> 8 & 255;
65
+ arr[curByte++] = tmp & 255;
66
+ }
67
+ return arr;
68
+ }
69
+ function tripletToBase64(num) {
70
+ return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
71
+ }
72
+ function encodeChunk(uint8, start, end) {
73
+ var tmp;
74
+ var output = [];
75
+ for (var i2 = start; i2 < end; i2 += 3) {
76
+ tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255);
77
+ output.push(tripletToBase64(tmp));
78
+ }
79
+ return output.join("");
80
+ }
81
+ function fromByteArray(uint8) {
82
+ var tmp;
83
+ var len2 = uint8.length;
84
+ var extraBytes = len2 % 3;
85
+ var parts = [];
86
+ var maxChunkLength = 16383;
87
+ for (var i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) {
88
+ parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength));
89
+ }
90
+ if (extraBytes === 1) {
91
+ tmp = uint8[len2 - 1];
92
+ parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==");
93
+ } else if (extraBytes === 2) {
94
+ tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
95
+ parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=");
96
+ }
97
+ return parts.join("");
98
+ }
99
+ return exports$2;
100
+ }
101
+ var exports$1 = {};
102
+ var _dewExec$1 = false;
103
+ function dew$1() {
104
+ if (_dewExec$1) return exports$1;
105
+ _dewExec$1 = true;
106
+ exports$1.read = function(buffer, offset, isLE, mLen, nBytes) {
107
+ var e, m;
108
+ var eLen = nBytes * 8 - mLen - 1;
109
+ var eMax = (1 << eLen) - 1;
110
+ var eBias = eMax >> 1;
111
+ var nBits = -7;
112
+ var i = isLE ? nBytes - 1 : 0;
113
+ var d = isLE ? -1 : 1;
114
+ var s = buffer[offset + i];
115
+ i += d;
116
+ e = s & (1 << -nBits) - 1;
117
+ s >>= -nBits;
118
+ nBits += eLen;
119
+ for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {
120
+ }
121
+ m = e & (1 << -nBits) - 1;
122
+ e >>= -nBits;
123
+ nBits += mLen;
124
+ for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {
125
+ }
126
+ if (e === 0) {
127
+ e = 1 - eBias;
128
+ } else if (e === eMax) {
129
+ return m ? NaN : (s ? -1 : 1) * Infinity;
130
+ } else {
131
+ m = m + Math.pow(2, mLen);
132
+ e = e - eBias;
133
+ }
134
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
135
+ };
136
+ exports$1.write = function(buffer, value, offset, isLE, mLen, nBytes) {
137
+ var e, m, c;
138
+ var eLen = nBytes * 8 - mLen - 1;
139
+ var eMax = (1 << eLen) - 1;
140
+ var eBias = eMax >> 1;
141
+ var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
142
+ var i = isLE ? 0 : nBytes - 1;
143
+ var d = isLE ? 1 : -1;
144
+ var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
145
+ value = Math.abs(value);
146
+ if (isNaN(value) || value === Infinity) {
147
+ m = isNaN(value) ? 1 : 0;
148
+ e = eMax;
149
+ } else {
150
+ e = Math.floor(Math.log(value) / Math.LN2);
151
+ if (value * (c = Math.pow(2, -e)) < 1) {
152
+ e--;
153
+ c *= 2;
154
+ }
155
+ if (e + eBias >= 1) {
156
+ value += rt / c;
157
+ } else {
158
+ value += rt * Math.pow(2, 1 - eBias);
159
+ }
160
+ if (value * c >= 2) {
161
+ e++;
162
+ c /= 2;
163
+ }
164
+ if (e + eBias >= eMax) {
165
+ m = 0;
166
+ e = eMax;
167
+ } else if (e + eBias >= 1) {
168
+ m = (value * c - 1) * Math.pow(2, mLen);
169
+ e = e + eBias;
170
+ } else {
171
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
172
+ e = 0;
173
+ }
174
+ }
175
+ for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {
176
+ }
177
+ e = e << mLen | m;
178
+ eLen += mLen;
179
+ for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {
180
+ }
181
+ buffer[offset + i - d] |= s * 128;
182
+ };
183
+ return exports$1;
184
+ }
185
+ var exports = {};
186
+ var _dewExec = false;
187
+ function dew() {
188
+ if (_dewExec) return exports;
189
+ _dewExec = true;
190
+ const base64 = dew$2();
191
+ const ieee754 = dew$1();
192
+ const customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
193
+ exports.Buffer = Buffer3;
194
+ exports.SlowBuffer = SlowBuffer;
195
+ exports.INSPECT_MAX_BYTES = 50;
196
+ const K_MAX_LENGTH = 2147483647;
197
+ exports.kMaxLength = K_MAX_LENGTH;
198
+ Buffer3.TYPED_ARRAY_SUPPORT = typedArraySupport();
199
+ if (!Buffer3.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") {
200
+ console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");
201
+ }
202
+ function typedArraySupport() {
203
+ try {
204
+ const arr = new Uint8Array(1);
205
+ const proto = {
206
+ foo: function() {
207
+ return 42;
208
+ }
209
+ };
210
+ Object.setPrototypeOf(proto, Uint8Array.prototype);
211
+ Object.setPrototypeOf(arr, proto);
212
+ return arr.foo() === 42;
213
+ } catch (e) {
214
+ return false;
215
+ }
216
+ }
217
+ Object.defineProperty(Buffer3.prototype, "parent", {
218
+ enumerable: true,
219
+ get: function() {
220
+ if (!Buffer3.isBuffer(this)) return void 0;
221
+ return this.buffer;
222
+ }
223
+ });
224
+ Object.defineProperty(Buffer3.prototype, "offset", {
225
+ enumerable: true,
226
+ get: function() {
227
+ if (!Buffer3.isBuffer(this)) return void 0;
228
+ return this.byteOffset;
229
+ }
230
+ });
231
+ function createBuffer(length) {
232
+ if (length > K_MAX_LENGTH) {
233
+ throw new RangeError('The value "' + length + '" is invalid for option "size"');
234
+ }
235
+ const buf = new Uint8Array(length);
236
+ Object.setPrototypeOf(buf, Buffer3.prototype);
237
+ return buf;
238
+ }
239
+ function Buffer3(arg, encodingOrOffset, length) {
240
+ if (typeof arg === "number") {
241
+ if (typeof encodingOrOffset === "string") {
242
+ throw new TypeError('The "string" argument must be of type string. Received type number');
243
+ }
244
+ return allocUnsafe(arg);
245
+ }
246
+ return from(arg, encodingOrOffset, length);
247
+ }
248
+ Buffer3.poolSize = 8192;
249
+ function from(value, encodingOrOffset, length) {
250
+ if (typeof value === "string") {
251
+ return fromString(value, encodingOrOffset);
252
+ }
253
+ if (ArrayBuffer.isView(value)) {
254
+ return fromArrayView(value);
255
+ }
256
+ if (value == null) {
257
+ throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value);
258
+ }
259
+ if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
260
+ return fromArrayBuffer(value, encodingOrOffset, length);
261
+ }
262
+ if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
263
+ return fromArrayBuffer(value, encodingOrOffset, length);
264
+ }
265
+ if (typeof value === "number") {
266
+ throw new TypeError('The "value" argument must not be of type number. Received type number');
267
+ }
268
+ const valueOf = value.valueOf && value.valueOf();
269
+ if (valueOf != null && valueOf !== value) {
270
+ return Buffer3.from(valueOf, encodingOrOffset, length);
271
+ }
272
+ const b = fromObject(value);
273
+ if (b) return b;
274
+ if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") {
275
+ return Buffer3.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
276
+ }
277
+ throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value);
278
+ }
279
+ Buffer3.from = function(value, encodingOrOffset, length) {
280
+ return from(value, encodingOrOffset, length);
281
+ };
282
+ Object.setPrototypeOf(Buffer3.prototype, Uint8Array.prototype);
283
+ Object.setPrototypeOf(Buffer3, Uint8Array);
284
+ function assertSize(size) {
285
+ if (typeof size !== "number") {
286
+ throw new TypeError('"size" argument must be of type number');
287
+ } else if (size < 0) {
288
+ throw new RangeError('The value "' + size + '" is invalid for option "size"');
289
+ }
290
+ }
291
+ function alloc(size, fill, encoding) {
292
+ assertSize(size);
293
+ if (size <= 0) {
294
+ return createBuffer(size);
295
+ }
296
+ if (fill !== void 0) {
297
+ return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
298
+ }
299
+ return createBuffer(size);
300
+ }
301
+ Buffer3.alloc = function(size, fill, encoding) {
302
+ return alloc(size, fill, encoding);
303
+ };
304
+ function allocUnsafe(size) {
305
+ assertSize(size);
306
+ return createBuffer(size < 0 ? 0 : checked(size) | 0);
307
+ }
308
+ Buffer3.allocUnsafe = function(size) {
309
+ return allocUnsafe(size);
310
+ };
311
+ Buffer3.allocUnsafeSlow = function(size) {
312
+ return allocUnsafe(size);
313
+ };
314
+ function fromString(string, encoding) {
315
+ if (typeof encoding !== "string" || encoding === "") {
316
+ encoding = "utf8";
317
+ }
318
+ if (!Buffer3.isEncoding(encoding)) {
319
+ throw new TypeError("Unknown encoding: " + encoding);
320
+ }
321
+ const length = byteLength(string, encoding) | 0;
322
+ let buf = createBuffer(length);
323
+ const actual = buf.write(string, encoding);
324
+ if (actual !== length) {
325
+ buf = buf.slice(0, actual);
326
+ }
327
+ return buf;
328
+ }
329
+ function fromArrayLike(array) {
330
+ const length = array.length < 0 ? 0 : checked(array.length) | 0;
331
+ const buf = createBuffer(length);
332
+ for (let i = 0; i < length; i += 1) {
333
+ buf[i] = array[i] & 255;
334
+ }
335
+ return buf;
336
+ }
337
+ function fromArrayView(arrayView) {
338
+ if (isInstance(arrayView, Uint8Array)) {
339
+ const copy = new Uint8Array(arrayView);
340
+ return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
341
+ }
342
+ return fromArrayLike(arrayView);
343
+ }
344
+ function fromArrayBuffer(array, byteOffset, length) {
345
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
346
+ throw new RangeError('"offset" is outside of buffer bounds');
347
+ }
348
+ if (array.byteLength < byteOffset + (length || 0)) {
349
+ throw new RangeError('"length" is outside of buffer bounds');
350
+ }
351
+ let buf;
352
+ if (byteOffset === void 0 && length === void 0) {
353
+ buf = new Uint8Array(array);
354
+ } else if (length === void 0) {
355
+ buf = new Uint8Array(array, byteOffset);
356
+ } else {
357
+ buf = new Uint8Array(array, byteOffset, length);
358
+ }
359
+ Object.setPrototypeOf(buf, Buffer3.prototype);
360
+ return buf;
361
+ }
362
+ function fromObject(obj) {
363
+ if (Buffer3.isBuffer(obj)) {
364
+ const len = checked(obj.length) | 0;
365
+ const buf = createBuffer(len);
366
+ if (buf.length === 0) {
367
+ return buf;
368
+ }
369
+ obj.copy(buf, 0, 0, len);
370
+ return buf;
371
+ }
372
+ if (obj.length !== void 0) {
373
+ if (typeof obj.length !== "number" || numberIsNaN(obj.length)) {
374
+ return createBuffer(0);
375
+ }
376
+ return fromArrayLike(obj);
377
+ }
378
+ if (obj.type === "Buffer" && Array.isArray(obj.data)) {
379
+ return fromArrayLike(obj.data);
380
+ }
381
+ }
382
+ function checked(length) {
383
+ if (length >= K_MAX_LENGTH) {
384
+ throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
385
+ }
386
+ return length | 0;
387
+ }
388
+ function SlowBuffer(length) {
389
+ if (+length != length) {
390
+ length = 0;
391
+ }
392
+ return Buffer3.alloc(+length);
393
+ }
394
+ Buffer3.isBuffer = function isBuffer(b) {
395
+ return b != null && b._isBuffer === true && b !== Buffer3.prototype;
396
+ };
397
+ Buffer3.compare = function compare(a, b) {
398
+ if (isInstance(a, Uint8Array)) a = Buffer3.from(a, a.offset, a.byteLength);
399
+ if (isInstance(b, Uint8Array)) b = Buffer3.from(b, b.offset, b.byteLength);
400
+ if (!Buffer3.isBuffer(a) || !Buffer3.isBuffer(b)) {
401
+ throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
402
+ }
403
+ if (a === b) return 0;
404
+ let x = a.length;
405
+ let y = b.length;
406
+ for (let i = 0, len = Math.min(x, y); i < len; ++i) {
407
+ if (a[i] !== b[i]) {
408
+ x = a[i];
409
+ y = b[i];
410
+ break;
411
+ }
412
+ }
413
+ if (x < y) return -1;
414
+ if (y < x) return 1;
415
+ return 0;
416
+ };
417
+ Buffer3.isEncoding = function isEncoding(encoding) {
418
+ switch (String(encoding).toLowerCase()) {
419
+ case "hex":
420
+ case "utf8":
421
+ case "utf-8":
422
+ case "ascii":
423
+ case "latin1":
424
+ case "binary":
425
+ case "base64":
426
+ case "ucs2":
427
+ case "ucs-2":
428
+ case "utf16le":
429
+ case "utf-16le":
430
+ return true;
431
+ default:
432
+ return false;
433
+ }
434
+ };
435
+ Buffer3.concat = function concat(list, length) {
436
+ if (!Array.isArray(list)) {
437
+ throw new TypeError('"list" argument must be an Array of Buffers');
438
+ }
439
+ if (list.length === 0) {
440
+ return Buffer3.alloc(0);
441
+ }
442
+ let i;
443
+ if (length === void 0) {
444
+ length = 0;
445
+ for (i = 0; i < list.length; ++i) {
446
+ length += list[i].length;
447
+ }
448
+ }
449
+ const buffer = Buffer3.allocUnsafe(length);
450
+ let pos = 0;
451
+ for (i = 0; i < list.length; ++i) {
452
+ let buf = list[i];
453
+ if (isInstance(buf, Uint8Array)) {
454
+ if (pos + buf.length > buffer.length) {
455
+ if (!Buffer3.isBuffer(buf)) buf = Buffer3.from(buf);
456
+ buf.copy(buffer, pos);
457
+ } else {
458
+ Uint8Array.prototype.set.call(buffer, buf, pos);
459
+ }
460
+ } else if (!Buffer3.isBuffer(buf)) {
461
+ throw new TypeError('"list" argument must be an Array of Buffers');
462
+ } else {
463
+ buf.copy(buffer, pos);
464
+ }
465
+ pos += buf.length;
466
+ }
467
+ return buffer;
468
+ };
469
+ function byteLength(string, encoding) {
470
+ if (Buffer3.isBuffer(string)) {
471
+ return string.length;
472
+ }
473
+ if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
474
+ return string.byteLength;
475
+ }
476
+ if (typeof string !== "string") {
477
+ throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string);
478
+ }
479
+ const len = string.length;
480
+ const mustMatch = arguments.length > 2 && arguments[2] === true;
481
+ if (!mustMatch && len === 0) return 0;
482
+ let loweredCase = false;
483
+ for (; ; ) {
484
+ switch (encoding) {
485
+ case "ascii":
486
+ case "latin1":
487
+ case "binary":
488
+ return len;
489
+ case "utf8":
490
+ case "utf-8":
491
+ return utf8ToBytes(string).length;
492
+ case "ucs2":
493
+ case "ucs-2":
494
+ case "utf16le":
495
+ case "utf-16le":
496
+ return len * 2;
497
+ case "hex":
498
+ return len >>> 1;
499
+ case "base64":
500
+ return base64ToBytes(string).length;
501
+ default:
502
+ if (loweredCase) {
503
+ return mustMatch ? -1 : utf8ToBytes(string).length;
504
+ }
505
+ encoding = ("" + encoding).toLowerCase();
506
+ loweredCase = true;
507
+ }
508
+ }
509
+ }
510
+ Buffer3.byteLength = byteLength;
511
+ function slowToString(encoding, start, end) {
512
+ let loweredCase = false;
513
+ if (start === void 0 || start < 0) {
514
+ start = 0;
515
+ }
516
+ if (start > this.length) {
517
+ return "";
518
+ }
519
+ if (end === void 0 || end > this.length) {
520
+ end = this.length;
521
+ }
522
+ if (end <= 0) {
523
+ return "";
524
+ }
525
+ end >>>= 0;
526
+ start >>>= 0;
527
+ if (end <= start) {
528
+ return "";
529
+ }
530
+ if (!encoding) encoding = "utf8";
531
+ while (true) {
532
+ switch (encoding) {
533
+ case "hex":
534
+ return hexSlice(this, start, end);
535
+ case "utf8":
536
+ case "utf-8":
537
+ return utf8Slice(this, start, end);
538
+ case "ascii":
539
+ return asciiSlice(this, start, end);
540
+ case "latin1":
541
+ case "binary":
542
+ return latin1Slice(this, start, end);
543
+ case "base64":
544
+ return base64Slice(this, start, end);
545
+ case "ucs2":
546
+ case "ucs-2":
547
+ case "utf16le":
548
+ case "utf-16le":
549
+ return utf16leSlice(this, start, end);
550
+ default:
551
+ if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
552
+ encoding = (encoding + "").toLowerCase();
553
+ loweredCase = true;
554
+ }
555
+ }
556
+ }
557
+ Buffer3.prototype._isBuffer = true;
558
+ function swap(b, n, m) {
559
+ const i = b[n];
560
+ b[n] = b[m];
561
+ b[m] = i;
562
+ }
563
+ Buffer3.prototype.swap16 = function swap16() {
564
+ const len = this.length;
565
+ if (len % 2 !== 0) {
566
+ throw new RangeError("Buffer size must be a multiple of 16-bits");
567
+ }
568
+ for (let i = 0; i < len; i += 2) {
569
+ swap(this, i, i + 1);
570
+ }
571
+ return this;
572
+ };
573
+ Buffer3.prototype.swap32 = function swap32() {
574
+ const len = this.length;
575
+ if (len % 4 !== 0) {
576
+ throw new RangeError("Buffer size must be a multiple of 32-bits");
577
+ }
578
+ for (let i = 0; i < len; i += 4) {
579
+ swap(this, i, i + 3);
580
+ swap(this, i + 1, i + 2);
581
+ }
582
+ return this;
583
+ };
584
+ Buffer3.prototype.swap64 = function swap64() {
585
+ const len = this.length;
586
+ if (len % 8 !== 0) {
587
+ throw new RangeError("Buffer size must be a multiple of 64-bits");
588
+ }
589
+ for (let i = 0; i < len; i += 8) {
590
+ swap(this, i, i + 7);
591
+ swap(this, i + 1, i + 6);
592
+ swap(this, i + 2, i + 5);
593
+ swap(this, i + 3, i + 4);
594
+ }
595
+ return this;
596
+ };
597
+ Buffer3.prototype.toString = function toString() {
598
+ const length = this.length;
599
+ if (length === 0) return "";
600
+ if (arguments.length === 0) return utf8Slice(this, 0, length);
601
+ return slowToString.apply(this, arguments);
602
+ };
603
+ Buffer3.prototype.toLocaleString = Buffer3.prototype.toString;
604
+ Buffer3.prototype.equals = function equals(b) {
605
+ if (!Buffer3.isBuffer(b)) throw new TypeError("Argument must be a Buffer");
606
+ if (this === b) return true;
607
+ return Buffer3.compare(this, b) === 0;
608
+ };
609
+ Buffer3.prototype.inspect = function inspect() {
610
+ let str = "";
611
+ const max = exports.INSPECT_MAX_BYTES;
612
+ str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim();
613
+ if (this.length > max) str += " ... ";
614
+ return "<Buffer " + str + ">";
615
+ };
616
+ if (customInspectSymbol) {
617
+ Buffer3.prototype[customInspectSymbol] = Buffer3.prototype.inspect;
618
+ }
619
+ Buffer3.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
620
+ if (isInstance(target, Uint8Array)) {
621
+ target = Buffer3.from(target, target.offset, target.byteLength);
622
+ }
623
+ if (!Buffer3.isBuffer(target)) {
624
+ throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target);
625
+ }
626
+ if (start === void 0) {
627
+ start = 0;
628
+ }
629
+ if (end === void 0) {
630
+ end = target ? target.length : 0;
631
+ }
632
+ if (thisStart === void 0) {
633
+ thisStart = 0;
634
+ }
635
+ if (thisEnd === void 0) {
636
+ thisEnd = this.length;
637
+ }
638
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
639
+ throw new RangeError("out of range index");
640
+ }
641
+ if (thisStart >= thisEnd && start >= end) {
642
+ return 0;
643
+ }
644
+ if (thisStart >= thisEnd) {
645
+ return -1;
646
+ }
647
+ if (start >= end) {
648
+ return 1;
649
+ }
650
+ start >>>= 0;
651
+ end >>>= 0;
652
+ thisStart >>>= 0;
653
+ thisEnd >>>= 0;
654
+ if (this === target) return 0;
655
+ let x = thisEnd - thisStart;
656
+ let y = end - start;
657
+ const len = Math.min(x, y);
658
+ const thisCopy = this.slice(thisStart, thisEnd);
659
+ const targetCopy = target.slice(start, end);
660
+ for (let i = 0; i < len; ++i) {
661
+ if (thisCopy[i] !== targetCopy[i]) {
662
+ x = thisCopy[i];
663
+ y = targetCopy[i];
664
+ break;
665
+ }
666
+ }
667
+ if (x < y) return -1;
668
+ if (y < x) return 1;
669
+ return 0;
670
+ };
671
+ function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
672
+ if (buffer.length === 0) return -1;
673
+ if (typeof byteOffset === "string") {
674
+ encoding = byteOffset;
675
+ byteOffset = 0;
676
+ } else if (byteOffset > 2147483647) {
677
+ byteOffset = 2147483647;
678
+ } else if (byteOffset < -2147483648) {
679
+ byteOffset = -2147483648;
680
+ }
681
+ byteOffset = +byteOffset;
682
+ if (numberIsNaN(byteOffset)) {
683
+ byteOffset = dir ? 0 : buffer.length - 1;
684
+ }
685
+ if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
686
+ if (byteOffset >= buffer.length) {
687
+ if (dir) return -1;
688
+ else byteOffset = buffer.length - 1;
689
+ } else if (byteOffset < 0) {
690
+ if (dir) byteOffset = 0;
691
+ else return -1;
692
+ }
693
+ if (typeof val === "string") {
694
+ val = Buffer3.from(val, encoding);
695
+ }
696
+ if (Buffer3.isBuffer(val)) {
697
+ if (val.length === 0) {
698
+ return -1;
699
+ }
700
+ return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
701
+ } else if (typeof val === "number") {
702
+ val = val & 255;
703
+ if (typeof Uint8Array.prototype.indexOf === "function") {
704
+ if (dir) {
705
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
706
+ } else {
707
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
708
+ }
709
+ }
710
+ return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
711
+ }
712
+ throw new TypeError("val must be string, number or Buffer");
713
+ }
714
+ function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
715
+ let indexSize = 1;
716
+ let arrLength = arr.length;
717
+ let valLength = val.length;
718
+ if (encoding !== void 0) {
719
+ encoding = String(encoding).toLowerCase();
720
+ if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
721
+ if (arr.length < 2 || val.length < 2) {
722
+ return -1;
723
+ }
724
+ indexSize = 2;
725
+ arrLength /= 2;
726
+ valLength /= 2;
727
+ byteOffset /= 2;
728
+ }
729
+ }
730
+ function read(buf, i2) {
731
+ if (indexSize === 1) {
732
+ return buf[i2];
733
+ } else {
734
+ return buf.readUInt16BE(i2 * indexSize);
735
+ }
736
+ }
737
+ let i;
738
+ if (dir) {
739
+ let foundIndex = -1;
740
+ for (i = byteOffset; i < arrLength; i++) {
741
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
742
+ if (foundIndex === -1) foundIndex = i;
743
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
744
+ } else {
745
+ if (foundIndex !== -1) i -= i - foundIndex;
746
+ foundIndex = -1;
747
+ }
748
+ }
749
+ } else {
750
+ if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
751
+ for (i = byteOffset; i >= 0; i--) {
752
+ let found = true;
753
+ for (let j = 0; j < valLength; j++) {
754
+ if (read(arr, i + j) !== read(val, j)) {
755
+ found = false;
756
+ break;
757
+ }
758
+ }
759
+ if (found) return i;
760
+ }
761
+ }
762
+ return -1;
763
+ }
764
+ Buffer3.prototype.includes = function includes(val, byteOffset, encoding) {
765
+ return this.indexOf(val, byteOffset, encoding) !== -1;
766
+ };
767
+ Buffer3.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
768
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
769
+ };
770
+ Buffer3.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
771
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
772
+ };
773
+ function hexWrite(buf, string, offset, length) {
774
+ offset = Number(offset) || 0;
775
+ const remaining = buf.length - offset;
776
+ if (!length) {
777
+ length = remaining;
778
+ } else {
779
+ length = Number(length);
780
+ if (length > remaining) {
781
+ length = remaining;
782
+ }
783
+ }
784
+ const strLen = string.length;
785
+ if (length > strLen / 2) {
786
+ length = strLen / 2;
787
+ }
788
+ let i;
789
+ for (i = 0; i < length; ++i) {
790
+ const parsed = parseInt(string.substr(i * 2, 2), 16);
791
+ if (numberIsNaN(parsed)) return i;
792
+ buf[offset + i] = parsed;
793
+ }
794
+ return i;
795
+ }
796
+ function utf8Write(buf, string, offset, length) {
797
+ return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
798
+ }
799
+ function asciiWrite(buf, string, offset, length) {
800
+ return blitBuffer(asciiToBytes(string), buf, offset, length);
801
+ }
802
+ function base64Write(buf, string, offset, length) {
803
+ return blitBuffer(base64ToBytes(string), buf, offset, length);
804
+ }
805
+ function ucs2Write(buf, string, offset, length) {
806
+ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
807
+ }
808
+ Buffer3.prototype.write = function write(string, offset, length, encoding) {
809
+ if (offset === void 0) {
810
+ encoding = "utf8";
811
+ length = this.length;
812
+ offset = 0;
813
+ } else if (length === void 0 && typeof offset === "string") {
814
+ encoding = offset;
815
+ length = this.length;
816
+ offset = 0;
817
+ } else if (isFinite(offset)) {
818
+ offset = offset >>> 0;
819
+ if (isFinite(length)) {
820
+ length = length >>> 0;
821
+ if (encoding === void 0) encoding = "utf8";
822
+ } else {
823
+ encoding = length;
824
+ length = void 0;
825
+ }
826
+ } else {
827
+ throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");
828
+ }
829
+ const remaining = this.length - offset;
830
+ if (length === void 0 || length > remaining) length = remaining;
831
+ if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
832
+ throw new RangeError("Attempt to write outside buffer bounds");
833
+ }
834
+ if (!encoding) encoding = "utf8";
835
+ let loweredCase = false;
836
+ for (; ; ) {
837
+ switch (encoding) {
838
+ case "hex":
839
+ return hexWrite(this, string, offset, length);
840
+ case "utf8":
841
+ case "utf-8":
842
+ return utf8Write(this, string, offset, length);
843
+ case "ascii":
844
+ case "latin1":
845
+ case "binary":
846
+ return asciiWrite(this, string, offset, length);
847
+ case "base64":
848
+ return base64Write(this, string, offset, length);
849
+ case "ucs2":
850
+ case "ucs-2":
851
+ case "utf16le":
852
+ case "utf-16le":
853
+ return ucs2Write(this, string, offset, length);
854
+ default:
855
+ if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
856
+ encoding = ("" + encoding).toLowerCase();
857
+ loweredCase = true;
858
+ }
859
+ }
860
+ };
861
+ Buffer3.prototype.toJSON = function toJSON() {
862
+ return {
863
+ type: "Buffer",
864
+ data: Array.prototype.slice.call(this._arr || this, 0)
865
+ };
866
+ };
867
+ function base64Slice(buf, start, end) {
868
+ if (start === 0 && end === buf.length) {
869
+ return base64.fromByteArray(buf);
870
+ } else {
871
+ return base64.fromByteArray(buf.slice(start, end));
872
+ }
873
+ }
874
+ function utf8Slice(buf, start, end) {
875
+ end = Math.min(buf.length, end);
876
+ const res = [];
877
+ let i = start;
878
+ while (i < end) {
879
+ const firstByte = buf[i];
880
+ let codePoint = null;
881
+ let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
882
+ if (i + bytesPerSequence <= end) {
883
+ let secondByte, thirdByte, fourthByte, tempCodePoint;
884
+ switch (bytesPerSequence) {
885
+ case 1:
886
+ if (firstByte < 128) {
887
+ codePoint = firstByte;
888
+ }
889
+ break;
890
+ case 2:
891
+ secondByte = buf[i + 1];
892
+ if ((secondByte & 192) === 128) {
893
+ tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
894
+ if (tempCodePoint > 127) {
895
+ codePoint = tempCodePoint;
896
+ }
897
+ }
898
+ break;
899
+ case 3:
900
+ secondByte = buf[i + 1];
901
+ thirdByte = buf[i + 2];
902
+ if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
903
+ tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
904
+ if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
905
+ codePoint = tempCodePoint;
906
+ }
907
+ }
908
+ break;
909
+ case 4:
910
+ secondByte = buf[i + 1];
911
+ thirdByte = buf[i + 2];
912
+ fourthByte = buf[i + 3];
913
+ if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
914
+ tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
915
+ if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
916
+ codePoint = tempCodePoint;
917
+ }
918
+ }
919
+ }
920
+ }
921
+ if (codePoint === null) {
922
+ codePoint = 65533;
923
+ bytesPerSequence = 1;
924
+ } else if (codePoint > 65535) {
925
+ codePoint -= 65536;
926
+ res.push(codePoint >>> 10 & 1023 | 55296);
927
+ codePoint = 56320 | codePoint & 1023;
928
+ }
929
+ res.push(codePoint);
930
+ i += bytesPerSequence;
931
+ }
932
+ return decodeCodePointsArray(res);
933
+ }
934
+ const MAX_ARGUMENTS_LENGTH = 4096;
935
+ function decodeCodePointsArray(codePoints) {
936
+ const len = codePoints.length;
937
+ if (len <= MAX_ARGUMENTS_LENGTH) {
938
+ return String.fromCharCode.apply(String, codePoints);
939
+ }
940
+ let res = "";
941
+ let i = 0;
942
+ while (i < len) {
943
+ res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
944
+ }
945
+ return res;
946
+ }
947
+ function asciiSlice(buf, start, end) {
948
+ let ret = "";
949
+ end = Math.min(buf.length, end);
950
+ for (let i = start; i < end; ++i) {
951
+ ret += String.fromCharCode(buf[i] & 127);
952
+ }
953
+ return ret;
954
+ }
955
+ function latin1Slice(buf, start, end) {
956
+ let ret = "";
957
+ end = Math.min(buf.length, end);
958
+ for (let i = start; i < end; ++i) {
959
+ ret += String.fromCharCode(buf[i]);
960
+ }
961
+ return ret;
962
+ }
963
+ function hexSlice(buf, start, end) {
964
+ const len = buf.length;
965
+ if (!start || start < 0) start = 0;
966
+ if (!end || end < 0 || end > len) end = len;
967
+ let out = "";
968
+ for (let i = start; i < end; ++i) {
969
+ out += hexSliceLookupTable[buf[i]];
970
+ }
971
+ return out;
972
+ }
973
+ function utf16leSlice(buf, start, end) {
974
+ const bytes = buf.slice(start, end);
975
+ let res = "";
976
+ for (let i = 0; i < bytes.length - 1; i += 2) {
977
+ res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
978
+ }
979
+ return res;
980
+ }
981
+ Buffer3.prototype.slice = function slice(start, end) {
982
+ const len = this.length;
983
+ start = ~~start;
984
+ end = end === void 0 ? len : ~~end;
985
+ if (start < 0) {
986
+ start += len;
987
+ if (start < 0) start = 0;
988
+ } else if (start > len) {
989
+ start = len;
990
+ }
991
+ if (end < 0) {
992
+ end += len;
993
+ if (end < 0) end = 0;
994
+ } else if (end > len) {
995
+ end = len;
996
+ }
997
+ if (end < start) end = start;
998
+ const newBuf = this.subarray(start, end);
999
+ Object.setPrototypeOf(newBuf, Buffer3.prototype);
1000
+ return newBuf;
1001
+ };
1002
+ function checkOffset(offset, ext, length) {
1003
+ if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint");
1004
+ if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length");
1005
+ }
1006
+ Buffer3.prototype.readUintLE = Buffer3.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) {
1007
+ offset = offset >>> 0;
1008
+ byteLength2 = byteLength2 >>> 0;
1009
+ if (!noAssert) checkOffset(offset, byteLength2, this.length);
1010
+ let val = this[offset];
1011
+ let mul = 1;
1012
+ let i = 0;
1013
+ while (++i < byteLength2 && (mul *= 256)) {
1014
+ val += this[offset + i] * mul;
1015
+ }
1016
+ return val;
1017
+ };
1018
+ Buffer3.prototype.readUintBE = Buffer3.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) {
1019
+ offset = offset >>> 0;
1020
+ byteLength2 = byteLength2 >>> 0;
1021
+ if (!noAssert) {
1022
+ checkOffset(offset, byteLength2, this.length);
1023
+ }
1024
+ let val = this[offset + --byteLength2];
1025
+ let mul = 1;
1026
+ while (byteLength2 > 0 && (mul *= 256)) {
1027
+ val += this[offset + --byteLength2] * mul;
1028
+ }
1029
+ return val;
1030
+ };
1031
+ Buffer3.prototype.readUint8 = Buffer3.prototype.readUInt8 = function readUInt8(offset, noAssert) {
1032
+ offset = offset >>> 0;
1033
+ if (!noAssert) checkOffset(offset, 1, this.length);
1034
+ return this[offset];
1035
+ };
1036
+ Buffer3.prototype.readUint16LE = Buffer3.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
1037
+ offset = offset >>> 0;
1038
+ if (!noAssert) checkOffset(offset, 2, this.length);
1039
+ return this[offset] | this[offset + 1] << 8;
1040
+ };
1041
+ Buffer3.prototype.readUint16BE = Buffer3.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
1042
+ offset = offset >>> 0;
1043
+ if (!noAssert) checkOffset(offset, 2, this.length);
1044
+ return this[offset] << 8 | this[offset + 1];
1045
+ };
1046
+ Buffer3.prototype.readUint32LE = Buffer3.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
1047
+ offset = offset >>> 0;
1048
+ if (!noAssert) checkOffset(offset, 4, this.length);
1049
+ return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
1050
+ };
1051
+ Buffer3.prototype.readUint32BE = Buffer3.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
1052
+ offset = offset >>> 0;
1053
+ if (!noAssert) checkOffset(offset, 4, this.length);
1054
+ return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
1055
+ };
1056
+ Buffer3.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) {
1057
+ offset = offset >>> 0;
1058
+ validateNumber(offset, "offset");
1059
+ const first = this[offset];
1060
+ const last = this[offset + 7];
1061
+ if (first === void 0 || last === void 0) {
1062
+ boundsError(offset, this.length - 8);
1063
+ }
1064
+ const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24;
1065
+ const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24;
1066
+ return BigInt(lo) + (BigInt(hi) << BigInt(32));
1067
+ });
1068
+ Buffer3.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) {
1069
+ offset = offset >>> 0;
1070
+ validateNumber(offset, "offset");
1071
+ const first = this[offset];
1072
+ const last = this[offset + 7];
1073
+ if (first === void 0 || last === void 0) {
1074
+ boundsError(offset, this.length - 8);
1075
+ }
1076
+ const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
1077
+ const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last;
1078
+ return (BigInt(hi) << BigInt(32)) + BigInt(lo);
1079
+ });
1080
+ Buffer3.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) {
1081
+ offset = offset >>> 0;
1082
+ byteLength2 = byteLength2 >>> 0;
1083
+ if (!noAssert) checkOffset(offset, byteLength2, this.length);
1084
+ let val = this[offset];
1085
+ let mul = 1;
1086
+ let i = 0;
1087
+ while (++i < byteLength2 && (mul *= 256)) {
1088
+ val += this[offset + i] * mul;
1089
+ }
1090
+ mul *= 128;
1091
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
1092
+ return val;
1093
+ };
1094
+ Buffer3.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) {
1095
+ offset = offset >>> 0;
1096
+ byteLength2 = byteLength2 >>> 0;
1097
+ if (!noAssert) checkOffset(offset, byteLength2, this.length);
1098
+ let i = byteLength2;
1099
+ let mul = 1;
1100
+ let val = this[offset + --i];
1101
+ while (i > 0 && (mul *= 256)) {
1102
+ val += this[offset + --i] * mul;
1103
+ }
1104
+ mul *= 128;
1105
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
1106
+ return val;
1107
+ };
1108
+ Buffer3.prototype.readInt8 = function readInt8(offset, noAssert) {
1109
+ offset = offset >>> 0;
1110
+ if (!noAssert) checkOffset(offset, 1, this.length);
1111
+ if (!(this[offset] & 128)) return this[offset];
1112
+ return (255 - this[offset] + 1) * -1;
1113
+ };
1114
+ Buffer3.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
1115
+ offset = offset >>> 0;
1116
+ if (!noAssert) checkOffset(offset, 2, this.length);
1117
+ const val = this[offset] | this[offset + 1] << 8;
1118
+ return val & 32768 ? val | 4294901760 : val;
1119
+ };
1120
+ Buffer3.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
1121
+ offset = offset >>> 0;
1122
+ if (!noAssert) checkOffset(offset, 2, this.length);
1123
+ const val = this[offset + 1] | this[offset] << 8;
1124
+ return val & 32768 ? val | 4294901760 : val;
1125
+ };
1126
+ Buffer3.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
1127
+ offset = offset >>> 0;
1128
+ if (!noAssert) checkOffset(offset, 4, this.length);
1129
+ return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
1130
+ };
1131
+ Buffer3.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
1132
+ offset = offset >>> 0;
1133
+ if (!noAssert) checkOffset(offset, 4, this.length);
1134
+ return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
1135
+ };
1136
+ Buffer3.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) {
1137
+ offset = offset >>> 0;
1138
+ validateNumber(offset, "offset");
1139
+ const first = this[offset];
1140
+ const last = this[offset + 7];
1141
+ if (first === void 0 || last === void 0) {
1142
+ boundsError(offset, this.length - 8);
1143
+ }
1144
+ const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24);
1145
+ return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24);
1146
+ });
1147
+ Buffer3.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) {
1148
+ offset = offset >>> 0;
1149
+ validateNumber(offset, "offset");
1150
+ const first = this[offset];
1151
+ const last = this[offset + 7];
1152
+ if (first === void 0 || last === void 0) {
1153
+ boundsError(offset, this.length - 8);
1154
+ }
1155
+ const val = (first << 24) + // Overflow
1156
+ this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
1157
+ return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last);
1158
+ });
1159
+ Buffer3.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
1160
+ offset = offset >>> 0;
1161
+ if (!noAssert) checkOffset(offset, 4, this.length);
1162
+ return ieee754.read(this, offset, true, 23, 4);
1163
+ };
1164
+ Buffer3.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
1165
+ offset = offset >>> 0;
1166
+ if (!noAssert) checkOffset(offset, 4, this.length);
1167
+ return ieee754.read(this, offset, false, 23, 4);
1168
+ };
1169
+ Buffer3.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
1170
+ offset = offset >>> 0;
1171
+ if (!noAssert) checkOffset(offset, 8, this.length);
1172
+ return ieee754.read(this, offset, true, 52, 8);
1173
+ };
1174
+ Buffer3.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
1175
+ offset = offset >>> 0;
1176
+ if (!noAssert) checkOffset(offset, 8, this.length);
1177
+ return ieee754.read(this, offset, false, 52, 8);
1178
+ };
1179
+ function checkInt(buf, value, offset, ext, max, min) {
1180
+ if (!Buffer3.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
1181
+ if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
1182
+ if (offset + ext > buf.length) throw new RangeError("Index out of range");
1183
+ }
1184
+ Buffer3.prototype.writeUintLE = Buffer3.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) {
1185
+ value = +value;
1186
+ offset = offset >>> 0;
1187
+ byteLength2 = byteLength2 >>> 0;
1188
+ if (!noAssert) {
1189
+ const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
1190
+ checkInt(this, value, offset, byteLength2, maxBytes, 0);
1191
+ }
1192
+ let mul = 1;
1193
+ let i = 0;
1194
+ this[offset] = value & 255;
1195
+ while (++i < byteLength2 && (mul *= 256)) {
1196
+ this[offset + i] = value / mul & 255;
1197
+ }
1198
+ return offset + byteLength2;
1199
+ };
1200
+ Buffer3.prototype.writeUintBE = Buffer3.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) {
1201
+ value = +value;
1202
+ offset = offset >>> 0;
1203
+ byteLength2 = byteLength2 >>> 0;
1204
+ if (!noAssert) {
1205
+ const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
1206
+ checkInt(this, value, offset, byteLength2, maxBytes, 0);
1207
+ }
1208
+ let i = byteLength2 - 1;
1209
+ let mul = 1;
1210
+ this[offset + i] = value & 255;
1211
+ while (--i >= 0 && (mul *= 256)) {
1212
+ this[offset + i] = value / mul & 255;
1213
+ }
1214
+ return offset + byteLength2;
1215
+ };
1216
+ Buffer3.prototype.writeUint8 = Buffer3.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
1217
+ value = +value;
1218
+ offset = offset >>> 0;
1219
+ if (!noAssert) checkInt(this, value, offset, 1, 255, 0);
1220
+ this[offset] = value & 255;
1221
+ return offset + 1;
1222
+ };
1223
+ Buffer3.prototype.writeUint16LE = Buffer3.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
1224
+ value = +value;
1225
+ offset = offset >>> 0;
1226
+ if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
1227
+ this[offset] = value & 255;
1228
+ this[offset + 1] = value >>> 8;
1229
+ return offset + 2;
1230
+ };
1231
+ Buffer3.prototype.writeUint16BE = Buffer3.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
1232
+ value = +value;
1233
+ offset = offset >>> 0;
1234
+ if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
1235
+ this[offset] = value >>> 8;
1236
+ this[offset + 1] = value & 255;
1237
+ return offset + 2;
1238
+ };
1239
+ Buffer3.prototype.writeUint32LE = Buffer3.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
1240
+ value = +value;
1241
+ offset = offset >>> 0;
1242
+ if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
1243
+ this[offset + 3] = value >>> 24;
1244
+ this[offset + 2] = value >>> 16;
1245
+ this[offset + 1] = value >>> 8;
1246
+ this[offset] = value & 255;
1247
+ return offset + 4;
1248
+ };
1249
+ Buffer3.prototype.writeUint32BE = Buffer3.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
1250
+ value = +value;
1251
+ offset = offset >>> 0;
1252
+ if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
1253
+ this[offset] = value >>> 24;
1254
+ this[offset + 1] = value >>> 16;
1255
+ this[offset + 2] = value >>> 8;
1256
+ this[offset + 3] = value & 255;
1257
+ return offset + 4;
1258
+ };
1259
+ function wrtBigUInt64LE(buf, value, offset, min, max) {
1260
+ checkIntBI(value, min, max, buf, offset, 7);
1261
+ let lo = Number(value & BigInt(4294967295));
1262
+ buf[offset++] = lo;
1263
+ lo = lo >> 8;
1264
+ buf[offset++] = lo;
1265
+ lo = lo >> 8;
1266
+ buf[offset++] = lo;
1267
+ lo = lo >> 8;
1268
+ buf[offset++] = lo;
1269
+ let hi = Number(value >> BigInt(32) & BigInt(4294967295));
1270
+ buf[offset++] = hi;
1271
+ hi = hi >> 8;
1272
+ buf[offset++] = hi;
1273
+ hi = hi >> 8;
1274
+ buf[offset++] = hi;
1275
+ hi = hi >> 8;
1276
+ buf[offset++] = hi;
1277
+ return offset;
1278
+ }
1279
+ function wrtBigUInt64BE(buf, value, offset, min, max) {
1280
+ checkIntBI(value, min, max, buf, offset, 7);
1281
+ let lo = Number(value & BigInt(4294967295));
1282
+ buf[offset + 7] = lo;
1283
+ lo = lo >> 8;
1284
+ buf[offset + 6] = lo;
1285
+ lo = lo >> 8;
1286
+ buf[offset + 5] = lo;
1287
+ lo = lo >> 8;
1288
+ buf[offset + 4] = lo;
1289
+ let hi = Number(value >> BigInt(32) & BigInt(4294967295));
1290
+ buf[offset + 3] = hi;
1291
+ hi = hi >> 8;
1292
+ buf[offset + 2] = hi;
1293
+ hi = hi >> 8;
1294
+ buf[offset + 1] = hi;
1295
+ hi = hi >> 8;
1296
+ buf[offset] = hi;
1297
+ return offset + 8;
1298
+ }
1299
+ Buffer3.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) {
1300
+ return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
1301
+ });
1302
+ Buffer3.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) {
1303
+ return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
1304
+ });
1305
+ Buffer3.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) {
1306
+ value = +value;
1307
+ offset = offset >>> 0;
1308
+ if (!noAssert) {
1309
+ const limit = Math.pow(2, 8 * byteLength2 - 1);
1310
+ checkInt(this, value, offset, byteLength2, limit - 1, -limit);
1311
+ }
1312
+ let i = 0;
1313
+ let mul = 1;
1314
+ let sub = 0;
1315
+ this[offset] = value & 255;
1316
+ while (++i < byteLength2 && (mul *= 256)) {
1317
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1318
+ sub = 1;
1319
+ }
1320
+ this[offset + i] = (value / mul >> 0) - sub & 255;
1321
+ }
1322
+ return offset + byteLength2;
1323
+ };
1324
+ Buffer3.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) {
1325
+ value = +value;
1326
+ offset = offset >>> 0;
1327
+ if (!noAssert) {
1328
+ const limit = Math.pow(2, 8 * byteLength2 - 1);
1329
+ checkInt(this, value, offset, byteLength2, limit - 1, -limit);
1330
+ }
1331
+ let i = byteLength2 - 1;
1332
+ let mul = 1;
1333
+ let sub = 0;
1334
+ this[offset + i] = value & 255;
1335
+ while (--i >= 0 && (mul *= 256)) {
1336
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1337
+ sub = 1;
1338
+ }
1339
+ this[offset + i] = (value / mul >> 0) - sub & 255;
1340
+ }
1341
+ return offset + byteLength2;
1342
+ };
1343
+ Buffer3.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
1344
+ value = +value;
1345
+ offset = offset >>> 0;
1346
+ if (!noAssert) checkInt(this, value, offset, 1, 127, -128);
1347
+ if (value < 0) value = 255 + value + 1;
1348
+ this[offset] = value & 255;
1349
+ return offset + 1;
1350
+ };
1351
+ Buffer3.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
1352
+ value = +value;
1353
+ offset = offset >>> 0;
1354
+ if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
1355
+ this[offset] = value & 255;
1356
+ this[offset + 1] = value >>> 8;
1357
+ return offset + 2;
1358
+ };
1359
+ Buffer3.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
1360
+ value = +value;
1361
+ offset = offset >>> 0;
1362
+ if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
1363
+ this[offset] = value >>> 8;
1364
+ this[offset + 1] = value & 255;
1365
+ return offset + 2;
1366
+ };
1367
+ Buffer3.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
1368
+ value = +value;
1369
+ offset = offset >>> 0;
1370
+ if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
1371
+ this[offset] = value & 255;
1372
+ this[offset + 1] = value >>> 8;
1373
+ this[offset + 2] = value >>> 16;
1374
+ this[offset + 3] = value >>> 24;
1375
+ return offset + 4;
1376
+ };
1377
+ Buffer3.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
1378
+ value = +value;
1379
+ offset = offset >>> 0;
1380
+ if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
1381
+ if (value < 0) value = 4294967295 + value + 1;
1382
+ this[offset] = value >>> 24;
1383
+ this[offset + 1] = value >>> 16;
1384
+ this[offset + 2] = value >>> 8;
1385
+ this[offset + 3] = value & 255;
1386
+ return offset + 4;
1387
+ };
1388
+ Buffer3.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) {
1389
+ return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
1390
+ });
1391
+ Buffer3.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) {
1392
+ return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
1393
+ });
1394
+ function checkIEEE754(buf, value, offset, ext, max, min) {
1395
+ if (offset + ext > buf.length) throw new RangeError("Index out of range");
1396
+ if (offset < 0) throw new RangeError("Index out of range");
1397
+ }
1398
+ function writeFloat(buf, value, offset, littleEndian, noAssert) {
1399
+ value = +value;
1400
+ offset = offset >>> 0;
1401
+ if (!noAssert) {
1402
+ checkIEEE754(buf, value, offset, 4);
1403
+ }
1404
+ ieee754.write(buf, value, offset, littleEndian, 23, 4);
1405
+ return offset + 4;
1406
+ }
1407
+ Buffer3.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
1408
+ return writeFloat(this, value, offset, true, noAssert);
1409
+ };
1410
+ Buffer3.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
1411
+ return writeFloat(this, value, offset, false, noAssert);
1412
+ };
1413
+ function writeDouble(buf, value, offset, littleEndian, noAssert) {
1414
+ value = +value;
1415
+ offset = offset >>> 0;
1416
+ if (!noAssert) {
1417
+ checkIEEE754(buf, value, offset, 8);
1418
+ }
1419
+ ieee754.write(buf, value, offset, littleEndian, 52, 8);
1420
+ return offset + 8;
1421
+ }
1422
+ Buffer3.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
1423
+ return writeDouble(this, value, offset, true, noAssert);
1424
+ };
1425
+ Buffer3.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
1426
+ return writeDouble(this, value, offset, false, noAssert);
1427
+ };
1428
+ Buffer3.prototype.copy = function copy(target, targetStart, start, end) {
1429
+ if (!Buffer3.isBuffer(target)) throw new TypeError("argument should be a Buffer");
1430
+ if (!start) start = 0;
1431
+ if (!end && end !== 0) end = this.length;
1432
+ if (targetStart >= target.length) targetStart = target.length;
1433
+ if (!targetStart) targetStart = 0;
1434
+ if (end > 0 && end < start) end = start;
1435
+ if (end === start) return 0;
1436
+ if (target.length === 0 || this.length === 0) return 0;
1437
+ if (targetStart < 0) {
1438
+ throw new RangeError("targetStart out of bounds");
1439
+ }
1440
+ if (start < 0 || start >= this.length) throw new RangeError("Index out of range");
1441
+ if (end < 0) throw new RangeError("sourceEnd out of bounds");
1442
+ if (end > this.length) end = this.length;
1443
+ if (target.length - targetStart < end - start) {
1444
+ end = target.length - targetStart + start;
1445
+ }
1446
+ const len = end - start;
1447
+ if (this === target && typeof Uint8Array.prototype.copyWithin === "function") {
1448
+ this.copyWithin(targetStart, start, end);
1449
+ } else {
1450
+ Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart);
1451
+ }
1452
+ return len;
1453
+ };
1454
+ Buffer3.prototype.fill = function fill(val, start, end, encoding) {
1455
+ if (typeof val === "string") {
1456
+ if (typeof start === "string") {
1457
+ encoding = start;
1458
+ start = 0;
1459
+ end = this.length;
1460
+ } else if (typeof end === "string") {
1461
+ encoding = end;
1462
+ end = this.length;
1463
+ }
1464
+ if (encoding !== void 0 && typeof encoding !== "string") {
1465
+ throw new TypeError("encoding must be a string");
1466
+ }
1467
+ if (typeof encoding === "string" && !Buffer3.isEncoding(encoding)) {
1468
+ throw new TypeError("Unknown encoding: " + encoding);
1469
+ }
1470
+ if (val.length === 1) {
1471
+ const code = val.charCodeAt(0);
1472
+ if (encoding === "utf8" && code < 128 || encoding === "latin1") {
1473
+ val = code;
1474
+ }
1475
+ }
1476
+ } else if (typeof val === "number") {
1477
+ val = val & 255;
1478
+ } else if (typeof val === "boolean") {
1479
+ val = Number(val);
1480
+ }
1481
+ if (start < 0 || this.length < start || this.length < end) {
1482
+ throw new RangeError("Out of range index");
1483
+ }
1484
+ if (end <= start) {
1485
+ return this;
1486
+ }
1487
+ start = start >>> 0;
1488
+ end = end === void 0 ? this.length : end >>> 0;
1489
+ if (!val) val = 0;
1490
+ let i;
1491
+ if (typeof val === "number") {
1492
+ for (i = start; i < end; ++i) {
1493
+ this[i] = val;
1494
+ }
1495
+ } else {
1496
+ const bytes = Buffer3.isBuffer(val) ? val : Buffer3.from(val, encoding);
1497
+ const len = bytes.length;
1498
+ if (len === 0) {
1499
+ throw new TypeError('The value "' + val + '" is invalid for argument "value"');
1500
+ }
1501
+ for (i = 0; i < end - start; ++i) {
1502
+ this[i + start] = bytes[i % len];
1503
+ }
1504
+ }
1505
+ return this;
1506
+ };
1507
+ const errors = {};
1508
+ function E(sym, getMessage, Base) {
1509
+ errors[sym] = class NodeError extends Base {
1510
+ constructor() {
1511
+ super();
1512
+ Object.defineProperty(this, "message", {
1513
+ value: getMessage.apply(this, arguments),
1514
+ writable: true,
1515
+ configurable: true
1516
+ });
1517
+ this.name = `${this.name} [${sym}]`;
1518
+ this.stack;
1519
+ delete this.name;
1520
+ }
1521
+ get code() {
1522
+ return sym;
1523
+ }
1524
+ set code(value) {
1525
+ Object.defineProperty(this, "code", {
1526
+ configurable: true,
1527
+ enumerable: true,
1528
+ value,
1529
+ writable: true
1530
+ });
1531
+ }
1532
+ toString() {
1533
+ return `${this.name} [${sym}]: ${this.message}`;
1534
+ }
1535
+ };
1536
+ }
1537
+ E("ERR_BUFFER_OUT_OF_BOUNDS", function(name2) {
1538
+ if (name2) {
1539
+ return `${name2} is outside of buffer bounds`;
1540
+ }
1541
+ return "Attempt to access memory outside buffer bounds";
1542
+ }, RangeError);
1543
+ E("ERR_INVALID_ARG_TYPE", function(name2, actual) {
1544
+ return `The "${name2}" argument must be of type number. Received type ${typeof actual}`;
1545
+ }, TypeError);
1546
+ E("ERR_OUT_OF_RANGE", function(str, range, input) {
1547
+ let msg = `The value of "${str}" is out of range.`;
1548
+ let received = input;
1549
+ if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
1550
+ received = addNumericalSeparator(String(input));
1551
+ } else if (typeof input === "bigint") {
1552
+ received = String(input);
1553
+ if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
1554
+ received = addNumericalSeparator(received);
1555
+ }
1556
+ received += "n";
1557
+ }
1558
+ msg += ` It must be ${range}. Received ${received}`;
1559
+ return msg;
1560
+ }, RangeError);
1561
+ function addNumericalSeparator(val) {
1562
+ let res = "";
1563
+ let i = val.length;
1564
+ const start = val[0] === "-" ? 1 : 0;
1565
+ for (; i >= start + 4; i -= 3) {
1566
+ res = `_${val.slice(i - 3, i)}${res}`;
1567
+ }
1568
+ return `${val.slice(0, i)}${res}`;
1569
+ }
1570
+ function checkBounds(buf, offset, byteLength2) {
1571
+ validateNumber(offset, "offset");
1572
+ if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) {
1573
+ boundsError(offset, buf.length - (byteLength2 + 1));
1574
+ }
1575
+ }
1576
+ function checkIntBI(value, min, max, buf, offset, byteLength2) {
1577
+ if (value > max || value < min) {
1578
+ const n = typeof min === "bigint" ? "n" : "";
1579
+ let range;
1580
+ {
1581
+ if (min === 0 || min === BigInt(0)) {
1582
+ range = `>= 0${n} and < 2${n} ** ${(byteLength2 + 1) * 8}${n}`;
1583
+ } else {
1584
+ range = `>= -(2${n} ** ${(byteLength2 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n}`;
1585
+ }
1586
+ }
1587
+ throw new errors.ERR_OUT_OF_RANGE("value", range, value);
1588
+ }
1589
+ checkBounds(buf, offset, byteLength2);
1590
+ }
1591
+ function validateNumber(value, name2) {
1592
+ if (typeof value !== "number") {
1593
+ throw new errors.ERR_INVALID_ARG_TYPE(name2, "number", value);
1594
+ }
1595
+ }
1596
+ function boundsError(value, length, type) {
1597
+ if (Math.floor(value) !== value) {
1598
+ validateNumber(value, type);
1599
+ throw new errors.ERR_OUT_OF_RANGE("offset", "an integer", value);
1600
+ }
1601
+ if (length < 0) {
1602
+ throw new errors.ERR_BUFFER_OUT_OF_BOUNDS();
1603
+ }
1604
+ throw new errors.ERR_OUT_OF_RANGE("offset", `>= ${0} and <= ${length}`, value);
1605
+ }
1606
+ const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
1607
+ function base64clean(str) {
1608
+ str = str.split("=")[0];
1609
+ str = str.trim().replace(INVALID_BASE64_RE, "");
1610
+ if (str.length < 2) return "";
1611
+ while (str.length % 4 !== 0) {
1612
+ str = str + "=";
1613
+ }
1614
+ return str;
1615
+ }
1616
+ function utf8ToBytes(string, units) {
1617
+ units = units || Infinity;
1618
+ let codePoint;
1619
+ const length = string.length;
1620
+ let leadSurrogate = null;
1621
+ const bytes = [];
1622
+ for (let i = 0; i < length; ++i) {
1623
+ codePoint = string.charCodeAt(i);
1624
+ if (codePoint > 55295 && codePoint < 57344) {
1625
+ if (!leadSurrogate) {
1626
+ if (codePoint > 56319) {
1627
+ if ((units -= 3) > -1) bytes.push(239, 191, 189);
1628
+ continue;
1629
+ } else if (i + 1 === length) {
1630
+ if ((units -= 3) > -1) bytes.push(239, 191, 189);
1631
+ continue;
1632
+ }
1633
+ leadSurrogate = codePoint;
1634
+ continue;
1635
+ }
1636
+ if (codePoint < 56320) {
1637
+ if ((units -= 3) > -1) bytes.push(239, 191, 189);
1638
+ leadSurrogate = codePoint;
1639
+ continue;
1640
+ }
1641
+ codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
1642
+ } else if (leadSurrogate) {
1643
+ if ((units -= 3) > -1) bytes.push(239, 191, 189);
1644
+ }
1645
+ leadSurrogate = null;
1646
+ if (codePoint < 128) {
1647
+ if ((units -= 1) < 0) break;
1648
+ bytes.push(codePoint);
1649
+ } else if (codePoint < 2048) {
1650
+ if ((units -= 2) < 0) break;
1651
+ bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128);
1652
+ } else if (codePoint < 65536) {
1653
+ if ((units -= 3) < 0) break;
1654
+ bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
1655
+ } else if (codePoint < 1114112) {
1656
+ if ((units -= 4) < 0) break;
1657
+ bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
1658
+ } else {
1659
+ throw new Error("Invalid code point");
1660
+ }
1661
+ }
1662
+ return bytes;
1663
+ }
1664
+ function asciiToBytes(str) {
1665
+ const byteArray = [];
1666
+ for (let i = 0; i < str.length; ++i) {
1667
+ byteArray.push(str.charCodeAt(i) & 255);
1668
+ }
1669
+ return byteArray;
1670
+ }
1671
+ function utf16leToBytes(str, units) {
1672
+ let c, hi, lo;
1673
+ const byteArray = [];
1674
+ for (let i = 0; i < str.length; ++i) {
1675
+ if ((units -= 2) < 0) break;
1676
+ c = str.charCodeAt(i);
1677
+ hi = c >> 8;
1678
+ lo = c % 256;
1679
+ byteArray.push(lo);
1680
+ byteArray.push(hi);
1681
+ }
1682
+ return byteArray;
1683
+ }
1684
+ function base64ToBytes(str) {
1685
+ return base64.toByteArray(base64clean(str));
1686
+ }
1687
+ function blitBuffer(src, dst, offset, length) {
1688
+ let i;
1689
+ for (i = 0; i < length; ++i) {
1690
+ if (i + offset >= dst.length || i >= src.length) break;
1691
+ dst[i + offset] = src[i];
1692
+ }
1693
+ return i;
1694
+ }
1695
+ function isInstance(obj, type) {
1696
+ return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
1697
+ }
1698
+ function numberIsNaN(obj) {
1699
+ return obj !== obj;
1700
+ }
1701
+ const hexSliceLookupTable = (function() {
1702
+ const alphabet = "0123456789abcdef";
1703
+ const table = new Array(256);
1704
+ for (let i = 0; i < 16; ++i) {
1705
+ const i16 = i * 16;
1706
+ for (let j = 0; j < 16; ++j) {
1707
+ table[i16 + j] = alphabet[i] + alphabet[j];
1708
+ }
1709
+ }
1710
+ return table;
1711
+ })();
1712
+ function defineBigIntMethod(fn) {
1713
+ return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn;
1714
+ }
1715
+ function BufferBigIntNotDefined() {
1716
+ throw new Error("BigInt not supported");
1717
+ }
1718
+ return exports;
1719
+ }
1720
+
1721
+ // node_modules/@jspm/core/nodelibs/browser/buffer.js
1722
+ var exports2 = dew();
1723
+ exports2["Buffer"];
1724
+ exports2["SlowBuffer"];
1725
+ exports2["INSPECT_MAX_BYTES"];
1726
+ exports2["kMaxLength"];
1727
+ var Buffer2 = exports2.Buffer;
1728
+ var INSPECT_MAX_BYTES = exports2.INSPECT_MAX_BYTES;
1729
+ var kMaxLength = exports2.kMaxLength;
1730
+
1731
+ // node_modules/@typespec/ts-http-runtime/dist/browser/util/bytesEncoding.common.js
1732
+ var hexDigits = new Set("0123456789abcdefABCDEF");
1733
+
1734
+ // node_modules/@typespec/ts-http-runtime/dist/browser/util/uuidUtils.common.js
1735
+ function generateUUID() {
1736
+ let uuid = "";
1737
+ for (let i = 0; i < 32; i++) {
1738
+ const randomNumber = Math.floor(Math.random() * 16);
1739
+ if (i === 12) {
1740
+ uuid += "4";
1741
+ } else if (i === 16) {
1742
+ uuid += (randomNumber & 3 | 8).toString(16);
1743
+ } else {
1744
+ uuid += randomNumber.toString(16);
1745
+ }
1746
+ if (i === 7 || i === 11 || i === 15 || i === 19) {
1747
+ uuid += "-";
1748
+ }
1749
+ }
1750
+ return uuid;
1751
+ }
1752
+
1753
+ // node_modules/@typespec/ts-http-runtime/dist/browser/util/uuidUtils-browser.mjs
1754
+ var uuidFunction = typeof globalThis?.crypto?.randomUUID === "function" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : generateUUID;
1755
+
1756
+ // node_modules/@typespec/ts-http-runtime/dist/browser/env-browser.mjs
1757
+ function getEnvironmentVariable(name2) {
1758
+ return globalThis.process?.env?.[name2];
1759
+ }
1760
+ var isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
1761
+ var isWebWorker = typeof self === "object" && "importScripts" in self && typeof self.importScripts === "function" && (self.constructor?.name === "DedicatedWorkerGlobalScope" || self.constructor?.name === "ServiceWorkerGlobalScope" || self.constructor?.name === "SharedWorkerGlobalScope");
1762
+
1763
+ // node_modules/@azure/abort-controller/dist/browser/AbortError.js
1764
+ var AbortError = class extends Error {
1765
+ constructor(message) {
1766
+ super(message);
1767
+ this.name = "AbortError";
1768
+ }
1769
+ };
1770
+
1771
+ // node_modules/@azure/core-util/dist/browser/createAbortablePromise.js
1772
+ function createAbortablePromise(buildPromise, options) {
1773
+ const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options ?? {};
1774
+ return new Promise((resolve, reject) => {
1775
+ function rejectOnAbort() {
1776
+ reject(new AbortError(abortErrorMsg ?? "The operation was aborted."));
1777
+ }
1778
+ function removeListeners() {
1779
+ abortSignal?.removeEventListener("abort", onAbort);
1780
+ }
1781
+ function onAbort() {
1782
+ cleanupBeforeAbort?.();
1783
+ removeListeners();
1784
+ rejectOnAbort();
1785
+ }
1786
+ if (abortSignal?.aborted) {
1787
+ return rejectOnAbort();
1788
+ }
1789
+ try {
1790
+ buildPromise((x) => {
1791
+ removeListeners();
1792
+ resolve(x);
1793
+ }, (x) => {
1794
+ removeListeners();
1795
+ reject(x);
1796
+ });
1797
+ } catch (err) {
1798
+ reject(err);
1799
+ }
1800
+ abortSignal?.addEventListener("abort", onAbort);
1801
+ });
1802
+ }
1803
+
1804
+ // node_modules/@azure/core-util/dist/browser/delay.js
1805
+ var StandardAbortMessage = "The delay was aborted.";
1806
+ function delay(timeInMs, options) {
1807
+ let token;
1808
+ const { abortSignal, abortErrorMsg } = options ?? {};
1809
+ return createAbortablePromise((resolve) => {
1810
+ token = setTimeout(resolve, timeInMs);
1811
+ }, {
1812
+ cleanupBeforeAbort: () => clearTimeout(token),
1813
+ abortSignal,
1814
+ abortErrorMsg: abortErrorMsg ?? StandardAbortMessage
1815
+ });
1816
+ }
1817
+
1818
+ // node_modules/@jspm/core/nodelibs/browser/events.js
1819
+ var exports$12 = {};
1820
+ var _dewExec2 = false;
1821
+ function dew2() {
1822
+ if (_dewExec2) return exports$12;
1823
+ _dewExec2 = true;
1824
+ var R = typeof Reflect === "object" ? Reflect : null;
1825
+ var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) {
1826
+ return Function.prototype.apply.call(target, receiver, args);
1827
+ };
1828
+ var ReflectOwnKeys;
1829
+ if (R && typeof R.ownKeys === "function") {
1830
+ ReflectOwnKeys = R.ownKeys;
1831
+ } else if (Object.getOwnPropertySymbols) {
1832
+ ReflectOwnKeys = function ReflectOwnKeys2(target) {
1833
+ return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target));
1834
+ };
1835
+ } else {
1836
+ ReflectOwnKeys = function ReflectOwnKeys2(target) {
1837
+ return Object.getOwnPropertyNames(target);
1838
+ };
1839
+ }
1840
+ function ProcessEmitWarning(warning) {
1841
+ if (console && console.warn) console.warn(warning);
1842
+ }
1843
+ var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) {
1844
+ return value !== value;
1845
+ };
1846
+ function EventEmitter2() {
1847
+ EventEmitter2.init.call(this);
1848
+ }
1849
+ exports$12 = EventEmitter2;
1850
+ exports$12.once = once2;
1851
+ EventEmitter2.EventEmitter = EventEmitter2;
1852
+ EventEmitter2.prototype._events = void 0;
1853
+ EventEmitter2.prototype._eventsCount = 0;
1854
+ EventEmitter2.prototype._maxListeners = void 0;
1855
+ var defaultMaxListeners2 = 10;
1856
+ function checkListener(listener) {
1857
+ if (typeof listener !== "function") {
1858
+ throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
1859
+ }
1860
+ }
1861
+ Object.defineProperty(EventEmitter2, "defaultMaxListeners", {
1862
+ enumerable: true,
1863
+ get: function() {
1864
+ return defaultMaxListeners2;
1865
+ },
1866
+ set: function(arg) {
1867
+ if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) {
1868
+ throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + ".");
1869
+ }
1870
+ defaultMaxListeners2 = arg;
1871
+ }
1872
+ });
1873
+ EventEmitter2.init = function() {
1874
+ if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) {
1875
+ this._events = /* @__PURE__ */ Object.create(null);
1876
+ this._eventsCount = 0;
1877
+ }
1878
+ this._maxListeners = this._maxListeners || void 0;
1879
+ };
1880
+ EventEmitter2.prototype.setMaxListeners = function setMaxListeners(n) {
1881
+ if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) {
1882
+ throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + ".");
1883
+ }
1884
+ this._maxListeners = n;
1885
+ return this;
1886
+ };
1887
+ function _getMaxListeners(that) {
1888
+ if (that._maxListeners === void 0) return EventEmitter2.defaultMaxListeners;
1889
+ return that._maxListeners;
1890
+ }
1891
+ EventEmitter2.prototype.getMaxListeners = function getMaxListeners() {
1892
+ return _getMaxListeners(this);
1893
+ };
1894
+ EventEmitter2.prototype.emit = function emit(type) {
1895
+ var args = [];
1896
+ for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
1897
+ var doError = type === "error";
1898
+ var events = this._events;
1899
+ if (events !== void 0) doError = doError && events.error === void 0;
1900
+ else if (!doError) return false;
1901
+ if (doError) {
1902
+ var er;
1903
+ if (args.length > 0) er = args[0];
1904
+ if (er instanceof Error) {
1905
+ throw er;
1906
+ }
1907
+ var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : ""));
1908
+ err.context = er;
1909
+ throw err;
1910
+ }
1911
+ var handler = events[type];
1912
+ if (handler === void 0) return false;
1913
+ if (typeof handler === "function") {
1914
+ ReflectApply(handler, this, args);
1915
+ } else {
1916
+ var len = handler.length;
1917
+ var listeners = arrayClone(handler, len);
1918
+ for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args);
1919
+ }
1920
+ return true;
1921
+ };
1922
+ function _addListener(target, type, listener, prepend) {
1923
+ var m;
1924
+ var events;
1925
+ var existing;
1926
+ checkListener(listener);
1927
+ events = target._events;
1928
+ if (events === void 0) {
1929
+ events = target._events = /* @__PURE__ */ Object.create(null);
1930
+ target._eventsCount = 0;
1931
+ } else {
1932
+ if (events.newListener !== void 0) {
1933
+ target.emit("newListener", type, listener.listener ? listener.listener : listener);
1934
+ events = target._events;
1935
+ }
1936
+ existing = events[type];
1937
+ }
1938
+ if (existing === void 0) {
1939
+ existing = events[type] = listener;
1940
+ ++target._eventsCount;
1941
+ } else {
1942
+ if (typeof existing === "function") {
1943
+ existing = events[type] = prepend ? [listener, existing] : [existing, listener];
1944
+ } else if (prepend) {
1945
+ existing.unshift(listener);
1946
+ } else {
1947
+ existing.push(listener);
1948
+ }
1949
+ m = _getMaxListeners(target);
1950
+ if (m > 0 && existing.length > m && !existing.warned) {
1951
+ existing.warned = true;
1952
+ var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit");
1953
+ w.name = "MaxListenersExceededWarning";
1954
+ w.emitter = target;
1955
+ w.type = type;
1956
+ w.count = existing.length;
1957
+ ProcessEmitWarning(w);
1958
+ }
1959
+ }
1960
+ return target;
1961
+ }
1962
+ EventEmitter2.prototype.addListener = function addListener(type, listener) {
1963
+ return _addListener(this, type, listener, false);
1964
+ };
1965
+ EventEmitter2.prototype.on = EventEmitter2.prototype.addListener;
1966
+ EventEmitter2.prototype.prependListener = function prependListener(type, listener) {
1967
+ return _addListener(this, type, listener, true);
1968
+ };
1969
+ function onceWrapper() {
1970
+ if (!this.fired) {
1971
+ this.target.removeListener(this.type, this.wrapFn);
1972
+ this.fired = true;
1973
+ if (arguments.length === 0) return this.listener.call(this.target);
1974
+ return this.listener.apply(this.target, arguments);
1975
+ }
1976
+ }
1977
+ function _onceWrap(target, type, listener) {
1978
+ var state = {
1979
+ fired: false,
1980
+ wrapFn: void 0,
1981
+ target,
1982
+ type,
1983
+ listener
1984
+ };
1985
+ var wrapped = onceWrapper.bind(state);
1986
+ wrapped.listener = listener;
1987
+ state.wrapFn = wrapped;
1988
+ return wrapped;
1989
+ }
1990
+ EventEmitter2.prototype.once = function once3(type, listener) {
1991
+ checkListener(listener);
1992
+ this.on(type, _onceWrap(this, type, listener));
1993
+ return this;
1994
+ };
1995
+ EventEmitter2.prototype.prependOnceListener = function prependOnceListener(type, listener) {
1996
+ checkListener(listener);
1997
+ this.prependListener(type, _onceWrap(this, type, listener));
1998
+ return this;
1999
+ };
2000
+ EventEmitter2.prototype.removeListener = function removeListener(type, listener) {
2001
+ var list, events, position, i, originalListener;
2002
+ checkListener(listener);
2003
+ events = this._events;
2004
+ if (events === void 0) return this;
2005
+ list = events[type];
2006
+ if (list === void 0) return this;
2007
+ if (list === listener || list.listener === listener) {
2008
+ if (--this._eventsCount === 0) this._events = /* @__PURE__ */ Object.create(null);
2009
+ else {
2010
+ delete events[type];
2011
+ if (events.removeListener) this.emit("removeListener", type, list.listener || listener);
2012
+ }
2013
+ } else if (typeof list !== "function") {
2014
+ position = -1;
2015
+ for (i = list.length - 1; i >= 0; i--) {
2016
+ if (list[i] === listener || list[i].listener === listener) {
2017
+ originalListener = list[i].listener;
2018
+ position = i;
2019
+ break;
2020
+ }
2021
+ }
2022
+ if (position < 0) return this;
2023
+ if (position === 0) list.shift();
2024
+ else {
2025
+ spliceOne(list, position);
2026
+ }
2027
+ if (list.length === 1) events[type] = list[0];
2028
+ if (events.removeListener !== void 0) this.emit("removeListener", type, originalListener || listener);
2029
+ }
2030
+ return this;
2031
+ };
2032
+ EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
2033
+ EventEmitter2.prototype.removeAllListeners = function removeAllListeners(type) {
2034
+ var listeners, events, i;
2035
+ events = this._events;
2036
+ if (events === void 0) return this;
2037
+ if (events.removeListener === void 0) {
2038
+ if (arguments.length === 0) {
2039
+ this._events = /* @__PURE__ */ Object.create(null);
2040
+ this._eventsCount = 0;
2041
+ } else if (events[type] !== void 0) {
2042
+ if (--this._eventsCount === 0) this._events = /* @__PURE__ */ Object.create(null);
2043
+ else delete events[type];
2044
+ }
2045
+ return this;
2046
+ }
2047
+ if (arguments.length === 0) {
2048
+ var keys = Object.keys(events);
2049
+ var key;
2050
+ for (i = 0; i < keys.length; ++i) {
2051
+ key = keys[i];
2052
+ if (key === "removeListener") continue;
2053
+ this.removeAllListeners(key);
2054
+ }
2055
+ this.removeAllListeners("removeListener");
2056
+ this._events = /* @__PURE__ */ Object.create(null);
2057
+ this._eventsCount = 0;
2058
+ return this;
2059
+ }
2060
+ listeners = events[type];
2061
+ if (typeof listeners === "function") {
2062
+ this.removeListener(type, listeners);
2063
+ } else if (listeners !== void 0) {
2064
+ for (i = listeners.length - 1; i >= 0; i--) {
2065
+ this.removeListener(type, listeners[i]);
2066
+ }
2067
+ }
2068
+ return this;
2069
+ };
2070
+ function _listeners(target, type, unwrap) {
2071
+ var events = target._events;
2072
+ if (events === void 0) return [];
2073
+ var evlistener = events[type];
2074
+ if (evlistener === void 0) return [];
2075
+ if (typeof evlistener === "function") return unwrap ? [evlistener.listener || evlistener] : [evlistener];
2076
+ return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
2077
+ }
2078
+ EventEmitter2.prototype.listeners = function listeners(type) {
2079
+ return _listeners(this, type, true);
2080
+ };
2081
+ EventEmitter2.prototype.rawListeners = function rawListeners(type) {
2082
+ return _listeners(this, type, false);
2083
+ };
2084
+ EventEmitter2.listenerCount = function(emitter, type) {
2085
+ if (typeof emitter.listenerCount === "function") {
2086
+ return emitter.listenerCount(type);
2087
+ } else {
2088
+ return listenerCount2.call(emitter, type);
2089
+ }
2090
+ };
2091
+ EventEmitter2.prototype.listenerCount = listenerCount2;
2092
+ function listenerCount2(type) {
2093
+ var events = this._events;
2094
+ if (events !== void 0) {
2095
+ var evlistener = events[type];
2096
+ if (typeof evlistener === "function") {
2097
+ return 1;
2098
+ } else if (evlistener !== void 0) {
2099
+ return evlistener.length;
2100
+ }
2101
+ }
2102
+ return 0;
2103
+ }
2104
+ EventEmitter2.prototype.eventNames = function eventNames() {
2105
+ return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
2106
+ };
2107
+ function arrayClone(arr, n) {
2108
+ var copy = new Array(n);
2109
+ for (var i = 0; i < n; ++i) copy[i] = arr[i];
2110
+ return copy;
2111
+ }
2112
+ function spliceOne(list, index) {
2113
+ for (; index + 1 < list.length; index++) list[index] = list[index + 1];
2114
+ list.pop();
2115
+ }
2116
+ function unwrapListeners(arr) {
2117
+ var ret = new Array(arr.length);
2118
+ for (var i = 0; i < ret.length; ++i) {
2119
+ ret[i] = arr[i].listener || arr[i];
2120
+ }
2121
+ return ret;
2122
+ }
2123
+ function once2(emitter, name2) {
2124
+ return new Promise(function(resolve, reject) {
2125
+ function errorListener(err) {
2126
+ emitter.removeListener(name2, resolver);
2127
+ reject(err);
2128
+ }
2129
+ function resolver() {
2130
+ if (typeof emitter.removeListener === "function") {
2131
+ emitter.removeListener("error", errorListener);
2132
+ }
2133
+ resolve([].slice.call(arguments));
2134
+ }
2135
+ eventTargetAgnosticAddListener(emitter, name2, resolver, {
2136
+ once: true
2137
+ });
2138
+ if (name2 !== "error") {
2139
+ addErrorHandlerIfEventEmitter(emitter, errorListener, {
2140
+ once: true
2141
+ });
2142
+ }
2143
+ });
2144
+ }
2145
+ function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
2146
+ if (typeof emitter.on === "function") {
2147
+ eventTargetAgnosticAddListener(emitter, "error", handler, flags);
2148
+ }
2149
+ }
2150
+ function eventTargetAgnosticAddListener(emitter, name2, listener, flags) {
2151
+ if (typeof emitter.on === "function") {
2152
+ if (flags.once) {
2153
+ emitter.once(name2, listener);
2154
+ } else {
2155
+ emitter.on(name2, listener);
2156
+ }
2157
+ } else if (typeof emitter.addEventListener === "function") {
2158
+ emitter.addEventListener(name2, function wrapListener(arg) {
2159
+ if (flags.once) {
2160
+ emitter.removeEventListener(name2, wrapListener);
2161
+ }
2162
+ listener(arg);
2163
+ });
2164
+ } else {
2165
+ throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
2166
+ }
2167
+ }
2168
+ return exports$12;
2169
+ }
2170
+ var exports3 = dew2();
2171
+ exports3["once"];
2172
+ exports3.once = function(emitter, event) {
2173
+ return new Promise((resolve, reject) => {
2174
+ function eventListener(...args) {
2175
+ if (errorListener !== void 0) {
2176
+ emitter.removeListener("error", errorListener);
2177
+ }
2178
+ resolve(args);
2179
+ }
2180
+ let errorListener;
2181
+ if (event !== "error") {
2182
+ errorListener = (err) => {
2183
+ emitter.removeListener(name, eventListener);
2184
+ reject(err);
2185
+ };
2186
+ emitter.once("error", errorListener);
2187
+ }
2188
+ emitter.once(event, eventListener);
2189
+ });
2190
+ };
2191
+ exports3.on = function(emitter, event) {
2192
+ const unconsumedEventValues = [];
2193
+ const unconsumedPromises = [];
2194
+ let error = null;
2195
+ let finished = false;
2196
+ const iterator = {
2197
+ async next() {
2198
+ const value = unconsumedEventValues.shift();
2199
+ if (value) {
2200
+ return createIterResult(value, false);
2201
+ }
2202
+ if (error) {
2203
+ const p = Promise.reject(error);
2204
+ error = null;
2205
+ return p;
2206
+ }
2207
+ if (finished) {
2208
+ return createIterResult(void 0, true);
2209
+ }
2210
+ return new Promise((resolve, reject) => unconsumedPromises.push({ resolve, reject }));
2211
+ },
2212
+ async return() {
2213
+ emitter.removeListener(event, eventHandler);
2214
+ emitter.removeListener("error", errorHandler);
2215
+ finished = true;
2216
+ for (const promise of unconsumedPromises) {
2217
+ promise.resolve(createIterResult(void 0, true));
2218
+ }
2219
+ return createIterResult(void 0, true);
2220
+ },
2221
+ throw(err) {
2222
+ error = err;
2223
+ emitter.removeListener(event, eventHandler);
2224
+ emitter.removeListener("error", errorHandler);
2225
+ },
2226
+ [Symbol.asyncIterator]() {
2227
+ return this;
2228
+ }
2229
+ };
2230
+ emitter.on(event, eventHandler);
2231
+ emitter.on("error", errorHandler);
2232
+ return iterator;
2233
+ function eventHandler(...args) {
2234
+ const promise = unconsumedPromises.shift();
2235
+ if (promise) {
2236
+ promise.resolve(createIterResult(args, false));
2237
+ } else {
2238
+ unconsumedEventValues.push(args);
2239
+ }
2240
+ }
2241
+ function errorHandler(err) {
2242
+ finished = true;
2243
+ const toError = unconsumedPromises.shift();
2244
+ if (toError) {
2245
+ toError.reject(err);
2246
+ } else {
2247
+ error = err;
2248
+ }
2249
+ iterator.return();
2250
+ }
2251
+ };
2252
+ var {
2253
+ EventEmitter,
2254
+ defaultMaxListeners,
2255
+ init,
2256
+ listenerCount,
2257
+ on,
2258
+ once
2259
+ } = exports3;
2260
+
2261
+ // node_modules/@azure/web-pubsub-client/dist/browser/errors/index.js
2262
+ var SendMessageError = class extends Error {
2263
+ /**
2264
+ * Initialize a SendMessageError
2265
+ * @param message - The error message
2266
+ * @param ackMessage - The ack message
2267
+ */
2268
+ constructor(message, options) {
2269
+ super(message);
2270
+ /**
2271
+ * Error name
2272
+ */
2273
+ __publicField(this, "name");
2274
+ /**
2275
+ * The ack id of the message
2276
+ */
2277
+ __publicField(this, "ackId");
2278
+ /**
2279
+ * The error details from the service
2280
+ */
2281
+ __publicField(this, "errorDetail");
2282
+ this.name = "SendMessageError";
2283
+ this.ackId = options.ackId;
2284
+ this.errorDetail = options.errorDetail;
2285
+ }
2286
+ };
2287
+ var InvocationError = class extends Error {
2288
+ constructor(message, options) {
2289
+ super(message);
2290
+ /**
2291
+ * The invocation id of the request.
2292
+ */
2293
+ __publicField(this, "invocationId");
2294
+ /**
2295
+ * Error details from the service if available.
2296
+ */
2297
+ __publicField(this, "errorDetail");
2298
+ this.name = "InvocationError";
2299
+ this.invocationId = options.invocationId;
2300
+ this.errorDetail = options.errorDetail;
2301
+ }
2302
+ };
2303
+
2304
+ // node_modules/@typespec/ts-http-runtime/dist/browser/logger/log.common.js
2305
+ function log(...args) {
2306
+ if (args.length > 0) {
2307
+ const firstArg = String(args[0]);
2308
+ if (firstArg.includes(":error")) {
2309
+ console.error(...args);
2310
+ } else if (firstArg.includes(":warning")) {
2311
+ console.warn(...args);
2312
+ } else if (firstArg.includes(":info")) {
2313
+ console.info(...args);
2314
+ } else if (firstArg.includes(":verbose")) {
2315
+ console.debug(...args);
2316
+ } else {
2317
+ console.debug(...args);
2318
+ }
2319
+ }
2320
+ }
2321
+
2322
+ // node_modules/@typespec/ts-http-runtime/dist/browser/logger/debug.js
2323
+ var debugEnvVariable = getEnvironmentVariable("DEBUG");
2324
+ var enabledString;
2325
+ var enabledNamespaces = [];
2326
+ var skippedNamespaces = [];
2327
+ var debuggers = [];
2328
+ if (debugEnvVariable) {
2329
+ enable(debugEnvVariable);
2330
+ }
2331
+ var debugObj = Object.assign((namespace) => {
2332
+ return createDebugger(namespace);
2333
+ }, {
2334
+ enable,
2335
+ enabled,
2336
+ disable,
2337
+ log
2338
+ });
2339
+ function enable(namespaces) {
2340
+ enabledString = namespaces;
2341
+ enabledNamespaces = [];
2342
+ skippedNamespaces = [];
2343
+ const namespaceList = namespaces.split(",").map((ns) => ns.trim());
2344
+ for (const ns of namespaceList) {
2345
+ if (ns.startsWith("-")) {
2346
+ skippedNamespaces.push(ns.substring(1));
2347
+ } else {
2348
+ enabledNamespaces.push(ns);
2349
+ }
2350
+ }
2351
+ for (const instance of debuggers) {
2352
+ instance.enabled = enabled(instance.namespace);
2353
+ }
2354
+ }
2355
+ function enabled(namespace) {
2356
+ if (namespace.endsWith("*")) {
2357
+ return true;
2358
+ }
2359
+ for (const skipped of skippedNamespaces) {
2360
+ if (namespaceMatches(namespace, skipped)) {
2361
+ return false;
2362
+ }
2363
+ }
2364
+ for (const enabledNamespace of enabledNamespaces) {
2365
+ if (namespaceMatches(namespace, enabledNamespace)) {
2366
+ return true;
2367
+ }
2368
+ }
2369
+ return false;
2370
+ }
2371
+ function namespaceMatches(namespace, patternToMatch) {
2372
+ if (patternToMatch.indexOf("*") === -1) {
2373
+ return namespace === patternToMatch;
2374
+ }
2375
+ let pattern = patternToMatch;
2376
+ if (patternToMatch.indexOf("**") !== -1) {
2377
+ const patternParts = [];
2378
+ let lastCharacter = "";
2379
+ for (const character of patternToMatch) {
2380
+ if (character === "*" && lastCharacter === "*") {
2381
+ continue;
2382
+ } else {
2383
+ lastCharacter = character;
2384
+ patternParts.push(character);
2385
+ }
2386
+ }
2387
+ pattern = patternParts.join("");
2388
+ }
2389
+ let namespaceIndex = 0;
2390
+ let patternIndex = 0;
2391
+ const patternLength = pattern.length;
2392
+ const namespaceLength = namespace.length;
2393
+ let lastWildcard = -1;
2394
+ let lastWildcardNamespace = -1;
2395
+ while (namespaceIndex < namespaceLength && patternIndex < patternLength) {
2396
+ if (pattern[patternIndex] === "*") {
2397
+ lastWildcard = patternIndex;
2398
+ patternIndex++;
2399
+ if (patternIndex === patternLength) {
2400
+ return true;
2401
+ }
2402
+ while (namespace[namespaceIndex] !== pattern[patternIndex]) {
2403
+ namespaceIndex++;
2404
+ if (namespaceIndex === namespaceLength) {
2405
+ return false;
2406
+ }
2407
+ }
2408
+ lastWildcardNamespace = namespaceIndex;
2409
+ namespaceIndex++;
2410
+ patternIndex++;
2411
+ continue;
2412
+ } else if (pattern[patternIndex] === namespace[namespaceIndex]) {
2413
+ patternIndex++;
2414
+ namespaceIndex++;
2415
+ } else if (lastWildcard >= 0) {
2416
+ patternIndex = lastWildcard + 1;
2417
+ namespaceIndex = lastWildcardNamespace + 1;
2418
+ if (namespaceIndex === namespaceLength) {
2419
+ return false;
2420
+ }
2421
+ while (namespace[namespaceIndex] !== pattern[patternIndex]) {
2422
+ namespaceIndex++;
2423
+ if (namespaceIndex === namespaceLength) {
2424
+ return false;
2425
+ }
2426
+ }
2427
+ lastWildcardNamespace = namespaceIndex;
2428
+ namespaceIndex++;
2429
+ patternIndex++;
2430
+ continue;
2431
+ } else {
2432
+ return false;
2433
+ }
2434
+ }
2435
+ const namespaceDone = namespaceIndex === namespace.length;
2436
+ const patternDone = patternIndex === pattern.length;
2437
+ const trailingWildCard = patternIndex === pattern.length - 1 && pattern[patternIndex] === "*";
2438
+ return namespaceDone && (patternDone || trailingWildCard);
2439
+ }
2440
+ function disable() {
2441
+ const result = enabledString || "";
2442
+ enable("");
2443
+ return result;
2444
+ }
2445
+ function createDebugger(namespace) {
2446
+ const newDebugger = Object.assign(debug, {
2447
+ enabled: enabled(namespace),
2448
+ destroy,
2449
+ log: debugObj.log,
2450
+ namespace,
2451
+ extend
2452
+ });
2453
+ function debug(...args) {
2454
+ if (!newDebugger.enabled) {
2455
+ return;
2456
+ }
2457
+ if (args.length > 0) {
2458
+ args[0] = `${namespace} ${args[0]}`;
2459
+ }
2460
+ newDebugger.log(...args);
2461
+ }
2462
+ debuggers.push(newDebugger);
2463
+ return newDebugger;
2464
+ }
2465
+ function destroy() {
2466
+ const index = debuggers.indexOf(this);
2467
+ if (index >= 0) {
2468
+ debuggers.splice(index, 1);
2469
+ return true;
2470
+ }
2471
+ return false;
2472
+ }
2473
+ function extend(namespace) {
2474
+ const newDebugger = createDebugger(`${this.namespace}:${namespace}`);
2475
+ newDebugger.log = this.log;
2476
+ return newDebugger;
2477
+ }
2478
+ var debug_default = debugObj;
2479
+
2480
+ // node_modules/@typespec/ts-http-runtime/dist/browser/logger/logger.js
2481
+ var TYPESPEC_RUNTIME_LOG_LEVELS = ["verbose", "info", "warning", "error"];
2482
+ var levelMap = {
2483
+ verbose: 400,
2484
+ info: 300,
2485
+ warning: 200,
2486
+ error: 100
2487
+ };
2488
+ function patchLogMethod(parent, child) {
2489
+ child.log = (...args) => {
2490
+ parent.log(...args);
2491
+ };
2492
+ }
2493
+ function isTypeSpecRuntimeLogLevel(level) {
2494
+ return TYPESPEC_RUNTIME_LOG_LEVELS.includes(level);
2495
+ }
2496
+ function createLoggerContext(options) {
2497
+ const registeredLoggers = /* @__PURE__ */ new Set();
2498
+ const logLevelFromEnv = getEnvironmentVariable(options.logLevelEnvVarName);
2499
+ let logLevel;
2500
+ const clientLogger = debug_default(options.namespace);
2501
+ clientLogger.log = (...args) => {
2502
+ debug_default.log(...args);
2503
+ };
2504
+ function contextSetLogLevel(level) {
2505
+ if (level && !isTypeSpecRuntimeLogLevel(level)) {
2506
+ throw new Error(`Unknown log level '${level}'. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(",")}`);
2507
+ }
2508
+ logLevel = level;
2509
+ const enabledNamespaces2 = [];
2510
+ for (const logger3 of registeredLoggers) {
2511
+ if (shouldEnable(logger3)) {
2512
+ enabledNamespaces2.push(logger3.namespace);
2513
+ }
2514
+ }
2515
+ debug_default.enable(enabledNamespaces2.join(","));
2516
+ }
2517
+ if (logLevelFromEnv) {
2518
+ if (isTypeSpecRuntimeLogLevel(logLevelFromEnv)) {
2519
+ contextSetLogLevel(logLevelFromEnv);
2520
+ } else {
2521
+ console.error(`${options.logLevelEnvVarName} set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(", ")}.`);
2522
+ }
2523
+ }
2524
+ function shouldEnable(logger3) {
2525
+ return Boolean(logLevel && levelMap[logger3.level] <= levelMap[logLevel]);
2526
+ }
2527
+ function createLogger(parent, level) {
2528
+ const logger3 = Object.assign(parent.extend(level), {
2529
+ level
2530
+ });
2531
+ patchLogMethod(parent, logger3);
2532
+ if (shouldEnable(logger3)) {
2533
+ const enabledNamespaces2 = debug_default.disable();
2534
+ debug_default.enable(enabledNamespaces2 + "," + logger3.namespace);
2535
+ }
2536
+ registeredLoggers.add(logger3);
2537
+ return logger3;
2538
+ }
2539
+ function contextGetLogLevel() {
2540
+ return logLevel;
2541
+ }
2542
+ function contextCreateClientLogger(namespace) {
2543
+ const clientRootLogger = clientLogger.extend(namespace);
2544
+ patchLogMethod(clientLogger, clientRootLogger);
2545
+ return {
2546
+ error: createLogger(clientRootLogger, "error"),
2547
+ warning: createLogger(clientRootLogger, "warning"),
2548
+ info: createLogger(clientRootLogger, "info"),
2549
+ verbose: createLogger(clientRootLogger, "verbose")
2550
+ };
2551
+ }
2552
+ return {
2553
+ setLogLevel: contextSetLogLevel,
2554
+ getLogLevel: contextGetLogLevel,
2555
+ createClientLogger: contextCreateClientLogger,
2556
+ logger: clientLogger
2557
+ };
2558
+ }
2559
+ var context = createLoggerContext({
2560
+ logLevelEnvVarName: "TYPESPEC_RUNTIME_LOG_LEVEL",
2561
+ namespace: "typeSpecRuntime"
2562
+ });
2563
+ var TypeSpecRuntimeLogger = context.logger;
2564
+
2565
+ // node_modules/@azure/logger/dist/browser/index.js
2566
+ var context2 = createLoggerContext({
2567
+ logLevelEnvVarName: "AZURE_LOG_LEVEL",
2568
+ namespace: "azure"
2569
+ });
2570
+ var AzureLogger = context2.logger;
2571
+ function createClientLogger(namespace) {
2572
+ return context2.createClientLogger(namespace);
2573
+ }
2574
+
2575
+ // node_modules/@azure/web-pubsub-client/dist/browser/logger.js
2576
+ var logger = createClientLogger("web-pubsub-client");
2577
+
2578
+ // node_modules/@azure/web-pubsub-client/dist/browser/protocols/jsonProtocolBase.js
2579
+ function parseMessages(input) {
2580
+ if (typeof input !== "string") {
2581
+ throw new Error("Invalid input for JSON hub protocol. Expected a string.");
2582
+ }
2583
+ if (!input) {
2584
+ throw new Error("No input");
2585
+ }
2586
+ const parsedMessage = JSON.parse(input);
2587
+ const typedMessage = parsedMessage;
2588
+ let returnMessage;
2589
+ if (typedMessage.type === "system") {
2590
+ if (typedMessage.event === "connected") {
2591
+ returnMessage = { ...parsedMessage, kind: "connected" };
2592
+ } else if (typedMessage.event === "disconnected") {
2593
+ returnMessage = { ...parsedMessage, kind: "disconnected" };
2594
+ } else {
2595
+ return null;
2596
+ }
2597
+ } else if (typedMessage.type === "message") {
2598
+ if (typedMessage.from === "group") {
2599
+ const data = parsePayload(parsedMessage.data, parsedMessage.dataType);
2600
+ if (data === null) {
2601
+ return null;
2602
+ }
2603
+ returnMessage = { ...parsedMessage, data, kind: "groupData" };
2604
+ } else if (typedMessage.from === "server") {
2605
+ const data = parsePayload(parsedMessage.data, parsedMessage.dataType);
2606
+ if (data === null) {
2607
+ return null;
2608
+ }
2609
+ returnMessage = {
2610
+ ...parsedMessage,
2611
+ data,
2612
+ kind: "serverData"
2613
+ };
2614
+ } else {
2615
+ return null;
2616
+ }
2617
+ } else if (typedMessage.type === "ack") {
2618
+ returnMessage = { ...parsedMessage, kind: "ack" };
2619
+ } else if (typedMessage.type === "invokeResponse") {
2620
+ let data;
2621
+ if (parsedMessage.dataType != null) {
2622
+ const parsedData = parsePayload(parsedMessage.data, parsedMessage.dataType);
2623
+ if (parsedData === null) {
2624
+ return null;
2625
+ }
2626
+ data = parsedData;
2627
+ }
2628
+ returnMessage = {
2629
+ kind: "invokeResponse",
2630
+ invocationId: parsedMessage.invocationId,
2631
+ success: parsedMessage.success,
2632
+ dataType: parsedMessage.dataType,
2633
+ data,
2634
+ error: parsedMessage.error
2635
+ };
2636
+ } else if (typedMessage.type === "cancelInvocation") {
2637
+ returnMessage = {
2638
+ ...parsedMessage,
2639
+ kind: "cancelInvocation"
2640
+ };
2641
+ } else if (typedMessage.type === "pong") {
2642
+ returnMessage = { ...parsedMessage, kind: "pong" };
2643
+ } else {
2644
+ return null;
2645
+ }
2646
+ return returnMessage;
2647
+ }
2648
+ function writeMessage(message) {
2649
+ let data;
2650
+ switch (message.kind) {
2651
+ case "joinGroup": {
2652
+ data = { type: "joinGroup", group: message.group, ackId: message.ackId };
2653
+ break;
2654
+ }
2655
+ case "leaveGroup": {
2656
+ data = { type: "leaveGroup", group: message.group, ackId: message.ackId };
2657
+ break;
2658
+ }
2659
+ case "sendEvent": {
2660
+ data = {
2661
+ type: "event",
2662
+ event: message.event,
2663
+ ackId: message.ackId,
2664
+ dataType: message.dataType,
2665
+ data: getPayload(message.data, message.dataType)
2666
+ };
2667
+ break;
2668
+ }
2669
+ case "sendToGroup": {
2670
+ data = {
2671
+ type: "sendToGroup",
2672
+ group: message.group,
2673
+ ackId: message.ackId,
2674
+ dataType: message.dataType,
2675
+ data: getPayload(message.data, message.dataType),
2676
+ noEcho: message.noEcho
2677
+ };
2678
+ break;
2679
+ }
2680
+ case "sequenceAck": {
2681
+ data = { type: "sequenceAck", sequenceId: message.sequenceId };
2682
+ break;
2683
+ }
2684
+ case "invoke": {
2685
+ const invokePayload = {
2686
+ type: "invoke",
2687
+ invocationId: message.invocationId,
2688
+ target: message.target,
2689
+ event: message.event
2690
+ };
2691
+ if (message.dataType != null && message.data != null) {
2692
+ invokePayload.dataType = message.dataType;
2693
+ invokePayload.data = getPayload(message.data, message.dataType);
2694
+ }
2695
+ data = invokePayload;
2696
+ break;
2697
+ }
2698
+ case "invokeResponse": {
2699
+ const invokeResponse = {
2700
+ type: "invokeResponse",
2701
+ invocationId: message.invocationId,
2702
+ success: message.success,
2703
+ error: message.error
2704
+ };
2705
+ if (message.dataType != null && message.data != null) {
2706
+ invokeResponse.dataType = message.dataType;
2707
+ invokeResponse.data = getPayload(message.data, message.dataType);
2708
+ }
2709
+ data = invokeResponse;
2710
+ break;
2711
+ }
2712
+ case "cancelInvocation": {
2713
+ data = {
2714
+ type: "cancelInvocation",
2715
+ invocationId: message.invocationId
2716
+ };
2717
+ break;
2718
+ }
2719
+ case "ping": {
2720
+ data = { type: "ping" };
2721
+ break;
2722
+ }
2723
+ default: {
2724
+ throw new Error(`Unsupported type: ${message.kind}`);
2725
+ }
2726
+ }
2727
+ return JSON.stringify(data);
2728
+ }
2729
+ function getPayload(data, dataType) {
2730
+ switch (dataType) {
2731
+ case "text": {
2732
+ if (typeof data !== "string") {
2733
+ throw new TypeError("Message must be a string.");
2734
+ }
2735
+ return data;
2736
+ }
2737
+ case "json": {
2738
+ return data;
2739
+ }
2740
+ case "binary":
2741
+ case "protobuf": {
2742
+ if (data instanceof ArrayBuffer) {
2743
+ return Buffer2.from(data).toString("base64");
2744
+ }
2745
+ throw new TypeError("Message must be a ArrayBuffer");
2746
+ }
2747
+ }
2748
+ }
2749
+ function parsePayload(data, dataType) {
2750
+ if (dataType === "text") {
2751
+ if (typeof data !== "string") {
2752
+ throw new TypeError("Message must be a string when dataType is text");
2753
+ }
2754
+ return data;
2755
+ } else if (dataType === "json") {
2756
+ return data;
2757
+ } else if (dataType === "binary" || dataType === "protobuf") {
2758
+ const buf = Buffer2.from(data, "base64");
2759
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
2760
+ } else {
2761
+ return null;
2762
+ }
2763
+ }
2764
+
2765
+ // node_modules/@azure/web-pubsub-client/dist/browser/protocols/webPubSubJsonReliableProtocol.js
2766
+ var WebPubSubJsonReliableProtocolImpl = class {
2767
+ constructor() {
2768
+ /**
2769
+ * True if the protocol supports reliable features
2770
+ */
2771
+ __publicField(this, "isReliableSubProtocol", true);
2772
+ /**
2773
+ * The name of subprotocol. Name will be used in websocket subprotocol
2774
+ */
2775
+ __publicField(this, "name", "json.reliable.webpubsub.azure.v1");
2776
+ }
2777
+ /**
2778
+ * Creates WebPubSubMessage objects from the specified serialized representation.
2779
+ * @param input - The serialized representation
2780
+ */
2781
+ parseMessages(input) {
2782
+ return parseMessages(input);
2783
+ }
2784
+ /**
2785
+ * Write WebPubSubMessage to string
2786
+ * @param message - The message to be written
2787
+ */
2788
+ writeMessage(message) {
2789
+ return writeMessage(message);
2790
+ }
2791
+ };
2792
+
2793
+ // node_modules/@azure/web-pubsub-client/dist/browser/protocols/index.js
2794
+ var WebPubSubJsonReliableProtocol = () => {
2795
+ return new WebPubSubJsonReliableProtocolImpl();
2796
+ };
2797
+
2798
+ // node_modules/@azure/web-pubsub-client/dist/browser/websocket/websocketClient.js
2799
+ var WebSocketClient = class {
2800
+ constructor(uri, protocolName) {
2801
+ __publicField(this, "_socket");
2802
+ this._socket = new WebSocket(uri, protocolName);
2803
+ this._socket.binaryType = "arraybuffer";
2804
+ }
2805
+ onopen(fn) {
2806
+ this._socket.onopen = fn;
2807
+ }
2808
+ onclose(fn) {
2809
+ this._socket.onclose = (ev) => fn(ev.code, ev.reason);
2810
+ }
2811
+ onerror(fn) {
2812
+ this._socket.onerror = (ev) => fn(ev);
2813
+ }
2814
+ onmessage(fn) {
2815
+ this._socket.onmessage = (event) => fn(event.data);
2816
+ }
2817
+ close(code, reason) {
2818
+ this._socket.close(code, reason);
2819
+ }
2820
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
2821
+ send(data, _) {
2822
+ return new Promise((resolve, reject) => {
2823
+ try {
2824
+ this._socket.send(data);
2825
+ resolve();
2826
+ } catch (err) {
2827
+ reject(err);
2828
+ }
2829
+ });
2830
+ }
2831
+ isOpen() {
2832
+ return this._socket.readyState === WebSocket.OPEN;
2833
+ }
2834
+ };
2835
+ var WebSocketClientFactory = class {
2836
+ create(uri, protocolName) {
2837
+ return new WebSocketClient(uri, protocolName);
2838
+ }
2839
+ };
2840
+
2841
+ // node_modules/@azure/web-pubsub-client/dist/browser/utils/abortablePromise.js
2842
+ async function abortablePromise(promise, signal) {
2843
+ if (signal.aborted) {
2844
+ throw new AbortError("The operation was aborted.");
2845
+ }
2846
+ let onAbort;
2847
+ const p = new Promise((_, reject) => {
2848
+ onAbort = () => {
2849
+ reject(new AbortError("The operation was aborted."));
2850
+ };
2851
+ signal.addEventListener("abort", onAbort);
2852
+ });
2853
+ try {
2854
+ return await Promise.race([promise, p]);
2855
+ } finally {
2856
+ signal.removeEventListener("abort", onAbort);
2857
+ }
2858
+ }
2859
+
2860
+ // node_modules/@azure/web-pubsub-client/dist/browser/ackManager.js
2861
+ var AckManager = class {
2862
+ constructor(initialAckId = 0) {
2863
+ __publicField(this, "_ackEntries", /* @__PURE__ */ new Map());
2864
+ __publicField(this, "_ackId");
2865
+ this._ackId = initialAckId;
2866
+ }
2867
+ registerAck(ackId) {
2868
+ const resolvedAckId = ackId ?? this._generateAckId();
2869
+ let entry = this._ackEntries.get(resolvedAckId);
2870
+ if (!entry) {
2871
+ entry = new AckEntity(resolvedAckId);
2872
+ this._ackEntries.set(resolvedAckId, entry);
2873
+ }
2874
+ const ackEntry = entry;
2875
+ return {
2876
+ ackId: resolvedAckId,
2877
+ wait: (abortSignal) => this._waitForEntry(ackEntry, abortSignal)
2878
+ };
2879
+ }
2880
+ resolveAck(ackId, result) {
2881
+ const entry = this._ackEntries.get(ackId);
2882
+ if (!entry) {
2883
+ return false;
2884
+ }
2885
+ this._ackEntries.delete(ackId);
2886
+ entry.resolve(result);
2887
+ return true;
2888
+ }
2889
+ rejectAck(ackId, reason) {
2890
+ const entry = this._ackEntries.get(ackId);
2891
+ if (!entry) {
2892
+ return false;
2893
+ }
2894
+ this._ackEntries.delete(ackId);
2895
+ entry.reject(reason);
2896
+ return true;
2897
+ }
2898
+ discard(ackId) {
2899
+ this._ackEntries.delete(ackId);
2900
+ }
2901
+ rejectAll(createReason) {
2902
+ this._ackEntries.forEach((entry, ackId) => {
2903
+ if (this._ackEntries.delete(ackId)) {
2904
+ entry.reject(createReason(ackId));
2905
+ }
2906
+ });
2907
+ }
2908
+ _waitForEntry(entry, abortSignal) {
2909
+ if (!abortSignal) {
2910
+ return entry.promise();
2911
+ }
2912
+ return abortablePromise(entry.promise(), abortSignal).catch((err) => {
2913
+ if (err instanceof Error && err.name === "AbortError") {
2914
+ throw new SendMessageError("Cancelled by abortSignal", { ackId: entry.ackId });
2915
+ }
2916
+ throw err;
2917
+ });
2918
+ }
2919
+ _generateAckId() {
2920
+ this._ackId += 1;
2921
+ return this._ackId;
2922
+ }
2923
+ };
2924
+ var AckEntity = class {
2925
+ constructor(ackId) {
2926
+ __publicField(this, "ackId");
2927
+ __publicField(this, "_promise");
2928
+ __publicField(this, "_resolve");
2929
+ __publicField(this, "_reject");
2930
+ this.ackId = ackId;
2931
+ this._promise = new Promise((resolve, reject) => {
2932
+ this._resolve = resolve;
2933
+ this._reject = reject;
2934
+ });
2935
+ }
2936
+ promise() {
2937
+ return this._promise;
2938
+ }
2939
+ resolve(value) {
2940
+ const callback = this._resolve;
2941
+ if (!callback) {
2942
+ return;
2943
+ }
2944
+ this._resolve = void 0;
2945
+ this._reject = void 0;
2946
+ callback(value);
2947
+ }
2948
+ reject(reason) {
2949
+ const callback = this._reject;
2950
+ if (!callback) {
2951
+ return;
2952
+ }
2953
+ this._resolve = void 0;
2954
+ this._reject = void 0;
2955
+ callback(reason);
2956
+ }
2957
+ };
2958
+
2959
+ // node_modules/@azure/web-pubsub-client/dist/browser/invocationManager.js
2960
+ var InvocationManager = class {
2961
+ constructor() {
2962
+ __publicField(this, "_entries", /* @__PURE__ */ new Map());
2963
+ __publicField(this, "_nextId", 0);
2964
+ }
2965
+ registerInvocation(invocationId) {
2966
+ const resolvedId = invocationId ?? this._generateInvocationId();
2967
+ if (this._entries.has(resolvedId)) {
2968
+ throw new InvocationError("Invocation id is already registered.", {
2969
+ invocationId: resolvedId
2970
+ });
2971
+ }
2972
+ const entity = new InvocationEntity(resolvedId);
2973
+ this._entries.set(resolvedId, entity);
2974
+ return {
2975
+ invocationId: resolvedId,
2976
+ wait: (options) => this._waitForEntry(entity, options)
2977
+ };
2978
+ }
2979
+ resolveInvocation(message) {
2980
+ const entry = this._entries.get(message.invocationId);
2981
+ if (!entry) {
2982
+ return false;
2983
+ }
2984
+ this._entries.delete(message.invocationId);
2985
+ entry.resolve(message);
2986
+ return true;
2987
+ }
2988
+ rejectInvocation(invocationId, reason) {
2989
+ const entry = this._entries.get(invocationId);
2990
+ if (!entry) {
2991
+ return false;
2992
+ }
2993
+ this._entries.delete(invocationId);
2994
+ entry.reject(reason);
2995
+ return true;
2996
+ }
2997
+ discard(invocationId) {
2998
+ this._entries.delete(invocationId);
2999
+ }
3000
+ rejectAll(createReason) {
3001
+ this._entries.forEach((entry, invocationId) => {
3002
+ if (this._entries.delete(invocationId)) {
3003
+ entry.reject(createReason(invocationId));
3004
+ }
3005
+ });
3006
+ }
3007
+ _waitForEntry(entry, options) {
3008
+ const waitPromise = entry.promise();
3009
+ const abortSignal = options?.abortSignal;
3010
+ if (!abortSignal) {
3011
+ return waitPromise;
3012
+ }
3013
+ if (abortSignal.aborted) {
3014
+ if (this._entries.delete(entry.invocationId)) {
3015
+ entry.reject(this._createAbortError(entry.invocationId));
3016
+ }
3017
+ return waitPromise;
3018
+ }
3019
+ return new Promise((resolve, reject) => {
3020
+ const onAbort = () => {
3021
+ abortSignal.removeEventListener("abort", onAbort);
3022
+ if (this._entries.delete(entry.invocationId)) {
3023
+ entry.reject(this._createAbortError(entry.invocationId));
3024
+ }
3025
+ };
3026
+ abortSignal.addEventListener("abort", onAbort);
3027
+ waitPromise.then((result) => {
3028
+ abortSignal.removeEventListener("abort", onAbort);
3029
+ return resolve(result);
3030
+ }).catch((err) => {
3031
+ abortSignal.removeEventListener("abort", onAbort);
3032
+ return reject(err);
3033
+ });
3034
+ });
3035
+ }
3036
+ _generateInvocationId() {
3037
+ this._nextId += 1;
3038
+ return this._nextId.toString();
3039
+ }
3040
+ _createAbortError(invocationId) {
3041
+ return new InvocationError("Invocation cancelled by abortSignal.", {
3042
+ invocationId
3043
+ });
3044
+ }
3045
+ };
3046
+ var InvocationEntity = class {
3047
+ constructor(invocationId) {
3048
+ __publicField(this, "invocationId");
3049
+ __publicField(this, "_promise");
3050
+ __publicField(this, "_resolve");
3051
+ __publicField(this, "_reject");
3052
+ this.invocationId = invocationId;
3053
+ this._promise = new Promise((resolve, reject) => {
3054
+ this._resolve = resolve;
3055
+ this._reject = reject;
3056
+ });
3057
+ }
3058
+ promise() {
3059
+ return this._promise;
3060
+ }
3061
+ resolve(value) {
3062
+ const callback = this._resolve;
3063
+ if (!callback) {
3064
+ return;
3065
+ }
3066
+ this._resolve = void 0;
3067
+ this._reject = void 0;
3068
+ callback(value);
3069
+ }
3070
+ reject(reason) {
3071
+ const callback = this._reject;
3072
+ if (!callback) {
3073
+ return;
3074
+ }
3075
+ this._resolve = void 0;
3076
+ this._reject = void 0;
3077
+ callback(reason);
3078
+ }
3079
+ };
3080
+
3081
+ // node_modules/@azure/web-pubsub-client/dist/browser/webPubSubClient.js
3082
+ var WebPubSubClientState;
3083
+ (function(WebPubSubClientState2) {
3084
+ WebPubSubClientState2["Stopped"] = "Stopped";
3085
+ WebPubSubClientState2["Disconnected"] = "Disconnected";
3086
+ WebPubSubClientState2["Connecting"] = "Connecting";
3087
+ WebPubSubClientState2["Connected"] = "Connected";
3088
+ WebPubSubClientState2["Recovering"] = "Recovering";
3089
+ })(WebPubSubClientState || (WebPubSubClientState = {}));
3090
+ var WebPubSubClient = class {
3091
+ constructor(credential, options) {
3092
+ __publicField(this, "_protocol");
3093
+ __publicField(this, "_credential");
3094
+ __publicField(this, "_options");
3095
+ __publicField(this, "_groupMap");
3096
+ __publicField(this, "_ackManager");
3097
+ __publicField(this, "_invocationManager");
3098
+ __publicField(this, "_sequenceId");
3099
+ __publicField(this, "_messageRetryPolicy");
3100
+ __publicField(this, "_reconnectRetryPolicy");
3101
+ __publicField(this, "_quickSequenceAckDiff", 300);
3102
+ // The timeout for keep alive
3103
+ __publicField(this, "_keepAliveTimeoutInMs");
3104
+ // The interval at which to send keep-alive ping messages to the runtime
3105
+ __publicField(this, "_keepAliveIntervalInMs");
3106
+ __publicField(this, "_emitter", new exports3());
3107
+ __publicField(this, "_state");
3108
+ __publicField(this, "_isStopping", false);
3109
+ __publicField(this, "_pingKeepaliveTask");
3110
+ __publicField(this, "_timeoutMonitorTask");
3111
+ // connection lifetime
3112
+ __publicField(this, "_wsClient");
3113
+ __publicField(this, "_uri");
3114
+ __publicField(this, "_lastCloseEvent");
3115
+ __publicField(this, "_lastDisconnectedMessage");
3116
+ __publicField(this, "_connectionId");
3117
+ __publicField(this, "_reconnectionToken");
3118
+ __publicField(this, "_isInitialConnected", false);
3119
+ __publicField(this, "_sequenceAckTask");
3120
+ __publicField(this, "_lastMessageReceived", Date.now());
3121
+ if (typeof credential === "string") {
3122
+ this._credential = { getClientAccessUrl: credential };
3123
+ } else {
3124
+ this._credential = credential;
3125
+ }
3126
+ if (options == null) {
3127
+ options = {};
3128
+ }
3129
+ this._buildDefaultOptions(options);
3130
+ this._options = options;
3131
+ this._messageRetryPolicy = new RetryPolicy(this._options.messageRetryOptions);
3132
+ this._reconnectRetryPolicy = new RetryPolicy(this._options.reconnectRetryOptions);
3133
+ this._protocol = this._options.protocol;
3134
+ this._groupMap = /* @__PURE__ */ new Map();
3135
+ this._ackManager = new AckManager();
3136
+ this._invocationManager = new InvocationManager();
3137
+ this._sequenceId = new SequenceId();
3138
+ this._keepAliveTimeoutInMs = this._options.keepAliveTimeoutInMs ?? 12e4;
3139
+ this._keepAliveIntervalInMs = this._options.keepAliveIntervalInMs ?? 2e4;
3140
+ this._state = WebPubSubClientState.Stopped;
3141
+ }
3142
+ /**
3143
+ * Start to start to the service.
3144
+ * @param abortSignal - The abort signal
3145
+ */
3146
+ async start(options) {
3147
+ if (this._isStopping) {
3148
+ throw new Error("Can't start a client during stopping");
3149
+ }
3150
+ if (this._state !== WebPubSubClientState.Stopped) {
3151
+ throw new Error("Client can be only started when it's Stopped");
3152
+ }
3153
+ let abortSignal;
3154
+ if (options) {
3155
+ abortSignal = options.abortSignal;
3156
+ }
3157
+ if (!this._pingKeepaliveTask && this._keepAliveIntervalInMs > 0) {
3158
+ this._pingKeepaliveTask = this._getPingKeepaliveTask();
3159
+ }
3160
+ if (!this._timeoutMonitorTask && this._keepAliveTimeoutInMs > 0) {
3161
+ this._timeoutMonitorTask = this._getTimeoutMonitorTask();
3162
+ }
3163
+ try {
3164
+ await this._startCore(abortSignal);
3165
+ } catch (err) {
3166
+ this._changeState(WebPubSubClientState.Stopped);
3167
+ this._disposeKeepaliveTasks();
3168
+ this._isStopping = false;
3169
+ throw err;
3170
+ }
3171
+ }
3172
+ async _startFromRestarting(abortSignal) {
3173
+ if (this._state !== WebPubSubClientState.Disconnected) {
3174
+ throw new Error("Client can be only restarted when it's Disconnected");
3175
+ }
3176
+ try {
3177
+ logger.verbose("Staring reconnecting.");
3178
+ await this._startCore(abortSignal);
3179
+ } catch (err) {
3180
+ this._changeState(WebPubSubClientState.Disconnected);
3181
+ throw err;
3182
+ }
3183
+ }
3184
+ async _startCore(abortSignal) {
3185
+ this._changeState(WebPubSubClientState.Connecting);
3186
+ logger.info("Staring a new connection");
3187
+ this._sequenceId.reset();
3188
+ this._isInitialConnected = false;
3189
+ this._lastCloseEvent = void 0;
3190
+ this._lastDisconnectedMessage = void 0;
3191
+ this._connectionId = void 0;
3192
+ this._reconnectionToken = void 0;
3193
+ this._uri = void 0;
3194
+ if (typeof this._credential.getClientAccessUrl === "string") {
3195
+ this._uri = this._credential.getClientAccessUrl;
3196
+ } else {
3197
+ this._uri = await this._credential.getClientAccessUrl({
3198
+ abortSignal
3199
+ });
3200
+ }
3201
+ if (typeof this._uri !== "string") {
3202
+ throw new Error(`The clientAccessUrl must be a string but currently it's ${typeof this._uri}`);
3203
+ }
3204
+ await this._connectCore(this._uri);
3205
+ }
3206
+ /**
3207
+ * Stop the client.
3208
+ */
3209
+ stop() {
3210
+ if (this._state === WebPubSubClientState.Stopped || this._isStopping) {
3211
+ return;
3212
+ }
3213
+ this._isStopping = true;
3214
+ if (this._wsClient && this._wsClient.isOpen()) {
3215
+ this._wsClient.close();
3216
+ } else {
3217
+ this._isStopping = false;
3218
+ }
3219
+ this._disposeKeepaliveTasks();
3220
+ }
3221
+ _disposeKeepaliveTasks() {
3222
+ if (this._pingKeepaliveTask) {
3223
+ this._pingKeepaliveTask.abort();
3224
+ this._pingKeepaliveTask = void 0;
3225
+ }
3226
+ if (this._timeoutMonitorTask) {
3227
+ this._timeoutMonitorTask.abort();
3228
+ this._timeoutMonitorTask = void 0;
3229
+ }
3230
+ }
3231
+ on(event, listener) {
3232
+ this._emitter.on(event, listener);
3233
+ }
3234
+ off(event, listener) {
3235
+ this._emitter.removeListener(event, listener);
3236
+ }
3237
+ _emitEvent(event, args) {
3238
+ this._emitter.emit(event, args);
3239
+ }
3240
+ /**
3241
+ * Send custom event to server.
3242
+ * @param eventName - The event name
3243
+ * @param content - The data content
3244
+ * @param dataType - The data type
3245
+ * @param options - The options
3246
+ * @param abortSignal - The abort signal
3247
+ */
3248
+ async sendEvent(eventName, content, dataType, options) {
3249
+ return this._operationExecuteWithRetry(() => this._sendEventAttempt(eventName, content, dataType, options), options?.abortSignal);
3250
+ }
3251
+ async _sendEventAttempt(eventName, content, dataType, options) {
3252
+ const fireAndForget = options?.fireAndForget ?? false;
3253
+ if (!fireAndForget) {
3254
+ return this._sendMessageWithAckId((id) => {
3255
+ return {
3256
+ kind: "sendEvent",
3257
+ dataType,
3258
+ data: content,
3259
+ ackId: id,
3260
+ event: eventName
3261
+ };
3262
+ }, options?.ackId, options?.abortSignal);
3263
+ }
3264
+ const message = {
3265
+ kind: "sendEvent",
3266
+ dataType,
3267
+ data: content,
3268
+ event: eventName
3269
+ };
3270
+ await this._sendMessage(message, options?.abortSignal);
3271
+ return { isDuplicated: false };
3272
+ }
3273
+ async _invokeEventAttempt(eventName, content, dataType, options) {
3274
+ const invokeOptions = options ?? {};
3275
+ const { invocationId, wait } = this._invocationManager.registerInvocation(invokeOptions.invocationId);
3276
+ const invokeMessage = {
3277
+ kind: "invoke",
3278
+ invocationId,
3279
+ target: "event",
3280
+ event: eventName,
3281
+ dataType,
3282
+ data: content
3283
+ };
3284
+ const responsePromise = wait({
3285
+ abortSignal: invokeOptions.abortSignal
3286
+ });
3287
+ try {
3288
+ await this._sendMessage(invokeMessage, invokeOptions.abortSignal);
3289
+ } catch (err) {
3290
+ const invocationError = err instanceof InvocationError ? err : new InvocationError(err instanceof Error ? err.message : "Failed to send invocation message.", {
3291
+ invocationId
3292
+ });
3293
+ this._invocationManager.rejectInvocation(invocationId, invocationError);
3294
+ void responsePromise.catch(() => {
3295
+ });
3296
+ throw invocationError;
3297
+ }
3298
+ try {
3299
+ const response = await responsePromise;
3300
+ return this._mapInvokeResponse(response);
3301
+ } catch (err) {
3302
+ const shouldCancel = err instanceof InvocationError && err.errorDetail == null || invokeOptions.abortSignal?.aborted === true;
3303
+ if (shouldCancel) {
3304
+ await this._sendCancelInvocation(invocationId).catch(() => {
3305
+ });
3306
+ }
3307
+ throw err;
3308
+ } finally {
3309
+ this._invocationManager.discard(invocationId);
3310
+ }
3311
+ }
3312
+ /**
3313
+ * Invoke an upstream event and wait for the correlated response.
3314
+ * @param eventName - The event name
3315
+ * @param content - The payload
3316
+ * @param dataType - The payload type
3317
+ * @param options - Invoke options
3318
+ */
3319
+ async invokeEvent(eventName, content, dataType, options) {
3320
+ return this._operationExecuteWithRetry(() => this._invokeEventAttempt(eventName, content, dataType, options), options?.abortSignal);
3321
+ }
3322
+ /**
3323
+ * Join the client to group
3324
+ * @param groupName - The group name
3325
+ * @param options - The join group options
3326
+ */
3327
+ async joinGroup(groupName, options) {
3328
+ return this._operationExecuteWithRetry(() => this._joinGroupAttempt(groupName, options), options?.abortSignal);
3329
+ }
3330
+ async _joinGroupAttempt(groupName, options) {
3331
+ const group = this._getOrAddGroup(groupName);
3332
+ const result = await this._joinGroupCore(groupName, options);
3333
+ group.isJoined = true;
3334
+ return result;
3335
+ }
3336
+ async _joinGroupCore(groupName, options) {
3337
+ return this._sendMessageWithAckId((id) => {
3338
+ return {
3339
+ group: groupName,
3340
+ ackId: id,
3341
+ kind: "joinGroup"
3342
+ };
3343
+ }, options?.ackId, options?.abortSignal);
3344
+ }
3345
+ /**
3346
+ * Leave the client from group
3347
+ * @param groupName - The group name
3348
+ * @param ackId - The optional ackId. If not specified, client will generate one.
3349
+ * @param abortSignal - The abort signal
3350
+ */
3351
+ async leaveGroup(groupName, options) {
3352
+ return this._operationExecuteWithRetry(() => this._leaveGroupAttempt(groupName, options), options?.abortSignal);
3353
+ }
3354
+ async _leaveGroupAttempt(groupName, options) {
3355
+ const group = this._getOrAddGroup(groupName);
3356
+ const result = await this._sendMessageWithAckId((id) => {
3357
+ return {
3358
+ group: groupName,
3359
+ ackId: id,
3360
+ kind: "leaveGroup"
3361
+ };
3362
+ }, options?.ackId, options?.abortSignal);
3363
+ group.isJoined = false;
3364
+ return result;
3365
+ }
3366
+ /**
3367
+ * Send message to group.
3368
+ * @param groupName - The group name
3369
+ * @param content - The data content
3370
+ * @param dataType - The data type
3371
+ * @param options - The options
3372
+ * @param abortSignal - The abort signal
3373
+ */
3374
+ async sendToGroup(groupName, content, dataType, options) {
3375
+ return this._operationExecuteWithRetry(() => this._sendToGroupAttempt(groupName, content, dataType, options), options?.abortSignal);
3376
+ }
3377
+ async _sendToGroupAttempt(groupName, content, dataType, options) {
3378
+ const fireAndForget = options?.fireAndForget ?? false;
3379
+ const noEcho = options?.noEcho ?? false;
3380
+ if (!fireAndForget) {
3381
+ return this._sendMessageWithAckId((id) => {
3382
+ return {
3383
+ kind: "sendToGroup",
3384
+ group: groupName,
3385
+ dataType,
3386
+ data: content,
3387
+ ackId: id,
3388
+ noEcho
3389
+ };
3390
+ }, options?.ackId, options?.abortSignal);
3391
+ }
3392
+ const message = {
3393
+ kind: "sendToGroup",
3394
+ group: groupName,
3395
+ dataType,
3396
+ data: content,
3397
+ noEcho
3398
+ };
3399
+ await this._sendMessage(message, options?.abortSignal);
3400
+ return { isDuplicated: false };
3401
+ }
3402
+ _getWebSocketClientFactory() {
3403
+ return new WebSocketClientFactory();
3404
+ }
3405
+ async _trySendSequenceAck() {
3406
+ if (!this._protocol.isReliableSubProtocol) {
3407
+ return;
3408
+ }
3409
+ const [isUpdated, seqId] = this._sequenceId.tryGetSequenceId();
3410
+ if (isUpdated && seqId !== null && seqId !== void 0) {
3411
+ const message = {
3412
+ kind: "sequenceAck",
3413
+ sequenceId: seqId
3414
+ };
3415
+ try {
3416
+ await this._sendMessage(message);
3417
+ } catch {
3418
+ this._sequenceId.tryUpdate(seqId);
3419
+ }
3420
+ }
3421
+ }
3422
+ _connectCore(uri) {
3423
+ if (this._isStopping) {
3424
+ throw new Error("Can't start a client during stopping");
3425
+ }
3426
+ return new Promise((resolve, reject) => {
3427
+ const client = this._wsClient = this._getWebSocketClientFactory().create(uri, this._protocol.name);
3428
+ client.onopen(() => {
3429
+ if (this._isStopping) {
3430
+ try {
3431
+ client.close();
3432
+ } catch {
3433
+ }
3434
+ reject(new Error(`The client is stopped`));
3435
+ }
3436
+ logger.verbose("WebSocket connection has opened");
3437
+ this._lastMessageReceived = Date.now();
3438
+ this._changeState(WebPubSubClientState.Connected);
3439
+ if (this._protocol.isReliableSubProtocol) {
3440
+ if (this._sequenceAckTask != null) {
3441
+ this._sequenceAckTask.abort();
3442
+ }
3443
+ this._sequenceAckTask = new AbortableTask(async () => {
3444
+ await this._trySendSequenceAck();
3445
+ }, 1e3);
3446
+ }
3447
+ resolve();
3448
+ });
3449
+ client.onerror((e) => {
3450
+ if (this._sequenceAckTask != null) {
3451
+ this._sequenceAckTask.abort();
3452
+ }
3453
+ reject(e);
3454
+ });
3455
+ client.onclose((code, reason) => {
3456
+ if (this._state === WebPubSubClientState.Connected) {
3457
+ logger.verbose("WebSocket closed after open");
3458
+ if (this._sequenceAckTask != null) {
3459
+ this._sequenceAckTask.abort();
3460
+ }
3461
+ logger.info(`WebSocket connection closed. Code: ${code}, Reason: ${reason}`);
3462
+ this._lastCloseEvent = { code, reason };
3463
+ this._handleConnectionClose.call(this);
3464
+ } else {
3465
+ logger.verbose("WebSocket closed before open");
3466
+ reject(new Error(`Failed to start WebSocket: ${code}`));
3467
+ }
3468
+ });
3469
+ client.onmessage((data) => {
3470
+ const handleAckMessage = (message) => {
3471
+ const isDuplicated = message.error != null && message.error.name === "Duplicate";
3472
+ if (message.success || isDuplicated) {
3473
+ this._ackManager.resolveAck(message.ackId, {
3474
+ ackId: message.ackId,
3475
+ isDuplicated
3476
+ });
3477
+ } else {
3478
+ this._ackManager.rejectAck(message.ackId, new SendMessageError("Failed to send message.", {
3479
+ ackId: message.ackId,
3480
+ errorDetail: message.error
3481
+ }));
3482
+ }
3483
+ };
3484
+ const handleConnectedMessage = async (message) => {
3485
+ this._connectionId = message.connectionId;
3486
+ this._reconnectionToken = message.reconnectionToken;
3487
+ if (!this._isInitialConnected) {
3488
+ this._isInitialConnected = true;
3489
+ if (this._options.autoRejoinGroups) {
3490
+ const groupPromises = [];
3491
+ this._groupMap.forEach((g) => {
3492
+ if (g.isJoined) {
3493
+ groupPromises.push((async () => {
3494
+ try {
3495
+ await this._joinGroupCore(g.name);
3496
+ } catch (err) {
3497
+ this._safeEmitRejoinGroupFailed(g.name, err);
3498
+ }
3499
+ })());
3500
+ }
3501
+ });
3502
+ await Promise.all(groupPromises).catch(() => {
3503
+ });
3504
+ }
3505
+ this._safeEmitConnected(message.connectionId, message.userId);
3506
+ }
3507
+ };
3508
+ const handleDisconnectedMessage = (message) => {
3509
+ this._lastDisconnectedMessage = message;
3510
+ };
3511
+ const handleGroupDataMessage = (message) => {
3512
+ if (message.sequenceId != null) {
3513
+ const diff = this._sequenceId.tryUpdate(message.sequenceId);
3514
+ if (diff === 0) {
3515
+ return;
3516
+ }
3517
+ if (diff > this._quickSequenceAckDiff) {
3518
+ this._trySendSequenceAck();
3519
+ }
3520
+ }
3521
+ this._safeEmitGroupMessage(message);
3522
+ };
3523
+ const handleServerDataMessage = (message) => {
3524
+ if (message.sequenceId != null) {
3525
+ const diff = this._sequenceId.tryUpdate(message.sequenceId);
3526
+ if (diff === 0) {
3527
+ return;
3528
+ }
3529
+ if (diff > this._quickSequenceAckDiff) {
3530
+ this._trySendSequenceAck();
3531
+ }
3532
+ }
3533
+ this._safeEmitServerMessage(message);
3534
+ };
3535
+ const handleInvokeResponseMessage = (message) => {
3536
+ const resolved = this._invocationManager.resolveInvocation(message);
3537
+ if (!resolved) {
3538
+ logger.verbose(`Received invokeResponse for unknown invocationId: ${message.invocationId}`);
3539
+ }
3540
+ };
3541
+ this._lastMessageReceived = Date.now();
3542
+ let messages;
3543
+ try {
3544
+ let convertedData;
3545
+ if (Array.isArray(data)) {
3546
+ convertedData = Buffer2.concat(data);
3547
+ } else {
3548
+ convertedData = data;
3549
+ }
3550
+ messages = this._protocol.parseMessages(convertedData);
3551
+ if (messages === null) {
3552
+ return;
3553
+ }
3554
+ } catch (err) {
3555
+ logger.warning("An error occurred while parsing the message from service", err);
3556
+ throw err;
3557
+ }
3558
+ if (!Array.isArray(messages)) {
3559
+ messages = [messages];
3560
+ }
3561
+ messages.forEach((message) => {
3562
+ try {
3563
+ switch (message.kind) {
3564
+ case "pong": {
3565
+ break;
3566
+ }
3567
+ case "ack": {
3568
+ handleAckMessage(message);
3569
+ break;
3570
+ }
3571
+ case "connected": {
3572
+ handleConnectedMessage(message);
3573
+ break;
3574
+ }
3575
+ case "disconnected": {
3576
+ handleDisconnectedMessage(message);
3577
+ break;
3578
+ }
3579
+ case "groupData": {
3580
+ handleGroupDataMessage(message);
3581
+ break;
3582
+ }
3583
+ case "serverData": {
3584
+ handleServerDataMessage(message);
3585
+ break;
3586
+ }
3587
+ case "invokeResponse": {
3588
+ handleInvokeResponseMessage(message);
3589
+ break;
3590
+ }
3591
+ }
3592
+ } catch (err) {
3593
+ logger.warning(`An error occurred while handling the message with kind: ${message.kind} from service`, err);
3594
+ }
3595
+ });
3596
+ });
3597
+ });
3598
+ }
3599
+ async _handleConnectionCloseAndNoRecovery() {
3600
+ this._state = WebPubSubClientState.Disconnected;
3601
+ this._safeEmitDisconnected(this._connectionId, this._lastDisconnectedMessage);
3602
+ if (this._options.autoReconnect) {
3603
+ await this._autoReconnect();
3604
+ } else {
3605
+ await this._handleConnectionStopped();
3606
+ }
3607
+ }
3608
+ async _autoReconnect() {
3609
+ let isSuccess = false;
3610
+ let attempt = 0;
3611
+ try {
3612
+ while (!this._isStopping) {
3613
+ try {
3614
+ await this._startFromRestarting();
3615
+ isSuccess = true;
3616
+ break;
3617
+ } catch (err) {
3618
+ logger.warning("An attempt to reconnect connection failed.", err);
3619
+ attempt++;
3620
+ const delayInMs = this._reconnectRetryPolicy.nextRetryDelayInMs(attempt);
3621
+ if (delayInMs == null) {
3622
+ break;
3623
+ }
3624
+ logger.verbose(`Delay time for reconnect attempt ${attempt}: ${delayInMs}`);
3625
+ await delay(delayInMs).catch(() => {
3626
+ });
3627
+ }
3628
+ }
3629
+ } finally {
3630
+ if (!isSuccess) {
3631
+ this._handleConnectionStopped();
3632
+ }
3633
+ }
3634
+ }
3635
+ _handleConnectionStopped() {
3636
+ this._isStopping = false;
3637
+ this._state = WebPubSubClientState.Stopped;
3638
+ this._disposeKeepaliveTasks();
3639
+ this._safeEmitStopped();
3640
+ }
3641
+ async _trySendPing() {
3642
+ if (this._state !== WebPubSubClientState.Connected || !this._wsClient?.isOpen()) {
3643
+ return;
3644
+ }
3645
+ const message = {
3646
+ kind: "ping"
3647
+ };
3648
+ try {
3649
+ await this._sendMessage(message);
3650
+ } catch {
3651
+ logger.warning("Failed to send keepalive message to the service");
3652
+ }
3653
+ }
3654
+ async _checkKeepAliveTimeout() {
3655
+ if (this._state !== WebPubSubClientState.Connected || !this._wsClient?.isOpen()) {
3656
+ return;
3657
+ }
3658
+ const now = Date.now();
3659
+ if (now - this._lastMessageReceived > this._keepAliveTimeoutInMs) {
3660
+ logger.warning(`No messages received for ${now - this._lastMessageReceived} ms. Closing. The keep alive timeout is set to ${this._keepAliveTimeoutInMs} ms.`);
3661
+ this._wsClient?.close();
3662
+ }
3663
+ }
3664
+ _getPingKeepaliveTask() {
3665
+ return new AbortableTask(async () => {
3666
+ await this._trySendPing();
3667
+ }, this._keepAliveIntervalInMs);
3668
+ }
3669
+ _getTimeoutMonitorTask() {
3670
+ const timeout = this._keepAliveTimeoutInMs;
3671
+ const checkInterval = Math.floor(timeout / 3);
3672
+ return new AbortableTask(async () => {
3673
+ await this._checkKeepAliveTimeout();
3674
+ }, checkInterval);
3675
+ }
3676
+ async _sendMessage(message, abortSignal) {
3677
+ if (!this._wsClient || !this._wsClient.isOpen()) {
3678
+ throw new Error("The connection is not connected.");
3679
+ }
3680
+ const payload = this._protocol.writeMessage(message);
3681
+ await this._wsClient.send(payload, abortSignal);
3682
+ }
3683
+ async _sendMessageWithAckId(messageProvider, ackId, abortSignal) {
3684
+ const { ackId: resolvedAckId, wait } = this._ackManager.registerAck(ackId);
3685
+ const message = messageProvider(resolvedAckId);
3686
+ try {
3687
+ await this._sendMessage(message, abortSignal);
3688
+ } catch (error) {
3689
+ this._ackManager.discard(resolvedAckId);
3690
+ let errorMessage = "";
3691
+ if (error instanceof Error) {
3692
+ errorMessage = error.message;
3693
+ }
3694
+ throw new SendMessageError(errorMessage, { ackId: resolvedAckId });
3695
+ }
3696
+ return wait(abortSignal);
3697
+ }
3698
+ async _handleConnectionClose() {
3699
+ this._ackManager.rejectAll((ackId) => {
3700
+ return new SendMessageError("Connection is disconnected before receive ack from the service", {
3701
+ ackId
3702
+ });
3703
+ });
3704
+ this._invocationManager.rejectAll((invocationId) => {
3705
+ return new InvocationError("Connection is disconnected before receiving invoke response from the service", {
3706
+ invocationId
3707
+ });
3708
+ });
3709
+ if (this._isStopping) {
3710
+ logger.warning("The client is stopping state. Stop recovery.");
3711
+ this._handleConnectionCloseAndNoRecovery();
3712
+ return;
3713
+ }
3714
+ if (this._lastCloseEvent && this._lastCloseEvent.code === 1008) {
3715
+ logger.warning("The websocket close with status code 1008. Stop recovery.");
3716
+ this._handleConnectionCloseAndNoRecovery();
3717
+ return;
3718
+ }
3719
+ if (!this._protocol.isReliableSubProtocol) {
3720
+ logger.warning("The protocol is not reliable, recovery is not applicable");
3721
+ this._handleConnectionCloseAndNoRecovery();
3722
+ return;
3723
+ }
3724
+ const recoveryUri = this._buildRecoveryUri();
3725
+ if (!recoveryUri) {
3726
+ logger.warning("Connection id or reconnection token is not available");
3727
+ this._handleConnectionCloseAndNoRecovery();
3728
+ return;
3729
+ }
3730
+ let recovered = false;
3731
+ this._state = WebPubSubClientState.Recovering;
3732
+ const abortSignal = AbortSignal.timeout(30 * 1e3);
3733
+ try {
3734
+ while (!abortSignal.aborted || this._isStopping) {
3735
+ try {
3736
+ await this._connectCore.call(this, recoveryUri);
3737
+ recovered = true;
3738
+ return;
3739
+ } catch {
3740
+ await delay(1e3);
3741
+ }
3742
+ }
3743
+ } finally {
3744
+ if (!recovered) {
3745
+ logger.warning("Recovery attempts failed more then 30 seconds or the client is stopping");
3746
+ this._handleConnectionCloseAndNoRecovery();
3747
+ }
3748
+ }
3749
+ }
3750
+ _safeEmitConnected(connectionId, userId) {
3751
+ this._emitEvent("connected", {
3752
+ connectionId,
3753
+ userId
3754
+ });
3755
+ }
3756
+ _safeEmitDisconnected(connectionId, lastDisconnectedMessage) {
3757
+ this._emitEvent("disconnected", {
3758
+ connectionId,
3759
+ message: lastDisconnectedMessage
3760
+ });
3761
+ }
3762
+ _safeEmitGroupMessage(message) {
3763
+ this._emitEvent("group-message", {
3764
+ message
3765
+ });
3766
+ }
3767
+ _safeEmitServerMessage(message) {
3768
+ this._emitEvent("server-message", {
3769
+ message
3770
+ });
3771
+ }
3772
+ _safeEmitStopped() {
3773
+ this._emitEvent("stopped", {});
3774
+ }
3775
+ _safeEmitRejoinGroupFailed(groupName, err) {
3776
+ this._emitEvent("rejoin-group-failed", {
3777
+ group: groupName,
3778
+ error: err
3779
+ });
3780
+ }
3781
+ _mapInvokeResponse(message) {
3782
+ if (message.success !== true) {
3783
+ if (message.success === false) {
3784
+ throw new InvocationError(message.error?.message ?? "Invocation failed.", {
3785
+ invocationId: message.invocationId,
3786
+ errorDetail: message.error
3787
+ });
3788
+ }
3789
+ throw new InvocationError("Unsupported invoke response frame.", {
3790
+ invocationId: message.invocationId
3791
+ });
3792
+ }
3793
+ return {
3794
+ invocationId: message.invocationId,
3795
+ dataType: message.dataType,
3796
+ data: message.data
3797
+ };
3798
+ }
3799
+ async _sendCancelInvocation(invocationId) {
3800
+ const message = {
3801
+ kind: "cancelInvocation",
3802
+ invocationId
3803
+ };
3804
+ try {
3805
+ await this._sendMessage(message);
3806
+ } catch (err) {
3807
+ logger.verbose(`Failed to send cancelInvocation for ${invocationId}`, err);
3808
+ }
3809
+ }
3810
+ _buildDefaultOptions(clientOptions) {
3811
+ if (clientOptions.autoReconnect == null) {
3812
+ clientOptions.autoReconnect = true;
3813
+ }
3814
+ if (clientOptions.autoRejoinGroups == null) {
3815
+ clientOptions.autoRejoinGroups = true;
3816
+ }
3817
+ if (clientOptions.protocol == null) {
3818
+ clientOptions.protocol = WebPubSubJsonReliableProtocol();
3819
+ }
3820
+ if (clientOptions.keepAliveTimeoutInMs == null) {
3821
+ clientOptions.keepAliveTimeoutInMs = 12e4;
3822
+ }
3823
+ if (clientOptions.keepAliveTimeoutInMs < 0) {
3824
+ throw new RangeError("keepAliveTimeoutInMs must be greater than or equal to 0.");
3825
+ }
3826
+ if (clientOptions.keepAliveIntervalInMs == null) {
3827
+ clientOptions.keepAliveIntervalInMs = 2e4;
3828
+ }
3829
+ if (clientOptions.keepAliveIntervalInMs < 0) {
3830
+ throw new RangeError("keepAliveIntervalInMs must be greater than or equal to 0.");
3831
+ }
3832
+ this._buildMessageRetryOptions(clientOptions);
3833
+ this._buildReconnectRetryOptions(clientOptions);
3834
+ return clientOptions;
3835
+ }
3836
+ _buildMessageRetryOptions(clientOptions) {
3837
+ if (!clientOptions.messageRetryOptions) {
3838
+ clientOptions.messageRetryOptions = {};
3839
+ }
3840
+ if (clientOptions.messageRetryOptions.maxRetries == null || clientOptions.messageRetryOptions.maxRetries < 0) {
3841
+ clientOptions.messageRetryOptions.maxRetries = 3;
3842
+ }
3843
+ if (clientOptions.messageRetryOptions.retryDelayInMs == null || clientOptions.messageRetryOptions.retryDelayInMs < 0) {
3844
+ clientOptions.messageRetryOptions.retryDelayInMs = 1e3;
3845
+ }
3846
+ if (clientOptions.messageRetryOptions.maxRetryDelayInMs == null || clientOptions.messageRetryOptions.maxRetryDelayInMs < 0) {
3847
+ clientOptions.messageRetryOptions.maxRetryDelayInMs = 3e4;
3848
+ }
3849
+ if (clientOptions.messageRetryOptions.mode == null) {
3850
+ clientOptions.messageRetryOptions.mode = "Fixed";
3851
+ }
3852
+ }
3853
+ _buildReconnectRetryOptions(clientOptions) {
3854
+ if (!clientOptions.reconnectRetryOptions) {
3855
+ clientOptions.reconnectRetryOptions = {};
3856
+ }
3857
+ if (clientOptions.reconnectRetryOptions.maxRetries == null || clientOptions.reconnectRetryOptions.maxRetries < 0) {
3858
+ clientOptions.reconnectRetryOptions.maxRetries = Number.MAX_VALUE;
3859
+ }
3860
+ if (clientOptions.reconnectRetryOptions.retryDelayInMs == null || clientOptions.reconnectRetryOptions.retryDelayInMs < 0) {
3861
+ clientOptions.reconnectRetryOptions.retryDelayInMs = 1e3;
3862
+ }
3863
+ if (clientOptions.reconnectRetryOptions.maxRetryDelayInMs == null || clientOptions.reconnectRetryOptions.maxRetryDelayInMs < 0) {
3864
+ clientOptions.reconnectRetryOptions.maxRetryDelayInMs = 3e4;
3865
+ }
3866
+ if (clientOptions.reconnectRetryOptions.mode == null) {
3867
+ clientOptions.reconnectRetryOptions.mode = "Fixed";
3868
+ }
3869
+ }
3870
+ _buildRecoveryUri() {
3871
+ if (this._connectionId && this._reconnectionToken && this._uri) {
3872
+ const url = new URL(this._uri);
3873
+ url.searchParams.append("awps_connection_id", this._connectionId);
3874
+ url.searchParams.append("awps_reconnection_token", this._reconnectionToken);
3875
+ return url.toString();
3876
+ }
3877
+ return null;
3878
+ }
3879
+ _getOrAddGroup(name2) {
3880
+ if (!this._groupMap.has(name2)) {
3881
+ this._groupMap.set(name2, new WebPubSubGroup(name2));
3882
+ }
3883
+ return this._groupMap.get(name2);
3884
+ }
3885
+ _changeState(newState) {
3886
+ logger.verbose(`The client state transfer from ${this._state.toString()} to ${newState.toString()}`);
3887
+ this._state = newState;
3888
+ }
3889
+ async _operationExecuteWithRetry(inner, signal) {
3890
+ let retryAttempt = 0;
3891
+ while (true) {
3892
+ try {
3893
+ return await inner.call(this);
3894
+ } catch (err) {
3895
+ if (err instanceof InvocationError) {
3896
+ throw err;
3897
+ }
3898
+ retryAttempt++;
3899
+ const delayInMs = this._messageRetryPolicy.nextRetryDelayInMs(retryAttempt);
3900
+ if (delayInMs == null) {
3901
+ throw err;
3902
+ }
3903
+ await delay(delayInMs);
3904
+ if (signal?.aborted) {
3905
+ throw err;
3906
+ }
3907
+ }
3908
+ }
3909
+ }
3910
+ };
3911
+ var RetryPolicy = class {
3912
+ constructor(retryOptions) {
3913
+ __publicField(this, "_retryOptions");
3914
+ __publicField(this, "_maxRetriesToGetMaxDelay");
3915
+ this._retryOptions = retryOptions;
3916
+ this._maxRetriesToGetMaxDelay = Math.ceil(Math.log2(this._retryOptions.maxRetryDelayInMs) - Math.log2(this._retryOptions.retryDelayInMs) + 1);
3917
+ }
3918
+ nextRetryDelayInMs(retryAttempt) {
3919
+ if (retryAttempt > this._retryOptions.maxRetries) {
3920
+ return null;
3921
+ } else {
3922
+ if (this._retryOptions.mode === "Fixed") {
3923
+ return this._retryOptions.retryDelayInMs;
3924
+ } else {
3925
+ return this._calculateExponentialDelay(retryAttempt);
3926
+ }
3927
+ }
3928
+ }
3929
+ _calculateExponentialDelay(attempt) {
3930
+ if (attempt >= this._maxRetriesToGetMaxDelay) {
3931
+ return this._retryOptions.maxRetryDelayInMs;
3932
+ } else {
3933
+ return (1 << attempt - 1) * this._retryOptions.retryDelayInMs;
3934
+ }
3935
+ }
3936
+ };
3937
+ var WebPubSubGroup = class {
3938
+ constructor(name2) {
3939
+ __publicField(this, "name");
3940
+ __publicField(this, "isJoined", false);
3941
+ this.name = name2;
3942
+ }
3943
+ };
3944
+ var SequenceId = class {
3945
+ constructor() {
3946
+ __publicField(this, "_sequenceId");
3947
+ __publicField(this, "_isUpdate");
3948
+ this._sequenceId = 0;
3949
+ this._isUpdate = false;
3950
+ }
3951
+ tryUpdate(sequenceId) {
3952
+ this._isUpdate = true;
3953
+ if (sequenceId > this._sequenceId) {
3954
+ const diff = sequenceId - this._sequenceId;
3955
+ this._sequenceId = sequenceId;
3956
+ return diff;
3957
+ }
3958
+ return 0;
3959
+ }
3960
+ tryGetSequenceId() {
3961
+ if (this._isUpdate) {
3962
+ this._isUpdate = false;
3963
+ return [true, this._sequenceId];
3964
+ }
3965
+ return [false, null];
3966
+ }
3967
+ reset() {
3968
+ this._sequenceId = 0;
3969
+ this._isUpdate = false;
3970
+ }
3971
+ };
3972
+ var AbortableTask = class {
3973
+ constructor(func, interval, obj) {
3974
+ __publicField(this, "_func");
3975
+ __publicField(this, "_abortController");
3976
+ __publicField(this, "_interval");
3977
+ __publicField(this, "_obj");
3978
+ this._func = func;
3979
+ this._abortController = new AbortController();
3980
+ this._interval = interval;
3981
+ this._obj = obj;
3982
+ this._start();
3983
+ }
3984
+ abort() {
3985
+ try {
3986
+ this._abortController.abort();
3987
+ } catch {
3988
+ }
3989
+ }
3990
+ async _start() {
3991
+ const signal = this._abortController.signal;
3992
+ while (!signal.aborted) {
3993
+ try {
3994
+ await this._func(this._obj);
3995
+ } catch {
3996
+ } finally {
3997
+ await delay(this._interval);
3998
+ }
3999
+ }
4000
+ }
4001
+ };
4002
+
4003
+ // node_modules/tslib/tslib.es6.mjs
4004
+ function __values(o) {
4005
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
4006
+ if (m) return m.call(o);
4007
+ if (o && typeof o.length === "number") return {
4008
+ next: function() {
4009
+ if (o && i >= o.length) o = void 0;
4010
+ return { value: o && o[i++], done: !o };
4011
+ }
4012
+ };
4013
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
4014
+ }
4015
+ function __await(v) {
4016
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
4017
+ }
4018
+ function __asyncGenerator(thisArg, _arguments, generator) {
4019
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
4020
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
4021
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() {
4022
+ return this;
4023
+ }, i;
4024
+ function awaitReturn(f) {
4025
+ return function(v) {
4026
+ return Promise.resolve(v).then(f, reject);
4027
+ };
4028
+ }
4029
+ function verb(n, f) {
4030
+ if (g[n]) {
4031
+ i[n] = function(v) {
4032
+ return new Promise(function(a, b) {
4033
+ q.push([n, v, a, b]) > 1 || resume(n, v);
4034
+ });
4035
+ };
4036
+ if (f) i[n] = f(i[n]);
4037
+ }
4038
+ }
4039
+ function resume(n, v) {
4040
+ try {
4041
+ step(g[n](v));
4042
+ } catch (e) {
4043
+ settle(q[0][3], e);
4044
+ }
4045
+ }
4046
+ function step(r) {
4047
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
4048
+ }
4049
+ function fulfill(value) {
4050
+ resume("next", value);
4051
+ }
4052
+ function reject(value) {
4053
+ resume("throw", value);
4054
+ }
4055
+ function settle(f, v) {
4056
+ if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
4057
+ }
4058
+ }
4059
+ function __asyncDelegator(o) {
4060
+ var i, p;
4061
+ return i = {}, verb("next"), verb("throw", function(e) {
4062
+ throw e;
4063
+ }), verb("return"), i[Symbol.iterator] = function() {
4064
+ return this;
4065
+ }, i;
4066
+ function verb(n, f) {
4067
+ i[n] = o[n] ? function(v) {
4068
+ return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v;
4069
+ } : f;
4070
+ }
4071
+ }
4072
+ function __asyncValues(o) {
4073
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
4074
+ var m = o[Symbol.asyncIterator], i;
4075
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
4076
+ return this;
4077
+ }, i);
4078
+ function verb(n) {
4079
+ i[n] = o[n] && function(v) {
4080
+ return new Promise(function(resolve, reject) {
4081
+ v = o[n](v), settle(resolve, reject, v.done, v.value);
4082
+ });
4083
+ };
4084
+ }
4085
+ function settle(resolve, reject, d, v) {
4086
+ Promise.resolve(v).then(function(v2) {
4087
+ resolve({ value: v2, done: d });
4088
+ }, reject);
4089
+ }
4090
+ }
4091
+
4092
+ // node_modules/@azure/core-paging/dist/browser/getPagedAsyncIterator.js
4093
+ function getPagedAsyncIterator(pagedResult) {
4094
+ var _a;
4095
+ const iter = getItemAsyncIterator(pagedResult);
4096
+ return {
4097
+ next() {
4098
+ return iter.next();
4099
+ },
4100
+ [Symbol.asyncIterator]() {
4101
+ return this;
4102
+ },
4103
+ byPage: (_a = pagedResult === null || pagedResult === void 0 ? void 0 : pagedResult.byPage) !== null && _a !== void 0 ? _a : ((settings) => {
4104
+ const { continuationToken, maxPageSize } = settings !== null && settings !== void 0 ? settings : {};
4105
+ return getPageAsyncIterator(pagedResult, {
4106
+ pageLink: continuationToken,
4107
+ maxPageSize
4108
+ });
4109
+ })
4110
+ };
4111
+ }
4112
+ function getItemAsyncIterator(pagedResult) {
4113
+ return __asyncGenerator(this, arguments, function* getItemAsyncIterator_1() {
4114
+ var _a, e_1, _b, _c, _d, e_2, _e, _f;
4115
+ const pages = getPageAsyncIterator(pagedResult);
4116
+ const firstVal = yield __await(pages.next());
4117
+ if (!Array.isArray(firstVal.value)) {
4118
+ const { toElements } = pagedResult;
4119
+ if (toElements) {
4120
+ yield __await(yield* __asyncDelegator(__asyncValues(toElements(firstVal.value))));
4121
+ try {
4122
+ for (var _g = true, pages_1 = __asyncValues(pages), pages_1_1; pages_1_1 = yield __await(pages_1.next()), _a = pages_1_1.done, !_a; _g = true) {
4123
+ _c = pages_1_1.value;
4124
+ _g = false;
4125
+ const page = _c;
4126
+ yield __await(yield* __asyncDelegator(__asyncValues(toElements(page))));
4127
+ }
4128
+ } catch (e_1_1) {
4129
+ e_1 = { error: e_1_1 };
4130
+ } finally {
4131
+ try {
4132
+ if (!_g && !_a && (_b = pages_1.return)) yield __await(_b.call(pages_1));
4133
+ } finally {
4134
+ if (e_1) throw e_1.error;
4135
+ }
4136
+ }
4137
+ } else {
4138
+ yield yield __await(firstVal.value);
4139
+ yield __await(yield* __asyncDelegator(__asyncValues(pages)));
4140
+ }
4141
+ } else {
4142
+ yield __await(yield* __asyncDelegator(__asyncValues(firstVal.value)));
4143
+ try {
4144
+ for (var _h = true, pages_2 = __asyncValues(pages), pages_2_1; pages_2_1 = yield __await(pages_2.next()), _d = pages_2_1.done, !_d; _h = true) {
4145
+ _f = pages_2_1.value;
4146
+ _h = false;
4147
+ const page = _f;
4148
+ yield __await(yield* __asyncDelegator(__asyncValues(page)));
4149
+ }
4150
+ } catch (e_2_1) {
4151
+ e_2 = { error: e_2_1 };
4152
+ } finally {
4153
+ try {
4154
+ if (!_h && !_d && (_e = pages_2.return)) yield __await(_e.call(pages_2));
4155
+ } finally {
4156
+ if (e_2) throw e_2.error;
4157
+ }
4158
+ }
4159
+ }
4160
+ });
4161
+ }
4162
+ function getPageAsyncIterator(pagedResult, options = {}) {
4163
+ return __asyncGenerator(this, arguments, function* getPageAsyncIterator_1() {
4164
+ const { pageLink, maxPageSize } = options;
4165
+ let response = yield __await(pagedResult.getPage(pageLink !== null && pageLink !== void 0 ? pageLink : pagedResult.firstPageLink, maxPageSize));
4166
+ if (!response) {
4167
+ return yield __await(void 0);
4168
+ }
4169
+ yield yield __await(response.page);
4170
+ while (response.nextPageLink) {
4171
+ response = yield __await(pagedResult.getPage(response.nextPageLink, maxPageSize));
4172
+ if (!response) {
4173
+ return yield __await(void 0);
4174
+ }
4175
+ yield yield __await(response.page);
4176
+ }
4177
+ });
4178
+ }
4179
+
4180
+ // src/constant.ts
4181
+ var INVOCATION_NAME = {
4182
+ LOGIN: "chat.login",
4183
+ LIST_USER_CONVERSATION: "chat.listUserConversation",
4184
+ GET_USER_PROPERTIES: "chat.getUserProperties",
4185
+ GET_ROOM: "chat.getRoom",
4186
+ LIST_MESSAGES: "chat.queryMessageHistory",
4187
+ SEND_TEXT_MESSAGE: "chat.sendTextMessage",
4188
+ CREATE_ROOM: "chat.createRoom",
4189
+ JOIN_ROOM: "chat.joinRoom",
4190
+ MANAGE_ROOM_MEMBER: "chat.manageRoomMember"
4191
+ };
4192
+ var ERRORS = {
4193
+ RoomAlreadyExists: "RoomAlreadyExists",
4194
+ UserAlreadyInRoom: "UserAlreadyInRoom",
4195
+ NoPermissionInRoom: "NoPermissionInRoom",
4196
+ NotStarted: "NotStarted",
4197
+ UnknownRoom: "UnknownRoom",
4198
+ InvalidServerResponse: "InvalidServerResponse"
4199
+ };
4200
+
4201
+ // src/logger.ts
4202
+ var logger2 = createClientLogger("web-pubsub-chat-client:*");
4203
+
4204
+ // src/utils.ts
4205
+ function isWebPubSubClient(obj) {
4206
+ if (typeof obj !== "object" || obj === null) return false;
4207
+ const anyObj = obj;
4208
+ return typeof anyObj === "object" && (typeof anyObj.start === "function" || typeof anyObj.stop === "function" || typeof anyObj.on === "function");
4209
+ }
4210
+
4211
+ // src/chatClient.ts
4212
+ var ChatError = class extends Error {
4213
+ constructor(message, code) {
4214
+ super(message);
4215
+ /** Stable, machine-readable error code. Compare against {@link KnownChatErrorCode}. */
4216
+ __publicField(this, "code");
4217
+ this.name = "ChatError";
4218
+ this.code = code;
4219
+ }
4220
+ };
4221
+ var PromiseCompletionSource = class {
4222
+ constructor() {
4223
+ __publicField(this, "promise");
4224
+ __publicField(this, "resolvePromise");
4225
+ this.promise = new Promise((resolve) => {
4226
+ this.resolvePromise = resolve;
4227
+ });
4228
+ }
4229
+ setResult() {
4230
+ this.resolvePromise();
4231
+ }
4232
+ wait() {
4233
+ return this.promise;
4234
+ }
4235
+ };
4236
+ var ChatClient = class _ChatClient {
4237
+ // Implementation also accepts a pre-built connection (test seam); this is
4238
+ // not a public overload, so it does not appear in the public API surface.
4239
+ constructor(credentialOrConnection) {
4240
+ /** The underlying transport. Private — `ChatClient` builds and owns it. */
4241
+ __publicField(this, "_connection");
4242
+ __publicField(this, "_emitter", new EventEmitter());
4243
+ __publicField(this, "_rooms", /* @__PURE__ */ new Map());
4244
+ __publicField(this, "_conversationIds", /* @__PURE__ */ new Set());
4245
+ __publicField(this, "_userId");
4246
+ __publicField(this, "_isStarted", false);
4247
+ __publicField(this, "_startPromise");
4248
+ // Created after the underlying connection starts so stop() can wait for the single "stopped" event.
4249
+ __publicField(this, "_connectionStoppedTCS");
4250
+ __publicField(this, "_isConnectionStopping", false);
4251
+ this._connection = isWebPubSubClient(credentialOrConnection) ? credentialOrConnection : new WebPubSubClient(credentialOrConnection);
4252
+ this._connection.on("group-message", (e) => {
4253
+ this._handleNotification(e.message.data);
4254
+ });
4255
+ this._connection.on("server-message", (e) => {
4256
+ this._handleNotification(e.message.data);
4257
+ });
4258
+ this._connection.on("stopped", () => {
4259
+ this._connectionStoppedTCS?.setResult();
4260
+ this._connectionStoppedTCS = void 0;
4261
+ this._isConnectionStopping = false;
4262
+ this.resetState();
4263
+ });
4264
+ }
4265
+ async _handleNotification(data) {
4266
+ if (!this._isStarted && !this._startPromise) {
4267
+ return;
4268
+ }
4269
+ logger2.info("Received notification:", data);
4270
+ try {
4271
+ const type = data.notificationType;
4272
+ switch (type) {
4273
+ case "MessageCreated": {
4274
+ const body = data.body;
4275
+ if (!body.conversation.roomId) {
4276
+ logger2.warning(
4277
+ `MessageCreated notification missing roomId; skipping emit. conversationId=${body.conversation.conversationId}`
4278
+ );
4279
+ break;
4280
+ }
4281
+ const event = {
4282
+ roomId: body.conversation.roomId,
4283
+ message: body.message
4284
+ };
4285
+ this._emitter.emit("message", event);
4286
+ break;
4287
+ }
4288
+ case "RoomJoined": {
4289
+ const roomInfo = data.body;
4290
+ this._rooms.set(roomInfo.roomId, roomInfo);
4291
+ const event = { room: roomInfo };
4292
+ this._emitter.emit("room-joined", event);
4293
+ break;
4294
+ }
4295
+ case "RoomMemberJoined": {
4296
+ const body = data.body;
4297
+ const event = { roomId: body.roomId, title: body.title, userId: body.userId };
4298
+ this._emitter.emit("member-joined", event);
4299
+ break;
4300
+ }
4301
+ // someone (not self) left a specific room
4302
+ case "RoomMemberLeft": {
4303
+ const body = data.body;
4304
+ const event = { roomId: body.roomId, title: body.title, userId: body.userId };
4305
+ this._emitter.emit("member-left", event);
4306
+ break;
4307
+ }
4308
+ // self left a specific room
4309
+ case "RoomLeft": {
4310
+ const body = data.body;
4311
+ if (!this._rooms.has(body.roomId)) {
4312
+ break;
4313
+ }
4314
+ const event = { roomId: body.roomId, title: body.title };
4315
+ this._emitter.emit("room-left", event);
4316
+ this._rooms.delete(body.roomId);
4317
+ break;
4318
+ }
4319
+ case "MessageUpdated":
4320
+ case "MessageDeleted":
4321
+ case "RoomClosed":
4322
+ case "AddContact":
4323
+ logger2.warning(`Known notification type ${type} received but not implemented yet.`);
4324
+ break;
4325
+ default:
4326
+ logger2.warning(`Unknown notification type received: ${type}`);
4327
+ }
4328
+ } catch (err) {
4329
+ logger2.error(`Error processing notification, error = ${err}, data: `, data);
4330
+ }
4331
+ }
4332
+ /** Invoke server event and return typed data */
4333
+ async invokeWithReturnType(eventName, payload, dataType, options) {
4334
+ logger2.verbose(`invoke event: '${eventName}', dataType: ${dataType}, payload:`, payload);
4335
+ try {
4336
+ const rawResponse = await this._connection.invokeEvent(eventName, payload, dataType, {
4337
+ abortSignal: options?.abortSignal
4338
+ });
4339
+ logger2.verbose(`invoke response for '${eventName}':`, rawResponse);
4340
+ const data = rawResponse.data;
4341
+ if (data && typeof data === "object" && typeof data.code === "string") {
4342
+ throw new ChatError(`Invocation of event "${eventName}" failed: ${data.code}`, data.code);
4343
+ }
4344
+ return data;
4345
+ } catch (e) {
4346
+ if (e instanceof ChatError) throw e;
4347
+ if (e instanceof InvocationError && e.errorDetail?.name) {
4348
+ throw new ChatError(e.message, e.errorDetail.name);
4349
+ }
4350
+ throw e;
4351
+ }
4352
+ }
4353
+ static async start(clientAccessUrlOrCredential, options) {
4354
+ const credential = typeof clientAccessUrlOrCredential === "string" ? { getClientAccessUrl: async () => clientAccessUrlOrCredential } : clientAccessUrlOrCredential;
4355
+ const chatClient = new _ChatClient(credential);
4356
+ await chatClient.start({ abortSignal: options?.abortSignal });
4357
+ return chatClient;
4358
+ }
4359
+ /**
4360
+ * Connect the underlying transport and authenticate with the chat
4361
+ * service.
4362
+ *
4363
+ * Idempotent: concurrent calls share a single in-flight promise, and
4364
+ * calls made on an already-started client resolve immediately. After
4365
+ * `stop()` the client can be started again; state from the previous
4366
+ * session is reset.
4367
+ *
4368
+ * @param options - Cancellation token for the start operation. Aborting
4369
+ * leaves the client in its initial (not-started) state.
4370
+ */
4371
+ async start(options) {
4372
+ if (this._startPromise) return this._startPromise;
4373
+ if (this._isStarted) return;
4374
+ if (this._connectionStoppedTCS && this._isConnectionStopping) {
4375
+ await this._connectionStoppedTCS.wait();
4376
+ if (this._startPromise) return this._startPromise;
4377
+ if (this._isStarted) return;
4378
+ }
4379
+ const startPromise = this.startCore(options);
4380
+ this._startPromise = startPromise;
4381
+ try {
4382
+ await startPromise;
4383
+ } finally {
4384
+ if (this._startPromise === startPromise) {
4385
+ this._startPromise = void 0;
4386
+ }
4387
+ }
4388
+ }
4389
+ async startCore(options) {
4390
+ this.resetState();
4391
+ try {
4392
+ await this._connection.start({ abortSignal: options?.abortSignal });
4393
+ this._connectionStoppedTCS = new PromiseCompletionSource();
4394
+ this._isConnectionStopping = false;
4395
+ const loginResponse = await this.invokeWithReturnType(
4396
+ INVOCATION_NAME.LOGIN,
4397
+ "",
4398
+ "text",
4399
+ options
4400
+ );
4401
+ logger2.info("loginResponse", loginResponse);
4402
+ const conversationIds = new Set(loginResponse.conversationIds || []);
4403
+ const roomInfos = await Promise.all(
4404
+ (loginResponse.roomIds || []).map(async (roomId) => {
4405
+ const roomInfo = await this.fetchRoomDetail(roomId, {
4406
+ abortSignal: options?.abortSignal,
4407
+ withMembers: false
4408
+ });
4409
+ return { roomId, roomInfo };
4410
+ })
4411
+ );
4412
+ this._userId = loginResponse.userId;
4413
+ this._conversationIds = conversationIds;
4414
+ roomInfos.forEach(({ roomId, roomInfo }) => {
4415
+ this._rooms.set(roomId, roomInfo);
4416
+ });
4417
+ this._isStarted = true;
4418
+ const startedEvent = { userId: loginResponse.userId };
4419
+ this._emitter.emit("started", startedEvent);
4420
+ } catch (err) {
4421
+ this.resetState();
4422
+ await this.stopConnection();
4423
+ throw err;
4424
+ }
4425
+ }
4426
+ ensureStarted() {
4427
+ if (!this._isStarted) {
4428
+ throw new ChatError("Not started. Please call start() first.", ERRORS.NotStarted);
4429
+ }
4430
+ }
4431
+ /**
4432
+ * Fetch a user's profile.
4433
+ *
4434
+ * @param userId - Id of the user to look up.
4435
+ * @param options - Optional `{ abortSignal }`.
4436
+ */
4437
+ async getUserProfile(userId, options) {
4438
+ this.ensureStarted();
4439
+ return this.invokeWithReturnType(
4440
+ INVOCATION_NAME.GET_USER_PROPERTIES,
4441
+ { userId },
4442
+ "json",
4443
+ options
4444
+ );
4445
+ }
4446
+ async sendToConversation(conversationId, message, options) {
4447
+ this.ensureStarted();
4448
+ const payload = {
4449
+ conversation: { conversationId },
4450
+ content: message
4451
+ };
4452
+ const resp = await this.invokeWithReturnType(
4453
+ INVOCATION_NAME.SEND_TEXT_MESSAGE,
4454
+ payload,
4455
+ "json",
4456
+ options
4457
+ );
4458
+ if (!resp || !resp.id) {
4459
+ throw new ChatError(
4460
+ `Failed to send message to conversation ${conversationId}, got invalid invoke response: ${JSON.stringify(resp)}`,
4461
+ ERRORS.InvalidServerResponse
4462
+ );
4463
+ }
4464
+ const msgId = resp.id;
4465
+ const roomId = Array.from(this._rooms.values()).find((r) => r.defaultConversationId === conversationId)?.roomId;
4466
+ if (!roomId) {
4467
+ logger2.warning(
4468
+ `Failed to find roomId for conversationId ${conversationId} when sending message; skipping local sender-echo emit.`
4469
+ );
4470
+ return { messageId: msgId };
4471
+ }
4472
+ const event = {
4473
+ roomId,
4474
+ message: {
4475
+ messageId: msgId,
4476
+ createdBy: this.userId,
4477
+ messageBodyType: "Inline",
4478
+ content: {
4479
+ text: message,
4480
+ binary: null
4481
+ }
4482
+ }
4483
+ };
4484
+ this._emitter.emit("message", event);
4485
+ return { messageId: msgId };
4486
+ }
4487
+ /**
4488
+ * Send a text message to a room and return the service-assigned message id.
4489
+ *
4490
+ * The room must be one this client has created or joined. The sender also
4491
+ * observes the message through the `"message"` event.
4492
+ *
4493
+ * @param roomId - Target room.
4494
+ * @param message - Message text to send.
4495
+ * @param options - Optional `{ abortSignal }`.
4496
+ * @returns A {@link SendMessageResult} with the service-assigned `messageId`.
4497
+ */
4498
+ async sendToRoom(roomId, message, options) {
4499
+ this.ensureStarted();
4500
+ const conversationId = this._rooms.get(roomId)?.defaultConversationId;
4501
+ if (!conversationId) {
4502
+ throw new ChatError(`Failed to sendToRoom, not found roomId ${roomId}`, ERRORS.UnknownRoom);
4503
+ }
4504
+ return await this.sendToConversation(conversationId, message, options);
4505
+ }
4506
+ // Internal: fetch a room's full wire shape (including its conversation id)
4507
+ // to populate the local cache. Public callers go through getRoomDetail().
4508
+ async fetchRoomDetail(roomId, options) {
4509
+ return this.invokeWithReturnType(
4510
+ INVOCATION_NAME.GET_ROOM,
4511
+ { id: roomId, withMembers: options?.withMembers ?? false },
4512
+ "json",
4513
+ options
4514
+ );
4515
+ }
4516
+ /**
4517
+ * Fetch the detailed view of a room.
4518
+ *
4519
+ * @param roomId - Room to query.
4520
+ * @param options - Optional `{ withMembers, abortSignal }`. Pass
4521
+ * `withMembers: true` to populate the returned `members` list; it is
4522
+ * left undefined otherwise.
4523
+ */
4524
+ async getRoomDetail(roomId, options) {
4525
+ this.ensureStarted();
4526
+ return this.fetchRoomDetail(roomId, options);
4527
+ }
4528
+ /**
4529
+ * Create a room and its initial members. The current user is always
4530
+ * included in the resulting member list.
4531
+ *
4532
+ * @param title - Display title for the room.
4533
+ * @param members - Other user ids to invite. The caller is added
4534
+ * automatically; duplicates are de-duplicated.
4535
+ * @param options - Optional `{ roomId, abortSignal }`. Pass `roomId`
4536
+ * to choose an id explicitly; omit to let the service assign one.
4537
+ */
4538
+ async createRoom(title, members, options) {
4539
+ this.ensureStarted();
4540
+ let roomDetails = {
4541
+ title,
4542
+ members: [.../* @__PURE__ */ new Set([...members, this.userId])]
4543
+ // deduplicate and add self
4544
+ };
4545
+ if (options?.roomId) {
4546
+ roomDetails = { ...roomDetails, roomId: options.roomId };
4547
+ }
4548
+ const roomInfo = await this.invokeWithReturnType(
4549
+ INVOCATION_NAME.CREATE_ROOM,
4550
+ roomDetails,
4551
+ "json",
4552
+ options
4553
+ );
4554
+ this._rooms.set(roomInfo.roomId, roomInfo);
4555
+ const event = { room: roomInfo };
4556
+ this._emitter.emit("room-joined", event);
4557
+ return roomInfo;
4558
+ }
4559
+ async manageRoomMember(request, options) {
4560
+ await this.invokeWithReturnType(INVOCATION_NAME.MANAGE_ROOM_MEMBER, request, "json", options);
4561
+ }
4562
+ async ensureRoomCached(roomId, options) {
4563
+ if (this._rooms.has(roomId)) {
4564
+ return;
4565
+ }
4566
+ const roomInfo = await this.fetchRoomDetail(roomId, options);
4567
+ this._rooms.set(roomId, roomInfo);
4568
+ }
4569
+ /** Add a user to a room. This is an admin operation where one user adds another user to a room. */
4570
+ async addUserToRoom(roomId, userId, options) {
4571
+ this.ensureStarted();
4572
+ const payload = { roomId, operation: "Add", userId };
4573
+ const isSelf = userId === this.userId;
4574
+ const shouldCacheRoomAfterSelfAdd = isSelf && !this._rooms.has(roomId);
4575
+ try {
4576
+ await this.manageRoomMember(payload, options);
4577
+ } catch (error) {
4578
+ if (!isSelf || !(error instanceof ChatError && error.code === ERRORS.UserAlreadyInRoom)) {
4579
+ throw error;
4580
+ }
4581
+ }
4582
+ if (shouldCacheRoomAfterSelfAdd) {
4583
+ await this.ensureRoomCached(roomId, options);
4584
+ }
4585
+ }
4586
+ /** Remove a user from a room. This is an admin operation where one user removes another user from a room. */
4587
+ async removeUserFromRoom(roomId, userId, options) {
4588
+ this.ensureStarted();
4589
+ const payload = { roomId, operation: "Delete", userId };
4590
+ await this.manageRoomMember(payload, options);
4591
+ if (userId === this.userId) {
4592
+ const roomInfo = this._rooms.get(roomId);
4593
+ if (roomInfo) {
4594
+ this._rooms.delete(roomId);
4595
+ const event = { roomId, title: roomInfo.title };
4596
+ this._emitter.emit("room-left", event);
4597
+ }
4598
+ }
4599
+ }
4600
+ /**
4601
+ * List messages in a room as a paged async iterator.
4602
+ *
4603
+ * The iterator transparently fetches additional pages from the
4604
+ * service as you iterate. For Teams-style infinite scrolling, drive
4605
+ * the iterator one page at a time via `byPage(...)`:
4606
+ *
4607
+ * @example Stream every message (e.g. for export or full sync):
4608
+ * ```ts
4609
+ * for await (const msg of client.listRoomMessages(roomId)) {
4610
+ * console.log(msg.content.text);
4611
+ * }
4612
+ * ```
4613
+ *
4614
+ * @example Load history one page at a time (Teams-style scroll-back):
4615
+ * ```ts
4616
+ * // Load up to 50 messages per page.
4617
+ * const pages = client.listRoomMessages(roomId).byPage({ maxPageSize: 50 });
4618
+ * const first = await pages.next();
4619
+ * displayMessages(first.value);
4620
+ * // later, when the user scrolls up:
4621
+ * const more = await pages.next();
4622
+ * displayMessages(more.value);
4623
+ * ```
4624
+ *
4625
+ * The room must be one this client has created or joined.
4626
+ */
4627
+ listRoomMessages(roomId, options) {
4628
+ this.ensureStarted();
4629
+ const conversationId = this._rooms.get(roomId)?.defaultConversationId;
4630
+ if (!conversationId) {
4631
+ throw new ChatError(`Failed to listRoomMessages, not found roomId ${roomId}`, ERRORS.UnknownRoom);
4632
+ }
4633
+ const defaultPageSize = options?.maxPageSize ?? 100;
4634
+ const firstPageLink = {
4635
+ conversation: { conversationId },
4636
+ start: options?.startId ?? null,
4637
+ end: options?.endId ?? null,
4638
+ maxCount: defaultPageSize
4639
+ };
4640
+ const fetchPage = async (link, maxPageSize) => {
4641
+ const query = {
4642
+ ...link,
4643
+ maxCount: maxPageSize ?? link.maxCount ?? defaultPageSize
4644
+ };
4645
+ const result = await this.invokeWithReturnType(
4646
+ INVOCATION_NAME.LIST_MESSAGES,
4647
+ query,
4648
+ "json",
4649
+ { abortSignal: options?.abortSignal }
4650
+ );
4651
+ if (result.messages.length === 0) {
4652
+ return void 0;
4653
+ }
4654
+ return { page: result.messages, nextPageLink: result.nextQuery ?? void 0 };
4655
+ };
4656
+ return getPagedAsyncIterator({
4657
+ firstPageLink,
4658
+ getPage: (link, maxPageSize) => fetchPage(link, maxPageSize)
4659
+ });
4660
+ }
4661
+ /** Cached rooms known to the client. */
4662
+ get rooms() {
4663
+ return Array.from(this._rooms.values());
4664
+ }
4665
+ /** Whether the current client has the room in its local joined-room cache. */
4666
+ hasJoinedRoom(roomId) {
4667
+ return this._rooms.has(roomId);
4668
+ }
4669
+ /**
4670
+ * The chat-domain identity of this client, established by `start()`.
4671
+ *
4672
+ * @throws `ChatError` with code `NotStarted` if the client is not started.
4673
+ */
4674
+ get userId() {
4675
+ if (!this._userId) {
4676
+ throw new ChatError("User ID is not set. Please call start() first.", ERRORS.NotStarted);
4677
+ }
4678
+ return this._userId;
4679
+ }
4680
+ on(event, listener) {
4681
+ this._emitter.on(event, listener);
4682
+ }
4683
+ off(event, listener) {
4684
+ this._emitter.off(event, listener);
4685
+ }
4686
+ /**
4687
+ * Stop the underlying connection and reset client state. Idempotent.
4688
+ *
4689
+ * After resolution the client returns to its initial state and may
4690
+ * be started again via `start()`. Callers that want the same identity
4691
+ * should keep their authentication source (URL or credential)
4692
+ * constant.
4693
+ *
4694
+ * Stopping is not cancellable: it tears down the transport and clears
4695
+ * local state, mirroring the underlying `WebPubSubClient.stop()`, which
4696
+ * takes no options.
4697
+ */
4698
+ async stop() {
4699
+ const startPromise = this._startPromise;
4700
+ if (startPromise) {
4701
+ await startPromise.catch(() => void 0);
4702
+ }
4703
+ this._startPromise = void 0;
4704
+ this.resetState();
4705
+ await this.stopConnection();
4706
+ }
4707
+ /**
4708
+ * Reset chat-domain state. Emits `"stopped"` exactly once per
4709
+ * started → not-started transition: if `_isStarted` was already
4710
+ * false on entry (e.g. the pre-start guard inside `startCore()` or
4711
+ * the post-failure rollback), no event fires.
4712
+ */
4713
+ resetState() {
4714
+ const wasStarted = this._isStarted;
4715
+ this._isStarted = false;
4716
+ this._userId = void 0;
4717
+ this._rooms.clear();
4718
+ this._conversationIds.clear();
4719
+ if (wasStarted) {
4720
+ const stoppedEvent = {};
4721
+ this._emitter.emit("stopped", stoppedEvent);
4722
+ }
4723
+ }
4724
+ async stopConnection() {
4725
+ const connectionStoppedTCS = this._connectionStoppedTCS;
4726
+ if (!connectionStoppedTCS) {
4727
+ return;
4728
+ }
4729
+ if (!this._isConnectionStopping) {
4730
+ this._isConnectionStopping = true;
4731
+ try {
4732
+ this._connection.stop();
4733
+ } catch (err) {
4734
+ this._isConnectionStopping = false;
4735
+ throw err;
4736
+ }
4737
+ }
4738
+ await connectionStoppedTCS.wait();
4739
+ }
4740
+ };
4741
+
4742
+ // src/index.ts
4743
+ var KnownChatErrorCode = ERRORS;
4744
+ export {
4745
+ ChatClient,
4746
+ ChatError,
4747
+ KnownChatErrorCode
4748
+ };
4749
+ /*! Bundled license information:
4750
+
4751
+ @jspm/core/nodelibs/browser/chunk-DtuTasat.js:
4752
+ (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
4753
+ */
4754
+ //# sourceMappingURL=index.js.map