@blinkdotnew/dev-sdk 2.2.2 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,9 +1,2582 @@
1
+ var __getOwnPropNames = Object.getOwnPropertyNames;
1
2
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
3
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
4
  }) : x)(function(x) {
4
5
  if (typeof require !== "undefined") return require.apply(this, arguments);
5
6
  throw Error('Dynamic require of "' + x + '" is not supported');
6
7
  });
8
+ var __commonJS = (cb, mod) => function __require2() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+
12
+ // ../../node_modules/async-limiter/index.js
13
+ var require_async_limiter = __commonJS({
14
+ "../../node_modules/async-limiter/index.js"(exports, module) {
15
+ function Queue(options) {
16
+ if (!(this instanceof Queue)) {
17
+ return new Queue(options);
18
+ }
19
+ options = options || {};
20
+ this.concurrency = options.concurrency || Infinity;
21
+ this.pending = 0;
22
+ this.jobs = [];
23
+ this.cbs = [];
24
+ this._done = done.bind(this);
25
+ }
26
+ var arrayAddMethods = [
27
+ "push",
28
+ "unshift",
29
+ "splice"
30
+ ];
31
+ arrayAddMethods.forEach(function(method) {
32
+ Queue.prototype[method] = function() {
33
+ var methodResult = Array.prototype[method].apply(this.jobs, arguments);
34
+ this._run();
35
+ return methodResult;
36
+ };
37
+ });
38
+ Object.defineProperty(Queue.prototype, "length", {
39
+ get: function() {
40
+ return this.pending + this.jobs.length;
41
+ }
42
+ });
43
+ Queue.prototype._run = function() {
44
+ if (this.pending === this.concurrency) {
45
+ return;
46
+ }
47
+ if (this.jobs.length) {
48
+ var job = this.jobs.shift();
49
+ this.pending++;
50
+ job(this._done);
51
+ this._run();
52
+ }
53
+ if (this.pending === 0) {
54
+ while (this.cbs.length !== 0) {
55
+ var cb = this.cbs.pop();
56
+ process.nextTick(cb);
57
+ }
58
+ }
59
+ };
60
+ Queue.prototype.onDone = function(cb) {
61
+ if (typeof cb === "function") {
62
+ this.cbs.push(cb);
63
+ this._run();
64
+ }
65
+ };
66
+ function done() {
67
+ this.pending--;
68
+ this._run();
69
+ }
70
+ module.exports = Queue;
71
+ }
72
+ });
73
+
74
+ // ../../node_modules/ws/lib/constants.js
75
+ var require_constants = __commonJS({
76
+ "../../node_modules/ws/lib/constants.js"(exports, module) {
77
+ module.exports = {
78
+ BINARY_TYPES: ["nodebuffer", "arraybuffer", "fragments"],
79
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
80
+ kStatusCode: Symbol("status-code"),
81
+ kWebSocket: Symbol("websocket"),
82
+ EMPTY_BUFFER: Buffer.alloc(0),
83
+ NOOP: () => {
84
+ }
85
+ };
86
+ }
87
+ });
88
+
89
+ // ../../node_modules/ws/lib/buffer-util.js
90
+ var require_buffer_util = __commonJS({
91
+ "../../node_modules/ws/lib/buffer-util.js"(exports, module) {
92
+ var { EMPTY_BUFFER } = require_constants();
93
+ function concat(list, totalLength) {
94
+ if (list.length === 0) return EMPTY_BUFFER;
95
+ if (list.length === 1) return list[0];
96
+ const target = Buffer.allocUnsafe(totalLength);
97
+ var offset = 0;
98
+ for (var i = 0; i < list.length; i++) {
99
+ const buf = list[i];
100
+ buf.copy(target, offset);
101
+ offset += buf.length;
102
+ }
103
+ return target;
104
+ }
105
+ function _mask(source, mask, output, offset, length) {
106
+ for (var i = 0; i < length; i++) {
107
+ output[offset + i] = source[i] ^ mask[i & 3];
108
+ }
109
+ }
110
+ function _unmask(buffer, mask) {
111
+ const length = buffer.length;
112
+ for (var i = 0; i < length; i++) {
113
+ buffer[i] ^= mask[i & 3];
114
+ }
115
+ }
116
+ function toArrayBuffer(buf) {
117
+ if (buf.byteLength === buf.buffer.byteLength) {
118
+ return buf.buffer;
119
+ }
120
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
121
+ }
122
+ function toBuffer(data) {
123
+ toBuffer.readOnly = true;
124
+ if (Buffer.isBuffer(data)) return data;
125
+ var buf;
126
+ if (data instanceof ArrayBuffer) {
127
+ buf = Buffer.from(data);
128
+ } else if (ArrayBuffer.isView(data)) {
129
+ buf = viewToBuffer(data);
130
+ } else {
131
+ buf = Buffer.from(data);
132
+ toBuffer.readOnly = false;
133
+ }
134
+ return buf;
135
+ }
136
+ function viewToBuffer(view) {
137
+ const buf = Buffer.from(view.buffer);
138
+ if (view.byteLength !== view.buffer.byteLength) {
139
+ return buf.slice(view.byteOffset, view.byteOffset + view.byteLength);
140
+ }
141
+ return buf;
142
+ }
143
+ try {
144
+ const bufferUtil = __require("bufferutil");
145
+ const bu = bufferUtil.BufferUtil || bufferUtil;
146
+ module.exports = {
147
+ concat,
148
+ mask(source, mask, output, offset, length) {
149
+ if (length < 48) _mask(source, mask, output, offset, length);
150
+ else bu.mask(source, mask, output, offset, length);
151
+ },
152
+ toArrayBuffer,
153
+ toBuffer,
154
+ unmask(buffer, mask) {
155
+ if (buffer.length < 32) _unmask(buffer, mask);
156
+ else bu.unmask(buffer, mask);
157
+ }
158
+ };
159
+ } catch (e) {
160
+ module.exports = {
161
+ concat,
162
+ mask: _mask,
163
+ toArrayBuffer,
164
+ toBuffer,
165
+ unmask: _unmask
166
+ };
167
+ }
168
+ }
169
+ });
170
+
171
+ // ../../node_modules/ws/lib/permessage-deflate.js
172
+ var require_permessage_deflate = __commonJS({
173
+ "../../node_modules/ws/lib/permessage-deflate.js"(exports, module) {
174
+ var Limiter = require_async_limiter();
175
+ var zlib = __require("zlib");
176
+ var bufferUtil = require_buffer_util();
177
+ var { kStatusCode, NOOP } = require_constants();
178
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
179
+ var EMPTY_BLOCK = Buffer.from([0]);
180
+ var kPerMessageDeflate = Symbol("permessage-deflate");
181
+ var kTotalLength = Symbol("total-length");
182
+ var kCallback = Symbol("callback");
183
+ var kBuffers = Symbol("buffers");
184
+ var kError = Symbol("error");
185
+ var zlibLimiter;
186
+ var PerMessageDeflate = class {
187
+ /**
188
+ * Creates a PerMessageDeflate instance.
189
+ *
190
+ * @param {Object} options Configuration options
191
+ * @param {Boolean} options.serverNoContextTakeover Request/accept disabling
192
+ * of server context takeover
193
+ * @param {Boolean} options.clientNoContextTakeover Advertise/acknowledge
194
+ * disabling of client context takeover
195
+ * @param {(Boolean|Number)} options.serverMaxWindowBits Request/confirm the
196
+ * use of a custom server window size
197
+ * @param {(Boolean|Number)} options.clientMaxWindowBits Advertise support
198
+ * for, or request, a custom client window size
199
+ * @param {Object} options.zlibDeflateOptions Options to pass to zlib on deflate
200
+ * @param {Object} options.zlibInflateOptions Options to pass to zlib on inflate
201
+ * @param {Number} options.threshold Size (in bytes) below which messages
202
+ * should not be compressed
203
+ * @param {Number} options.concurrencyLimit The number of concurrent calls to
204
+ * zlib
205
+ * @param {Boolean} isServer Create the instance in either server or client
206
+ * mode
207
+ * @param {Number} maxPayload The maximum allowed message length
208
+ */
209
+ constructor(options, isServer2, maxPayload) {
210
+ this._maxPayload = maxPayload | 0;
211
+ this._options = options || {};
212
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
213
+ this._isServer = !!isServer2;
214
+ this._deflate = null;
215
+ this._inflate = null;
216
+ this.params = null;
217
+ if (!zlibLimiter) {
218
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
219
+ zlibLimiter = new Limiter({ concurrency });
220
+ }
221
+ }
222
+ /**
223
+ * @type {String}
224
+ */
225
+ static get extensionName() {
226
+ return "permessage-deflate";
227
+ }
228
+ /**
229
+ * Create an extension negotiation offer.
230
+ *
231
+ * @return {Object} Extension parameters
232
+ * @public
233
+ */
234
+ offer() {
235
+ const params = {};
236
+ if (this._options.serverNoContextTakeover) {
237
+ params.server_no_context_takeover = true;
238
+ }
239
+ if (this._options.clientNoContextTakeover) {
240
+ params.client_no_context_takeover = true;
241
+ }
242
+ if (this._options.serverMaxWindowBits) {
243
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
244
+ }
245
+ if (this._options.clientMaxWindowBits) {
246
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
247
+ } else if (this._options.clientMaxWindowBits == null) {
248
+ params.client_max_window_bits = true;
249
+ }
250
+ return params;
251
+ }
252
+ /**
253
+ * Accept an extension negotiation offer/response.
254
+ *
255
+ * @param {Array} configurations The extension negotiation offers/reponse
256
+ * @return {Object} Accepted configuration
257
+ * @public
258
+ */
259
+ accept(configurations) {
260
+ configurations = this.normalizeParams(configurations);
261
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
262
+ return this.params;
263
+ }
264
+ /**
265
+ * Releases all resources used by the extension.
266
+ *
267
+ * @public
268
+ */
269
+ cleanup() {
270
+ if (this._inflate) {
271
+ this._inflate.close();
272
+ this._inflate = null;
273
+ }
274
+ if (this._deflate) {
275
+ this._deflate.close();
276
+ this._deflate = null;
277
+ }
278
+ }
279
+ /**
280
+ * Accept an extension negotiation offer.
281
+ *
282
+ * @param {Array} offers The extension negotiation offers
283
+ * @return {Object} Accepted configuration
284
+ * @private
285
+ */
286
+ acceptAsServer(offers) {
287
+ const opts = this._options;
288
+ const accepted = offers.find((params) => {
289
+ 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) {
290
+ return false;
291
+ }
292
+ return true;
293
+ });
294
+ if (!accepted) {
295
+ throw new Error("None of the extension offers can be accepted");
296
+ }
297
+ if (opts.serverNoContextTakeover) {
298
+ accepted.server_no_context_takeover = true;
299
+ }
300
+ if (opts.clientNoContextTakeover) {
301
+ accepted.client_no_context_takeover = true;
302
+ }
303
+ if (typeof opts.serverMaxWindowBits === "number") {
304
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
305
+ }
306
+ if (typeof opts.clientMaxWindowBits === "number") {
307
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
308
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
309
+ delete accepted.client_max_window_bits;
310
+ }
311
+ return accepted;
312
+ }
313
+ /**
314
+ * Accept the extension negotiation response.
315
+ *
316
+ * @param {Array} response The extension negotiation response
317
+ * @return {Object} Accepted configuration
318
+ * @private
319
+ */
320
+ acceptAsClient(response) {
321
+ const params = response[0];
322
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
323
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
324
+ }
325
+ if (!params.client_max_window_bits) {
326
+ if (typeof this._options.clientMaxWindowBits === "number") {
327
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
328
+ }
329
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
330
+ throw new Error(
331
+ 'Unexpected or invalid parameter "client_max_window_bits"'
332
+ );
333
+ }
334
+ return params;
335
+ }
336
+ /**
337
+ * Normalize parameters.
338
+ *
339
+ * @param {Array} configurations The extension negotiation offers/reponse
340
+ * @return {Array} The offers/response with normalized parameters
341
+ * @private
342
+ */
343
+ normalizeParams(configurations) {
344
+ configurations.forEach((params) => {
345
+ Object.keys(params).forEach((key) => {
346
+ var value = params[key];
347
+ if (value.length > 1) {
348
+ throw new Error(`Parameter "${key}" must have only a single value`);
349
+ }
350
+ value = value[0];
351
+ if (key === "client_max_window_bits") {
352
+ if (value !== true) {
353
+ const num = +value;
354
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
355
+ throw new TypeError(
356
+ `Invalid value for parameter "${key}": ${value}`
357
+ );
358
+ }
359
+ value = num;
360
+ } else if (!this._isServer) {
361
+ throw new TypeError(
362
+ `Invalid value for parameter "${key}": ${value}`
363
+ );
364
+ }
365
+ } else if (key === "server_max_window_bits") {
366
+ const num = +value;
367
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
368
+ throw new TypeError(
369
+ `Invalid value for parameter "${key}": ${value}`
370
+ );
371
+ }
372
+ value = num;
373
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
374
+ if (value !== true) {
375
+ throw new TypeError(
376
+ `Invalid value for parameter "${key}": ${value}`
377
+ );
378
+ }
379
+ } else {
380
+ throw new Error(`Unknown parameter "${key}"`);
381
+ }
382
+ params[key] = value;
383
+ });
384
+ });
385
+ return configurations;
386
+ }
387
+ /**
388
+ * Decompress data. Concurrency limited by async-limiter.
389
+ *
390
+ * @param {Buffer} data Compressed data
391
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
392
+ * @param {Function} callback Callback
393
+ * @public
394
+ */
395
+ decompress(data, fin, callback) {
396
+ zlibLimiter.push((done) => {
397
+ this._decompress(data, fin, (err, result) => {
398
+ done();
399
+ callback(err, result);
400
+ });
401
+ });
402
+ }
403
+ /**
404
+ * Compress data. Concurrency limited by async-limiter.
405
+ *
406
+ * @param {Buffer} data Data to compress
407
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
408
+ * @param {Function} callback Callback
409
+ * @public
410
+ */
411
+ compress(data, fin, callback) {
412
+ zlibLimiter.push((done) => {
413
+ this._compress(data, fin, (err, result) => {
414
+ done();
415
+ callback(err, result);
416
+ });
417
+ });
418
+ }
419
+ /**
420
+ * Decompress data.
421
+ *
422
+ * @param {Buffer} data Compressed data
423
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
424
+ * @param {Function} callback Callback
425
+ * @private
426
+ */
427
+ _decompress(data, fin, callback) {
428
+ const endpoint = this._isServer ? "client" : "server";
429
+ if (!this._inflate) {
430
+ const key = `${endpoint}_max_window_bits`;
431
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
432
+ this._inflate = zlib.createInflateRaw(
433
+ Object.assign({}, this._options.zlibInflateOptions, { windowBits })
434
+ );
435
+ this._inflate[kPerMessageDeflate] = this;
436
+ this._inflate[kTotalLength] = 0;
437
+ this._inflate[kBuffers] = [];
438
+ this._inflate.on("error", inflateOnError);
439
+ this._inflate.on("data", inflateOnData);
440
+ }
441
+ this._inflate[kCallback] = callback;
442
+ this._inflate.write(data);
443
+ if (fin) this._inflate.write(TRAILER);
444
+ this._inflate.flush(() => {
445
+ const err = this._inflate[kError];
446
+ if (err) {
447
+ this._inflate.close();
448
+ this._inflate = null;
449
+ callback(err);
450
+ return;
451
+ }
452
+ const data2 = bufferUtil.concat(
453
+ this._inflate[kBuffers],
454
+ this._inflate[kTotalLength]
455
+ );
456
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
457
+ this._inflate.close();
458
+ this._inflate = null;
459
+ } else {
460
+ this._inflate[kTotalLength] = 0;
461
+ this._inflate[kBuffers] = [];
462
+ }
463
+ callback(null, data2);
464
+ });
465
+ }
466
+ /**
467
+ * Compress data.
468
+ *
469
+ * @param {Buffer} data Data to compress
470
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
471
+ * @param {Function} callback Callback
472
+ * @private
473
+ */
474
+ _compress(data, fin, callback) {
475
+ if (!data || data.length === 0) {
476
+ process.nextTick(callback, null, EMPTY_BLOCK);
477
+ return;
478
+ }
479
+ const endpoint = this._isServer ? "server" : "client";
480
+ if (!this._deflate) {
481
+ const key = `${endpoint}_max_window_bits`;
482
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
483
+ this._deflate = zlib.createDeflateRaw(
484
+ Object.assign({}, this._options.zlibDeflateOptions, { windowBits })
485
+ );
486
+ this._deflate[kTotalLength] = 0;
487
+ this._deflate[kBuffers] = [];
488
+ this._deflate.on("error", NOOP);
489
+ this._deflate.on("data", deflateOnData);
490
+ }
491
+ this._deflate.write(data);
492
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
493
+ if (!this._deflate) {
494
+ return;
495
+ }
496
+ var data2 = bufferUtil.concat(
497
+ this._deflate[kBuffers],
498
+ this._deflate[kTotalLength]
499
+ );
500
+ if (fin) data2 = data2.slice(0, data2.length - 4);
501
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
502
+ this._deflate.close();
503
+ this._deflate = null;
504
+ } else {
505
+ this._deflate[kTotalLength] = 0;
506
+ this._deflate[kBuffers] = [];
507
+ }
508
+ callback(null, data2);
509
+ });
510
+ }
511
+ };
512
+ module.exports = PerMessageDeflate;
513
+ function deflateOnData(chunk) {
514
+ this[kBuffers].push(chunk);
515
+ this[kTotalLength] += chunk.length;
516
+ }
517
+ function inflateOnData(chunk) {
518
+ this[kTotalLength] += chunk.length;
519
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
520
+ this[kBuffers].push(chunk);
521
+ return;
522
+ }
523
+ this[kError] = new RangeError("Max payload size exceeded");
524
+ this[kError][kStatusCode] = 1009;
525
+ this.removeListener("data", inflateOnData);
526
+ this.reset();
527
+ }
528
+ function inflateOnError(err) {
529
+ this[kPerMessageDeflate]._inflate = null;
530
+ err[kStatusCode] = 1007;
531
+ this[kCallback](err);
532
+ }
533
+ }
534
+ });
535
+
536
+ // ../../node_modules/ws/lib/event-target.js
537
+ var require_event_target = __commonJS({
538
+ "../../node_modules/ws/lib/event-target.js"(exports, module) {
539
+ var Event = class {
540
+ /**
541
+ * Create a new `Event`.
542
+ *
543
+ * @param {String} type The name of the event
544
+ * @param {Object} target A reference to the target to which the event was dispatched
545
+ */
546
+ constructor(type, target) {
547
+ this.target = target;
548
+ this.type = type;
549
+ }
550
+ };
551
+ var MessageEvent = class extends Event {
552
+ /**
553
+ * Create a new `MessageEvent`.
554
+ *
555
+ * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data
556
+ * @param {WebSocket} target A reference to the target to which the event was dispatched
557
+ */
558
+ constructor(data, target) {
559
+ super("message", target);
560
+ this.data = data;
561
+ }
562
+ };
563
+ var CloseEvent = class extends Event {
564
+ /**
565
+ * Create a new `CloseEvent`.
566
+ *
567
+ * @param {Number} code The status code explaining why the connection is being closed
568
+ * @param {String} reason A human-readable string explaining why the connection is closing
569
+ * @param {WebSocket} target A reference to the target to which the event was dispatched
570
+ */
571
+ constructor(code, reason, target) {
572
+ super("close", target);
573
+ this.wasClean = target._closeFrameReceived && target._closeFrameSent;
574
+ this.reason = reason;
575
+ this.code = code;
576
+ }
577
+ };
578
+ var OpenEvent = class extends Event {
579
+ /**
580
+ * Create a new `OpenEvent`.
581
+ *
582
+ * @param {WebSocket} target A reference to the target to which the event was dispatched
583
+ */
584
+ constructor(target) {
585
+ super("open", target);
586
+ }
587
+ };
588
+ var ErrorEvent = class extends Event {
589
+ /**
590
+ * Create a new `ErrorEvent`.
591
+ *
592
+ * @param {Object} error The error that generated this event
593
+ * @param {WebSocket} target A reference to the target to which the event was dispatched
594
+ */
595
+ constructor(error, target) {
596
+ super("error", target);
597
+ this.message = error.message;
598
+ this.error = error;
599
+ }
600
+ };
601
+ var EventTarget = {
602
+ /**
603
+ * Register an event listener.
604
+ *
605
+ * @param {String} method A string representing the event type to listen for
606
+ * @param {Function} listener The listener to add
607
+ * @public
608
+ */
609
+ addEventListener(method, listener) {
610
+ if (typeof listener !== "function") return;
611
+ function onMessage(data) {
612
+ listener.call(this, new MessageEvent(data, this));
613
+ }
614
+ function onClose(code, message) {
615
+ listener.call(this, new CloseEvent(code, message, this));
616
+ }
617
+ function onError(error) {
618
+ listener.call(this, new ErrorEvent(error, this));
619
+ }
620
+ function onOpen() {
621
+ listener.call(this, new OpenEvent(this));
622
+ }
623
+ if (method === "message") {
624
+ onMessage._listener = listener;
625
+ this.on(method, onMessage);
626
+ } else if (method === "close") {
627
+ onClose._listener = listener;
628
+ this.on(method, onClose);
629
+ } else if (method === "error") {
630
+ onError._listener = listener;
631
+ this.on(method, onError);
632
+ } else if (method === "open") {
633
+ onOpen._listener = listener;
634
+ this.on(method, onOpen);
635
+ } else {
636
+ this.on(method, listener);
637
+ }
638
+ },
639
+ /**
640
+ * Remove an event listener.
641
+ *
642
+ * @param {String} method A string representing the event type to remove
643
+ * @param {Function} listener The listener to remove
644
+ * @public
645
+ */
646
+ removeEventListener(method, listener) {
647
+ const listeners = this.listeners(method);
648
+ for (var i = 0; i < listeners.length; i++) {
649
+ if (listeners[i] === listener || listeners[i]._listener === listener) {
650
+ this.removeListener(method, listeners[i]);
651
+ }
652
+ }
653
+ }
654
+ };
655
+ module.exports = EventTarget;
656
+ }
657
+ });
658
+
659
+ // ../../node_modules/ws/lib/extension.js
660
+ var require_extension = __commonJS({
661
+ "../../node_modules/ws/lib/extension.js"(exports, module) {
662
+ var tokenChars = [
663
+ 0,
664
+ 0,
665
+ 0,
666
+ 0,
667
+ 0,
668
+ 0,
669
+ 0,
670
+ 0,
671
+ 0,
672
+ 0,
673
+ 0,
674
+ 0,
675
+ 0,
676
+ 0,
677
+ 0,
678
+ 0,
679
+ // 0 - 15
680
+ 0,
681
+ 0,
682
+ 0,
683
+ 0,
684
+ 0,
685
+ 0,
686
+ 0,
687
+ 0,
688
+ 0,
689
+ 0,
690
+ 0,
691
+ 0,
692
+ 0,
693
+ 0,
694
+ 0,
695
+ 0,
696
+ // 16 - 31
697
+ 0,
698
+ 1,
699
+ 0,
700
+ 1,
701
+ 1,
702
+ 1,
703
+ 1,
704
+ 1,
705
+ 0,
706
+ 0,
707
+ 1,
708
+ 1,
709
+ 0,
710
+ 1,
711
+ 1,
712
+ 0,
713
+ // 32 - 47
714
+ 1,
715
+ 1,
716
+ 1,
717
+ 1,
718
+ 1,
719
+ 1,
720
+ 1,
721
+ 1,
722
+ 1,
723
+ 1,
724
+ 0,
725
+ 0,
726
+ 0,
727
+ 0,
728
+ 0,
729
+ 0,
730
+ // 48 - 63
731
+ 0,
732
+ 1,
733
+ 1,
734
+ 1,
735
+ 1,
736
+ 1,
737
+ 1,
738
+ 1,
739
+ 1,
740
+ 1,
741
+ 1,
742
+ 1,
743
+ 1,
744
+ 1,
745
+ 1,
746
+ 1,
747
+ // 64 - 79
748
+ 1,
749
+ 1,
750
+ 1,
751
+ 1,
752
+ 1,
753
+ 1,
754
+ 1,
755
+ 1,
756
+ 1,
757
+ 1,
758
+ 1,
759
+ 0,
760
+ 0,
761
+ 0,
762
+ 1,
763
+ 1,
764
+ // 80 - 95
765
+ 1,
766
+ 1,
767
+ 1,
768
+ 1,
769
+ 1,
770
+ 1,
771
+ 1,
772
+ 1,
773
+ 1,
774
+ 1,
775
+ 1,
776
+ 1,
777
+ 1,
778
+ 1,
779
+ 1,
780
+ 1,
781
+ // 96 - 111
782
+ 1,
783
+ 1,
784
+ 1,
785
+ 1,
786
+ 1,
787
+ 1,
788
+ 1,
789
+ 1,
790
+ 1,
791
+ 1,
792
+ 1,
793
+ 0,
794
+ 1,
795
+ 0,
796
+ 1,
797
+ 0
798
+ // 112 - 127
799
+ ];
800
+ function push(dest, name, elem) {
801
+ if (Object.prototype.hasOwnProperty.call(dest, name)) dest[name].push(elem);
802
+ else dest[name] = [elem];
803
+ }
804
+ function parse(header) {
805
+ const offers = {};
806
+ if (header === void 0 || header === "") return offers;
807
+ var params = {};
808
+ var mustUnescape = false;
809
+ var isEscaping = false;
810
+ var inQuotes = false;
811
+ var extensionName;
812
+ var paramName;
813
+ var start = -1;
814
+ var end = -1;
815
+ for (var i = 0; i < header.length; i++) {
816
+ const code = header.charCodeAt(i);
817
+ if (extensionName === void 0) {
818
+ if (end === -1 && tokenChars[code] === 1) {
819
+ if (start === -1) start = i;
820
+ } else if (code === 32 || code === 9) {
821
+ if (end === -1 && start !== -1) end = i;
822
+ } else if (code === 59 || code === 44) {
823
+ if (start === -1) {
824
+ throw new SyntaxError(`Unexpected character at index ${i}`);
825
+ }
826
+ if (end === -1) end = i;
827
+ const name = header.slice(start, end);
828
+ if (code === 44) {
829
+ push(offers, name, params);
830
+ params = {};
831
+ } else {
832
+ extensionName = name;
833
+ }
834
+ start = end = -1;
835
+ } else {
836
+ throw new SyntaxError(`Unexpected character at index ${i}`);
837
+ }
838
+ } else if (paramName === void 0) {
839
+ if (end === -1 && tokenChars[code] === 1) {
840
+ if (start === -1) start = i;
841
+ } else if (code === 32 || code === 9) {
842
+ if (end === -1 && start !== -1) end = i;
843
+ } else if (code === 59 || code === 44) {
844
+ if (start === -1) {
845
+ throw new SyntaxError(`Unexpected character at index ${i}`);
846
+ }
847
+ if (end === -1) end = i;
848
+ push(params, header.slice(start, end), true);
849
+ if (code === 44) {
850
+ push(offers, extensionName, params);
851
+ params = {};
852
+ extensionName = void 0;
853
+ }
854
+ start = end = -1;
855
+ } else if (code === 61 && start !== -1 && end === -1) {
856
+ paramName = header.slice(start, i);
857
+ start = end = -1;
858
+ } else {
859
+ throw new SyntaxError(`Unexpected character at index ${i}`);
860
+ }
861
+ } else {
862
+ if (isEscaping) {
863
+ if (tokenChars[code] !== 1) {
864
+ throw new SyntaxError(`Unexpected character at index ${i}`);
865
+ }
866
+ if (start === -1) start = i;
867
+ else if (!mustUnescape) mustUnescape = true;
868
+ isEscaping = false;
869
+ } else if (inQuotes) {
870
+ if (tokenChars[code] === 1) {
871
+ if (start === -1) start = i;
872
+ } else if (code === 34 && start !== -1) {
873
+ inQuotes = false;
874
+ end = i;
875
+ } else if (code === 92) {
876
+ isEscaping = true;
877
+ } else {
878
+ throw new SyntaxError(`Unexpected character at index ${i}`);
879
+ }
880
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
881
+ inQuotes = true;
882
+ } else if (end === -1 && tokenChars[code] === 1) {
883
+ if (start === -1) start = i;
884
+ } else if (start !== -1 && (code === 32 || code === 9)) {
885
+ if (end === -1) end = i;
886
+ } else if (code === 59 || code === 44) {
887
+ if (start === -1) {
888
+ throw new SyntaxError(`Unexpected character at index ${i}`);
889
+ }
890
+ if (end === -1) end = i;
891
+ var value = header.slice(start, end);
892
+ if (mustUnescape) {
893
+ value = value.replace(/\\/g, "");
894
+ mustUnescape = false;
895
+ }
896
+ push(params, paramName, value);
897
+ if (code === 44) {
898
+ push(offers, extensionName, params);
899
+ params = {};
900
+ extensionName = void 0;
901
+ }
902
+ paramName = void 0;
903
+ start = end = -1;
904
+ } else {
905
+ throw new SyntaxError(`Unexpected character at index ${i}`);
906
+ }
907
+ }
908
+ }
909
+ if (start === -1 || inQuotes) {
910
+ throw new SyntaxError("Unexpected end of input");
911
+ }
912
+ if (end === -1) end = i;
913
+ const token = header.slice(start, end);
914
+ if (extensionName === void 0) {
915
+ push(offers, token, {});
916
+ } else {
917
+ if (paramName === void 0) {
918
+ push(params, token, true);
919
+ } else if (mustUnescape) {
920
+ push(params, paramName, token.replace(/\\/g, ""));
921
+ } else {
922
+ push(params, paramName, token);
923
+ }
924
+ push(offers, extensionName, params);
925
+ }
926
+ return offers;
927
+ }
928
+ function format(extensions) {
929
+ return Object.keys(extensions).map((extension) => {
930
+ var configurations = extensions[extension];
931
+ if (!Array.isArray(configurations)) configurations = [configurations];
932
+ return configurations.map((params) => {
933
+ return [extension].concat(
934
+ Object.keys(params).map((k) => {
935
+ var values = params[k];
936
+ if (!Array.isArray(values)) values = [values];
937
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
938
+ })
939
+ ).join("; ");
940
+ }).join(", ");
941
+ }).join(", ");
942
+ }
943
+ module.exports = { format, parse };
944
+ }
945
+ });
946
+
947
+ // ../../node_modules/ws/lib/validation.js
948
+ var require_validation = __commonJS({
949
+ "../../node_modules/ws/lib/validation.js"(exports) {
950
+ try {
951
+ const isValidUTF8 = __require("utf-8-validate");
952
+ exports.isValidUTF8 = typeof isValidUTF8 === "object" ? isValidUTF8.Validation.isValidUTF8 : isValidUTF8;
953
+ } catch (e) {
954
+ exports.isValidUTF8 = () => true;
955
+ }
956
+ exports.isValidStatusCode = (code) => {
957
+ return code >= 1e3 && code <= 1013 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
958
+ };
959
+ }
960
+ });
961
+
962
+ // ../../node_modules/ws/lib/receiver.js
963
+ var require_receiver = __commonJS({
964
+ "../../node_modules/ws/lib/receiver.js"(exports, module) {
965
+ var { Writable } = __require("stream");
966
+ var PerMessageDeflate = require_permessage_deflate();
967
+ var {
968
+ BINARY_TYPES,
969
+ EMPTY_BUFFER,
970
+ kStatusCode,
971
+ kWebSocket
972
+ } = require_constants();
973
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
974
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
975
+ var GET_INFO = 0;
976
+ var GET_PAYLOAD_LENGTH_16 = 1;
977
+ var GET_PAYLOAD_LENGTH_64 = 2;
978
+ var GET_MASK = 3;
979
+ var GET_DATA = 4;
980
+ var INFLATING = 5;
981
+ var Receiver = class extends Writable {
982
+ /**
983
+ * Creates a Receiver instance.
984
+ *
985
+ * @param {String} binaryType The type for binary data
986
+ * @param {Object} extensions An object containing the negotiated extensions
987
+ * @param {Number} maxPayload The maximum allowed message length
988
+ */
989
+ constructor(binaryType, extensions, maxPayload) {
990
+ super();
991
+ this._binaryType = binaryType || BINARY_TYPES[0];
992
+ this[kWebSocket] = void 0;
993
+ this._extensions = extensions || {};
994
+ this._maxPayload = maxPayload | 0;
995
+ this._bufferedBytes = 0;
996
+ this._buffers = [];
997
+ this._compressed = false;
998
+ this._payloadLength = 0;
999
+ this._mask = void 0;
1000
+ this._fragmented = 0;
1001
+ this._masked = false;
1002
+ this._fin = false;
1003
+ this._opcode = 0;
1004
+ this._totalPayloadLength = 0;
1005
+ this._messageLength = 0;
1006
+ this._fragments = [];
1007
+ this._state = GET_INFO;
1008
+ this._loop = false;
1009
+ }
1010
+ /**
1011
+ * Implements `Writable.prototype._write()`.
1012
+ *
1013
+ * @param {Buffer} chunk The chunk of data to write
1014
+ * @param {String} encoding The character encoding of `chunk`
1015
+ * @param {Function} cb Callback
1016
+ */
1017
+ _write(chunk, encoding, cb) {
1018
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
1019
+ this._bufferedBytes += chunk.length;
1020
+ this._buffers.push(chunk);
1021
+ this.startLoop(cb);
1022
+ }
1023
+ /**
1024
+ * Consumes `n` bytes from the buffered data.
1025
+ *
1026
+ * @param {Number} n The number of bytes to consume
1027
+ * @return {Buffer} The consumed bytes
1028
+ * @private
1029
+ */
1030
+ consume(n) {
1031
+ this._bufferedBytes -= n;
1032
+ if (n === this._buffers[0].length) return this._buffers.shift();
1033
+ if (n < this._buffers[0].length) {
1034
+ const buf = this._buffers[0];
1035
+ this._buffers[0] = buf.slice(n);
1036
+ return buf.slice(0, n);
1037
+ }
1038
+ const dst = Buffer.allocUnsafe(n);
1039
+ do {
1040
+ const buf = this._buffers[0];
1041
+ if (n >= buf.length) {
1042
+ this._buffers.shift().copy(dst, dst.length - n);
1043
+ } else {
1044
+ buf.copy(dst, dst.length - n, 0, n);
1045
+ this._buffers[0] = buf.slice(n);
1046
+ }
1047
+ n -= buf.length;
1048
+ } while (n > 0);
1049
+ return dst;
1050
+ }
1051
+ /**
1052
+ * Starts the parsing loop.
1053
+ *
1054
+ * @param {Function} cb Callback
1055
+ * @private
1056
+ */
1057
+ startLoop(cb) {
1058
+ var err;
1059
+ this._loop = true;
1060
+ do {
1061
+ switch (this._state) {
1062
+ case GET_INFO:
1063
+ err = this.getInfo();
1064
+ break;
1065
+ case GET_PAYLOAD_LENGTH_16:
1066
+ err = this.getPayloadLength16();
1067
+ break;
1068
+ case GET_PAYLOAD_LENGTH_64:
1069
+ err = this.getPayloadLength64();
1070
+ break;
1071
+ case GET_MASK:
1072
+ this.getMask();
1073
+ break;
1074
+ case GET_DATA:
1075
+ err = this.getData(cb);
1076
+ break;
1077
+ default:
1078
+ this._loop = false;
1079
+ return;
1080
+ }
1081
+ } while (this._loop);
1082
+ cb(err);
1083
+ }
1084
+ /**
1085
+ * Reads the first two bytes of a frame.
1086
+ *
1087
+ * @return {(RangeError|undefined)} A possible error
1088
+ * @private
1089
+ */
1090
+ getInfo() {
1091
+ if (this._bufferedBytes < 2) {
1092
+ this._loop = false;
1093
+ return;
1094
+ }
1095
+ const buf = this.consume(2);
1096
+ if ((buf[0] & 48) !== 0) {
1097
+ this._loop = false;
1098
+ return error(RangeError, "RSV2 and RSV3 must be clear", true, 1002);
1099
+ }
1100
+ const compressed = (buf[0] & 64) === 64;
1101
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
1102
+ this._loop = false;
1103
+ return error(RangeError, "RSV1 must be clear", true, 1002);
1104
+ }
1105
+ this._fin = (buf[0] & 128) === 128;
1106
+ this._opcode = buf[0] & 15;
1107
+ this._payloadLength = buf[1] & 127;
1108
+ if (this._opcode === 0) {
1109
+ if (compressed) {
1110
+ this._loop = false;
1111
+ return error(RangeError, "RSV1 must be clear", true, 1002);
1112
+ }
1113
+ if (!this._fragmented) {
1114
+ this._loop = false;
1115
+ return error(RangeError, "invalid opcode 0", true, 1002);
1116
+ }
1117
+ this._opcode = this._fragmented;
1118
+ } else if (this._opcode === 1 || this._opcode === 2) {
1119
+ if (this._fragmented) {
1120
+ this._loop = false;
1121
+ return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002);
1122
+ }
1123
+ this._compressed = compressed;
1124
+ } else if (this._opcode > 7 && this._opcode < 11) {
1125
+ if (!this._fin) {
1126
+ this._loop = false;
1127
+ return error(RangeError, "FIN must be set", true, 1002);
1128
+ }
1129
+ if (compressed) {
1130
+ this._loop = false;
1131
+ return error(RangeError, "RSV1 must be clear", true, 1002);
1132
+ }
1133
+ if (this._payloadLength > 125) {
1134
+ this._loop = false;
1135
+ return error(
1136
+ RangeError,
1137
+ `invalid payload length ${this._payloadLength}`,
1138
+ true,
1139
+ 1002
1140
+ );
1141
+ }
1142
+ } else {
1143
+ this._loop = false;
1144
+ return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002);
1145
+ }
1146
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1147
+ this._masked = (buf[1] & 128) === 128;
1148
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1149
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1150
+ else return this.haveLength();
1151
+ }
1152
+ /**
1153
+ * Gets extended payload length (7+16).
1154
+ *
1155
+ * @return {(RangeError|undefined)} A possible error
1156
+ * @private
1157
+ */
1158
+ getPayloadLength16() {
1159
+ if (this._bufferedBytes < 2) {
1160
+ this._loop = false;
1161
+ return;
1162
+ }
1163
+ this._payloadLength = this.consume(2).readUInt16BE(0);
1164
+ return this.haveLength();
1165
+ }
1166
+ /**
1167
+ * Gets extended payload length (7+64).
1168
+ *
1169
+ * @return {(RangeError|undefined)} A possible error
1170
+ * @private
1171
+ */
1172
+ getPayloadLength64() {
1173
+ if (this._bufferedBytes < 8) {
1174
+ this._loop = false;
1175
+ return;
1176
+ }
1177
+ const buf = this.consume(8);
1178
+ const num = buf.readUInt32BE(0);
1179
+ if (num > Math.pow(2, 53 - 32) - 1) {
1180
+ this._loop = false;
1181
+ return error(
1182
+ RangeError,
1183
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
1184
+ false,
1185
+ 1009
1186
+ );
1187
+ }
1188
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1189
+ return this.haveLength();
1190
+ }
1191
+ /**
1192
+ * Payload length has been read.
1193
+ *
1194
+ * @return {(RangeError|undefined)} A possible error
1195
+ * @private
1196
+ */
1197
+ haveLength() {
1198
+ if (this._payloadLength && this._opcode < 8) {
1199
+ this._totalPayloadLength += this._payloadLength;
1200
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1201
+ this._loop = false;
1202
+ return error(RangeError, "Max payload size exceeded", false, 1009);
1203
+ }
1204
+ }
1205
+ if (this._masked) this._state = GET_MASK;
1206
+ else this._state = GET_DATA;
1207
+ }
1208
+ /**
1209
+ * Reads mask bytes.
1210
+ *
1211
+ * @private
1212
+ */
1213
+ getMask() {
1214
+ if (this._bufferedBytes < 4) {
1215
+ this._loop = false;
1216
+ return;
1217
+ }
1218
+ this._mask = this.consume(4);
1219
+ this._state = GET_DATA;
1220
+ }
1221
+ /**
1222
+ * Reads data bytes.
1223
+ *
1224
+ * @param {Function} cb Callback
1225
+ * @return {(Error|RangeError|undefined)} A possible error
1226
+ * @private
1227
+ */
1228
+ getData(cb) {
1229
+ var data = EMPTY_BUFFER;
1230
+ if (this._payloadLength) {
1231
+ if (this._bufferedBytes < this._payloadLength) {
1232
+ this._loop = false;
1233
+ return;
1234
+ }
1235
+ data = this.consume(this._payloadLength);
1236
+ if (this._masked) unmask(data, this._mask);
1237
+ }
1238
+ if (this._opcode > 7) return this.controlMessage(data);
1239
+ if (this._compressed) {
1240
+ this._state = INFLATING;
1241
+ this.decompress(data, cb);
1242
+ return;
1243
+ }
1244
+ if (data.length) {
1245
+ this._messageLength = this._totalPayloadLength;
1246
+ this._fragments.push(data);
1247
+ }
1248
+ return this.dataMessage();
1249
+ }
1250
+ /**
1251
+ * Decompresses data.
1252
+ *
1253
+ * @param {Buffer} data Compressed data
1254
+ * @param {Function} cb Callback
1255
+ * @private
1256
+ */
1257
+ decompress(data, cb) {
1258
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1259
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1260
+ if (err) return cb(err);
1261
+ if (buf.length) {
1262
+ this._messageLength += buf.length;
1263
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1264
+ return cb(
1265
+ error(RangeError, "Max payload size exceeded", false, 1009)
1266
+ );
1267
+ }
1268
+ this._fragments.push(buf);
1269
+ }
1270
+ const er = this.dataMessage();
1271
+ if (er) return cb(er);
1272
+ this.startLoop(cb);
1273
+ });
1274
+ }
1275
+ /**
1276
+ * Handles a data message.
1277
+ *
1278
+ * @return {(Error|undefined)} A possible error
1279
+ * @private
1280
+ */
1281
+ dataMessage() {
1282
+ if (this._fin) {
1283
+ const messageLength = this._messageLength;
1284
+ const fragments = this._fragments;
1285
+ this._totalPayloadLength = 0;
1286
+ this._messageLength = 0;
1287
+ this._fragmented = 0;
1288
+ this._fragments = [];
1289
+ if (this._opcode === 2) {
1290
+ var data;
1291
+ if (this._binaryType === "nodebuffer") {
1292
+ data = concat(fragments, messageLength);
1293
+ } else if (this._binaryType === "arraybuffer") {
1294
+ data = toArrayBuffer(concat(fragments, messageLength));
1295
+ } else {
1296
+ data = fragments;
1297
+ }
1298
+ this.emit("message", data);
1299
+ } else {
1300
+ const buf = concat(fragments, messageLength);
1301
+ if (!isValidUTF8(buf)) {
1302
+ this._loop = false;
1303
+ return error(Error, "invalid UTF-8 sequence", true, 1007);
1304
+ }
1305
+ this.emit("message", buf.toString());
1306
+ }
1307
+ }
1308
+ this._state = GET_INFO;
1309
+ }
1310
+ /**
1311
+ * Handles a control message.
1312
+ *
1313
+ * @param {Buffer} data Data to handle
1314
+ * @return {(Error|RangeError|undefined)} A possible error
1315
+ * @private
1316
+ */
1317
+ controlMessage(data) {
1318
+ if (this._opcode === 8) {
1319
+ this._loop = false;
1320
+ if (data.length === 0) {
1321
+ this.emit("conclude", 1005, "");
1322
+ this.end();
1323
+ } else if (data.length === 1) {
1324
+ return error(RangeError, "invalid payload length 1", true, 1002);
1325
+ } else {
1326
+ const code = data.readUInt16BE(0);
1327
+ if (!isValidStatusCode(code)) {
1328
+ return error(RangeError, `invalid status code ${code}`, true, 1002);
1329
+ }
1330
+ const buf = data.slice(2);
1331
+ if (!isValidUTF8(buf)) {
1332
+ return error(Error, "invalid UTF-8 sequence", true, 1007);
1333
+ }
1334
+ this.emit("conclude", code, buf.toString());
1335
+ this.end();
1336
+ }
1337
+ } else if (this._opcode === 9) {
1338
+ this.emit("ping", data);
1339
+ } else {
1340
+ this.emit("pong", data);
1341
+ }
1342
+ this._state = GET_INFO;
1343
+ }
1344
+ };
1345
+ module.exports = Receiver;
1346
+ function error(ErrorCtor, message, prefix, statusCode) {
1347
+ const err = new ErrorCtor(
1348
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1349
+ );
1350
+ Error.captureStackTrace(err, error);
1351
+ err[kStatusCode] = statusCode;
1352
+ return err;
1353
+ }
1354
+ }
1355
+ });
1356
+
1357
+ // ../../node_modules/ws/lib/sender.js
1358
+ var require_sender = __commonJS({
1359
+ "../../node_modules/ws/lib/sender.js"(exports, module) {
1360
+ var { randomBytes } = __require("crypto");
1361
+ var PerMessageDeflate = require_permessage_deflate();
1362
+ var { EMPTY_BUFFER } = require_constants();
1363
+ var { isValidStatusCode } = require_validation();
1364
+ var { mask: applyMask, toBuffer } = require_buffer_util();
1365
+ var Sender = class _Sender {
1366
+ /**
1367
+ * Creates a Sender instance.
1368
+ *
1369
+ * @param {net.Socket} socket The connection socket
1370
+ * @param {Object} extensions An object containing the negotiated extensions
1371
+ */
1372
+ constructor(socket, extensions) {
1373
+ this._extensions = extensions || {};
1374
+ this._socket = socket;
1375
+ this._firstFragment = true;
1376
+ this._compress = false;
1377
+ this._bufferedBytes = 0;
1378
+ this._deflating = false;
1379
+ this._queue = [];
1380
+ }
1381
+ /**
1382
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1383
+ *
1384
+ * @param {Buffer} data The data to frame
1385
+ * @param {Object} options Options object
1386
+ * @param {Number} options.opcode The opcode
1387
+ * @param {Boolean} options.readOnly Specifies whether `data` can be modified
1388
+ * @param {Boolean} options.fin Specifies whether or not to set the FIN bit
1389
+ * @param {Boolean} options.mask Specifies whether or not to mask `data`
1390
+ * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit
1391
+ * @return {Buffer[]} The framed data as a list of `Buffer` instances
1392
+ * @public
1393
+ */
1394
+ static frame(data, options) {
1395
+ const merge = options.mask && options.readOnly;
1396
+ var offset = options.mask ? 6 : 2;
1397
+ var payloadLength = data.length;
1398
+ if (data.length >= 65536) {
1399
+ offset += 8;
1400
+ payloadLength = 127;
1401
+ } else if (data.length > 125) {
1402
+ offset += 2;
1403
+ payloadLength = 126;
1404
+ }
1405
+ const target = Buffer.allocUnsafe(merge ? data.length + offset : offset);
1406
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1407
+ if (options.rsv1) target[0] |= 64;
1408
+ target[1] = payloadLength;
1409
+ if (payloadLength === 126) {
1410
+ target.writeUInt16BE(data.length, 2);
1411
+ } else if (payloadLength === 127) {
1412
+ target.writeUInt32BE(0, 2);
1413
+ target.writeUInt32BE(data.length, 6);
1414
+ }
1415
+ if (!options.mask) return [target, data];
1416
+ const mask = randomBytes(4);
1417
+ target[1] |= 128;
1418
+ target[offset - 4] = mask[0];
1419
+ target[offset - 3] = mask[1];
1420
+ target[offset - 2] = mask[2];
1421
+ target[offset - 1] = mask[3];
1422
+ if (merge) {
1423
+ applyMask(data, mask, target, offset, data.length);
1424
+ return [target];
1425
+ }
1426
+ applyMask(data, mask, data, 0, data.length);
1427
+ return [target, data];
1428
+ }
1429
+ /**
1430
+ * Sends a close message to the other peer.
1431
+ *
1432
+ * @param {(Number|undefined)} code The status code component of the body
1433
+ * @param {String} data The message component of the body
1434
+ * @param {Boolean} mask Specifies whether or not to mask the message
1435
+ * @param {Function} cb Callback
1436
+ * @public
1437
+ */
1438
+ close(code, data, mask, cb) {
1439
+ var buf;
1440
+ if (code === void 0) {
1441
+ buf = EMPTY_BUFFER;
1442
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1443
+ throw new TypeError("First argument must be a valid error code number");
1444
+ } else if (data === void 0 || data === "") {
1445
+ buf = Buffer.allocUnsafe(2);
1446
+ buf.writeUInt16BE(code, 0);
1447
+ } else {
1448
+ buf = Buffer.allocUnsafe(2 + Buffer.byteLength(data));
1449
+ buf.writeUInt16BE(code, 0);
1450
+ buf.write(data, 2);
1451
+ }
1452
+ if (this._deflating) {
1453
+ this.enqueue([this.doClose, buf, mask, cb]);
1454
+ } else {
1455
+ this.doClose(buf, mask, cb);
1456
+ }
1457
+ }
1458
+ /**
1459
+ * Frames and sends a close message.
1460
+ *
1461
+ * @param {Buffer} data The message to send
1462
+ * @param {Boolean} mask Specifies whether or not to mask `data`
1463
+ * @param {Function} cb Callback
1464
+ * @private
1465
+ */
1466
+ doClose(data, mask, cb) {
1467
+ this.sendFrame(
1468
+ _Sender.frame(data, {
1469
+ fin: true,
1470
+ rsv1: false,
1471
+ opcode: 8,
1472
+ mask,
1473
+ readOnly: false
1474
+ }),
1475
+ cb
1476
+ );
1477
+ }
1478
+ /**
1479
+ * Sends a ping message to the other peer.
1480
+ *
1481
+ * @param {*} data The message to send
1482
+ * @param {Boolean} mask Specifies whether or not to mask `data`
1483
+ * @param {Function} cb Callback
1484
+ * @public
1485
+ */
1486
+ ping(data, mask, cb) {
1487
+ const buf = toBuffer(data);
1488
+ if (this._deflating) {
1489
+ this.enqueue([this.doPing, buf, mask, toBuffer.readOnly, cb]);
1490
+ } else {
1491
+ this.doPing(buf, mask, toBuffer.readOnly, cb);
1492
+ }
1493
+ }
1494
+ /**
1495
+ * Frames and sends a ping message.
1496
+ *
1497
+ * @param {*} data The message to send
1498
+ * @param {Boolean} mask Specifies whether or not to mask `data`
1499
+ * @param {Boolean} readOnly Specifies whether `data` can be modified
1500
+ * @param {Function} cb Callback
1501
+ * @private
1502
+ */
1503
+ doPing(data, mask, readOnly, cb) {
1504
+ this.sendFrame(
1505
+ _Sender.frame(data, {
1506
+ fin: true,
1507
+ rsv1: false,
1508
+ opcode: 9,
1509
+ mask,
1510
+ readOnly
1511
+ }),
1512
+ cb
1513
+ );
1514
+ }
1515
+ /**
1516
+ * Sends a pong message to the other peer.
1517
+ *
1518
+ * @param {*} data The message to send
1519
+ * @param {Boolean} mask Specifies whether or not to mask `data`
1520
+ * @param {Function} cb Callback
1521
+ * @public
1522
+ */
1523
+ pong(data, mask, cb) {
1524
+ const buf = toBuffer(data);
1525
+ if (this._deflating) {
1526
+ this.enqueue([this.doPong, buf, mask, toBuffer.readOnly, cb]);
1527
+ } else {
1528
+ this.doPong(buf, mask, toBuffer.readOnly, cb);
1529
+ }
1530
+ }
1531
+ /**
1532
+ * Frames and sends a pong message.
1533
+ *
1534
+ * @param {*} data The message to send
1535
+ * @param {Boolean} mask Specifies whether or not to mask `data`
1536
+ * @param {Boolean} readOnly Specifies whether `data` can be modified
1537
+ * @param {Function} cb Callback
1538
+ * @private
1539
+ */
1540
+ doPong(data, mask, readOnly, cb) {
1541
+ this.sendFrame(
1542
+ _Sender.frame(data, {
1543
+ fin: true,
1544
+ rsv1: false,
1545
+ opcode: 10,
1546
+ mask,
1547
+ readOnly
1548
+ }),
1549
+ cb
1550
+ );
1551
+ }
1552
+ /**
1553
+ * Sends a data message to the other peer.
1554
+ *
1555
+ * @param {*} data The message to send
1556
+ * @param {Object} options Options object
1557
+ * @param {Boolean} options.compress Specifies whether or not to compress `data`
1558
+ * @param {Boolean} options.binary Specifies whether `data` is binary or text
1559
+ * @param {Boolean} options.fin Specifies whether the fragment is the last one
1560
+ * @param {Boolean} options.mask Specifies whether or not to mask `data`
1561
+ * @param {Function} cb Callback
1562
+ * @public
1563
+ */
1564
+ send(data, options, cb) {
1565
+ const buf = toBuffer(data);
1566
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1567
+ var opcode = options.binary ? 2 : 1;
1568
+ var rsv1 = options.compress;
1569
+ if (this._firstFragment) {
1570
+ this._firstFragment = false;
1571
+ if (rsv1 && perMessageDeflate) {
1572
+ rsv1 = buf.length >= perMessageDeflate._threshold;
1573
+ }
1574
+ this._compress = rsv1;
1575
+ } else {
1576
+ rsv1 = false;
1577
+ opcode = 0;
1578
+ }
1579
+ if (options.fin) this._firstFragment = true;
1580
+ if (perMessageDeflate) {
1581
+ const opts = {
1582
+ fin: options.fin,
1583
+ rsv1,
1584
+ opcode,
1585
+ mask: options.mask,
1586
+ readOnly: toBuffer.readOnly
1587
+ };
1588
+ if (this._deflating) {
1589
+ this.enqueue([this.dispatch, buf, this._compress, opts, cb]);
1590
+ } else {
1591
+ this.dispatch(buf, this._compress, opts, cb);
1592
+ }
1593
+ } else {
1594
+ this.sendFrame(
1595
+ _Sender.frame(buf, {
1596
+ fin: options.fin,
1597
+ rsv1: false,
1598
+ opcode,
1599
+ mask: options.mask,
1600
+ readOnly: toBuffer.readOnly
1601
+ }),
1602
+ cb
1603
+ );
1604
+ }
1605
+ }
1606
+ /**
1607
+ * Dispatches a data message.
1608
+ *
1609
+ * @param {Buffer} data The message to send
1610
+ * @param {Boolean} compress Specifies whether or not to compress `data`
1611
+ * @param {Object} options Options object
1612
+ * @param {Number} options.opcode The opcode
1613
+ * @param {Boolean} options.readOnly Specifies whether `data` can be modified
1614
+ * @param {Boolean} options.fin Specifies whether or not to set the FIN bit
1615
+ * @param {Boolean} options.mask Specifies whether or not to mask `data`
1616
+ * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit
1617
+ * @param {Function} cb Callback
1618
+ * @private
1619
+ */
1620
+ dispatch(data, compress, options, cb) {
1621
+ if (!compress) {
1622
+ this.sendFrame(_Sender.frame(data, options), cb);
1623
+ return;
1624
+ }
1625
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1626
+ this._deflating = true;
1627
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1628
+ this._deflating = false;
1629
+ options.readOnly = false;
1630
+ this.sendFrame(_Sender.frame(buf, options), cb);
1631
+ this.dequeue();
1632
+ });
1633
+ }
1634
+ /**
1635
+ * Executes queued send operations.
1636
+ *
1637
+ * @private
1638
+ */
1639
+ dequeue() {
1640
+ while (!this._deflating && this._queue.length) {
1641
+ const params = this._queue.shift();
1642
+ this._bufferedBytes -= params[1].length;
1643
+ params[0].apply(this, params.slice(1));
1644
+ }
1645
+ }
1646
+ /**
1647
+ * Enqueues a send operation.
1648
+ *
1649
+ * @param {Array} params Send operation parameters.
1650
+ * @private
1651
+ */
1652
+ enqueue(params) {
1653
+ this._bufferedBytes += params[1].length;
1654
+ this._queue.push(params);
1655
+ }
1656
+ /**
1657
+ * Sends a frame.
1658
+ *
1659
+ * @param {Buffer[]} list The frame to send
1660
+ * @param {Function} cb Callback
1661
+ * @private
1662
+ */
1663
+ sendFrame(list, cb) {
1664
+ if (list.length === 2) {
1665
+ this._socket.cork();
1666
+ this._socket.write(list[0]);
1667
+ this._socket.write(list[1], cb);
1668
+ this._socket.uncork();
1669
+ } else {
1670
+ this._socket.write(list[0], cb);
1671
+ }
1672
+ }
1673
+ };
1674
+ module.exports = Sender;
1675
+ }
1676
+ });
1677
+
1678
+ // ../../node_modules/ws/lib/websocket.js
1679
+ var require_websocket = __commonJS({
1680
+ "../../node_modules/ws/lib/websocket.js"(exports, module) {
1681
+ var EventEmitter = __require("events");
1682
+ var crypto2 = __require("crypto");
1683
+ var https = __require("https");
1684
+ var http = __require("http");
1685
+ var net = __require("net");
1686
+ var tls = __require("tls");
1687
+ var url = __require("url");
1688
+ var PerMessageDeflate = require_permessage_deflate();
1689
+ var EventTarget = require_event_target();
1690
+ var extension = require_extension();
1691
+ var Receiver = require_receiver();
1692
+ var Sender = require_sender();
1693
+ var {
1694
+ BINARY_TYPES,
1695
+ EMPTY_BUFFER,
1696
+ GUID,
1697
+ kStatusCode,
1698
+ kWebSocket,
1699
+ NOOP
1700
+ } = require_constants();
1701
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
1702
+ var protocolVersions = [8, 13];
1703
+ var closeTimeout = 30 * 1e3;
1704
+ var WebSocket2 = class _WebSocket extends EventEmitter {
1705
+ /**
1706
+ * Create a new `WebSocket`.
1707
+ *
1708
+ * @param {(String|url.Url|url.URL)} address The URL to which to connect
1709
+ * @param {(String|String[])} protocols The subprotocols
1710
+ * @param {Object} options Connection options
1711
+ */
1712
+ constructor(address, protocols, options) {
1713
+ super();
1714
+ this.readyState = _WebSocket.CONNECTING;
1715
+ this.protocol = "";
1716
+ this._binaryType = BINARY_TYPES[0];
1717
+ this._closeFrameReceived = false;
1718
+ this._closeFrameSent = false;
1719
+ this._closeMessage = "";
1720
+ this._closeTimer = null;
1721
+ this._closeCode = 1006;
1722
+ this._extensions = {};
1723
+ this._receiver = null;
1724
+ this._sender = null;
1725
+ this._socket = null;
1726
+ if (address !== null) {
1727
+ this._isServer = false;
1728
+ this._redirects = 0;
1729
+ if (Array.isArray(protocols)) {
1730
+ protocols = protocols.join(", ");
1731
+ } else if (typeof protocols === "object" && protocols !== null) {
1732
+ options = protocols;
1733
+ protocols = void 0;
1734
+ }
1735
+ initAsClient(this, address, protocols, options);
1736
+ } else {
1737
+ this._isServer = true;
1738
+ }
1739
+ }
1740
+ get CONNECTING() {
1741
+ return _WebSocket.CONNECTING;
1742
+ }
1743
+ get CLOSING() {
1744
+ return _WebSocket.CLOSING;
1745
+ }
1746
+ get CLOSED() {
1747
+ return _WebSocket.CLOSED;
1748
+ }
1749
+ get OPEN() {
1750
+ return _WebSocket.OPEN;
1751
+ }
1752
+ /**
1753
+ * This deviates from the WHATWG interface since ws doesn't support the
1754
+ * required default "blob" type (instead we define a custom "nodebuffer"
1755
+ * type).
1756
+ *
1757
+ * @type {String}
1758
+ */
1759
+ get binaryType() {
1760
+ return this._binaryType;
1761
+ }
1762
+ set binaryType(type) {
1763
+ if (!BINARY_TYPES.includes(type)) return;
1764
+ this._binaryType = type;
1765
+ if (this._receiver) this._receiver._binaryType = type;
1766
+ }
1767
+ /**
1768
+ * @type {Number}
1769
+ */
1770
+ get bufferedAmount() {
1771
+ if (!this._socket) return 0;
1772
+ return (this._socket.bufferSize || 0) + this._sender._bufferedBytes;
1773
+ }
1774
+ /**
1775
+ * @type {String}
1776
+ */
1777
+ get extensions() {
1778
+ return Object.keys(this._extensions).join();
1779
+ }
1780
+ /**
1781
+ * Set up the socket and the internal resources.
1782
+ *
1783
+ * @param {net.Socket} socket The network socket between the server and client
1784
+ * @param {Buffer} head The first packet of the upgraded stream
1785
+ * @param {Number} maxPayload The maximum allowed message size
1786
+ * @private
1787
+ */
1788
+ setSocket(socket, head, maxPayload) {
1789
+ const receiver = new Receiver(
1790
+ this._binaryType,
1791
+ this._extensions,
1792
+ maxPayload
1793
+ );
1794
+ this._sender = new Sender(socket, this._extensions);
1795
+ this._receiver = receiver;
1796
+ this._socket = socket;
1797
+ receiver[kWebSocket] = this;
1798
+ socket[kWebSocket] = this;
1799
+ receiver.on("conclude", receiverOnConclude);
1800
+ receiver.on("drain", receiverOnDrain);
1801
+ receiver.on("error", receiverOnError);
1802
+ receiver.on("message", receiverOnMessage);
1803
+ receiver.on("ping", receiverOnPing);
1804
+ receiver.on("pong", receiverOnPong);
1805
+ socket.setTimeout(0);
1806
+ socket.setNoDelay();
1807
+ if (head.length > 0) socket.unshift(head);
1808
+ socket.on("close", socketOnClose);
1809
+ socket.on("data", socketOnData);
1810
+ socket.on("end", socketOnEnd);
1811
+ socket.on("error", socketOnError);
1812
+ this.readyState = _WebSocket.OPEN;
1813
+ this.emit("open");
1814
+ }
1815
+ /**
1816
+ * Emit the `'close'` event.
1817
+ *
1818
+ * @private
1819
+ */
1820
+ emitClose() {
1821
+ this.readyState = _WebSocket.CLOSED;
1822
+ if (!this._socket) {
1823
+ this.emit("close", this._closeCode, this._closeMessage);
1824
+ return;
1825
+ }
1826
+ if (this._extensions[PerMessageDeflate.extensionName]) {
1827
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
1828
+ }
1829
+ this._receiver.removeAllListeners();
1830
+ this.emit("close", this._closeCode, this._closeMessage);
1831
+ }
1832
+ /**
1833
+ * Start a closing handshake.
1834
+ *
1835
+ * +----------+ +-----------+ +----------+
1836
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
1837
+ * | +----------+ +-----------+ +----------+ |
1838
+ * +----------+ +-----------+ |
1839
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
1840
+ * +----------+ +-----------+ |
1841
+ * | | | +---+ |
1842
+ * +------------------------+-->|fin| - - - -
1843
+ * | +---+ | +---+
1844
+ * - - - - -|fin|<---------------------+
1845
+ * +---+
1846
+ *
1847
+ * @param {Number} code Status code explaining why the connection is closing
1848
+ * @param {String} data A string explaining why the connection is closing
1849
+ * @public
1850
+ */
1851
+ close(code, data) {
1852
+ if (this.readyState === _WebSocket.CLOSED) return;
1853
+ if (this.readyState === _WebSocket.CONNECTING) {
1854
+ const msg = "WebSocket was closed before the connection was established";
1855
+ return abortHandshake(this, this._req, msg);
1856
+ }
1857
+ if (this.readyState === _WebSocket.CLOSING) {
1858
+ if (this._closeFrameSent && this._closeFrameReceived) this._socket.end();
1859
+ return;
1860
+ }
1861
+ this.readyState = _WebSocket.CLOSING;
1862
+ this._sender.close(code, data, !this._isServer, (err) => {
1863
+ if (err) return;
1864
+ this._closeFrameSent = true;
1865
+ if (this._closeFrameReceived) this._socket.end();
1866
+ });
1867
+ this._closeTimer = setTimeout(
1868
+ this._socket.destroy.bind(this._socket),
1869
+ closeTimeout
1870
+ );
1871
+ }
1872
+ /**
1873
+ * Send a ping.
1874
+ *
1875
+ * @param {*} data The data to send
1876
+ * @param {Boolean} mask Indicates whether or not to mask `data`
1877
+ * @param {Function} cb Callback which is executed when the ping is sent
1878
+ * @public
1879
+ */
1880
+ ping(data, mask, cb) {
1881
+ if (typeof data === "function") {
1882
+ cb = data;
1883
+ data = mask = void 0;
1884
+ } else if (typeof mask === "function") {
1885
+ cb = mask;
1886
+ mask = void 0;
1887
+ }
1888
+ if (this.readyState !== _WebSocket.OPEN) {
1889
+ const err = new Error(
1890
+ `WebSocket is not open: readyState ${this.readyState} (${readyStates[this.readyState]})`
1891
+ );
1892
+ if (cb) return cb(err);
1893
+ throw err;
1894
+ }
1895
+ if (typeof data === "number") data = data.toString();
1896
+ if (mask === void 0) mask = !this._isServer;
1897
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
1898
+ }
1899
+ /**
1900
+ * Send a pong.
1901
+ *
1902
+ * @param {*} data The data to send
1903
+ * @param {Boolean} mask Indicates whether or not to mask `data`
1904
+ * @param {Function} cb Callback which is executed when the pong is sent
1905
+ * @public
1906
+ */
1907
+ pong(data, mask, cb) {
1908
+ if (typeof data === "function") {
1909
+ cb = data;
1910
+ data = mask = void 0;
1911
+ } else if (typeof mask === "function") {
1912
+ cb = mask;
1913
+ mask = void 0;
1914
+ }
1915
+ if (this.readyState !== _WebSocket.OPEN) {
1916
+ const err = new Error(
1917
+ `WebSocket is not open: readyState ${this.readyState} (${readyStates[this.readyState]})`
1918
+ );
1919
+ if (cb) return cb(err);
1920
+ throw err;
1921
+ }
1922
+ if (typeof data === "number") data = data.toString();
1923
+ if (mask === void 0) mask = !this._isServer;
1924
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
1925
+ }
1926
+ /**
1927
+ * Send a data message.
1928
+ *
1929
+ * @param {*} data The message to send
1930
+ * @param {Object} options Options object
1931
+ * @param {Boolean} options.compress Specifies whether or not to compress `data`
1932
+ * @param {Boolean} options.binary Specifies whether `data` is binary or text
1933
+ * @param {Boolean} options.fin Specifies whether the fragment is the last one
1934
+ * @param {Boolean} options.mask Specifies whether or not to mask `data`
1935
+ * @param {Function} cb Callback which is executed when data is written out
1936
+ * @public
1937
+ */
1938
+ send(data, options, cb) {
1939
+ if (typeof options === "function") {
1940
+ cb = options;
1941
+ options = {};
1942
+ }
1943
+ if (this.readyState !== _WebSocket.OPEN) {
1944
+ const err = new Error(
1945
+ `WebSocket is not open: readyState ${this.readyState} (${readyStates[this.readyState]})`
1946
+ );
1947
+ if (cb) return cb(err);
1948
+ throw err;
1949
+ }
1950
+ if (typeof data === "number") data = data.toString();
1951
+ const opts = Object.assign(
1952
+ {
1953
+ binary: typeof data !== "string",
1954
+ mask: !this._isServer,
1955
+ compress: true,
1956
+ fin: true
1957
+ },
1958
+ options
1959
+ );
1960
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
1961
+ opts.compress = false;
1962
+ }
1963
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
1964
+ }
1965
+ /**
1966
+ * Forcibly close the connection.
1967
+ *
1968
+ * @public
1969
+ */
1970
+ terminate() {
1971
+ if (this.readyState === _WebSocket.CLOSED) return;
1972
+ if (this.readyState === _WebSocket.CONNECTING) {
1973
+ const msg = "WebSocket was closed before the connection was established";
1974
+ return abortHandshake(this, this._req, msg);
1975
+ }
1976
+ if (this._socket) {
1977
+ this.readyState = _WebSocket.CLOSING;
1978
+ this._socket.destroy();
1979
+ }
1980
+ }
1981
+ };
1982
+ readyStates.forEach((readyState, i) => {
1983
+ WebSocket2[readyState] = i;
1984
+ });
1985
+ ["open", "error", "close", "message"].forEach((method) => {
1986
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
1987
+ /**
1988
+ * Return the listener of the event.
1989
+ *
1990
+ * @return {(Function|undefined)} The event listener or `undefined`
1991
+ * @public
1992
+ */
1993
+ get() {
1994
+ const listeners = this.listeners(method);
1995
+ for (var i = 0; i < listeners.length; i++) {
1996
+ if (listeners[i]._listener) return listeners[i]._listener;
1997
+ }
1998
+ return void 0;
1999
+ },
2000
+ /**
2001
+ * Add a listener for the event.
2002
+ *
2003
+ * @param {Function} listener The listener to add
2004
+ * @public
2005
+ */
2006
+ set(listener) {
2007
+ const listeners = this.listeners(method);
2008
+ for (var i = 0; i < listeners.length; i++) {
2009
+ if (listeners[i]._listener) this.removeListener(method, listeners[i]);
2010
+ }
2011
+ this.addEventListener(method, listener);
2012
+ }
2013
+ });
2014
+ });
2015
+ WebSocket2.prototype.addEventListener = EventTarget.addEventListener;
2016
+ WebSocket2.prototype.removeEventListener = EventTarget.removeEventListener;
2017
+ module.exports = WebSocket2;
2018
+ function initAsClient(websocket, address, protocols, options) {
2019
+ const opts = Object.assign(
2020
+ {
2021
+ protocolVersion: protocolVersions[1],
2022
+ maxPayload: 100 * 1024 * 1024,
2023
+ perMessageDeflate: true,
2024
+ followRedirects: false,
2025
+ maxRedirects: 10
2026
+ },
2027
+ options,
2028
+ {
2029
+ createConnection: void 0,
2030
+ socketPath: void 0,
2031
+ hostname: void 0,
2032
+ protocol: void 0,
2033
+ timeout: void 0,
2034
+ method: void 0,
2035
+ auth: void 0,
2036
+ host: void 0,
2037
+ path: void 0,
2038
+ port: void 0
2039
+ }
2040
+ );
2041
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2042
+ throw new RangeError(
2043
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2044
+ );
2045
+ }
2046
+ var parsedUrl;
2047
+ if (typeof address === "object" && address.href !== void 0) {
2048
+ parsedUrl = address;
2049
+ websocket.url = address.href;
2050
+ } else {
2051
+ parsedUrl = url.URL ? new url.URL(address) : url.parse(address);
2052
+ websocket.url = address;
2053
+ }
2054
+ const isUnixSocket = parsedUrl.protocol === "ws+unix:";
2055
+ if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) {
2056
+ throw new Error(`Invalid URL: ${websocket.url}`);
2057
+ }
2058
+ const isSecure = parsedUrl.protocol === "wss:" || parsedUrl.protocol === "https:";
2059
+ const defaultPort = isSecure ? 443 : 80;
2060
+ const key = crypto2.randomBytes(16).toString("base64");
2061
+ const get = isSecure ? https.get : http.get;
2062
+ const path = parsedUrl.search ? `${parsedUrl.pathname || "/"}${parsedUrl.search}` : parsedUrl.pathname || "/";
2063
+ var perMessageDeflate;
2064
+ opts.createConnection = isSecure ? tlsConnect : netConnect;
2065
+ opts.defaultPort = opts.defaultPort || defaultPort;
2066
+ opts.port = parsedUrl.port || defaultPort;
2067
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2068
+ opts.headers = Object.assign(
2069
+ {
2070
+ "Sec-WebSocket-Version": opts.protocolVersion,
2071
+ "Sec-WebSocket-Key": key,
2072
+ Connection: "Upgrade",
2073
+ Upgrade: "websocket"
2074
+ },
2075
+ opts.headers
2076
+ );
2077
+ opts.path = path;
2078
+ opts.timeout = opts.handshakeTimeout;
2079
+ if (opts.perMessageDeflate) {
2080
+ perMessageDeflate = new PerMessageDeflate(
2081
+ opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
2082
+ false,
2083
+ opts.maxPayload
2084
+ );
2085
+ opts.headers["Sec-WebSocket-Extensions"] = extension.format({
2086
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
2087
+ });
2088
+ }
2089
+ if (protocols) {
2090
+ opts.headers["Sec-WebSocket-Protocol"] = protocols;
2091
+ }
2092
+ if (opts.origin) {
2093
+ if (opts.protocolVersion < 13) {
2094
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2095
+ } else {
2096
+ opts.headers.Origin = opts.origin;
2097
+ }
2098
+ }
2099
+ if (parsedUrl.auth) {
2100
+ opts.auth = parsedUrl.auth;
2101
+ } else if (parsedUrl.username || parsedUrl.password) {
2102
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2103
+ }
2104
+ if (isUnixSocket) {
2105
+ const parts = path.split(":");
2106
+ opts.socketPath = parts[0];
2107
+ opts.path = parts[1];
2108
+ }
2109
+ var req = websocket._req = get(opts);
2110
+ if (opts.timeout) {
2111
+ req.on("timeout", () => {
2112
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2113
+ });
2114
+ }
2115
+ req.on("error", (err) => {
2116
+ if (websocket._req.aborted) return;
2117
+ req = websocket._req = null;
2118
+ websocket.readyState = WebSocket2.CLOSING;
2119
+ websocket.emit("error", err);
2120
+ websocket.emitClose();
2121
+ });
2122
+ req.on("response", (res) => {
2123
+ const location = res.headers.location;
2124
+ const statusCode = res.statusCode;
2125
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2126
+ if (++websocket._redirects > opts.maxRedirects) {
2127
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2128
+ return;
2129
+ }
2130
+ req.abort();
2131
+ const addr = url.URL ? new url.URL(location, address) : url.resolve(address, location);
2132
+ initAsClient(websocket, addr, protocols, options);
2133
+ } else if (!websocket.emit("unexpected-response", req, res)) {
2134
+ abortHandshake(
2135
+ websocket,
2136
+ req,
2137
+ `Unexpected server response: ${res.statusCode}`
2138
+ );
2139
+ }
2140
+ });
2141
+ req.on("upgrade", (res, socket, head) => {
2142
+ websocket.emit("upgrade", res);
2143
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
2144
+ req = websocket._req = null;
2145
+ const digest = crypto2.createHash("sha1").update(key + GUID).digest("base64");
2146
+ if (res.headers["sec-websocket-accept"] !== digest) {
2147
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2148
+ return;
2149
+ }
2150
+ const serverProt = res.headers["sec-websocket-protocol"];
2151
+ const protList = (protocols || "").split(/, */);
2152
+ var protError;
2153
+ if (!protocols && serverProt) {
2154
+ protError = "Server sent a subprotocol but none was requested";
2155
+ } else if (protocols && !serverProt) {
2156
+ protError = "Server sent no subprotocol";
2157
+ } else if (serverProt && !protList.includes(serverProt)) {
2158
+ protError = "Server sent an invalid subprotocol";
2159
+ }
2160
+ if (protError) {
2161
+ abortHandshake(websocket, socket, protError);
2162
+ return;
2163
+ }
2164
+ if (serverProt) websocket.protocol = serverProt;
2165
+ if (perMessageDeflate) {
2166
+ try {
2167
+ const extensions = extension.parse(
2168
+ res.headers["sec-websocket-extensions"]
2169
+ );
2170
+ if (extensions[PerMessageDeflate.extensionName]) {
2171
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2172
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2173
+ }
2174
+ } catch (err) {
2175
+ abortHandshake(
2176
+ websocket,
2177
+ socket,
2178
+ "Invalid Sec-WebSocket-Extensions header"
2179
+ );
2180
+ return;
2181
+ }
2182
+ }
2183
+ websocket.setSocket(socket, head, opts.maxPayload);
2184
+ });
2185
+ }
2186
+ function netConnect(options) {
2187
+ if (options.protocolVersion) options.path = options.socketPath;
2188
+ return net.connect(options);
2189
+ }
2190
+ function tlsConnect(options) {
2191
+ options.path = void 0;
2192
+ options.servername = options.servername || options.host;
2193
+ return tls.connect(options);
2194
+ }
2195
+ function abortHandshake(websocket, stream, message) {
2196
+ websocket.readyState = WebSocket2.CLOSING;
2197
+ const err = new Error(message);
2198
+ Error.captureStackTrace(err, abortHandshake);
2199
+ if (stream.setHeader) {
2200
+ stream.abort();
2201
+ stream.once("abort", websocket.emitClose.bind(websocket));
2202
+ websocket.emit("error", err);
2203
+ } else {
2204
+ stream.destroy(err);
2205
+ stream.once("error", websocket.emit.bind(websocket, "error"));
2206
+ stream.once("close", websocket.emitClose.bind(websocket));
2207
+ }
2208
+ }
2209
+ function receiverOnConclude(code, reason) {
2210
+ const websocket = this[kWebSocket];
2211
+ websocket._socket.removeListener("data", socketOnData);
2212
+ websocket._socket.resume();
2213
+ websocket._closeFrameReceived = true;
2214
+ websocket._closeMessage = reason;
2215
+ websocket._closeCode = code;
2216
+ if (code === 1005) websocket.close();
2217
+ else websocket.close(code, reason);
2218
+ }
2219
+ function receiverOnDrain() {
2220
+ this[kWebSocket]._socket.resume();
2221
+ }
2222
+ function receiverOnError(err) {
2223
+ const websocket = this[kWebSocket];
2224
+ websocket._socket.removeListener("data", socketOnData);
2225
+ websocket.readyState = WebSocket2.CLOSING;
2226
+ websocket._closeCode = err[kStatusCode];
2227
+ websocket.emit("error", err);
2228
+ websocket._socket.destroy();
2229
+ }
2230
+ function receiverOnFinish() {
2231
+ this[kWebSocket].emitClose();
2232
+ }
2233
+ function receiverOnMessage(data) {
2234
+ this[kWebSocket].emit("message", data);
2235
+ }
2236
+ function receiverOnPing(data) {
2237
+ const websocket = this[kWebSocket];
2238
+ websocket.pong(data, !websocket._isServer, NOOP);
2239
+ websocket.emit("ping", data);
2240
+ }
2241
+ function receiverOnPong(data) {
2242
+ this[kWebSocket].emit("pong", data);
2243
+ }
2244
+ function socketOnClose() {
2245
+ const websocket = this[kWebSocket];
2246
+ this.removeListener("close", socketOnClose);
2247
+ this.removeListener("end", socketOnEnd);
2248
+ websocket.readyState = WebSocket2.CLOSING;
2249
+ websocket._socket.read();
2250
+ websocket._receiver.end();
2251
+ this.removeListener("data", socketOnData);
2252
+ this[kWebSocket] = void 0;
2253
+ clearTimeout(websocket._closeTimer);
2254
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
2255
+ websocket.emitClose();
2256
+ } else {
2257
+ websocket._receiver.on("error", receiverOnFinish);
2258
+ websocket._receiver.on("finish", receiverOnFinish);
2259
+ }
2260
+ }
2261
+ function socketOnData(chunk) {
2262
+ if (!this[kWebSocket]._receiver.write(chunk)) {
2263
+ this.pause();
2264
+ }
2265
+ }
2266
+ function socketOnEnd() {
2267
+ const websocket = this[kWebSocket];
2268
+ websocket.readyState = WebSocket2.CLOSING;
2269
+ websocket._receiver.end();
2270
+ this.end();
2271
+ }
2272
+ function socketOnError() {
2273
+ const websocket = this[kWebSocket];
2274
+ this.removeListener("error", socketOnError);
2275
+ this.on("error", NOOP);
2276
+ websocket.readyState = WebSocket2.CLOSING;
2277
+ this.destroy();
2278
+ }
2279
+ }
2280
+ });
2281
+
2282
+ // ../../node_modules/ws/lib/websocket-server.js
2283
+ var require_websocket_server = __commonJS({
2284
+ "../../node_modules/ws/lib/websocket-server.js"(exports, module) {
2285
+ var EventEmitter = __require("events");
2286
+ var crypto2 = __require("crypto");
2287
+ var http = __require("http");
2288
+ var PerMessageDeflate = require_permessage_deflate();
2289
+ var extension = require_extension();
2290
+ var WebSocket2 = require_websocket();
2291
+ var { GUID } = require_constants();
2292
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
2293
+ var WebSocketServer = class extends EventEmitter {
2294
+ /**
2295
+ * Create a `WebSocketServer` instance.
2296
+ *
2297
+ * @param {Object} options Configuration options
2298
+ * @param {Number} options.backlog The maximum length of the queue of pending
2299
+ * connections
2300
+ * @param {Boolean} options.clientTracking Specifies whether or not to track
2301
+ * clients
2302
+ * @param {Function} options.handleProtocols An hook to handle protocols
2303
+ * @param {String} options.host The hostname where to bind the server
2304
+ * @param {Number} options.maxPayload The maximum allowed message size
2305
+ * @param {Boolean} options.noServer Enable no server mode
2306
+ * @param {String} options.path Accept only connections matching this path
2307
+ * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable
2308
+ * permessage-deflate
2309
+ * @param {Number} options.port The port where to bind the server
2310
+ * @param {http.Server} options.server A pre-created HTTP/S server to use
2311
+ * @param {Function} options.verifyClient An hook to reject connections
2312
+ * @param {Function} callback A listener for the `listening` event
2313
+ */
2314
+ constructor(options, callback) {
2315
+ super();
2316
+ options = Object.assign(
2317
+ {
2318
+ maxPayload: 100 * 1024 * 1024,
2319
+ perMessageDeflate: false,
2320
+ handleProtocols: null,
2321
+ clientTracking: true,
2322
+ verifyClient: null,
2323
+ noServer: false,
2324
+ backlog: null,
2325
+ // use default (511 as implemented in net.js)
2326
+ server: null,
2327
+ host: null,
2328
+ path: null,
2329
+ port: null
2330
+ },
2331
+ options
2332
+ );
2333
+ if (options.port == null && !options.server && !options.noServer) {
2334
+ throw new TypeError(
2335
+ 'One of the "port", "server", or "noServer" options must be specified'
2336
+ );
2337
+ }
2338
+ if (options.port != null) {
2339
+ this._server = http.createServer((req, res) => {
2340
+ const body = http.STATUS_CODES[426];
2341
+ res.writeHead(426, {
2342
+ "Content-Length": body.length,
2343
+ "Content-Type": "text/plain"
2344
+ });
2345
+ res.end(body);
2346
+ });
2347
+ this._server.listen(
2348
+ options.port,
2349
+ options.host,
2350
+ options.backlog,
2351
+ callback
2352
+ );
2353
+ } else if (options.server) {
2354
+ this._server = options.server;
2355
+ }
2356
+ if (this._server) {
2357
+ this._removeListeners = addListeners(this._server, {
2358
+ listening: this.emit.bind(this, "listening"),
2359
+ error: this.emit.bind(this, "error"),
2360
+ upgrade: (req, socket, head) => {
2361
+ this.handleUpgrade(req, socket, head, (ws) => {
2362
+ this.emit("connection", ws, req);
2363
+ });
2364
+ }
2365
+ });
2366
+ }
2367
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
2368
+ if (options.clientTracking) this.clients = /* @__PURE__ */ new Set();
2369
+ this.options = options;
2370
+ }
2371
+ /**
2372
+ * Returns the bound address, the address family name, and port of the server
2373
+ * as reported by the operating system if listening on an IP socket.
2374
+ * If the server is listening on a pipe or UNIX domain socket, the name is
2375
+ * returned as a string.
2376
+ *
2377
+ * @return {(Object|String|null)} The address of the server
2378
+ * @public
2379
+ */
2380
+ address() {
2381
+ if (this.options.noServer) {
2382
+ throw new Error('The server is operating in "noServer" mode');
2383
+ }
2384
+ if (!this._server) return null;
2385
+ return this._server.address();
2386
+ }
2387
+ /**
2388
+ * Close the server.
2389
+ *
2390
+ * @param {Function} cb Callback
2391
+ * @public
2392
+ */
2393
+ close(cb) {
2394
+ if (cb) this.once("close", cb);
2395
+ if (this.clients) {
2396
+ for (const client of this.clients) client.terminate();
2397
+ }
2398
+ const server = this._server;
2399
+ if (server) {
2400
+ this._removeListeners();
2401
+ this._removeListeners = this._server = null;
2402
+ if (this.options.port != null) {
2403
+ server.close(() => this.emit("close"));
2404
+ return;
2405
+ }
2406
+ }
2407
+ process.nextTick(emitClose, this);
2408
+ }
2409
+ /**
2410
+ * See if a given request should be handled by this server instance.
2411
+ *
2412
+ * @param {http.IncomingMessage} req Request object to inspect
2413
+ * @return {Boolean} `true` if the request is valid, else `false`
2414
+ * @public
2415
+ */
2416
+ shouldHandle(req) {
2417
+ if (this.options.path) {
2418
+ const index = req.url.indexOf("?");
2419
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
2420
+ if (pathname !== this.options.path) return false;
2421
+ }
2422
+ return true;
2423
+ }
2424
+ /**
2425
+ * Handle a HTTP Upgrade request.
2426
+ *
2427
+ * @param {http.IncomingMessage} req The request object
2428
+ * @param {net.Socket} socket The network socket between the server and client
2429
+ * @param {Buffer} head The first packet of the upgraded stream
2430
+ * @param {Function} cb Callback
2431
+ * @public
2432
+ */
2433
+ handleUpgrade(req, socket, head, cb) {
2434
+ socket.on("error", socketOnError);
2435
+ const key = req.headers["sec-websocket-key"] !== void 0 ? req.headers["sec-websocket-key"].trim() : false;
2436
+ const upgrade = req.headers.upgrade;
2437
+ const version = +req.headers["sec-websocket-version"];
2438
+ const extensions = {};
2439
+ if (req.method !== "GET" || upgrade === void 0 || upgrade.toLowerCase() !== "websocket" || !key || !keyRegex.test(key) || version !== 8 && version !== 13 || !this.shouldHandle(req)) {
2440
+ return abortHandshake(socket, 400);
2441
+ }
2442
+ if (this.options.perMessageDeflate) {
2443
+ const perMessageDeflate = new PerMessageDeflate(
2444
+ this.options.perMessageDeflate,
2445
+ true,
2446
+ this.options.maxPayload
2447
+ );
2448
+ try {
2449
+ const offers = extension.parse(req.headers["sec-websocket-extensions"]);
2450
+ if (offers[PerMessageDeflate.extensionName]) {
2451
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
2452
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2453
+ }
2454
+ } catch (err) {
2455
+ return abortHandshake(socket, 400);
2456
+ }
2457
+ }
2458
+ if (this.options.verifyClient) {
2459
+ const info = {
2460
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
2461
+ secure: !!(req.connection.authorized || req.connection.encrypted),
2462
+ req
2463
+ };
2464
+ if (this.options.verifyClient.length === 2) {
2465
+ this.options.verifyClient(info, (verified, code, message, headers) => {
2466
+ if (!verified) {
2467
+ return abortHandshake(socket, code || 401, message, headers);
2468
+ }
2469
+ this.completeUpgrade(key, extensions, req, socket, head, cb);
2470
+ });
2471
+ return;
2472
+ }
2473
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
2474
+ }
2475
+ this.completeUpgrade(key, extensions, req, socket, head, cb);
2476
+ }
2477
+ /**
2478
+ * Upgrade the connection to WebSocket.
2479
+ *
2480
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
2481
+ * @param {Object} extensions The accepted extensions
2482
+ * @param {http.IncomingMessage} req The request object
2483
+ * @param {net.Socket} socket The network socket between the server and client
2484
+ * @param {Buffer} head The first packet of the upgraded stream
2485
+ * @param {Function} cb Callback
2486
+ * @private
2487
+ */
2488
+ completeUpgrade(key, extensions, req, socket, head, cb) {
2489
+ if (!socket.readable || !socket.writable) return socket.destroy();
2490
+ const digest = crypto2.createHash("sha1").update(key + GUID).digest("base64");
2491
+ const headers = [
2492
+ "HTTP/1.1 101 Switching Protocols",
2493
+ "Upgrade: websocket",
2494
+ "Connection: Upgrade",
2495
+ `Sec-WebSocket-Accept: ${digest}`
2496
+ ];
2497
+ const ws = new WebSocket2(null);
2498
+ var protocol = req.headers["sec-websocket-protocol"];
2499
+ if (protocol) {
2500
+ protocol = protocol.split(",").map(trim);
2501
+ if (this.options.handleProtocols) {
2502
+ protocol = this.options.handleProtocols(protocol, req);
2503
+ } else {
2504
+ protocol = protocol[0];
2505
+ }
2506
+ if (protocol) {
2507
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
2508
+ ws.protocol = protocol;
2509
+ }
2510
+ }
2511
+ if (extensions[PerMessageDeflate.extensionName]) {
2512
+ const params = extensions[PerMessageDeflate.extensionName].params;
2513
+ const value = extension.format({
2514
+ [PerMessageDeflate.extensionName]: [params]
2515
+ });
2516
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
2517
+ ws._extensions = extensions;
2518
+ }
2519
+ this.emit("headers", headers, req);
2520
+ socket.write(headers.concat("\r\n").join("\r\n"));
2521
+ socket.removeListener("error", socketOnError);
2522
+ ws.setSocket(socket, head, this.options.maxPayload);
2523
+ if (this.clients) {
2524
+ this.clients.add(ws);
2525
+ ws.on("close", () => this.clients.delete(ws));
2526
+ }
2527
+ cb(ws);
2528
+ }
2529
+ };
2530
+ module.exports = WebSocketServer;
2531
+ function addListeners(server, map) {
2532
+ for (const event of Object.keys(map)) server.on(event, map[event]);
2533
+ return function removeListeners() {
2534
+ for (const event of Object.keys(map)) {
2535
+ server.removeListener(event, map[event]);
2536
+ }
2537
+ };
2538
+ }
2539
+ function emitClose(server) {
2540
+ server.emit("close");
2541
+ }
2542
+ function socketOnError() {
2543
+ this.destroy();
2544
+ }
2545
+ function abortHandshake(socket, code, message, headers) {
2546
+ if (socket.writable) {
2547
+ message = message || http.STATUS_CODES[code];
2548
+ headers = Object.assign(
2549
+ {
2550
+ Connection: "close",
2551
+ "Content-type": "text/html",
2552
+ "Content-Length": Buffer.byteLength(message)
2553
+ },
2554
+ headers
2555
+ );
2556
+ socket.write(
2557
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
2558
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
2559
+ );
2560
+ }
2561
+ socket.removeListener("error", socketOnError);
2562
+ socket.destroy();
2563
+ }
2564
+ function trim(str) {
2565
+ return str.trim();
2566
+ }
2567
+ }
2568
+ });
2569
+
2570
+ // ../../node_modules/ws/index.js
2571
+ var require_ws = __commonJS({
2572
+ "../../node_modules/ws/index.js"(exports, module) {
2573
+ var WebSocket2 = require_websocket();
2574
+ WebSocket2.Server = require_websocket_server();
2575
+ WebSocket2.Receiver = require_receiver();
2576
+ WebSocket2.Sender = require_sender();
2577
+ module.exports = WebSocket2;
2578
+ }
2579
+ });
7
2580
 
