swiftbase-sdk 1.0.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,4778 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __typeError = (msg) => {
13
+ throw TypeError(msg);
14
+ };
15
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
16
+ var __spreadValues = (a, b) => {
17
+ for (var prop in b || (b = {}))
18
+ if (__hasOwnProp.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ if (__getOwnPropSymbols)
21
+ for (var prop of __getOwnPropSymbols(b)) {
22
+ if (__propIsEnum.call(b, prop))
23
+ __defNormalProp(a, prop, b[prop]);
24
+ }
25
+ return a;
26
+ };
27
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
28
+ var __esm = (fn, res) => function __init() {
29
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
30
+ };
31
+ var __commonJS = (cb, mod) => function __require() {
32
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
33
+ };
34
+ var __export = (target, all) => {
35
+ for (var name in all)
36
+ __defProp(target, name, { get: all[name], enumerable: true });
37
+ };
38
+ var __copyProps = (to, from, except, desc) => {
39
+ if (from && typeof from === "object" || typeof from === "function") {
40
+ for (let key of __getOwnPropNames(from))
41
+ if (!__hasOwnProp.call(to, key) && key !== except)
42
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
43
+ }
44
+ return to;
45
+ };
46
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
47
+ // If the importer is in node compatibility mode or this is not an ESM
48
+ // file that has been converted to a CommonJS file using a Babel-
49
+ // compatible transform (i.e. "__esModule" has not been set), then set
50
+ // "default" to the CommonJS "module.exports" for node compatibility.
51
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
52
+ mod
53
+ ));
54
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
55
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
56
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
57
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
58
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
59
+ var __async = (__this, __arguments, generator) => {
60
+ return new Promise((resolve, reject) => {
61
+ var fulfilled = (value) => {
62
+ try {
63
+ step(generator.next(value));
64
+ } catch (e) {
65
+ reject(e);
66
+ }
67
+ };
68
+ var rejected = (value) => {
69
+ try {
70
+ step(generator.throw(value));
71
+ } catch (e) {
72
+ reject(e);
73
+ }
74
+ };
75
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
76
+ step((generator = generator.apply(__this, __arguments)).next());
77
+ });
78
+ };
79
+
80
+ // node_modules/ws/lib/stream.js
81
+ var require_stream = __commonJS({
82
+ "node_modules/ws/lib/stream.js"(exports2, module2) {
83
+ "use strict";
84
+ var { Duplex } = require("stream");
85
+ function emitClose(stream) {
86
+ stream.emit("close");
87
+ }
88
+ function duplexOnEnd() {
89
+ if (!this.destroyed && this._writableState.finished) {
90
+ this.destroy();
91
+ }
92
+ }
93
+ function duplexOnError(err) {
94
+ this.removeListener("error", duplexOnError);
95
+ this.destroy();
96
+ if (this.listenerCount("error") === 0) {
97
+ this.emit("error", err);
98
+ }
99
+ }
100
+ function createWebSocketStream2(ws, options) {
101
+ let terminateOnDestroy = true;
102
+ const duplex = new Duplex(__spreadProps(__spreadValues({}, options), {
103
+ autoDestroy: false,
104
+ emitClose: false,
105
+ objectMode: false,
106
+ writableObjectMode: false
107
+ }));
108
+ ws.on("message", function message(msg, isBinary) {
109
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
110
+ if (!duplex.push(data)) ws.pause();
111
+ });
112
+ ws.once("error", function error(err) {
113
+ if (duplex.destroyed) return;
114
+ terminateOnDestroy = false;
115
+ duplex.destroy(err);
116
+ });
117
+ ws.once("close", function close() {
118
+ if (duplex.destroyed) return;
119
+ duplex.push(null);
120
+ });
121
+ duplex._destroy = function(err, callback) {
122
+ if (ws.readyState === ws.CLOSED) {
123
+ callback(err);
124
+ process.nextTick(emitClose, duplex);
125
+ return;
126
+ }
127
+ let called = false;
128
+ ws.once("error", function error(err2) {
129
+ called = true;
130
+ callback(err2);
131
+ });
132
+ ws.once("close", function close() {
133
+ if (!called) callback(err);
134
+ process.nextTick(emitClose, duplex);
135
+ });
136
+ if (terminateOnDestroy) ws.terminate();
137
+ };
138
+ duplex._final = function(callback) {
139
+ if (ws.readyState === ws.CONNECTING) {
140
+ ws.once("open", function open() {
141
+ duplex._final(callback);
142
+ });
143
+ return;
144
+ }
145
+ if (ws._socket === null) return;
146
+ if (ws._socket._writableState.finished) {
147
+ callback();
148
+ if (duplex._readableState.endEmitted) duplex.destroy();
149
+ } else {
150
+ ws._socket.once("finish", function finish() {
151
+ callback();
152
+ });
153
+ ws.close();
154
+ }
155
+ };
156
+ duplex._read = function() {
157
+ if (ws.isPaused) ws.resume();
158
+ };
159
+ duplex._write = function(chunk, encoding, callback) {
160
+ if (ws.readyState === ws.CONNECTING) {
161
+ ws.once("open", function open() {
162
+ duplex._write(chunk, encoding, callback);
163
+ });
164
+ return;
165
+ }
166
+ ws.send(chunk, callback);
167
+ };
168
+ duplex.on("end", duplexOnEnd);
169
+ duplex.on("error", duplexOnError);
170
+ return duplex;
171
+ }
172
+ module2.exports = createWebSocketStream2;
173
+ }
174
+ });
175
+
176
+ // node_modules/ws/lib/constants.js
177
+ var require_constants = __commonJS({
178
+ "node_modules/ws/lib/constants.js"(exports2, module2) {
179
+ "use strict";
180
+ module2.exports = {
181
+ BINARY_TYPES: ["nodebuffer", "arraybuffer", "fragments"],
182
+ EMPTY_BUFFER: Buffer.alloc(0),
183
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
184
+ kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
185
+ kListener: /* @__PURE__ */ Symbol("kListener"),
186
+ kStatusCode: /* @__PURE__ */ Symbol("status-code"),
187
+ kWebSocket: /* @__PURE__ */ Symbol("websocket"),
188
+ NOOP: () => {
189
+ }
190
+ };
191
+ }
192
+ });
193
+
194
+ // node_modules/ws/lib/buffer-util.js
195
+ var require_buffer_util = __commonJS({
196
+ "node_modules/ws/lib/buffer-util.js"(exports2, module2) {
197
+ "use strict";
198
+ var { EMPTY_BUFFER } = require_constants();
199
+ var FastBuffer = Buffer[Symbol.species];
200
+ function concat(list, totalLength) {
201
+ if (list.length === 0) return EMPTY_BUFFER;
202
+ if (list.length === 1) return list[0];
203
+ const target = Buffer.allocUnsafe(totalLength);
204
+ let offset = 0;
205
+ for (let i = 0; i < list.length; i++) {
206
+ const buf = list[i];
207
+ target.set(buf, offset);
208
+ offset += buf.length;
209
+ }
210
+ if (offset < totalLength) {
211
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
212
+ }
213
+ return target;
214
+ }
215
+ function _mask(source, mask, output, offset, length) {
216
+ for (let i = 0; i < length; i++) {
217
+ output[offset + i] = source[i] ^ mask[i & 3];
218
+ }
219
+ }
220
+ function _unmask(buffer, mask) {
221
+ for (let i = 0; i < buffer.length; i++) {
222
+ buffer[i] ^= mask[i & 3];
223
+ }
224
+ }
225
+ function toArrayBuffer(buf) {
226
+ if (buf.length === buf.buffer.byteLength) {
227
+ return buf.buffer;
228
+ }
229
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
230
+ }
231
+ function toBuffer(data) {
232
+ toBuffer.readOnly = true;
233
+ if (Buffer.isBuffer(data)) return data;
234
+ let buf;
235
+ if (data instanceof ArrayBuffer) {
236
+ buf = new FastBuffer(data);
237
+ } else if (ArrayBuffer.isView(data)) {
238
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
239
+ } else {
240
+ buf = Buffer.from(data);
241
+ toBuffer.readOnly = false;
242
+ }
243
+ return buf;
244
+ }
245
+ module2.exports = {
246
+ concat,
247
+ mask: _mask,
248
+ toArrayBuffer,
249
+ toBuffer,
250
+ unmask: _unmask
251
+ };
252
+ if (!process.env.WS_NO_BUFFER_UTIL) {
253
+ try {
254
+ const bufferUtil = require("bufferutil");
255
+ module2.exports.mask = function(source, mask, output, offset, length) {
256
+ if (length < 48) _mask(source, mask, output, offset, length);
257
+ else bufferUtil.mask(source, mask, output, offset, length);
258
+ };
259
+ module2.exports.unmask = function(buffer, mask) {
260
+ if (buffer.length < 32) _unmask(buffer, mask);
261
+ else bufferUtil.unmask(buffer, mask);
262
+ };
263
+ } catch (e) {
264
+ }
265
+ }
266
+ }
267
+ });
268
+
269
+ // node_modules/ws/lib/limiter.js
270
+ var require_limiter = __commonJS({
271
+ "node_modules/ws/lib/limiter.js"(exports2, module2) {
272
+ "use strict";
273
+ var kDone = /* @__PURE__ */ Symbol("kDone");
274
+ var kRun = /* @__PURE__ */ Symbol("kRun");
275
+ var Limiter = class {
276
+ /**
277
+ * Creates a new `Limiter`.
278
+ *
279
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
280
+ * to run concurrently
281
+ */
282
+ constructor(concurrency) {
283
+ this[kDone] = () => {
284
+ this.pending--;
285
+ this[kRun]();
286
+ };
287
+ this.concurrency = concurrency || Infinity;
288
+ this.jobs = [];
289
+ this.pending = 0;
290
+ }
291
+ /**
292
+ * Adds a job to the queue.
293
+ *
294
+ * @param {Function} job The job to run
295
+ * @public
296
+ */
297
+ add(job) {
298
+ this.jobs.push(job);
299
+ this[kRun]();
300
+ }
301
+ /**
302
+ * Removes a job from the queue and runs it if possible.
303
+ *
304
+ * @private
305
+ */
306
+ [kRun]() {
307
+ if (this.pending === this.concurrency) return;
308
+ if (this.jobs.length) {
309
+ const job = this.jobs.shift();
310
+ this.pending++;
311
+ job(this[kDone]);
312
+ }
313
+ }
314
+ };
315
+ module2.exports = Limiter;
316
+ }
317
+ });
318
+
319
+ // node_modules/ws/lib/permessage-deflate.js
320
+ var require_permessage_deflate = __commonJS({
321
+ "node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
322
+ "use strict";
323
+ var zlib = require("zlib");
324
+ var bufferUtil = require_buffer_util();
325
+ var Limiter = require_limiter();
326
+ var { kStatusCode } = require_constants();
327
+ var FastBuffer = Buffer[Symbol.species];
328
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
329
+ var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
330
+ var kTotalLength = /* @__PURE__ */ Symbol("total-length");
331
+ var kCallback = /* @__PURE__ */ Symbol("callback");
332
+ var kBuffers = /* @__PURE__ */ Symbol("buffers");
333
+ var kError = /* @__PURE__ */ Symbol("error");
334
+ var zlibLimiter;
335
+ var PerMessageDeflate = class {
336
+ /**
337
+ * Creates a PerMessageDeflate instance.
338
+ *
339
+ * @param {Object} [options] Configuration options
340
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
341
+ * for, or request, a custom client window size
342
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
343
+ * acknowledge disabling of client context takeover
344
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
345
+ * calls to zlib
346
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
347
+ * use of a custom server window size
348
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
349
+ * disabling of server context takeover
350
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
351
+ * messages should not be compressed if context takeover is disabled
352
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
353
+ * deflate
354
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
355
+ * inflate
356
+ * @param {Boolean} [isServer=false] Create the instance in either server or
357
+ * client mode
358
+ * @param {Number} [maxPayload=0] The maximum allowed message length
359
+ */
360
+ constructor(options, isServer, maxPayload) {
361
+ this._maxPayload = maxPayload | 0;
362
+ this._options = options || {};
363
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
364
+ this._isServer = !!isServer;
365
+ this._deflate = null;
366
+ this._inflate = null;
367
+ this.params = null;
368
+ if (!zlibLimiter) {
369
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
370
+ zlibLimiter = new Limiter(concurrency);
371
+ }
372
+ }
373
+ /**
374
+ * @type {String}
375
+ */
376
+ static get extensionName() {
377
+ return "permessage-deflate";
378
+ }
379
+ /**
380
+ * Create an extension negotiation offer.
381
+ *
382
+ * @return {Object} Extension parameters
383
+ * @public
384
+ */
385
+ offer() {
386
+ const params = {};
387
+ if (this._options.serverNoContextTakeover) {
388
+ params.server_no_context_takeover = true;
389
+ }
390
+ if (this._options.clientNoContextTakeover) {
391
+ params.client_no_context_takeover = true;
392
+ }
393
+ if (this._options.serverMaxWindowBits) {
394
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
395
+ }
396
+ if (this._options.clientMaxWindowBits) {
397
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
398
+ } else if (this._options.clientMaxWindowBits == null) {
399
+ params.client_max_window_bits = true;
400
+ }
401
+ return params;
402
+ }
403
+ /**
404
+ * Accept an extension negotiation offer/response.
405
+ *
406
+ * @param {Array} configurations The extension negotiation offers/reponse
407
+ * @return {Object} Accepted configuration
408
+ * @public
409
+ */
410
+ accept(configurations) {
411
+ configurations = this.normalizeParams(configurations);
412
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
413
+ return this.params;
414
+ }
415
+ /**
416
+ * Releases all resources used by the extension.
417
+ *
418
+ * @public
419
+ */
420
+ cleanup() {
421
+ if (this._inflate) {
422
+ this._inflate.close();
423
+ this._inflate = null;
424
+ }
425
+ if (this._deflate) {
426
+ const callback = this._deflate[kCallback];
427
+ this._deflate.close();
428
+ this._deflate = null;
429
+ if (callback) {
430
+ callback(
431
+ new Error(
432
+ "The deflate stream was closed while data was being processed"
433
+ )
434
+ );
435
+ }
436
+ }
437
+ }
438
+ /**
439
+ * Accept an extension negotiation offer.
440
+ *
441
+ * @param {Array} offers The extension negotiation offers
442
+ * @return {Object} Accepted configuration
443
+ * @private
444
+ */
445
+ acceptAsServer(offers) {
446
+ const opts = this._options;
447
+ const accepted = offers.find((params) => {
448
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
449
+ return false;
450
+ }
451
+ return true;
452
+ });
453
+ if (!accepted) {
454
+ throw new Error("None of the extension offers can be accepted");
455
+ }
456
+ if (opts.serverNoContextTakeover) {
457
+ accepted.server_no_context_takeover = true;
458
+ }
459
+ if (opts.clientNoContextTakeover) {
460
+ accepted.client_no_context_takeover = true;
461
+ }
462
+ if (typeof opts.serverMaxWindowBits === "number") {
463
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
464
+ }
465
+ if (typeof opts.clientMaxWindowBits === "number") {
466
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
467
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
468
+ delete accepted.client_max_window_bits;
469
+ }
470
+ return accepted;
471
+ }
472
+ /**
473
+ * Accept the extension negotiation response.
474
+ *
475
+ * @param {Array} response The extension negotiation response
476
+ * @return {Object} Accepted configuration
477
+ * @private
478
+ */
479
+ acceptAsClient(response) {
480
+ const params = response[0];
481
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
482
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
483
+ }
484
+ if (!params.client_max_window_bits) {
485
+ if (typeof this._options.clientMaxWindowBits === "number") {
486
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
487
+ }
488
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
489
+ throw new Error(
490
+ 'Unexpected or invalid parameter "client_max_window_bits"'
491
+ );
492
+ }
493
+ return params;
494
+ }
495
+ /**
496
+ * Normalize parameters.
497
+ *
498
+ * @param {Array} configurations The extension negotiation offers/reponse
499
+ * @return {Array} The offers/response with normalized parameters
500
+ * @private
501
+ */
502
+ normalizeParams(configurations) {
503
+ configurations.forEach((params) => {
504
+ Object.keys(params).forEach((key) => {
505
+ let value = params[key];
506
+ if (value.length > 1) {
507
+ throw new Error(`Parameter "${key}" must have only a single value`);
508
+ }
509
+ value = value[0];
510
+ if (key === "client_max_window_bits") {
511
+ if (value !== true) {
512
+ const num = +value;
513
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
514
+ throw new TypeError(
515
+ `Invalid value for parameter "${key}": ${value}`
516
+ );
517
+ }
518
+ value = num;
519
+ } else if (!this._isServer) {
520
+ throw new TypeError(
521
+ `Invalid value for parameter "${key}": ${value}`
522
+ );
523
+ }
524
+ } else if (key === "server_max_window_bits") {
525
+ const num = +value;
526
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
527
+ throw new TypeError(
528
+ `Invalid value for parameter "${key}": ${value}`
529
+ );
530
+ }
531
+ value = num;
532
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
533
+ if (value !== true) {
534
+ throw new TypeError(
535
+ `Invalid value for parameter "${key}": ${value}`
536
+ );
537
+ }
538
+ } else {
539
+ throw new Error(`Unknown parameter "${key}"`);
540
+ }
541
+ params[key] = value;
542
+ });
543
+ });
544
+ return configurations;
545
+ }
546
+ /**
547
+ * Decompress data. Concurrency limited.
548
+ *
549
+ * @param {Buffer} data Compressed data
550
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
551
+ * @param {Function} callback Callback
552
+ * @public
553
+ */
554
+ decompress(data, fin, callback) {
555
+ zlibLimiter.add((done) => {
556
+ this._decompress(data, fin, (err, result) => {
557
+ done();
558
+ callback(err, result);
559
+ });
560
+ });
561
+ }
562
+ /**
563
+ * Compress data. Concurrency limited.
564
+ *
565
+ * @param {(Buffer|String)} data Data to compress
566
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
567
+ * @param {Function} callback Callback
568
+ * @public
569
+ */
570
+ compress(data, fin, callback) {
571
+ zlibLimiter.add((done) => {
572
+ this._compress(data, fin, (err, result) => {
573
+ done();
574
+ callback(err, result);
575
+ });
576
+ });
577
+ }
578
+ /**
579
+ * Decompress data.
580
+ *
581
+ * @param {Buffer} data Compressed data
582
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
583
+ * @param {Function} callback Callback
584
+ * @private
585
+ */
586
+ _decompress(data, fin, callback) {
587
+ const endpoint = this._isServer ? "client" : "server";
588
+ if (!this._inflate) {
589
+ const key = `${endpoint}_max_window_bits`;
590
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
591
+ this._inflate = zlib.createInflateRaw(__spreadProps(__spreadValues({}, this._options.zlibInflateOptions), {
592
+ windowBits
593
+ }));
594
+ this._inflate[kPerMessageDeflate] = this;
595
+ this._inflate[kTotalLength] = 0;
596
+ this._inflate[kBuffers] = [];
597
+ this._inflate.on("error", inflateOnError);
598
+ this._inflate.on("data", inflateOnData);
599
+ }
600
+ this._inflate[kCallback] = callback;
601
+ this._inflate.write(data);
602
+ if (fin) this._inflate.write(TRAILER);
603
+ this._inflate.flush(() => {
604
+ const err = this._inflate[kError];
605
+ if (err) {
606
+ this._inflate.close();
607
+ this._inflate = null;
608
+ callback(err);
609
+ return;
610
+ }
611
+ const data2 = bufferUtil.concat(
612
+ this._inflate[kBuffers],
613
+ this._inflate[kTotalLength]
614
+ );
615
+ if (this._inflate._readableState.endEmitted) {
616
+ this._inflate.close();
617
+ this._inflate = null;
618
+ } else {
619
+ this._inflate[kTotalLength] = 0;
620
+ this._inflate[kBuffers] = [];
621
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
622
+ this._inflate.reset();
623
+ }
624
+ }
625
+ callback(null, data2);
626
+ });
627
+ }
628
+ /**
629
+ * Compress data.
630
+ *
631
+ * @param {(Buffer|String)} data Data to compress
632
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
633
+ * @param {Function} callback Callback
634
+ * @private
635
+ */
636
+ _compress(data, fin, callback) {
637
+ const endpoint = this._isServer ? "server" : "client";
638
+ if (!this._deflate) {
639
+ const key = `${endpoint}_max_window_bits`;
640
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
641
+ this._deflate = zlib.createDeflateRaw(__spreadProps(__spreadValues({}, this._options.zlibDeflateOptions), {
642
+ windowBits
643
+ }));
644
+ this._deflate[kTotalLength] = 0;
645
+ this._deflate[kBuffers] = [];
646
+ this._deflate.on("data", deflateOnData);
647
+ }
648
+ this._deflate[kCallback] = callback;
649
+ this._deflate.write(data);
650
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
651
+ if (!this._deflate) {
652
+ return;
653
+ }
654
+ let data2 = bufferUtil.concat(
655
+ this._deflate[kBuffers],
656
+ this._deflate[kTotalLength]
657
+ );
658
+ if (fin) {
659
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
660
+ }
661
+ this._deflate[kCallback] = null;
662
+ this._deflate[kTotalLength] = 0;
663
+ this._deflate[kBuffers] = [];
664
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
665
+ this._deflate.reset();
666
+ }
667
+ callback(null, data2);
668
+ });
669
+ }
670
+ };
671
+ module2.exports = PerMessageDeflate;
672
+ function deflateOnData(chunk) {
673
+ this[kBuffers].push(chunk);
674
+ this[kTotalLength] += chunk.length;
675
+ }
676
+ function inflateOnData(chunk) {
677
+ this[kTotalLength] += chunk.length;
678
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
679
+ this[kBuffers].push(chunk);
680
+ return;
681
+ }
682
+ this[kError] = new RangeError("Max payload size exceeded");
683
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
684
+ this[kError][kStatusCode] = 1009;
685
+ this.removeListener("data", inflateOnData);
686
+ this.reset();
687
+ }
688
+ function inflateOnError(err) {
689
+ this[kPerMessageDeflate]._inflate = null;
690
+ err[kStatusCode] = 1007;
691
+ this[kCallback](err);
692
+ }
693
+ }
694
+ });
695
+
696
+ // node_modules/ws/lib/validation.js
697
+ var require_validation = __commonJS({
698
+ "node_modules/ws/lib/validation.js"(exports2, module2) {
699
+ "use strict";
700
+ var { isUtf8 } = require("buffer");
701
+ var tokenChars = [
702
+ 0,
703
+ 0,
704
+ 0,
705
+ 0,
706
+ 0,
707
+ 0,
708
+ 0,
709
+ 0,
710
+ 0,
711
+ 0,
712
+ 0,
713
+ 0,
714
+ 0,
715
+ 0,
716
+ 0,
717
+ 0,
718
+ // 0 - 15
719
+ 0,
720
+ 0,
721
+ 0,
722
+ 0,
723
+ 0,
724
+ 0,
725
+ 0,
726
+ 0,
727
+ 0,
728
+ 0,
729
+ 0,
730
+ 0,
731
+ 0,
732
+ 0,
733
+ 0,
734
+ 0,
735
+ // 16 - 31
736
+ 0,
737
+ 1,
738
+ 0,
739
+ 1,
740
+ 1,
741
+ 1,
742
+ 1,
743
+ 1,
744
+ 0,
745
+ 0,
746
+ 1,
747
+ 1,
748
+ 0,
749
+ 1,
750
+ 1,
751
+ 0,
752
+ // 32 - 47
753
+ 1,
754
+ 1,
755
+ 1,
756
+ 1,
757
+ 1,
758
+ 1,
759
+ 1,
760
+ 1,
761
+ 1,
762
+ 1,
763
+ 0,
764
+ 0,
765
+ 0,
766
+ 0,
767
+ 0,
768
+ 0,
769
+ // 48 - 63
770
+ 0,
771
+ 1,
772
+ 1,
773
+ 1,
774
+ 1,
775
+ 1,
776
+ 1,
777
+ 1,
778
+ 1,
779
+ 1,
780
+ 1,
781
+ 1,
782
+ 1,
783
+ 1,
784
+ 1,
785
+ 1,
786
+ // 64 - 79
787
+ 1,
788
+ 1,
789
+ 1,
790
+ 1,
791
+ 1,
792
+ 1,
793
+ 1,
794
+ 1,
795
+ 1,
796
+ 1,
797
+ 1,
798
+ 0,
799
+ 0,
800
+ 0,
801
+ 1,
802
+ 1,
803
+ // 80 - 95
804
+ 1,
805
+ 1,
806
+ 1,
807
+ 1,
808
+ 1,
809
+ 1,
810
+ 1,
811
+ 1,
812
+ 1,
813
+ 1,
814
+ 1,
815
+ 1,
816
+ 1,
817
+ 1,
818
+ 1,
819
+ 1,
820
+ // 96 - 111
821
+ 1,
822
+ 1,
823
+ 1,
824
+ 1,
825
+ 1,
826
+ 1,
827
+ 1,
828
+ 1,
829
+ 1,
830
+ 1,
831
+ 1,
832
+ 0,
833
+ 1,
834
+ 0,
835
+ 1,
836
+ 0
837
+ // 112 - 127
838
+ ];
839
+ function isValidStatusCode(code) {
840
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
841
+ }
842
+ function _isValidUTF8(buf) {
843
+ const len = buf.length;
844
+ let i = 0;
845
+ while (i < len) {
846
+ if ((buf[i] & 128) === 0) {
847
+ i++;
848
+ } else if ((buf[i] & 224) === 192) {
849
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
850
+ return false;
851
+ }
852
+ i += 2;
853
+ } else if ((buf[i] & 240) === 224) {
854
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
855
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
856
+ return false;
857
+ }
858
+ i += 3;
859
+ } else if ((buf[i] & 248) === 240) {
860
+ if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
861
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
862
+ return false;
863
+ }
864
+ i += 4;
865
+ } else {
866
+ return false;
867
+ }
868
+ }
869
+ return true;
870
+ }
871
+ module2.exports = {
872
+ isValidStatusCode,
873
+ isValidUTF8: _isValidUTF8,
874
+ tokenChars
875
+ };
876
+ if (isUtf8) {
877
+ module2.exports.isValidUTF8 = function(buf) {
878
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
879
+ };
880
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
881
+ try {
882
+ const isValidUTF8 = require("utf-8-validate");
883
+ module2.exports.isValidUTF8 = function(buf) {
884
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
885
+ };
886
+ } catch (e) {
887
+ }
888
+ }
889
+ }
890
+ });
891
+
892
+ // node_modules/ws/lib/receiver.js
893
+ var require_receiver = __commonJS({
894
+ "node_modules/ws/lib/receiver.js"(exports2, module2) {
895
+ "use strict";
896
+ var { Writable } = require("stream");
897
+ var PerMessageDeflate = require_permessage_deflate();
898
+ var {
899
+ BINARY_TYPES,
900
+ EMPTY_BUFFER,
901
+ kStatusCode,
902
+ kWebSocket
903
+ } = require_constants();
904
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
905
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
906
+ var FastBuffer = Buffer[Symbol.species];
907
+ var GET_INFO = 0;
908
+ var GET_PAYLOAD_LENGTH_16 = 1;
909
+ var GET_PAYLOAD_LENGTH_64 = 2;
910
+ var GET_MASK = 3;
911
+ var GET_DATA = 4;
912
+ var INFLATING = 5;
913
+ var DEFER_EVENT = 6;
914
+ var Receiver2 = class extends Writable {
915
+ /**
916
+ * Creates a Receiver instance.
917
+ *
918
+ * @param {Object} [options] Options object
919
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
920
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
921
+ * multiple times in the same tick
922
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
923
+ * @param {Object} [options.extensions] An object containing the negotiated
924
+ * extensions
925
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
926
+ * client or server mode
927
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
928
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
929
+ * not to skip UTF-8 validation for text and close messages
930
+ */
931
+ constructor(options = {}) {
932
+ super();
933
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
934
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
935
+ this._extensions = options.extensions || {};
936
+ this._isServer = !!options.isServer;
937
+ this._maxPayload = options.maxPayload | 0;
938
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
939
+ this[kWebSocket] = void 0;
940
+ this._bufferedBytes = 0;
941
+ this._buffers = [];
942
+ this._compressed = false;
943
+ this._payloadLength = 0;
944
+ this._mask = void 0;
945
+ this._fragmented = 0;
946
+ this._masked = false;
947
+ this._fin = false;
948
+ this._opcode = 0;
949
+ this._totalPayloadLength = 0;
950
+ this._messageLength = 0;
951
+ this._fragments = [];
952
+ this._errored = false;
953
+ this._loop = false;
954
+ this._state = GET_INFO;
955
+ }
956
+ /**
957
+ * Implements `Writable.prototype._write()`.
958
+ *
959
+ * @param {Buffer} chunk The chunk of data to write
960
+ * @param {String} encoding The character encoding of `chunk`
961
+ * @param {Function} cb Callback
962
+ * @private
963
+ */
964
+ _write(chunk, encoding, cb) {
965
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
966
+ this._bufferedBytes += chunk.length;
967
+ this._buffers.push(chunk);
968
+ this.startLoop(cb);
969
+ }
970
+ /**
971
+ * Consumes `n` bytes from the buffered data.
972
+ *
973
+ * @param {Number} n The number of bytes to consume
974
+ * @return {Buffer} The consumed bytes
975
+ * @private
976
+ */
977
+ consume(n) {
978
+ this._bufferedBytes -= n;
979
+ if (n === this._buffers[0].length) return this._buffers.shift();
980
+ if (n < this._buffers[0].length) {
981
+ const buf = this._buffers[0];
982
+ this._buffers[0] = new FastBuffer(
983
+ buf.buffer,
984
+ buf.byteOffset + n,
985
+ buf.length - n
986
+ );
987
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
988
+ }
989
+ const dst = Buffer.allocUnsafe(n);
990
+ do {
991
+ const buf = this._buffers[0];
992
+ const offset = dst.length - n;
993
+ if (n >= buf.length) {
994
+ dst.set(this._buffers.shift(), offset);
995
+ } else {
996
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
997
+ this._buffers[0] = new FastBuffer(
998
+ buf.buffer,
999
+ buf.byteOffset + n,
1000
+ buf.length - n
1001
+ );
1002
+ }
1003
+ n -= buf.length;
1004
+ } while (n > 0);
1005
+ return dst;
1006
+ }
1007
+ /**
1008
+ * Starts the parsing loop.
1009
+ *
1010
+ * @param {Function} cb Callback
1011
+ * @private
1012
+ */
1013
+ startLoop(cb) {
1014
+ this._loop = true;
1015
+ do {
1016
+ switch (this._state) {
1017
+ case GET_INFO:
1018
+ this.getInfo(cb);
1019
+ break;
1020
+ case GET_PAYLOAD_LENGTH_16:
1021
+ this.getPayloadLength16(cb);
1022
+ break;
1023
+ case GET_PAYLOAD_LENGTH_64:
1024
+ this.getPayloadLength64(cb);
1025
+ break;
1026
+ case GET_MASK:
1027
+ this.getMask();
1028
+ break;
1029
+ case GET_DATA:
1030
+ this.getData(cb);
1031
+ break;
1032
+ case INFLATING:
1033
+ case DEFER_EVENT:
1034
+ this._loop = false;
1035
+ return;
1036
+ }
1037
+ } while (this._loop);
1038
+ if (!this._errored) cb();
1039
+ }
1040
+ /**
1041
+ * Reads the first two bytes of a frame.
1042
+ *
1043
+ * @param {Function} cb Callback
1044
+ * @private
1045
+ */
1046
+ getInfo(cb) {
1047
+ if (this._bufferedBytes < 2) {
1048
+ this._loop = false;
1049
+ return;
1050
+ }
1051
+ const buf = this.consume(2);
1052
+ if ((buf[0] & 48) !== 0) {
1053
+ const error = this.createError(
1054
+ RangeError,
1055
+ "RSV2 and RSV3 must be clear",
1056
+ true,
1057
+ 1002,
1058
+ "WS_ERR_UNEXPECTED_RSV_2_3"
1059
+ );
1060
+ cb(error);
1061
+ return;
1062
+ }
1063
+ const compressed = (buf[0] & 64) === 64;
1064
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
1065
+ const error = this.createError(
1066
+ RangeError,
1067
+ "RSV1 must be clear",
1068
+ true,
1069
+ 1002,
1070
+ "WS_ERR_UNEXPECTED_RSV_1"
1071
+ );
1072
+ cb(error);
1073
+ return;
1074
+ }
1075
+ this._fin = (buf[0] & 128) === 128;
1076
+ this._opcode = buf[0] & 15;
1077
+ this._payloadLength = buf[1] & 127;
1078
+ if (this._opcode === 0) {
1079
+ if (compressed) {
1080
+ const error = this.createError(
1081
+ RangeError,
1082
+ "RSV1 must be clear",
1083
+ true,
1084
+ 1002,
1085
+ "WS_ERR_UNEXPECTED_RSV_1"
1086
+ );
1087
+ cb(error);
1088
+ return;
1089
+ }
1090
+ if (!this._fragmented) {
1091
+ const error = this.createError(
1092
+ RangeError,
1093
+ "invalid opcode 0",
1094
+ true,
1095
+ 1002,
1096
+ "WS_ERR_INVALID_OPCODE"
1097
+ );
1098
+ cb(error);
1099
+ return;
1100
+ }
1101
+ this._opcode = this._fragmented;
1102
+ } else if (this._opcode === 1 || this._opcode === 2) {
1103
+ if (this._fragmented) {
1104
+ const error = this.createError(
1105
+ RangeError,
1106
+ `invalid opcode ${this._opcode}`,
1107
+ true,
1108
+ 1002,
1109
+ "WS_ERR_INVALID_OPCODE"
1110
+ );
1111
+ cb(error);
1112
+ return;
1113
+ }
1114
+ this._compressed = compressed;
1115
+ } else if (this._opcode > 7 && this._opcode < 11) {
1116
+ if (!this._fin) {
1117
+ const error = this.createError(
1118
+ RangeError,
1119
+ "FIN must be set",
1120
+ true,
1121
+ 1002,
1122
+ "WS_ERR_EXPECTED_FIN"
1123
+ );
1124
+ cb(error);
1125
+ return;
1126
+ }
1127
+ if (compressed) {
1128
+ const error = this.createError(
1129
+ RangeError,
1130
+ "RSV1 must be clear",
1131
+ true,
1132
+ 1002,
1133
+ "WS_ERR_UNEXPECTED_RSV_1"
1134
+ );
1135
+ cb(error);
1136
+ return;
1137
+ }
1138
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1139
+ const error = this.createError(
1140
+ RangeError,
1141
+ `invalid payload length ${this._payloadLength}`,
1142
+ true,
1143
+ 1002,
1144
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1145
+ );
1146
+ cb(error);
1147
+ return;
1148
+ }
1149
+ } else {
1150
+ const error = this.createError(
1151
+ RangeError,
1152
+ `invalid opcode ${this._opcode}`,
1153
+ true,
1154
+ 1002,
1155
+ "WS_ERR_INVALID_OPCODE"
1156
+ );
1157
+ cb(error);
1158
+ return;
1159
+ }
1160
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1161
+ this._masked = (buf[1] & 128) === 128;
1162
+ if (this._isServer) {
1163
+ if (!this._masked) {
1164
+ const error = this.createError(
1165
+ RangeError,
1166
+ "MASK must be set",
1167
+ true,
1168
+ 1002,
1169
+ "WS_ERR_EXPECTED_MASK"
1170
+ );
1171
+ cb(error);
1172
+ return;
1173
+ }
1174
+ } else if (this._masked) {
1175
+ const error = this.createError(
1176
+ RangeError,
1177
+ "MASK must be clear",
1178
+ true,
1179
+ 1002,
1180
+ "WS_ERR_UNEXPECTED_MASK"
1181
+ );
1182
+ cb(error);
1183
+ return;
1184
+ }
1185
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1186
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1187
+ else this.haveLength(cb);
1188
+ }
1189
+ /**
1190
+ * Gets extended payload length (7+16).
1191
+ *
1192
+ * @param {Function} cb Callback
1193
+ * @private
1194
+ */
1195
+ getPayloadLength16(cb) {
1196
+ if (this._bufferedBytes < 2) {
1197
+ this._loop = false;
1198
+ return;
1199
+ }
1200
+ this._payloadLength = this.consume(2).readUInt16BE(0);
1201
+ this.haveLength(cb);
1202
+ }
1203
+ /**
1204
+ * Gets extended payload length (7+64).
1205
+ *
1206
+ * @param {Function} cb Callback
1207
+ * @private
1208
+ */
1209
+ getPayloadLength64(cb) {
1210
+ if (this._bufferedBytes < 8) {
1211
+ this._loop = false;
1212
+ return;
1213
+ }
1214
+ const buf = this.consume(8);
1215
+ const num = buf.readUInt32BE(0);
1216
+ if (num > Math.pow(2, 53 - 32) - 1) {
1217
+ const error = this.createError(
1218
+ RangeError,
1219
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
1220
+ false,
1221
+ 1009,
1222
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1223
+ );
1224
+ cb(error);
1225
+ return;
1226
+ }
1227
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1228
+ this.haveLength(cb);
1229
+ }
1230
+ /**
1231
+ * Payload length has been read.
1232
+ *
1233
+ * @param {Function} cb Callback
1234
+ * @private
1235
+ */
1236
+ haveLength(cb) {
1237
+ if (this._payloadLength && this._opcode < 8) {
1238
+ this._totalPayloadLength += this._payloadLength;
1239
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1240
+ const error = this.createError(
1241
+ RangeError,
1242
+ "Max payload size exceeded",
1243
+ false,
1244
+ 1009,
1245
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1246
+ );
1247
+ cb(error);
1248
+ return;
1249
+ }
1250
+ }
1251
+ if (this._masked) this._state = GET_MASK;
1252
+ else this._state = GET_DATA;
1253
+ }
1254
+ /**
1255
+ * Reads mask bytes.
1256
+ *
1257
+ * @private
1258
+ */
1259
+ getMask() {
1260
+ if (this._bufferedBytes < 4) {
1261
+ this._loop = false;
1262
+ return;
1263
+ }
1264
+ this._mask = this.consume(4);
1265
+ this._state = GET_DATA;
1266
+ }
1267
+ /**
1268
+ * Reads data bytes.
1269
+ *
1270
+ * @param {Function} cb Callback
1271
+ * @private
1272
+ */
1273
+ getData(cb) {
1274
+ let data = EMPTY_BUFFER;
1275
+ if (this._payloadLength) {
1276
+ if (this._bufferedBytes < this._payloadLength) {
1277
+ this._loop = false;
1278
+ return;
1279
+ }
1280
+ data = this.consume(this._payloadLength);
1281
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1282
+ unmask(data, this._mask);
1283
+ }
1284
+ }
1285
+ if (this._opcode > 7) {
1286
+ this.controlMessage(data, cb);
1287
+ return;
1288
+ }
1289
+ if (this._compressed) {
1290
+ this._state = INFLATING;
1291
+ this.decompress(data, cb);
1292
+ return;
1293
+ }
1294
+ if (data.length) {
1295
+ this._messageLength = this._totalPayloadLength;
1296
+ this._fragments.push(data);
1297
+ }
1298
+ this.dataMessage(cb);
1299
+ }
1300
+ /**
1301
+ * Decompresses data.
1302
+ *
1303
+ * @param {Buffer} data Compressed data
1304
+ * @param {Function} cb Callback
1305
+ * @private
1306
+ */
1307
+ decompress(data, cb) {
1308
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1309
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1310
+ if (err) return cb(err);
1311
+ if (buf.length) {
1312
+ this._messageLength += buf.length;
1313
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1314
+ const error = this.createError(
1315
+ RangeError,
1316
+ "Max payload size exceeded",
1317
+ false,
1318
+ 1009,
1319
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1320
+ );
1321
+ cb(error);
1322
+ return;
1323
+ }
1324
+ this._fragments.push(buf);
1325
+ }
1326
+ this.dataMessage(cb);
1327
+ if (this._state === GET_INFO) this.startLoop(cb);
1328
+ });
1329
+ }
1330
+ /**
1331
+ * Handles a data message.
1332
+ *
1333
+ * @param {Function} cb Callback
1334
+ * @private
1335
+ */
1336
+ dataMessage(cb) {
1337
+ if (!this._fin) {
1338
+ this._state = GET_INFO;
1339
+ return;
1340
+ }
1341
+ const messageLength = this._messageLength;
1342
+ const fragments = this._fragments;
1343
+ this._totalPayloadLength = 0;
1344
+ this._messageLength = 0;
1345
+ this._fragmented = 0;
1346
+ this._fragments = [];
1347
+ if (this._opcode === 2) {
1348
+ let data;
1349
+ if (this._binaryType === "nodebuffer") {
1350
+ data = concat(fragments, messageLength);
1351
+ } else if (this._binaryType === "arraybuffer") {
1352
+ data = toArrayBuffer(concat(fragments, messageLength));
1353
+ } else {
1354
+ data = fragments;
1355
+ }
1356
+ if (this._allowSynchronousEvents) {
1357
+ this.emit("message", data, true);
1358
+ this._state = GET_INFO;
1359
+ } else {
1360
+ this._state = DEFER_EVENT;
1361
+ setImmediate(() => {
1362
+ this.emit("message", data, true);
1363
+ this._state = GET_INFO;
1364
+ this.startLoop(cb);
1365
+ });
1366
+ }
1367
+ } else {
1368
+ const buf = concat(fragments, messageLength);
1369
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1370
+ const error = this.createError(
1371
+ Error,
1372
+ "invalid UTF-8 sequence",
1373
+ true,
1374
+ 1007,
1375
+ "WS_ERR_INVALID_UTF8"
1376
+ );
1377
+ cb(error);
1378
+ return;
1379
+ }
1380
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
1381
+ this.emit("message", buf, false);
1382
+ this._state = GET_INFO;
1383
+ } else {
1384
+ this._state = DEFER_EVENT;
1385
+ setImmediate(() => {
1386
+ this.emit("message", buf, false);
1387
+ this._state = GET_INFO;
1388
+ this.startLoop(cb);
1389
+ });
1390
+ }
1391
+ }
1392
+ }
1393
+ /**
1394
+ * Handles a control message.
1395
+ *
1396
+ * @param {Buffer} data Data to handle
1397
+ * @return {(Error|RangeError|undefined)} A possible error
1398
+ * @private
1399
+ */
1400
+ controlMessage(data, cb) {
1401
+ if (this._opcode === 8) {
1402
+ if (data.length === 0) {
1403
+ this._loop = false;
1404
+ this.emit("conclude", 1005, EMPTY_BUFFER);
1405
+ this.end();
1406
+ } else {
1407
+ const code = data.readUInt16BE(0);
1408
+ if (!isValidStatusCode(code)) {
1409
+ const error = this.createError(
1410
+ RangeError,
1411
+ `invalid status code ${code}`,
1412
+ true,
1413
+ 1002,
1414
+ "WS_ERR_INVALID_CLOSE_CODE"
1415
+ );
1416
+ cb(error);
1417
+ return;
1418
+ }
1419
+ const buf = new FastBuffer(
1420
+ data.buffer,
1421
+ data.byteOffset + 2,
1422
+ data.length - 2
1423
+ );
1424
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1425
+ const error = this.createError(
1426
+ Error,
1427
+ "invalid UTF-8 sequence",
1428
+ true,
1429
+ 1007,
1430
+ "WS_ERR_INVALID_UTF8"
1431
+ );
1432
+ cb(error);
1433
+ return;
1434
+ }
1435
+ this._loop = false;
1436
+ this.emit("conclude", code, buf);
1437
+ this.end();
1438
+ }
1439
+ this._state = GET_INFO;
1440
+ return;
1441
+ }
1442
+ if (this._allowSynchronousEvents) {
1443
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1444
+ this._state = GET_INFO;
1445
+ } else {
1446
+ this._state = DEFER_EVENT;
1447
+ setImmediate(() => {
1448
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1449
+ this._state = GET_INFO;
1450
+ this.startLoop(cb);
1451
+ });
1452
+ }
1453
+ }
1454
+ /**
1455
+ * Builds an error object.
1456
+ *
1457
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1458
+ * @param {String} message The error message
1459
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1460
+ * `message`
1461
+ * @param {Number} statusCode The status code
1462
+ * @param {String} errorCode The exposed error code
1463
+ * @return {(Error|RangeError)} The error
1464
+ * @private
1465
+ */
1466
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1467
+ this._loop = false;
1468
+ this._errored = true;
1469
+ const err = new ErrorCtor(
1470
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1471
+ );
1472
+ Error.captureStackTrace(err, this.createError);
1473
+ err.code = errorCode;
1474
+ err[kStatusCode] = statusCode;
1475
+ return err;
1476
+ }
1477
+ };
1478
+ module2.exports = Receiver2;
1479
+ }
1480
+ });
1481
+
1482
+ // node_modules/ws/lib/sender.js
1483
+ var require_sender = __commonJS({
1484
+ "node_modules/ws/lib/sender.js"(exports2, module2) {
1485
+ "use strict";
1486
+ var { Duplex } = require("stream");
1487
+ var { randomFillSync } = require("crypto");
1488
+ var PerMessageDeflate = require_permessage_deflate();
1489
+ var { EMPTY_BUFFER } = require_constants();
1490
+ var { isValidStatusCode } = require_validation();
1491
+ var { mask: applyMask, toBuffer } = require_buffer_util();
1492
+ var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
1493
+ var maskBuffer = Buffer.alloc(4);
1494
+ var RANDOM_POOL_SIZE = 8 * 1024;
1495
+ var randomPool;
1496
+ var randomPoolPointer = RANDOM_POOL_SIZE;
1497
+ var Sender2 = class _Sender {
1498
+ /**
1499
+ * Creates a Sender instance.
1500
+ *
1501
+ * @param {Duplex} socket The connection socket
1502
+ * @param {Object} [extensions] An object containing the negotiated extensions
1503
+ * @param {Function} [generateMask] The function used to generate the masking
1504
+ * key
1505
+ */
1506
+ constructor(socket, extensions, generateMask) {
1507
+ this._extensions = extensions || {};
1508
+ if (generateMask) {
1509
+ this._generateMask = generateMask;
1510
+ this._maskBuffer = Buffer.alloc(4);
1511
+ }
1512
+ this._socket = socket;
1513
+ this._firstFragment = true;
1514
+ this._compress = false;
1515
+ this._bufferedBytes = 0;
1516
+ this._deflating = false;
1517
+ this._queue = [];
1518
+ }
1519
+ /**
1520
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1521
+ *
1522
+ * @param {(Buffer|String)} data The data to frame
1523
+ * @param {Object} options Options object
1524
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1525
+ * FIN bit
1526
+ * @param {Function} [options.generateMask] The function used to generate the
1527
+ * masking key
1528
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1529
+ * `data`
1530
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1531
+ * key
1532
+ * @param {Number} options.opcode The opcode
1533
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1534
+ * modified
1535
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1536
+ * RSV1 bit
1537
+ * @return {(Buffer|String)[]} The framed data
1538
+ * @public
1539
+ */
1540
+ static frame(data, options) {
1541
+ let mask;
1542
+ let merge = false;
1543
+ let offset = 2;
1544
+ let skipMasking = false;
1545
+ if (options.mask) {
1546
+ mask = options.maskBuffer || maskBuffer;
1547
+ if (options.generateMask) {
1548
+ options.generateMask(mask);
1549
+ } else {
1550
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1551
+ if (randomPool === void 0) {
1552
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1553
+ }
1554
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1555
+ randomPoolPointer = 0;
1556
+ }
1557
+ mask[0] = randomPool[randomPoolPointer++];
1558
+ mask[1] = randomPool[randomPoolPointer++];
1559
+ mask[2] = randomPool[randomPoolPointer++];
1560
+ mask[3] = randomPool[randomPoolPointer++];
1561
+ }
1562
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1563
+ offset = 6;
1564
+ }
1565
+ let dataLength;
1566
+ if (typeof data === "string") {
1567
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1568
+ dataLength = options[kByteLength];
1569
+ } else {
1570
+ data = Buffer.from(data);
1571
+ dataLength = data.length;
1572
+ }
1573
+ } else {
1574
+ dataLength = data.length;
1575
+ merge = options.mask && options.readOnly && !skipMasking;
1576
+ }
1577
+ let payloadLength = dataLength;
1578
+ if (dataLength >= 65536) {
1579
+ offset += 8;
1580
+ payloadLength = 127;
1581
+ } else if (dataLength > 125) {
1582
+ offset += 2;
1583
+ payloadLength = 126;
1584
+ }
1585
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1586
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1587
+ if (options.rsv1) target[0] |= 64;
1588
+ target[1] = payloadLength;
1589
+ if (payloadLength === 126) {
1590
+ target.writeUInt16BE(dataLength, 2);
1591
+ } else if (payloadLength === 127) {
1592
+ target[2] = target[3] = 0;
1593
+ target.writeUIntBE(dataLength, 4, 6);
1594
+ }
1595
+ if (!options.mask) return [target, data];
1596
+ target[1] |= 128;
1597
+ target[offset - 4] = mask[0];
1598
+ target[offset - 3] = mask[1];
1599
+ target[offset - 2] = mask[2];
1600
+ target[offset - 1] = mask[3];
1601
+ if (skipMasking) return [target, data];
1602
+ if (merge) {
1603
+ applyMask(data, mask, target, offset, dataLength);
1604
+ return [target];
1605
+ }
1606
+ applyMask(data, mask, data, 0, dataLength);
1607
+ return [target, data];
1608
+ }
1609
+ /**
1610
+ * Sends a close message to the other peer.
1611
+ *
1612
+ * @param {Number} [code] The status code component of the body
1613
+ * @param {(String|Buffer)} [data] The message component of the body
1614
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1615
+ * @param {Function} [cb] Callback
1616
+ * @public
1617
+ */
1618
+ close(code, data, mask, cb) {
1619
+ let buf;
1620
+ if (code === void 0) {
1621
+ buf = EMPTY_BUFFER;
1622
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1623
+ throw new TypeError("First argument must be a valid error code number");
1624
+ } else if (data === void 0 || !data.length) {
1625
+ buf = Buffer.allocUnsafe(2);
1626
+ buf.writeUInt16BE(code, 0);
1627
+ } else {
1628
+ const length = Buffer.byteLength(data);
1629
+ if (length > 123) {
1630
+ throw new RangeError("The message must not be greater than 123 bytes");
1631
+ }
1632
+ buf = Buffer.allocUnsafe(2 + length);
1633
+ buf.writeUInt16BE(code, 0);
1634
+ if (typeof data === "string") {
1635
+ buf.write(data, 2);
1636
+ } else {
1637
+ buf.set(data, 2);
1638
+ }
1639
+ }
1640
+ const options = {
1641
+ [kByteLength]: buf.length,
1642
+ fin: true,
1643
+ generateMask: this._generateMask,
1644
+ mask,
1645
+ maskBuffer: this._maskBuffer,
1646
+ opcode: 8,
1647
+ readOnly: false,
1648
+ rsv1: false
1649
+ };
1650
+ if (this._deflating) {
1651
+ this.enqueue([this.dispatch, buf, false, options, cb]);
1652
+ } else {
1653
+ this.sendFrame(_Sender.frame(buf, options), cb);
1654
+ }
1655
+ }
1656
+ /**
1657
+ * Sends a ping message to the other peer.
1658
+ *
1659
+ * @param {*} data The message to send
1660
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1661
+ * @param {Function} [cb] Callback
1662
+ * @public
1663
+ */
1664
+ ping(data, mask, cb) {
1665
+ let byteLength;
1666
+ let readOnly;
1667
+ if (typeof data === "string") {
1668
+ byteLength = Buffer.byteLength(data);
1669
+ readOnly = false;
1670
+ } else {
1671
+ data = toBuffer(data);
1672
+ byteLength = data.length;
1673
+ readOnly = toBuffer.readOnly;
1674
+ }
1675
+ if (byteLength > 125) {
1676
+ throw new RangeError("The data size must not be greater than 125 bytes");
1677
+ }
1678
+ const options = {
1679
+ [kByteLength]: byteLength,
1680
+ fin: true,
1681
+ generateMask: this._generateMask,
1682
+ mask,
1683
+ maskBuffer: this._maskBuffer,
1684
+ opcode: 9,
1685
+ readOnly,
1686
+ rsv1: false
1687
+ };
1688
+ if (this._deflating) {
1689
+ this.enqueue([this.dispatch, data, false, options, cb]);
1690
+ } else {
1691
+ this.sendFrame(_Sender.frame(data, options), cb);
1692
+ }
1693
+ }
1694
+ /**
1695
+ * Sends a pong message to the other peer.
1696
+ *
1697
+ * @param {*} data The message to send
1698
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1699
+ * @param {Function} [cb] Callback
1700
+ * @public
1701
+ */
1702
+ pong(data, mask, cb) {
1703
+ let byteLength;
1704
+ let readOnly;
1705
+ if (typeof data === "string") {
1706
+ byteLength = Buffer.byteLength(data);
1707
+ readOnly = false;
1708
+ } else {
1709
+ data = toBuffer(data);
1710
+ byteLength = data.length;
1711
+ readOnly = toBuffer.readOnly;
1712
+ }
1713
+ if (byteLength > 125) {
1714
+ throw new RangeError("The data size must not be greater than 125 bytes");
1715
+ }
1716
+ const options = {
1717
+ [kByteLength]: byteLength,
1718
+ fin: true,
1719
+ generateMask: this._generateMask,
1720
+ mask,
1721
+ maskBuffer: this._maskBuffer,
1722
+ opcode: 10,
1723
+ readOnly,
1724
+ rsv1: false
1725
+ };
1726
+ if (this._deflating) {
1727
+ this.enqueue([this.dispatch, data, false, options, cb]);
1728
+ } else {
1729
+ this.sendFrame(_Sender.frame(data, options), cb);
1730
+ }
1731
+ }
1732
+ /**
1733
+ * Sends a data message to the other peer.
1734
+ *
1735
+ * @param {*} data The message to send
1736
+ * @param {Object} options Options object
1737
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1738
+ * or text
1739
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1740
+ * compress `data`
1741
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1742
+ * last one
1743
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1744
+ * `data`
1745
+ * @param {Function} [cb] Callback
1746
+ * @public
1747
+ */
1748
+ send(data, options, cb) {
1749
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1750
+ let opcode = options.binary ? 2 : 1;
1751
+ let rsv1 = options.compress;
1752
+ let byteLength;
1753
+ let readOnly;
1754
+ if (typeof data === "string") {
1755
+ byteLength = Buffer.byteLength(data);
1756
+ readOnly = false;
1757
+ } else {
1758
+ data = toBuffer(data);
1759
+ byteLength = data.length;
1760
+ readOnly = toBuffer.readOnly;
1761
+ }
1762
+ if (this._firstFragment) {
1763
+ this._firstFragment = false;
1764
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1765
+ rsv1 = byteLength >= perMessageDeflate._threshold;
1766
+ }
1767
+ this._compress = rsv1;
1768
+ } else {
1769
+ rsv1 = false;
1770
+ opcode = 0;
1771
+ }
1772
+ if (options.fin) this._firstFragment = true;
1773
+ if (perMessageDeflate) {
1774
+ const opts = {
1775
+ [kByteLength]: byteLength,
1776
+ fin: options.fin,
1777
+ generateMask: this._generateMask,
1778
+ mask: options.mask,
1779
+ maskBuffer: this._maskBuffer,
1780
+ opcode,
1781
+ readOnly,
1782
+ rsv1
1783
+ };
1784
+ if (this._deflating) {
1785
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1786
+ } else {
1787
+ this.dispatch(data, this._compress, opts, cb);
1788
+ }
1789
+ } else {
1790
+ this.sendFrame(
1791
+ _Sender.frame(data, {
1792
+ [kByteLength]: byteLength,
1793
+ fin: options.fin,
1794
+ generateMask: this._generateMask,
1795
+ mask: options.mask,
1796
+ maskBuffer: this._maskBuffer,
1797
+ opcode,
1798
+ readOnly,
1799
+ rsv1: false
1800
+ }),
1801
+ cb
1802
+ );
1803
+ }
1804
+ }
1805
+ /**
1806
+ * Dispatches a message.
1807
+ *
1808
+ * @param {(Buffer|String)} data The message to send
1809
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1810
+ * `data`
1811
+ * @param {Object} options Options object
1812
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1813
+ * FIN bit
1814
+ * @param {Function} [options.generateMask] The function used to generate the
1815
+ * masking key
1816
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1817
+ * `data`
1818
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1819
+ * key
1820
+ * @param {Number} options.opcode The opcode
1821
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1822
+ * modified
1823
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1824
+ * RSV1 bit
1825
+ * @param {Function} [cb] Callback
1826
+ * @private
1827
+ */
1828
+ dispatch(data, compress, options, cb) {
1829
+ if (!compress) {
1830
+ this.sendFrame(_Sender.frame(data, options), cb);
1831
+ return;
1832
+ }
1833
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1834
+ this._bufferedBytes += options[kByteLength];
1835
+ this._deflating = true;
1836
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1837
+ if (this._socket.destroyed) {
1838
+ const err = new Error(
1839
+ "The socket was closed while data was being compressed"
1840
+ );
1841
+ if (typeof cb === "function") cb(err);
1842
+ for (let i = 0; i < this._queue.length; i++) {
1843
+ const params = this._queue[i];
1844
+ const callback = params[params.length - 1];
1845
+ if (typeof callback === "function") callback(err);
1846
+ }
1847
+ return;
1848
+ }
1849
+ this._bufferedBytes -= options[kByteLength];
1850
+ this._deflating = false;
1851
+ options.readOnly = false;
1852
+ this.sendFrame(_Sender.frame(buf, options), cb);
1853
+ this.dequeue();
1854
+ });
1855
+ }
1856
+ /**
1857
+ * Executes queued send operations.
1858
+ *
1859
+ * @private
1860
+ */
1861
+ dequeue() {
1862
+ while (!this._deflating && this._queue.length) {
1863
+ const params = this._queue.shift();
1864
+ this._bufferedBytes -= params[3][kByteLength];
1865
+ Reflect.apply(params[0], this, params.slice(1));
1866
+ }
1867
+ }
1868
+ /**
1869
+ * Enqueues a send operation.
1870
+ *
1871
+ * @param {Array} params Send operation parameters.
1872
+ * @private
1873
+ */
1874
+ enqueue(params) {
1875
+ this._bufferedBytes += params[3][kByteLength];
1876
+ this._queue.push(params);
1877
+ }
1878
+ /**
1879
+ * Sends a frame.
1880
+ *
1881
+ * @param {Buffer[]} list The frame to send
1882
+ * @param {Function} [cb] Callback
1883
+ * @private
1884
+ */
1885
+ sendFrame(list, cb) {
1886
+ if (list.length === 2) {
1887
+ this._socket.cork();
1888
+ this._socket.write(list[0]);
1889
+ this._socket.write(list[1], cb);
1890
+ this._socket.uncork();
1891
+ } else {
1892
+ this._socket.write(list[0], cb);
1893
+ }
1894
+ }
1895
+ };
1896
+ module2.exports = Sender2;
1897
+ }
1898
+ });
1899
+
1900
+ // node_modules/ws/lib/event-target.js
1901
+ var require_event_target = __commonJS({
1902
+ "node_modules/ws/lib/event-target.js"(exports2, module2) {
1903
+ "use strict";
1904
+ var { kForOnEventAttribute, kListener } = require_constants();
1905
+ var kCode = /* @__PURE__ */ Symbol("kCode");
1906
+ var kData = /* @__PURE__ */ Symbol("kData");
1907
+ var kError = /* @__PURE__ */ Symbol("kError");
1908
+ var kMessage = /* @__PURE__ */ Symbol("kMessage");
1909
+ var kReason = /* @__PURE__ */ Symbol("kReason");
1910
+ var kTarget = /* @__PURE__ */ Symbol("kTarget");
1911
+ var kType = /* @__PURE__ */ Symbol("kType");
1912
+ var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
1913
+ var Event = class {
1914
+ /**
1915
+ * Create a new `Event`.
1916
+ *
1917
+ * @param {String} type The name of the event
1918
+ * @throws {TypeError} If the `type` argument is not specified
1919
+ */
1920
+ constructor(type) {
1921
+ this[kTarget] = null;
1922
+ this[kType] = type;
1923
+ }
1924
+ /**
1925
+ * @type {*}
1926
+ */
1927
+ get target() {
1928
+ return this[kTarget];
1929
+ }
1930
+ /**
1931
+ * @type {String}
1932
+ */
1933
+ get type() {
1934
+ return this[kType];
1935
+ }
1936
+ };
1937
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
1938
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
1939
+ var CloseEvent = class extends Event {
1940
+ /**
1941
+ * Create a new `CloseEvent`.
1942
+ *
1943
+ * @param {String} type The name of the event
1944
+ * @param {Object} [options] A dictionary object that allows for setting
1945
+ * attributes via object members of the same name
1946
+ * @param {Number} [options.code=0] The status code explaining why the
1947
+ * connection was closed
1948
+ * @param {String} [options.reason=''] A human-readable string explaining why
1949
+ * the connection was closed
1950
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1951
+ * connection was cleanly closed
1952
+ */
1953
+ constructor(type, options = {}) {
1954
+ super(type);
1955
+ this[kCode] = options.code === void 0 ? 0 : options.code;
1956
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
1957
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1958
+ }
1959
+ /**
1960
+ * @type {Number}
1961
+ */
1962
+ get code() {
1963
+ return this[kCode];
1964
+ }
1965
+ /**
1966
+ * @type {String}
1967
+ */
1968
+ get reason() {
1969
+ return this[kReason];
1970
+ }
1971
+ /**
1972
+ * @type {Boolean}
1973
+ */
1974
+ get wasClean() {
1975
+ return this[kWasClean];
1976
+ }
1977
+ };
1978
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1979
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1980
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1981
+ var ErrorEvent = class extends Event {
1982
+ /**
1983
+ * Create a new `ErrorEvent`.
1984
+ *
1985
+ * @param {String} type The name of the event
1986
+ * @param {Object} [options] A dictionary object that allows for setting
1987
+ * attributes via object members of the same name
1988
+ * @param {*} [options.error=null] The error that generated this event
1989
+ * @param {String} [options.message=''] The error message
1990
+ */
1991
+ constructor(type, options = {}) {
1992
+ super(type);
1993
+ this[kError] = options.error === void 0 ? null : options.error;
1994
+ this[kMessage] = options.message === void 0 ? "" : options.message;
1995
+ }
1996
+ /**
1997
+ * @type {*}
1998
+ */
1999
+ get error() {
2000
+ return this[kError];
2001
+ }
2002
+ /**
2003
+ * @type {String}
2004
+ */
2005
+ get message() {
2006
+ return this[kMessage];
2007
+ }
2008
+ };
2009
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
2010
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
2011
+ var MessageEvent = class extends Event {
2012
+ /**
2013
+ * Create a new `MessageEvent`.
2014
+ *
2015
+ * @param {String} type The name of the event
2016
+ * @param {Object} [options] A dictionary object that allows for setting
2017
+ * attributes via object members of the same name
2018
+ * @param {*} [options.data=null] The message content
2019
+ */
2020
+ constructor(type, options = {}) {
2021
+ super(type);
2022
+ this[kData] = options.data === void 0 ? null : options.data;
2023
+ }
2024
+ /**
2025
+ * @type {*}
2026
+ */
2027
+ get data() {
2028
+ return this[kData];
2029
+ }
2030
+ };
2031
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
2032
+ var EventTarget = {
2033
+ /**
2034
+ * Register an event listener.
2035
+ *
2036
+ * @param {String} type A string representing the event type to listen for
2037
+ * @param {(Function|Object)} handler The listener to add
2038
+ * @param {Object} [options] An options object specifies characteristics about
2039
+ * the event listener
2040
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
2041
+ * listener should be invoked at most once after being added. If `true`,
2042
+ * the listener would be automatically removed when invoked.
2043
+ * @public
2044
+ */
2045
+ addEventListener(type, handler, options = {}) {
2046
+ for (const listener of this.listeners(type)) {
2047
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2048
+ return;
2049
+ }
2050
+ }
2051
+ let wrapper;
2052
+ if (type === "message") {
2053
+ wrapper = function onMessage(data, isBinary) {
2054
+ const event = new MessageEvent("message", {
2055
+ data: isBinary ? data : data.toString()
2056
+ });
2057
+ event[kTarget] = this;
2058
+ callListener(handler, this, event);
2059
+ };
2060
+ } else if (type === "close") {
2061
+ wrapper = function onClose(code, message) {
2062
+ const event = new CloseEvent("close", {
2063
+ code,
2064
+ reason: message.toString(),
2065
+ wasClean: this._closeFrameReceived && this._closeFrameSent
2066
+ });
2067
+ event[kTarget] = this;
2068
+ callListener(handler, this, event);
2069
+ };
2070
+ } else if (type === "error") {
2071
+ wrapper = function onError(error) {
2072
+ const event = new ErrorEvent("error", {
2073
+ error,
2074
+ message: error.message
2075
+ });
2076
+ event[kTarget] = this;
2077
+ callListener(handler, this, event);
2078
+ };
2079
+ } else if (type === "open") {
2080
+ wrapper = function onOpen() {
2081
+ const event = new Event("open");
2082
+ event[kTarget] = this;
2083
+ callListener(handler, this, event);
2084
+ };
2085
+ } else {
2086
+ return;
2087
+ }
2088
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2089
+ wrapper[kListener] = handler;
2090
+ if (options.once) {
2091
+ this.once(type, wrapper);
2092
+ } else {
2093
+ this.on(type, wrapper);
2094
+ }
2095
+ },
2096
+ /**
2097
+ * Remove an event listener.
2098
+ *
2099
+ * @param {String} type A string representing the event type to remove
2100
+ * @param {(Function|Object)} handler The listener to remove
2101
+ * @public
2102
+ */
2103
+ removeEventListener(type, handler) {
2104
+ for (const listener of this.listeners(type)) {
2105
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2106
+ this.removeListener(type, listener);
2107
+ break;
2108
+ }
2109
+ }
2110
+ }
2111
+ };
2112
+ module2.exports = {
2113
+ CloseEvent,
2114
+ ErrorEvent,
2115
+ Event,
2116
+ EventTarget,
2117
+ MessageEvent
2118
+ };
2119
+ function callListener(listener, thisArg, event) {
2120
+ if (typeof listener === "object" && listener.handleEvent) {
2121
+ listener.handleEvent.call(listener, event);
2122
+ } else {
2123
+ listener.call(thisArg, event);
2124
+ }
2125
+ }
2126
+ }
2127
+ });
2128
+
2129
+ // node_modules/ws/lib/extension.js
2130
+ var require_extension = __commonJS({
2131
+ "node_modules/ws/lib/extension.js"(exports2, module2) {
2132
+ "use strict";
2133
+ var { tokenChars } = require_validation();
2134
+ function push(dest, name, elem) {
2135
+ if (dest[name] === void 0) dest[name] = [elem];
2136
+ else dest[name].push(elem);
2137
+ }
2138
+ function parse(header) {
2139
+ const offers = /* @__PURE__ */ Object.create(null);
2140
+ let params = /* @__PURE__ */ Object.create(null);
2141
+ let mustUnescape = false;
2142
+ let isEscaping = false;
2143
+ let inQuotes = false;
2144
+ let extensionName;
2145
+ let paramName;
2146
+ let start = -1;
2147
+ let code = -1;
2148
+ let end = -1;
2149
+ let i = 0;
2150
+ for (; i < header.length; i++) {
2151
+ code = header.charCodeAt(i);
2152
+ if (extensionName === void 0) {
2153
+ if (end === -1 && tokenChars[code] === 1) {
2154
+ if (start === -1) start = i;
2155
+ } else if (i !== 0 && (code === 32 || code === 9)) {
2156
+ if (end === -1 && start !== -1) end = i;
2157
+ } else if (code === 59 || code === 44) {
2158
+ if (start === -1) {
2159
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2160
+ }
2161
+ if (end === -1) end = i;
2162
+ const name = header.slice(start, end);
2163
+ if (code === 44) {
2164
+ push(offers, name, params);
2165
+ params = /* @__PURE__ */ Object.create(null);
2166
+ } else {
2167
+ extensionName = name;
2168
+ }
2169
+ start = end = -1;
2170
+ } else {
2171
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2172
+ }
2173
+ } else if (paramName === void 0) {
2174
+ if (end === -1 && tokenChars[code] === 1) {
2175
+ if (start === -1) start = i;
2176
+ } else if (code === 32 || code === 9) {
2177
+ if (end === -1 && start !== -1) end = i;
2178
+ } else if (code === 59 || code === 44) {
2179
+ if (start === -1) {
2180
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2181
+ }
2182
+ if (end === -1) end = i;
2183
+ push(params, header.slice(start, end), true);
2184
+ if (code === 44) {
2185
+ push(offers, extensionName, params);
2186
+ params = /* @__PURE__ */ Object.create(null);
2187
+ extensionName = void 0;
2188
+ }
2189
+ start = end = -1;
2190
+ } else if (code === 61 && start !== -1 && end === -1) {
2191
+ paramName = header.slice(start, i);
2192
+ start = end = -1;
2193
+ } else {
2194
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2195
+ }
2196
+ } else {
2197
+ if (isEscaping) {
2198
+ if (tokenChars[code] !== 1) {
2199
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2200
+ }
2201
+ if (start === -1) start = i;
2202
+ else if (!mustUnescape) mustUnescape = true;
2203
+ isEscaping = false;
2204
+ } else if (inQuotes) {
2205
+ if (tokenChars[code] === 1) {
2206
+ if (start === -1) start = i;
2207
+ } else if (code === 34 && start !== -1) {
2208
+ inQuotes = false;
2209
+ end = i;
2210
+ } else if (code === 92) {
2211
+ isEscaping = true;
2212
+ } else {
2213
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2214
+ }
2215
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2216
+ inQuotes = true;
2217
+ } else if (end === -1 && tokenChars[code] === 1) {
2218
+ if (start === -1) start = i;
2219
+ } else if (start !== -1 && (code === 32 || code === 9)) {
2220
+ if (end === -1) end = i;
2221
+ } else if (code === 59 || code === 44) {
2222
+ if (start === -1) {
2223
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2224
+ }
2225
+ if (end === -1) end = i;
2226
+ let value = header.slice(start, end);
2227
+ if (mustUnescape) {
2228
+ value = value.replace(/\\/g, "");
2229
+ mustUnescape = false;
2230
+ }
2231
+ push(params, paramName, value);
2232
+ if (code === 44) {
2233
+ push(offers, extensionName, params);
2234
+ params = /* @__PURE__ */ Object.create(null);
2235
+ extensionName = void 0;
2236
+ }
2237
+ paramName = void 0;
2238
+ start = end = -1;
2239
+ } else {
2240
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2241
+ }
2242
+ }
2243
+ }
2244
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
2245
+ throw new SyntaxError("Unexpected end of input");
2246
+ }
2247
+ if (end === -1) end = i;
2248
+ const token = header.slice(start, end);
2249
+ if (extensionName === void 0) {
2250
+ push(offers, token, params);
2251
+ } else {
2252
+ if (paramName === void 0) {
2253
+ push(params, token, true);
2254
+ } else if (mustUnescape) {
2255
+ push(params, paramName, token.replace(/\\/g, ""));
2256
+ } else {
2257
+ push(params, paramName, token);
2258
+ }
2259
+ push(offers, extensionName, params);
2260
+ }
2261
+ return offers;
2262
+ }
2263
+ function format(extensions) {
2264
+ return Object.keys(extensions).map((extension) => {
2265
+ let configurations = extensions[extension];
2266
+ if (!Array.isArray(configurations)) configurations = [configurations];
2267
+ return configurations.map((params) => {
2268
+ return [extension].concat(
2269
+ Object.keys(params).map((k) => {
2270
+ let values = params[k];
2271
+ if (!Array.isArray(values)) values = [values];
2272
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2273
+ })
2274
+ ).join("; ");
2275
+ }).join(", ");
2276
+ }).join(", ");
2277
+ }
2278
+ module2.exports = { format, parse };
2279
+ }
2280
+ });
2281
+
2282
+ // node_modules/ws/lib/websocket.js
2283
+ var require_websocket = __commonJS({
2284
+ "node_modules/ws/lib/websocket.js"(exports2, module2) {
2285
+ "use strict";
2286
+ var EventEmitter = require("events");
2287
+ var https = require("https");
2288
+ var http = require("http");
2289
+ var net = require("net");
2290
+ var tls = require("tls");
2291
+ var { randomBytes, createHash } = require("crypto");
2292
+ var { Duplex, Readable } = require("stream");
2293
+ var { URL: URL2 } = require("url");
2294
+ var PerMessageDeflate = require_permessage_deflate();
2295
+ var Receiver2 = require_receiver();
2296
+ var Sender2 = require_sender();
2297
+ var {
2298
+ BINARY_TYPES,
2299
+ EMPTY_BUFFER,
2300
+ GUID,
2301
+ kForOnEventAttribute,
2302
+ kListener,
2303
+ kStatusCode,
2304
+ kWebSocket,
2305
+ NOOP
2306
+ } = require_constants();
2307
+ var {
2308
+ EventTarget: { addEventListener, removeEventListener }
2309
+ } = require_event_target();
2310
+ var { format, parse } = require_extension();
2311
+ var { toBuffer } = require_buffer_util();
2312
+ var closeTimeout = 30 * 1e3;
2313
+ var kAborted = /* @__PURE__ */ Symbol("kAborted");
2314
+ var protocolVersions = [8, 13];
2315
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2316
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2317
+ var WebSocket3 = class _WebSocket extends EventEmitter {
2318
+ /**
2319
+ * Create a new `WebSocket`.
2320
+ *
2321
+ * @param {(String|URL)} address The URL to which to connect
2322
+ * @param {(String|String[])} [protocols] The subprotocols
2323
+ * @param {Object} [options] Connection options
2324
+ */
2325
+ constructor(address, protocols, options) {
2326
+ super();
2327
+ this._binaryType = BINARY_TYPES[0];
2328
+ this._closeCode = 1006;
2329
+ this._closeFrameReceived = false;
2330
+ this._closeFrameSent = false;
2331
+ this._closeMessage = EMPTY_BUFFER;
2332
+ this._closeTimer = null;
2333
+ this._extensions = {};
2334
+ this._paused = false;
2335
+ this._protocol = "";
2336
+ this._readyState = _WebSocket.CONNECTING;
2337
+ this._receiver = null;
2338
+ this._sender = null;
2339
+ this._socket = null;
2340
+ if (address !== null) {
2341
+ this._bufferedAmount = 0;
2342
+ this._isServer = false;
2343
+ this._redirects = 0;
2344
+ if (protocols === void 0) {
2345
+ protocols = [];
2346
+ } else if (!Array.isArray(protocols)) {
2347
+ if (typeof protocols === "object" && protocols !== null) {
2348
+ options = protocols;
2349
+ protocols = [];
2350
+ } else {
2351
+ protocols = [protocols];
2352
+ }
2353
+ }
2354
+ initAsClient(this, address, protocols, options);
2355
+ } else {
2356
+ this._autoPong = options.autoPong;
2357
+ this._isServer = true;
2358
+ }
2359
+ }
2360
+ /**
2361
+ * This deviates from the WHATWG interface since ws doesn't support the
2362
+ * required default "blob" type (instead we define a custom "nodebuffer"
2363
+ * type).
2364
+ *
2365
+ * @type {String}
2366
+ */
2367
+ get binaryType() {
2368
+ return this._binaryType;
2369
+ }
2370
+ set binaryType(type) {
2371
+ if (!BINARY_TYPES.includes(type)) return;
2372
+ this._binaryType = type;
2373
+ if (this._receiver) this._receiver._binaryType = type;
2374
+ }
2375
+ /**
2376
+ * @type {Number}
2377
+ */
2378
+ get bufferedAmount() {
2379
+ if (!this._socket) return this._bufferedAmount;
2380
+ return this._socket._writableState.length + this._sender._bufferedBytes;
2381
+ }
2382
+ /**
2383
+ * @type {String}
2384
+ */
2385
+ get extensions() {
2386
+ return Object.keys(this._extensions).join();
2387
+ }
2388
+ /**
2389
+ * @type {Boolean}
2390
+ */
2391
+ get isPaused() {
2392
+ return this._paused;
2393
+ }
2394
+ /**
2395
+ * @type {Function}
2396
+ */
2397
+ /* istanbul ignore next */
2398
+ get onclose() {
2399
+ return null;
2400
+ }
2401
+ /**
2402
+ * @type {Function}
2403
+ */
2404
+ /* istanbul ignore next */
2405
+ get onerror() {
2406
+ return null;
2407
+ }
2408
+ /**
2409
+ * @type {Function}
2410
+ */
2411
+ /* istanbul ignore next */
2412
+ get onopen() {
2413
+ return null;
2414
+ }
2415
+ /**
2416
+ * @type {Function}
2417
+ */
2418
+ /* istanbul ignore next */
2419
+ get onmessage() {
2420
+ return null;
2421
+ }
2422
+ /**
2423
+ * @type {String}
2424
+ */
2425
+ get protocol() {
2426
+ return this._protocol;
2427
+ }
2428
+ /**
2429
+ * @type {Number}
2430
+ */
2431
+ get readyState() {
2432
+ return this._readyState;
2433
+ }
2434
+ /**
2435
+ * @type {String}
2436
+ */
2437
+ get url() {
2438
+ return this._url;
2439
+ }
2440
+ /**
2441
+ * Set up the socket and the internal resources.
2442
+ *
2443
+ * @param {Duplex} socket The network socket between the server and client
2444
+ * @param {Buffer} head The first packet of the upgraded stream
2445
+ * @param {Object} options Options object
2446
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2447
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2448
+ * multiple times in the same tick
2449
+ * @param {Function} [options.generateMask] The function used to generate the
2450
+ * masking key
2451
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
2452
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2453
+ * not to skip UTF-8 validation for text and close messages
2454
+ * @private
2455
+ */
2456
+ setSocket(socket, head, options) {
2457
+ const receiver = new Receiver2({
2458
+ allowSynchronousEvents: options.allowSynchronousEvents,
2459
+ binaryType: this.binaryType,
2460
+ extensions: this._extensions,
2461
+ isServer: this._isServer,
2462
+ maxPayload: options.maxPayload,
2463
+ skipUTF8Validation: options.skipUTF8Validation
2464
+ });
2465
+ this._sender = new Sender2(socket, this._extensions, options.generateMask);
2466
+ this._receiver = receiver;
2467
+ this._socket = socket;
2468
+ receiver[kWebSocket] = this;
2469
+ socket[kWebSocket] = this;
2470
+ receiver.on("conclude", receiverOnConclude);
2471
+ receiver.on("drain", receiverOnDrain);
2472
+ receiver.on("error", receiverOnError);
2473
+ receiver.on("message", receiverOnMessage);
2474
+ receiver.on("ping", receiverOnPing);
2475
+ receiver.on("pong", receiverOnPong);
2476
+ if (socket.setTimeout) socket.setTimeout(0);
2477
+ if (socket.setNoDelay) socket.setNoDelay();
2478
+ if (head.length > 0) socket.unshift(head);
2479
+ socket.on("close", socketOnClose);
2480
+ socket.on("data", socketOnData);
2481
+ socket.on("end", socketOnEnd);
2482
+ socket.on("error", socketOnError);
2483
+ this._readyState = _WebSocket.OPEN;
2484
+ this.emit("open");
2485
+ }
2486
+ /**
2487
+ * Emit the `'close'` event.
2488
+ *
2489
+ * @private
2490
+ */
2491
+ emitClose() {
2492
+ if (!this._socket) {
2493
+ this._readyState = _WebSocket.CLOSED;
2494
+ this.emit("close", this._closeCode, this._closeMessage);
2495
+ return;
2496
+ }
2497
+ if (this._extensions[PerMessageDeflate.extensionName]) {
2498
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
2499
+ }
2500
+ this._receiver.removeAllListeners();
2501
+ this._readyState = _WebSocket.CLOSED;
2502
+ this.emit("close", this._closeCode, this._closeMessage);
2503
+ }
2504
+ /**
2505
+ * Start a closing handshake.
2506
+ *
2507
+ * +----------+ +-----------+ +----------+
2508
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2509
+ * | +----------+ +-----------+ +----------+ |
2510
+ * +----------+ +-----------+ |
2511
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2512
+ * +----------+ +-----------+ |
2513
+ * | | | +---+ |
2514
+ * +------------------------+-->|fin| - - - -
2515
+ * | +---+ | +---+
2516
+ * - - - - -|fin|<---------------------+
2517
+ * +---+
2518
+ *
2519
+ * @param {Number} [code] Status code explaining why the connection is closing
2520
+ * @param {(String|Buffer)} [data] The reason why the connection is
2521
+ * closing
2522
+ * @public
2523
+ */
2524
+ close(code, data) {
2525
+ if (this.readyState === _WebSocket.CLOSED) return;
2526
+ if (this.readyState === _WebSocket.CONNECTING) {
2527
+ const msg = "WebSocket was closed before the connection was established";
2528
+ abortHandshake(this, this._req, msg);
2529
+ return;
2530
+ }
2531
+ if (this.readyState === _WebSocket.CLOSING) {
2532
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
2533
+ this._socket.end();
2534
+ }
2535
+ return;
2536
+ }
2537
+ this._readyState = _WebSocket.CLOSING;
2538
+ this._sender.close(code, data, !this._isServer, (err) => {
2539
+ if (err) return;
2540
+ this._closeFrameSent = true;
2541
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2542
+ this._socket.end();
2543
+ }
2544
+ });
2545
+ this._closeTimer = setTimeout(
2546
+ this._socket.destroy.bind(this._socket),
2547
+ closeTimeout
2548
+ );
2549
+ }
2550
+ /**
2551
+ * Pause the socket.
2552
+ *
2553
+ * @public
2554
+ */
2555
+ pause() {
2556
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2557
+ return;
2558
+ }
2559
+ this._paused = true;
2560
+ this._socket.pause();
2561
+ }
2562
+ /**
2563
+ * Send a ping.
2564
+ *
2565
+ * @param {*} [data] The data to send
2566
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2567
+ * @param {Function} [cb] Callback which is executed when the ping is sent
2568
+ * @public
2569
+ */
2570
+ ping(data, mask, cb) {
2571
+ if (this.readyState === _WebSocket.CONNECTING) {
2572
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2573
+ }
2574
+ if (typeof data === "function") {
2575
+ cb = data;
2576
+ data = mask = void 0;
2577
+ } else if (typeof mask === "function") {
2578
+ cb = mask;
2579
+ mask = void 0;
2580
+ }
2581
+ if (typeof data === "number") data = data.toString();
2582
+ if (this.readyState !== _WebSocket.OPEN) {
2583
+ sendAfterClose(this, data, cb);
2584
+ return;
2585
+ }
2586
+ if (mask === void 0) mask = !this._isServer;
2587
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2588
+ }
2589
+ /**
2590
+ * Send a pong.
2591
+ *
2592
+ * @param {*} [data] The data to send
2593
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2594
+ * @param {Function} [cb] Callback which is executed when the pong is sent
2595
+ * @public
2596
+ */
2597
+ pong(data, mask, cb) {
2598
+ if (this.readyState === _WebSocket.CONNECTING) {
2599
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2600
+ }
2601
+ if (typeof data === "function") {
2602
+ cb = data;
2603
+ data = mask = void 0;
2604
+ } else if (typeof mask === "function") {
2605
+ cb = mask;
2606
+ mask = void 0;
2607
+ }
2608
+ if (typeof data === "number") data = data.toString();
2609
+ if (this.readyState !== _WebSocket.OPEN) {
2610
+ sendAfterClose(this, data, cb);
2611
+ return;
2612
+ }
2613
+ if (mask === void 0) mask = !this._isServer;
2614
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2615
+ }
2616
+ /**
2617
+ * Resume the socket.
2618
+ *
2619
+ * @public
2620
+ */
2621
+ resume() {
2622
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2623
+ return;
2624
+ }
2625
+ this._paused = false;
2626
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
2627
+ }
2628
+ /**
2629
+ * Send a data message.
2630
+ *
2631
+ * @param {*} data The message to send
2632
+ * @param {Object} [options] Options object
2633
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2634
+ * text
2635
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
2636
+ * `data`
2637
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2638
+ * last one
2639
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2640
+ * @param {Function} [cb] Callback which is executed when data is written out
2641
+ * @public
2642
+ */
2643
+ send(data, options, cb) {
2644
+ if (this.readyState === _WebSocket.CONNECTING) {
2645
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2646
+ }
2647
+ if (typeof options === "function") {
2648
+ cb = options;
2649
+ options = {};
2650
+ }
2651
+ if (typeof data === "number") data = data.toString();
2652
+ if (this.readyState !== _WebSocket.OPEN) {
2653
+ sendAfterClose(this, data, cb);
2654
+ return;
2655
+ }
2656
+ const opts = __spreadValues({
2657
+ binary: typeof data !== "string",
2658
+ mask: !this._isServer,
2659
+ compress: true,
2660
+ fin: true
2661
+ }, options);
2662
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
2663
+ opts.compress = false;
2664
+ }
2665
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
2666
+ }
2667
+ /**
2668
+ * Forcibly close the connection.
2669
+ *
2670
+ * @public
2671
+ */
2672
+ terminate() {
2673
+ if (this.readyState === _WebSocket.CLOSED) return;
2674
+ if (this.readyState === _WebSocket.CONNECTING) {
2675
+ const msg = "WebSocket was closed before the connection was established";
2676
+ abortHandshake(this, this._req, msg);
2677
+ return;
2678
+ }
2679
+ if (this._socket) {
2680
+ this._readyState = _WebSocket.CLOSING;
2681
+ this._socket.destroy();
2682
+ }
2683
+ }
2684
+ };
2685
+ Object.defineProperty(WebSocket3, "CONNECTING", {
2686
+ enumerable: true,
2687
+ value: readyStates.indexOf("CONNECTING")
2688
+ });
2689
+ Object.defineProperty(WebSocket3.prototype, "CONNECTING", {
2690
+ enumerable: true,
2691
+ value: readyStates.indexOf("CONNECTING")
2692
+ });
2693
+ Object.defineProperty(WebSocket3, "OPEN", {
2694
+ enumerable: true,
2695
+ value: readyStates.indexOf("OPEN")
2696
+ });
2697
+ Object.defineProperty(WebSocket3.prototype, "OPEN", {
2698
+ enumerable: true,
2699
+ value: readyStates.indexOf("OPEN")
2700
+ });
2701
+ Object.defineProperty(WebSocket3, "CLOSING", {
2702
+ enumerable: true,
2703
+ value: readyStates.indexOf("CLOSING")
2704
+ });
2705
+ Object.defineProperty(WebSocket3.prototype, "CLOSING", {
2706
+ enumerable: true,
2707
+ value: readyStates.indexOf("CLOSING")
2708
+ });
2709
+ Object.defineProperty(WebSocket3, "CLOSED", {
2710
+ enumerable: true,
2711
+ value: readyStates.indexOf("CLOSED")
2712
+ });
2713
+ Object.defineProperty(WebSocket3.prototype, "CLOSED", {
2714
+ enumerable: true,
2715
+ value: readyStates.indexOf("CLOSED")
2716
+ });
2717
+ [
2718
+ "binaryType",
2719
+ "bufferedAmount",
2720
+ "extensions",
2721
+ "isPaused",
2722
+ "protocol",
2723
+ "readyState",
2724
+ "url"
2725
+ ].forEach((property) => {
2726
+ Object.defineProperty(WebSocket3.prototype, property, { enumerable: true });
2727
+ });
2728
+ ["open", "error", "close", "message"].forEach((method) => {
2729
+ Object.defineProperty(WebSocket3.prototype, `on${method}`, {
2730
+ enumerable: true,
2731
+ get() {
2732
+ for (const listener of this.listeners(method)) {
2733
+ if (listener[kForOnEventAttribute]) return listener[kListener];
2734
+ }
2735
+ return null;
2736
+ },
2737
+ set(handler) {
2738
+ for (const listener of this.listeners(method)) {
2739
+ if (listener[kForOnEventAttribute]) {
2740
+ this.removeListener(method, listener);
2741
+ break;
2742
+ }
2743
+ }
2744
+ if (typeof handler !== "function") return;
2745
+ this.addEventListener(method, handler, {
2746
+ [kForOnEventAttribute]: true
2747
+ });
2748
+ }
2749
+ });
2750
+ });
2751
+ WebSocket3.prototype.addEventListener = addEventListener;
2752
+ WebSocket3.prototype.removeEventListener = removeEventListener;
2753
+ module2.exports = WebSocket3;
2754
+ function initAsClient(websocket, address, protocols, options) {
2755
+ const opts = __spreadProps(__spreadValues({
2756
+ allowSynchronousEvents: true,
2757
+ autoPong: true,
2758
+ protocolVersion: protocolVersions[1],
2759
+ maxPayload: 100 * 1024 * 1024,
2760
+ skipUTF8Validation: false,
2761
+ perMessageDeflate: true,
2762
+ followRedirects: false,
2763
+ maxRedirects: 10
2764
+ }, options), {
2765
+ socketPath: void 0,
2766
+ hostname: void 0,
2767
+ protocol: void 0,
2768
+ timeout: void 0,
2769
+ method: "GET",
2770
+ host: void 0,
2771
+ path: void 0,
2772
+ port: void 0
2773
+ });
2774
+ websocket._autoPong = opts.autoPong;
2775
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2776
+ throw new RangeError(
2777
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2778
+ );
2779
+ }
2780
+ let parsedUrl;
2781
+ if (address instanceof URL2) {
2782
+ parsedUrl = address;
2783
+ } else {
2784
+ try {
2785
+ parsedUrl = new URL2(address);
2786
+ } catch (e) {
2787
+ throw new SyntaxError(`Invalid URL: ${address}`);
2788
+ }
2789
+ }
2790
+ if (parsedUrl.protocol === "http:") {
2791
+ parsedUrl.protocol = "ws:";
2792
+ } else if (parsedUrl.protocol === "https:") {
2793
+ parsedUrl.protocol = "wss:";
2794
+ }
2795
+ websocket._url = parsedUrl.href;
2796
+ const isSecure = parsedUrl.protocol === "wss:";
2797
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2798
+ let invalidUrlMessage;
2799
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2800
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"`;
2801
+ } else if (isIpcUrl && !parsedUrl.pathname) {
2802
+ invalidUrlMessage = "The URL's pathname is empty";
2803
+ } else if (parsedUrl.hash) {
2804
+ invalidUrlMessage = "The URL contains a fragment identifier";
2805
+ }
2806
+ if (invalidUrlMessage) {
2807
+ const err = new SyntaxError(invalidUrlMessage);
2808
+ if (websocket._redirects === 0) {
2809
+ throw err;
2810
+ } else {
2811
+ emitErrorAndClose(websocket, err);
2812
+ return;
2813
+ }
2814
+ }
2815
+ const defaultPort = isSecure ? 443 : 80;
2816
+ const key = randomBytes(16).toString("base64");
2817
+ const request = isSecure ? https.request : http.request;
2818
+ const protocolSet = /* @__PURE__ */ new Set();
2819
+ let perMessageDeflate;
2820
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2821
+ opts.defaultPort = opts.defaultPort || defaultPort;
2822
+ opts.port = parsedUrl.port || defaultPort;
2823
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2824
+ opts.headers = __spreadProps(__spreadValues({}, opts.headers), {
2825
+ "Sec-WebSocket-Version": opts.protocolVersion,
2826
+ "Sec-WebSocket-Key": key,
2827
+ Connection: "Upgrade",
2828
+ Upgrade: "websocket"
2829
+ });
2830
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2831
+ opts.timeout = opts.handshakeTimeout;
2832
+ if (opts.perMessageDeflate) {
2833
+ perMessageDeflate = new PerMessageDeflate(
2834
+ opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
2835
+ false,
2836
+ opts.maxPayload
2837
+ );
2838
+ opts.headers["Sec-WebSocket-Extensions"] = format({
2839
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
2840
+ });
2841
+ }
2842
+ if (protocols.length) {
2843
+ for (const protocol of protocols) {
2844
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2845
+ throw new SyntaxError(
2846
+ "An invalid or duplicated subprotocol was specified"
2847
+ );
2848
+ }
2849
+ protocolSet.add(protocol);
2850
+ }
2851
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2852
+ }
2853
+ if (opts.origin) {
2854
+ if (opts.protocolVersion < 13) {
2855
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2856
+ } else {
2857
+ opts.headers.Origin = opts.origin;
2858
+ }
2859
+ }
2860
+ if (parsedUrl.username || parsedUrl.password) {
2861
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2862
+ }
2863
+ if (isIpcUrl) {
2864
+ const parts = opts.path.split(":");
2865
+ opts.socketPath = parts[0];
2866
+ opts.path = parts[1];
2867
+ }
2868
+ let req;
2869
+ if (opts.followRedirects) {
2870
+ if (websocket._redirects === 0) {
2871
+ websocket._originalIpc = isIpcUrl;
2872
+ websocket._originalSecure = isSecure;
2873
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2874
+ const headers = options && options.headers;
2875
+ options = __spreadProps(__spreadValues({}, options), { headers: {} });
2876
+ if (headers) {
2877
+ for (const [key2, value] of Object.entries(headers)) {
2878
+ options.headers[key2.toLowerCase()] = value;
2879
+ }
2880
+ }
2881
+ } else if (websocket.listenerCount("redirect") === 0) {
2882
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2883
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2884
+ delete opts.headers.authorization;
2885
+ delete opts.headers.cookie;
2886
+ if (!isSameHost) delete opts.headers.host;
2887
+ opts.auth = void 0;
2888
+ }
2889
+ }
2890
+ if (opts.auth && !options.headers.authorization) {
2891
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2892
+ }
2893
+ req = websocket._req = request(opts);
2894
+ if (websocket._redirects) {
2895
+ websocket.emit("redirect", websocket.url, req);
2896
+ }
2897
+ } else {
2898
+ req = websocket._req = request(opts);
2899
+ }
2900
+ if (opts.timeout) {
2901
+ req.on("timeout", () => {
2902
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2903
+ });
2904
+ }
2905
+ req.on("error", (err) => {
2906
+ if (req === null || req[kAborted]) return;
2907
+ req = websocket._req = null;
2908
+ emitErrorAndClose(websocket, err);
2909
+ });
2910
+ req.on("response", (res) => {
2911
+ const location = res.headers.location;
2912
+ const statusCode = res.statusCode;
2913
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2914
+ if (++websocket._redirects > opts.maxRedirects) {
2915
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2916
+ return;
2917
+ }
2918
+ req.abort();
2919
+ let addr;
2920
+ try {
2921
+ addr = new URL2(location, address);
2922
+ } catch (e) {
2923
+ const err = new SyntaxError(`Invalid URL: ${location}`);
2924
+ emitErrorAndClose(websocket, err);
2925
+ return;
2926
+ }
2927
+ initAsClient(websocket, addr, protocols, options);
2928
+ } else if (!websocket.emit("unexpected-response", req, res)) {
2929
+ abortHandshake(
2930
+ websocket,
2931
+ req,
2932
+ `Unexpected server response: ${res.statusCode}`
2933
+ );
2934
+ }
2935
+ });
2936
+ req.on("upgrade", (res, socket, head) => {
2937
+ websocket.emit("upgrade", res);
2938
+ if (websocket.readyState !== WebSocket3.CONNECTING) return;
2939
+ req = websocket._req = null;
2940
+ const upgrade = res.headers.upgrade;
2941
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2942
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
2943
+ return;
2944
+ }
2945
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
2946
+ if (res.headers["sec-websocket-accept"] !== digest) {
2947
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2948
+ return;
2949
+ }
2950
+ const serverProt = res.headers["sec-websocket-protocol"];
2951
+ let protError;
2952
+ if (serverProt !== void 0) {
2953
+ if (!protocolSet.size) {
2954
+ protError = "Server sent a subprotocol but none was requested";
2955
+ } else if (!protocolSet.has(serverProt)) {
2956
+ protError = "Server sent an invalid subprotocol";
2957
+ }
2958
+ } else if (protocolSet.size) {
2959
+ protError = "Server sent no subprotocol";
2960
+ }
2961
+ if (protError) {
2962
+ abortHandshake(websocket, socket, protError);
2963
+ return;
2964
+ }
2965
+ if (serverProt) websocket._protocol = serverProt;
2966
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2967
+ if (secWebSocketExtensions !== void 0) {
2968
+ if (!perMessageDeflate) {
2969
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2970
+ abortHandshake(websocket, socket, message);
2971
+ return;
2972
+ }
2973
+ let extensions;
2974
+ try {
2975
+ extensions = parse(secWebSocketExtensions);
2976
+ } catch (err) {
2977
+ const message = "Invalid Sec-WebSocket-Extensions header";
2978
+ abortHandshake(websocket, socket, message);
2979
+ return;
2980
+ }
2981
+ const extensionNames = Object.keys(extensions);
2982
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
2983
+ const message = "Server indicated an extension that was not requested";
2984
+ abortHandshake(websocket, socket, message);
2985
+ return;
2986
+ }
2987
+ try {
2988
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2989
+ } catch (err) {
2990
+ const message = "Invalid Sec-WebSocket-Extensions header";
2991
+ abortHandshake(websocket, socket, message);
2992
+ return;
2993
+ }
2994
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2995
+ }
2996
+ websocket.setSocket(socket, head, {
2997
+ allowSynchronousEvents: opts.allowSynchronousEvents,
2998
+ generateMask: opts.generateMask,
2999
+ maxPayload: opts.maxPayload,
3000
+ skipUTF8Validation: opts.skipUTF8Validation
3001
+ });
3002
+ });
3003
+ if (opts.finishRequest) {
3004
+ opts.finishRequest(req, websocket);
3005
+ } else {
3006
+ req.end();
3007
+ }
3008
+ }
3009
+ function emitErrorAndClose(websocket, err) {
3010
+ websocket._readyState = WebSocket3.CLOSING;
3011
+ websocket.emit("error", err);
3012
+ websocket.emitClose();
3013
+ }
3014
+ function netConnect(options) {
3015
+ options.path = options.socketPath;
3016
+ return net.connect(options);
3017
+ }
3018
+ function tlsConnect(options) {
3019
+ options.path = void 0;
3020
+ if (!options.servername && options.servername !== "") {
3021
+ options.servername = net.isIP(options.host) ? "" : options.host;
3022
+ }
3023
+ return tls.connect(options);
3024
+ }
3025
+ function abortHandshake(websocket, stream, message) {
3026
+ websocket._readyState = WebSocket3.CLOSING;
3027
+ const err = new Error(message);
3028
+ Error.captureStackTrace(err, abortHandshake);
3029
+ if (stream.setHeader) {
3030
+ stream[kAborted] = true;
3031
+ stream.abort();
3032
+ if (stream.socket && !stream.socket.destroyed) {
3033
+ stream.socket.destroy();
3034
+ }
3035
+ process.nextTick(emitErrorAndClose, websocket, err);
3036
+ } else {
3037
+ stream.destroy(err);
3038
+ stream.once("error", websocket.emit.bind(websocket, "error"));
3039
+ stream.once("close", websocket.emitClose.bind(websocket));
3040
+ }
3041
+ }
3042
+ function sendAfterClose(websocket, data, cb) {
3043
+ if (data) {
3044
+ const length = toBuffer(data).length;
3045
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
3046
+ else websocket._bufferedAmount += length;
3047
+ }
3048
+ if (cb) {
3049
+ const err = new Error(
3050
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
3051
+ );
3052
+ process.nextTick(cb, err);
3053
+ }
3054
+ }
3055
+ function receiverOnConclude(code, reason) {
3056
+ const websocket = this[kWebSocket];
3057
+ websocket._closeFrameReceived = true;
3058
+ websocket._closeMessage = reason;
3059
+ websocket._closeCode = code;
3060
+ if (websocket._socket[kWebSocket] === void 0) return;
3061
+ websocket._socket.removeListener("data", socketOnData);
3062
+ process.nextTick(resume, websocket._socket);
3063
+ if (code === 1005) websocket.close();
3064
+ else websocket.close(code, reason);
3065
+ }
3066
+ function receiverOnDrain() {
3067
+ const websocket = this[kWebSocket];
3068
+ if (!websocket.isPaused) websocket._socket.resume();
3069
+ }
3070
+ function receiverOnError(err) {
3071
+ const websocket = this[kWebSocket];
3072
+ if (websocket._socket[kWebSocket] !== void 0) {
3073
+ websocket._socket.removeListener("data", socketOnData);
3074
+ process.nextTick(resume, websocket._socket);
3075
+ websocket.close(err[kStatusCode]);
3076
+ }
3077
+ websocket.emit("error", err);
3078
+ }
3079
+ function receiverOnFinish() {
3080
+ this[kWebSocket].emitClose();
3081
+ }
3082
+ function receiverOnMessage(data, isBinary) {
3083
+ this[kWebSocket].emit("message", data, isBinary);
3084
+ }
3085
+ function receiverOnPing(data) {
3086
+ const websocket = this[kWebSocket];
3087
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3088
+ websocket.emit("ping", data);
3089
+ }
3090
+ function receiverOnPong(data) {
3091
+ this[kWebSocket].emit("pong", data);
3092
+ }
3093
+ function resume(stream) {
3094
+ stream.resume();
3095
+ }
3096
+ function socketOnClose() {
3097
+ const websocket = this[kWebSocket];
3098
+ this.removeListener("close", socketOnClose);
3099
+ this.removeListener("data", socketOnData);
3100
+ this.removeListener("end", socketOnEnd);
3101
+ websocket._readyState = WebSocket3.CLOSING;
3102
+ let chunk;
3103
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
3104
+ websocket._receiver.write(chunk);
3105
+ }
3106
+ websocket._receiver.end();
3107
+ this[kWebSocket] = void 0;
3108
+ clearTimeout(websocket._closeTimer);
3109
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3110
+ websocket.emitClose();
3111
+ } else {
3112
+ websocket._receiver.on("error", receiverOnFinish);
3113
+ websocket._receiver.on("finish", receiverOnFinish);
3114
+ }
3115
+ }
3116
+ function socketOnData(chunk) {
3117
+ if (!this[kWebSocket]._receiver.write(chunk)) {
3118
+ this.pause();
3119
+ }
3120
+ }
3121
+ function socketOnEnd() {
3122
+ const websocket = this[kWebSocket];
3123
+ websocket._readyState = WebSocket3.CLOSING;
3124
+ websocket._receiver.end();
3125
+ this.end();
3126
+ }
3127
+ function socketOnError() {
3128
+ const websocket = this[kWebSocket];
3129
+ this.removeListener("error", socketOnError);
3130
+ this.on("error", NOOP);
3131
+ if (websocket) {
3132
+ websocket._readyState = WebSocket3.CLOSING;
3133
+ this.destroy();
3134
+ }
3135
+ }
3136
+ }
3137
+ });
3138
+
3139
+ // node_modules/ws/lib/subprotocol.js
3140
+ var require_subprotocol = __commonJS({
3141
+ "node_modules/ws/lib/subprotocol.js"(exports2, module2) {
3142
+ "use strict";
3143
+ var { tokenChars } = require_validation();
3144
+ function parse(header) {
3145
+ const protocols = /* @__PURE__ */ new Set();
3146
+ let start = -1;
3147
+ let end = -1;
3148
+ let i = 0;
3149
+ for (i; i < header.length; i++) {
3150
+ const code = header.charCodeAt(i);
3151
+ if (end === -1 && tokenChars[code] === 1) {
3152
+ if (start === -1) start = i;
3153
+ } else if (i !== 0 && (code === 32 || code === 9)) {
3154
+ if (end === -1 && start !== -1) end = i;
3155
+ } else if (code === 44) {
3156
+ if (start === -1) {
3157
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3158
+ }
3159
+ if (end === -1) end = i;
3160
+ const protocol2 = header.slice(start, end);
3161
+ if (protocols.has(protocol2)) {
3162
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3163
+ }
3164
+ protocols.add(protocol2);
3165
+ start = end = -1;
3166
+ } else {
3167
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3168
+ }
3169
+ }
3170
+ if (start === -1 || end !== -1) {
3171
+ throw new SyntaxError("Unexpected end of input");
3172
+ }
3173
+ const protocol = header.slice(start, i);
3174
+ if (protocols.has(protocol)) {
3175
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3176
+ }
3177
+ protocols.add(protocol);
3178
+ return protocols;
3179
+ }
3180
+ module2.exports = { parse };
3181
+ }
3182
+ });
3183
+
3184
+ // node_modules/ws/lib/websocket-server.js
3185
+ var require_websocket_server = __commonJS({
3186
+ "node_modules/ws/lib/websocket-server.js"(exports2, module2) {
3187
+ "use strict";
3188
+ var EventEmitter = require("events");
3189
+ var http = require("http");
3190
+ var { Duplex } = require("stream");
3191
+ var { createHash } = require("crypto");
3192
+ var extension = require_extension();
3193
+ var PerMessageDeflate = require_permessage_deflate();
3194
+ var subprotocol = require_subprotocol();
3195
+ var WebSocket3 = require_websocket();
3196
+ var { GUID, kWebSocket } = require_constants();
3197
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3198
+ var RUNNING = 0;
3199
+ var CLOSING = 1;
3200
+ var CLOSED = 2;
3201
+ var WebSocketServer2 = class extends EventEmitter {
3202
+ /**
3203
+ * Create a `WebSocketServer` instance.
3204
+ *
3205
+ * @param {Object} options Configuration options
3206
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3207
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3208
+ * multiple times in the same tick
3209
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3210
+ * automatically send a pong in response to a ping
3211
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
3212
+ * pending connections
3213
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3214
+ * track clients
3215
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
3216
+ * @param {String} [options.host] The hostname where to bind the server
3217
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3218
+ * size
3219
+ * @param {Boolean} [options.noServer=false] Enable no server mode
3220
+ * @param {String} [options.path] Accept only connections matching this path
3221
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3222
+ * permessage-deflate
3223
+ * @param {Number} [options.port] The port where to bind the server
3224
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3225
+ * server to use
3226
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3227
+ * not to skip UTF-8 validation for text and close messages
3228
+ * @param {Function} [options.verifyClient] A hook to reject connections
3229
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3230
+ * class to use. It must be the `WebSocket` class or class that extends it
3231
+ * @param {Function} [callback] A listener for the `listening` event
3232
+ */
3233
+ constructor(options, callback) {
3234
+ super();
3235
+ options = __spreadValues({
3236
+ allowSynchronousEvents: true,
3237
+ autoPong: true,
3238
+ maxPayload: 100 * 1024 * 1024,
3239
+ skipUTF8Validation: false,
3240
+ perMessageDeflate: false,
3241
+ handleProtocols: null,
3242
+ clientTracking: true,
3243
+ verifyClient: null,
3244
+ noServer: false,
3245
+ backlog: null,
3246
+ // use default (511 as implemented in net.js)
3247
+ server: null,
3248
+ host: null,
3249
+ path: null,
3250
+ port: null,
3251
+ WebSocket: WebSocket3
3252
+ }, options);
3253
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
3254
+ throw new TypeError(
3255
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
3256
+ );
3257
+ }
3258
+ if (options.port != null) {
3259
+ this._server = http.createServer((req, res) => {
3260
+ const body = http.STATUS_CODES[426];
3261
+ res.writeHead(426, {
3262
+ "Content-Length": body.length,
3263
+ "Content-Type": "text/plain"
3264
+ });
3265
+ res.end(body);
3266
+ });
3267
+ this._server.listen(
3268
+ options.port,
3269
+ options.host,
3270
+ options.backlog,
3271
+ callback
3272
+ );
3273
+ } else if (options.server) {
3274
+ this._server = options.server;
3275
+ }
3276
+ if (this._server) {
3277
+ const emitConnection = this.emit.bind(this, "connection");
3278
+ this._removeListeners = addListeners(this._server, {
3279
+ listening: this.emit.bind(this, "listening"),
3280
+ error: this.emit.bind(this, "error"),
3281
+ upgrade: (req, socket, head) => {
3282
+ this.handleUpgrade(req, socket, head, emitConnection);
3283
+ }
3284
+ });
3285
+ }
3286
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3287
+ if (options.clientTracking) {
3288
+ this.clients = /* @__PURE__ */ new Set();
3289
+ this._shouldEmitClose = false;
3290
+ }
3291
+ this.options = options;
3292
+ this._state = RUNNING;
3293
+ }
3294
+ /**
3295
+ * Returns the bound address, the address family name, and port of the server
3296
+ * as reported by the operating system if listening on an IP socket.
3297
+ * If the server is listening on a pipe or UNIX domain socket, the name is
3298
+ * returned as a string.
3299
+ *
3300
+ * @return {(Object|String|null)} The address of the server
3301
+ * @public
3302
+ */
3303
+ address() {
3304
+ if (this.options.noServer) {
3305
+ throw new Error('The server is operating in "noServer" mode');
3306
+ }
3307
+ if (!this._server) return null;
3308
+ return this._server.address();
3309
+ }
3310
+ /**
3311
+ * Stop the server from accepting new connections and emit the `'close'` event
3312
+ * when all existing connections are closed.
3313
+ *
3314
+ * @param {Function} [cb] A one-time listener for the `'close'` event
3315
+ * @public
3316
+ */
3317
+ close(cb) {
3318
+ if (this._state === CLOSED) {
3319
+ if (cb) {
3320
+ this.once("close", () => {
3321
+ cb(new Error("The server is not running"));
3322
+ });
3323
+ }
3324
+ process.nextTick(emitClose, this);
3325
+ return;
3326
+ }
3327
+ if (cb) this.once("close", cb);
3328
+ if (this._state === CLOSING) return;
3329
+ this._state = CLOSING;
3330
+ if (this.options.noServer || this.options.server) {
3331
+ if (this._server) {
3332
+ this._removeListeners();
3333
+ this._removeListeners = this._server = null;
3334
+ }
3335
+ if (this.clients) {
3336
+ if (!this.clients.size) {
3337
+ process.nextTick(emitClose, this);
3338
+ } else {
3339
+ this._shouldEmitClose = true;
3340
+ }
3341
+ } else {
3342
+ process.nextTick(emitClose, this);
3343
+ }
3344
+ } else {
3345
+ const server = this._server;
3346
+ this._removeListeners();
3347
+ this._removeListeners = this._server = null;
3348
+ server.close(() => {
3349
+ emitClose(this);
3350
+ });
3351
+ }
3352
+ }
3353
+ /**
3354
+ * See if a given request should be handled by this server instance.
3355
+ *
3356
+ * @param {http.IncomingMessage} req Request object to inspect
3357
+ * @return {Boolean} `true` if the request is valid, else `false`
3358
+ * @public
3359
+ */
3360
+ shouldHandle(req) {
3361
+ if (this.options.path) {
3362
+ const index = req.url.indexOf("?");
3363
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3364
+ if (pathname !== this.options.path) return false;
3365
+ }
3366
+ return true;
3367
+ }
3368
+ /**
3369
+ * Handle a HTTP Upgrade request.
3370
+ *
3371
+ * @param {http.IncomingMessage} req The request object
3372
+ * @param {Duplex} socket The network socket between the server and client
3373
+ * @param {Buffer} head The first packet of the upgraded stream
3374
+ * @param {Function} cb Callback
3375
+ * @public
3376
+ */
3377
+ handleUpgrade(req, socket, head, cb) {
3378
+ socket.on("error", socketOnError);
3379
+ const key = req.headers["sec-websocket-key"];
3380
+ const upgrade = req.headers.upgrade;
3381
+ const version = +req.headers["sec-websocket-version"];
3382
+ if (req.method !== "GET") {
3383
+ const message = "Invalid HTTP method";
3384
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3385
+ return;
3386
+ }
3387
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3388
+ const message = "Invalid Upgrade header";
3389
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3390
+ return;
3391
+ }
3392
+ if (key === void 0 || !keyRegex.test(key)) {
3393
+ const message = "Missing or invalid Sec-WebSocket-Key header";
3394
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3395
+ return;
3396
+ }
3397
+ if (version !== 8 && version !== 13) {
3398
+ const message = "Missing or invalid Sec-WebSocket-Version header";
3399
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3400
+ return;
3401
+ }
3402
+ if (!this.shouldHandle(req)) {
3403
+ abortHandshake(socket, 400);
3404
+ return;
3405
+ }
3406
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3407
+ let protocols = /* @__PURE__ */ new Set();
3408
+ if (secWebSocketProtocol !== void 0) {
3409
+ try {
3410
+ protocols = subprotocol.parse(secWebSocketProtocol);
3411
+ } catch (err) {
3412
+ const message = "Invalid Sec-WebSocket-Protocol header";
3413
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3414
+ return;
3415
+ }
3416
+ }
3417
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3418
+ const extensions = {};
3419
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3420
+ const perMessageDeflate = new PerMessageDeflate(
3421
+ this.options.perMessageDeflate,
3422
+ true,
3423
+ this.options.maxPayload
3424
+ );
3425
+ try {
3426
+ const offers = extension.parse(secWebSocketExtensions);
3427
+ if (offers[PerMessageDeflate.extensionName]) {
3428
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
3429
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
3430
+ }
3431
+ } catch (err) {
3432
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3433
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3434
+ return;
3435
+ }
3436
+ }
3437
+ if (this.options.verifyClient) {
3438
+ const info = {
3439
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3440
+ secure: !!(req.socket.authorized || req.socket.encrypted),
3441
+ req
3442
+ };
3443
+ if (this.options.verifyClient.length === 2) {
3444
+ this.options.verifyClient(info, (verified, code, message, headers) => {
3445
+ if (!verified) {
3446
+ return abortHandshake(socket, code || 401, message, headers);
3447
+ }
3448
+ this.completeUpgrade(
3449
+ extensions,
3450
+ key,
3451
+ protocols,
3452
+ req,
3453
+ socket,
3454
+ head,
3455
+ cb
3456
+ );
3457
+ });
3458
+ return;
3459
+ }
3460
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3461
+ }
3462
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3463
+ }
3464
+ /**
3465
+ * Upgrade the connection to WebSocket.
3466
+ *
3467
+ * @param {Object} extensions The accepted extensions
3468
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
3469
+ * @param {Set} protocols The subprotocols
3470
+ * @param {http.IncomingMessage} req The request object
3471
+ * @param {Duplex} socket The network socket between the server and client
3472
+ * @param {Buffer} head The first packet of the upgraded stream
3473
+ * @param {Function} cb Callback
3474
+ * @throws {Error} If called more than once with the same socket
3475
+ * @private
3476
+ */
3477
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3478
+ if (!socket.readable || !socket.writable) return socket.destroy();
3479
+ if (socket[kWebSocket]) {
3480
+ throw new Error(
3481
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
3482
+ );
3483
+ }
3484
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
3485
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
3486
+ const headers = [
3487
+ "HTTP/1.1 101 Switching Protocols",
3488
+ "Upgrade: websocket",
3489
+ "Connection: Upgrade",
3490
+ `Sec-WebSocket-Accept: ${digest}`
3491
+ ];
3492
+ const ws = new this.options.WebSocket(null, void 0, this.options);
3493
+ if (protocols.size) {
3494
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3495
+ if (protocol) {
3496
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3497
+ ws._protocol = protocol;
3498
+ }
3499
+ }
3500
+ if (extensions[PerMessageDeflate.extensionName]) {
3501
+ const params = extensions[PerMessageDeflate.extensionName].params;
3502
+ const value = extension.format({
3503
+ [PerMessageDeflate.extensionName]: [params]
3504
+ });
3505
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
3506
+ ws._extensions = extensions;
3507
+ }
3508
+ this.emit("headers", headers, req);
3509
+ socket.write(headers.concat("\r\n").join("\r\n"));
3510
+ socket.removeListener("error", socketOnError);
3511
+ ws.setSocket(socket, head, {
3512
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
3513
+ maxPayload: this.options.maxPayload,
3514
+ skipUTF8Validation: this.options.skipUTF8Validation
3515
+ });
3516
+ if (this.clients) {
3517
+ this.clients.add(ws);
3518
+ ws.on("close", () => {
3519
+ this.clients.delete(ws);
3520
+ if (this._shouldEmitClose && !this.clients.size) {
3521
+ process.nextTick(emitClose, this);
3522
+ }
3523
+ });
3524
+ }
3525
+ cb(ws, req);
3526
+ }
3527
+ };
3528
+ module2.exports = WebSocketServer2;
3529
+ function addListeners(server, map) {
3530
+ for (const event of Object.keys(map)) server.on(event, map[event]);
3531
+ return function removeListeners() {
3532
+ for (const event of Object.keys(map)) {
3533
+ server.removeListener(event, map[event]);
3534
+ }
3535
+ };
3536
+ }
3537
+ function emitClose(server) {
3538
+ server._state = CLOSED;
3539
+ server.emit("close");
3540
+ }
3541
+ function socketOnError() {
3542
+ this.destroy();
3543
+ }
3544
+ function abortHandshake(socket, code, message, headers) {
3545
+ message = message || http.STATUS_CODES[code];
3546
+ headers = __spreadValues({
3547
+ Connection: "close",
3548
+ "Content-Type": "text/html",
3549
+ "Content-Length": Buffer.byteLength(message)
3550
+ }, headers);
3551
+ socket.once("finish", socket.destroy);
3552
+ socket.end(
3553
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
3554
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
3555
+ );
3556
+ }
3557
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
3558
+ if (server.listenerCount("wsClientError")) {
3559
+ const err = new Error(message);
3560
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3561
+ server.emit("wsClientError", err, socket, req);
3562
+ } else {
3563
+ abortHandshake(socket, code, message);
3564
+ }
3565
+ }
3566
+ }
3567
+ });
3568
+
3569
+ // node_modules/ws/wrapper.mjs
3570
+ var wrapper_exports = {};
3571
+ __export(wrapper_exports, {
3572
+ Receiver: () => import_receiver.default,
3573
+ Sender: () => import_sender.default,
3574
+ WebSocket: () => import_websocket.default,
3575
+ WebSocketServer: () => import_websocket_server.default,
3576
+ createWebSocketStream: () => import_stream.default,
3577
+ default: () => wrapper_default
3578
+ });
3579
+ var import_stream, import_receiver, import_sender, import_websocket, import_websocket_server, wrapper_default;
3580
+ var init_wrapper = __esm({
3581
+ "node_modules/ws/wrapper.mjs"() {
3582
+ "use strict";
3583
+ import_stream = __toESM(require_stream(), 1);
3584
+ import_receiver = __toESM(require_receiver(), 1);
3585
+ import_sender = __toESM(require_sender(), 1);
3586
+ import_websocket = __toESM(require_websocket(), 1);
3587
+ import_websocket_server = __toESM(require_websocket_server(), 1);
3588
+ wrapper_default = import_websocket.default;
3589
+ }
3590
+ });
3591
+
3592
+ // src/index.ts
3593
+ var index_exports = {};
3594
+ __export(index_exports, {
3595
+ PaginatedResponse: () => PaginatedResponse,
3596
+ Storage: () => Storage,
3597
+ assignRole: () => assignRole,
3598
+ changePassword: () => changePassword,
3599
+ createRole: () => createRole,
3600
+ createService: () => createService,
3601
+ db: () => db,
3602
+ deleteRole: () => deleteRole,
3603
+ deleteService: () => deleteService,
3604
+ getAccessToken: () => getAccessToken,
3605
+ getProfile: () => getProfile,
3606
+ getRoles: () => getRoles,
3607
+ getServices: () => getServices,
3608
+ getUsers: () => getUsers,
3609
+ handleRedirectCallback: () => handleRedirectCallback,
3610
+ initializeSdk: () => initializeSdk,
3611
+ isLoggedIn: () => isLoggedIn,
3612
+ login: () => loginService,
3613
+ loginService: () => loginService,
3614
+ loginWithPassword: () => loginWithPassword,
3615
+ loginWithRedirect: () => loginWithRedirect,
3616
+ logout: () => logout,
3617
+ refreshTokens: () => refreshTokens,
3618
+ resetPassword: () => resetPassword,
3619
+ setAccessToken: () => setAccessToken,
3620
+ setRefreshToken: () => setRefreshToken,
3621
+ unassignRole: () => unassignRole,
3622
+ updateProfile: () => updateProfile,
3623
+ updateUser: () => updateUser,
3624
+ verifyServiceToken: () => verifyServiceToken,
3625
+ verifyToken: () => verifyToken
3626
+ });
3627
+ module.exports = __toCommonJS(index_exports);
3628
+
3629
+ // src/common/token.ts
3630
+ var _token, _type, _expiration;
3631
+ var Token = class {
3632
+ constructor(token, type, expiration) {
3633
+ __privateAdd(this, _token);
3634
+ __privateAdd(this, _type);
3635
+ __privateAdd(this, _expiration);
3636
+ __privateSet(this, _token, token);
3637
+ __privateSet(this, _type, type);
3638
+ if (expiration) {
3639
+ __privateSet(this, _expiration, expiration);
3640
+ } else {
3641
+ __privateSet(this, _expiration, this.decodeExpiration(token));
3642
+ }
3643
+ }
3644
+ decodeExpiration(token) {
3645
+ try {
3646
+ const payload = JSON.parse(atob(token.split(".")[1]));
3647
+ return payload.exp * 1e3;
3648
+ } catch (e) {
3649
+ return 0;
3650
+ }
3651
+ }
3652
+ /**
3653
+ * Getter for the raw token
3654
+ *
3655
+ * @returns {string} The token
3656
+ */
3657
+ value() {
3658
+ return __privateGet(this, _token);
3659
+ }
3660
+ /**
3661
+ * Checks if the token is valid
3662
+ *
3663
+ * @returns {boolean} True if the API key is valid, false otherwise
3664
+ */
3665
+ isValid() {
3666
+ return __privateGet(this, _expiration) > Date.now();
3667
+ }
3668
+ /**
3669
+ * Checks if the API key is a secret key
3670
+ *
3671
+ * @returns {boolean} True if the API key is a secret key, false otherwise
3672
+ */
3673
+ isAccessToken() {
3674
+ return __privateGet(this, _type) === "access";
3675
+ }
3676
+ /**
3677
+ * Checks if the API key is a public key
3678
+ *
3679
+ * @returns {boolean} True if the API key is a public key, false otherwise
3680
+ */
3681
+ isRefreshToken() {
3682
+ return __privateGet(this, _type) === "refresh";
3683
+ }
3684
+ };
3685
+ _token = new WeakMap();
3686
+ _type = new WeakMap();
3687
+ _expiration = new WeakMap();
3688
+
3689
+ // src/common/app.ts
3690
+ var import_oidc_client_ts = require("oidc-client-ts");
3691
+ var app = {
3692
+ projectId: "",
3693
+ baseUrl: "https://api.swiftbase.io",
3694
+ accessToken: null,
3695
+ refreshToken: null,
3696
+ debounceTimeout: 300,
3697
+ cacheArticles: true,
3698
+ searchCacheEnabled: true,
3699
+ searchCacheCapacity: 50,
3700
+ userManager: null
3701
+ };
3702
+ var initializeSdk = (projectId, options) => {
3703
+ app.projectId = projectId;
3704
+ if (options == null ? void 0 : options.baseUrl) {
3705
+ app.baseUrl = options.baseUrl.endsWith("/") ? options.baseUrl.slice(0, -1) : options.baseUrl;
3706
+ }
3707
+ if ((options == null ? void 0 : options.debounceTimeout) !== void 0) {
3708
+ app.debounceTimeout = options.debounceTimeout;
3709
+ }
3710
+ if ((options == null ? void 0 : options.cacheArticles) !== void 0) {
3711
+ app.cacheArticles = options.cacheArticles;
3712
+ }
3713
+ if ((options == null ? void 0 : options.searchCacheEnabled) !== void 0) {
3714
+ app.searchCacheEnabled = options.searchCacheEnabled;
3715
+ }
3716
+ if ((options == null ? void 0 : options.searchCacheCapacity) !== void 0) {
3717
+ app.searchCacheCapacity = options.searchCacheCapacity;
3718
+ }
3719
+ if (typeof window !== "undefined" && window.sessionStorage) {
3720
+ const accessToken = window.sessionStorage.getItem("swiftbase_access_token");
3721
+ const refreshToken = window.sessionStorage.getItem("swiftbase_refresh_token");
3722
+ if (accessToken) {
3723
+ app.accessToken = new Token(accessToken, "access");
3724
+ }
3725
+ if (refreshToken) {
3726
+ app.refreshToken = new Token(refreshToken, "refresh");
3727
+ }
3728
+ }
3729
+ if (typeof window !== "undefined") {
3730
+ app.userManager = new import_oidc_client_ts.UserManager({
3731
+ authority: app.baseUrl,
3732
+ client_id: app.projectId,
3733
+ redirect_uri: window.location.origin,
3734
+ response_type: "code",
3735
+ scope: "openid profile email",
3736
+ userStore: new import_oidc_client_ts.WebStorageStateStore({ store: window.sessionStorage }),
3737
+ automaticSilentRenew: true,
3738
+ filterProtocolClaims: true,
3739
+ loadUserInfo: true
3740
+ });
3741
+ app.userManager.events.addUserLoaded((user) => {
3742
+ console.log("[SDK] User loaded from UserManager");
3743
+ setAccessToken(user.access_token, user.expires_at ? user.expires_at * 1e3 : void 0);
3744
+ if (user.refresh_token) {
3745
+ setRefreshToken(user.refresh_token);
3746
+ }
3747
+ });
3748
+ app.userManager.events.addUserUnloaded(() => {
3749
+ console.log("[SDK] User unloaded from UserManager");
3750
+ setAccessToken("");
3751
+ setRefreshToken("");
3752
+ });
3753
+ }
3754
+ };
3755
+ var setAccessToken = (token, expiration) => {
3756
+ console.log("[SDK] setAccessToken called", !!token);
3757
+ if (!token || token === "null" || token === "undefined") {
3758
+ app.accessToken = null;
3759
+ if (typeof window !== "undefined" && window.sessionStorage) {
3760
+ window.sessionStorage.removeItem("swiftbase_access_token");
3761
+ }
3762
+ return;
3763
+ }
3764
+ app.accessToken = new Token(token, "access", expiration);
3765
+ if (typeof window !== "undefined" && window.sessionStorage) {
3766
+ window.sessionStorage.setItem("swiftbase_access_token", token);
3767
+ }
3768
+ };
3769
+ var setRefreshToken = (token, expiration) => {
3770
+ console.log("[SDK] setRefreshToken called", !!token);
3771
+ if (!token || token === "null" || token === "undefined") {
3772
+ app.refreshToken = null;
3773
+ if (typeof window !== "undefined" && window.sessionStorage) {
3774
+ window.sessionStorage.removeItem("swiftbase_refresh_token");
3775
+ }
3776
+ return;
3777
+ }
3778
+ app.refreshToken = new Token(token, "refresh", expiration);
3779
+ if (typeof window !== "undefined" && window.sessionStorage) {
3780
+ window.sessionStorage.setItem("swiftbase_refresh_token", token);
3781
+ }
3782
+ };
3783
+ var refreshTokens = () => __async(null, null, function* () {
3784
+ if (app.userManager) {
3785
+ try {
3786
+ yield app.userManager.signinSilent();
3787
+ return;
3788
+ } catch (e) {
3789
+ console.error("[SDK] signinSilent failed", e);
3790
+ }
3791
+ }
3792
+ if (!app.refreshToken) {
3793
+ throw new Error("No refresh token available");
3794
+ }
3795
+ const tokenUrl = `${app.baseUrl}/oauth2/token`;
3796
+ const response = yield fetch(tokenUrl, {
3797
+ method: "POST",
3798
+ headers: {
3799
+ "Content-Type": "application/x-www-form-urlencoded"
3800
+ },
3801
+ body: new URLSearchParams({
3802
+ grant_type: "refresh_token",
3803
+ client_id: app.projectId,
3804
+ refresh_token: app.refreshToken.value()
3805
+ })
3806
+ });
3807
+ if (!response.ok) {
3808
+ const errorData = yield response.json().catch(() => ({}));
3809
+ throw new Error(errorData.error_description || errorData.error || "Failed to refresh tokens");
3810
+ }
3811
+ const data = yield response.json();
3812
+ const expiresAt = Date.now() + data.expires_in * 1e3;
3813
+ setAccessToken(data.access_token, expiresAt);
3814
+ if (data.refresh_token) {
3815
+ const refreshExpiresAt = Date.now() + 30 * 24 * 60 * 60 * 1e3;
3816
+ setRefreshToken(data.refresh_token, refreshExpiresAt);
3817
+ }
3818
+ });
3819
+
3820
+ // src/auth/getaccesstoken.ts
3821
+ var getAccessToken = (forceRefresh = false) => __async(null, null, function* () {
3822
+ if (typeof window === "undefined" || !app.userManager) {
3823
+ return app.accessToken ? app.accessToken.value() : null;
3824
+ }
3825
+ let user = yield app.userManager.getUser();
3826
+ if (forceRefresh || !user || user.expired) {
3827
+ try {
3828
+ user = yield app.userManager.signinSilent();
3829
+ } catch (e) {
3830
+ console.warn("Failed to silently refresh token during getAccessToken", e);
3831
+ }
3832
+ }
3833
+ return user ? user.access_token : app.accessToken ? app.accessToken.value() : null;
3834
+ });
3835
+
3836
+ // src/common/makerequest.ts
3837
+ var Unauthorized = class _Unauthorized extends Error {
3838
+ constructor(msg) {
3839
+ super(msg);
3840
+ Object.setPrototypeOf(this, _Unauthorized.prototype);
3841
+ }
3842
+ };
3843
+ var Forbidden = class _Forbidden extends Error {
3844
+ constructor(msg) {
3845
+ super(msg);
3846
+ Object.setPrototypeOf(this, _Forbidden.prototype);
3847
+ }
3848
+ };
3849
+ var BadRequest = class _BadRequest extends Error {
3850
+ constructor(msg) {
3851
+ super(msg);
3852
+ Object.setPrototypeOf(this, _BadRequest.prototype);
3853
+ }
3854
+ };
3855
+ var TooManyRequests = class _TooManyRequests extends Error {
3856
+ constructor(msg) {
3857
+ super(msg);
3858
+ Object.setPrototypeOf(this, _TooManyRequests.prototype);
3859
+ }
3860
+ };
3861
+ var handleRequestError = (status) => {
3862
+ if (status === 401) {
3863
+ throw new Unauthorized("Unauthorized");
3864
+ } else if (status === 403) {
3865
+ throw new Forbidden("Forbidden");
3866
+ } else if (status === 400) {
3867
+ throw new BadRequest("Bad Request");
3868
+ } else if (status === 429) {
3869
+ throw new TooManyRequests("Too Many Requests");
3870
+ } else {
3871
+ throw new Error("Unexpected error");
3872
+ }
3873
+ };
3874
+ var _data, _meta;
3875
+ var PaginatedResponse = class {
3876
+ constructor(response) {
3877
+ __privateAdd(this, _data, []);
3878
+ __privateAdd(this, _meta);
3879
+ __privateSet(this, _data, response.data);
3880
+ __privateSet(this, _meta, response.meta);
3881
+ }
3882
+ get items() {
3883
+ return __privateGet(this, _data);
3884
+ }
3885
+ get total() {
3886
+ return __privateGet(this, _meta).total;
3887
+ }
3888
+ get page() {
3889
+ return __privateGet(this, _meta).page;
3890
+ }
3891
+ get limit() {
3892
+ return __privateGet(this, _meta).limit;
3893
+ }
3894
+ get hasNext() {
3895
+ return !!__privateGet(this, _meta).next;
3896
+ }
3897
+ get hasBack() {
3898
+ return !!__privateGet(this, _meta).back;
3899
+ }
3900
+ next() {
3901
+ return __async(this, null, function* () {
3902
+ if (!__privateGet(this, _meta).next) return null;
3903
+ return yield makeRequest("get" /* GET */, __privateGet(this, _meta).next);
3904
+ });
3905
+ }
3906
+ back() {
3907
+ return __async(this, null, function* () {
3908
+ if (!__privateGet(this, _meta).back) return null;
3909
+ return yield makeRequest("get" /* GET */, __privateGet(this, _meta).back);
3910
+ });
3911
+ }
3912
+ };
3913
+ _data = new WeakMap();
3914
+ _meta = new WeakMap();
3915
+ var makeRequest = (method, path, params, body) => __async(null, null, function* () {
3916
+ const token = yield getAccessToken();
3917
+ let url = path.startsWith("http") ? path : `${app.baseUrl}${!path.startsWith("/") ? "/" : ""}${path}`;
3918
+ if (params) {
3919
+ const query = new URLSearchParams();
3920
+ for (const [key, value] of Object.entries(params)) {
3921
+ if (value !== void 0) query.append(key, String(value));
3922
+ }
3923
+ const queryString = query.toString();
3924
+ if (queryString) {
3925
+ url += (url.includes("?") ? "&" : "?") + queryString;
3926
+ }
3927
+ }
3928
+ const headers = {
3929
+ "Content-Type": "application/json"
3930
+ };
3931
+ if (token) {
3932
+ headers["Authorization"] = `Bearer ${token}`;
3933
+ }
3934
+ const options = {
3935
+ method,
3936
+ headers
3937
+ };
3938
+ if (body) {
3939
+ options.body = JSON.stringify(body);
3940
+ }
3941
+ try {
3942
+ const response = yield fetch(url, options);
3943
+ if (!response.ok) {
3944
+ handleRequestError(response.status);
3945
+ }
3946
+ const data = yield response.json();
3947
+ if (data.data !== void 0 && data.meta !== void 0) {
3948
+ return new PaginatedResponse(data);
3949
+ } else {
3950
+ return data;
3951
+ }
3952
+ } catch (error) {
3953
+ console.error(error);
3954
+ throw error;
3955
+ }
3956
+ });
3957
+
3958
+ // src/auth/loginwithpassword.ts
3959
+ var loginWithPassword = (input) => __async(null, null, function* () {
3960
+ const data = yield makeRequest("post" /* POST */, "/api/login", void 0, input);
3961
+ const { token, user } = data;
3962
+ setAccessToken(token);
3963
+ return user;
3964
+ });
3965
+
3966
+ // src/auth/loginservice.ts
3967
+ var loginService = (projectId, serviceId, secretKey) => __async(null, null, function* () {
3968
+ const body = new URLSearchParams({
3969
+ grant_type: "client_credentials",
3970
+ client_id: serviceId,
3971
+ client_secret: secretKey,
3972
+ scope: "all"
3973
+ });
3974
+ const response = yield fetch(`${app.baseUrl}/oauth2/token`, {
3975
+ method: "POST",
3976
+ headers: {
3977
+ "Content-Type": "application/x-www-form-urlencoded"
3978
+ },
3979
+ body
3980
+ });
3981
+ if (!response.ok) {
3982
+ throw new Error("Service login failed");
3983
+ }
3984
+ const data = yield response.json();
3985
+ if (data.access_token) {
3986
+ setAccessToken(data.access_token);
3987
+ }
3988
+ return data;
3989
+ });
3990
+
3991
+ // src/auth/loginwithredirect.ts
3992
+ var loginWithRedirect = (..._0) => __async(null, [..._0], function* (options = {}) {
3993
+ if (typeof window === "undefined" || !app.userManager) {
3994
+ throw new Error("loginWithRedirect can only be used in a browser environment after initializeSdk");
3995
+ }
3996
+ const {
3997
+ redirectUri = window.location.origin,
3998
+ state,
3999
+ scope,
4000
+ prompt
4001
+ } = options;
4002
+ yield app.userManager.signinRedirect({
4003
+ redirect_uri: redirectUri,
4004
+ state,
4005
+ scope,
4006
+ prompt
4007
+ });
4008
+ });
4009
+
4010
+ // src/auth/handleredirectcallback.ts
4011
+ var handleRedirectCallback = (url) => __async(null, null, function* () {
4012
+ if (typeof window === "undefined" || !app.userManager) {
4013
+ throw new Error("handleRedirectCallback can only be used in a browser environment after initializeSdk");
4014
+ }
4015
+ const user = yield app.userManager.signinRedirectCallback(url);
4016
+ if (!user.profile) {
4017
+ throw new Error("User profile not found in token response");
4018
+ }
4019
+ return user.profile;
4020
+ });
4021
+
4022
+ // src/auth/resetpassword.ts
4023
+ var resetPassword = (input) => __async(null, null, function* () {
4024
+ return yield makeRequest("post" /* POST */, "/api/users/reset-password", void 0, input);
4025
+ });
4026
+
4027
+ // src/auth/isloggedin.ts
4028
+ var isLoggedIn = () => {
4029
+ return app.accessToken !== null && app.accessToken.isValid();
4030
+ };
4031
+
4032
+ // src/auth/logout.ts
4033
+ var logout = () => __async(null, null, function* () {
4034
+ if (typeof window === "undefined" || !app.userManager) {
4035
+ app.accessToken = null;
4036
+ app.refreshToken = null;
4037
+ if (typeof window !== "undefined" && window.sessionStorage) {
4038
+ window.sessionStorage.removeItem("swiftbase_access_token");
4039
+ window.sessionStorage.removeItem("swiftbase_refresh_token");
4040
+ }
4041
+ return;
4042
+ }
4043
+ yield app.userManager.signoutRedirect();
4044
+ });
4045
+
4046
+ // src/auth/verifytoken.ts
4047
+ var verifyToken = (token, projectId) => __async(null, null, function* () {
4048
+ const url = `${app.baseUrl}/api/me`;
4049
+ const response = yield fetch(url, {
4050
+ headers: {
4051
+ "Authorization": `Bearer ${token}`
4052
+ }
4053
+ });
4054
+ if (!response.ok) {
4055
+ throw new Error("Invalid token");
4056
+ }
4057
+ return yield response.json();
4058
+ });
4059
+ var verifyServiceToken = (token, projectId, scope) => __async(null, null, function* () {
4060
+ return yield makeRequest("post" /* POST */, "/api/verify-service-token", void 0, {
4061
+ token,
4062
+ scope
4063
+ });
4064
+ });
4065
+
4066
+ // src/profile/getprofile.ts
4067
+ var getProfile = () => __async(null, null, function* () {
4068
+ return yield makeRequest("get" /* GET */, "/api/me");
4069
+ });
4070
+
4071
+ // src/profile/updateprofile.ts
4072
+ var updateProfile = (input) => __async(null, null, function* () {
4073
+ const me = yield makeRequest("get" /* GET */, "/api/me");
4074
+ return yield makeRequest("put" /* PUT */, `/api/users/${me.id}`, void 0, input);
4075
+ });
4076
+
4077
+ // src/profile/updateuser.ts
4078
+ var updateUser = (id, input) => __async(null, null, function* () {
4079
+ return yield makeRequest("put" /* PUT */, `/api/users/${id}`, void 0, input);
4080
+ });
4081
+
4082
+ // src/profile/changepassword.ts
4083
+ var changePassword = (input) => __async(null, null, function* () {
4084
+ return yield makeRequest("post" /* POST */, "/api/users/change-password", void 0, input);
4085
+ });
4086
+
4087
+ // src/identity/index.ts
4088
+ var getUsers = (projectId) => __async(null, null, function* () {
4089
+ const response = yield makeRequest("get" /* GET */, "/api/users", { projectId });
4090
+ return response instanceof PaginatedResponse ? response.items : response;
4091
+ });
4092
+ var getRoles = (projectId) => __async(null, null, function* () {
4093
+ const response = yield makeRequest("get" /* GET */, "/api/roles", { projectId });
4094
+ return response instanceof PaginatedResponse ? response.items : response;
4095
+ });
4096
+ var getServices = (projectId) => __async(null, null, function* () {
4097
+ const response = yield makeRequest("get" /* GET */, "/api/services", { projectId });
4098
+ return response instanceof PaginatedResponse ? response.items : response;
4099
+ });
4100
+ var createRole = (input) => __async(null, null, function* () {
4101
+ return yield makeRequest("post" /* POST */, "/api/roles", void 0, input);
4102
+ });
4103
+ var deleteRole = (id) => __async(null, null, function* () {
4104
+ return yield makeRequest("delete" /* DELETE */, `/api/roles/${id}`);
4105
+ });
4106
+ var createService = (input) => __async(null, null, function* () {
4107
+ return yield makeRequest("post" /* POST */, "/api/services", void 0, input);
4108
+ });
4109
+ var deleteService = (id) => __async(null, null, function* () {
4110
+ return yield makeRequest("delete" /* DELETE */, `/api/services/${id}`);
4111
+ });
4112
+ var assignRole = (userId, roleName) => __async(null, null, function* () {
4113
+ const user = yield makeRequest("get" /* GET */, `/api/users/${userId}`);
4114
+ const roles = [...user.roles || []];
4115
+ if (!roles.includes(roleName)) {
4116
+ roles.push(roleName);
4117
+ }
4118
+ return yield makeRequest("put" /* PUT */, `/api/users/${userId}`, void 0, { roles });
4119
+ });
4120
+ var unassignRole = (userId, roleName) => __async(null, null, function* () {
4121
+ const user = yield makeRequest("get" /* GET */, `/api/users/${userId}`);
4122
+ const roles = (user.roles || []).filter((r) => r !== roleName);
4123
+ return yield makeRequest("put" /* PUT */, `/api/users/${userId}`, void 0, { roles });
4124
+ });
4125
+
4126
+ // src/database/index.ts
4127
+ var import_uuid = require("uuid");
4128
+ var _DatabaseSocketManager = class _DatabaseSocketManager {
4129
+ constructor() {
4130
+ this.socket = null;
4131
+ this.connectionPromise = null;
4132
+ this.pendingQueries = /* @__PURE__ */ new Map();
4133
+ this.activeSubscriptions = /* @__PURE__ */ new Map();
4134
+ }
4135
+ static getInstance() {
4136
+ if (!_DatabaseSocketManager.instance) {
4137
+ _DatabaseSocketManager.instance = new _DatabaseSocketManager();
4138
+ }
4139
+ return _DatabaseSocketManager.instance;
4140
+ }
4141
+ isWebSocketAvailable() {
4142
+ return this.socket !== null && (this.socket.readyState === 0 || this.socket.readyState === 1);
4143
+ }
4144
+ getWebSocketUrl(baseUrl, token) {
4145
+ let wsUrl = baseUrl.replace(/^http/, "ws");
4146
+ wsUrl = wsUrl.endsWith("/") ? wsUrl.slice(0, -1) : wsUrl;
4147
+ wsUrl = `${wsUrl}/ws`;
4148
+ if (token) {
4149
+ wsUrl = `${wsUrl}?token=${encodeURIComponent(token)}`;
4150
+ }
4151
+ return wsUrl;
4152
+ }
4153
+ ensureConnected() {
4154
+ return __async(this, null, function* () {
4155
+ if (this.socket && (this.socket.readyState === 0 || this.socket.readyState === 1)) {
4156
+ return;
4157
+ }
4158
+ if (this.connectionPromise) {
4159
+ return this.connectionPromise;
4160
+ }
4161
+ this.connectionPromise = (() => __async(this, null, function* () {
4162
+ const token = yield getAccessToken();
4163
+ const wsUrl = this.getWebSocketUrl(app.baseUrl, token);
4164
+ let WS = typeof WebSocket !== "undefined" ? WebSocket : globalThis.WebSocket;
4165
+ if (!WS) {
4166
+ try {
4167
+ const wsModule = yield Promise.resolve().then(() => (init_wrapper(), wrapper_exports));
4168
+ WS = wsModule.default || wsModule;
4169
+ } catch (err) {
4170
+ this.connectionPromise = null;
4171
+ throw new Error(
4172
+ "WebSocket constructor not found. Please install the 'ws' package or run in an environment with global WebSocket support."
4173
+ );
4174
+ }
4175
+ }
4176
+ return new Promise((resolve, reject) => {
4177
+ try {
4178
+ const socket = new WS(wsUrl);
4179
+ this.socket = socket;
4180
+ socket.onopen = () => {
4181
+ this.connectionPromise = null;
4182
+ resolve();
4183
+ this.resubscribeAll().catch((err) => {
4184
+ console.error("[DatabaseSocketManager] Re-subscription failed:", err);
4185
+ });
4186
+ };
4187
+ socket.onerror = (err) => {
4188
+ this.connectionPromise = null;
4189
+ reject(err);
4190
+ };
4191
+ socket.onclose = () => {
4192
+ this.socket = null;
4193
+ this.connectionPromise = null;
4194
+ for (const [_, { reject: rejectQuery }] of this.pendingQueries.entries()) {
4195
+ rejectQuery(new Error("WebSocket disconnected"));
4196
+ }
4197
+ this.pendingQueries.clear();
4198
+ };
4199
+ socket.onmessage = (event) => {
4200
+ this.handleMessage(event);
4201
+ };
4202
+ } catch (err) {
4203
+ this.connectionPromise = null;
4204
+ reject(err);
4205
+ }
4206
+ });
4207
+ }))();
4208
+ return this.connectionPromise;
4209
+ });
4210
+ }
4211
+ resubscribeAll() {
4212
+ return __async(this, null, function* () {
4213
+ for (const key of this.activeSubscriptions.keys()) {
4214
+ const [database, table] = key.split(":");
4215
+ yield this.sendListenRequest(database, table);
4216
+ }
4217
+ });
4218
+ }
4219
+ sendListenRequest(database, table) {
4220
+ return __async(this, null, function* () {
4221
+ if (!this.socket || this.socket.readyState !== 1) {
4222
+ throw new Error("WebSocket not open");
4223
+ }
4224
+ const id = (0, import_uuid.v4)();
4225
+ this.socket.send(JSON.stringify({
4226
+ id,
4227
+ action: "listen",
4228
+ payload: { database, table }
4229
+ }));
4230
+ return new Promise((resolve, reject) => {
4231
+ this.pendingQueries.set(id, { resolve: () => resolve(), reject });
4232
+ });
4233
+ });
4234
+ }
4235
+ handleMessage(event) {
4236
+ try {
4237
+ const msg = JSON.parse(event.data.toString());
4238
+ if (msg.action === "change") {
4239
+ const { database, table, event: changeEvent, data } = msg.payload;
4240
+ const key = `${database}:${table}`;
4241
+ const callbacks = this.activeSubscriptions.get(key);
4242
+ if (callbacks) {
4243
+ for (const cb of callbacks) {
4244
+ try {
4245
+ cb({ event: changeEvent, data });
4246
+ } catch (err) {
4247
+ console.error("[DatabaseSocketManager] Callback error:", err);
4248
+ }
4249
+ }
4250
+ }
4251
+ } else if (msg.id && this.pendingQueries.has(msg.id)) {
4252
+ const { resolve, reject } = this.pendingQueries.get(msg.id);
4253
+ this.pendingQueries.delete(msg.id);
4254
+ if (msg.status === "success") {
4255
+ resolve(msg.data);
4256
+ } else {
4257
+ reject(new Error(msg.message || "Query failed over WebSocket"));
4258
+ }
4259
+ }
4260
+ } catch (err) {
4261
+ console.error("[DatabaseSocketManager] Message handling error:", err);
4262
+ }
4263
+ }
4264
+ executeQuery(payload) {
4265
+ return __async(this, null, function* () {
4266
+ yield this.ensureConnected();
4267
+ const id = (0, import_uuid.v4)();
4268
+ this.socket.send(JSON.stringify({
4269
+ id,
4270
+ action: "query",
4271
+ payload
4272
+ }));
4273
+ return new Promise((resolve, reject) => {
4274
+ this.pendingQueries.set(id, { resolve, reject });
4275
+ });
4276
+ });
4277
+ }
4278
+ subscribe(database, table, callback) {
4279
+ return __async(this, null, function* () {
4280
+ const key = `${database}:${table}`;
4281
+ let cbs = this.activeSubscriptions.get(key);
4282
+ const isNewTable = !cbs || cbs.size === 0;
4283
+ if (!cbs) {
4284
+ cbs = /* @__PURE__ */ new Set();
4285
+ this.activeSubscriptions.set(key, cbs);
4286
+ }
4287
+ cbs.add(callback);
4288
+ yield this.ensureConnected();
4289
+ if (isNewTable) {
4290
+ try {
4291
+ yield this.sendListenRequest(database, table);
4292
+ } catch (err) {
4293
+ cbs.delete(callback);
4294
+ if (cbs.size === 0) {
4295
+ this.activeSubscriptions.delete(key);
4296
+ }
4297
+ throw err;
4298
+ }
4299
+ }
4300
+ return () => {
4301
+ const currentCbs = this.activeSubscriptions.get(key);
4302
+ if (currentCbs) {
4303
+ currentCbs.delete(callback);
4304
+ if (currentCbs.size === 0) {
4305
+ this.activeSubscriptions.delete(key);
4306
+ }
4307
+ }
4308
+ };
4309
+ });
4310
+ }
4311
+ };
4312
+ _DatabaseSocketManager.instance = null;
4313
+ var DatabaseSocketManager = _DatabaseSocketManager;
4314
+ var QueryBuilder = class {
4315
+ constructor(dbName, tableName) {
4316
+ this.dbName = dbName;
4317
+ this.tableName = tableName;
4318
+ this.payload = {
4319
+ database: dbName,
4320
+ table: tableName
4321
+ };
4322
+ }
4323
+ select(...columns) {
4324
+ const flatColumns = columns.flat();
4325
+ if (flatColumns.length > 0) {
4326
+ if (!this.payload.select) {
4327
+ this.payload.select = [];
4328
+ }
4329
+ this.payload.select.push(...flatColumns);
4330
+ }
4331
+ return this;
4332
+ }
4333
+ where(columnOrObj, operatorOrValue, value) {
4334
+ if (!this.payload.where) {
4335
+ this.payload.where = [];
4336
+ }
4337
+ if (typeof columnOrObj === "string") {
4338
+ if (value !== void 0) {
4339
+ this.payload.where.push({
4340
+ column: columnOrObj,
4341
+ operator: operatorOrValue,
4342
+ value
4343
+ });
4344
+ } else if (operatorOrValue !== void 0) {
4345
+ this.payload.where.push({
4346
+ column: columnOrObj,
4347
+ operator: "=",
4348
+ value: operatorOrValue
4349
+ });
4350
+ }
4351
+ } else if (columnOrObj && typeof columnOrObj === "object") {
4352
+ for (const [k, v] of Object.entries(columnOrObj)) {
4353
+ this.payload.where.push({
4354
+ column: k,
4355
+ operator: "=",
4356
+ value: v
4357
+ });
4358
+ }
4359
+ }
4360
+ return this;
4361
+ }
4362
+ limit(value) {
4363
+ this.payload.limit = value;
4364
+ return this;
4365
+ }
4366
+ offset(value) {
4367
+ this.payload.offset = value;
4368
+ return this;
4369
+ }
4370
+ insert(data) {
4371
+ this.payload.insert = data;
4372
+ return this;
4373
+ }
4374
+ update(data) {
4375
+ this.payload.update = data;
4376
+ return this;
4377
+ }
4378
+ delete() {
4379
+ this.payload.delete = true;
4380
+ return this;
4381
+ }
4382
+ listen(callback) {
4383
+ let unsubscribed = false;
4384
+ let unsub = null;
4385
+ DatabaseSocketManager.getInstance().subscribe(this.dbName, this.tableName, callback).then((u) => {
4386
+ if (unsubscribed) {
4387
+ u();
4388
+ } else {
4389
+ unsub = u;
4390
+ }
4391
+ }).catch((err) => {
4392
+ console.error("[QueryBuilder] Subscription failed:", err);
4393
+ });
4394
+ return () => {
4395
+ unsubscribed = true;
4396
+ if (unsub) {
4397
+ unsub();
4398
+ }
4399
+ };
4400
+ }
4401
+ execute() {
4402
+ return __async(this, null, function* () {
4403
+ const socketManager = DatabaseSocketManager.getInstance();
4404
+ if (socketManager.isWebSocketAvailable()) {
4405
+ try {
4406
+ return yield socketManager.executeQuery(this.payload);
4407
+ } catch (err) {
4408
+ console.warn("[QueryBuilder] WebSocket execution failed, falling back to REST:", err);
4409
+ }
4410
+ }
4411
+ return yield makeRequest("post" /* POST */, "/api/db/query", void 0, this.payload);
4412
+ });
4413
+ }
4414
+ then(onfulfilled, onrejected) {
4415
+ return this.execute().then(onfulfilled, onrejected);
4416
+ }
4417
+ };
4418
+ function db(dbName) {
4419
+ return function(tableName) {
4420
+ return new QueryBuilder(dbName, tableName);
4421
+ };
4422
+ }
4423
+
4424
+ // src/storage/sigv4.ts
4425
+ function stringToUint8Array(str) {
4426
+ return new TextEncoder().encode(str);
4427
+ }
4428
+ function bufferToHex(buffer) {
4429
+ return Array.from(new Uint8Array(buffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
4430
+ }
4431
+ function getCryptoObj() {
4432
+ return __async(this, null, function* () {
4433
+ if (typeof globalThis.crypto !== "undefined") {
4434
+ return globalThis.crypto;
4435
+ }
4436
+ const cryptoModule = yield import("crypto");
4437
+ return cryptoModule.webcrypto;
4438
+ });
4439
+ }
4440
+ function sha256(data) {
4441
+ return __async(this, null, function* () {
4442
+ const cryptoObj = yield getCryptoObj();
4443
+ const dataArr = typeof data === "string" ? stringToUint8Array(data) : data;
4444
+ return yield cryptoObj.subtle.digest("SHA-256", dataArr);
4445
+ });
4446
+ }
4447
+ function hmac(key, data) {
4448
+ return __async(this, null, function* () {
4449
+ const cryptoObj = yield getCryptoObj();
4450
+ const cryptoKey = yield cryptoObj.subtle.importKey(
4451
+ "raw",
4452
+ key,
4453
+ { name: "HMAC", hash: "SHA-256" },
4454
+ false,
4455
+ ["sign"]
4456
+ );
4457
+ const dataArr = typeof data === "string" ? stringToUint8Array(data) : data;
4458
+ return yield cryptoObj.subtle.sign("HMAC", cryptoKey, dataArr);
4459
+ });
4460
+ }
4461
+ function getSigningKey(secretKey, date, region, service) {
4462
+ return __async(this, null, function* () {
4463
+ const kDate = yield hmac(stringToUint8Array("AWS4" + secretKey), date);
4464
+ const kRegion = yield hmac(new Uint8Array(kDate), region);
4465
+ const kService = yield hmac(new Uint8Array(kRegion), service);
4466
+ const kSigning = yield hmac(new Uint8Array(kService), "aws4_request");
4467
+ return new Uint8Array(kSigning);
4468
+ });
4469
+ }
4470
+ function signS3Request(options) {
4471
+ return __async(this, null, function* () {
4472
+ const { method, url, headers, body = "", accessKeyId, secretAccessKey, region } = options;
4473
+ const parsedUrl = new URL(url);
4474
+ const host = parsedUrl.host;
4475
+ const now = /* @__PURE__ */ new Date();
4476
+ const amzDate = now.toISOString().replace(/[:-]/g, "").split(".")[0] + "Z";
4477
+ const dateStamp = amzDate.substring(0, 8);
4478
+ const headersToSign = {};
4479
+ headersToSign["host"] = host;
4480
+ headersToSign["x-amz-date"] = amzDate;
4481
+ const payloadHash = bufferToHex(yield sha256(body));
4482
+ headersToSign["x-amz-content-sha256"] = payloadHash;
4483
+ for (const [key, value] of Object.entries(headers)) {
4484
+ const lowerKey = key.toLowerCase();
4485
+ if (lowerKey !== "authorization" && lowerKey !== "host" && lowerKey !== "x-amz-date" && lowerKey !== "x-amz-content-sha256") {
4486
+ headersToSign[lowerKey] = value.trim().replace(/\s+/g, " ");
4487
+ }
4488
+ }
4489
+ const sortedHeaderKeys = Object.keys(headersToSign).sort();
4490
+ let canonicalHeaders = "";
4491
+ for (const key of sortedHeaderKeys) {
4492
+ canonicalHeaders += `${key}:${headersToSign[key]}
4493
+ `;
4494
+ }
4495
+ const signedHeaders = sortedHeaderKeys.join(";");
4496
+ const queryParams = [];
4497
+ parsedUrl.searchParams.forEach((value, key) => {
4498
+ queryParams.push({ key, value });
4499
+ });
4500
+ queryParams.sort((a, b) => a.key.localeCompare(b.key));
4501
+ const rfc3986Encode = (str) => encodeURIComponent(str).replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());
4502
+ const canonicalQueryString = queryParams.map((p) => `${rfc3986Encode(p.key)}=${rfc3986Encode(p.value)}`).join("&");
4503
+ const canonicalUri = parsedUrl.pathname || "/";
4504
+ const canonicalRequest = [
4505
+ method.toUpperCase(),
4506
+ canonicalUri,
4507
+ canonicalQueryString,
4508
+ canonicalHeaders,
4509
+ signedHeaders,
4510
+ payloadHash
4511
+ ].join("\n");
4512
+ const canonicalRequestHash = bufferToHex(yield sha256(canonicalRequest));
4513
+ const algorithm = "AWS4-HMAC-SHA256";
4514
+ const credentialScope = `${dateStamp}/${region}/s3/aws4_request`;
4515
+ const stringToSign = [
4516
+ algorithm,
4517
+ amzDate,
4518
+ credentialScope,
4519
+ canonicalRequestHash
4520
+ ].join("\n");
4521
+ const signingKey = yield getSigningKey(secretAccessKey, dateStamp, region, "s3");
4522
+ const signature = bufferToHex(yield hmac(signingKey, stringToSign));
4523
+ const authorizationHeader = `${algorithm} Credential=${accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
4524
+ const resultHeaders = __spreadValues({}, headers);
4525
+ resultHeaders["Host"] = host;
4526
+ resultHeaders["x-amz-date"] = amzDate;
4527
+ resultHeaders["x-amz-content-sha256"] = payloadHash;
4528
+ resultHeaders["Authorization"] = authorizationHeader;
4529
+ return resultHeaders;
4530
+ });
4531
+ }
4532
+
4533
+ // src/storage/storage.ts
4534
+ function getDefaultEndpoint() {
4535
+ const base = app.baseUrl || "https://api.swiftbase.io";
4536
+ if (base.includes("localhost") || base.includes("127.0.0.1")) {
4537
+ return "http://localhost:3006";
4538
+ }
4539
+ return base.replace("api.swiftbase", "storage.swiftbase");
4540
+ }
4541
+ function parseListBuckets(xml) {
4542
+ const buckets = [];
4543
+ const bucketMatches = xml.matchAll(/<Bucket>([\s\S]*?)<\/Bucket>/g);
4544
+ for (const match of bucketMatches) {
4545
+ const bucketContent = match[1];
4546
+ const nameMatch = bucketContent.match(/<Name>(.*?)<\/Name>/);
4547
+ const dateMatch = bucketContent.match(/<CreationDate>(.*?)<\/CreationDate>/);
4548
+ if (nameMatch) {
4549
+ buckets.push({
4550
+ name: nameMatch[1],
4551
+ creationDate: dateMatch ? dateMatch[1] : void 0
4552
+ });
4553
+ }
4554
+ }
4555
+ return buckets;
4556
+ }
4557
+ function parseListObjects(xml) {
4558
+ const nameMatch = xml.match(/<Name>(.*?)<\/Name>/);
4559
+ const prefixMatch = xml.match(/<Prefix>(.*?)<\/Prefix>/);
4560
+ const maxKeysMatch = xml.match(/<MaxKeys>(.*?)<\/MaxKeys>/);
4561
+ const isTruncatedMatch = xml.match(/<IsTruncated>(.*?)<\/IsTruncated>/);
4562
+ const contents = [];
4563
+ const contentMatches = xml.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g);
4564
+ for (const match of contentMatches) {
4565
+ const content = match[1];
4566
+ const keyMatch = content.match(/<Key>(.*?)<\/Key>/);
4567
+ const lmMatch = content.match(/<LastModified>(.*?)<\/LastModified>/);
4568
+ const etagMatch = content.match(/<ETag>(.*?)<\/ETag>/);
4569
+ const sizeMatch = content.match(/<Size>(.*?)<\/Size>/);
4570
+ if (keyMatch) {
4571
+ contents.push({
4572
+ key: keyMatch[1],
4573
+ lastModified: lmMatch ? lmMatch[1] : void 0,
4574
+ etag: etagMatch ? etagMatch[1].replace(/"/g, "") : void 0,
4575
+ size: sizeMatch ? parseInt(sizeMatch[1]) : 0
4576
+ });
4577
+ }
4578
+ }
4579
+ const commonPrefixes = [];
4580
+ const cpMatches = xml.matchAll(/<CommonPrefixes>([\s\S]*?)<\/CommonPrefixes>/g);
4581
+ for (const match of cpMatches) {
4582
+ const prefixMatch2 = match[1].match(/<Prefix>(.*?)<\/Prefix>/);
4583
+ if (prefixMatch2) {
4584
+ commonPrefixes.push(prefixMatch2[1]);
4585
+ }
4586
+ }
4587
+ return {
4588
+ name: nameMatch ? nameMatch[1] : "",
4589
+ prefix: prefixMatch ? prefixMatch[1] : "",
4590
+ maxKeys: maxKeysMatch ? parseInt(maxKeysMatch[1]) : 1e3,
4591
+ isTruncated: isTruncatedMatch ? isTruncatedMatch[1] === "true" : false,
4592
+ contents,
4593
+ commonPrefixes
4594
+ };
4595
+ }
4596
+ function parseErrorXml(xml) {
4597
+ const codeMatch = xml.match(/<Code>(.*?)<\/Code>/);
4598
+ const messageMatch = xml.match(/<Message>(.*?)<\/Message>/);
4599
+ if (codeMatch && messageMatch) {
4600
+ return `${codeMatch[1]}: ${messageMatch[1]}`;
4601
+ }
4602
+ return xml;
4603
+ }
4604
+ var Storage = class {
4605
+ constructor(options) {
4606
+ this.bucket = options.bucket;
4607
+ this.endpoint = options.endpoint || getDefaultEndpoint();
4608
+ this.region = options.region || "us-east-1";
4609
+ this.accessKeyId = options.accessKeyId;
4610
+ this.secretAccessKey = options.secretAccessKey;
4611
+ }
4612
+ getHeaders(_0, _1, _2) {
4613
+ return __async(this, arguments, function* (method, url, body, customHeaders = {}) {
4614
+ let headers = __spreadValues({}, customHeaders);
4615
+ if (this.accessKeyId && this.secretAccessKey) {
4616
+ headers = yield signS3Request({
4617
+ method,
4618
+ url,
4619
+ headers,
4620
+ body,
4621
+ accessKeyId: this.accessKeyId,
4622
+ secretAccessKey: this.secretAccessKey,
4623
+ region: this.region
4624
+ });
4625
+ } else {
4626
+ const token = yield getAccessToken();
4627
+ if (token) {
4628
+ headers["Authorization"] = `Bearer ${token}`;
4629
+ }
4630
+ }
4631
+ return headers;
4632
+ });
4633
+ }
4634
+ listBuckets() {
4635
+ return __async(this, null, function* () {
4636
+ const method = "GET";
4637
+ const url = `${this.endpoint.replace(/\/$/, "")}/`;
4638
+ const headers = yield this.getHeaders(method, url);
4639
+ const response = yield fetch(url, { method, headers });
4640
+ const text = yield response.text();
4641
+ if (!response.ok) {
4642
+ throw new Error(parseErrorXml(text) || `Failed to list buckets: ${response.statusText}`);
4643
+ }
4644
+ return parseListBuckets(text);
4645
+ });
4646
+ }
4647
+ listObjects(options) {
4648
+ return __async(this, null, function* () {
4649
+ const method = "GET";
4650
+ const query = new URLSearchParams();
4651
+ if (options == null ? void 0 : options.prefix) query.append("prefix", options.prefix);
4652
+ if (options == null ? void 0 : options.delimiter) query.append("delimiter", options.delimiter);
4653
+ if (options == null ? void 0 : options.maxKeys) query.append("max-keys", String(options.maxKeys));
4654
+ const queryString = query.toString();
4655
+ const url = `${this.endpoint.replace(/\/$/, "")}/${this.bucket}${queryString ? "?" + queryString : ""}`;
4656
+ const headers = yield this.getHeaders(method, url);
4657
+ const response = yield fetch(url, { method, headers });
4658
+ const text = yield response.text();
4659
+ if (!response.ok) {
4660
+ throw new Error(parseErrorXml(text) || `Failed to list objects: ${response.statusText}`);
4661
+ }
4662
+ return parseListObjects(text);
4663
+ });
4664
+ }
4665
+ getObject(key) {
4666
+ return __async(this, null, function* () {
4667
+ const method = "GET";
4668
+ const cleanKey = key.startsWith("/") ? key : "/" + key;
4669
+ const url = `${this.endpoint.replace(/\/$/, "")}/${this.bucket}${cleanKey}`;
4670
+ const headers = yield this.getHeaders(method, url);
4671
+ const response = yield fetch(url, { method, headers });
4672
+ if (!response.ok) {
4673
+ const text = yield response.text();
4674
+ throw new Error(parseErrorXml(text) || `Failed to get object: ${response.statusText}`);
4675
+ }
4676
+ return response;
4677
+ });
4678
+ }
4679
+ getObjectAsText(key) {
4680
+ return __async(this, null, function* () {
4681
+ const res = yield this.getObject(key);
4682
+ return yield res.text();
4683
+ });
4684
+ }
4685
+ getObjectAsJson(key) {
4686
+ return __async(this, null, function* () {
4687
+ const res = yield this.getObject(key);
4688
+ return yield res.json();
4689
+ });
4690
+ }
4691
+ getObjectAsArrayBuffer(key) {
4692
+ return __async(this, null, function* () {
4693
+ const res = yield this.getObject(key);
4694
+ return yield res.arrayBuffer();
4695
+ });
4696
+ }
4697
+ putObject(key, body, options) {
4698
+ return __async(this, null, function* () {
4699
+ const method = "PUT";
4700
+ const cleanKey = key.startsWith("/") ? key : "/" + key;
4701
+ const url = `${this.endpoint.replace(/\/$/, "")}/${this.bucket}${cleanKey}`;
4702
+ let bodyData;
4703
+ if (typeof body === "string") {
4704
+ bodyData = new TextEncoder().encode(body);
4705
+ } else if (body instanceof ArrayBuffer) {
4706
+ bodyData = new Uint8Array(body);
4707
+ } else if (body instanceof Uint8Array) {
4708
+ bodyData = body;
4709
+ } else if (typeof Blob !== "undefined" && body instanceof Blob) {
4710
+ bodyData = new Uint8Array(yield body.arrayBuffer());
4711
+ } else {
4712
+ throw new Error("Unsupported body type. Must be string, ArrayBuffer, Uint8Array, or Blob.");
4713
+ }
4714
+ const customHeaders = {};
4715
+ if (options == null ? void 0 : options.contentType) {
4716
+ customHeaders["Content-Type"] = options.contentType;
4717
+ }
4718
+ const headers = yield this.getHeaders(method, url, bodyData, customHeaders);
4719
+ const response = yield fetch(url, {
4720
+ method,
4721
+ headers,
4722
+ body: bodyData
4723
+ });
4724
+ if (!response.ok) {
4725
+ const text = yield response.text();
4726
+ throw new Error(parseErrorXml(text) || `Failed to put object: ${response.statusText}`);
4727
+ }
4728
+ });
4729
+ }
4730
+ deleteObject(key) {
4731
+ return __async(this, null, function* () {
4732
+ const method = "DELETE";
4733
+ const cleanKey = key.startsWith("/") ? key : "/" + key;
4734
+ const url = `${this.endpoint.replace(/\/$/, "")}/${this.bucket}${cleanKey}`;
4735
+ const headers = yield this.getHeaders(method, url);
4736
+ const response = yield fetch(url, { method, headers });
4737
+ if (!response.ok) {
4738
+ const text = yield response.text();
4739
+ throw new Error(parseErrorXml(text) || `Failed to delete object: ${response.statusText}`);
4740
+ }
4741
+ });
4742
+ }
4743
+ };
4744
+ // Annotate the CommonJS export names for ESM import in node:
4745
+ 0 && (module.exports = {
4746
+ PaginatedResponse,
4747
+ Storage,
4748
+ assignRole,
4749
+ changePassword,
4750
+ createRole,
4751
+ createService,
4752
+ db,
4753
+ deleteRole,
4754
+ deleteService,
4755
+ getAccessToken,
4756
+ getProfile,
4757
+ getRoles,
4758
+ getServices,
4759
+ getUsers,
4760
+ handleRedirectCallback,
4761
+ initializeSdk,
4762
+ isLoggedIn,
4763
+ login,
4764
+ loginService,
4765
+ loginWithPassword,
4766
+ loginWithRedirect,
4767
+ logout,
4768
+ refreshTokens,
4769
+ resetPassword,
4770
+ setAccessToken,
4771
+ setRefreshToken,
4772
+ unassignRole,
4773
+ updateProfile,
4774
+ updateUser,
4775
+ verifyServiceToken,
4776
+ verifyToken
4777
+ });
4778
+ //# sourceMappingURL=index.cjs.map