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