@blinkdotnew/sdk 2.2.0 → 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.js CHANGED
@@ -1,11 +1,2584 @@
1
1
  'use strict';
2
2
 
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
4
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
5
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
6
  }) : x)(function(x) {
6
7
  if (typeof require !== "undefined") return require.apply(this, arguments);
7
8
  throw Error('Dynamic require of "' + x + '" is not supported');
8
9
  });
10
+ var __commonJS = (cb, mod) => function __require2() {
11
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
12
+ };
13
+
14
+ // ../../node_modules/async-limiter/index.js
15
+ var require_async_limiter = __commonJS({
16
+ "../../node_modules/async-limiter/index.js"(exports, module) {
17
+ function Queue(options) {
18
+ if (!(this instanceof Queue)) {
19
+ return new Queue(options);
20
+ }
21
+ options = options || {};
22
+ this.concurrency = options.concurrency || Infinity;
23
+ this.pending = 0;
24
+ this.jobs = [];
25
+ this.cbs = [];
26
+ this._done = done.bind(this);
27
+ }
28
+ var arrayAddMethods = [
29
+ "push",
30
+ "unshift",
31
+ "splice"
32
+ ];
33
+ arrayAddMethods.forEach(function(method) {
34
+ Queue.prototype[method] = function() {
35
+ var methodResult = Array.prototype[method].apply(this.jobs, arguments);
36
+ this._run();
37
+ return methodResult;
38
+ };
39
+ });
40
+ Object.defineProperty(Queue.prototype, "length", {
41
+ get: function() {
42
+ return this.pending + this.jobs.length;
43
+ }
44
+ });
45
+ Queue.prototype._run = function() {
46
+ if (this.pending === this.concurrency) {
47
+ return;
48
+ }
49
+ if (this.jobs.length) {
50
+ var job = this.jobs.shift();
51
+ this.pending++;
52
+ job(this._done);
53
+ this._run();
54
+ }
55
+ if (this.pending === 0) {
56
+ while (this.cbs.length !== 0) {
57
+ var cb = this.cbs.pop();
58
+ process.nextTick(cb);
59
+ }
60
+ }
61
+ };
62
+ Queue.prototype.onDone = function(cb) {
63
+ if (typeof cb === "function") {
64
+ this.cbs.push(cb);
65
+ this._run();
66
+ }
67
+ };
68
+ function done() {
69
+ this.pending--;
70
+ this._run();
71
+ }
72
+ module.exports = Queue;
73
+ }
74
+ });
75
+
76
+ // ../../node_modules/ws/lib/constants.js
77
+ var require_constants = __commonJS({
78
+ "../../node_modules/ws/lib/constants.js"(exports, module) {
79
+ module.exports = {
80
+ BINARY_TYPES: ["nodebuffer", "arraybuffer", "fragments"],
81
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
82
+ kStatusCode: Symbol("status-code"),
83
+ kWebSocket: Symbol("websocket"),
84
+ EMPTY_BUFFER: Buffer.alloc(0),
85
+ NOOP: () => {
86
+ }
87
+ };
88
+ }
89
+ });
90
+
91
+ // ../../node_modules/ws/lib/buffer-util.js
92
+ var require_buffer_util = __commonJS({
93
+ "../../node_modules/ws/lib/buffer-util.js"(exports, module) {
94
+ var { EMPTY_BUFFER } = require_constants();
95
+ function concat(list, totalLength) {
96
+ if (list.length === 0) return EMPTY_BUFFER;
97
+ if (list.length === 1) return list[0];
98
+ const target = Buffer.allocUnsafe(totalLength);
99
+ var offset = 0;
100
+ for (var i = 0; i < list.length; i++) {
101
+ const buf = list[i];
102
+ buf.copy(target, offset);
103
+ offset += buf.length;
104
+ }
105
+ return target;
106
+ }
107
+ function _mask(source, mask, output, offset, length) {
108
+ for (var i = 0; i < length; i++) {
109
+ output[offset + i] = source[i] ^ mask[i & 3];
110
+ }
111
+ }
112
+ function _unmask(buffer, mask) {
113
+ const length = buffer.length;
114
+ for (var i = 0; i < length; i++) {
115
+ buffer[i] ^= mask[i & 3];
116
+ }
117
+ }
118
+ function toArrayBuffer(buf) {
119
+ if (buf.byteLength === buf.buffer.byteLength) {
120
+ return buf.buffer;
121
+ }
122
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
123
+ }
124
+ function toBuffer(data) {
125
+ toBuffer.readOnly = true;
126
+ if (Buffer.isBuffer(data)) return data;
127
+ var buf;
128
+ if (data instanceof ArrayBuffer) {
129
+ buf = Buffer.from(data);
130
+ } else if (ArrayBuffer.isView(data)) {
131
+ buf = viewToBuffer(data);
132
+ } else {
133
+ buf = Buffer.from(data);
134
+ toBuffer.readOnly = false;
135
+ }
136
+ return buf;
137
+ }
138
+ function viewToBuffer(view) {
139
+ const buf = Buffer.from(view.buffer);
140
+ if (view.byteLength !== view.buffer.byteLength) {
141
+ return buf.slice(view.byteOffset, view.byteOffset + view.byteLength);
142
+ }
143
+ return buf;
144
+ }
145
+ try {
146
+ const bufferUtil = __require("bufferutil");
147
+ const bu = bufferUtil.BufferUtil || bufferUtil;
148
+ module.exports = {
149
+ concat,
150
+ mask(source, mask, output, offset, length) {
151
+ if (length < 48) _mask(source, mask, output, offset, length);
152
+ else bu.mask(source, mask, output, offset, length);
153
+ },
154
+ toArrayBuffer,
155
+ toBuffer,
156
+ unmask(buffer, mask) {
157
+ if (buffer.length < 32) _unmask(buffer, mask);
158
+ else bu.unmask(buffer, mask);
159
+ }
160
+ };
161
+ } catch (e) {
162
+ module.exports = {
163
+ concat,
164
+ mask: _mask,
165
+ toArrayBuffer,
166
+ toBuffer,
167
+ unmask: _unmask
168
+ };
169
+ }
170
+ }
171
+ });
172
+
173
+ // ../../node_modules/ws/lib/permessage-deflate.js
174
+ var require_permessage_deflate = __commonJS({
175
+ "../../node_modules/ws/lib/permessage-deflate.js"(exports, module) {
176
+ var Limiter = require_async_limiter();
177
+ var zlib = __require("zlib");
178
+ var bufferUtil = require_buffer_util();
179
+ var { kStatusCode, NOOP } = require_constants();
180
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
181
+ var EMPTY_BLOCK = Buffer.from([0]);
182
+ var kPerMessageDeflate = Symbol("permessage-deflate");
183
+ var kTotalLength = Symbol("total-length");
184
+ var kCallback = Symbol("callback");
185
+ var kBuffers = Symbol("buffers");
186
+ var kError = Symbol("error");
187
+ var zlibLimiter;
188
+ var PerMessageDeflate = class {
189
+ /**
190
+ * Creates a PerMessageDeflate instance.
191
+ *
192
+ * @param {Object} options Configuration options
193
+ * @param {Boolean} options.serverNoContextTakeover Request/accept disabling
194
+ * of server context takeover
195
+ * @param {Boolean} options.clientNoContextTakeover Advertise/acknowledge
196
+ * disabling of client context takeover
197
+ * @param {(Boolean|Number)} options.serverMaxWindowBits Request/confirm the
198
+ * use of a custom server window size
199
+ * @param {(Boolean|Number)} options.clientMaxWindowBits Advertise support
200
+ * for, or request, a custom client window size
201
+ * @param {Object} options.zlibDeflateOptions Options to pass to zlib on deflate
202
+ * @param {Object} options.zlibInflateOptions Options to pass to zlib on inflate
203
+ * @param {Number} options.threshold Size (in bytes) below which messages
204
+ * should not be compressed
205
+ * @param {Number} options.concurrencyLimit The number of concurrent calls to
206
+ * zlib
207
+ * @param {Boolean} isServer Create the instance in either server or client
208
+ * mode
209
+ * @param {Number} maxPayload The maximum allowed message length
210
+ */
211
+ constructor(options, isServer2, maxPayload) {
212
+ this._maxPayload = maxPayload | 0;
213
+ this._options = options || {};
214
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
215
+ this._isServer = !!isServer2;
216
+ this._deflate = null;
217
+ this._inflate = null;
218
+ this.params = null;
219
+ if (!zlibLimiter) {
220
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
221
+ zlibLimiter = new Limiter({ concurrency });
222
+ }
223
+ }
224
+ /**
225
+ * @type {String}
226
+ */
227
+ static get extensionName() {
228
+ return "permessage-deflate";
229
+ }
230
+ /**
231
+ * Create an extension negotiation offer.
232
+ *
233
+ * @return {Object} Extension parameters
234
+ * @public
235
+ */
236
+ offer() {
237
+ const params = {};
238
+ if (this._options.serverNoContextTakeover) {
239
+ params.server_no_context_takeover = true;
240
+ }
241
+ if (this._options.clientNoContextTakeover) {
242
+ params.client_no_context_takeover = true;
243
+ }
244
+ if (this._options.serverMaxWindowBits) {
245
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
246
+ }
247
+ if (this._options.clientMaxWindowBits) {
248
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
249
+ } else if (this._options.clientMaxWindowBits == null) {
250
+ params.client_max_window_bits = true;
251
+ }
252
+ return params;
253
+ }
254
+ /**
255
+ * Accept an extension negotiation offer/response.
256
+ *
257
+ * @param {Array} configurations The extension negotiation offers/reponse
258
+ * @return {Object} Accepted configuration
259
+ * @public
260
+ */
261
+ accept(configurations) {
262
+ configurations = this.normalizeParams(configurations);
263
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
264
+ return this.params;
265
+ }
266
+ /**
267
+ * Releases all resources used by the extension.
268
+ *
269
+ * @public
270
+ */
271
+ cleanup() {
272
+ if (this._inflate) {
273
+ this._inflate.close();
274
+ this._inflate = null;
275
+ }
276
+ if (this._deflate) {
277
+ this._deflate.close();
278
+ this._deflate = null;
279
+ }
280
+ }
281
+ /**
282
+ * Accept an extension negotiation offer.
283
+ *
284
+ * @param {Array} offers The extension negotiation offers
285
+ * @return {Object} Accepted configuration
286
+ * @private
287
+ */
288
+ acceptAsServer(offers) {
289
+ const opts = this._options;
290
+ const accepted = offers.find((params) => {
291
+ 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) {
292
+ return false;
293
+ }
294
+ return true;
295
+ });
296
+ if (!accepted) {
297
+ throw new Error("None of the extension offers can be accepted");
298
+ }
299
+ if (opts.serverNoContextTakeover) {
300
+ accepted.server_no_context_takeover = true;
301
+ }
302
+ if (opts.clientNoContextTakeover) {
303
+ accepted.client_no_context_takeover = true;
304
+ }
305
+ if (typeof opts.serverMaxWindowBits === "number") {
306
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
307
+ }
308
+ if (typeof opts.clientMaxWindowBits === "number") {
309
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
310
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
311
+ delete accepted.client_max_window_bits;
312
+ }
313
+ return accepted;
314
+ }
315
+ /**
316
+ * Accept the extension negotiation response.
317
+ *
318
+ * @param {Array} response The extension negotiation response
319
+ * @return {Object} Accepted configuration
320
+ * @private
321
+ */
322
+ acceptAsClient(response) {
323
+ const params = response[0];
324
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
325
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
326
+ }
327
+ if (!params.client_max_window_bits) {
328
+ if (typeof this._options.clientMaxWindowBits === "number") {
329
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
330
+ }
331
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
332
+ throw new Error(
333
+ 'Unexpected or invalid parameter "client_max_window_bits"'
334
+ );
335
+ }
336
+ return params;
337
+ }
338
+ /**
339
+ * Normalize parameters.
340
+ *
341
+ * @param {Array} configurations The extension negotiation offers/reponse
342
+ * @return {Array} The offers/response with normalized parameters
343
+ * @private
344
+ */
345
+ normalizeParams(configurations) {
346
+ configurations.forEach((params) => {
347
+ Object.keys(params).forEach((key) => {
348
+ var value = params[key];
349
+ if (value.length > 1) {
350
+ throw new Error(`Parameter "${key}" must have only a single value`);
351
+ }
352
+ value = value[0];
353
+ if (key === "client_max_window_bits") {
354
+ if (value !== true) {
355
+ const num = +value;
356
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
357
+ throw new TypeError(
358
+ `Invalid value for parameter "${key}": ${value}`
359
+ );
360
+ }
361
+ value = num;
362
+ } else if (!this._isServer) {
363
+ throw new TypeError(
364
+ `Invalid value for parameter "${key}": ${value}`
365
+ );
366
+ }
367
+ } else if (key === "server_max_window_bits") {
368
+ const num = +value;
369
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
370
+ throw new TypeError(
371
+ `Invalid value for parameter "${key}": ${value}`
372
+ );
373
+ }
374
+ value = num;
375
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
376
+ if (value !== true) {
377
+ throw new TypeError(
378
+ `Invalid value for parameter "${key}": ${value}`
379
+ );
380
+ }
381
+ } else {
382
+ throw new Error(`Unknown parameter "${key}"`);
383
+ }
384
+ params[key] = value;
385
+ });
386
+ });
387
+ return configurations;
388
+ }
389
+ /**
390
+ * Decompress data. Concurrency limited by async-limiter.
391
+ *
392
+ * @param {Buffer} data Compressed data
393
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
394
+ * @param {Function} callback Callback
395
+ * @public
396
+ */
397
+ decompress(data, fin, callback) {
398
+ zlibLimiter.push((done) => {
399
+ this._decompress(data, fin, (err, result) => {
400
+ done();
401
+ callback(err, result);
402
+ });
403
+ });
404
+ }
405
+ /**
406
+ * Compress data. Concurrency limited by async-limiter.
407
+ *
408
+ * @param {Buffer} data Data to compress
409
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
410
+ * @param {Function} callback Callback
411
+ * @public
412
+ */
413
+ compress(data, fin, callback) {
414
+ zlibLimiter.push((done) => {
415
+ this._compress(data, fin, (err, result) => {
416
+ done();
417
+ callback(err, result);
418
+ });
419
+ });
420
+ }
421
+ /**
422
+ * Decompress data.
423
+ *
424
+ * @param {Buffer} data Compressed data
425
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
426
+ * @param {Function} callback Callback
427
+ * @private
428
+ */
429
+ _decompress(data, fin, callback) {
430
+ const endpoint = this._isServer ? "client" : "server";
431
+ if (!this._inflate) {
432
+ const key = `${endpoint}_max_window_bits`;
433
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
434
+ this._inflate = zlib.createInflateRaw(
435
+ Object.assign({}, this._options.zlibInflateOptions, { windowBits })
436
+ );
437
+ this._inflate[kPerMessageDeflate] = this;
438
+ this._inflate[kTotalLength] = 0;
439
+ this._inflate[kBuffers] = [];
440
+ this._inflate.on("error", inflateOnError);
441
+ this._inflate.on("data", inflateOnData);
442
+ }
443
+ this._inflate[kCallback] = callback;
444
+ this._inflate.write(data);
445
+ if (fin) this._inflate.write(TRAILER);
446
+ this._inflate.flush(() => {
447
+ const err = this._inflate[kError];
448
+ if (err) {
449
+ this._inflate.close();
450
+ this._inflate = null;
451
+ callback(err);
452
+ return;
453
+ }
454
+ const data2 = bufferUtil.concat(
455
+ this._inflate[kBuffers],
456
+ this._inflate[kTotalLength]
457
+ );
458
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
459
+ this._inflate.close();
460
+ this._inflate = null;
461
+ } else {
462
+ this._inflate[kTotalLength] = 0;
463
+ this._inflate[kBuffers] = [];
464
+ }
465
+ callback(null, data2);
466
+ });
467
+ }
468
+ /**
469
+ * Compress data.
470
+ *
471
+ * @param {Buffer} data Data to compress
472
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
473
+ * @param {Function} callback Callback
474
+ * @private
475
+ */
476
+ _compress(data, fin, callback) {
477
+ if (!data || data.length === 0) {
478
+ process.nextTick(callback, null, EMPTY_BLOCK);
479
+ return;
480
+ }
481
+ const endpoint = this._isServer ? "server" : "client";
482
+ if (!this._deflate) {
483
+ const key = `${endpoint}_max_window_bits`;
484
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
485
+ this._deflate = zlib.createDeflateRaw(
486
+ Object.assign({}, this._options.zlibDeflateOptions, { windowBits })
487
+ );
488
+ this._deflate[kTotalLength] = 0;
489
+ this._deflate[kBuffers] = [];
490
+ this._deflate.on("error", NOOP);
491
+ this._deflate.on("data", deflateOnData);
492
+ }
493
+ this._deflate.write(data);
494
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
495
+ if (!this._deflate) {
496
+ return;
497
+ }
498
+ var data2 = bufferUtil.concat(
499
+ this._deflate[kBuffers],
500
+ this._deflate[kTotalLength]
501
+ );
502
+ if (fin) data2 = data2.slice(0, data2.length - 4);
503
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
504
+ this._deflate.close();
505
+ this._deflate = null;
506
+ } else {
507
+ this._deflate[kTotalLength] = 0;
508
+ this._deflate[kBuffers] = [];
509
+ }
510
+ callback(null, data2);
511
+ });
512
+ }
513
+ };
514
+ module.exports = PerMessageDeflate;
515
+ function deflateOnData(chunk) {
516
+ this[kBuffers].push(chunk);
517
+ this[kTotalLength] += chunk.length;
518
+ }
519
+ function inflateOnData(chunk) {
520
+ this[kTotalLength] += chunk.length;
521
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
522
+ this[kBuffers].push(chunk);
523
+ return;
524
+ }
525
+ this[kError] = new RangeError("Max payload size exceeded");
526
+ this[kError][kStatusCode] = 1009;
527
+ this.removeListener("data", inflateOnData);
528
+ this.reset();
529
+ }
530
+ function inflateOnError(err) {
531
+ this[kPerMessageDeflate]._inflate = null;
532
+ err[kStatusCode] = 1007;
533
+ this[kCallback](err);
534
+ }
535
+ }
536
+ });
537
+
538
+ // ../../node_modules/ws/lib/event-target.js
539
+ var require_event_target = __commonJS({
540
+ "../../node_modules/ws/lib/event-target.js"(exports, module) {
541
+ var Event = class {
542
+ /**
543
+ * Create a new `Event`.
544
+ *
545
+ * @param {String} type The name of the event
546
+ * @param {Object} target A reference to the target to which the event was dispatched
547
+ */
548
+ constructor(type, target) {
549
+ this.target = target;
550
+ this.type = type;
551
+ }
552
+ };
553
+ var MessageEvent = class extends Event {
554
+ /**
555
+ * Create a new `MessageEvent`.
556
+ *
557
+ * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data
558
+ * @param {WebSocket} target A reference to the target to which the event was dispatched
559
+ */
560
+ constructor(data, target) {
561
+ super("message", target);
562
+ this.data = data;
563
+ }
564
+ };
565
+ var CloseEvent = class extends Event {
566
+ /**
567
+ * Create a new `CloseEvent`.
568
+ *
569
+ * @param {Number} code The status code explaining why the connection is being closed
570
+ * @param {String} reason A human-readable string explaining why the connection is closing
571
+ * @param {WebSocket} target A reference to the target to which the event was dispatched
572
+ */
573
+ constructor(code, reason, target) {
574
+ super("close", target);
575
+ this.wasClean = target._closeFrameReceived && target._closeFrameSent;
576
+ this.reason = reason;
577
+ this.code = code;
578
+ }
579
+ };
580
+ var OpenEvent = class extends Event {
581
+ /**
582
+ * Create a new `OpenEvent`.
583
+ *
584
+ * @param {WebSocket} target A reference to the target to which the event was dispatched
585
+ */
586
+ constructor(target) {
587
+ super("open", target);
588
+ }
589
+ };
590
+ var ErrorEvent = class extends Event {
591
+ /**
592
+ * Create a new `ErrorEvent`.
593
+ *
594
+ * @param {Object} error The error that generated this event
595
+ * @param {WebSocket} target A reference to the target to which the event was dispatched
596
+ */
597
+ constructor(error, target) {
598
+ super("error", target);
599
+ this.message = error.message;
600
+ this.error = error;
601
+ }
602
+ };
603
+ var EventTarget = {
604
+ /**
605
+ * Register an event listener.
606
+ *
607
+ * @param {String} method A string representing the event type to listen for
608
+ * @param {Function} listener The listener to add
609
+ * @public
610
+ */
611
+ addEventListener(method, listener) {
612
+ if (typeof listener !== "function") return;
613
+ function onMessage(data) {
614
+ listener.call(this, new MessageEvent(data, this));
615
+ }
616
+ function onClose(code, message) {
617
+ listener.call(this, new CloseEvent(code, message, this));
618
+ }
619
+ function onError(error) {
620
+ listener.call(this, new ErrorEvent(error, this));
621
+ }
622
+ function onOpen() {
623
+ listener.call(this, new OpenEvent(this));
624
+ }
625
+ if (method === "message") {
626
+ onMessage._listener = listener;
627
+ this.on(method, onMessage);
628
+ } else if (method === "close") {
629
+ onClose._listener = listener;
630
+ this.on(method, onClose);
631
+ } else if (method === "error") {
632
+ onError._listener = listener;
633
+ this.on(method, onError);
634
+ } else if (method === "open") {
635
+ onOpen._listener = listener;
636
+ this.on(method, onOpen);
637
+ } else {
638
+ this.on(method, listener);
639
+ }
640
+ },
641
+ /**
642
+ * Remove an event listener.
643
+ *
644
+ * @param {String} method A string representing the event type to remove
645
+ * @param {Function} listener The listener to remove
646
+ * @public
647
+ */
648
+ removeEventListener(method, listener) {
649
+ const listeners = this.listeners(method);
650
+ for (var i = 0; i < listeners.length; i++) {
651
+ if (listeners[i] === listener || listeners[i]._listener === listener) {
652
+ this.removeListener(method, listeners[i]);
653
+ }
654
+ }
655
+ }
656
+ };
657
+ module.exports = EventTarget;
658
+ }
659
+ });
660
+
661
+ // ../../node_modules/ws/lib/extension.js
662
+ var require_extension = __commonJS({
663
+ "../../node_modules/ws/lib/extension.js"(exports, module) {
664
+ var tokenChars = [
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,
680
+ 0,
681
+ // 0 - 15
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
+ 0,
697
+ 0,
698
+ // 16 - 31
699
+ 0,
700
+ 1,
701
+ 0,
702
+ 1,
703
+ 1,
704
+ 1,
705
+ 1,
706
+ 1,
707
+ 0,
708
+ 0,
709
+ 1,
710
+ 1,
711
+ 0,
712
+ 1,
713
+ 1,
714
+ 0,
715
+ // 32 - 47
716
+ 1,
717
+ 1,
718
+ 1,
719
+ 1,
720
+ 1,
721
+ 1,
722
+ 1,
723
+ 1,
724
+ 1,
725
+ 1,
726
+ 0,
727
+ 0,
728
+ 0,
729
+ 0,
730
+ 0,
731
+ 0,
732
+ // 48 - 63
733
+ 0,
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
+ 1,
748
+ 1,
749
+ // 64 - 79
750
+ 1,
751
+ 1,
752
+ 1,
753
+ 1,
754
+ 1,
755
+ 1,
756
+ 1,
757
+ 1,
758
+ 1,
759
+ 1,
760
+ 1,
761
+ 0,
762
+ 0,
763
+ 0,
764
+ 1,
765
+ 1,
766
+ // 80 - 95
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
+ 1,
782
+ 1,
783
+ // 96 - 111
784
+ 1,
785
+ 1,
786
+ 1,
787
+ 1,
788
+ 1,
789
+ 1,
790
+ 1,
791
+ 1,
792
+ 1,
793
+ 1,
794
+ 1,
795
+ 0,
796
+ 1,
797
+ 0,
798
+ 1,
799
+ 0
800
+ // 112 - 127
801
+ ];
802
+ function push(dest, name, elem) {
803
+ if (Object.prototype.hasOwnProperty.call(dest, name)) dest[name].push(elem);
804
+ else dest[name] = [elem];
805
+ }
806
+ function parse(header) {
807
+ const offers = {};
808
+ if (header === void 0 || header === "") return offers;
809
+ var params = {};
810
+ var mustUnescape = false;
811
+ var isEscaping = false;
812
+ var inQuotes = false;
813
+ var extensionName;
814
+ var paramName;
815
+ var start = -1;
816
+ var end = -1;
817
+ for (var i = 0; i < header.length; i++) {
818
+ const code = header.charCodeAt(i);
819
+ if (extensionName === void 0) {
820
+ if (end === -1 && tokenChars[code] === 1) {
821
+ if (start === -1) start = i;
822
+ } else if (code === 32 || code === 9) {
823
+ if (end === -1 && start !== -1) end = i;
824
+ } else if (code === 59 || code === 44) {
825
+ if (start === -1) {
826
+ throw new SyntaxError(`Unexpected character at index ${i}`);
827
+ }
828
+ if (end === -1) end = i;
829
+ const name = header.slice(start, end);
830
+ if (code === 44) {
831
+ push(offers, name, params);
832
+ params = {};
833
+ } else {
834
+ extensionName = name;
835
+ }
836
+ start = end = -1;
837
+ } else {
838
+ throw new SyntaxError(`Unexpected character at index ${i}`);
839
+ }
840
+ } else if (paramName === void 0) {
841
+ if (end === -1 && tokenChars[code] === 1) {
842
+ if (start === -1) start = i;
843
+ } else if (code === 32 || code === 9) {
844
+ if (end === -1 && start !== -1) end = i;
845
+ } else if (code === 59 || code === 44) {
846
+ if (start === -1) {
847
+ throw new SyntaxError(`Unexpected character at index ${i}`);
848
+ }
849
+ if (end === -1) end = i;
850
+ push(params, header.slice(start, end), true);
851
+ if (code === 44) {
852
+ push(offers, extensionName, params);
853
+ params = {};
854
+ extensionName = void 0;
855
+ }
856
+ start = end = -1;
857
+ } else if (code === 61 && start !== -1 && end === -1) {
858
+ paramName = header.slice(start, i);
859
+ start = end = -1;
860
+ } else {
861
+ throw new SyntaxError(`Unexpected character at index ${i}`);
862
+ }
863
+ } else {
864
+ if (isEscaping) {
865
+ if (tokenChars[code] !== 1) {
866
+ throw new SyntaxError(`Unexpected character at index ${i}`);
867
+ }
868
+ if (start === -1) start = i;
869
+ else if (!mustUnescape) mustUnescape = true;
870
+ isEscaping = false;
871
+ } else if (inQuotes) {
872
+ if (tokenChars[code] === 1) {
873
+ if (start === -1) start = i;
874
+ } else if (code === 34 && start !== -1) {
875
+ inQuotes = false;
876
+ end = i;
877
+ } else if (code === 92) {
878
+ isEscaping = true;
879
+ } else {
880
+ throw new SyntaxError(`Unexpected character at index ${i}`);
881
+ }
882
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
883
+ inQuotes = true;
884
+ } else if (end === -1 && tokenChars[code] === 1) {
885
+ if (start === -1) start = i;
886
+ } else if (start !== -1 && (code === 32 || code === 9)) {
887
+ if (end === -1) end = i;
888
+ } else if (code === 59 || code === 44) {
889
+ if (start === -1) {
890
+ throw new SyntaxError(`Unexpected character at index ${i}`);
891
+ }
892
+ if (end === -1) end = i;
893
+ var value = header.slice(start, end);
894
+ if (mustUnescape) {
895
+ value = value.replace(/\\/g, "");
896
+ mustUnescape = false;
897
+ }
898
+ push(params, paramName, value);
899
+ if (code === 44) {
900
+ push(offers, extensionName, params);
901
+ params = {};
902
+ extensionName = void 0;
903
+ }
904
+ paramName = void 0;
905
+ start = end = -1;
906
+ } else {
907
+ throw new SyntaxError(`Unexpected character at index ${i}`);
908
+ }
909
+ }
910
+ }
911
+ if (start === -1 || inQuotes) {
912
+ throw new SyntaxError("Unexpected end of input");
913
+ }
914
+ if (end === -1) end = i;
915
+ const token = header.slice(start, end);
916
+ if (extensionName === void 0) {
917
+ push(offers, token, {});
918
+ } else {
919
+ if (paramName === void 0) {
920
+ push(params, token, true);
921
+ } else if (mustUnescape) {
922
+ push(params, paramName, token.replace(/\\/g, ""));
923
+ } else {
924
+ push(params, paramName, token);
925
+ }
926
+ push(offers, extensionName, params);
927
+ }
928
+ return offers;
929
+ }
930
+ function format(extensions) {
931
+ return Object.keys(extensions).map((extension) => {
932
+ var configurations = extensions[extension];
933
+ if (!Array.isArray(configurations)) configurations = [configurations];
934
+ return configurations.map((params) => {
935
+ return [extension].concat(
936
+ Object.keys(params).map((k) => {
937
+ var values = params[k];
938
+ if (!Array.isArray(values)) values = [values];
939
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
940
+ })
941
+ ).join("; ");
942
+ }).join(", ");
943
+ }).join(", ");
944
+ }
945
+ module.exports = { format, parse };
946
+ }
947
+ });
948
+
949
+ // ../../node_modules/ws/lib/validation.js
950
+ var require_validation = __commonJS({
951
+ "../../node_modules/ws/lib/validation.js"(exports) {
952
+ try {
953
+ const isValidUTF8 = __require("utf-8-validate");
954
+ exports.isValidUTF8 = typeof isValidUTF8 === "object" ? isValidUTF8.Validation.isValidUTF8 : isValidUTF8;
955
+ } catch (e) {
956
+ exports.isValidUTF8 = () => true;
957
+ }
958
+ exports.isValidStatusCode = (code) => {
959
+ return code >= 1e3 && code <= 1013 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
960
+ };
961
+ }
962
+ });
963
+
964
+ // ../../node_modules/ws/lib/receiver.js
965
+ var require_receiver = __commonJS({
966
+ "../../node_modules/ws/lib/receiver.js"(exports, module) {
967
+ var { Writable } = __require("stream");
968
+ var PerMessageDeflate = require_permessage_deflate();
969
+ var {
970
+ BINARY_TYPES,
971
+ EMPTY_BUFFER,
972
+ kStatusCode,
973
+ kWebSocket
974
+ } = require_constants();
975
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
976
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
977
+ var GET_INFO = 0;
978
+ var GET_PAYLOAD_LENGTH_16 = 1;
979
+ var GET_PAYLOAD_LENGTH_64 = 2;
980
+ var GET_MASK = 3;
981
+ var GET_DATA = 4;
982
+ var INFLATING = 5;
983
+ var Receiver = class extends Writable {
984
+ /**
985
+ * Creates a Receiver instance.
986
+ *
987
+ * @param {String} binaryType The type for binary data
988
+ * @param {Object} extensions An object containing the negotiated extensions
989
+ * @param {Number} maxPayload The maximum allowed message length
990
+ */
991
+ constructor(binaryType, extensions, maxPayload) {
992
+ super();
993
+ this._binaryType = binaryType || BINARY_TYPES[0];
994
+ this[kWebSocket] = void 0;
995
+ this._extensions = extensions || {};
996
+ this._maxPayload = maxPayload | 0;
997
+ this._bufferedBytes = 0;
998
+ this._buffers = [];
999
+ this._compressed = false;
1000
+ this._payloadLength = 0;
1001
+ this._mask = void 0;
1002
+ this._fragmented = 0;
1003
+ this._masked = false;
1004
+ this._fin = false;
1005
+ this._opcode = 0;
1006
+ this._totalPayloadLength = 0;
1007
+ this._messageLength = 0;
1008
+ this._fragments = [];
1009
+ this._state = GET_INFO;
1010
+ this._loop = false;
1011
+ }
1012
+ /**
1013
+ * Implements `Writable.prototype._write()`.
1014
+ *
1015
+ * @param {Buffer} chunk The chunk of data to write
1016
+ * @param {String} encoding The character encoding of `chunk`
1017
+ * @param {Function} cb Callback
1018
+ */
1019
+ _write(chunk, encoding, cb) {
1020
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
1021
+ this._bufferedBytes += chunk.length;
1022
+ this._buffers.push(chunk);
1023
+ this.startLoop(cb);
1024
+ }
1025
+ /**
1026
+ * Consumes `n` bytes from the buffered data.
1027
+ *
1028
+ * @param {Number} n The number of bytes to consume
1029
+ * @return {Buffer} The consumed bytes
1030
+ * @private
1031
+ */
1032
+ consume(n) {
1033
+ this._bufferedBytes -= n;
1034
+ if (n === this._buffers[0].length) return this._buffers.shift();
1035
+ if (n < this._buffers[0].length) {
1036
+ const buf = this._buffers[0];
1037
+ this._buffers[0] = buf.slice(n);
1038
+ return buf.slice(0, n);
1039
+ }
1040
+ const dst = Buffer.allocUnsafe(n);
1041
+ do {
1042
+ const buf = this._buffers[0];
1043
+ if (n >= buf.length) {
1044
+ this._buffers.shift().copy(dst, dst.length - n);
1045
+ } else {
1046
+ buf.copy(dst, dst.length - n, 0, n);
1047
+ this._buffers[0] = buf.slice(n);
1048
+ }
1049
+ n -= buf.length;
1050
+ } while (n > 0);
1051
+ return dst;
1052
+ }
1053
+ /**
1054
+ * Starts the parsing loop.
1055
+ *
1056
+ * @param {Function} cb Callback
1057
+ * @private
1058
+ */
1059
+ startLoop(cb) {
1060
+ var err;
1061
+ this._loop = true;
1062
+ do {
1063
+ switch (this._state) {
1064
+ case GET_INFO:
1065
+ err = this.getInfo();
1066
+ break;
1067
+ case GET_PAYLOAD_LENGTH_16:
1068
+ err = this.getPayloadLength16();
1069
+ break;
1070
+ case GET_PAYLOAD_LENGTH_64:
1071
+ err = this.getPayloadLength64();
1072
+ break;
1073
+ case GET_MASK:
1074
+ this.getMask();
1075
+ break;
1076
+ case GET_DATA:
1077
+ err = this.getData(cb);
1078
+ break;
1079
+ default:
1080
+ this._loop = false;
1081
+ return;
1082
+ }
1083
+ } while (this._loop);
1084
+ cb(err);
1085
+ }
1086
+ /**
1087
+ * Reads the first two bytes of a frame.
1088
+ *
1089
+ * @return {(RangeError|undefined)} A possible error
1090
+ * @private
1091
+ */
1092
+ getInfo() {
1093
+ if (this._bufferedBytes < 2) {
1094
+ this._loop = false;
1095
+ return;
1096
+ }
1097
+ const buf = this.consume(2);
1098
+ if ((buf[0] & 48) !== 0) {
1099
+ this._loop = false;
1100
+ return error(RangeError, "RSV2 and RSV3 must be clear", true, 1002);
1101
+ }
1102
+ const compressed = (buf[0] & 64) === 64;
1103
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
1104
+ this._loop = false;
1105
+ return error(RangeError, "RSV1 must be clear", true, 1002);
1106
+ }
1107
+ this._fin = (buf[0] & 128) === 128;
1108
+ this._opcode = buf[0] & 15;
1109
+ this._payloadLength = buf[1] & 127;
1110
+ if (this._opcode === 0) {
1111
+ if (compressed) {
1112
+ this._loop = false;
1113
+ return error(RangeError, "RSV1 must be clear", true, 1002);
1114
+ }
1115
+ if (!this._fragmented) {
1116
+ this._loop = false;
1117
+ return error(RangeError, "invalid opcode 0", true, 1002);
1118
+ }
1119
+ this._opcode = this._fragmented;
1120
+ } else if (this._opcode === 1 || this._opcode === 2) {
1121
+ if (this._fragmented) {
1122
+ this._loop = false;
1123
+ return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002);
1124
+ }
1125
+ this._compressed = compressed;
1126
+ } else if (this._opcode > 7 && this._opcode < 11) {
1127
+ if (!this._fin) {
1128
+ this._loop = false;
1129
+ return error(RangeError, "FIN must be set", true, 1002);
1130
+ }
1131
+ if (compressed) {
1132
+ this._loop = false;
1133
+ return error(RangeError, "RSV1 must be clear", true, 1002);
1134
+ }
1135
+ if (this._payloadLength > 125) {
1136
+ this._loop = false;
1137
+ return error(
1138
+ RangeError,
1139
+ `invalid payload length ${this._payloadLength}`,
1140
+ true,
1141
+ 1002
1142
+ );
1143
+ }
1144
+ } else {
1145
+ this._loop = false;
1146
+ return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002);
1147
+ }
1148
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1149
+ this._masked = (buf[1] & 128) === 128;
1150
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1151
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1152
+ else return this.haveLength();
1153
+ }
1154
+ /**
1155
+ * Gets extended payload length (7+16).
1156
+ *
1157
+ * @return {(RangeError|undefined)} A possible error
1158
+ * @private
1159
+ */
1160
+ getPayloadLength16() {
1161
+ if (this._bufferedBytes < 2) {
1162
+ this._loop = false;
1163
+ return;
1164
+ }
1165
+ this._payloadLength = this.consume(2).readUInt16BE(0);
1166
+ return this.haveLength();
1167
+ }
1168
+ /**
1169
+ * Gets extended payload length (7+64).
1170
+ *
1171
+ * @return {(RangeError|undefined)} A possible error
1172
+ * @private
1173
+ */
1174
+ getPayloadLength64() {
1175
+ if (this._bufferedBytes < 8) {
1176
+ this._loop = false;
1177
+ return;
1178
+ }
1179
+ const buf = this.consume(8);
1180
+ const num = buf.readUInt32BE(0);
1181
+ if (num > Math.pow(2, 53 - 32) - 1) {
1182
+ this._loop = false;
1183
+ return error(
1184
+ RangeError,
1185
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
1186
+ false,
1187
+ 1009
1188
+ );
1189
+ }
1190
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1191
+ return this.haveLength();
1192
+ }
1193
+ /**
1194
+ * Payload length has been read.
1195
+ *
1196
+ * @return {(RangeError|undefined)} A possible error
1197
+ * @private
1198
+ */
1199
+ haveLength() {
1200
+ if (this._payloadLength && this._opcode < 8) {
1201
+ this._totalPayloadLength += this._payloadLength;
1202
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1203
+ this._loop = false;
1204
+ return error(RangeError, "Max payload size exceeded", false, 1009);
1205
+ }
1206
+ }
1207
+ if (this._masked) this._state = GET_MASK;
1208
+ else this._state = GET_DATA;
1209
+ }
1210
+ /**
1211
+ * Reads mask bytes.
1212
+ *
1213
+ * @private
1214
+ */
1215
+ getMask() {
1216
+ if (this._bufferedBytes < 4) {
1217
+ this._loop = false;
1218
+ return;
1219
+ }
1220
+ this._mask = this.consume(4);
1221
+ this._state = GET_DATA;
1222
+ }
1223
+ /**
1224
+ * Reads data bytes.
1225
+ *
1226
+ * @param {Function} cb Callback
1227
+ * @return {(Error|RangeError|undefined)} A possible error
1228
+ * @private
1229
+ */
1230
+ getData(cb) {
1231
+ var data = EMPTY_BUFFER;
1232
+ if (this._payloadLength) {
1233
+ if (this._bufferedBytes < this._payloadLength) {
1234
+ this._loop = false;
1235
+ return;
1236
+ }
1237
+ data = this.consume(this._payloadLength);
1238
+ if (this._masked) unmask(data, this._mask);
1239
+ }
1240
+ if (this._opcode > 7) return this.controlMessage(data);
1241
+ if (this._compressed) {
1242
+ this._state = INFLATING;
1243
+ this.decompress(data, cb);
1244
+ return;
1245
+ }
1246
+ if (data.length) {
1247
+ this._messageLength = this._totalPayloadLength;
1248
+ this._fragments.push(data);
1249
+ }
1250
+ return this.dataMessage();
1251
+ }
1252
+ /**
1253
+ * Decompresses data.
1254
+ *
1255
+ * @param {Buffer} data Compressed data
1256
+ * @param {Function} cb Callback
1257
+ * @private
1258
+ */
1259
+ decompress(data, cb) {
1260
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1261
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1262
+ if (err) return cb(err);
1263
+ if (buf.length) {
1264
+ this._messageLength += buf.length;
1265
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1266
+ return cb(
1267
+ error(RangeError, "Max payload size exceeded", false, 1009)
1268
+ );
1269
+ }
1270
+ this._fragments.push(buf);
1271
+ }
1272
+ const er = this.dataMessage();
1273
+ if (er) return cb(er);
1274
+ this.startLoop(cb);
1275
+ });
1276
+ }
1277
+ /**
1278
+ * Handles a data message.
1279
+ *
1280
+ * @return {(Error|undefined)} A possible error
1281
+ * @private
1282
+ */
1283
+ dataMessage() {
1284
+ if (this._fin) {
1285
+ const messageLength = this._messageLength;
1286
+ const fragments = this._fragments;
1287
+ this._totalPayloadLength = 0;
1288
+ this._messageLength = 0;
1289
+ this._fragmented = 0;
1290
+ this._fragments = [];
1291
+ if (this._opcode === 2) {
1292
+ var data;
1293
+ if (this._binaryType === "nodebuffer") {
1294
+ data = concat(fragments, messageLength);
1295
+ } else if (this._binaryType === "arraybuffer") {
1296
+ data = toArrayBuffer(concat(fragments, messageLength));
1297
+ } else {
1298
+ data = fragments;
1299
+ }
1300
+ this.emit("message", data);
1301
+ } else {
1302
+ const buf = concat(fragments, messageLength);
1303
+ if (!isValidUTF8(buf)) {
1304
+ this._loop = false;
1305
+ return error(Error, "invalid UTF-8 sequence", true, 1007);
1306
+ }
1307
+ this.emit("message", buf.toString());
1308
+ }
1309
+ }
1310
+ this._state = GET_INFO;
1311
+ }
1312
+ /**
1313
+ * Handles a control message.
1314
+ *
1315
+ * @param {Buffer} data Data to handle
1316
+ * @return {(Error|RangeError|undefined)} A possible error
1317
+ * @private
1318
+ */
1319
+ controlMessage(data) {
1320
+ if (this._opcode === 8) {
1321
+ this._loop = false;
1322
+ if (data.length === 0) {
1323
+ this.emit("conclude", 1005, "");
1324
+ this.end();
1325
+ } else if (data.length === 1) {
1326
+ return error(RangeError, "invalid payload length 1", true, 1002);
1327
+ } else {
1328
+ const code = data.readUInt16BE(0);
1329
+ if (!isValidStatusCode(code)) {
1330
+ return error(RangeError, `invalid status code ${code}`, true, 1002);
1331
+ }
1332
+ const buf = data.slice(2);
1333
+ if (!isValidUTF8(buf)) {
1334
+ return error(Error, "invalid UTF-8 sequence", true, 1007);
1335
+ }
1336
+ this.emit("conclude", code, buf.toString());
1337
+ this.end();
1338
+ }
1339
+ } else if (this._opcode === 9) {
1340
+ this.emit("ping", data);
1341
+ } else {
1342
+ this.emit("pong", data);
1343
+ }
1344
+ this._state = GET_INFO;
1345
+ }
1346
+ };
1347
+ module.exports = Receiver;
1348
+ function error(ErrorCtor, message, prefix, statusCode) {
1349
+ const err = new ErrorCtor(
1350
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1351
+ );
1352
+ Error.captureStackTrace(err, error);
1353
+ err[kStatusCode] = statusCode;
1354
+ return err;
1355
+ }
1356
+ }
1357
+ });
1358
+
1359
+ // ../../node_modules/ws/lib/sender.js
1360
+ var require_sender = __commonJS({
1361
+ "../../node_modules/ws/lib/sender.js"(exports, module) {
1362
+ var { randomBytes } = __require("crypto");
1363
+ var PerMessageDeflate = require_permessage_deflate();
1364
+ var { EMPTY_BUFFER } = require_constants();
1365
+ var { isValidStatusCode } = require_validation();
1366
+ var { mask: applyMask, toBuffer } = require_buffer_util();
1367
+ var Sender = class _Sender {
1368
+ /**
1369
+ * Creates a Sender instance.
1370
+ *
1371
+ * @param {net.Socket} socket The connection socket
1372
+ * @param {Object} extensions An object containing the negotiated extensions
1373
+ */
1374
+ constructor(socket, extensions) {
1375
+ this._extensions = extensions || {};
1376
+ this._socket = socket;
1377
+ this._firstFragment = true;
1378
+ this._compress = false;
1379
+ this._bufferedBytes = 0;
1380
+ this._deflating = false;
1381
+ this._queue = [];
1382
+ }
1383
+ /**
1384
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1385
+ *
1386
+ * @param {Buffer} data The data to frame
1387
+ * @param {Object} options Options object
1388
+ * @param {Number} options.opcode The opcode
1389
+ * @param {Boolean} options.readOnly Specifies whether `data` can be modified
1390
+ * @param {Boolean} options.fin Specifies whether or not to set the FIN bit
1391
+ * @param {Boolean} options.mask Specifies whether or not to mask `data`
1392
+ * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit
1393
+ * @return {Buffer[]} The framed data as a list of `Buffer` instances
1394
+ * @public
1395
+ */
1396
+ static frame(data, options) {
1397
+ const merge = options.mask && options.readOnly;
1398
+ var offset = options.mask ? 6 : 2;
1399
+ var payloadLength = data.length;
1400
+ if (data.length >= 65536) {
1401
+ offset += 8;
1402
+ payloadLength = 127;
1403
+ } else if (data.length > 125) {
1404
+ offset += 2;
1405
+ payloadLength = 126;
1406
+ }
1407
+ const target = Buffer.allocUnsafe(merge ? data.length + offset : offset);
1408
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1409
+ if (options.rsv1) target[0] |= 64;
1410
+ target[1] = payloadLength;
1411
+ if (payloadLength === 126) {
1412
+ target.writeUInt16BE(data.length, 2);
1413
+ } else if (payloadLength === 127) {
1414
+ target.writeUInt32BE(0, 2);
1415
+ target.writeUInt32BE(data.length, 6);
1416
+ }
1417
+ if (!options.mask) return [target, data];
1418
+ const mask = randomBytes(4);
1419
+ target[1] |= 128;
1420
+ target[offset - 4] = mask[0];
1421
+ target[offset - 3] = mask[1];
1422
+ target[offset - 2] = mask[2];
1423
+ target[offset - 1] = mask[3];
1424
+ if (merge) {
1425
+ applyMask(data, mask, target, offset, data.length);
1426
+ return [target];
1427
+ }
1428
+ applyMask(data, mask, data, 0, data.length);
1429
+ return [target, data];
1430
+ }
1431
+ /**
1432
+ * Sends a close message to the other peer.
1433
+ *
1434
+ * @param {(Number|undefined)} code The status code component of the body
1435
+ * @param {String} data The message component of the body
1436
+ * @param {Boolean} mask Specifies whether or not to mask the message
1437
+ * @param {Function} cb Callback
1438
+ * @public
1439
+ */
1440
+ close(code, data, mask, cb) {
1441
+ var buf;
1442
+ if (code === void 0) {
1443
+ buf = EMPTY_BUFFER;
1444
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1445
+ throw new TypeError("First argument must be a valid error code number");
1446
+ } else if (data === void 0 || data === "") {
1447
+ buf = Buffer.allocUnsafe(2);
1448
+ buf.writeUInt16BE(code, 0);
1449
+ } else {
1450
+ buf = Buffer.allocUnsafe(2 + Buffer.byteLength(data));
1451
+ buf.writeUInt16BE(code, 0);
1452
+ buf.write(data, 2);
1453
+ }
1454
+ if (this._deflating) {
1455
+ this.enqueue([this.doClose, buf, mask, cb]);
1456
+ } else {
1457
+ this.doClose(buf, mask, cb);
1458
+ }
1459
+ }
1460
+ /**
1461
+ * Frames and sends a close message.
1462
+ *
1463
+ * @param {Buffer} data The message to send
1464
+ * @param {Boolean} mask Specifies whether or not to mask `data`
1465
+ * @param {Function} cb Callback
1466
+ * @private
1467
+ */
1468
+ doClose(data, mask, cb) {
1469
+ this.sendFrame(
1470
+ _Sender.frame(data, {
1471
+ fin: true,
1472
+ rsv1: false,
1473
+ opcode: 8,
1474
+ mask,
1475
+ readOnly: false
1476
+ }),
1477
+ cb
1478
+ );
1479
+ }
1480
+ /**
1481
+ * Sends a ping message to the other peer.
1482
+ *
1483
+ * @param {*} data The message to send
1484
+ * @param {Boolean} mask Specifies whether or not to mask `data`
1485
+ * @param {Function} cb Callback
1486
+ * @public
1487
+ */
1488
+ ping(data, mask, cb) {
1489
+ const buf = toBuffer(data);
1490
+ if (this._deflating) {
1491
+ this.enqueue([this.doPing, buf, mask, toBuffer.readOnly, cb]);
1492
+ } else {
1493
+ this.doPing(buf, mask, toBuffer.readOnly, cb);
1494
+ }
1495
+ }
1496
+ /**
1497
+ * Frames and sends a ping message.
1498
+ *
1499
+ * @param {*} data The message to send
1500
+ * @param {Boolean} mask Specifies whether or not to mask `data`
1501
+ * @param {Boolean} readOnly Specifies whether `data` can be modified
1502
+ * @param {Function} cb Callback
1503
+ * @private
1504
+ */
1505
+ doPing(data, mask, readOnly, cb) {
1506
+ this.sendFrame(
1507
+ _Sender.frame(data, {
1508
+ fin: true,
1509
+ rsv1: false,
1510
+ opcode: 9,
1511
+ mask,
1512
+ readOnly
1513
+ }),
1514
+ cb
1515
+ );
1516
+ }
1517
+ /**
1518
+ * Sends a pong message to the other peer.
1519
+ *
1520
+ * @param {*} data The message to send
1521
+ * @param {Boolean} mask Specifies whether or not to mask `data`
1522
+ * @param {Function} cb Callback
1523
+ * @public
1524
+ */
1525
+ pong(data, mask, cb) {
1526
+ const buf = toBuffer(data);
1527
+ if (this._deflating) {
1528
+ this.enqueue([this.doPong, buf, mask, toBuffer.readOnly, cb]);
1529
+ } else {
1530
+ this.doPong(buf, mask, toBuffer.readOnly, cb);
1531
+ }
1532
+ }
1533
+ /**
1534
+ * Frames and sends a pong message.
1535
+ *
1536
+ * @param {*} data The message to send
1537
+ * @param {Boolean} mask Specifies whether or not to mask `data`
1538
+ * @param {Boolean} readOnly Specifies whether `data` can be modified
1539
+ * @param {Function} cb Callback
1540
+ * @private
1541
+ */
1542
+ doPong(data, mask, readOnly, cb) {
1543
+ this.sendFrame(
1544
+ _Sender.frame(data, {
1545
+ fin: true,
1546
+ rsv1: false,
1547
+ opcode: 10,
1548
+ mask,
1549
+ readOnly
1550
+ }),
1551
+ cb
1552
+ );
1553
+ }
1554
+ /**
1555
+ * Sends a data message to the other peer.
1556
+ *
1557
+ * @param {*} data The message to send
1558
+ * @param {Object} options Options object
1559
+ * @param {Boolean} options.compress Specifies whether or not to compress `data`
1560
+ * @param {Boolean} options.binary Specifies whether `data` is binary or text
1561
+ * @param {Boolean} options.fin Specifies whether the fragment is the last one
1562
+ * @param {Boolean} options.mask Specifies whether or not to mask `data`
1563
+ * @param {Function} cb Callback
1564
+ * @public
1565
+ */
1566
+ send(data, options, cb) {
1567
+ const buf = toBuffer(data);
1568
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1569
+ var opcode = options.binary ? 2 : 1;
1570
+ var rsv1 = options.compress;
1571
+ if (this._firstFragment) {
1572
+ this._firstFragment = false;
1573
+ if (rsv1 && perMessageDeflate) {
1574
+ rsv1 = buf.length >= perMessageDeflate._threshold;
1575
+ }
1576
+ this._compress = rsv1;
1577
+ } else {
1578
+ rsv1 = false;
1579
+ opcode = 0;
1580
+ }
1581
+ if (options.fin) this._firstFragment = true;
1582
+ if (perMessageDeflate) {
1583
+ const opts = {
1584
+ fin: options.fin,
1585
+ rsv1,
1586
+ opcode,
1587
+ mask: options.mask,
1588
+ readOnly: toBuffer.readOnly
1589
+ };
1590
+ if (this._deflating) {
1591
+ this.enqueue([this.dispatch, buf, this._compress, opts, cb]);
1592
+ } else {
1593
+ this.dispatch(buf, this._compress, opts, cb);
1594
+ }
1595
+ } else {
1596
+ this.sendFrame(
1597
+ _Sender.frame(buf, {
1598
+ fin: options.fin,
1599
+ rsv1: false,
1600
+ opcode,
1601
+ mask: options.mask,
1602
+ readOnly: toBuffer.readOnly
1603
+ }),
1604
+ cb
1605
+ );
1606
+ }
1607
+ }
1608
+ /**
1609
+ * Dispatches a data message.
1610
+ *
1611
+ * @param {Buffer} data The message to send
1612
+ * @param {Boolean} compress Specifies whether or not to compress `data`
1613
+ * @param {Object} options Options object
1614
+ * @param {Number} options.opcode The opcode
1615
+ * @param {Boolean} options.readOnly Specifies whether `data` can be modified
1616
+ * @param {Boolean} options.fin Specifies whether or not to set the FIN bit
1617
+ * @param {Boolean} options.mask Specifies whether or not to mask `data`
1618
+ * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit
1619
+ * @param {Function} cb Callback
1620
+ * @private
1621
+ */
1622
+ dispatch(data, compress, options, cb) {
1623
+ if (!compress) {
1624
+ this.sendFrame(_Sender.frame(data, options), cb);
1625
+ return;
1626
+ }
1627
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1628
+ this._deflating = true;
1629
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1630
+ this._deflating = false;
1631
+ options.readOnly = false;
1632
+ this.sendFrame(_Sender.frame(buf, options), cb);
1633
+ this.dequeue();
1634
+ });
1635
+ }
1636
+ /**
1637
+ * Executes queued send operations.
1638
+ *
1639
+ * @private
1640
+ */
1641
+ dequeue() {
1642
+ while (!this._deflating && this._queue.length) {
1643
+ const params = this._queue.shift();
1644
+ this._bufferedBytes -= params[1].length;
1645
+ params[0].apply(this, params.slice(1));
1646
+ }
1647
+ }
1648
+ /**
1649
+ * Enqueues a send operation.
1650
+ *
1651
+ * @param {Array} params Send operation parameters.
1652
+ * @private
1653
+ */
1654
+ enqueue(params) {
1655
+ this._bufferedBytes += params[1].length;
1656
+ this._queue.push(params);
1657
+ }
1658
+ /**
1659
+ * Sends a frame.
1660
+ *
1661
+ * @param {Buffer[]} list The frame to send
1662
+ * @param {Function} cb Callback
1663
+ * @private
1664
+ */
1665
+ sendFrame(list, cb) {
1666
+ if (list.length === 2) {
1667
+ this._socket.cork();
1668
+ this._socket.write(list[0]);
1669
+ this._socket.write(list[1], cb);
1670
+ this._socket.uncork();
1671
+ } else {
1672
+ this._socket.write(list[0], cb);
1673
+ }
1674
+ }
1675
+ };
1676
+ module.exports = Sender;
1677
+ }
1678
+ });
1679
+
1680
+ // ../../node_modules/ws/lib/websocket.js
1681
+ var require_websocket = __commonJS({
1682
+ "../../node_modules/ws/lib/websocket.js"(exports, module) {
1683
+ var EventEmitter = __require("events");
1684
+ var crypto2 = __require("crypto");
1685
+ var https = __require("https");
1686
+ var http = __require("http");
1687
+ var net = __require("net");
1688
+ var tls = __require("tls");
1689
+ var url = __require("url");
1690
+ var PerMessageDeflate = require_permessage_deflate();
1691
+ var EventTarget = require_event_target();
1692
+ var extension = require_extension();
1693
+ var Receiver = require_receiver();
1694
+ var Sender = require_sender();
1695
+ var {
1696
+ BINARY_TYPES,
1697
+ EMPTY_BUFFER,
1698
+ GUID,
1699
+ kStatusCode,
1700
+ kWebSocket,
1701
+ NOOP
1702
+ } = require_constants();
1703
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
1704
+ var protocolVersions = [8, 13];
1705
+ var closeTimeout = 30 * 1e3;
1706
+ var WebSocket2 = class _WebSocket extends EventEmitter {
1707
+ /**
1708
+ * Create a new `WebSocket`.
1709
+ *
1710
+ * @param {(String|url.Url|url.URL)} address The URL to which to connect
1711
+ * @param {(String|String[])} protocols The subprotocols
1712
+ * @param {Object} options Connection options
1713
+ */
1714
+ constructor(address, protocols, options) {
1715
+ super();
1716
+ this.readyState = _WebSocket.CONNECTING;
1717
+ this.protocol = "";
1718
+ this._binaryType = BINARY_TYPES[0];
1719
+ this._closeFrameReceived = false;
1720
+ this._closeFrameSent = false;
1721
+ this._closeMessage = "";
1722
+ this._closeTimer = null;
1723
+ this._closeCode = 1006;
1724
+ this._extensions = {};
1725
+ this._receiver = null;
1726
+ this._sender = null;
1727
+ this._socket = null;
1728
+ if (address !== null) {
1729
+ this._isServer = false;
1730
+ this._redirects = 0;
1731
+ if (Array.isArray(protocols)) {
1732
+ protocols = protocols.join(", ");
1733
+ } else if (typeof protocols === "object" && protocols !== null) {
1734
+ options = protocols;
1735
+ protocols = void 0;
1736
+ }
1737
+ initAsClient(this, address, protocols, options);
1738
+ } else {
1739
+ this._isServer = true;
1740
+ }
1741
+ }
1742
+ get CONNECTING() {
1743
+ return _WebSocket.CONNECTING;
1744
+ }
1745
+ get CLOSING() {
1746
+ return _WebSocket.CLOSING;
1747
+ }
1748
+ get CLOSED() {
1749
+ return _WebSocket.CLOSED;
1750
+ }
1751
+ get OPEN() {
1752
+ return _WebSocket.OPEN;
1753
+ }
1754
+ /**
1755
+ * This deviates from the WHATWG interface since ws doesn't support the
1756
+ * required default "blob" type (instead we define a custom "nodebuffer"
1757
+ * type).
1758
+ *
1759
+ * @type {String}
1760
+ */
1761
+ get binaryType() {
1762
+ return this._binaryType;
1763
+ }
1764
+ set binaryType(type) {
1765
+ if (!BINARY_TYPES.includes(type)) return;
1766
+ this._binaryType = type;
1767
+ if (this._receiver) this._receiver._binaryType = type;
1768
+ }
1769
+ /**
1770
+ * @type {Number}
1771
+ */
1772
+ get bufferedAmount() {
1773
+ if (!this._socket) return 0;
1774
+ return (this._socket.bufferSize || 0) + this._sender._bufferedBytes;
1775
+ }
1776
+ /**
1777
+ * @type {String}
1778
+ */
1779
+ get extensions() {
1780
+ return Object.keys(this._extensions).join();
1781
+ }
1782
+ /**
1783
+ * Set up the socket and the internal resources.
1784
+ *
1785
+ * @param {net.Socket} socket The network socket between the server and client
1786
+ * @param {Buffer} head The first packet of the upgraded stream
1787
+ * @param {Number} maxPayload The maximum allowed message size
1788
+ * @private
1789
+ */
1790
+ setSocket(socket, head, maxPayload) {
1791
+ const receiver = new Receiver(
1792
+ this._binaryType,
1793
+ this._extensions,
1794
+ maxPayload
1795
+ );
1796
+ this._sender = new Sender(socket, this._extensions);
1797
+ this._receiver = receiver;
1798
+ this._socket = socket;
1799
+ receiver[kWebSocket] = this;
1800
+ socket[kWebSocket] = this;
1801
+ receiver.on("conclude", receiverOnConclude);
1802
+ receiver.on("drain", receiverOnDrain);
1803
+ receiver.on("error", receiverOnError);
1804
+ receiver.on("message", receiverOnMessage);
1805
+ receiver.on("ping", receiverOnPing);
1806
+ receiver.on("pong", receiverOnPong);
1807
+ socket.setTimeout(0);
1808
+ socket.setNoDelay();
1809
+ if (head.length > 0) socket.unshift(head);
1810
+ socket.on("close", socketOnClose);
1811
+ socket.on("data", socketOnData);
1812
+ socket.on("end", socketOnEnd);
1813
+ socket.on("error", socketOnError);
1814
+ this.readyState = _WebSocket.OPEN;
1815
+ this.emit("open");
1816
+ }
1817
+ /**
1818
+ * Emit the `'close'` event.
1819
+ *
1820
+ * @private
1821
+ */
1822
+ emitClose() {
1823
+ this.readyState = _WebSocket.CLOSED;
1824
+ if (!this._socket) {
1825
+ this.emit("close", this._closeCode, this._closeMessage);
1826
+ return;
1827
+ }
1828
+ if (this._extensions[PerMessageDeflate.extensionName]) {
1829
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
1830
+ }
1831
+ this._receiver.removeAllListeners();
1832
+ this.emit("close", this._closeCode, this._closeMessage);
1833
+ }
1834
+ /**
1835
+ * Start a closing handshake.
1836
+ *
1837
+ * +----------+ +-----------+ +----------+
1838
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
1839
+ * | +----------+ +-----------+ +----------+ |
1840
+ * +----------+ +-----------+ |
1841
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
1842
+ * +----------+ +-----------+ |
1843
+ * | | | +---+ |
1844
+ * +------------------------+-->|fin| - - - -
1845
+ * | +---+ | +---+
1846
+ * - - - - -|fin|<---------------------+
1847
+ * +---+
1848
+ *
1849
+ * @param {Number} code Status code explaining why the connection is closing
1850
+ * @param {String} data A string explaining why the connection is closing
1851
+ * @public
1852
+ */
1853
+ close(code, data) {
1854
+ if (this.readyState === _WebSocket.CLOSED) return;
1855
+ if (this.readyState === _WebSocket.CONNECTING) {
1856
+ const msg = "WebSocket was closed before the connection was established";
1857
+ return abortHandshake(this, this._req, msg);
1858
+ }
1859
+ if (this.readyState === _WebSocket.CLOSING) {
1860
+ if (this._closeFrameSent && this._closeFrameReceived) this._socket.end();
1861
+ return;
1862
+ }
1863
+ this.readyState = _WebSocket.CLOSING;
1864
+ this._sender.close(code, data, !this._isServer, (err) => {
1865
+ if (err) return;
1866
+ this._closeFrameSent = true;
1867
+ if (this._closeFrameReceived) this._socket.end();
1868
+ });
1869
+ this._closeTimer = setTimeout(
1870
+ this._socket.destroy.bind(this._socket),
1871
+ closeTimeout
1872
+ );
1873
+ }
1874
+ /**
1875
+ * Send a ping.
1876
+ *
1877
+ * @param {*} data The data to send
1878
+ * @param {Boolean} mask Indicates whether or not to mask `data`
1879
+ * @param {Function} cb Callback which is executed when the ping is sent
1880
+ * @public
1881
+ */
1882
+ ping(data, mask, cb) {
1883
+ if (typeof data === "function") {
1884
+ cb = data;
1885
+ data = mask = void 0;
1886
+ } else if (typeof mask === "function") {
1887
+ cb = mask;
1888
+ mask = void 0;
1889
+ }
1890
+ if (this.readyState !== _WebSocket.OPEN) {
1891
+ const err = new Error(
1892
+ `WebSocket is not open: readyState ${this.readyState} (${readyStates[this.readyState]})`
1893
+ );
1894
+ if (cb) return cb(err);
1895
+ throw err;
1896
+ }
1897
+ if (typeof data === "number") data = data.toString();
1898
+ if (mask === void 0) mask = !this._isServer;
1899
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
1900
+ }
1901
+ /**
1902
+ * Send a pong.
1903
+ *
1904
+ * @param {*} data The data to send
1905
+ * @param {Boolean} mask Indicates whether or not to mask `data`
1906
+ * @param {Function} cb Callback which is executed when the pong is sent
1907
+ * @public
1908
+ */
1909
+ pong(data, mask, cb) {
1910
+ if (typeof data === "function") {
1911
+ cb = data;
1912
+ data = mask = void 0;
1913
+ } else if (typeof mask === "function") {
1914
+ cb = mask;
1915
+ mask = void 0;
1916
+ }
1917
+ if (this.readyState !== _WebSocket.OPEN) {
1918
+ const err = new Error(
1919
+ `WebSocket is not open: readyState ${this.readyState} (${readyStates[this.readyState]})`
1920
+ );
1921
+ if (cb) return cb(err);
1922
+ throw err;
1923
+ }
1924
+ if (typeof data === "number") data = data.toString();
1925
+ if (mask === void 0) mask = !this._isServer;
1926
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
1927
+ }
1928
+ /**
1929
+ * Send a data message.
1930
+ *
1931
+ * @param {*} data The message to send
1932
+ * @param {Object} options Options object
1933
+ * @param {Boolean} options.compress Specifies whether or not to compress `data`
1934
+ * @param {Boolean} options.binary Specifies whether `data` is binary or text
1935
+ * @param {Boolean} options.fin Specifies whether the fragment is the last one
1936
+ * @param {Boolean} options.mask Specifies whether or not to mask `data`
1937
+ * @param {Function} cb Callback which is executed when data is written out
1938
+ * @public
1939
+ */
1940
+ send(data, options, cb) {
1941
+ if (typeof options === "function") {
1942
+ cb = options;
1943
+ options = {};
1944
+ }
1945
+ if (this.readyState !== _WebSocket.OPEN) {
1946
+ const err = new Error(
1947
+ `WebSocket is not open: readyState ${this.readyState} (${readyStates[this.readyState]})`
1948
+ );
1949
+ if (cb) return cb(err);
1950
+ throw err;
1951
+ }
1952
+ if (typeof data === "number") data = data.toString();
1953
+ const opts = Object.assign(
1954
+ {
1955
+ binary: typeof data !== "string",
1956
+ mask: !this._isServer,
1957
+ compress: true,
1958
+ fin: true
1959
+ },
1960
+ options
1961
+ );
1962
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
1963
+ opts.compress = false;
1964
+ }
1965
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
1966
+ }
1967
+ /**
1968
+ * Forcibly close the connection.
1969
+ *
1970
+ * @public
1971
+ */
1972
+ terminate() {
1973
+ if (this.readyState === _WebSocket.CLOSED) return;
1974
+ if (this.readyState === _WebSocket.CONNECTING) {
1975
+ const msg = "WebSocket was closed before the connection was established";
1976
+ return abortHandshake(this, this._req, msg);
1977
+ }
1978
+ if (this._socket) {
1979
+ this.readyState = _WebSocket.CLOSING;
1980
+ this._socket.destroy();
1981
+ }
1982
+ }
1983
+ };
1984
+ readyStates.forEach((readyState, i) => {
1985
+ WebSocket2[readyState] = i;
1986
+ });
1987
+ ["open", "error", "close", "message"].forEach((method) => {
1988
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
1989
+ /**
1990
+ * Return the listener of the event.
1991
+ *
1992
+ * @return {(Function|undefined)} The event listener or `undefined`
1993
+ * @public
1994
+ */
1995
+ get() {
1996
+ const listeners = this.listeners(method);
1997
+ for (var i = 0; i < listeners.length; i++) {
1998
+ if (listeners[i]._listener) return listeners[i]._listener;
1999
+ }
2000
+ return void 0;
2001
+ },
2002
+ /**
2003
+ * Add a listener for the event.
2004
+ *
2005
+ * @param {Function} listener The listener to add
2006
+ * @public
2007
+ */
2008
+ set(listener) {
2009
+ const listeners = this.listeners(method);
2010
+ for (var i = 0; i < listeners.length; i++) {
2011
+ if (listeners[i]._listener) this.removeListener(method, listeners[i]);
2012
+ }
2013
+ this.addEventListener(method, listener);
2014
+ }
2015
+ });
2016
+ });
2017
+ WebSocket2.prototype.addEventListener = EventTarget.addEventListener;
2018
+ WebSocket2.prototype.removeEventListener = EventTarget.removeEventListener;
2019
+ module.exports = WebSocket2;
2020
+ function initAsClient(websocket, address, protocols, options) {
2021
+ const opts = Object.assign(
2022
+ {
2023
+ protocolVersion: protocolVersions[1],
2024
+ maxPayload: 100 * 1024 * 1024,
2025
+ perMessageDeflate: true,
2026
+ followRedirects: false,
2027
+ maxRedirects: 10
2028
+ },
2029
+ options,
2030
+ {
2031
+ createConnection: void 0,
2032
+ socketPath: void 0,
2033
+ hostname: void 0,
2034
+ protocol: void 0,
2035
+ timeout: void 0,
2036
+ method: void 0,
2037
+ auth: void 0,
2038
+ host: void 0,
2039
+ path: void 0,
2040
+ port: void 0
2041
+ }
2042
+ );
2043
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2044
+ throw new RangeError(
2045
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2046
+ );
2047
+ }
2048
+ var parsedUrl;
2049
+ if (typeof address === "object" && address.href !== void 0) {
2050
+ parsedUrl = address;
2051
+ websocket.url = address.href;
2052
+ } else {
2053
+ parsedUrl = url.URL ? new url.URL(address) : url.parse(address);
2054
+ websocket.url = address;
2055
+ }
2056
+ const isUnixSocket = parsedUrl.protocol === "ws+unix:";
2057
+ if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) {
2058
+ throw new Error(`Invalid URL: ${websocket.url}`);
2059
+ }
2060
+ const isSecure = parsedUrl.protocol === "wss:" || parsedUrl.protocol === "https:";
2061
+ const defaultPort = isSecure ? 443 : 80;
2062
+ const key = crypto2.randomBytes(16).toString("base64");
2063
+ const get = isSecure ? https.get : http.get;
2064
+ const path = parsedUrl.search ? `${parsedUrl.pathname || "/"}${parsedUrl.search}` : parsedUrl.pathname || "/";
2065
+ var perMessageDeflate;
2066
+ opts.createConnection = isSecure ? tlsConnect : netConnect;
2067
+ opts.defaultPort = opts.defaultPort || defaultPort;
2068
+ opts.port = parsedUrl.port || defaultPort;
2069
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2070
+ opts.headers = Object.assign(
2071
+ {
2072
+ "Sec-WebSocket-Version": opts.protocolVersion,
2073
+ "Sec-WebSocket-Key": key,
2074
+ Connection: "Upgrade",
2075
+ Upgrade: "websocket"
2076
+ },
2077
+ opts.headers
2078
+ );
2079
+ opts.path = path;
2080
+ opts.timeout = opts.handshakeTimeout;
2081
+ if (opts.perMessageDeflate) {
2082
+ perMessageDeflate = new PerMessageDeflate(
2083
+ opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
2084
+ false,
2085
+ opts.maxPayload
2086
+ );
2087
+ opts.headers["Sec-WebSocket-Extensions"] = extension.format({
2088
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
2089
+ });
2090
+ }
2091
+ if (protocols) {
2092
+ opts.headers["Sec-WebSocket-Protocol"] = protocols;
2093
+ }
2094
+ if (opts.origin) {
2095
+ if (opts.protocolVersion < 13) {
2096
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2097
+ } else {
2098
+ opts.headers.Origin = opts.origin;
2099
+ }
2100
+ }
2101
+ if (parsedUrl.auth) {
2102
+ opts.auth = parsedUrl.auth;
2103
+ } else if (parsedUrl.username || parsedUrl.password) {
2104
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2105
+ }
2106
+ if (isUnixSocket) {
2107
+ const parts = path.split(":");
2108
+ opts.socketPath = parts[0];
2109
+ opts.path = parts[1];
2110
+ }
2111
+ var req = websocket._req = get(opts);
2112
+ if (opts.timeout) {
2113
+ req.on("timeout", () => {
2114
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2115
+ });
2116
+ }
2117
+ req.on("error", (err) => {
2118
+ if (websocket._req.aborted) return;
2119
+ req = websocket._req = null;
2120
+ websocket.readyState = WebSocket2.CLOSING;
2121
+ websocket.emit("error", err);
2122
+ websocket.emitClose();
2123
+ });
2124
+ req.on("response", (res) => {
2125
+ const location = res.headers.location;
2126
+ const statusCode = res.statusCode;
2127
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2128
+ if (++websocket._redirects > opts.maxRedirects) {
2129
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2130
+ return;
2131
+ }
2132
+ req.abort();
2133
+ const addr = url.URL ? new url.URL(location, address) : url.resolve(address, location);
2134
+ initAsClient(websocket, addr, protocols, options);
2135
+ } else if (!websocket.emit("unexpected-response", req, res)) {
2136
+ abortHandshake(
2137
+ websocket,
2138
+ req,
2139
+ `Unexpected server response: ${res.statusCode}`
2140
+ );
2141
+ }
2142
+ });
2143
+ req.on("upgrade", (res, socket, head) => {
2144
+ websocket.emit("upgrade", res);
2145
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
2146
+ req = websocket._req = null;
2147
+ const digest = crypto2.createHash("sha1").update(key + GUID).digest("base64");
2148
+ if (res.headers["sec-websocket-accept"] !== digest) {
2149
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2150
+ return;
2151
+ }
2152
+ const serverProt = res.headers["sec-websocket-protocol"];
2153
+ const protList = (protocols || "").split(/, */);
2154
+ var protError;
2155
+ if (!protocols && serverProt) {
2156
+ protError = "Server sent a subprotocol but none was requested";
2157
+ } else if (protocols && !serverProt) {
2158
+ protError = "Server sent no subprotocol";
2159
+ } else if (serverProt && !protList.includes(serverProt)) {
2160
+ protError = "Server sent an invalid subprotocol";
2161
+ }
2162
+ if (protError) {
2163
+ abortHandshake(websocket, socket, protError);
2164
+ return;
2165
+ }
2166
+ if (serverProt) websocket.protocol = serverProt;
2167
+ if (perMessageDeflate) {
2168
+ try {
2169
+ const extensions = extension.parse(
2170
+ res.headers["sec-websocket-extensions"]
2171
+ );
2172
+ if (extensions[PerMessageDeflate.extensionName]) {
2173
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2174
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2175
+ }
2176
+ } catch (err) {
2177
+ abortHandshake(
2178
+ websocket,
2179
+ socket,
2180
+ "Invalid Sec-WebSocket-Extensions header"
2181
+ );
2182
+ return;
2183
+ }
2184
+ }
2185
+ websocket.setSocket(socket, head, opts.maxPayload);
2186
+ });
2187
+ }
2188
+ function netConnect(options) {
2189
+ if (options.protocolVersion) options.path = options.socketPath;
2190
+ return net.connect(options);
2191
+ }
2192
+ function tlsConnect(options) {
2193
+ options.path = void 0;
2194
+ options.servername = options.servername || options.host;
2195
+ return tls.connect(options);
2196
+ }
2197
+ function abortHandshake(websocket, stream, message) {
2198
+ websocket.readyState = WebSocket2.CLOSING;
2199
+ const err = new Error(message);
2200
+ Error.captureStackTrace(err, abortHandshake);
2201
+ if (stream.setHeader) {
2202
+ stream.abort();
2203
+ stream.once("abort", websocket.emitClose.bind(websocket));
2204
+ websocket.emit("error", err);
2205
+ } else {
2206
+ stream.destroy(err);
2207
+ stream.once("error", websocket.emit.bind(websocket, "error"));
2208
+ stream.once("close", websocket.emitClose.bind(websocket));
2209
+ }
2210
+ }
2211
+ function receiverOnConclude(code, reason) {
2212
+ const websocket = this[kWebSocket];
2213
+ websocket._socket.removeListener("data", socketOnData);
2214
+ websocket._socket.resume();
2215
+ websocket._closeFrameReceived = true;
2216
+ websocket._closeMessage = reason;
2217
+ websocket._closeCode = code;
2218
+ if (code === 1005) websocket.close();
2219
+ else websocket.close(code, reason);
2220
+ }
2221
+ function receiverOnDrain() {
2222
+ this[kWebSocket]._socket.resume();
2223
+ }
2224
+ function receiverOnError(err) {
2225
+ const websocket = this[kWebSocket];
2226
+ websocket._socket.removeListener("data", socketOnData);
2227
+ websocket.readyState = WebSocket2.CLOSING;
2228
+ websocket._closeCode = err[kStatusCode];
2229
+ websocket.emit("error", err);
2230
+ websocket._socket.destroy();
2231
+ }
2232
+ function receiverOnFinish() {
2233
+ this[kWebSocket].emitClose();
2234
+ }
2235
+ function receiverOnMessage(data) {
2236
+ this[kWebSocket].emit("message", data);
2237
+ }
2238
+ function receiverOnPing(data) {
2239
+ const websocket = this[kWebSocket];
2240
+ websocket.pong(data, !websocket._isServer, NOOP);
2241
+ websocket.emit("ping", data);
2242
+ }
2243
+ function receiverOnPong(data) {
2244
+ this[kWebSocket].emit("pong", data);
2245
+ }
2246
+ function socketOnClose() {
2247
+ const websocket = this[kWebSocket];
2248
+ this.removeListener("close", socketOnClose);
2249
+ this.removeListener("end", socketOnEnd);
2250
+ websocket.readyState = WebSocket2.CLOSING;
2251
+ websocket._socket.read();
2252
+ websocket._receiver.end();
2253
+ this.removeListener("data", socketOnData);
2254
+ this[kWebSocket] = void 0;
2255
+ clearTimeout(websocket._closeTimer);
2256
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
2257
+ websocket.emitClose();
2258
+ } else {
2259
+ websocket._receiver.on("error", receiverOnFinish);
2260
+ websocket._receiver.on("finish", receiverOnFinish);
2261
+ }
2262
+ }
2263
+ function socketOnData(chunk) {
2264
+ if (!this[kWebSocket]._receiver.write(chunk)) {
2265
+ this.pause();
2266
+ }
2267
+ }
2268
+ function socketOnEnd() {
2269
+ const websocket = this[kWebSocket];
2270
+ websocket.readyState = WebSocket2.CLOSING;
2271
+ websocket._receiver.end();
2272
+ this.end();
2273
+ }
2274
+ function socketOnError() {
2275
+ const websocket = this[kWebSocket];
2276
+ this.removeListener("error", socketOnError);
2277
+ this.on("error", NOOP);
2278
+ websocket.readyState = WebSocket2.CLOSING;
2279
+ this.destroy();
2280
+ }
2281
+ }
2282
+ });
2283
+
2284
+ // ../../node_modules/ws/lib/websocket-server.js
2285
+ var require_websocket_server = __commonJS({
2286
+ "../../node_modules/ws/lib/websocket-server.js"(exports, module) {
2287
+ var EventEmitter = __require("events");
2288
+ var crypto2 = __require("crypto");
2289
+ var http = __require("http");
2290
+ var PerMessageDeflate = require_permessage_deflate();
2291
+ var extension = require_extension();
2292
+ var WebSocket2 = require_websocket();
2293
+ var { GUID } = require_constants();
2294
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
2295
+ var WebSocketServer = class extends EventEmitter {
2296
+ /**
2297
+ * Create a `WebSocketServer` instance.
2298
+ *
2299
+ * @param {Object} options Configuration options
2300
+ * @param {Number} options.backlog The maximum length of the queue of pending
2301
+ * connections
2302
+ * @param {Boolean} options.clientTracking Specifies whether or not to track
2303
+ * clients
2304
+ * @param {Function} options.handleProtocols An hook to handle protocols
2305
+ * @param {String} options.host The hostname where to bind the server
2306
+ * @param {Number} options.maxPayload The maximum allowed message size
2307
+ * @param {Boolean} options.noServer Enable no server mode
2308
+ * @param {String} options.path Accept only connections matching this path
2309
+ * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable
2310
+ * permessage-deflate
2311
+ * @param {Number} options.port The port where to bind the server
2312
+ * @param {http.Server} options.server A pre-created HTTP/S server to use
2313
+ * @param {Function} options.verifyClient An hook to reject connections
2314
+ * @param {Function} callback A listener for the `listening` event
2315
+ */
2316
+ constructor(options, callback) {
2317
+ super();
2318
+ options = Object.assign(
2319
+ {
2320
+ maxPayload: 100 * 1024 * 1024,
2321
+ perMessageDeflate: false,
2322
+ handleProtocols: null,
2323
+ clientTracking: true,
2324
+ verifyClient: null,
2325
+ noServer: false,
2326
+ backlog: null,
2327
+ // use default (511 as implemented in net.js)
2328
+ server: null,
2329
+ host: null,
2330
+ path: null,
2331
+ port: null
2332
+ },
2333
+ options
2334
+ );
2335
+ if (options.port == null && !options.server && !options.noServer) {
2336
+ throw new TypeError(
2337
+ 'One of the "port", "server", or "noServer" options must be specified'
2338
+ );
2339
+ }
2340
+ if (options.port != null) {
2341
+ this._server = http.createServer((req, res) => {
2342
+ const body = http.STATUS_CODES[426];
2343
+ res.writeHead(426, {
2344
+ "Content-Length": body.length,
2345
+ "Content-Type": "text/plain"
2346
+ });
2347
+ res.end(body);
2348
+ });
2349
+ this._server.listen(
2350
+ options.port,
2351
+ options.host,
2352
+ options.backlog,
2353
+ callback
2354
+ );
2355
+ } else if (options.server) {
2356
+ this._server = options.server;
2357
+ }
2358
+ if (this._server) {
2359
+ this._removeListeners = addListeners(this._server, {
2360
+ listening: this.emit.bind(this, "listening"),
2361
+ error: this.emit.bind(this, "error"),
2362
+ upgrade: (req, socket, head) => {
2363
+ this.handleUpgrade(req, socket, head, (ws) => {
2364
+ this.emit("connection", ws, req);
2365
+ });
2366
+ }
2367
+ });
2368
+ }
2369
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
2370
+ if (options.clientTracking) this.clients = /* @__PURE__ */ new Set();
2371
+ this.options = options;
2372
+ }
2373
+ /**
2374
+ * Returns the bound address, the address family name, and port of the server
2375
+ * as reported by the operating system if listening on an IP socket.
2376
+ * If the server is listening on a pipe or UNIX domain socket, the name is
2377
+ * returned as a string.
2378
+ *
2379
+ * @return {(Object|String|null)} The address of the server
2380
+ * @public
2381
+ */
2382
+ address() {
2383
+ if (this.options.noServer) {
2384
+ throw new Error('The server is operating in "noServer" mode');
2385
+ }
2386
+ if (!this._server) return null;
2387
+ return this._server.address();
2388
+ }
2389
+ /**
2390
+ * Close the server.
2391
+ *
2392
+ * @param {Function} cb Callback
2393
+ * @public
2394
+ */
2395
+ close(cb) {
2396
+ if (cb) this.once("close", cb);
2397
+ if (this.clients) {
2398
+ for (const client of this.clients) client.terminate();
2399
+ }
2400
+ const server = this._server;
2401
+ if (server) {
2402
+ this._removeListeners();
2403
+ this._removeListeners = this._server = null;
2404
+ if (this.options.port != null) {
2405
+ server.close(() => this.emit("close"));
2406
+ return;
2407
+ }
2408
+ }
2409
+ process.nextTick(emitClose, this);
2410
+ }
2411
+ /**
2412
+ * See if a given request should be handled by this server instance.
2413
+ *
2414
+ * @param {http.IncomingMessage} req Request object to inspect
2415
+ * @return {Boolean} `true` if the request is valid, else `false`
2416
+ * @public
2417
+ */
2418
+ shouldHandle(req) {
2419
+ if (this.options.path) {
2420
+ const index = req.url.indexOf("?");
2421
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
2422
+ if (pathname !== this.options.path) return false;
2423
+ }
2424
+ return true;
2425
+ }
2426
+ /**
2427
+ * Handle a HTTP Upgrade request.
2428
+ *
2429
+ * @param {http.IncomingMessage} req The request object
2430
+ * @param {net.Socket} socket The network socket between the server and client
2431
+ * @param {Buffer} head The first packet of the upgraded stream
2432
+ * @param {Function} cb Callback
2433
+ * @public
2434
+ */
2435
+ handleUpgrade(req, socket, head, cb) {
2436
+ socket.on("error", socketOnError);
2437
+ const key = req.headers["sec-websocket-key"] !== void 0 ? req.headers["sec-websocket-key"].trim() : false;
2438
+ const upgrade = req.headers.upgrade;
2439
+ const version = +req.headers["sec-websocket-version"];
2440
+ const extensions = {};
2441
+ if (req.method !== "GET" || upgrade === void 0 || upgrade.toLowerCase() !== "websocket" || !key || !keyRegex.test(key) || version !== 8 && version !== 13 || !this.shouldHandle(req)) {
2442
+ return abortHandshake(socket, 400);
2443
+ }
2444
+ if (this.options.perMessageDeflate) {
2445
+ const perMessageDeflate = new PerMessageDeflate(
2446
+ this.options.perMessageDeflate,
2447
+ true,
2448
+ this.options.maxPayload
2449
+ );
2450
+ try {
2451
+ const offers = extension.parse(req.headers["sec-websocket-extensions"]);
2452
+ if (offers[PerMessageDeflate.extensionName]) {
2453
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
2454
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2455
+ }
2456
+ } catch (err) {
2457
+ return abortHandshake(socket, 400);
2458
+ }
2459
+ }
2460
+ if (this.options.verifyClient) {
2461
+ const info = {
2462
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
2463
+ secure: !!(req.connection.authorized || req.connection.encrypted),
2464
+ req
2465
+ };
2466
+ if (this.options.verifyClient.length === 2) {
2467
+ this.options.verifyClient(info, (verified, code, message, headers) => {
2468
+ if (!verified) {
2469
+ return abortHandshake(socket, code || 401, message, headers);
2470
+ }
2471
+ this.completeUpgrade(key, extensions, req, socket, head, cb);
2472
+ });
2473
+ return;
2474
+ }
2475
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
2476
+ }
2477
+ this.completeUpgrade(key, extensions, req, socket, head, cb);
2478
+ }
2479
+ /**
2480
+ * Upgrade the connection to WebSocket.
2481
+ *
2482
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
2483
+ * @param {Object} extensions The accepted extensions
2484
+ * @param {http.IncomingMessage} req The request object
2485
+ * @param {net.Socket} socket The network socket between the server and client
2486
+ * @param {Buffer} head The first packet of the upgraded stream
2487
+ * @param {Function} cb Callback
2488
+ * @private
2489
+ */
2490
+ completeUpgrade(key, extensions, req, socket, head, cb) {
2491
+ if (!socket.readable || !socket.writable) return socket.destroy();
2492
+ const digest = crypto2.createHash("sha1").update(key + GUID).digest("base64");
2493
+ const headers = [
2494
+ "HTTP/1.1 101 Switching Protocols",
2495
+ "Upgrade: websocket",
2496
+ "Connection: Upgrade",
2497
+ `Sec-WebSocket-Accept: ${digest}`
2498
+ ];
2499
+ const ws = new WebSocket2(null);
2500
+ var protocol = req.headers["sec-websocket-protocol"];
2501
+ if (protocol) {
2502
+ protocol = protocol.split(",").map(trim);
2503
+ if (this.options.handleProtocols) {
2504
+ protocol = this.options.handleProtocols(protocol, req);
2505
+ } else {
2506
+ protocol = protocol[0];
2507
+ }
2508
+ if (protocol) {
2509
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
2510
+ ws.protocol = protocol;
2511
+ }
2512
+ }
2513
+ if (extensions[PerMessageDeflate.extensionName]) {
2514
+ const params = extensions[PerMessageDeflate.extensionName].params;
2515
+ const value = extension.format({
2516
+ [PerMessageDeflate.extensionName]: [params]
2517
+ });
2518
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
2519
+ ws._extensions = extensions;
2520
+ }
2521
+ this.emit("headers", headers, req);
2522
+ socket.write(headers.concat("\r\n").join("\r\n"));
2523
+ socket.removeListener("error", socketOnError);
2524
+ ws.setSocket(socket, head, this.options.maxPayload);
2525
+ if (this.clients) {
2526
+ this.clients.add(ws);
2527
+ ws.on("close", () => this.clients.delete(ws));
2528
+ }
2529
+ cb(ws);
2530
+ }
2531
+ };
2532
+ module.exports = WebSocketServer;
2533
+ function addListeners(server, map) {
2534
+ for (const event of Object.keys(map)) server.on(event, map[event]);
2535
+ return function removeListeners() {
2536
+ for (const event of Object.keys(map)) {
2537
+ server.removeListener(event, map[event]);
2538
+ }
2539
+ };
2540
+ }
2541
+ function emitClose(server) {
2542
+ server.emit("close");
2543
+ }
2544
+ function socketOnError() {
2545
+ this.destroy();
2546
+ }
2547
+ function abortHandshake(socket, code, message, headers) {
2548
+ if (socket.writable) {
2549
+ message = message || http.STATUS_CODES[code];
2550
+ headers = Object.assign(
2551
+ {
2552
+ Connection: "close",
2553
+ "Content-type": "text/html",
2554
+ "Content-Length": Buffer.byteLength(message)
2555
+ },
2556
+ headers
2557
+ );
2558
+ socket.write(
2559
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
2560
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
2561
+ );
2562
+ }
2563
+ socket.removeListener("error", socketOnError);
2564
+ socket.destroy();
2565
+ }
2566
+ function trim(str) {
2567
+ return str.trim();
2568
+ }
2569
+ }
2570
+ });
2571
+
2572
+ // ../../node_modules/ws/index.js
2573
+ var require_ws = __commonJS({
2574
+ "../../node_modules/ws/index.js"(exports, module) {
2575
+ var WebSocket2 = require_websocket();
2576
+ WebSocket2.Server = require_websocket_server();
2577
+ WebSocket2.Receiver = require_receiver();
2578
+ WebSocket2.Sender = require_sender();
2579
+ module.exports = WebSocket2;
2580
+ }
2581
+ });
9
2582
 