8
2581
  // ../core/src/platform.ts
9
2582
  function detectPlatform() {
@@ -894,6 +3467,63 @@ var HttpClient = class {
894
3467
  signal
895
3468
  });
896
3469
  }
3470
+ /**
3471
+ * AI Agent request (non-streaming)
3472
+ * Returns JSON response with text, steps, usage, and billing
3473
+ */
3474
+ async aiAgent(requestBody, signal) {
3475
+ return this.request(`/api/ai/${this.projectId}/agent`, {
3476
+ method: "POST",
3477
+ body: requestBody,
3478
+ signal
3479
+ });
3480
+ }
3481
+ /**
3482
+ * AI Agent streaming request
3483
+ * Returns raw Response for SSE streaming (compatible with AI SDK useChat)
3484
+ */
3485
+ async aiAgentStream(requestBody, signal) {
3486
+ const url = this.buildUrl(`/api/ai/${this.projectId}/agent`);
3487
+ const token = this.getValidToken ? await this.getValidToken() : this.getToken();
3488
+ const headers = {
3489
+ "Content-Type": "application/json"
3490
+ };
3491
+ const auth = this.getAuthorizationHeader(url, token);
3492
+ if (auth) headers.Authorization = auth;
3493
+ const response = await fetch(url, {
3494
+ method: "POST",
3495
+ headers,
3496
+ body: JSON.stringify(requestBody),
3497
+ signal
3498
+ });
3499
+ if (!response.ok) {
3500
+ await this.handleErrorResponse(response);
3501
+ }
3502
+ return response;
3503
+ }
3504
+ /**
3505
+ * RAG AI Search streaming request
3506
+ * Returns raw Response for SSE streaming
3507
+ */
3508
+ async ragAiSearchStream(body, signal) {
3509
+ const url = this.buildUrl(`/api/rag/${this.projectId}/ai-search`);
3510
+ const token = this.getValidToken ? await this.getValidToken() : this.getToken();
3511
+ const headers = {
3512
+ "Content-Type": "application/json"
3513
+ };
3514
+ const auth = this.getAuthorizationHeader(url, token);
3515
+ if (auth) headers.Authorization = auth;
3516
+ const response = await fetch(url, {
3517
+ method: "POST",
3518
+ headers,
3519
+ body: JSON.stringify(body),
3520
+ signal
3521
+ });
3522
+ if (!response.ok) {
3523
+ await this.handleErrorResponse(response);
3524
+ }
3525
+ return response;
3526
+ }
897
3527
  /**
898
3528
  * Data-specific requests
899
3529
  */
