vitest 1.3.0 → 1.3.1

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