10
2583
  // ../core/src/platform.ts
11
2584
  function detectPlatform() {
@@ -896,6 +3469,40 @@ var HttpClient = class {
896
3469
  signal
897
3470
  });
898
3471
  }
3472
+ /**
3473
+ * AI Agent request (non-streaming)
3474
+ * Returns JSON response with text, steps, usage, and billing
3475
+ */
3476
+ async aiAgent(requestBody, signal) {
3477
+ return this.request(`/api/ai/${this.projectId}/agent`, {
3478
+ method: "POST",
3479
+ body: requestBody,
3480
+ signal
3481
+ });
3482
+ }
3483
+ /**
3484
+ * AI Agent streaming request
3485
+ * Returns raw Response for SSE streaming (compatible with AI SDK useChat)
3486
+ */
3487
+ async aiAgentStream(requestBody, signal) {
3488
+ const url = this.buildUrl(`/api/ai/${this.projectId}/agent`);
3489
+ const token = this.getValidToken ? await this.getValidToken() : this.getToken();
3490
+ const headers = {
3491
+ "Content-Type": "application/json"
3492
+ };
3493
+ const auth = this.getAuthorizationHeader(url, token);
3494
+ if (auth) headers.Authorization = auth;
3495
+ const response = await fetch(url, {
3496
+ method: "POST",
3497
+ headers,
3498
+ body: JSON.stringify(requestBody),
3499
+ signal
3500
+ });
3501
+ if (!response.ok) {
3502
+ await this.handleErrorResponse(response);
3503
+ }
3504
+ return response;
3505
+ }
899
3506
  /**
900
3507
  * Data-specific requests
901
3508
  */