@@ -1264,15 +3894,6 @@ function getSessionStorage() {
1264
3894
  return null;
1265
3895
  }
1266
3896
  }
1267
- function isSafari() {
1268
- if (!hasWindow()) return false;
1269
- const ua = navigator.userAgent.toLowerCase();
1270
- const hasSafariUA = /safari/i.test(ua) && !/chrome|chromium|android/i.test(ua);
1271
- const isSafariVendor = typeof navigator !== "undefined" && /apple computer|apple/i.test(navigator.vendor || "");
1272
- const isIOSSafari = /safari/i.test(ua) && /iphone|ipad|ipod/i.test(ua);
1273
- const hasSafariProperties = typeof window !== "undefined" && "safari" in window && !("chrome" in window);
1274
- return hasSafariUA || isSafariVendor || isIOSSafari || hasSafariProperties;
1275
- }
1276
3897
 
1277
3898
  // src/auth.ts
1278
3899
  var BlinkAuth = class {
@@ -1295,16 +3916,16 @@ var BlinkAuth = class {
1295
3916
  this.authConfig = {
1296
3917
  mode: "managed",
1297
3918
  // Default mode
1298
- authUrl: "https://dev.blink.new",
1299
- coreUrl: "https://core.dev.blink.new",
3919
+ authUrl: "https://blink.new",
3920
+ coreUrl: "https://core.blink.new",
1300
3921
  detectSessionInUrl: true,
1301
3922
  // Default to true for web compatibility
1302
3923
  ...config.auth
1303
3924
  };
1304
- this.authUrl = this.authConfig.authUrl || "https://dev.blink.new";
1305
- this.coreUrl = this.authConfig.coreUrl || "https://core.dev.blink.new";
3925
+ this.authUrl = this.authConfig.authUrl || "https://blink.new";
3926
+ this.coreUrl = this.authConfig.coreUrl || "https://core.blink.new";
1306
3927
  const hostname = getLocationHostname();
1307
- if (hostname && this.authUrl === "https://dev.blink.new" && (hostname === "localhost" || hostname === "127.0.0.1")) {
3928
+ if (hostname && this.authUrl === "https://blink.new" && (hostname === "localhost" || hostname === "127.0.0.1")) {
1308
3929
  console.warn("\u26A0\uFE0F Using default authUrl in development. Set auth.authUrl to your app origin for headless auth endpoints to work.");
1309
3930
  }
1310
3931
  if (config.authRequired !== void 0 && !config.auth?.mode) {
@@ -1356,7 +3977,7 @@ var BlinkAuth = class {
1356
3977
  setupParentWindowListener() {
1357
3978
  if (!isWeb || !this.isIframe || !hasWindow()) return;
1358
3979
  window.addEventListener("message", (event) => {
1359
- if (event.origin !== "https://dev.blink.new" && event.origin !== "https://blink.new" && event.origin !== "http://localhost:3000" && event.origin !== "http://localhost:3001") {
3980
+ if (event.origin !== "https://blink.new" && event.origin !== "http://localhost:3000" && event.origin !== "http://localhost:3001") {
1360
3981
  return;
1361
3982
  }
1362
3983
  if (event.data?.type === "BLINK_AUTH_TOKENS") {
@@ -2019,7 +4640,7 @@ var BlinkAuth = class {
2019
4640
  if (!hasWindow()) {
2020
4641
  throw new BlinkAuthError("NETWORK_ERROR" /* NETWORK_ERROR */, "signInWithProvider requires a browser environment");
2021
4642
  }
2022
- const shouldPreferRedirect = isWeb && this.isIframe || typeof window !== "undefined" && window.crossOriginIsolated === true || isWeb && isSafari();
4643
+ const shouldPreferRedirect = isWeb && this.isIframe || typeof window !== "undefined" && window.crossOriginIsolated === true;
2023
4644
  const state = this.generateState();
2024
4645
  try {
2025
4646
  const sessionStorage = getSessionStorage();
@@ -2649,6 +5270,83 @@ var BlinkAuth = class {
2649
5270
  const user = await this.me();
2650
5271
  return user;
2651
5272
  }
5273
+ /**
5274
+ * Verify a Blink Auth token using the introspection endpoint.
5275
+ *
5276
+ * **Server-side / Edge Function use only.**
5277
+ *
5278
+ * This is the recommended way to verify user tokens in Deno Edge Functions
5279
+ * and other server-side contexts. It calls the Blink API introspection
5280
+ * endpoint which validates the token without exposing the JWT secret.
5281
+ *
5282
+ * @param token - The raw JWT token (without "Bearer " prefix) or full Authorization header
5283
+ * @returns Token introspection result with validity and claims
5284
+ *
5285
+ * @example
5286
+ * // Deno Edge Function usage
5287
+ * import { createClient } from "npm:@blinkdotnew/sdk";
5288
+ *
5289
+ * const blink = createClient({
5290
+ * projectId: Deno.env.get("BLINK_PROJECT_ID")!,
5291
+ * secretKey: Deno.env.get("BLINK_SECRET_KEY"),
5292
+ * });
5293
+ *
5294
+ * async function handler(req: Request): Promise<Response> {
5295
+ * const authHeader = req.headers.get("Authorization");
5296
+ * const result = await blink.auth.verifyToken(authHeader);
5297
+ *
5298
+ * if (!result.valid) {
5299
+ * return new Response(JSON.stringify({ error: result.error }), { status: 401 });
5300
+ * }
5301
+ *
5302
+ * // User is authenticated
5303
+ * console.log("User ID:", result.userId);
5304
+ * console.log("Email:", result.email);
5305
+ * console.log("Project:", result.projectId);
5306
+ *
5307
+ * // Continue with your logic...
5308
+ * }
5309
+ */
5310
+ async verifyToken(token) {
5311
+ if (!token) {
5312
+ return { valid: false, error: "Token required" };
5313
+ }
5314
+ let cleanToken = token.toLowerCase().startsWith("bearer ") ? token.slice(7) : token;
5315
+ cleanToken = cleanToken.trim();
5316
+ if (!cleanToken) {
5317
+ return { valid: false, error: "Token required" };
5318
+ }
5319
+ try {
5320
+ const response = await fetch(`${this.coreUrl}/api/auth/introspect`, {
5321
+ method: "POST",
5322
+ headers: {
5323
+ "Authorization": `Bearer ${cleanToken}`,
5324
+ "Content-Type": "application/json"
5325
+ }
5326
+ });
5327
+ const contentType = response.headers.get("content-type")?.toLowerCase();
5328
+ if (!contentType || !contentType.includes("application/json")) {
5329
+ return {
5330
+ valid: false,
5331
+ error: `Server error: ${response.status} ${response.statusText}`
5332
+ };
5333
+ }
5334
+ const result = await response.json();
5335
+ if (!result || typeof result !== "object" || typeof result.valid !== "boolean") {
5336
+ return {
5337
+ valid: false,
5338
+ error: result && (result.error || result.message) || `Request failed: ${response.status}`
5339
+ };
5340
+ }
5341
+ return result;
5342
+ } catch (error) {
5343
+ console.error("[BlinkAuth] Token verification failed:", error);
5344
+ return {
5345
+ valid: false,
5346
+ error: error instanceof Error ? error.message : "Token verification failed"
5347
+ };
5348
+ }
5349
+ }
2652
5350
  /**
2653
5351
  * Refresh access token using refresh token
2654
5352
  */
@@ -3672,6 +6370,253 @@ var BlinkStorageImpl = class {
3672
6370
  }
3673
6371
  };
3674
6372
 
6373
+ // src/tools/core.ts
6374
+ var webSearch = "web_search";
6375
+ var fetchUrl = "fetch_url";
6376
+ var runCode = "run_code";
6377
+ var coreTools = [webSearch, fetchUrl, runCode];
6378
+
6379
+ // src/tools/sandbox.ts
6380
+ var readFile = "read_file";
6381
+ var listDir = "list_dir";
6382
+ var writeFile = "write_file";
6383
+ var searchReplace = "search_replace";
6384
+ var grep = "grep";
6385
+ var globFileSearch = "glob_file_search";
6386
+ var runTerminalCmd = "run_terminal_cmd";
6387
+ var getHost = "get_host";
6388
+ var sandboxTools = [
6389
+ readFile,
6390
+ listDir,
6391
+ writeFile,
6392
+ searchReplace,
6393
+ grep,
6394
+ globFileSearch,
6395
+ runTerminalCmd,
6396
+ getHost
6397
+ ];
6398
+
6399
+ // src/tools/db.ts
6400
+ var dbInsert = "db_insert";
6401
+ var dbList = "db_list";
6402
+ var dbGet = "db_get";
6403
+ var dbUpdate = "db_update";
6404
+ var dbDelete = "db_delete";
6405
+ var dbTools = [dbInsert, dbList, dbGet, dbUpdate, dbDelete];
6406
+
6407
+ // src/tools/storage.ts
6408
+ var storageUpload = "storage_upload";
6409
+ var storageDownload = "storage_download";
6410
+ var storageList = "storage_list";
6411
+ var storageDelete = "storage_delete";
6412
+ var storagePublicUrl = "storage_public_url";
6413
+ var storageMove = "storage_move";
6414
+ var storageCopy = "storage_copy";
6415
+ var storageTools = [
6416
+ storageUpload,
6417
+ storageDownload,
6418
+ storageList,
6419
+ storageDelete,
6420
+ storagePublicUrl,
6421
+ storageMove,
6422
+ storageCopy
6423
+ ];
6424
+
6425
+ // src/tools/rag.ts
6426
+ var ragSearch = "rag_search";
6427
+ var ragTools = [ragSearch];
6428
+
6429
+ // src/tools/media.ts
6430
+ var generateImage = "generate_image";
6431
+ var editImage = "edit_image";
6432
+ var generateVideo = "generate_video";
6433
+ var imageToVideo = "image_to_video";
6434
+ var mediaTools = [generateImage, editImage, generateVideo, imageToVideo];
6435
+
6436
+ // src/tools/index.ts
6437
+ function serializeTools(tools) {
6438
+ return tools;
6439
+ }
6440
+
6441
+ // src/agent.ts
6442
+ function createStopConditions(maxSteps, stopWhen) {
6443
+ if (stopWhen && stopWhen.length > 0) {
6444
+ return stopWhen;
6445
+ }
6446
+ if (maxSteps && maxSteps > 0) {
6447
+ return [{ type: "step_count_is", count: maxSteps }];
6448
+ }
6449
+ return void 0;
6450
+ }
6451
+ var Agent = class {
6452
+ httpClient = null;
6453
+ config;
6454
+ /**
6455
+ * Create a new Agent instance
6456
+ * @param options - Agent configuration options
6457
+ */
6458
+ constructor(options) {
6459
+ if (!options.model) {
6460
+ throw new BlinkAIError("Agent model is required");
6461
+ }
6462
+ this.config = options;
6463
+ }
6464
+ /**
6465
+ * Internal: Set the HTTP client (called by BlinkClient)
6466
+ */
6467
+ _setHttpClient(client) {
6468
+ this.httpClient = client;
6469
+ }
6470
+ /**
6471
+ * Internal: Get the agent config for API requests
6472
+ */
6473
+ getAgentConfig() {
6474
+ const { model, system, instructions, tools, webhookTools, clientTools, toolChoice, stopWhen, maxSteps } = this.config;
6475
+ const serializedTools = tools ? serializeTools(tools) : void 0;
6476
+ const stopConditions = createStopConditions(maxSteps, stopWhen);
6477
+ return {
6478
+ model,
6479
+ system: system || instructions,
6480
+ tools: serializedTools,
6481
+ webhook_tools: webhookTools,
6482
+ client_tools: clientTools,
6483
+ tool_choice: toolChoice,
6484
+ stop_when: stopConditions
6485
+ };
6486
+ }
6487
+ /**
6488
+ * Generate a response (non-streaming)
6489
+ *
6490
+ * @param options - Generation options (prompt or messages)
6491
+ * @returns Promise<AgentResponse> with text, steps, usage, and billing
6492
+ *
6493
+ * @example
6494
+ * ```ts
6495
+ * const result = await agent.generate({
6496
+ * prompt: 'What is the weather in San Francisco?',
6497
+ * })
6498
+ * console.log(result.text)
6499
+ * console.log(result.steps)
6500
+ * ```
6501
+ */
6502
+ async generate(options) {
6503
+ if (!this.httpClient) {
6504
+ throw new BlinkAIError(
6505
+ "Agent not initialized. Use blink.ai.createAgent() or pass the agent to useAgent()."
6506
+ );
6507
+ }
6508
+ if (!options.prompt && !options.messages) {
6509
+ throw new BlinkAIError("Either prompt or messages is required");
6510
+ }
6511
+ if (options.prompt && options.messages) {
6512
+ throw new BlinkAIError("prompt and messages are mutually exclusive");
6513
+ }
6514
+ try {
6515
+ const requestBody = {
6516
+ stream: false,
6517
+ agent: this.getAgentConfig()
6518
+ };
6519
+ if (options.prompt) {
6520
+ requestBody.prompt = options.prompt;
6521
+ } else if (options.messages) {
6522
+ requestBody.messages = options.messages;
6523
+ }
6524
+ if (options.sandbox) {
6525
+ requestBody.sandbox_id = typeof options.sandbox === "string" ? options.sandbox : options.sandbox.id;
6526
+ }
6527
+ const response = await this.httpClient.aiAgent(requestBody, options.signal);
6528
+ return response.data;
6529
+ } catch (error) {
6530
+ console.error("[Agent] generate failed:", error);
6531
+ if (error instanceof BlinkAIError) {
6532
+ throw error;
6533
+ }
6534
+ throw new BlinkAIError(
6535
+ `Agent generate failed: ${error instanceof Error ? error.message : "Unknown error"}`,
6536
+ void 0,
6537
+ { originalError: error }
6538
+ );
6539
+ }
6540
+ }
6541
+ /**
6542
+ * Stream a response (real-time)
6543
+ *
6544
+ * @param options - Stream options (prompt or messages)
6545
+ * @returns Promise<Response> - AI SDK UI Message Stream for useChat compatibility
6546
+ *
6547
+ * @example
6548
+ * ```ts
6549
+ * const stream = await agent.stream({
6550
+ * prompt: 'Tell me a story',
6551
+ * })
6552
+ *
6553
+ * // Process stream
6554
+ * for await (const chunk of stream.body) {
6555
+ * // Handle chunk
6556
+ * }
6557
+ * ```
6558
+ */
6559
+ async stream(options) {
6560
+ if (!this.httpClient) {
6561
+ throw new BlinkAIError(
6562
+ "Agent not initialized. Use blink.ai.createAgent() or pass the agent to useAgent()."
6563
+ );
6564
+ }
6565
+ if (!options.prompt && !options.messages) {
6566
+ throw new BlinkAIError("Either prompt or messages is required");
6567
+ }
6568
+ if (options.prompt && options.messages) {
6569
+ throw new BlinkAIError("prompt and messages are mutually exclusive");
6570
+ }
6571
+ try {
6572
+ const requestBody = {
6573
+ stream: true,
6574
+ agent: this.getAgentConfig()
6575
+ };
6576
+ if (options.prompt) {
6577
+ requestBody.prompt = options.prompt;
6578
+ } else if (options.messages) {
6579
+ requestBody.messages = options.messages;
6580
+ }
6581
+ if (options.sandbox) {
6582
+ requestBody.sandbox_id = typeof options.sandbox === "string" ? options.sandbox : options.sandbox.id;
6583
+ }
6584
+ return await this.httpClient.aiAgentStream(requestBody, options.signal);
6585
+ } catch (error) {
6586
+ console.error("[Agent] stream failed:", error);
6587
+ if (error instanceof BlinkAIError) {
6588
+ throw error;
6589
+ }
6590
+ throw new BlinkAIError(
6591
+ `Agent stream failed: ${error instanceof Error ? error.message : "Unknown error"}`,
6592
+ void 0,
6593
+ { originalError: error }
6594
+ );
6595
+ }
6596
+ }
6597
+ /**
6598
+ * Get the agent's model
6599
+ */
6600
+ get model() {
6601
+ return this.config.model;
6602
+ }
6603
+ /**
6604
+ * Get the agent's system prompt
6605
+ */
6606
+ get system() {
6607
+ return this.config.system || this.config.instructions;
6608
+ }
6609
+ /**
6610
+ * Get the agent's tools
6611
+ */
6612
+ get tools() {
6613
+ return this.config.tools;
6614
+ }
6615
+ };
6616
+ function stepCountIs(count) {
6617
+ return { type: "step_count_is", count };
6618
+ }
6619
+
3675
6620
  // src/ai.ts
3676
6621
  var BlinkAIImpl = class {
3677
6622
  constructor(httpClient) {
@@ -4642,6 +7587,104 @@ var BlinkAIImpl = class {
4642
7587
  );
4643
7588
  }
4644
7589
  }
7590
+ async agent(options) {
7591
+ try {
7592
+ if (!options.agent?.model) {
7593
+ throw new BlinkAIError("agent.model is required");
7594
+ }
7595
+ if (!options.prompt && !options.messages) {
7596
+ throw new BlinkAIError("Either prompt or messages is required");
7597
+ }
7598
+ if (options.prompt && options.messages) {
7599
+ throw new BlinkAIError("prompt and messages are mutually exclusive");
7600
+ }
7601
+ const serializedTools = options.agent.tools ? serializeTools(options.agent.tools) : void 0;
7602
+ const requestBody = {
7603
+ stream: options.stream,
7604
+ agent: {
7605
+ model: options.agent.model,
7606
+ system: options.agent.system,
7607
+ tools: serializedTools,
7608
+ webhook_tools: options.agent.webhook_tools,
7609
+ client_tools: options.agent.client_tools,
7610
+ tool_choice: options.agent.tool_choice,
7611
+ stop_when: options.agent.stop_when,
7612
+ prepare_step: options.agent.prepare_step
7613
+ }
7614
+ };
7615
+ if (options.prompt) {
7616
+ requestBody.prompt = options.prompt;
7617
+ } else if (options.messages) {
7618
+ requestBody.messages = options.messages;
7619
+ }
7620
+ if (options.stream) {
7621
+ return await this.httpClient.aiAgentStream(requestBody, options.signal);
7622
+ } else {
7623
+ const response = await this.httpClient.aiAgent(requestBody, options.signal);
7624
+ return response.data;
7625
+ }
7626
+ } catch (error) {
7627
+ if (error instanceof BlinkAIError) {
7628
+ throw error;
7629
+ }
7630
+ throw new BlinkAIError(
7631
+ `Agent request failed: ${error instanceof Error ? error.message : "Unknown error"}`,
7632
+ void 0,
7633
+ { originalError: error }
7634
+ );
7635
+ }
7636
+ }
7637
+ // ============================================================================
7638
+ // Agent Factory
7639
+ // ============================================================================
7640
+ /**
7641
+ * Creates a reusable Agent instance with the Vercel AI SDK pattern.
7642
+ *
7643
+ * The Agent can be used multiple times with different prompts:
7644
+ * - `agent.generate({ prompt })` for non-streaming
7645
+ * - `agent.stream({ prompt })` for streaming
7646
+ *
7647
+ * @param options - Agent configuration (model, tools, system, etc.)
7648
+ * @returns Agent instance
7649
+ *
7650
+ * @example
7651
+ * ```ts
7652
+ * const weatherAgent = blink.ai.createAgent({
7653
+ * model: 'anthropic/claude-sonnet-4-20250514',
7654
+ * system: 'You are a helpful weather assistant.',
7655
+ * tools: [webSearch, fetchUrl],
7656
+ * maxSteps: 10,
7657
+ * })
7658
+ *
7659
+ * // Non-streaming
7660
+ * const result = await weatherAgent.generate({
7661
+ * prompt: 'What is the weather in San Francisco?',
7662
+ * })
7663
+ *
7664
+ * // Streaming
7665
+ * const stream = await weatherAgent.stream({
7666
+ * prompt: 'Tell me about weather patterns',
7667
+ * })
7668
+ * ```
7669
+ */
7670
+ createAgent(options) {
7671
+ const agent = new Agent(options);
7672
+ agent._setHttpClient(this.httpClient);
7673
+ return agent;
7674
+ }
7675
+ /**
7676
+ * Binds an existing Agent instance to this client's HTTP client.
7677
+ *
7678
+ * Used internally by useAgent() when an Agent instance is passed.
7679
+ * This allows agents created with `new Agent()` to be used with the hook.
7680
+ *
7681
+ * @param agent - Existing Agent instance
7682
+ * @returns The same Agent instance (with httpClient set)
7683
+ */
7684
+ bindAgent(agent) {
7685
+ agent._setHttpClient(this.httpClient);
7686
+ return agent;
7687
+ }
4645
7688
  };
4646
7689
 
4647
7690
  // src/data.ts
@@ -4751,7 +7794,7 @@ var getWebSocketClass = () => {
4751
7794
  return WebSocket;
4752
7795
  }
4753
7796
  try {
4754
- const WS = __require("ws");
7797
+ const WS = require_ws();
4755
7798
  return WS;
4756
7799
  } catch (error) {
4757
7800
  throw new BlinkRealtimeError('WebSocket is not available. Install "ws" package for Node.js environments.');
@@ -5760,6 +8803,411 @@ var BlinkFunctionsImpl = class {
5760
8803
  }
5761
8804
  };
5762
8805
 
8806
+ // src/rag.ts
8807
+ function removeUndefined(obj) {
8808
+ return Object.fromEntries(
8809
+ Object.entries(obj).filter(([, v]) => v !== void 0)
8810
+ );
8811
+ }
8812
+ function convertCollection(api) {
8813
+ return {
8814
+ id: api.id,
8815
+ name: api.name,
8816
+ description: api.description,
8817
+ embeddingModel: api.embedding_model,
8818
+ embeddingDimensions: api.embedding_dimensions,
8819
+ indexMetric: api.index_metric,
8820
+ chunkMaxTokens: api.chunk_max_tokens,
8821
+ chunkOverlapTokens: api.chunk_overlap_tokens,
8822
+ documentCount: api.document_count,
8823
+ chunkCount: api.chunk_count,
8824
+ shared: api.shared,
8825
+ createdAt: api.created_at,
8826
+ updatedAt: api.updated_at
8827
+ };
8828
+ }
8829
+ function convertDocument(api) {
8830
+ return {
8831
+ id: api.id,
8832
+ collectionId: api.collection_id,
8833
+ filename: api.filename,
8834
+ sourceType: api.source_type,
8835
+ sourceUrl: api.source_url,
8836
+ contentType: api.content_type,
8837
+ fileSize: api.file_size,
8838
+ status: api.status,
8839
+ errorMessage: api.error_message,
8840
+ processingStartedAt: api.processing_started_at,
8841
+ processingCompletedAt: api.processing_completed_at,
8842
+ chunkCount: api.chunk_count,
8843
+ tokenCount: api.token_count,
8844
+ metadata: api.metadata,
8845
+ createdAt: api.created_at,
8846
+ updatedAt: api.updated_at
8847
+ };
8848
+ }
8849
+ function convertPartialDocument(api, options) {
8850
+ let sourceType = "text";
8851
+ if (options.url) sourceType = "url";
8852
+ if (options.file) sourceType = "file";
8853
+ return {
8854
+ id: api.id || "",
8855
+ collectionId: api.collection_id || options.collectionId || "",
8856
+ filename: api.filename || options.filename,
8857
+ sourceType: api.source_type || sourceType,
8858
+ sourceUrl: api.source_url ?? options.url ?? null,
8859
+ contentType: api.content_type ?? options.file?.contentType ?? null,
8860
+ fileSize: api.file_size ?? null,
8861
+ status: api.status || "pending",
8862
+ errorMessage: api.error_message ?? null,
8863
+ processingStartedAt: api.processing_started_at ?? null,
8864
+ processingCompletedAt: api.processing_completed_at ?? null,
8865
+ chunkCount: api.chunk_count ?? 0,
8866
+ tokenCount: api.token_count ?? null,
8867
+ metadata: api.metadata || options.metadata || {},
8868
+ createdAt: api.created_at || (/* @__PURE__ */ new Date()).toISOString(),
8869
+ updatedAt: api.updated_at || api.created_at || (/* @__PURE__ */ new Date()).toISOString()
8870
+ };
8871
+ }
8872
+ function convertSearchResult(api) {
8873
+ return {
8874
+ chunkId: api.chunk_id,
8875
+ documentId: api.document_id,
8876
+ filename: api.filename,
8877
+ content: api.content,
8878
+ score: api.score,
8879
+ chunkIndex: api.chunk_index,
8880
+ metadata: api.metadata
8881
+ };
8882
+ }
8883
+ function convertSearchResponse(api) {
8884
+ return {
8885
+ results: api.results.map(convertSearchResult),
8886
+ query: api.query,
8887
+ collectionId: api.collection_id,
8888
+ totalResults: api.total_results
8889
+ };
8890
+ }
8891
+ function convertAISearchSource(api) {
8892
+ return {
8893
+ documentId: api.document_id,
8894
+ filename: api.filename,
8895
+ chunkId: api.chunk_id,
8896
+ excerpt: api.excerpt,
8897
+ score: api.score
8898
+ };
8899
+ }
8900
+ function convertAISearchResult(api) {
8901
+ return {
8902
+ answer: api.answer,
8903
+ sources: api.sources.map(convertAISearchSource),
8904
+ query: api.query,
8905
+ model: api.model,
8906
+ usage: {
8907
+ inputTokens: api.usage.input_tokens,
8908
+ outputTokens: api.usage.output_tokens
8909
+ }
8910
+ };
8911
+ }
8912
+ var BlinkRAGImpl = class {
8913
+ constructor(httpClient) {
8914
+ this.httpClient = httpClient;
8915
+ this.projectId = httpClient.projectId;
8916
+ }
8917
+ projectId;
8918
+ /**
8919
+ * Build URL with project_id prefix
8920
+ */
8921
+ url(path) {
8922
+ return `/api/rag/${this.projectId}${path}`;
8923
+ }
8924
+ // ============================================================================
8925
+ // Collections
8926
+ // ============================================================================
8927
+ /**
8928
+ * Create a new RAG collection
8929
+ */
8930
+ async createCollection(options) {
8931
+ const body = removeUndefined({
8932
+ name: options.name,
8933
+ description: options.description,
8934
+ embedding_model: options.embeddingModel,
8935
+ embedding_dimensions: options.embeddingDimensions,
8936
+ index_metric: options.indexMetric,
8937
+ chunk_max_tokens: options.chunkMaxTokens,
8938
+ chunk_overlap_tokens: options.chunkOverlapTokens,
8939
+ shared: options.shared
8940
+ });
8941
+ const response = await this.httpClient.post(this.url("/collections"), body);
8942
+ return convertCollection(response.data);
8943
+ }
8944
+ /**
8945
+ * List all collections accessible to the current user
8946
+ */
8947
+ async listCollections() {
8948
+ const response = await this.httpClient.get(this.url("/collections"));
8949
+ return response.data.collections.map(convertCollection);
8950
+ }
8951
+ /**
8952
+ * Get a specific collection by ID
8953
+ */
8954
+ async getCollection(collectionId) {
8955
+ const response = await this.httpClient.get(this.url(`/collections/${collectionId}`));
8956
+ return convertCollection(response.data);
8957
+ }
8958
+ /**
8959
+ * Delete a collection and all its documents
8960
+ */
8961
+ async deleteCollection(collectionId) {
8962
+ await this.httpClient.delete(this.url(`/collections/${collectionId}`));
8963
+ }
8964
+ // ============================================================================
8965
+ // Documents
8966
+ // ============================================================================
8967
+ /**
8968
+ * Upload a document for processing
8969
+ *
8970
+ * @example
8971
+ * // Upload text content
8972
+ * const doc = await blink.rag.upload({
8973
+ * collectionName: 'docs',
8974
+ * filename: 'notes.txt',
8975
+ * content: 'My document content...'
8976
+ * })
8977
+ *
8978
+ * @example
8979
+ * // Upload from URL
8980
+ * const doc = await blink.rag.upload({
8981
+ * collectionId: 'col_abc123',
8982
+ * filename: 'article.html',
8983
+ * url: 'https://example.com/article'
8984
+ * })
8985
+ *
8986
+ * @example
8987
+ * // Upload a file (base64)
8988
+ * const doc = await blink.rag.upload({
8989
+ * collectionName: 'docs',
8990
+ * filename: 'report.pdf',
8991
+ * file: { data: base64Data, contentType: 'application/pdf' }
8992
+ * })
8993
+ */
8994
+ async upload(options) {
8995
+ if (!options.collectionId && !options.collectionName) {
8996
+ throw new Error("collectionId or collectionName is required");
8997
+ }
8998
+ const body = removeUndefined({
8999
+ collection_id: options.collectionId,
9000
+ collection_name: options.collectionName,
9001
+ filename: options.filename,
9002
+ content: options.content,
9003
+ url: options.url,
9004
+ metadata: options.metadata
9005
+ });
9006
+ if (options.file) {
9007
+ body.file = {
9008
+ data: options.file.data,
9009
+ content_type: options.file.contentType
9010
+ };
9011
+ }
9012
+ const response = await this.httpClient.post(this.url("/documents"), body);
9013
+ return convertPartialDocument(response.data, options);
9014
+ }
9015
+ /**
9016
+ * Get document status and metadata
9017
+ */
9018
+ async getDocument(documentId) {
9019
+ const response = await this.httpClient.get(this.url(`/documents/${documentId}`));
9020
+ return convertDocument(response.data);
9021
+ }
9022
+ /**
9023
+ * List documents, optionally filtered by collection or status
9024
+ */
9025
+ async listDocuments(options) {
9026
+ const params = {};
9027
+ if (options?.collectionId) params.collection_id = options.collectionId;
9028
+ if (options?.status) params.status = options.status;
9029
+ const queryString = Object.keys(params).length > 0 ? `?${new URLSearchParams(params).toString()}` : "";
9030
+ const response = await this.httpClient.get(
9031
+ this.url(`/documents${queryString}`)
9032
+ );
9033
+ return response.data.documents.map(convertDocument);
9034
+ }
9035
+ /**
9036
+ * Delete a document and its chunks
9037
+ */
9038
+ async deleteDocument(documentId) {
9039
+ await this.httpClient.delete(this.url(`/documents/${documentId}`));
9040
+ }
9041
+ /**
9042
+ * Wait for a document to finish processing
9043
+ *
9044
+ * @example
9045
+ * const doc = await blink.rag.upload({ ... })
9046
+ * const readyDoc = await blink.rag.waitForReady(doc.id)
9047
+ * console.log(`Processed ${readyDoc.chunkCount} chunks`)
9048
+ */
9049
+ async waitForReady(documentId, options) {
9050
+ const { timeoutMs = 12e4, pollIntervalMs = 2e3 } = options || {};
9051
+ const start = Date.now();
9052
+ while (Date.now() - start < timeoutMs) {
9053
+ const doc = await this.getDocument(documentId);
9054
+ if (doc.status === "ready") {
9055
+ return doc;
9056
+ }
9057
+ if (doc.status === "error") {
9058
+ throw new Error(`Document processing failed: ${doc.errorMessage}`);
9059
+ }
9060
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
9061
+ }
9062
+ throw new Error(`Document processing timeout after ${timeoutMs}ms`);
9063
+ }
9064
+ // ============================================================================
9065
+ // Search
9066
+ // ============================================================================
9067
+ /**
9068
+ * Search for similar chunks using vector similarity
9069
+ *
9070
+ * @example
9071
+ * const results = await blink.rag.search({
9072
+ * collectionName: 'docs',
9073
+ * query: 'How do I configure authentication?',
9074
+ * maxResults: 5
9075
+ * })
9076
+ */
9077
+ async search(options) {
9078
+ if (!options.collectionId && !options.collectionName) {
9079
+ throw new Error("collectionId or collectionName is required");
9080
+ }
9081
+ const body = removeUndefined({
9082
+ collection_id: options.collectionId,
9083
+ collection_name: options.collectionName,
9084
+ query: options.query,
9085
+ max_results: options.maxResults,
9086
+ score_threshold: options.scoreThreshold,
9087
+ filters: options.filters,
9088
+ include_content: options.includeContent
9089
+ });
9090
+ const response = await this.httpClient.post(this.url("/search"), body);
9091
+ return convertSearchResponse(response.data);
9092
+ }
9093
+ async aiSearch(options) {
9094
+ if (!options.collectionId && !options.collectionName) {
9095
+ throw new Error("collectionId or collectionName is required");
9096
+ }
9097
+ const body = removeUndefined({
9098
+ collection_id: options.collectionId,
9099
+ collection_name: options.collectionName,
9100
+ query: options.query,
9101
+ model: options.model,
9102
+ max_context_chunks: options.maxContextChunks,
9103
+ score_threshold: options.scoreThreshold,
9104
+ system_prompt: options.systemPrompt,
9105
+ stream: options.stream
9106
+ });
9107
+ if (options.stream) {
9108
+ const response2 = await this.httpClient.ragAiSearchStream(body, options.signal);
9109
+ return response2.body;
9110
+ }
9111
+ const response = await this.httpClient.post(this.url("/ai-search"), body);
9112
+ return convertAISearchResult(response.data);
9113
+ }
9114
+ };
9115
+
9116
+ // src/sandbox.ts
9117
+ var SANDBOX_TEMPLATES = [
9118
+ "devtools-base",
9119
+ // Node 22 + Bun + Python + Git + ripgrep (DEFAULT)
9120
+ "nextjs-app",
9121
+ // Next.js + Tailwind + shadcn UI (Node)
9122
+ "nextjs-app-bun",
9123
+ // Next.js + Tailwind + shadcn UI (Bun)
9124
+ "vite-react",
9125
+ // Vite + React + Tailwind + shadcn (Node)
9126
+ "vite-react-bun",
9127
+ // Vite + React + Tailwind + shadcn (Bun)
9128
+ "expo-app",
9129
+ // Expo + React Native
9130
+ "desktop",
9131
+ // Electron + Vite + React
9132
+ "claude-code"
9133
+ // Node 21 + Python + Git + ripgrep
9134
+ ];
9135
+ var SandboxConnectionError = class extends Error {
9136
+ sandboxId;
9137
+ constructor(sandboxId, cause) {
9138
+ super(`Failed to connect to sandbox ${sandboxId}`);
9139
+ this.name = "SandboxConnectionError";
9140
+ this.sandboxId = sandboxId;
9141
+ if (cause) {
9142
+ this.cause = cause;
9143
+ }
9144
+ }
9145
+ };
9146
+ var SandboxImpl = class {
9147
+ constructor(id, template, hostPattern) {
9148
+ this.id = id;
9149
+ this.template = template;
9150
+ this.hostPattern = hostPattern;
9151
+ }
9152
+ getHost(port) {
9153
+ return this.hostPattern.replace("{port}", String(port));
9154
+ }
9155
+ };
9156
+ var MAX_RETRIES = 3;
9157
+ var INITIAL_RETRY_DELAY_MS = 250;
9158
+ var BlinkSandboxImpl = class {
9159
+ constructor(httpClient) {
9160
+ this.httpClient = httpClient;
9161
+ this.projectId = httpClient.projectId;
9162
+ }
9163
+ projectId;
9164
+ /**
9165
+ * Build URL with project_id prefix
9166
+ */
9167
+ url(path) {
9168
+ return `/api/sandbox/${this.projectId}${path}`;
9169
+ }
9170
+ async create(options = {}) {
9171
+ const body = {
9172
+ template: options.template,
9173
+ timeout_ms: options.timeoutMs,
9174
+ metadata: options.metadata
9175
+ };
9176
+ const response = await this.httpClient.post(this.url("/create"), body);
9177
+ const { id, template, host_pattern } = response.data;
9178
+ return new SandboxImpl(id, template, host_pattern);
9179
+ }
9180
+ async connect(sandboxId, options = {}) {
9181
+ let lastError;
9182
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
9183
+ try {
9184
+ const body = {
9185
+ sandbox_id: sandboxId,
9186
+ timeout_ms: options.timeoutMs
9187
+ };
9188
+ const response = await this.httpClient.post(this.url("/connect"), body);
9189
+ const { id, template, host_pattern } = response.data;
9190
+ return new SandboxImpl(id, template, host_pattern);
9191
+ } catch (error) {
9192
+ console.error(`[Sandbox] Connect attempt ${attempt + 1} failed:`, error);
9193
+ lastError = error instanceof Error ? error : new Error(String(error));
9194
+ if (lastError.message.includes("404") || lastError.message.includes("not found") || lastError.message.includes("unauthorized")) {
9195
+ throw new SandboxConnectionError(sandboxId, lastError);
9196
+ }
9197
+ if (attempt < MAX_RETRIES - 1) {
9198
+ const delay = INITIAL_RETRY_DELAY_MS * Math.pow(2, attempt);
9199
+ await new Promise((resolve) => setTimeout(resolve, delay));
9200
+ }
9201
+ }
9202
+ }
9203
+ console.error(`[Sandbox] All ${MAX_RETRIES} connection attempts failed for sandbox ${sandboxId}`);
9204
+ throw new SandboxConnectionError(sandboxId, lastError);
9205
+ }
9206
+ async kill(sandboxId) {
9207
+ await this.httpClient.post(this.url("/kill"), { sandbox_id: sandboxId });
9208
+ }
9209
+ };
9210
+
5763
9211
  // src/client.ts
5764
9212
  var BlinkClientImpl = class {
5765
9213
  auth;
@@ -5772,6 +9220,8 @@ var BlinkClientImpl = class {
5772
9220
  analytics;
5773
9221
  connectors;
5774
9222
  functions;
9223
+ rag;
9224
+ sandbox;
5775
9225
  httpClient;
5776
9226
  constructor(config) {
5777
9227
  if ((config.secretKey || config.serviceToken) && isBrowser) {
@@ -5796,6 +9246,8 @@ var BlinkClientImpl = class {
5796
9246
  config.projectId,
5797
9247
  () => this.auth.getValidToken()
5798
9248
  );
9249
+ this.rag = new BlinkRAGImpl(this.httpClient);
9250
+ this.sandbox = new BlinkSandboxImpl(this.httpClient);
5799
9251
  this.auth.onAuthStateChanged((state) => {
5800
9252
  if (state.isAuthenticated && state.user) {
5801
9253
  this.analytics.setUserId(state.user.id);
@@ -5814,6 +9266,6 @@ function createClient(config) {
5814
9266
  return new BlinkClientImpl(config);
5815
9267
  }
5816
9268
 
5817
- export { AsyncStorageAdapter, BlinkAIImpl, BlinkAnalyticsImpl, BlinkConnectorsImpl, BlinkDataImpl, BlinkDatabase, BlinkRealtimeChannel, BlinkRealtimeImpl, BlinkStorageImpl, BlinkTable, NoOpStorageAdapter, WebStorageAdapter, createClient, getDefaultStorageAdapter, isBrowser, isDeno, isNode, isReactNative, isServer, isWeb, platform };
9269
+ export { Agent, AsyncStorageAdapter, BlinkAIImpl, BlinkAnalyticsImpl, BlinkConnectorsImpl, BlinkDataImpl, BlinkDatabase, BlinkRAGImpl, BlinkRealtimeChannel, BlinkRealtimeImpl, BlinkSandboxImpl, BlinkStorageImpl, BlinkTable, NoOpStorageAdapter, SANDBOX_TEMPLATES, SandboxConnectionError, WebStorageAdapter, coreTools, createClient, dbDelete, dbGet, dbInsert, dbList, dbTools, dbUpdate, editImage, fetchUrl, generateImage, generateVideo, getDefaultStorageAdapter, getHost, globFileSearch, grep, imageToVideo, isBrowser, isDeno, isNode, isReactNative, isServer, isWeb, listDir, mediaTools, platform, ragSearch, ragTools, readFile, runCode, runTerminalCmd, sandboxTools, searchReplace, serializeTools, stepCountIs, storageCopy, storageDelete, storageDownload, storageList, storageMove, storagePublicUrl, storageTools, storageUpload, webSearch, writeFile };
5818
9270
  //# sourceMappingURL=index.mjs.map
5819
9271
  //# sourceMappingURL=index.mjs.map