@blinkdotnew/sdk 2.2.1 → 2.3.0

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