@@ -937,6 +3544,38 @@ var HttpClient = class {
937
3544
  async dataSearch(projectId, request) {
938
3545
  return this.post(`/api/data/${projectId}/search`, request);
939
3546
  }
3547
+ /**
3548
+ * Connector requests
3549
+ */
3550
+ formatProviderForPath(provider) {
3551
+ return provider.replace("_", "-");
3552
+ }
3553
+ async connectorStatus(provider) {
3554
+ return this.request(`/api/connectors/${this.formatProviderForPath(provider)}/${this.projectId}/status`, {
3555
+ method: "GET"
3556
+ });
3557
+ }
3558
+ async connectorExecute(provider, request) {
3559
+ const path = request.method.startsWith("/") ? request.method : `/${request.method}`;
3560
+ const url = `/api/connectors/${this.formatProviderForPath(provider)}/${this.projectId}${path}`;
3561
+ const method = (request.http_method || "GET").toUpperCase();
3562
+ if (method === "GET") {
3563
+ return this.request(url, {
3564
+ method: "GET",
3565
+ searchParams: request.params
3566
+ });
3567
+ }
3568
+ return this.request(url, {
3569
+ method,
3570
+ body: request.params || {}
3571
+ });
3572
+ }
3573
+ async connectorSaveApiKey(provider, request) {
3574
+ return this.request(`/api/connectors/${this.formatProviderForPath(provider)}/${this.projectId}/api-key`, {
3575
+ method: "POST",
3576
+ body: request
3577
+ });
3578
+ }
940
3579
  /**
941
3580
  * Realtime-specific requests
942
3581
  */
@@ -2610,6 +5249,83 @@ var BlinkAuth = class {
2610
5249
  const user = await this.me();
2611
5250
  return user;
2612
5251
  }
5252
+ /**
5253
+ * Verify a Blink Auth token using the introspection endpoint.
5254
+ *
5255
+ * **Server-side / Edge Function use only.**
5256
+ *
5257
+ * This is the recommended way to verify user tokens in Deno Edge Functions
5258
+ * and other server-side contexts. It calls the Blink API introspection
5259
+ * endpoint which validates the token without exposing the JWT secret.
5260
+ *
5261
+ * @param token - The raw JWT token (without "Bearer " prefix) or full Authorization header
5262
+ * @returns Token introspection result with validity and claims
5263
+ *
5264
+ * @example
5265
+ * // Deno Edge Function usage
5266
+ * import { createClient } from "npm:@blinkdotnew/sdk";
5267
+ *
5268
+ * const blink = createClient({
5269
+ * projectId: Deno.env.get("BLINK_PROJECT_ID")!,
5270
+ * secretKey: Deno.env.get("BLINK_SECRET_KEY"),
5271
+ * });
5272
+ *
5273
+ * async function handler(req: Request): Promise<Response> {
5274
+ * const authHeader = req.headers.get("Authorization");
5275
+ * const result = await blink.auth.verifyToken(authHeader);
5276
+ *
5277
+ * if (!result.valid) {
5278
+ * return new Response(JSON.stringify({ error: result.error }), { status: 401 });
5279
+ * }
5280
+ *
5281
+ * // User is authenticated
5282
+ * console.log("User ID:", result.userId);
5283
+ * console.log("Email:", result.email);
5284
+ * console.log("Project:", result.projectId);
5285
+ *
5286
+ * // Continue with your logic...
5287
+ * }
5288
+ */
5289
+ async verifyToken(token) {
5290
+ if (!token) {
5291
+ return { valid: false, error: "Token required" };
5292
+ }
5293
+ let cleanToken = token.toLowerCase().startsWith("bearer ") ? token.slice(7) : token;
5294
+ cleanToken = cleanToken.trim();
5295
+ if (!cleanToken) {
5296
+ return { valid: false, error: "Token required" };
5297
+ }
5298
+ try {
5299
+ const response = await fetch(`${this.coreUrl}/api/auth/introspect`, {
5300
+ method: "POST",
5301
+ headers: {
5302
+ "Authorization": `Bearer ${cleanToken}`,
5303
+ "Content-Type": "application/json"
5304
+ }
5305
+ });
5306
+ const contentType = response.headers.get("content-type")?.toLowerCase();
5307
+ if (!contentType || !contentType.includes("application/json")) {
5308
+ return {
5309
+ valid: false,
5310
+ error: `Server error: ${response.status} ${response.statusText}`
5311
+ };
5312
+ }
5313
+ const result = await response.json();
5314
+ if (!result || typeof result !== "object" || typeof result.valid !== "boolean") {
5315
+ return {
5316
+ valid: false,
5317
+ error: result && (result.error || result.message) || `Request failed: ${response.status}`
5318
+ };
5319
+ }
5320
+ return result;
5321
+ } catch (error) {
5322
+ console.error("[BlinkAuth] Token verification failed:", error);
5323
+ return {
5324
+ valid: false,
5325
+ error: error instanceof Error ? error.message : "Token verification failed"
5326
+ };
5327
+ }
5328
+ }
2613
5329
  /**
2614
5330
  * Refresh access token using refresh token
2615
5331
  */
@@ -3539,99 +6255,884 @@ var BlinkStorageImpl = class {
3539
6255
  * <a href={downloadUrl} download={filename}>Download Image</a>
3540
6256
  * ```
3541
6257
  */
3542
- async download(path, options = {}) {
6258
+ async download(path, options = {}) {
6259
+ try {
6260
+ if (!path || typeof path !== "string" || !path.trim()) {
6261
+ throw new BlinkStorageError("Path must be a non-empty string");
6262
+ }
6263
+ const response = await this.httpClient.request(
6264
+ `/api/storage/${this.httpClient.projectId}/download`,
6265
+ {
6266
+ method: "GET",
6267
+ searchParams: {
6268
+ path: path.trim(),
6269
+ ...options.filename && { filename: options.filename }
6270
+ }
6271
+ }
6272
+ );
6273
+ if (response.data?.downloadUrl) {
6274
+ return {
6275
+ downloadUrl: response.data.downloadUrl,
6276
+ filename: response.data.filename || options.filename || path.split("/").pop() || "download",
6277
+ contentType: response.data.contentType,
6278
+ size: response.data.size
6279
+ };
6280
+ } else {
6281
+ throw new BlinkStorageError("Invalid response format: missing downloadUrl");
6282
+ }
6283
+ } catch (error) {
6284
+ if (error instanceof BlinkStorageError) {
6285
+ throw error;
6286
+ }
6287
+ if (error instanceof Error && "status" in error) {
6288
+ const status = error.status;
6289
+ if (status === 404) {
6290
+ throw new BlinkStorageError("File not found", 404);
6291
+ }
6292
+ if (status === 400) {
6293
+ throw new BlinkStorageError("Invalid request parameters", 400);
6294
+ }
6295
+ }
6296
+ throw new BlinkStorageError(
6297
+ `Download failed: ${error instanceof Error ? error.message : "Unknown error"}`,
6298
+ void 0,
6299
+ { originalError: error }
6300
+ );
6301
+ }
6302
+ }
6303
+ /**
6304
+ * Remove one or more files from project storage
6305
+ *
6306
+ * @param paths - File paths to remove
6307
+ * @returns Promise that resolves when files are removed
6308
+ *
6309
+ * @example
6310
+ * ```ts
6311
+ * await blink.storage.remove('avatars/user1.png');
6312
+ * await blink.storage.remove('file1.pdf', 'file2.pdf', 'file3.pdf');
6313
+ * ```
6314
+ */
6315
+ async remove(...paths) {
6316
+ try {
6317
+ if (paths.length === 0) {
6318
+ throw new BlinkStorageError("At least one path must be provided");
6319
+ }
6320
+ for (const path of paths) {
6321
+ if (!path || typeof path !== "string") {
6322
+ throw new BlinkStorageError("All paths must be non-empty strings");
6323
+ }
6324
+ }
6325
+ await this.httpClient.request(
6326
+ `/api/storage/${this.httpClient.projectId}/remove`,
6327
+ {
6328
+ method: "DELETE",
6329
+ body: { paths },
6330
+ headers: { "Content-Type": "application/json" }
6331
+ }
6332
+ );
6333
+ } catch (error) {
6334
+ if (error instanceof BlinkStorageError) {
6335
+ throw error;
6336
+ }
6337
+ if (error instanceof Error && "status" in error) {
6338
+ const status = error.status;
6339
+ if (status === 400) {
6340
+ throw new BlinkStorageError("Invalid request parameters", 400);
6341
+ }
6342
+ }
6343
+ throw new BlinkStorageError(
6344
+ `Failed to remove files: ${error instanceof Error ? error.message : "Unknown error"}`,
6345
+ void 0,
6346
+ { originalError: error }
6347
+ );
6348
+ }
6349
+ }
6350
+ };
6351
+
6352
+ // src/tools/core.ts
6353
+ var webSearch = {
6354
+ name: "web_search",
6355
+ description: "Search the web for current information. Returns titles, URLs, and snippets from relevant web pages. Powered by Exa AI.",
6356
+ inputSchema: {
6357
+ type: "object",
6358
+ properties: {
6359
+ query: {
6360
+ type: "string",
6361
+ description: "Search query"
6362
+ },
6363
+ max_results: {
6364
+ type: "number",
6365
+ description: "Maximum number of results (default: 10, max: 20)"
6366
+ }
6367
+ },
6368
+ required: ["query"]
6369
+ }
6370
+ };
6371
+ var fetchUrl = {
6372
+ name: "fetch_url",
6373
+ description: "Fetch content from a URL and extract clean text (HTML stripped). Fast, no JavaScript rendering. Good for Wikipedia, documentation, articles.",
6374
+ inputSchema: {
6375
+ type: "object",
6376
+ properties: {
6377
+ url: {
6378
+ type: "string",
6379
+ format: "uri",
6380
+ description: "URL to fetch content from"
6381
+ },
6382
+ chunking: {
6383
+ type: "boolean",
6384
+ description: "Whether to return content as chunks (default: false)"
6385
+ },
6386
+ chunk_size: {
6387
+ type: "number",
6388
+ description: "Size of each chunk in characters (default: 4000)"
6389
+ }
6390
+ },
6391
+ required: ["url"]
6392
+ }
6393
+ };
6394
+ var runCode = {
6395
+ name: "run_code",
6396
+ description: "Execute Python code in an isolated sandbox with numpy, pandas, matplotlib, scipy, scikit-learn, requests. Returns stdout, stderr, text result, and rich outputs (matplotlib plots as base64 PNG images). Use for calculations, data analysis, and visualizations.",
6397
+ inputSchema: {
6398
+ type: "object",
6399
+ properties: {
6400
+ code: {
6401
+ type: "string",
6402
+ minLength: 1,
6403
+ description: "Python code to execute. Matplotlib plots are automatically captured - use plt.show() or display(plt.gcf())"
6404
+ },
6405
+ timeout: {
6406
+ type: "number",
6407
+ minimum: 1,
6408
+ maximum: 60,
6409
+ description: "Execution timeout in seconds (default: 30, max: 60)"
6410
+ }
6411
+ },
6412
+ required: ["code"]
6413
+ }
6414
+ };
6415
+
6416
+ // src/tools/sandbox.ts
6417
+ var readFile = {
6418
+ name: "read_file",
6419
+ description: `Read file from sandbox filesystem.
6420
+ - Lines are numbered: LINE_NUMBER|CONTENT
6421
+ - Use offset/limit for large files
6422
+ - Images (png, jpg, gif, webp) returned as base64`,
6423
+ inputSchema: {
6424
+ type: "object",
6425
+ properties: {
6426
+ path: {
6427
+ type: "string",
6428
+ description: "File path to read"
6429
+ },
6430
+ offset: {
6431
+ type: "number",
6432
+ description: "Line number to start from (1-based)"
6433
+ },
6434
+ limit: {
6435
+ type: "number",
6436
+ description: "Number of lines to read"
6437
+ }
6438
+ },
6439
+ required: ["path"]
6440
+ }
6441
+ };
6442
+ var listDir = {
6443
+ name: "list_dir",
6444
+ description: `List files and directories at path.
6445
+ - Returns [FILE] and [DIR] prefixes
6446
+ - Auto-excludes node_modules, .git, dist, etc.
6447
+ - Use include_glob to filter for specific patterns`,
6448
+ inputSchema: {
6449
+ type: "object",
6450
+ properties: {
6451
+ path: {
6452
+ type: "string",
6453
+ description: "Directory path to list"
6454
+ },
6455
+ include_glob: {
6456
+ type: "string",
6457
+ description: 'Glob pattern to filter results (e.g., "*.ts", "*.{ts,tsx}"). Only matching files/dirs shown.'
6458
+ },
6459
+ ignore_globs: {
6460
+ type: "array",
6461
+ items: { type: "string" },
6462
+ description: 'Additional patterns to exclude (e.g., ["*.log", "temp*"])'
6463
+ }
6464
+ },
6465
+ required: ["path"]
6466
+ }
6467
+ };
6468
+ var writeFile = {
6469
+ name: "write_file",
6470
+ description: `Create a NEW file. For existing files, use search_replace instead!
6471
+ \u26A0\uFE0F This OVERWRITES existing files - only use for NEW files.`,
6472
+ inputSchema: {
6473
+ type: "object",
6474
+ properties: {
6475
+ path: {
6476
+ type: "string",
6477
+ description: "Path to create the file"
6478
+ },
6479
+ content: {
6480
+ type: "string",
6481
+ description: "File content"
6482
+ }
6483
+ },
6484
+ required: ["path", "content"]
6485
+ }
6486
+ };
6487
+ var searchReplace = {
6488
+ name: "search_replace",
6489
+ description: `\u{1F6A8} PREFERRED: Safest way to modify existing files.
6490
+ - Include 3-5 lines of context for unique matching
6491
+ - Use replace_all=true for renaming variables across file
6492
+ - Preserves all other code (surgical precision)`,
6493
+ inputSchema: {
6494
+ type: "object",
6495
+ properties: {
6496
+ file_path: {
6497
+ type: "string",
6498
+ description: "Path to the file to modify"
6499
+ },
6500
+ old_string: {
6501
+ type: "string",
6502
+ description: "Text to replace (include 3-5 lines of context for uniqueness)"
6503
+ },
6504
+ new_string: {
6505
+ type: "string",
6506
+ description: "Replacement text"
6507
+ },
6508
+ replace_all: {
6509
+ type: "boolean",
6510
+ description: "Replace ALL occurrences (default: false)"
6511
+ }
6512
+ },
6513
+ required: ["file_path", "old_string", "new_string"]
6514
+ }
6515
+ };
6516
+ var grep = {
6517
+ name: "grep",
6518
+ description: `Search file contents using ripgrep regex.
6519
+ - Supports: "log.*Error", "function\\s+\\w+"
6520
+ - Modes: "content" (lines), "files_with_matches" (paths), "count"
6521
+ - Context: -A (after), -B (before), -C (both)`,
6522
+ inputSchema: {
6523
+ type: "object",
6524
+ properties: {
6525
+ pattern: {
6526
+ type: "string",
6527
+ description: "Regex pattern to search for"
6528
+ },
6529
+ path: {
6530
+ type: "string",
6531
+ description: "Search path (default: project root)"
6532
+ },
6533
+ type: {
6534
+ type: "string",
6535
+ description: "File type filter (js, py, ts, tsx, etc.)"
6536
+ },
6537
+ glob: {
6538
+ type: "string",
6539
+ description: 'Glob pattern filter (e.g., "*.tsx")'
6540
+ },
6541
+ output_mode: {
6542
+ type: "string",
6543
+ enum: ["content", "files_with_matches", "count"],
6544
+ description: "Output format (default: content)"
6545
+ },
6546
+ "-i": {
6547
+ type: "boolean",
6548
+ description: "Case insensitive search"
6549
+ },
6550
+ "-A": {
6551
+ type: "number",
6552
+ description: "Lines to show after match"
6553
+ },
6554
+ "-B": {
6555
+ type: "number",
6556
+ description: "Lines to show before match"
6557
+ },
6558
+ "-C": {
6559
+ type: "number",
6560
+ description: "Lines to show around match"
6561
+ },
6562
+ multiline: {
6563
+ type: "boolean",
6564
+ description: "Enable multiline matching"
6565
+ },
6566
+ head_limit: {
6567
+ type: "number",
6568
+ description: "Limit output lines"
6569
+ }
6570
+ },
6571
+ required: ["pattern"]
6572
+ }
6573
+ };
6574
+ var globFileSearch = {
6575
+ name: "glob_file_search",
6576
+ description: `Find files by name pattern.
6577
+ - Examples: "*.ts", "**/*.test.tsx", "src/**/*.js"
6578
+ - Results sorted by modification time (recent first)
6579
+ - Use grep to search file CONTENTS, this searches file NAMES`,
6580
+ inputSchema: {
6581
+ type: "object",
6582
+ properties: {
6583
+ pattern: {
6584
+ type: "string",
6585
+ description: 'Glob pattern (e.g., "*.ts", "**/*.test.tsx")'
6586
+ },
6587
+ path: {
6588
+ type: "string",
6589
+ description: "Directory to search in (default: project root)"
6590
+ },
6591
+ output_mode: {
6592
+ type: "string",
6593
+ enum: ["files", "count", "details"],
6594
+ description: "Output format (default: files)"
6595
+ },
6596
+ max_results: {
6597
+ type: "number",
6598
+ description: "Maximum results to return (default: 200, max: 500)"
6599
+ },
6600
+ include_hidden: {
6601
+ type: "boolean",
6602
+ description: "Include hidden files/dirs (starting with dot). Default: false"
6603
+ }
6604
+ },
6605
+ required: ["pattern"]
6606
+ }
6607
+ };
6608
+ var runTerminalCmd = {
6609
+ name: "run_terminal_cmd",
6610
+ description: `Run shell command in sandbox.
6611
+ - Use background=true for dev servers
6612
+ - Auto-prefixes sudo for package installs`,
6613
+ inputSchema: {
6614
+ type: "object",
6615
+ properties: {
6616
+ command: {
6617
+ type: "string",
6618
+ description: "Shell command to execute"
6619
+ },
6620
+ background: {
6621
+ type: "boolean",
6622
+ description: "Run in background (for servers)"
6623
+ }
6624
+ },
6625
+ required: ["command"]
6626
+ }
6627
+ };
6628
+ var getHost = {
6629
+ name: "get_host",
6630
+ description: "Get public URL for a sandbox port (e.g., 3000 for dev server).",
6631
+ inputSchema: {
6632
+ type: "object",
6633
+ properties: {
6634
+ port: {
6635
+ type: "number",
6636
+ description: "Port number to get URL for"
6637
+ }
6638
+ },
6639
+ required: ["port"]
6640
+ }
6641
+ };
6642
+ var sandboxTools = [
6643
+ // File reading
6644
+ readFile,
6645
+ listDir,
6646
+ // File editing
6647
+ writeFile,
6648
+ searchReplace,
6649
+ // Search
6650
+ grep,
6651
+ globFileSearch,
6652
+ // Execution
6653
+ runTerminalCmd,
6654
+ getHost
6655
+ ];
6656
+
6657
+ // src/tools/db.ts
6658
+ var dbInsert = {
6659
+ name: "db_insert",
6660
+ description: "Insert a new row into a database table. The user_id is automatically set via row-level security.",
6661
+ inputSchema: {
6662
+ type: "object",
6663
+ properties: {
6664
+ table: {
6665
+ type: "string",
6666
+ description: "Table name to insert into"
6667
+ },
6668
+ data: {
6669
+ type: "object",
6670
+ additionalProperties: true,
6671
+ description: "Data to insert (user_id is auto-set)"
6672
+ }
6673
+ },
6674
+ required: ["table", "data"]
6675
+ }
6676
+ };
6677
+ var dbList = {
6678
+ name: "db_list",
6679
+ description: "List rows from a database table with optional filtering, sorting, and pagination. Only returns rows owned by the current user (RLS enforced).",
6680
+ inputSchema: {
6681
+ type: "object",
6682
+ properties: {
6683
+ table: {
6684
+ type: "string",
6685
+ description: "Table name to query"
6686
+ },
6687
+ where: {
6688
+ type: "object",
6689
+ additionalProperties: true,
6690
+ description: 'Filter conditions like { status: "active", type: "order" }'
6691
+ },
6692
+ order_by: {
6693
+ type: "object",
6694
+ properties: {
6695
+ column: { type: "string", description: "Column to sort by" },
6696
+ direction: { type: "string", enum: ["asc", "desc"], description: "Sort direction" }
6697
+ },
6698
+ required: ["column", "direction"],
6699
+ description: "Sort order"
6700
+ },
6701
+ limit: {
6702
+ type: "number",
6703
+ description: "Maximum rows to return (default: 50, max: 100)"
6704
+ },
6705
+ offset: {
6706
+ type: "number",
6707
+ description: "Rows to skip for pagination"
6708
+ }
6709
+ },
6710
+ required: ["table"]
6711
+ }
6712
+ };
6713
+ var dbGet = {
6714
+ name: "db_get",
6715
+ description: "Get a single row by ID from a database table. Returns null if not found or not owned by user.",
6716
+ inputSchema: {
6717
+ type: "object",
6718
+ properties: {
6719
+ table: {
6720
+ type: "string",
6721
+ description: "Table name"
6722
+ },
6723
+ id: {
6724
+ type: "string",
6725
+ description: "Row ID to retrieve"
6726
+ }
6727
+ },
6728
+ required: ["table", "id"]
6729
+ }
6730
+ };
6731
+ var dbUpdate = {
6732
+ name: "db_update",
6733
+ description: "Update a row by ID. Only updates rows owned by the current user (RLS enforced).",
6734
+ inputSchema: {
6735
+ type: "object",
6736
+ properties: {
6737
+ table: {
6738
+ type: "string",
6739
+ description: "Table name"
6740
+ },
6741
+ id: {
6742
+ type: "string",
6743
+ description: "Row ID to update"
6744
+ },
6745
+ data: {
6746
+ type: "object",
6747
+ additionalProperties: true,
6748
+ description: "Fields to update"
6749
+ }
6750
+ },
6751
+ required: ["table", "id", "data"]
6752
+ }
6753
+ };
6754
+ var dbDelete = {
6755
+ name: "db_delete",
6756
+ description: "Delete a row by ID. Only deletes rows owned by the current user (RLS enforced).",
6757
+ inputSchema: {
6758
+ type: "object",
6759
+ properties: {
6760
+ table: {
6761
+ type: "string",
6762
+ description: "Table name"
6763
+ },
6764
+ id: {
6765
+ type: "string",
6766
+ description: "Row ID to delete"
6767
+ }
6768
+ },
6769
+ required: ["table", "id"]
6770
+ }
6771
+ };
6772
+ var dbTools = [
6773
+ dbInsert,
6774
+ dbList,
6775
+ dbGet,
6776
+ dbUpdate,
6777
+ dbDelete
6778
+ ];
6779
+
6780
+ // src/tools/storage.ts
6781
+ var storageUpload = {
6782
+ name: "storage_upload",
6783
+ description: "Upload a file to storage. Accepts base64-encoded content or a URL to fetch from.",
6784
+ inputSchema: {
6785
+ type: "object",
6786
+ properties: {
6787
+ path: {
6788
+ type: "string",
6789
+ description: "Destination path for the file"
6790
+ },
6791
+ content: {
6792
+ type: "string",
6793
+ description: "Base64-encoded file content OR URL to fetch"
6794
+ },
6795
+ content_type: {
6796
+ type: "string",
6797
+ description: "MIME type (auto-detected if omitted)"
6798
+ }
6799
+ },
6800
+ required: ["path", "content"]
6801
+ }
6802
+ };
6803
+ var storageDownload = {
6804
+ name: "storage_download",
6805
+ description: "Get download URL for a file in storage.",
6806
+ inputSchema: {
6807
+ type: "object",
6808
+ properties: {
6809
+ path: {
6810
+ type: "string",
6811
+ description: "Path to the file to download"
6812
+ }
6813
+ },
6814
+ required: ["path"]
6815
+ }
6816
+ };
6817
+ var storageList = {
6818
+ name: "storage_list",
6819
+ description: "List files in a storage directory.",
6820
+ inputSchema: {
6821
+ type: "object",
6822
+ properties: {
6823
+ path: {
6824
+ type: "string",
6825
+ description: 'Folder path to list (default: "/")'
6826
+ },
6827
+ limit: {
6828
+ type: "number",
6829
+ description: "Max files to return (default: 50, max: 100)"
6830
+ }
6831
+ }
6832
+ }
6833
+ };
6834
+ var storageDelete = {
6835
+ name: "storage_delete",
6836
+ description: "Delete a file from storage.",
6837
+ inputSchema: {
6838
+ type: "object",
6839
+ properties: {
6840
+ path: {
6841
+ type: "string",
6842
+ description: "Path to the file to delete"
6843
+ }
6844
+ },
6845
+ required: ["path"]
6846
+ }
6847
+ };
6848
+ var storagePublicUrl = {
6849
+ name: "storage_public_url",
6850
+ description: "Get the public URL for a file in storage.",
6851
+ inputSchema: {
6852
+ type: "object",
6853
+ properties: {
6854
+ path: {
6855
+ type: "string",
6856
+ description: "Path to the file"
6857
+ }
6858
+ },
6859
+ required: ["path"]
6860
+ }
6861
+ };
6862
+ var storageMove = {
6863
+ name: "storage_move",
6864
+ description: "Move or rename a file in storage.",
6865
+ inputSchema: {
6866
+ type: "object",
6867
+ properties: {
6868
+ from: {
6869
+ type: "string",
6870
+ description: "Source path"
6871
+ },
6872
+ to: {
6873
+ type: "string",
6874
+ description: "Destination path"
6875
+ }
6876
+ },
6877
+ required: ["from", "to"]
6878
+ }
6879
+ };
6880
+ var storageCopy = {
6881
+ name: "storage_copy",
6882
+ description: "Copy a file to a new location in storage.",
6883
+ inputSchema: {
6884
+ type: "object",
6885
+ properties: {
6886
+ from: {
6887
+ type: "string",
6888
+ description: "Source path"
6889
+ },
6890
+ to: {
6891
+ type: "string",
6892
+ description: "Destination path"
6893
+ }
6894
+ },
6895
+ required: ["from", "to"]
6896
+ }
6897
+ };
6898
+ var storageTools = [
6899
+ storageUpload,
6900
+ storageDownload,
6901
+ storageList,
6902
+ storageDelete,
6903
+ storagePublicUrl,
6904
+ storageMove,
6905
+ storageCopy
6906
+ ];
6907
+
6908
+ // src/tools/rag.ts
6909
+ var ragSearch = {
6910
+ name: "rag_search",
6911
+ description: "Search a knowledge base using semantic similarity. Returns relevant document chunks with content and scores. Use this to find information in uploaded documents, then synthesize an answer from the results.",
6912
+ inputSchema: {
6913
+ type: "object",
6914
+ properties: {
6915
+ collection_id: {
6916
+ type: "string",
6917
+ description: "Collection ID to search in"
6918
+ },
6919
+ collection_name: {
6920
+ type: "string",
6921
+ description: "Collection name to search in (alternative to collection_id)"
6922
+ },
6923
+ query: {
6924
+ type: "string",
6925
+ description: "Search query - what you want to find in the knowledge base"
6926
+ },
6927
+ max_results: {
6928
+ type: "number",
6929
+ description: "Maximum number of results (1-100, default: 10)"
6930
+ },
6931
+ score_threshold: {
6932
+ type: "number",
6933
+ description: "Minimum similarity score 0-1 (default: 0.3)"
6934
+ },
6935
+ filters: {
6936
+ type: "object",
6937
+ description: "Metadata filters to narrow results",
6938
+ additionalProperties: true
6939
+ }
6940
+ },
6941
+ required: ["query"]
6942
+ }
6943
+ };
6944
+ var ragTools = [
6945
+ ragSearch
6946
+ ];
6947
+
6948
+ // src/tools/index.ts
6949
+ function serializeTools(tools) {
6950
+ return tools.map((tool) => {
6951
+ if (typeof tool === "string") {
6952
+ return tool;
6953
+ }
6954
+ return tool.name;
6955
+ });
6956
+ }
6957
+
6958
+ // src/agent.ts
6959
+ function createStopConditions(maxSteps, stopWhen) {
6960
+ if (stopWhen && stopWhen.length > 0) {
6961
+ return stopWhen;
6962
+ }
6963
+ if (maxSteps && maxSteps > 0) {
6964
+ return [{ type: "step_count_is", count: maxSteps }];
6965
+ }
6966
+ return void 0;
6967
+ }
6968
+ var Agent = class {
6969
+ httpClient = null;
6970
+ config;
6971
+ /**
6972
+ * Create a new Agent instance
6973
+ * @param options - Agent configuration options
6974
+ */
6975
+ constructor(options) {
6976
+ if (!options.model) {
6977
+ throw new BlinkAIError("Agent model is required");
6978
+ }
6979
+ this.config = options;
6980
+ }
6981
+ /**
6982
+ * Internal: Set the HTTP client (called by BlinkClient)
6983
+ */
6984
+ _setHttpClient(client) {
6985
+ this.httpClient = client;
6986
+ }
6987
+ /**
6988
+ * Internal: Get the agent config for API requests
6989
+ */
6990
+ getAgentConfig() {
6991
+ const { model, system, instructions, tools, webhookTools, clientTools, toolChoice, stopWhen, maxSteps } = this.config;
6992
+ const serializedTools = tools ? serializeTools(tools) : void 0;
6993
+ const stopConditions = createStopConditions(maxSteps, stopWhen);
6994
+ return {
6995
+ model,
6996
+ system: system || instructions,
6997
+ tools: serializedTools,
6998
+ webhook_tools: webhookTools,
6999
+ client_tools: clientTools,
7000
+ tool_choice: toolChoice,
7001
+ stop_when: stopConditions
7002
+ };
7003
+ }
7004
+ /**
7005
+ * Generate a response (non-streaming)
7006
+ *
7007
+ * @param options - Generation options (prompt or messages)
7008
+ * @returns Promise<AgentResponse> with text, steps, usage, and billing
7009
+ *
7010
+ * @example
7011
+ * ```ts
7012
+ * const result = await agent.generate({
7013
+ * prompt: 'What is the weather in San Francisco?',
7014
+ * })
7015
+ * console.log(result.text)
7016
+ * console.log(result.steps)
7017
+ * ```
7018
+ */
7019
+ async generate(options) {
7020
+ if (!this.httpClient) {
7021
+ throw new BlinkAIError(
7022
+ "Agent not initialized. Use blink.ai.createAgent() or pass the agent to useAgent()."
7023
+ );
7024
+ }
7025
+ if (!options.prompt && !options.messages) {
7026
+ throw new BlinkAIError("Either prompt or messages is required");
7027
+ }
7028
+ if (options.prompt && options.messages) {
7029
+ throw new BlinkAIError("prompt and messages are mutually exclusive");
7030
+ }
3543
7031
  try {
3544
- if (!path || typeof path !== "string" || !path.trim()) {
3545
- throw new BlinkStorageError("Path must be a non-empty string");
7032
+ const requestBody = {
7033
+ stream: false,
7034
+ agent: this.getAgentConfig()
7035
+ };
7036
+ if (options.prompt) {
7037
+ requestBody.prompt = options.prompt;
7038
+ } else if (options.messages) {
7039
+ requestBody.messages = options.messages;
3546
7040
  }
3547
- const response = await this.httpClient.request(
3548
- `/api/storage/${this.httpClient.projectId}/download`,
3549
- {
3550
- method: "GET",
3551
- searchParams: {
3552
- path: path.trim(),
3553
- ...options.filename && { filename: options.filename }
3554
- }
3555
- }
3556
- );
3557
- if (response.data?.downloadUrl) {
3558
- return {
3559
- downloadUrl: response.data.downloadUrl,
3560
- filename: response.data.filename || options.filename || path.split("/").pop() || "download",
3561
- contentType: response.data.contentType,
3562
- size: response.data.size
3563
- };
3564
- } else {
3565
- throw new BlinkStorageError("Invalid response format: missing downloadUrl");
7041
+ if (options.sandbox) {
7042
+ requestBody.sandbox_id = typeof options.sandbox === "string" ? options.sandbox : options.sandbox.id;
3566
7043
  }
7044
+ const response = await this.httpClient.aiAgent(requestBody, options.signal);
7045
+ return response.data;
3567
7046
  } catch (error) {
3568
- if (error instanceof BlinkStorageError) {
7047
+ console.error("[Agent] generate failed:", error);
7048
+ if (error instanceof BlinkAIError) {
3569
7049
  throw error;
3570
7050
  }
3571
- if (error instanceof Error && "status" in error) {
3572
- const status = error.status;
3573
- if (status === 404) {
3574
- throw new BlinkStorageError("File not found", 404);
3575
- }
3576
- if (status === 400) {
3577
- throw new BlinkStorageError("Invalid request parameters", 400);
3578
- }
3579
- }
3580
- throw new BlinkStorageError(
3581
- `Download failed: ${error instanceof Error ? error.message : "Unknown error"}`,
7051
+ throw new BlinkAIError(
7052
+ `Agent generate failed: ${error instanceof Error ? error.message : "Unknown error"}`,
3582
7053
  void 0,
3583
7054
  { originalError: error }
3584
7055
  );
3585
7056
  }
3586
7057
  }
3587
7058
  /**
3588
- * Remove one or more files from project storage
7059
+ * Stream a response (real-time)
3589
7060
  *
3590
- * @param paths - File paths to remove
3591
- * @returns Promise that resolves when files are removed
7061
+ * @param options - Stream options (prompt or messages)
7062
+ * @returns Promise<Response> - AI SDK UI Message Stream for useChat compatibility
3592
7063
  *
3593
7064
  * @example
3594
7065
  * ```ts
3595
- * await blink.storage.remove('avatars/user1.png');
3596
- * await blink.storage.remove('file1.pdf', 'file2.pdf', 'file3.pdf');
7066
+ * const stream = await agent.stream({
7067
+ * prompt: 'Tell me a story',
7068
+ * })
7069
+ *
7070
+ * // Process stream
7071
+ * for await (const chunk of stream.body) {
7072
+ * // Handle chunk
7073
+ * }
3597
7074
  * ```
3598
7075
  */
3599
- async remove(...paths) {
7076
+ async stream(options) {
7077
+ if (!this.httpClient) {
7078
+ throw new BlinkAIError(
7079
+ "Agent not initialized. Use blink.ai.createAgent() or pass the agent to useAgent()."
7080
+ );
7081
+ }
7082
+ if (!options.prompt && !options.messages) {
7083
+ throw new BlinkAIError("Either prompt or messages is required");
7084
+ }
7085
+ if (options.prompt && options.messages) {
7086
+ throw new BlinkAIError("prompt and messages are mutually exclusive");
7087
+ }
3600
7088
  try {
3601
- if (paths.length === 0) {
3602
- throw new BlinkStorageError("At least one path must be provided");
7089
+ const requestBody = {
7090
+ stream: true,
7091
+ agent: this.getAgentConfig()
7092
+ };
7093
+ if (options.prompt) {
7094
+ requestBody.prompt = options.prompt;
7095
+ } else if (options.messages) {
7096
+ requestBody.messages = options.messages;
3603
7097
  }
3604
- for (const path of paths) {
3605
- if (!path || typeof path !== "string") {
3606
- throw new BlinkStorageError("All paths must be non-empty strings");
3607
- }
7098
+ if (options.sandbox) {
7099
+ requestBody.sandbox_id = typeof options.sandbox === "string" ? options.sandbox : options.sandbox.id;
3608
7100
  }
3609
- await this.httpClient.request(
3610
- `/api/storage/${this.httpClient.projectId}/remove`,
3611
- {
3612
- method: "DELETE",
3613
- body: { paths },
3614
- headers: { "Content-Type": "application/json" }
3615
- }
3616
- );
7101
+ return await this.httpClient.aiAgentStream(requestBody, options.signal);
3617
7102
  } catch (error) {
3618
- if (error instanceof BlinkStorageError) {
7103
+ console.error("[Agent] stream failed:", error);
7104
+ if (error instanceof BlinkAIError) {
3619
7105
  throw error;
3620
7106
  }
3621
- if (error instanceof Error && "status" in error) {
3622
- const status = error.status;
3623
- if (status === 400) {
3624
- throw new BlinkStorageError("Invalid request parameters", 400);
3625
- }
3626
- }
3627
- throw new BlinkStorageError(
3628
- `Failed to remove files: ${error instanceof Error ? error.message : "Unknown error"}`,
7107
+ throw new BlinkAIError(
7108
+ `Agent stream failed: ${error instanceof Error ? error.message : "Unknown error"}`,
3629
7109
  void 0,
3630
7110
  { originalError: error }
3631
7111
  );
3632
7112
  }
3633
7113
  }
7114
+ /**
7115
+ * Get the agent's model
7116
+ */
7117
+ get model() {
7118
+ return this.config.model;
7119
+ }
7120
+ /**
7121
+ * Get the agent's system prompt
7122
+ */
7123
+ get system() {
7124
+ return this.config.system || this.config.instructions;
7125
+ }
7126
+ /**
7127
+ * Get the agent's tools
7128
+ */
7129
+ get tools() {
7130
+ return this.config.tools;
7131
+ }
3634
7132
  };
7133
+ function stepCountIs(count) {
7134
+ return { type: "step_count_is", count };
7135
+ }
3635
7136
 
3636
7137
  // src/ai.ts
3637
7138
  var BlinkAIImpl = class {
@@ -4603,6 +8104,104 @@ var BlinkAIImpl = class {
4603
8104
  );
4604
8105
  }
4605
8106
  }
8107
+ async agent(options) {
8108
+ try {
8109
+ if (!options.agent?.model) {
8110
+ throw new BlinkAIError("agent.model is required");
8111
+ }
8112
+ if (!options.prompt && !options.messages) {
8113
+ throw new BlinkAIError("Either prompt or messages is required");
8114
+ }
8115
+ if (options.prompt && options.messages) {
8116
+ throw new BlinkAIError("prompt and messages are mutually exclusive");
8117
+ }
8118
+ const serializedTools = options.agent.tools ? serializeTools(options.agent.tools) : void 0;
8119
+ const requestBody = {
8120
+ stream: options.stream,
8121
+ agent: {
8122
+ model: options.agent.model,
8123
+ system: options.agent.system,
8124
+ tools: serializedTools,
8125
+ webhook_tools: options.agent.webhook_tools,
8126
+ client_tools: options.agent.client_tools,
8127
+ tool_choice: options.agent.tool_choice,
8128
+ stop_when: options.agent.stop_when,
8129
+ prepare_step: options.agent.prepare_step
8130
+ }
8131
+ };
8132
+ if (options.prompt) {
8133
+ requestBody.prompt = options.prompt;
8134
+ } else if (options.messages) {
8135
+ requestBody.messages = options.messages;
8136
+ }
8137
+ if (options.stream) {
8138
+ return await this.httpClient.aiAgentStream(requestBody, options.signal);
8139
+ } else {
8140
+ const response = await this.httpClient.aiAgent(requestBody, options.signal);
8141
+ return response.data;
8142
+ }
8143
+ } catch (error) {
8144
+ if (error instanceof BlinkAIError) {
8145
+ throw error;
8146
+ }
8147
+ throw new BlinkAIError(
8148
+ `Agent request failed: ${error instanceof Error ? error.message : "Unknown error"}`,
8149
+ void 0,
8150
+ { originalError: error }
8151
+ );
8152
+ }
8153
+ }
8154
+ // ============================================================================
8155
+ // Agent Factory
8156
+ // ============================================================================
8157
+ /**
8158
+ * Creates a reusable Agent instance with the Vercel AI SDK pattern.
8159
+ *
8160
+ * The Agent can be used multiple times with different prompts:
8161
+ * - `agent.generate({ prompt })` for non-streaming
8162
+ * - `agent.stream({ prompt })` for streaming
8163
+ *
8164
+ * @param options - Agent configuration (model, tools, system, etc.)
8165
+ * @returns Agent instance
8166
+ *
8167
+ * @example
8168
+ * ```ts
8169
+ * const weatherAgent = blink.ai.createAgent({
8170
+ * model: 'anthropic/claude-sonnet-4-20250514',
8171
+ * system: 'You are a helpful weather assistant.',
8172
+ * tools: [webSearch, fetchUrl],
8173
+ * maxSteps: 10,
8174
+ * })
8175
+ *
8176
+ * // Non-streaming
8177
+ * const result = await weatherAgent.generate({
8178
+ * prompt: 'What is the weather in San Francisco?',
8179
+ * })
8180
+ *
8181
+ * // Streaming
8182
+ * const stream = await weatherAgent.stream({
8183
+ * prompt: 'Tell me about weather patterns',
8184
+ * })
8185
+ * ```
8186
+ */
8187
+ createAgent(options) {
8188
+ const agent = new Agent(options);
8189
+ agent._setHttpClient(this.httpClient);
8190
+ return agent;
8191
+ }
8192
+ /**
8193
+ * Binds an existing Agent instance to this client's HTTP client.
8194
+ *
8195
+ * Used internally by useAgent() when an Agent instance is passed.
8196
+ * This allows agents created with `new Agent()` to be used with the hook.
8197
+ *
8198
+ * @param agent - Existing Agent instance
8199
+ * @returns The same Agent instance (with httpClient set)
8200
+ */
8201
+ bindAgent(agent) {
8202
+ agent._setHttpClient(this.httpClient);
8203
+ return agent;
8204
+ }
4606
8205
  };
4607
8206
 
4608
8207
  // src/data.ts
@@ -4712,7 +8311,7 @@ var getWebSocketClass = () => {
4712
8311
  return WebSocket;
4713
8312
  }
4714
8313
  try {
4715
- const WS = __require("ws");
8314
+ const WS = require_ws();
4716
8315
  return WS;
4717
8316
  } catch (error) {
4718
8317
  throw new BlinkRealtimeError('WebSocket is not available. Install "ws" package for Node.js environments.');
@@ -5663,6 +9262,25 @@ var BlinkAnalyticsImpl = class {
5663
9262
  }
5664
9263
  };
5665
9264
 
9265
+ // src/connectors.ts
9266
+ var BlinkConnectorsImpl = class {
9267
+ constructor(httpClient) {
9268
+ this.httpClient = httpClient;
9269
+ }
9270
+ async status(provider, options) {
9271
+ const response = await this.httpClient.connectorStatus(provider);
9272
+ return response.data;
9273
+ }
9274
+ async execute(provider, request) {
9275
+ const response = await this.httpClient.connectorExecute(provider, request);
9276
+ return response.data;
9277
+ }
9278
+ async saveApiKey(provider, request) {
9279
+ const response = await this.httpClient.connectorSaveApiKey(provider, request);
9280
+ return response.data;
9281
+ }
9282
+ };
9283
+
5666
9284
  // src/functions.ts
5667
9285
  var BlinkFunctionsImpl = class {
5668
9286
  httpClient;
@@ -5702,6 +9320,410 @@ var BlinkFunctionsImpl = class {
5702
9320
  }
5703
9321
  };
5704
9322
 
9323
+ // src/rag.ts
9324
+ function removeUndefined(obj) {
9325
+ return Object.fromEntries(
9326
+ Object.entries(obj).filter(([, v]) => v !== void 0)
9327
+ );
9328
+ }
9329
+ function convertCollection(api) {
9330
+ return {
9331
+ id: api.id,
9332
+ name: api.name,
9333
+ description: api.description,
9334
+ embeddingModel: api.embedding_model,
9335
+ embeddingDimensions: api.embedding_dimensions,
9336
+ indexMetric: api.index_metric,
9337
+ chunkMaxTokens: api.chunk_max_tokens,
9338
+ chunkOverlapTokens: api.chunk_overlap_tokens,
9339
+ documentCount: api.document_count,
9340
+ chunkCount: api.chunk_count,
9341
+ shared: api.shared,
9342
+ createdAt: api.created_at,
9343
+ updatedAt: api.updated_at
9344
+ };
9345
+ }
9346
+ function convertDocument(api) {
9347
+ return {
9348
+ id: api.id,
9349
+ collectionId: api.collection_id,
9350
+ filename: api.filename,
9351
+ sourceType: api.source_type,
9352
+ sourceUrl: api.source_url,
9353
+ contentType: api.content_type,
9354
+ fileSize: api.file_size,
9355
+ status: api.status,
9356
+ errorMessage: api.error_message,
9357
+ processingStartedAt: api.processing_started_at,
9358
+ processingCompletedAt: api.processing_completed_at,
9359
+ chunkCount: api.chunk_count,
9360
+ tokenCount: api.token_count,
9361
+ metadata: api.metadata,
9362
+ createdAt: api.created_at,
9363
+ updatedAt: api.updated_at
9364
+ };
9365
+ }
9366
+ function convertPartialDocument(api, options) {
9367
+ let sourceType = "text";
9368
+ if (options.url) sourceType = "url";
9369
+ if (options.file) sourceType = "file";
9370
+ return {
9371
+ id: api.id || "",
9372
+ collectionId: api.collection_id || options.collectionId || "",
9373
+ filename: api.filename || options.filename,
9374
+ sourceType: api.source_type || sourceType,
9375
+ sourceUrl: api.source_url ?? options.url ?? null,
9376
+ contentType: api.content_type ?? options.file?.contentType ?? null,
9377
+ fileSize: api.file_size ?? null,
9378
+ status: api.status || "pending",
9379
+ errorMessage: api.error_message ?? null,
9380
+ processingStartedAt: api.processing_started_at ?? null,
9381
+ processingCompletedAt: api.processing_completed_at ?? null,
9382
+ chunkCount: api.chunk_count ?? 0,
9383
+ tokenCount: api.token_count ?? null,
9384
+ metadata: api.metadata || options.metadata || {},
9385
+ createdAt: api.created_at || (/* @__PURE__ */ new Date()).toISOString(),
9386
+ updatedAt: api.updated_at || api.created_at || (/* @__PURE__ */ new Date()).toISOString()
9387
+ };
9388
+ }
9389
+ function convertSearchResult(api) {
9390
+ return {
9391
+ chunkId: api.chunk_id,
9392
+ documentId: api.document_id,
9393
+ filename: api.filename,
9394
+ content: api.content,
9395
+ score: api.score,
9396
+ chunkIndex: api.chunk_index,
9397
+ metadata: api.metadata
9398
+ };
9399
+ }
9400
+ function convertSearchResponse(api) {
9401
+ return {
9402
+ results: api.results.map(convertSearchResult),
9403
+ query: api.query,
9404
+ collectionId: api.collection_id,
9405
+ totalResults: api.total_results
9406
+ };
9407
+ }
9408
+ function convertAISearchSource(api) {
9409
+ return {
9410
+ documentId: api.document_id,
9411
+ filename: api.filename,
9412
+ chunkId: api.chunk_id,
9413
+ excerpt: api.excerpt,
9414
+ score: api.score
9415
+ };
9416
+ }
9417
+ function convertAISearchResult(api) {
9418
+ return {
9419
+ answer: api.answer,
9420
+ sources: api.sources.map(convertAISearchSource),
9421
+ query: api.query,
9422
+ model: api.model,
9423
+ usage: {
9424
+ inputTokens: api.usage.input_tokens,
9425
+ outputTokens: api.usage.output_tokens
9426
+ }
9427
+ };
9428
+ }
9429
+ var BlinkRAGImpl = class {
9430
+ constructor(httpClient) {
9431
+ this.httpClient = httpClient;
9432
+ this.projectId = httpClient.projectId;
9433
+ }
9434
+ projectId;
9435
+ /**
9436
+ * Build URL with project_id prefix
9437
+ */
9438
+ url(path) {
9439
+ return `/api/rag/${this.projectId}${path}`;
9440
+ }
9441
+ // ============================================================================
9442
+ // Collections
9443
+ // ============================================================================
9444
+ /**
9445
+ * Create a new RAG collection
9446
+ */
9447
+ async createCollection(options) {
9448
+ const body = removeUndefined({
9449
+ name: options.name,
9450
+ description: options.description,
9451
+ embedding_model: options.embeddingModel,
9452
+ embedding_dimensions: options.embeddingDimensions,
9453
+ index_metric: options.indexMetric,
9454
+ chunk_max_tokens: options.chunkMaxTokens,
9455
+ chunk_overlap_tokens: options.chunkOverlapTokens,
9456
+ shared: options.shared
9457
+ });
9458
+ const response = await this.httpClient.post(this.url("/collections"), body);
9459
+ return convertCollection(response.data);
9460
+ }
9461
+ /**
9462
+ * List all collections accessible to the current user
9463
+ */
9464
+ async listCollections() {
9465
+ const response = await this.httpClient.get(this.url("/collections"));
9466
+ return response.data.collections.map(convertCollection);
9467
+ }
9468
+ /**
9469
+ * Get a specific collection by ID
9470
+ */
9471
+ async getCollection(collectionId) {
9472
+ const response = await this.httpClient.get(this.url(`/collections/${collectionId}`));
9473
+ return convertCollection(response.data);
9474
+ }
9475
+ /**
9476
+ * Delete a collection and all its documents
9477
+ */
9478
+ async deleteCollection(collectionId) {
9479
+ await this.httpClient.delete(this.url(`/collections/${collectionId}`));
9480
+ }
9481
+ // ============================================================================
9482
+ // Documents
9483
+ // ============================================================================
9484
+ /**
9485
+ * Upload a document for processing
9486
+ *
9487
+ * @example
9488
+ * // Upload text content
9489
+ * const doc = await blink.rag.upload({
9490
+ * collectionName: 'docs',
9491
+ * filename: 'notes.txt',
9492
+ * content: 'My document content...'
9493
+ * })
9494
+ *
9495
+ * @example
9496
+ * // Upload from URL
9497
+ * const doc = await blink.rag.upload({
9498
+ * collectionId: 'col_abc123',
9499
+ * filename: 'article.html',
9500
+ * url: 'https://example.com/article'
9501
+ * })
9502
+ *
9503
+ * @example
9504
+ * // Upload a file (base64)
9505
+ * const doc = await blink.rag.upload({
9506
+ * collectionName: 'docs',
9507
+ * filename: 'report.pdf',
9508
+ * file: { data: base64Data, contentType: 'application/pdf' }
9509
+ * })
9510
+ */
9511
+ async upload(options) {
9512
+ if (!options.collectionId && !options.collectionName) {
9513
+ throw new Error("collectionId or collectionName is required");
9514
+ }
9515
+ const body = removeUndefined({
9516
+ collection_id: options.collectionId,
9517
+ collection_name: options.collectionName,
9518
+ filename: options.filename,
9519
+ content: options.content,
9520
+ url: options.url,
9521
+ metadata: options.metadata
9522
+ });
9523
+ if (options.file) {
9524
+ body.file = {
9525
+ data: options.file.data,
9526
+ content_type: options.file.contentType
9527
+ };
9528
+ }
9529
+ const response = await this.httpClient.post(this.url("/documents"), body);
9530
+ return convertPartialDocument(response.data, options);
9531
+ }
9532
+ /**
9533
+ * Get document status and metadata
9534
+ */
9535
+ async getDocument(documentId) {
9536
+ const response = await this.httpClient.get(this.url(`/documents/${documentId}`));
9537
+ return convertDocument(response.data);
9538
+ }
9539
+ /**
9540
+ * List documents, optionally filtered by collection or status
9541
+ */
9542
+ async listDocuments(options) {
9543
+ const params = {};
9544
+ if (options?.collectionId) params.collection_id = options.collectionId;
9545
+ if (options?.status) params.status = options.status;
9546
+ const queryString = Object.keys(params).length > 0 ? `?${new URLSearchParams(params).toString()}` : "";
9547
+ const response = await this.httpClient.get(
9548
+ this.url(`/documents${queryString}`)
9549
+ );
9550
+ return response.data.documents.map(convertDocument);
9551
+ }
9552
+ /**
9553
+ * Delete a document and its chunks
9554
+ */
9555
+ async deleteDocument(documentId) {
9556
+ await this.httpClient.delete(this.url(`/documents/${documentId}`));
9557
+ }
9558
+ /**
9559
+ * Wait for a document to finish processing
9560
+ *
9561
+ * @example
9562
+ * const doc = await blink.rag.upload({ ... })
9563
+ * const readyDoc = await blink.rag.waitForReady(doc.id)
9564
+ * console.log(`Processed ${readyDoc.chunkCount} chunks`)
9565
+ */
9566
+ async waitForReady(documentId, options) {
9567
+ const { timeoutMs = 12e4, pollIntervalMs = 2e3 } = options || {};
9568
+ const start = Date.now();
9569
+ while (Date.now() - start < timeoutMs) {
9570
+ const doc = await this.getDocument(documentId);
9571
+ if (doc.status === "ready") {
9572
+ return doc;
9573
+ }
9574
+ if (doc.status === "error") {
9575
+ throw new Error(`Document processing failed: ${doc.errorMessage}`);
9576
+ }
9577
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
9578
+ }
9579
+ throw new Error(`Document processing timeout after ${timeoutMs}ms`);
9580
+ }
9581
+ // ============================================================================
9582
+ // Search
9583
+ // ============================================================================
9584
+ /**
9585
+ * Search for similar chunks using vector similarity
9586
+ *
9587
+ * @example
9588
+ * const results = await blink.rag.search({
9589
+ * collectionName: 'docs',
9590
+ * query: 'How do I configure authentication?',
9591
+ * maxResults: 5
9592
+ * })
9593
+ */
9594
+ async search(options) {
9595
+ if (!options.collectionId && !options.collectionName) {
9596
+ throw new Error("collectionId or collectionName is required");
9597
+ }
9598
+ const body = removeUndefined({
9599
+ collection_id: options.collectionId,
9600
+ collection_name: options.collectionName,
9601
+ query: options.query,
9602
+ max_results: options.maxResults,
9603
+ score_threshold: options.scoreThreshold,
9604
+ filters: options.filters,
9605
+ include_content: options.includeContent
9606
+ });
9607
+ const response = await this.httpClient.post(this.url("/search"), body);
9608
+ return convertSearchResponse(response.data);
9609
+ }
9610
+ async aiSearch(options) {
9611
+ if (!options.collectionId && !options.collectionName) {
9612
+ throw new Error("collectionId or collectionName is required");
9613
+ }
9614
+ const body = removeUndefined({
9615
+ collection_id: options.collectionId,
9616
+ collection_name: options.collectionName,
9617
+ query: options.query,
9618
+ model: options.model,
9619
+ max_context_chunks: options.maxContextChunks,
9620
+ score_threshold: options.scoreThreshold,
9621
+ system_prompt: options.systemPrompt,
9622
+ stream: options.stream
9623
+ });
9624
+ if (options.stream) {
9625
+ throw new Error("Streaming not yet supported in SDK. Use stream: false or call API directly.");
9626
+ }
9627
+ const response = await this.httpClient.post(this.url("/ai-search"), body);
9628
+ return convertAISearchResult(response.data);
9629
+ }
9630
+ };
9631
+
9632
+ // src/sandbox.ts
9633
+ var SANDBOX_TEMPLATES = [
9634
+ "devtools-base",
9635
+ // Node 22 + Bun + Python + Git + ripgrep (DEFAULT)
9636
+ "nextjs-app",
9637
+ // Next.js + Tailwind + shadcn UI (Node)
9638
+ "nextjs-app-bun",
9639
+ // Next.js + Tailwind + shadcn UI (Bun)
9640
+ "vite-react",
9641
+ // Vite + React + Tailwind + shadcn (Node)
9642
+ "vite-react-bun",
9643
+ // Vite + React + Tailwind + shadcn (Bun)
9644
+ "expo-app",
9645
+ // Expo + React Native
9646
+ "desktop",
9647
+ // Electron + Vite + React
9648
+ "claude-code"
9649
+ // Node 21 + Python + Git + ripgrep
9650
+ ];
9651
+ var SandboxConnectionError = class extends Error {
9652
+ sandboxId;
9653
+ constructor(sandboxId, cause) {
9654
+ super(`Failed to connect to sandbox ${sandboxId}`);
9655
+ this.name = "SandboxConnectionError";
9656
+ this.sandboxId = sandboxId;
9657
+ if (cause) {
9658
+ this.cause = cause;
9659
+ }
9660
+ }
9661
+ };
9662
+ var SandboxImpl = class {
9663
+ constructor(id, template, hostPattern) {
9664
+ this.id = id;
9665
+ this.template = template;
9666
+ this.hostPattern = hostPattern;
9667
+ }
9668
+ getHost(port) {
9669
+ return this.hostPattern.replace("{port}", String(port));
9670
+ }
9671
+ };
9672
+ var MAX_RETRIES = 3;
9673
+ var INITIAL_RETRY_DELAY_MS = 250;
9674
+ var BlinkSandboxImpl = class {
9675
+ constructor(httpClient) {
9676
+ this.httpClient = httpClient;
9677
+ this.projectId = httpClient.projectId;
9678
+ }
9679
+ projectId;
9680
+ /**
9681
+ * Build URL with project_id prefix
9682
+ */
9683
+ url(path) {
9684
+ return `/api/sandbox/${this.projectId}${path}`;
9685
+ }
9686
+ async create(options = {}) {
9687
+ const body = {
9688
+ template: options.template,
9689
+ timeout_ms: options.timeoutMs,
9690
+ metadata: options.metadata
9691
+ };
9692
+ const response = await this.httpClient.post(this.url("/create"), body);
9693
+ const { id, template, host_pattern } = response.data;
9694
+ return new SandboxImpl(id, template, host_pattern);
9695
+ }
9696
+ async connect(sandboxId, options = {}) {
9697
+ let lastError;
9698
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
9699
+ try {
9700
+ const body = {
9701
+ sandbox_id: sandboxId,
9702
+ timeout_ms: options.timeoutMs
9703
+ };
9704
+ const response = await this.httpClient.post(this.url("/connect"), body);
9705
+ const { id, template, host_pattern } = response.data;
9706
+ return new SandboxImpl(id, template, host_pattern);
9707
+ } catch (error) {
9708
+ console.error(`[Sandbox] Connect attempt ${attempt + 1} failed:`, error);
9709
+ lastError = error instanceof Error ? error : new Error(String(error));
9710
+ if (lastError.message.includes("404") || lastError.message.includes("not found") || lastError.message.includes("unauthorized")) {
9711
+ throw new SandboxConnectionError(sandboxId, lastError);
9712
+ }
9713
+ if (attempt < MAX_RETRIES - 1) {
9714
+ const delay = INITIAL_RETRY_DELAY_MS * Math.pow(2, attempt);
9715
+ await new Promise((resolve) => setTimeout(resolve, delay));
9716
+ }
9717
+ }
9718
+ }
9719
+ console.error(`[Sandbox] All ${MAX_RETRIES} connection attempts failed for sandbox ${sandboxId}`);
9720
+ throw new SandboxConnectionError(sandboxId, lastError);
9721
+ }
9722
+ async kill(sandboxId) {
9723
+ await this.httpClient.post(this.url("/kill"), { sandbox_id: sandboxId });
9724
+ }
9725
+ };
9726
+
5705
9727
  // src/client.ts
5706
9728
  var BlinkClientImpl = class {
5707
9729
  auth;
@@ -5712,7 +9734,10 @@ var BlinkClientImpl = class {
5712
9734
  realtime;
5713
9735
  notifications;
5714
9736
  analytics;
9737
+ connectors;
5715
9738
  functions;
9739
+ rag;
9740
+ sandbox;
5716
9741
  httpClient;
5717
9742
  constructor(config) {
5718
9743
  if ((config.secretKey || config.serviceToken) && isBrowser) {
@@ -5731,11 +9756,14 @@ var BlinkClientImpl = class {
5731
9756
  this.realtime = new BlinkRealtimeImpl(this.httpClient, config.projectId);
5732
9757
  this.notifications = new BlinkNotificationsImpl(this.httpClient);
5733
9758
  this.analytics = new BlinkAnalyticsImpl(this.httpClient, config.projectId);
9759
+ this.connectors = new BlinkConnectorsImpl(this.httpClient);
5734
9760
  this.functions = new BlinkFunctionsImpl(
5735
9761
  this.httpClient,
5736
9762
  config.projectId,
5737
9763
  () => this.auth.getValidToken()
5738
9764
  );
9765
+ this.rag = new BlinkRAGImpl(this.httpClient);
9766
+ this.sandbox = new BlinkSandboxImpl(this.httpClient);
5739
9767
  this.auth.onAuthStateChanged((state) => {
5740
9768
  if (state.isAuthenticated && state.user) {
5741
9769
  this.analytics.setUserId(state.user.id);
@@ -5754,25 +9782,61 @@ function createClient(config) {
5754
9782
  return new BlinkClientImpl(config);
5755
9783
  }
5756
9784
 
9785
+ exports.Agent = Agent;
5757
9786
  exports.AsyncStorageAdapter = AsyncStorageAdapter;
5758
9787
  exports.BlinkAIImpl = BlinkAIImpl;
5759
9788
  exports.BlinkAnalyticsImpl = BlinkAnalyticsImpl;
9789
+ exports.BlinkConnectorsImpl = BlinkConnectorsImpl;
5760
9790
  exports.BlinkDataImpl = BlinkDataImpl;
5761
9791
  exports.BlinkDatabase = BlinkDatabase;
9792
+ exports.BlinkRAGImpl = BlinkRAGImpl;
5762
9793
  exports.BlinkRealtimeChannel = BlinkRealtimeChannel;
5763
9794
  exports.BlinkRealtimeImpl = BlinkRealtimeImpl;
9795
+ exports.BlinkSandboxImpl = BlinkSandboxImpl;
5764
9796
  exports.BlinkStorageImpl = BlinkStorageImpl;
5765
9797
  exports.BlinkTable = BlinkTable;
5766
9798
  exports.NoOpStorageAdapter = NoOpStorageAdapter;
9799
+ exports.SANDBOX_TEMPLATES = SANDBOX_TEMPLATES;
9800
+ exports.SandboxConnectionError = SandboxConnectionError;
5767
9801
  exports.WebStorageAdapter = WebStorageAdapter;
5768
9802
  exports.createClient = createClient;
9803
+ exports.dbDelete = dbDelete;
9804
+ exports.dbGet = dbGet;
9805
+ exports.dbInsert = dbInsert;
9806
+ exports.dbList = dbList;
9807
+ exports.dbTools = dbTools;
9808
+ exports.dbUpdate = dbUpdate;
9809
+ exports.fetchUrl = fetchUrl;
5769
9810
  exports.getDefaultStorageAdapter = getDefaultStorageAdapter;
9811
+ exports.getHost = getHost;
9812
+ exports.globFileSearch = globFileSearch;
9813
+ exports.grep = grep;
5770
9814
  exports.isBrowser = isBrowser;
5771
9815
  exports.isDeno = isDeno;
5772
9816
  exports.isNode = isNode;
5773
9817
  exports.isReactNative = isReactNative;
5774
9818
  exports.isServer = isServer;
5775
9819
  exports.isWeb = isWeb;
9820
+ exports.listDir = listDir;
5776
9821
  exports.platform = platform;
9822
+ exports.ragSearch = ragSearch;
9823
+ exports.ragTools = ragTools;
9824
+ exports.readFile = readFile;
9825
+ exports.runCode = runCode;
9826
+ exports.runTerminalCmd = runTerminalCmd;
9827
+ exports.sandboxTools = sandboxTools;
9828
+ exports.searchReplace = searchReplace;
9829
+ exports.serializeTools = serializeTools;
9830
+ exports.stepCountIs = stepCountIs;
9831
+ exports.storageCopy = storageCopy;
9832
+ exports.storageDelete = storageDelete;
9833
+ exports.storageDownload = storageDownload;
9834
+ exports.storageList = storageList;
9835
+ exports.storageMove = storageMove;
9836
+ exports.storagePublicUrl = storagePublicUrl;
9837
+ exports.storageTools = storageTools;
9838
+ exports.storageUpload = storageUpload;
9839
+ exports.webSearch = webSearch;
9840
+ exports.writeFile = writeFile;
5777
9841
  //# sourceMappingURL=index.js.map
5778
9842
  //# sourceMappingURL=index.js.map