peachsim 0.1.2441 → 0.1.2457

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 (170) hide show
  1. package/README.md +4 -49
  2. package/cli/app-catalog.ts +8 -7
  3. package/cli/app-stubs.ts +98 -70
  4. package/cli/cloud-box-artifact.ts +2 -5
  5. package/cli/cloud-client.ts +12 -1
  6. package/cli/commands/box.ts +41 -2
  7. package/cli/commands/compat.ts +5 -3
  8. package/cli/commands/cpu-profile.ts +11 -14
  9. package/cli/commands/diagnose.ts +5 -18
  10. package/cli/commands/inspect/describe.ts +4 -8
  11. package/cli/commands/maestro-generate.ts +4 -8
  12. package/cli/commands/mode.ts +3 -19
  13. package/cli/commands/perf.ts +3 -19
  14. package/cli/commands/permissions.ts +2 -6
  15. package/cli/commands/platform.ts +22 -14
  16. package/cli/commands/react.ts +7 -21
  17. package/cli/commands/record-three.ts +6 -10
  18. package/cli/commands/record.ts +38 -62
  19. package/cli/commands/screenshot-command.ts +8 -25
  20. package/cli/commands/storage.ts +4 -16
  21. package/cli/commands/three-mode.ts +6 -10
  22. package/cli/outbound-endpoints.ts +4 -5
  23. package/cli/parse-args.ts +45 -0
  24. package/cli/remote-metro.ts +1 -1
  25. package/cli/remote-simulators.ts +5 -1
  26. package/cli/send-to-box.ts +3 -1
  27. package/detox/index.ts +20 -1
  28. package/dist-lib/agent-daemon-client.cjs +2 -2
  29. package/dist-lib/agent-events.cjs +1 -1
  30. package/dist-lib/attached-projects.cjs +1 -1
  31. package/dist-lib/auth/shared-session.cjs +1 -1
  32. package/dist-lib/backend-origin.cjs +1 -1
  33. package/dist-lib/beta.cjs +1 -1
  34. package/dist-lib/beta.mjs +2 -2
  35. package/dist-lib/bridge-constants.cjs +1 -1
  36. package/dist-lib/bridge-contract-input.cjs +1 -1
  37. package/dist-lib/bridge-contract-input.mjs +5 -5
  38. package/dist-lib/bridge-contract.cjs +1 -1
  39. package/dist-lib/bridge-contract.mjs +3 -3
  40. package/dist-lib/bundle-channel.cjs +240 -316
  41. package/dist-lib/capture-contract.cjs +1 -1
  42. package/dist-lib/capture-contract.mjs +3 -3
  43. package/dist-lib/cloud-contract.cjs +14 -1
  44. package/dist-lib/cloud-contract.mjs +5 -3
  45. package/dist-lib/cloud-test-args.cjs +1 -1
  46. package/dist-lib/cloud-test-args.mjs +2 -2
  47. package/dist-lib/cloud.cjs +1 -1
  48. package/dist-lib/cloud.mjs +7 -7
  49. package/dist-lib/config.cjs +1 -6
  50. package/dist-lib/config.mjs +5 -9
  51. package/dist-lib/detox/index.cjs +17 -5
  52. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  53. package/dist-lib/esm-chunks/{acorn-FRQNHKFC.mjs → acorn-73XUBXBT.mjs} +3 -3
  54. package/dist-lib/esm-chunks/{chunk-IRMC5BCX.mjs → chunk-7V2QJGVI.mjs} +1 -1
  55. package/dist-lib/esm-chunks/{chunk-PMGJ7FLI.mjs → chunk-BHQEYJAF.mjs} +1 -1
  56. package/dist-lib/esm-chunks/{chunk-BAYRN7ZL.mjs → chunk-DSPFMVBM.mjs} +1 -1
  57. package/dist-lib/esm-chunks/{chunk-4HEUXQGM.mjs → chunk-GA73RJSG.mjs} +4 -4
  58. package/dist-lib/esm-chunks/{chunk-ABMB3G7I.mjs → chunk-IGBAFWZ3.mjs} +3 -3
  59. package/dist-lib/esm-chunks/{chunk-ZCMAKWHN.mjs → chunk-IKZDUGT6.mjs} +1 -1
  60. package/dist-lib/esm-chunks/{chunk-VAQJQDWI.mjs → chunk-IP5ZV36U.mjs} +1 -1
  61. package/dist-lib/esm-chunks/{chunk-O4EOBXAP.mjs → chunk-KGHQ4GK2.mjs} +1 -1
  62. package/dist-lib/esm-chunks/{chunk-4BZ3Z3IQ.mjs → chunk-KY63O76W.mjs} +2 -2
  63. package/dist-lib/esm-chunks/{chunk-QYYJESMK.mjs → chunk-LJ74MO6Y.mjs} +1 -1
  64. package/dist-lib/esm-chunks/{chunk-DJMWTW2B.mjs → chunk-LJX42YVT.mjs} +1 -1
  65. package/dist-lib/esm-chunks/{chunk-XO5GX4PI.mjs → chunk-O4KAW2JJ.mjs} +1 -1
  66. package/dist-lib/esm-chunks/{chunk-6A6JEVIF.mjs → chunk-OIFM356B.mjs} +1 -1
  67. package/dist-lib/esm-chunks/{chunk-NPLEBOWJ.mjs → chunk-P63DPATT.mjs} +1 -1
  68. package/dist-lib/esm-chunks/{chunk-VCAJFWZD.mjs → chunk-SCCOZKCP.mjs} +1 -1
  69. package/dist-lib/esm-chunks/{chunk-QUBR7LHU.mjs → chunk-TAZL253K.mjs} +41 -15
  70. package/dist-lib/esm-chunks/{chunk-ORYS5CC4.mjs → chunk-UBXCWZL3.mjs} +1 -1
  71. package/dist-lib/esm-chunks/{chunk-4ZRMJ5YO.mjs → chunk-ZQWWO33G.mjs} +14 -2
  72. package/dist-lib/esm-chunks/{metro-layout-parser-AUAVE5VL.mjs → metro-layout-parser-HNQRTPVE.mjs} +3 -3
  73. package/dist-lib/expo-swift-bundle.cjs +197 -336
  74. package/dist-lib/expo-swift-metadata.cjs +1 -1
  75. package/dist-lib/expo-swift-metadata.mjs +7 -7
  76. package/dist-lib/home-paths.cjs +1 -1
  77. package/dist-lib/host/bridge-host.cjs +276 -381
  78. package/dist-lib/host/fetch-proxy-handler.cjs +35 -43
  79. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  80. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  81. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  82. package/dist-lib/host/websocket-proxy.cjs +4 -2
  83. package/dist-lib/index.cjs +2 -105
  84. package/dist-lib/kotlin-host.cjs +6 -4
  85. package/dist-lib/menu.cjs +1 -1
  86. package/dist-lib/menu.mjs +3 -3
  87. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  88. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  89. package/dist-lib/metro-production-bundle.cjs +1 -1
  90. package/dist-lib/metro-production-bundle.mjs +4 -4
  91. package/dist-lib/native-app-identity-project.cjs +2 -2
  92. package/dist-lib/native-app-identity-project.mjs +12 -12
  93. package/dist-lib/native-app-identity.cjs +1 -1
  94. package/dist-lib/native-app-identity.mjs +6 -6
  95. package/dist-lib/native-firebase-metadata.cjs +1 -1
  96. package/dist-lib/native-firebase-metadata.mjs +3 -3
  97. package/dist-lib/pdfium-raster.cjs +1 -1
  98. package/dist-lib/pdfium-raster.mjs +2 -2
  99. package/dist-lib/plist.cjs +1 -1
  100. package/dist-lib/plist.mjs +3 -3
  101. package/dist-lib/profiles.cjs +1 -1
  102. package/dist-lib/public-brand.cjs +1 -1
  103. package/dist-lib/public-origins-lib-esm.json +64 -64
  104. package/dist-lib/public-origins-lib-static.json +1 -1
  105. package/dist-lib/public-origins-lib.json +107 -85
  106. package/dist-lib/react-native-host-modules.cjs +1 -1
  107. package/dist-lib/react-native-host-modules.mjs +2 -2
  108. package/dist-lib/reap-browser.cjs +1 -1
  109. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  110. package/dist-lib/sdk.cjs +1 -1
  111. package/dist-lib/sdk.mjs +7 -7
  112. package/dist-lib/skills.cjs +310 -310
  113. package/dist-lib/swift-compile.cjs +37 -11
  114. package/dist-lib/swift-compile.mjs +8 -8
  115. package/dist-lib/swift-package.cjs +1 -1
  116. package/dist-lib/swift-package.mjs +3 -3
  117. package/dist-lib/swift-submit.cjs +1 -1
  118. package/dist-lib/swift-submit.mjs +5 -5
  119. package/dist-lib/swift-toolchain.cjs +1 -1
  120. package/dist-lib/swift.cjs +1 -1
  121. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  122. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +14770 -0
  123. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +2790 -0
  124. package/dist-lib/vendor/acorn.cjs +1 -1
  125. package/dist-lib/vendor/bplist-parser.cjs +1 -1
  126. package/dist-lib/vendor/ignore.cjs +1 -1
  127. package/dist-lib/vendor/magic-string.cjs +1 -1
  128. package/dist-lib/vendor/plist.cjs +1 -1
  129. package/dist-lib/vendor/prism.wasm +0 -0
  130. package/dist-lib/vendor/smol-toml.cjs +1 -1
  131. package/dist-lib/vendor/stream-json.cjs +1 -1
  132. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  133. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  134. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  135. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  136. package/dist-lib/vendor/sucrase.cjs +1 -1
  137. package/dist-lib/vendor/terser.cjs +1 -1
  138. package/dist-lib/vendor/valibot.cjs +1 -1
  139. package/dist-lib/vendor/ws.cjs +3710 -0
  140. package/dist-lib/vendor/zod.cjs +1 -1
  141. package/dist-lib/worklet-executable.cjs +1 -1
  142. package/dist-lib/worklet-executable.mjs +3 -3
  143. package/dist-types/packages/peach-compat/src/stubs/native-seams/react-native-gesture-handler.d.ts +0 -3
  144. package/dist-types/packages/peach-engine/src/config.d.ts +1 -1
  145. package/dist-types/packages/peach-engine/src/engine/scene-table.d.ts +1 -0
  146. package/dist-types/packages/peach-engine/src/engine/text-line-break.d.ts +3 -1
  147. package/dist-types/packages/peach-engine/src/engine/text-paint.d.ts +1 -0
  148. package/dist-types/packages/peach-engine/src/engine/text-runs.d.ts +6 -1
  149. package/kotlin/sdk.tar.gz +0 -0
  150. package/package.json +22 -14
  151. package/skills/peach-setup/references/native-config.md +3 -3
  152. package/src/app-config.ts +7 -15
  153. package/src/cloud-contract.ts +35 -0
  154. package/src/config.ts +2 -6
  155. package/src/estree-walk.ts +13 -0
  156. package/src/host/network-policy.ts +4 -1
  157. package/src/index.ts +0 -1
  158. package/src/one-native-app-config.ts +14 -15
  159. package/src/podspec-prism.ts +7 -1
  160. package/src/process-group.ts +4 -1
  161. package/src/process-table.ts +6 -1
  162. package/src/swift-compile.ts +38 -8
  163. package/src/swift-host.ts +10 -4
  164. package/cli/commands/box/bundle-plane.ts +0 -154
  165. package/dist-lib/jump-to-source-babel.cjs +0 -131
  166. package/dist-lib/jump-to-source-native.cjs +0 -235
  167. package/src/java-static-imports.ts +0 -68
  168. package/src/jump-to-source-babel.ts +0 -143
  169. package/src/jump-to-source-native.ts +0 -200
  170. package/src/kotlin-jvm-sources.ts +0 -35
@@ -0,0 +1,3710 @@
1
+ /*! peach v0.1.2457 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
2
+ let __sootsim_import_meta_url = '', __sootsim_import_meta_dirname = '', __sootsim_import_meta_filename = ''; try { __sootsim_import_meta_url = require('url').pathToFileURL(__filename).href; __sootsim_import_meta_dirname = __dirname; __sootsim_import_meta_filename = __filename; } catch {}
3
+ "use strict";
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __commonJS = (cb, mod) => function __require() {
6
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
7
+ };
8
+
9
+ // ../../node_modules/ws/lib/constants.js
10
+ var require_constants = __commonJS({
11
+ "../../node_modules/ws/lib/constants.js"(exports2, module2) {
12
+ "use strict";
13
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
14
+ var hasBlob = typeof Blob !== "undefined";
15
+ if (hasBlob) BINARY_TYPES.push("blob");
16
+ module2.exports = {
17
+ BINARY_TYPES,
18
+ CLOSE_TIMEOUT: 3e4,
19
+ EMPTY_BUFFER: Buffer.alloc(0),
20
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
21
+ hasBlob,
22
+ kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
23
+ kListener: Symbol("kListener"),
24
+ kStatusCode: Symbol("status-code"),
25
+ kWebSocket: Symbol("websocket"),
26
+ NOOP: () => {
27
+ }
28
+ };
29
+ }
30
+ });
31
+
32
+ // ../../node_modules/ws/lib/buffer-util.js
33
+ var require_buffer_util = __commonJS({
34
+ "../../node_modules/ws/lib/buffer-util.js"(exports2, module2) {
35
+ "use strict";
36
+ var { EMPTY_BUFFER } = require_constants();
37
+ var FastBuffer = Buffer[Symbol.species];
38
+ function concat(list, totalLength) {
39
+ if (list.length === 0) return EMPTY_BUFFER;
40
+ if (list.length === 1) return list[0];
41
+ const target = Buffer.allocUnsafe(totalLength);
42
+ let offset = 0;
43
+ for (let i = 0; i < list.length; i++) {
44
+ const buf = list[i];
45
+ target.set(buf, offset);
46
+ offset += buf.length;
47
+ }
48
+ if (offset < totalLength) {
49
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
50
+ }
51
+ return target;
52
+ }
53
+ function _mask(source, mask, output, offset, length) {
54
+ for (let i = 0; i < length; i++) {
55
+ output[offset + i] = source[i] ^ mask[i & 3];
56
+ }
57
+ }
58
+ function _unmask(buffer, mask) {
59
+ for (let i = 0; i < buffer.length; i++) {
60
+ buffer[i] ^= mask[i & 3];
61
+ }
62
+ }
63
+ function toArrayBuffer(buf) {
64
+ if (buf.length === buf.buffer.byteLength) {
65
+ return buf.buffer;
66
+ }
67
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
68
+ }
69
+ function toBuffer(data) {
70
+ toBuffer.readOnly = true;
71
+ if (Buffer.isBuffer(data)) return data;
72
+ let buf;
73
+ if (data instanceof ArrayBuffer) {
74
+ buf = new FastBuffer(data);
75
+ } else if (ArrayBuffer.isView(data)) {
76
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
77
+ } else {
78
+ buf = Buffer.from(data);
79
+ toBuffer.readOnly = false;
80
+ }
81
+ return buf;
82
+ }
83
+ module2.exports = {
84
+ concat,
85
+ mask: _mask,
86
+ toArrayBuffer,
87
+ toBuffer,
88
+ unmask: _unmask
89
+ };
90
+ if (!process.env.WS_NO_BUFFER_UTIL) {
91
+ try {
92
+ const bufferUtil = require("bufferutil");
93
+ module2.exports.mask = function(source, mask, output, offset, length) {
94
+ if (length < 48) _mask(source, mask, output, offset, length);
95
+ else bufferUtil.mask(source, mask, output, offset, length);
96
+ };
97
+ module2.exports.unmask = function(buffer, mask) {
98
+ if (buffer.length < 32) _unmask(buffer, mask);
99
+ else bufferUtil.unmask(buffer, mask);
100
+ };
101
+ } catch (e) {
102
+ }
103
+ }
104
+ }
105
+ });
106
+
107
+ // ../../node_modules/ws/lib/limiter.js
108
+ var require_limiter = __commonJS({
109
+ "../../node_modules/ws/lib/limiter.js"(exports2, module2) {
110
+ "use strict";
111
+ var kDone = Symbol("kDone");
112
+ var kRun = Symbol("kRun");
113
+ var Limiter = class {
114
+ /**
115
+ * Creates a new `Limiter`.
116
+ *
117
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
118
+ * to run concurrently
119
+ */
120
+ constructor(concurrency) {
121
+ this[kDone] = () => {
122
+ this.pending--;
123
+ this[kRun]();
124
+ };
125
+ this.concurrency = concurrency || Infinity;
126
+ this.jobs = [];
127
+ this.pending = 0;
128
+ }
129
+ /**
130
+ * Adds a job to the queue.
131
+ *
132
+ * @param {Function} job The job to run
133
+ * @public
134
+ */
135
+ add(job) {
136
+ this.jobs.push(job);
137
+ this[kRun]();
138
+ }
139
+ /**
140
+ * Removes a job from the queue and runs it if possible.
141
+ *
142
+ * @private
143
+ */
144
+ [kRun]() {
145
+ if (this.pending === this.concurrency) return;
146
+ if (this.jobs.length) {
147
+ const job = this.jobs.shift();
148
+ this.pending++;
149
+ job(this[kDone]);
150
+ }
151
+ }
152
+ };
153
+ module2.exports = Limiter;
154
+ }
155
+ });
156
+
157
+ // ../../node_modules/ws/lib/permessage-deflate.js
158
+ var require_permessage_deflate = __commonJS({
159
+ "../../node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
160
+ "use strict";
161
+ var zlib = require("zlib");
162
+ var bufferUtil = require_buffer_util();
163
+ var Limiter = require_limiter();
164
+ var { kStatusCode } = require_constants();
165
+ var FastBuffer = Buffer[Symbol.species];
166
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
167
+ var kPerMessageDeflate = Symbol("permessage-deflate");
168
+ var kTotalLength = Symbol("total-length");
169
+ var kCallback = Symbol("callback");
170
+ var kBuffers = Symbol("buffers");
171
+ var kError = Symbol("error");
172
+ var zlibLimiter;
173
+ var PerMessageDeflate2 = class {
174
+ /**
175
+ * Creates a PerMessageDeflate instance.
176
+ *
177
+ * @param {Object} [options] Configuration options
178
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
179
+ * for, or request, a custom client window size
180
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
181
+ * acknowledge disabling of client context takeover
182
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
183
+ * calls to zlib
184
+ * @param {Boolean} [options.isServer=false] Create the instance in either
185
+ * server or client mode
186
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
187
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
188
+ * use of a custom server window size
189
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
190
+ * disabling of server context takeover
191
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
192
+ * messages should not be compressed if context takeover is disabled
193
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
194
+ * deflate
195
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
196
+ * inflate
197
+ */
198
+ constructor(options) {
199
+ this._options = options || {};
200
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
201
+ this._maxPayload = this._options.maxPayload | 0;
202
+ this._isServer = !!this._options.isServer;
203
+ this._deflate = null;
204
+ this._inflate = null;
205
+ this.params = null;
206
+ if (!zlibLimiter) {
207
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
208
+ zlibLimiter = new Limiter(concurrency);
209
+ }
210
+ }
211
+ /**
212
+ * @type {String}
213
+ */
214
+ static get extensionName() {
215
+ return "permessage-deflate";
216
+ }
217
+ /**
218
+ * Create an extension negotiation offer.
219
+ *
220
+ * @return {Object} Extension parameters
221
+ * @public
222
+ */
223
+ offer() {
224
+ const params = {};
225
+ if (this._options.serverNoContextTakeover) {
226
+ params.server_no_context_takeover = true;
227
+ }
228
+ if (this._options.clientNoContextTakeover) {
229
+ params.client_no_context_takeover = true;
230
+ }
231
+ if (this._options.serverMaxWindowBits) {
232
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
233
+ }
234
+ if (this._options.clientMaxWindowBits) {
235
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
236
+ } else if (this._options.clientMaxWindowBits == null) {
237
+ params.client_max_window_bits = true;
238
+ }
239
+ return params;
240
+ }
241
+ /**
242
+ * Accept an extension negotiation offer/response.
243
+ *
244
+ * @param {Array} configurations The extension negotiation offers/reponse
245
+ * @return {Object} Accepted configuration
246
+ * @public
247
+ */
248
+ accept(configurations) {
249
+ configurations = this.normalizeParams(configurations);
250
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
251
+ return this.params;
252
+ }
253
+ /**
254
+ * Releases all resources used by the extension.
255
+ *
256
+ * @public
257
+ */
258
+ cleanup() {
259
+ if (this._inflate) {
260
+ this._inflate.close();
261
+ this._inflate = null;
262
+ }
263
+ if (this._deflate) {
264
+ const callback = this._deflate[kCallback];
265
+ this._deflate.close();
266
+ this._deflate = null;
267
+ if (callback) {
268
+ callback(
269
+ new Error(
270
+ "The deflate stream was closed while data was being processed"
271
+ )
272
+ );
273
+ }
274
+ }
275
+ }
276
+ /**
277
+ * Accept an extension negotiation offer.
278
+ *
279
+ * @param {Array} offers The extension negotiation offers
280
+ * @return {Object} Accepted configuration
281
+ * @private
282
+ */
283
+ acceptAsServer(offers) {
284
+ const opts = this._options;
285
+ const accepted = offers.find((params) => {
286
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && (typeof params.client_max_window_bits === "number" ? opts.clientMaxWindowBits > params.client_max_window_bits : !params.client_max_window_bits)) {
287
+ return false;
288
+ }
289
+ return true;
290
+ });
291
+ if (!accepted) {
292
+ throw new Error("None of the extension offers can be accepted");
293
+ }
294
+ if (opts.serverNoContextTakeover) {
295
+ accepted.server_no_context_takeover = true;
296
+ }
297
+ if (opts.clientNoContextTakeover) {
298
+ accepted.client_no_context_takeover = true;
299
+ }
300
+ if (typeof opts.serverMaxWindowBits === "number") {
301
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
302
+ }
303
+ if (typeof opts.clientMaxWindowBits === "number") {
304
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
305
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
306
+ delete accepted.client_max_window_bits;
307
+ }
308
+ return accepted;
309
+ }
310
+ /**
311
+ * Accept the extension negotiation response.
312
+ *
313
+ * @param {Array} response The extension negotiation response
314
+ * @return {Object} Accepted configuration
315
+ * @private
316
+ */
317
+ acceptAsClient(response) {
318
+ const params = response[0];
319
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
320
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
321
+ }
322
+ if (!params.client_max_window_bits) {
323
+ if (typeof this._options.clientMaxWindowBits === "number") {
324
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
325
+ }
326
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
327
+ throw new Error(
328
+ 'Unexpected or invalid parameter "client_max_window_bits"'
329
+ );
330
+ }
331
+ return params;
332
+ }
333
+ /**
334
+ * Normalize parameters.
335
+ *
336
+ * @param {Array} configurations The extension negotiation offers/reponse
337
+ * @return {Array} The offers/response with normalized parameters
338
+ * @private
339
+ */
340
+ normalizeParams(configurations) {
341
+ configurations.forEach((params) => {
342
+ Object.keys(params).forEach((key) => {
343
+ let value = params[key];
344
+ if (value.length > 1) {
345
+ throw new Error(`Parameter "${key}" must have only a single value`);
346
+ }
347
+ value = value[0];
348
+ if (key === "client_max_window_bits") {
349
+ if (value !== true) {
350
+ const num = +value;
351
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
352
+ throw new TypeError(
353
+ `Invalid value for parameter "${key}": ${value}`
354
+ );
355
+ }
356
+ value = num;
357
+ } else if (!this._isServer) {
358
+ throw new TypeError(
359
+ `Invalid value for parameter "${key}": ${value}`
360
+ );
361
+ }
362
+ } else if (key === "server_max_window_bits") {
363
+ const num = +value;
364
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
365
+ throw new TypeError(
366
+ `Invalid value for parameter "${key}": ${value}`
367
+ );
368
+ }
369
+ value = num;
370
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
371
+ if (value !== true) {
372
+ throw new TypeError(
373
+ `Invalid value for parameter "${key}": ${value}`
374
+ );
375
+ }
376
+ } else {
377
+ throw new Error(`Unknown parameter "${key}"`);
378
+ }
379
+ params[key] = value;
380
+ });
381
+ });
382
+ return configurations;
383
+ }
384
+ /**
385
+ * Decompress data. Concurrency limited.
386
+ *
387
+ * @param {Buffer} data Compressed data
388
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
389
+ * @param {Function} callback Callback
390
+ * @public
391
+ */
392
+ decompress(data, fin, callback) {
393
+ zlibLimiter.add((done) => {
394
+ this._decompress(data, fin, (err, result) => {
395
+ done();
396
+ callback(err, result);
397
+ });
398
+ });
399
+ }
400
+ /**
401
+ * Compress data. Concurrency limited.
402
+ *
403
+ * @param {(Buffer|String)} data Data to compress
404
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
405
+ * @param {Function} callback Callback
406
+ * @public
407
+ */
408
+ compress(data, fin, callback) {
409
+ zlibLimiter.add((done) => {
410
+ this._compress(data, fin, (err, result) => {
411
+ done();
412
+ callback(err, result);
413
+ });
414
+ });
415
+ }
416
+ /**
417
+ * Decompress data.
418
+ *
419
+ * @param {Buffer} data Compressed data
420
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
421
+ * @param {Function} callback Callback
422
+ * @private
423
+ */
424
+ _decompress(data, fin, callback) {
425
+ const endpoint = this._isServer ? "client" : "server";
426
+ if (!this._inflate) {
427
+ const key = `${endpoint}_max_window_bits`;
428
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
429
+ this._inflate = zlib.createInflateRaw({
430
+ ...this._options.zlibInflateOptions,
431
+ windowBits
432
+ });
433
+ this._inflate[kPerMessageDeflate] = this;
434
+ this._inflate[kTotalLength] = 0;
435
+ this._inflate[kBuffers] = [];
436
+ this._inflate.on("error", inflateOnError);
437
+ this._inflate.on("data", inflateOnData);
438
+ }
439
+ this._inflate[kCallback] = callback;
440
+ this._inflate.write(data);
441
+ if (fin) this._inflate.write(TRAILER);
442
+ this._inflate.flush(() => {
443
+ const err = this._inflate[kError];
444
+ if (err) {
445
+ this._inflate.close();
446
+ this._inflate = null;
447
+ callback(err);
448
+ return;
449
+ }
450
+ const data2 = bufferUtil.concat(
451
+ this._inflate[kBuffers],
452
+ this._inflate[kTotalLength]
453
+ );
454
+ if (this._inflate._readableState.endEmitted) {
455
+ this._inflate.close();
456
+ this._inflate = null;
457
+ } else {
458
+ this._inflate[kTotalLength] = 0;
459
+ this._inflate[kBuffers] = [];
460
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
461
+ this._inflate.reset();
462
+ }
463
+ }
464
+ callback(null, data2);
465
+ });
466
+ }
467
+ /**
468
+ * Compress data.
469
+ *
470
+ * @param {(Buffer|String)} data Data to compress
471
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
472
+ * @param {Function} callback Callback
473
+ * @private
474
+ */
475
+ _compress(data, fin, callback) {
476
+ const endpoint = this._isServer ? "server" : "client";
477
+ if (!this._deflate) {
478
+ const key = `${endpoint}_max_window_bits`;
479
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
480
+ this._deflate = zlib.createDeflateRaw({
481
+ ...this._options.zlibDeflateOptions,
482
+ windowBits
483
+ });
484
+ this._deflate[kTotalLength] = 0;
485
+ this._deflate[kBuffers] = [];
486
+ this._deflate.on("data", deflateOnData);
487
+ }
488
+ this._deflate[kCallback] = callback;
489
+ this._deflate.write(data);
490
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
491
+ if (!this._deflate) {
492
+ return;
493
+ }
494
+ let data2 = bufferUtil.concat(
495
+ this._deflate[kBuffers],
496
+ this._deflate[kTotalLength]
497
+ );
498
+ if (fin) {
499
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
500
+ }
501
+ this._deflate[kCallback] = null;
502
+ this._deflate[kTotalLength] = 0;
503
+ this._deflate[kBuffers] = [];
504
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
505
+ this._deflate.reset();
506
+ }
507
+ callback(null, data2);
508
+ });
509
+ }
510
+ };
511
+ module2.exports = PerMessageDeflate2;
512
+ function deflateOnData(chunk) {
513
+ this[kBuffers].push(chunk);
514
+ this[kTotalLength] += chunk.length;
515
+ }
516
+ function inflateOnData(chunk) {
517
+ this[kTotalLength] += chunk.length;
518
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
519
+ this[kBuffers].push(chunk);
520
+ return;
521
+ }
522
+ this[kError] = new RangeError("Max payload size exceeded");
523
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
524
+ this[kError][kStatusCode] = 1009;
525
+ this.removeListener("data", inflateOnData);
526
+ this.reset();
527
+ }
528
+ function inflateOnError(err) {
529
+ this[kPerMessageDeflate]._inflate = null;
530
+ if (this[kError]) {
531
+ this[kCallback](this[kError]);
532
+ return;
533
+ }
534
+ err[kStatusCode] = 1007;
535
+ this[kCallback](err);
536
+ }
537
+ }
538
+ });
539
+
540
+ // ../../node_modules/ws/lib/validation.js
541
+ var require_validation = __commonJS({
542
+ "../../node_modules/ws/lib/validation.js"(exports2, module2) {
543
+ "use strict";
544
+ var { isUtf8 } = require("buffer");
545
+ var { hasBlob } = require_constants();
546
+ var tokenChars = [
547
+ 0,
548
+ 0,
549
+ 0,
550
+ 0,
551
+ 0,
552
+ 0,
553
+ 0,
554
+ 0,
555
+ 0,
556
+ 0,
557
+ 0,
558
+ 0,
559
+ 0,
560
+ 0,
561
+ 0,
562
+ 0,
563
+ // 0 - 15
564
+ 0,
565
+ 0,
566
+ 0,
567
+ 0,
568
+ 0,
569
+ 0,
570
+ 0,
571
+ 0,
572
+ 0,
573
+ 0,
574
+ 0,
575
+ 0,
576
+ 0,
577
+ 0,
578
+ 0,
579
+ 0,
580
+ // 16 - 31
581
+ 0,
582
+ 1,
583
+ 0,
584
+ 1,
585
+ 1,
586
+ 1,
587
+ 1,
588
+ 1,
589
+ 0,
590
+ 0,
591
+ 1,
592
+ 1,
593
+ 0,
594
+ 1,
595
+ 1,
596
+ 0,
597
+ // 32 - 47
598
+ 1,
599
+ 1,
600
+ 1,
601
+ 1,
602
+ 1,
603
+ 1,
604
+ 1,
605
+ 1,
606
+ 1,
607
+ 1,
608
+ 0,
609
+ 0,
610
+ 0,
611
+ 0,
612
+ 0,
613
+ 0,
614
+ // 48 - 63
615
+ 0,
616
+ 1,
617
+ 1,
618
+ 1,
619
+ 1,
620
+ 1,
621
+ 1,
622
+ 1,
623
+ 1,
624
+ 1,
625
+ 1,
626
+ 1,
627
+ 1,
628
+ 1,
629
+ 1,
630
+ 1,
631
+ // 64 - 79
632
+ 1,
633
+ 1,
634
+ 1,
635
+ 1,
636
+ 1,
637
+ 1,
638
+ 1,
639
+ 1,
640
+ 1,
641
+ 1,
642
+ 1,
643
+ 0,
644
+ 0,
645
+ 0,
646
+ 1,
647
+ 1,
648
+ // 80 - 95
649
+ 1,
650
+ 1,
651
+ 1,
652
+ 1,
653
+ 1,
654
+ 1,
655
+ 1,
656
+ 1,
657
+ 1,
658
+ 1,
659
+ 1,
660
+ 1,
661
+ 1,
662
+ 1,
663
+ 1,
664
+ 1,
665
+ // 96 - 111
666
+ 1,
667
+ 1,
668
+ 1,
669
+ 1,
670
+ 1,
671
+ 1,
672
+ 1,
673
+ 1,
674
+ 1,
675
+ 1,
676
+ 1,
677
+ 0,
678
+ 1,
679
+ 0,
680
+ 1,
681
+ 0
682
+ // 112 - 127
683
+ ];
684
+ function isValidStatusCode(code) {
685
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
686
+ }
687
+ function _isValidUTF8(buf) {
688
+ const len = buf.length;
689
+ let i = 0;
690
+ while (i < len) {
691
+ if ((buf[i] & 128) === 0) {
692
+ i++;
693
+ } else if ((buf[i] & 224) === 192) {
694
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
695
+ return false;
696
+ }
697
+ i += 2;
698
+ } else if ((buf[i] & 240) === 224) {
699
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
700
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
701
+ return false;
702
+ }
703
+ i += 3;
704
+ } else if ((buf[i] & 248) === 240) {
705
+ if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
706
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
707
+ return false;
708
+ }
709
+ i += 4;
710
+ } else {
711
+ return false;
712
+ }
713
+ }
714
+ return true;
715
+ }
716
+ function isBlob(value) {
717
+ return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
718
+ }
719
+ module2.exports = {
720
+ isBlob,
721
+ isValidStatusCode,
722
+ isValidUTF8: _isValidUTF8,
723
+ tokenChars
724
+ };
725
+ if (isUtf8) {
726
+ module2.exports.isValidUTF8 = function(buf) {
727
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
728
+ };
729
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
730
+ try {
731
+ const isValidUTF8 = require("utf-8-validate");
732
+ module2.exports.isValidUTF8 = function(buf) {
733
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
734
+ };
735
+ } catch (e) {
736
+ }
737
+ }
738
+ }
739
+ });
740
+
741
+ // ../../node_modules/ws/lib/receiver.js
742
+ var require_receiver = __commonJS({
743
+ "../../node_modules/ws/lib/receiver.js"(exports2, module2) {
744
+ "use strict";
745
+ var { Writable } = require("stream");
746
+ var PerMessageDeflate2 = require_permessage_deflate();
747
+ var {
748
+ BINARY_TYPES,
749
+ EMPTY_BUFFER,
750
+ kStatusCode,
751
+ kWebSocket
752
+ } = require_constants();
753
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
754
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
755
+ var FastBuffer = Buffer[Symbol.species];
756
+ var GET_INFO = 0;
757
+ var GET_PAYLOAD_LENGTH_16 = 1;
758
+ var GET_PAYLOAD_LENGTH_64 = 2;
759
+ var GET_MASK = 3;
760
+ var GET_DATA = 4;
761
+ var INFLATING = 5;
762
+ var DEFER_EVENT = 6;
763
+ var Receiver2 = class extends Writable {
764
+ /**
765
+ * Creates a Receiver instance.
766
+ *
767
+ * @param {Object} [options] Options object
768
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
769
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
770
+ * multiple times in the same tick
771
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
772
+ * @param {Object} [options.extensions] An object containing the negotiated
773
+ * extensions
774
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
775
+ * client or server mode
776
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
777
+ * buffered data chunks
778
+ * @param {Number} [options.maxFragments=0] The maximum number of message
779
+ * fragments
780
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
781
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
782
+ * not to skip UTF-8 validation for text and close messages
783
+ */
784
+ constructor(options = {}) {
785
+ super();
786
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
787
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
788
+ this._extensions = options.extensions || {};
789
+ this._isServer = !!options.isServer;
790
+ this._maxBufferedChunks = options.maxBufferedChunks | 0;
791
+ this._maxFragments = options.maxFragments | 0;
792
+ this._maxPayload = options.maxPayload | 0;
793
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
794
+ this[kWebSocket] = void 0;
795
+ this._bufferedBytes = 0;
796
+ this._buffers = [];
797
+ this._compressed = false;
798
+ this._payloadLength = 0;
799
+ this._mask = void 0;
800
+ this._fragmented = 0;
801
+ this._masked = false;
802
+ this._fin = false;
803
+ this._opcode = 0;
804
+ this._totalPayloadLength = 0;
805
+ this._messageLength = 0;
806
+ this._numFragments = 0;
807
+ this._fragments = [];
808
+ this._errored = false;
809
+ this._loop = false;
810
+ this._state = GET_INFO;
811
+ }
812
+ /**
813
+ * Implements `Writable.prototype._write()`.
814
+ *
815
+ * @param {Buffer} chunk The chunk of data to write
816
+ * @param {String} encoding The character encoding of `chunk`
817
+ * @param {Function} cb Callback
818
+ * @private
819
+ */
820
+ _write(chunk, encoding, cb) {
821
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
822
+ if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
823
+ cb(
824
+ this.createError(
825
+ RangeError,
826
+ "Too many buffered chunks",
827
+ false,
828
+ 1008,
829
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
830
+ )
831
+ );
832
+ return;
833
+ }
834
+ this._bufferedBytes += chunk.length;
835
+ this._buffers.push(chunk);
836
+ this.startLoop(cb);
837
+ }
838
+ /**
839
+ * Consumes `n` bytes from the buffered data.
840
+ *
841
+ * @param {Number} n The number of bytes to consume
842
+ * @return {Buffer} The consumed bytes
843
+ * @private
844
+ */
845
+ consume(n) {
846
+ this._bufferedBytes -= n;
847
+ if (n === this._buffers[0].length) return this._buffers.shift();
848
+ if (n < this._buffers[0].length) {
849
+ const buf = this._buffers[0];
850
+ this._buffers[0] = new FastBuffer(
851
+ buf.buffer,
852
+ buf.byteOffset + n,
853
+ buf.length - n
854
+ );
855
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
856
+ }
857
+ const dst = Buffer.allocUnsafe(n);
858
+ do {
859
+ const buf = this._buffers[0];
860
+ const offset = dst.length - n;
861
+ if (n >= buf.length) {
862
+ dst.set(this._buffers.shift(), offset);
863
+ } else {
864
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
865
+ this._buffers[0] = new FastBuffer(
866
+ buf.buffer,
867
+ buf.byteOffset + n,
868
+ buf.length - n
869
+ );
870
+ }
871
+ n -= buf.length;
872
+ } while (n > 0);
873
+ return dst;
874
+ }
875
+ /**
876
+ * Starts the parsing loop.
877
+ *
878
+ * @param {Function} cb Callback
879
+ * @private
880
+ */
881
+ startLoop(cb) {
882
+ this._loop = true;
883
+ do {
884
+ switch (this._state) {
885
+ case GET_INFO:
886
+ this.getInfo(cb);
887
+ break;
888
+ case GET_PAYLOAD_LENGTH_16:
889
+ this.getPayloadLength16(cb);
890
+ break;
891
+ case GET_PAYLOAD_LENGTH_64:
892
+ this.getPayloadLength64(cb);
893
+ break;
894
+ case GET_MASK:
895
+ this.getMask();
896
+ break;
897
+ case GET_DATA:
898
+ this.getData(cb);
899
+ break;
900
+ case INFLATING:
901
+ case DEFER_EVENT:
902
+ this._loop = false;
903
+ return;
904
+ }
905
+ } while (this._loop);
906
+ if (!this._errored) cb();
907
+ }
908
+ /**
909
+ * Reads the first two bytes of a frame.
910
+ *
911
+ * @param {Function} cb Callback
912
+ * @private
913
+ */
914
+ getInfo(cb) {
915
+ if (this._bufferedBytes < 2) {
916
+ this._loop = false;
917
+ return;
918
+ }
919
+ const buf = this.consume(2);
920
+ if ((buf[0] & 48) !== 0) {
921
+ const error = this.createError(
922
+ RangeError,
923
+ "RSV2 and RSV3 must be clear",
924
+ true,
925
+ 1002,
926
+ "WS_ERR_UNEXPECTED_RSV_2_3"
927
+ );
928
+ cb(error);
929
+ return;
930
+ }
931
+ const compressed = (buf[0] & 64) === 64;
932
+ if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
933
+ const error = this.createError(
934
+ RangeError,
935
+ "RSV1 must be clear",
936
+ true,
937
+ 1002,
938
+ "WS_ERR_UNEXPECTED_RSV_1"
939
+ );
940
+ cb(error);
941
+ return;
942
+ }
943
+ this._fin = (buf[0] & 128) === 128;
944
+ this._opcode = buf[0] & 15;
945
+ this._payloadLength = buf[1] & 127;
946
+ if (this._opcode === 0) {
947
+ if (compressed) {
948
+ const error = this.createError(
949
+ RangeError,
950
+ "RSV1 must be clear",
951
+ true,
952
+ 1002,
953
+ "WS_ERR_UNEXPECTED_RSV_1"
954
+ );
955
+ cb(error);
956
+ return;
957
+ }
958
+ if (!this._fragmented) {
959
+ const error = this.createError(
960
+ RangeError,
961
+ "invalid opcode 0",
962
+ true,
963
+ 1002,
964
+ "WS_ERR_INVALID_OPCODE"
965
+ );
966
+ cb(error);
967
+ return;
968
+ }
969
+ this._opcode = this._fragmented;
970
+ } else if (this._opcode === 1 || this._opcode === 2) {
971
+ if (this._fragmented) {
972
+ const error = this.createError(
973
+ RangeError,
974
+ `invalid opcode ${this._opcode}`,
975
+ true,
976
+ 1002,
977
+ "WS_ERR_INVALID_OPCODE"
978
+ );
979
+ cb(error);
980
+ return;
981
+ }
982
+ this._compressed = compressed;
983
+ } else if (this._opcode > 7 && this._opcode < 11) {
984
+ if (!this._fin) {
985
+ const error = this.createError(
986
+ RangeError,
987
+ "FIN must be set",
988
+ true,
989
+ 1002,
990
+ "WS_ERR_EXPECTED_FIN"
991
+ );
992
+ cb(error);
993
+ return;
994
+ }
995
+ if (compressed) {
996
+ const error = this.createError(
997
+ RangeError,
998
+ "RSV1 must be clear",
999
+ true,
1000
+ 1002,
1001
+ "WS_ERR_UNEXPECTED_RSV_1"
1002
+ );
1003
+ cb(error);
1004
+ return;
1005
+ }
1006
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1007
+ const error = this.createError(
1008
+ RangeError,
1009
+ `invalid payload length ${this._payloadLength}`,
1010
+ true,
1011
+ 1002,
1012
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1013
+ );
1014
+ cb(error);
1015
+ return;
1016
+ }
1017
+ } else {
1018
+ const error = this.createError(
1019
+ RangeError,
1020
+ `invalid opcode ${this._opcode}`,
1021
+ true,
1022
+ 1002,
1023
+ "WS_ERR_INVALID_OPCODE"
1024
+ );
1025
+ cb(error);
1026
+ return;
1027
+ }
1028
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1029
+ this._masked = (buf[1] & 128) === 128;
1030
+ if (this._isServer) {
1031
+ if (!this._masked) {
1032
+ const error = this.createError(
1033
+ RangeError,
1034
+ "MASK must be set",
1035
+ true,
1036
+ 1002,
1037
+ "WS_ERR_EXPECTED_MASK"
1038
+ );
1039
+ cb(error);
1040
+ return;
1041
+ }
1042
+ } else if (this._masked) {
1043
+ const error = this.createError(
1044
+ RangeError,
1045
+ "MASK must be clear",
1046
+ true,
1047
+ 1002,
1048
+ "WS_ERR_UNEXPECTED_MASK"
1049
+ );
1050
+ cb(error);
1051
+ return;
1052
+ }
1053
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1054
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1055
+ else this.haveLength(cb);
1056
+ }
1057
+ /**
1058
+ * Gets extended payload length (7+16).
1059
+ *
1060
+ * @param {Function} cb Callback
1061
+ * @private
1062
+ */
1063
+ getPayloadLength16(cb) {
1064
+ if (this._bufferedBytes < 2) {
1065
+ this._loop = false;
1066
+ return;
1067
+ }
1068
+ this._payloadLength = this.consume(2).readUInt16BE(0);
1069
+ this.haveLength(cb);
1070
+ }
1071
+ /**
1072
+ * Gets extended payload length (7+64).
1073
+ *
1074
+ * @param {Function} cb Callback
1075
+ * @private
1076
+ */
1077
+ getPayloadLength64(cb) {
1078
+ if (this._bufferedBytes < 8) {
1079
+ this._loop = false;
1080
+ return;
1081
+ }
1082
+ const buf = this.consume(8);
1083
+ const num = buf.readUInt32BE(0);
1084
+ if (num > Math.pow(2, 53 - 32) - 1) {
1085
+ const error = this.createError(
1086
+ RangeError,
1087
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
1088
+ false,
1089
+ 1009,
1090
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1091
+ );
1092
+ cb(error);
1093
+ return;
1094
+ }
1095
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1096
+ this.haveLength(cb);
1097
+ }
1098
+ /**
1099
+ * Payload length has been read.
1100
+ *
1101
+ * @param {Function} cb Callback
1102
+ * @private
1103
+ */
1104
+ haveLength(cb) {
1105
+ if (this._payloadLength && this._opcode < 8) {
1106
+ this._totalPayloadLength += this._payloadLength;
1107
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1108
+ const error = this.createError(
1109
+ RangeError,
1110
+ "Max payload size exceeded",
1111
+ false,
1112
+ 1009,
1113
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1114
+ );
1115
+ cb(error);
1116
+ return;
1117
+ }
1118
+ }
1119
+ if (this._masked) this._state = GET_MASK;
1120
+ else this._state = GET_DATA;
1121
+ }
1122
+ /**
1123
+ * Reads mask bytes.
1124
+ *
1125
+ * @private
1126
+ */
1127
+ getMask() {
1128
+ if (this._bufferedBytes < 4) {
1129
+ this._loop = false;
1130
+ return;
1131
+ }
1132
+ this._mask = this.consume(4);
1133
+ this._state = GET_DATA;
1134
+ }
1135
+ /**
1136
+ * Reads data bytes.
1137
+ *
1138
+ * @param {Function} cb Callback
1139
+ * @private
1140
+ */
1141
+ getData(cb) {
1142
+ let data = EMPTY_BUFFER;
1143
+ if (this._payloadLength) {
1144
+ if (this._bufferedBytes < this._payloadLength) {
1145
+ this._loop = false;
1146
+ return;
1147
+ }
1148
+ data = this.consume(this._payloadLength);
1149
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1150
+ unmask(data, this._mask);
1151
+ }
1152
+ }
1153
+ if (this._opcode > 7) {
1154
+ this.controlMessage(data, cb);
1155
+ return;
1156
+ }
1157
+ if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {
1158
+ const error = this.createError(
1159
+ RangeError,
1160
+ "Too many message fragments",
1161
+ false,
1162
+ 1008,
1163
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
1164
+ );
1165
+ cb(error);
1166
+ return;
1167
+ }
1168
+ if (this._compressed) {
1169
+ this._state = INFLATING;
1170
+ this.decompress(data, cb);
1171
+ return;
1172
+ }
1173
+ if (data.length) {
1174
+ this._messageLength = this._totalPayloadLength;
1175
+ this._fragments.push(data);
1176
+ }
1177
+ this.dataMessage(cb);
1178
+ }
1179
+ /**
1180
+ * Decompresses data.
1181
+ *
1182
+ * @param {Buffer} data Compressed data
1183
+ * @param {Function} cb Callback
1184
+ * @private
1185
+ */
1186
+ decompress(data, cb) {
1187
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1188
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1189
+ if (err) return cb(err);
1190
+ if (buf.length) {
1191
+ this._messageLength += buf.length;
1192
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1193
+ const error = this.createError(
1194
+ RangeError,
1195
+ "Max payload size exceeded",
1196
+ false,
1197
+ 1009,
1198
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1199
+ );
1200
+ cb(error);
1201
+ return;
1202
+ }
1203
+ this._fragments.push(buf);
1204
+ }
1205
+ this.dataMessage(cb);
1206
+ if (this._state === GET_INFO) this.startLoop(cb);
1207
+ });
1208
+ }
1209
+ /**
1210
+ * Handles a data message.
1211
+ *
1212
+ * @param {Function} cb Callback
1213
+ * @private
1214
+ */
1215
+ dataMessage(cb) {
1216
+ if (!this._fin) {
1217
+ this._state = GET_INFO;
1218
+ return;
1219
+ }
1220
+ const messageLength = this._messageLength;
1221
+ const fragments = this._fragments;
1222
+ this._totalPayloadLength = 0;
1223
+ this._messageLength = 0;
1224
+ this._fragmented = 0;
1225
+ this._numFragments = 0;
1226
+ this._fragments = [];
1227
+ if (this._opcode === 2) {
1228
+ let data;
1229
+ if (this._binaryType === "nodebuffer") {
1230
+ data = concat(fragments, messageLength);
1231
+ } else if (this._binaryType === "arraybuffer") {
1232
+ data = toArrayBuffer(concat(fragments, messageLength));
1233
+ } else if (this._binaryType === "blob") {
1234
+ data = new Blob(fragments);
1235
+ } else {
1236
+ data = fragments;
1237
+ }
1238
+ if (this._allowSynchronousEvents) {
1239
+ this.emit("message", data, true);
1240
+ this._state = GET_INFO;
1241
+ } else {
1242
+ this._state = DEFER_EVENT;
1243
+ setImmediate(() => {
1244
+ this.emit("message", data, true);
1245
+ this._state = GET_INFO;
1246
+ this.startLoop(cb);
1247
+ });
1248
+ }
1249
+ } else {
1250
+ const buf = concat(fragments, messageLength);
1251
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1252
+ const error = this.createError(
1253
+ Error,
1254
+ "invalid UTF-8 sequence",
1255
+ true,
1256
+ 1007,
1257
+ "WS_ERR_INVALID_UTF8"
1258
+ );
1259
+ cb(error);
1260
+ return;
1261
+ }
1262
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
1263
+ this.emit("message", buf, false);
1264
+ this._state = GET_INFO;
1265
+ } else {
1266
+ this._state = DEFER_EVENT;
1267
+ setImmediate(() => {
1268
+ this.emit("message", buf, false);
1269
+ this._state = GET_INFO;
1270
+ this.startLoop(cb);
1271
+ });
1272
+ }
1273
+ }
1274
+ }
1275
+ /**
1276
+ * Handles a control message.
1277
+ *
1278
+ * @param {Buffer} data Data to handle
1279
+ * @return {(Error|RangeError|undefined)} A possible error
1280
+ * @private
1281
+ */
1282
+ controlMessage(data, cb) {
1283
+ if (this._opcode === 8) {
1284
+ if (data.length === 0) {
1285
+ this._loop = false;
1286
+ this.emit("conclude", 1005, EMPTY_BUFFER);
1287
+ this.end();
1288
+ } else {
1289
+ const code = data.readUInt16BE(0);
1290
+ if (!isValidStatusCode(code)) {
1291
+ const error = this.createError(
1292
+ RangeError,
1293
+ `invalid status code ${code}`,
1294
+ true,
1295
+ 1002,
1296
+ "WS_ERR_INVALID_CLOSE_CODE"
1297
+ );
1298
+ cb(error);
1299
+ return;
1300
+ }
1301
+ const buf = new FastBuffer(
1302
+ data.buffer,
1303
+ data.byteOffset + 2,
1304
+ data.length - 2
1305
+ );
1306
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1307
+ const error = this.createError(
1308
+ Error,
1309
+ "invalid UTF-8 sequence",
1310
+ true,
1311
+ 1007,
1312
+ "WS_ERR_INVALID_UTF8"
1313
+ );
1314
+ cb(error);
1315
+ return;
1316
+ }
1317
+ this._loop = false;
1318
+ this.emit("conclude", code, buf);
1319
+ this.end();
1320
+ }
1321
+ this._state = GET_INFO;
1322
+ return;
1323
+ }
1324
+ if (this._allowSynchronousEvents) {
1325
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1326
+ this._state = GET_INFO;
1327
+ } else {
1328
+ this._state = DEFER_EVENT;
1329
+ setImmediate(() => {
1330
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1331
+ this._state = GET_INFO;
1332
+ this.startLoop(cb);
1333
+ });
1334
+ }
1335
+ }
1336
+ /**
1337
+ * Builds an error object.
1338
+ *
1339
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1340
+ * @param {String} message The error message
1341
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1342
+ * `message`
1343
+ * @param {Number} statusCode The status code
1344
+ * @param {String} errorCode The exposed error code
1345
+ * @return {(Error|RangeError)} The error
1346
+ * @private
1347
+ */
1348
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1349
+ this._loop = false;
1350
+ this._errored = true;
1351
+ const err = new ErrorCtor(
1352
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1353
+ );
1354
+ Error.captureStackTrace(err, this.createError);
1355
+ err.code = errorCode;
1356
+ err[kStatusCode] = statusCode;
1357
+ return err;
1358
+ }
1359
+ };
1360
+ module2.exports = Receiver2;
1361
+ }
1362
+ });
1363
+
1364
+ // ../../node_modules/ws/lib/sender.js
1365
+ var require_sender = __commonJS({
1366
+ "../../node_modules/ws/lib/sender.js"(exports2, module2) {
1367
+ "use strict";
1368
+ var { Duplex } = require("stream");
1369
+ var { randomFillSync } = require("crypto");
1370
+ var {
1371
+ types: { isUint8Array }
1372
+ } = require("util");
1373
+ var PerMessageDeflate2 = require_permessage_deflate();
1374
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1375
+ var { isBlob, isValidStatusCode } = require_validation();
1376
+ var { mask: applyMask, toBuffer } = require_buffer_util();
1377
+ var kByteLength = Symbol("kByteLength");
1378
+ var maskBuffer = Buffer.alloc(4);
1379
+ var RANDOM_POOL_SIZE = 8 * 1024;
1380
+ var randomPool;
1381
+ var randomPoolPointer = RANDOM_POOL_SIZE;
1382
+ var DEFAULT = 0;
1383
+ var DEFLATING = 1;
1384
+ var GET_BLOB_DATA = 2;
1385
+ var Sender2 = class _Sender {
1386
+ /**
1387
+ * Creates a Sender instance.
1388
+ *
1389
+ * @param {Duplex} socket The connection socket
1390
+ * @param {Object} [extensions] An object containing the negotiated extensions
1391
+ * @param {Function} [generateMask] The function used to generate the masking
1392
+ * key
1393
+ */
1394
+ constructor(socket, extensions, generateMask) {
1395
+ this._extensions = extensions || {};
1396
+ if (generateMask) {
1397
+ this._generateMask = generateMask;
1398
+ this._maskBuffer = Buffer.alloc(4);
1399
+ }
1400
+ this._socket = socket;
1401
+ this._firstFragment = true;
1402
+ this._compress = false;
1403
+ this._bufferedBytes = 0;
1404
+ this._queue = [];
1405
+ this._state = DEFAULT;
1406
+ this.onerror = NOOP;
1407
+ this[kWebSocket] = void 0;
1408
+ }
1409
+ /**
1410
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1411
+ *
1412
+ * @param {(Buffer|String)} data The data to frame
1413
+ * @param {Object} options Options object
1414
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1415
+ * FIN bit
1416
+ * @param {Function} [options.generateMask] The function used to generate the
1417
+ * masking key
1418
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1419
+ * `data`
1420
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1421
+ * key
1422
+ * @param {Number} options.opcode The opcode
1423
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1424
+ * modified
1425
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1426
+ * RSV1 bit
1427
+ * @return {(Buffer|String)[]} The framed data
1428
+ * @public
1429
+ */
1430
+ static frame(data, options) {
1431
+ let mask;
1432
+ let merge = false;
1433
+ let offset = 2;
1434
+ let skipMasking = false;
1435
+ if (options.mask) {
1436
+ mask = options.maskBuffer || maskBuffer;
1437
+ if (options.generateMask) {
1438
+ options.generateMask(mask);
1439
+ } else {
1440
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1441
+ if (randomPool === void 0) {
1442
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1443
+ }
1444
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1445
+ randomPoolPointer = 0;
1446
+ }
1447
+ mask[0] = randomPool[randomPoolPointer++];
1448
+ mask[1] = randomPool[randomPoolPointer++];
1449
+ mask[2] = randomPool[randomPoolPointer++];
1450
+ mask[3] = randomPool[randomPoolPointer++];
1451
+ }
1452
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1453
+ offset = 6;
1454
+ }
1455
+ let dataLength;
1456
+ if (typeof data === "string") {
1457
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1458
+ dataLength = options[kByteLength];
1459
+ } else {
1460
+ data = Buffer.from(data);
1461
+ dataLength = data.length;
1462
+ }
1463
+ } else {
1464
+ dataLength = data.length;
1465
+ merge = options.mask && options.readOnly && !skipMasking;
1466
+ }
1467
+ let payloadLength = dataLength;
1468
+ if (dataLength >= 65536) {
1469
+ offset += 8;
1470
+ payloadLength = 127;
1471
+ } else if (dataLength > 125) {
1472
+ offset += 2;
1473
+ payloadLength = 126;
1474
+ }
1475
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1476
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1477
+ if (options.rsv1) target[0] |= 64;
1478
+ target[1] = payloadLength;
1479
+ if (payloadLength === 126) {
1480
+ target.writeUInt16BE(dataLength, 2);
1481
+ } else if (payloadLength === 127) {
1482
+ target[2] = target[3] = 0;
1483
+ target.writeUIntBE(dataLength, 4, 6);
1484
+ }
1485
+ if (!options.mask) return [target, data];
1486
+ target[1] |= 128;
1487
+ target[offset - 4] = mask[0];
1488
+ target[offset - 3] = mask[1];
1489
+ target[offset - 2] = mask[2];
1490
+ target[offset - 1] = mask[3];
1491
+ if (skipMasking) return [target, data];
1492
+ if (merge) {
1493
+ applyMask(data, mask, target, offset, dataLength);
1494
+ return [target];
1495
+ }
1496
+ applyMask(data, mask, data, 0, dataLength);
1497
+ return [target, data];
1498
+ }
1499
+ /**
1500
+ * Sends a close message to the other peer.
1501
+ *
1502
+ * @param {Number} [code] The status code component of the body
1503
+ * @param {(String|Buffer)} [data] The message component of the body
1504
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1505
+ * @param {Function} [cb] Callback
1506
+ * @public
1507
+ */
1508
+ close(code, data, mask, cb) {
1509
+ let buf;
1510
+ if (code === void 0) {
1511
+ buf = EMPTY_BUFFER;
1512
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1513
+ throw new TypeError("First argument must be a valid error code number");
1514
+ } else if (data === void 0 || !data.length) {
1515
+ buf = Buffer.allocUnsafe(2);
1516
+ buf.writeUInt16BE(code, 0);
1517
+ } else {
1518
+ const length = Buffer.byteLength(data);
1519
+ if (length > 123) {
1520
+ throw new RangeError("The message must not be greater than 123 bytes");
1521
+ }
1522
+ buf = Buffer.allocUnsafe(2 + length);
1523
+ buf.writeUInt16BE(code, 0);
1524
+ if (typeof data === "string") {
1525
+ buf.write(data, 2);
1526
+ } else if (isUint8Array(data)) {
1527
+ buf.set(data, 2);
1528
+ } else {
1529
+ throw new TypeError("Second argument must be a string or a Uint8Array");
1530
+ }
1531
+ }
1532
+ const options = {
1533
+ [kByteLength]: buf.length,
1534
+ fin: true,
1535
+ generateMask: this._generateMask,
1536
+ mask,
1537
+ maskBuffer: this._maskBuffer,
1538
+ opcode: 8,
1539
+ readOnly: false,
1540
+ rsv1: false
1541
+ };
1542
+ if (this._state !== DEFAULT) {
1543
+ this.enqueue([this.dispatch, buf, false, options, cb]);
1544
+ } else {
1545
+ this.sendFrame(_Sender.frame(buf, options), cb);
1546
+ }
1547
+ }
1548
+ /**
1549
+ * Sends a ping message to the other peer.
1550
+ *
1551
+ * @param {*} data The message to send
1552
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1553
+ * @param {Function} [cb] Callback
1554
+ * @public
1555
+ */
1556
+ ping(data, mask, cb) {
1557
+ let byteLength;
1558
+ let readOnly;
1559
+ if (typeof data === "string") {
1560
+ byteLength = Buffer.byteLength(data);
1561
+ readOnly = false;
1562
+ } else if (isBlob(data)) {
1563
+ byteLength = data.size;
1564
+ readOnly = false;
1565
+ } else {
1566
+ data = toBuffer(data);
1567
+ byteLength = data.length;
1568
+ readOnly = toBuffer.readOnly;
1569
+ }
1570
+ if (byteLength > 125) {
1571
+ throw new RangeError("The data size must not be greater than 125 bytes");
1572
+ }
1573
+ const options = {
1574
+ [kByteLength]: byteLength,
1575
+ fin: true,
1576
+ generateMask: this._generateMask,
1577
+ mask,
1578
+ maskBuffer: this._maskBuffer,
1579
+ opcode: 9,
1580
+ readOnly,
1581
+ rsv1: false
1582
+ };
1583
+ if (isBlob(data)) {
1584
+ if (this._state !== DEFAULT) {
1585
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1586
+ } else {
1587
+ this.getBlobData(data, false, options, cb);
1588
+ }
1589
+ } else if (this._state !== DEFAULT) {
1590
+ this.enqueue([this.dispatch, data, false, options, cb]);
1591
+ } else {
1592
+ this.sendFrame(_Sender.frame(data, options), cb);
1593
+ }
1594
+ }
1595
+ /**
1596
+ * Sends a pong message to the other peer.
1597
+ *
1598
+ * @param {*} data The message to send
1599
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1600
+ * @param {Function} [cb] Callback
1601
+ * @public
1602
+ */
1603
+ pong(data, mask, cb) {
1604
+ let byteLength;
1605
+ let readOnly;
1606
+ if (typeof data === "string") {
1607
+ byteLength = Buffer.byteLength(data);
1608
+ readOnly = false;
1609
+ } else if (isBlob(data)) {
1610
+ byteLength = data.size;
1611
+ readOnly = false;
1612
+ } else {
1613
+ data = toBuffer(data);
1614
+ byteLength = data.length;
1615
+ readOnly = toBuffer.readOnly;
1616
+ }
1617
+ if (byteLength > 125) {
1618
+ throw new RangeError("The data size must not be greater than 125 bytes");
1619
+ }
1620
+ const options = {
1621
+ [kByteLength]: byteLength,
1622
+ fin: true,
1623
+ generateMask: this._generateMask,
1624
+ mask,
1625
+ maskBuffer: this._maskBuffer,
1626
+ opcode: 10,
1627
+ readOnly,
1628
+ rsv1: false
1629
+ };
1630
+ if (isBlob(data)) {
1631
+ if (this._state !== DEFAULT) {
1632
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1633
+ } else {
1634
+ this.getBlobData(data, false, options, cb);
1635
+ }
1636
+ } else if (this._state !== DEFAULT) {
1637
+ this.enqueue([this.dispatch, data, false, options, cb]);
1638
+ } else {
1639
+ this.sendFrame(_Sender.frame(data, options), cb);
1640
+ }
1641
+ }
1642
+ /**
1643
+ * Sends a data message to the other peer.
1644
+ *
1645
+ * @param {*} data The message to send
1646
+ * @param {Object} options Options object
1647
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1648
+ * or text
1649
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1650
+ * compress `data`
1651
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1652
+ * last one
1653
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1654
+ * `data`
1655
+ * @param {Function} [cb] Callback
1656
+ * @public
1657
+ */
1658
+ send(data, options, cb) {
1659
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1660
+ let opcode = options.binary ? 2 : 1;
1661
+ let rsv1 = options.compress;
1662
+ let byteLength;
1663
+ let readOnly;
1664
+ if (typeof data === "string") {
1665
+ byteLength = Buffer.byteLength(data);
1666
+ readOnly = false;
1667
+ } else if (isBlob(data)) {
1668
+ byteLength = data.size;
1669
+ readOnly = false;
1670
+ } else {
1671
+ data = toBuffer(data);
1672
+ byteLength = data.length;
1673
+ readOnly = toBuffer.readOnly;
1674
+ }
1675
+ if (this._firstFragment) {
1676
+ this._firstFragment = false;
1677
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1678
+ rsv1 = byteLength >= perMessageDeflate._threshold;
1679
+ }
1680
+ this._compress = rsv1;
1681
+ } else {
1682
+ rsv1 = false;
1683
+ opcode = 0;
1684
+ }
1685
+ if (options.fin) this._firstFragment = true;
1686
+ const opts = {
1687
+ [kByteLength]: byteLength,
1688
+ fin: options.fin,
1689
+ generateMask: this._generateMask,
1690
+ mask: options.mask,
1691
+ maskBuffer: this._maskBuffer,
1692
+ opcode,
1693
+ readOnly,
1694
+ rsv1
1695
+ };
1696
+ if (isBlob(data)) {
1697
+ if (this._state !== DEFAULT) {
1698
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
1699
+ } else {
1700
+ this.getBlobData(data, this._compress, opts, cb);
1701
+ }
1702
+ } else if (this._state !== DEFAULT) {
1703
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1704
+ } else {
1705
+ this.dispatch(data, this._compress, opts, cb);
1706
+ }
1707
+ }
1708
+ /**
1709
+ * Gets the contents of a blob as binary data.
1710
+ *
1711
+ * @param {Blob} blob The blob
1712
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1713
+ * the data
1714
+ * @param {Object} options Options object
1715
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1716
+ * FIN bit
1717
+ * @param {Function} [options.generateMask] The function used to generate the
1718
+ * masking key
1719
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1720
+ * `data`
1721
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1722
+ * key
1723
+ * @param {Number} options.opcode The opcode
1724
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1725
+ * modified
1726
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1727
+ * RSV1 bit
1728
+ * @param {Function} [cb] Callback
1729
+ * @private
1730
+ */
1731
+ getBlobData(blob, compress, options, cb) {
1732
+ this._bufferedBytes += options[kByteLength];
1733
+ this._state = GET_BLOB_DATA;
1734
+ blob.arrayBuffer().then((arrayBuffer) => {
1735
+ if (this._socket.destroyed) {
1736
+ const err = new Error(
1737
+ "The socket was closed while the blob was being read"
1738
+ );
1739
+ process.nextTick(callCallbacks, this, err, cb);
1740
+ return;
1741
+ }
1742
+ this._bufferedBytes -= options[kByteLength];
1743
+ const data = toBuffer(arrayBuffer);
1744
+ if (!compress) {
1745
+ this._state = DEFAULT;
1746
+ this.sendFrame(_Sender.frame(data, options), cb);
1747
+ this.dequeue();
1748
+ } else {
1749
+ this.dispatch(data, compress, options, cb);
1750
+ }
1751
+ }).catch((err) => {
1752
+ process.nextTick(onError, this, err, cb);
1753
+ });
1754
+ }
1755
+ /**
1756
+ * Dispatches a message.
1757
+ *
1758
+ * @param {(Buffer|String)} data The message to send
1759
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1760
+ * `data`
1761
+ * @param {Object} options Options object
1762
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1763
+ * FIN bit
1764
+ * @param {Function} [options.generateMask] The function used to generate the
1765
+ * masking key
1766
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1767
+ * `data`
1768
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1769
+ * key
1770
+ * @param {Number} options.opcode The opcode
1771
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1772
+ * modified
1773
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1774
+ * RSV1 bit
1775
+ * @param {Function} [cb] Callback
1776
+ * @private
1777
+ */
1778
+ dispatch(data, compress, options, cb) {
1779
+ if (!compress) {
1780
+ this.sendFrame(_Sender.frame(data, options), cb);
1781
+ return;
1782
+ }
1783
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1784
+ this._bufferedBytes += options[kByteLength];
1785
+ this._state = DEFLATING;
1786
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1787
+ if (this._socket.destroyed) {
1788
+ const err = new Error(
1789
+ "The socket was closed while data was being compressed"
1790
+ );
1791
+ callCallbacks(this, err, cb);
1792
+ return;
1793
+ }
1794
+ this._bufferedBytes -= options[kByteLength];
1795
+ this._state = DEFAULT;
1796
+ options.readOnly = false;
1797
+ this.sendFrame(_Sender.frame(buf, options), cb);
1798
+ this.dequeue();
1799
+ });
1800
+ }
1801
+ /**
1802
+ * Executes queued send operations.
1803
+ *
1804
+ * @private
1805
+ */
1806
+ dequeue() {
1807
+ while (this._state === DEFAULT && this._queue.length) {
1808
+ const params = this._queue.shift();
1809
+ this._bufferedBytes -= params[3][kByteLength];
1810
+ Reflect.apply(params[0], this, params.slice(1));
1811
+ }
1812
+ }
1813
+ /**
1814
+ * Enqueues a send operation.
1815
+ *
1816
+ * @param {Array} params Send operation parameters.
1817
+ * @private
1818
+ */
1819
+ enqueue(params) {
1820
+ this._bufferedBytes += params[3][kByteLength];
1821
+ this._queue.push(params);
1822
+ }
1823
+ /**
1824
+ * Sends a frame.
1825
+ *
1826
+ * @param {(Buffer | String)[]} list The frame to send
1827
+ * @param {Function} [cb] Callback
1828
+ * @private
1829
+ */
1830
+ sendFrame(list, cb) {
1831
+ if (list.length === 2) {
1832
+ this._socket.cork();
1833
+ this._socket.write(list[0]);
1834
+ this._socket.write(list[1], cb);
1835
+ this._socket.uncork();
1836
+ } else {
1837
+ this._socket.write(list[0], cb);
1838
+ }
1839
+ }
1840
+ };
1841
+ module2.exports = Sender2;
1842
+ function callCallbacks(sender, err, cb) {
1843
+ if (typeof cb === "function") cb(err);
1844
+ for (let i = 0; i < sender._queue.length; i++) {
1845
+ const params = sender._queue[i];
1846
+ const callback = params[params.length - 1];
1847
+ if (typeof callback === "function") callback(err);
1848
+ }
1849
+ }
1850
+ function onError(sender, err, cb) {
1851
+ callCallbacks(sender, err, cb);
1852
+ sender.onerror(err);
1853
+ }
1854
+ }
1855
+ });
1856
+
1857
+ // ../../node_modules/ws/lib/event-target.js
1858
+ var require_event_target = __commonJS({
1859
+ "../../node_modules/ws/lib/event-target.js"(exports2, module2) {
1860
+ "use strict";
1861
+ var { kForOnEventAttribute, kListener } = require_constants();
1862
+ var kCode = Symbol("kCode");
1863
+ var kData = Symbol("kData");
1864
+ var kError = Symbol("kError");
1865
+ var kMessage = Symbol("kMessage");
1866
+ var kReason = Symbol("kReason");
1867
+ var kTarget = Symbol("kTarget");
1868
+ var kType = Symbol("kType");
1869
+ var kWasClean = Symbol("kWasClean");
1870
+ var Event = class {
1871
+ /**
1872
+ * Create a new `Event`.
1873
+ *
1874
+ * @param {String} type The name of the event
1875
+ * @throws {TypeError} If the `type` argument is not specified
1876
+ */
1877
+ constructor(type) {
1878
+ this[kTarget] = null;
1879
+ this[kType] = type;
1880
+ }
1881
+ /**
1882
+ * @type {*}
1883
+ */
1884
+ get target() {
1885
+ return this[kTarget];
1886
+ }
1887
+ /**
1888
+ * @type {String}
1889
+ */
1890
+ get type() {
1891
+ return this[kType];
1892
+ }
1893
+ };
1894
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
1895
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
1896
+ var CloseEvent = class extends Event {
1897
+ /**
1898
+ * Create a new `CloseEvent`.
1899
+ *
1900
+ * @param {String} type The name of the event
1901
+ * @param {Object} [options] A dictionary object that allows for setting
1902
+ * attributes via object members of the same name
1903
+ * @param {Number} [options.code=0] The status code explaining why the
1904
+ * connection was closed
1905
+ * @param {String} [options.reason=''] A human-readable string explaining why
1906
+ * the connection was closed
1907
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1908
+ * connection was cleanly closed
1909
+ */
1910
+ constructor(type, options = {}) {
1911
+ super(type);
1912
+ this[kCode] = options.code === void 0 ? 0 : options.code;
1913
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
1914
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1915
+ }
1916
+ /**
1917
+ * @type {Number}
1918
+ */
1919
+ get code() {
1920
+ return this[kCode];
1921
+ }
1922
+ /**
1923
+ * @type {String}
1924
+ */
1925
+ get reason() {
1926
+ return this[kReason];
1927
+ }
1928
+ /**
1929
+ * @type {Boolean}
1930
+ */
1931
+ get wasClean() {
1932
+ return this[kWasClean];
1933
+ }
1934
+ };
1935
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1936
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1937
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1938
+ var ErrorEvent = class extends Event {
1939
+ /**
1940
+ * Create a new `ErrorEvent`.
1941
+ *
1942
+ * @param {String} type The name of the event
1943
+ * @param {Object} [options] A dictionary object that allows for setting
1944
+ * attributes via object members of the same name
1945
+ * @param {*} [options.error=null] The error that generated this event
1946
+ * @param {String} [options.message=''] The error message
1947
+ */
1948
+ constructor(type, options = {}) {
1949
+ super(type);
1950
+ this[kError] = options.error === void 0 ? null : options.error;
1951
+ this[kMessage] = options.message === void 0 ? "" : options.message;
1952
+ }
1953
+ /**
1954
+ * @type {*}
1955
+ */
1956
+ get error() {
1957
+ return this[kError];
1958
+ }
1959
+ /**
1960
+ * @type {String}
1961
+ */
1962
+ get message() {
1963
+ return this[kMessage];
1964
+ }
1965
+ };
1966
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1967
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1968
+ var MessageEvent = class extends Event {
1969
+ /**
1970
+ * Create a new `MessageEvent`.
1971
+ *
1972
+ * @param {String} type The name of the event
1973
+ * @param {Object} [options] A dictionary object that allows for setting
1974
+ * attributes via object members of the same name
1975
+ * @param {*} [options.data=null] The message content
1976
+ */
1977
+ constructor(type, options = {}) {
1978
+ super(type);
1979
+ this[kData] = options.data === void 0 ? null : options.data;
1980
+ }
1981
+ /**
1982
+ * @type {*}
1983
+ */
1984
+ get data() {
1985
+ return this[kData];
1986
+ }
1987
+ };
1988
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
1989
+ var EventTarget = {
1990
+ /**
1991
+ * Register an event listener.
1992
+ *
1993
+ * @param {String} type A string representing the event type to listen for
1994
+ * @param {(Function|Object)} handler The listener to add
1995
+ * @param {Object} [options] An options object specifies characteristics about
1996
+ * the event listener
1997
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
1998
+ * listener should be invoked at most once after being added. If `true`,
1999
+ * the listener would be automatically removed when invoked.
2000
+ * @public
2001
+ */
2002
+ addEventListener(type, handler, options = {}) {
2003
+ for (const listener of this.listeners(type)) {
2004
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2005
+ return;
2006
+ }
2007
+ }
2008
+ let wrapper;
2009
+ if (type === "message") {
2010
+ wrapper = function onMessage(data, isBinary) {
2011
+ const event = new MessageEvent("message", {
2012
+ data: isBinary ? data : data.toString()
2013
+ });
2014
+ event[kTarget] = this;
2015
+ callListener(handler, this, event);
2016
+ };
2017
+ } else if (type === "close") {
2018
+ wrapper = function onClose(code, message) {
2019
+ const event = new CloseEvent("close", {
2020
+ code,
2021
+ reason: message.toString(),
2022
+ wasClean: this._closeFrameReceived && this._closeFrameSent
2023
+ });
2024
+ event[kTarget] = this;
2025
+ callListener(handler, this, event);
2026
+ };
2027
+ } else if (type === "error") {
2028
+ wrapper = function onError(error) {
2029
+ const event = new ErrorEvent("error", {
2030
+ error,
2031
+ message: error.message
2032
+ });
2033
+ event[kTarget] = this;
2034
+ callListener(handler, this, event);
2035
+ };
2036
+ } else if (type === "open") {
2037
+ wrapper = function onOpen() {
2038
+ const event = new Event("open");
2039
+ event[kTarget] = this;
2040
+ callListener(handler, this, event);
2041
+ };
2042
+ } else {
2043
+ return;
2044
+ }
2045
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2046
+ wrapper[kListener] = handler;
2047
+ if (options.once) {
2048
+ this.once(type, wrapper);
2049
+ } else {
2050
+ this.on(type, wrapper);
2051
+ }
2052
+ },
2053
+ /**
2054
+ * Remove an event listener.
2055
+ *
2056
+ * @param {String} type A string representing the event type to remove
2057
+ * @param {(Function|Object)} handler The listener to remove
2058
+ * @public
2059
+ */
2060
+ removeEventListener(type, handler) {
2061
+ for (const listener of this.listeners(type)) {
2062
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2063
+ this.removeListener(type, listener);
2064
+ break;
2065
+ }
2066
+ }
2067
+ }
2068
+ };
2069
+ module2.exports = {
2070
+ CloseEvent,
2071
+ ErrorEvent,
2072
+ Event,
2073
+ EventTarget,
2074
+ MessageEvent
2075
+ };
2076
+ function callListener(listener, thisArg, event) {
2077
+ if (typeof listener === "object" && listener.handleEvent) {
2078
+ listener.handleEvent.call(listener, event);
2079
+ } else {
2080
+ listener.call(thisArg, event);
2081
+ }
2082
+ }
2083
+ }
2084
+ });
2085
+
2086
+ // ../../node_modules/ws/lib/extension.js
2087
+ var require_extension = __commonJS({
2088
+ "../../node_modules/ws/lib/extension.js"(exports2, module2) {
2089
+ "use strict";
2090
+ var { tokenChars } = require_validation();
2091
+ function push(dest, name, elem) {
2092
+ if (dest[name] === void 0) dest[name] = [elem];
2093
+ else dest[name].push(elem);
2094
+ }
2095
+ function parse(header) {
2096
+ const offers = /* @__PURE__ */ Object.create(null);
2097
+ let params = /* @__PURE__ */ Object.create(null);
2098
+ let mustUnescape = false;
2099
+ let isEscaping = false;
2100
+ let inQuotes = false;
2101
+ let extensionName;
2102
+ let paramName;
2103
+ let start = -1;
2104
+ let code = -1;
2105
+ let end = -1;
2106
+ let i = 0;
2107
+ for (; i < header.length; i++) {
2108
+ code = header.charCodeAt(i);
2109
+ if (extensionName === void 0) {
2110
+ if (end === -1 && tokenChars[code] === 1) {
2111
+ if (start === -1) start = i;
2112
+ } else if (i !== 0 && (code === 32 || code === 9)) {
2113
+ if (end === -1 && start !== -1) end = i;
2114
+ } else if (code === 59 || code === 44) {
2115
+ if (start === -1) {
2116
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2117
+ }
2118
+ if (end === -1) end = i;
2119
+ const name = header.slice(start, end);
2120
+ if (code === 44) {
2121
+ push(offers, name, params);
2122
+ params = /* @__PURE__ */ Object.create(null);
2123
+ } else {
2124
+ extensionName = name;
2125
+ }
2126
+ start = end = -1;
2127
+ } else {
2128
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2129
+ }
2130
+ } else if (paramName === void 0) {
2131
+ if (end === -1 && tokenChars[code] === 1) {
2132
+ if (start === -1) start = i;
2133
+ } else if (code === 32 || code === 9) {
2134
+ if (end === -1 && start !== -1) end = i;
2135
+ } else if (code === 59 || code === 44) {
2136
+ if (start === -1) {
2137
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2138
+ }
2139
+ if (end === -1) end = i;
2140
+ push(params, header.slice(start, end), true);
2141
+ if (code === 44) {
2142
+ push(offers, extensionName, params);
2143
+ params = /* @__PURE__ */ Object.create(null);
2144
+ extensionName = void 0;
2145
+ }
2146
+ start = end = -1;
2147
+ } else if (code === 61 && start !== -1 && end === -1) {
2148
+ paramName = header.slice(start, i);
2149
+ start = end = -1;
2150
+ } else {
2151
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2152
+ }
2153
+ } else {
2154
+ if (isEscaping) {
2155
+ if (tokenChars[code] !== 1) {
2156
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2157
+ }
2158
+ if (start === -1) start = i;
2159
+ else if (!mustUnescape) mustUnescape = true;
2160
+ isEscaping = false;
2161
+ } else if (inQuotes) {
2162
+ if (tokenChars[code] === 1) {
2163
+ if (start === -1) start = i;
2164
+ } else if (code === 34 && start !== -1) {
2165
+ inQuotes = false;
2166
+ end = i;
2167
+ } else if (code === 92) {
2168
+ isEscaping = true;
2169
+ } else {
2170
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2171
+ }
2172
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2173
+ inQuotes = true;
2174
+ } else if (end === -1 && tokenChars[code] === 1) {
2175
+ if (start === -1) start = i;
2176
+ } else if (start !== -1 && (code === 32 || code === 9)) {
2177
+ if (end === -1) end = i;
2178
+ } else if (code === 59 || code === 44) {
2179
+ if (start === -1) {
2180
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2181
+ }
2182
+ if (end === -1) end = i;
2183
+ let value = header.slice(start, end);
2184
+ if (mustUnescape) {
2185
+ value = value.replace(/\\/g, "");
2186
+ mustUnescape = false;
2187
+ }
2188
+ push(params, paramName, value);
2189
+ if (code === 44) {
2190
+ push(offers, extensionName, params);
2191
+ params = /* @__PURE__ */ Object.create(null);
2192
+ extensionName = void 0;
2193
+ }
2194
+ paramName = void 0;
2195
+ start = end = -1;
2196
+ } else {
2197
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2198
+ }
2199
+ }
2200
+ }
2201
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
2202
+ throw new SyntaxError("Unexpected end of input");
2203
+ }
2204
+ if (end === -1) end = i;
2205
+ const token = header.slice(start, end);
2206
+ if (extensionName === void 0) {
2207
+ push(offers, token, params);
2208
+ } else {
2209
+ if (paramName === void 0) {
2210
+ push(params, token, true);
2211
+ } else if (mustUnescape) {
2212
+ push(params, paramName, token.replace(/\\/g, ""));
2213
+ } else {
2214
+ push(params, paramName, token);
2215
+ }
2216
+ push(offers, extensionName, params);
2217
+ }
2218
+ return offers;
2219
+ }
2220
+ function format(extensions) {
2221
+ return Object.keys(extensions).map((extension2) => {
2222
+ let configurations = extensions[extension2];
2223
+ if (!Array.isArray(configurations)) configurations = [configurations];
2224
+ return configurations.map((params) => {
2225
+ return [extension2].concat(
2226
+ Object.keys(params).map((k) => {
2227
+ let values = params[k];
2228
+ if (!Array.isArray(values)) values = [values];
2229
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2230
+ })
2231
+ ).join("; ");
2232
+ }).join(", ");
2233
+ }).join(", ");
2234
+ }
2235
+ module2.exports = { format, parse };
2236
+ }
2237
+ });
2238
+
2239
+ // ../../node_modules/ws/lib/websocket.js
2240
+ var require_websocket = __commonJS({
2241
+ "../../node_modules/ws/lib/websocket.js"(exports2, module2) {
2242
+ "use strict";
2243
+ var EventEmitter = require("events");
2244
+ var https = require("https");
2245
+ var http = require("http");
2246
+ var net = require("net");
2247
+ var tls = require("tls");
2248
+ var { randomBytes, createHash } = require("crypto");
2249
+ var { Duplex, Readable } = require("stream");
2250
+ var { URL } = require("url");
2251
+ var PerMessageDeflate2 = require_permessage_deflate();
2252
+ var Receiver2 = require_receiver();
2253
+ var Sender2 = require_sender();
2254
+ var { isBlob } = require_validation();
2255
+ var {
2256
+ BINARY_TYPES,
2257
+ CLOSE_TIMEOUT,
2258
+ EMPTY_BUFFER,
2259
+ GUID,
2260
+ kForOnEventAttribute,
2261
+ kListener,
2262
+ kStatusCode,
2263
+ kWebSocket,
2264
+ NOOP
2265
+ } = require_constants();
2266
+ var {
2267
+ EventTarget: { addEventListener, removeEventListener }
2268
+ } = require_event_target();
2269
+ var { format, parse } = require_extension();
2270
+ var { toBuffer } = require_buffer_util();
2271
+ var kAborted = Symbol("kAborted");
2272
+ var protocolVersions = [8, 13];
2273
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2274
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2275
+ var WebSocket2 = class _WebSocket extends EventEmitter {
2276
+ /**
2277
+ * Create a new `WebSocket`.
2278
+ *
2279
+ * @param {(String|URL)} address The URL to which to connect
2280
+ * @param {(String|String[])} [protocols] The subprotocols
2281
+ * @param {Object} [options] Connection options
2282
+ */
2283
+ constructor(address, protocols, options) {
2284
+ super();
2285
+ this._binaryType = BINARY_TYPES[0];
2286
+ this._closeCode = 1006;
2287
+ this._closeFrameReceived = false;
2288
+ this._closeFrameSent = false;
2289
+ this._closeMessage = EMPTY_BUFFER;
2290
+ this._closeTimer = null;
2291
+ this._errorEmitted = false;
2292
+ this._extensions = {};
2293
+ this._paused = false;
2294
+ this._protocol = "";
2295
+ this._readyState = _WebSocket.CONNECTING;
2296
+ this._receiver = null;
2297
+ this._sender = null;
2298
+ this._socket = null;
2299
+ if (address !== null) {
2300
+ this._bufferedAmount = 0;
2301
+ this._isServer = false;
2302
+ this._redirects = 0;
2303
+ if (protocols === void 0) {
2304
+ if (!options || options.protocols === void 0) {
2305
+ protocols = [];
2306
+ } else if (Array.isArray(options.protocols)) {
2307
+ protocols = options.protocols;
2308
+ } else {
2309
+ protocols = [options.protocols];
2310
+ }
2311
+ } else if (!Array.isArray(protocols)) {
2312
+ if (typeof protocols === "object" && protocols !== null) {
2313
+ options = protocols;
2314
+ if (options.protocols === void 0) {
2315
+ protocols = [];
2316
+ } else if (Array.isArray(options.protocols)) {
2317
+ protocols = options.protocols;
2318
+ } else {
2319
+ protocols = [options.protocols];
2320
+ }
2321
+ } else {
2322
+ protocols = [protocols];
2323
+ }
2324
+ }
2325
+ initAsClient(this, address, protocols, options);
2326
+ } else {
2327
+ this._autoPong = options.autoPong;
2328
+ this._closeTimeout = options.closeTimeout;
2329
+ this._isServer = true;
2330
+ }
2331
+ }
2332
+ /**
2333
+ * For historical reasons, the custom "nodebuffer" type is used by the default
2334
+ * instead of "blob".
2335
+ *
2336
+ * @type {String}
2337
+ */
2338
+ get binaryType() {
2339
+ return this._binaryType;
2340
+ }
2341
+ set binaryType(type) {
2342
+ if (!BINARY_TYPES.includes(type)) return;
2343
+ this._binaryType = type;
2344
+ if (this._receiver) this._receiver._binaryType = type;
2345
+ }
2346
+ /**
2347
+ * @type {Number}
2348
+ */
2349
+ get bufferedAmount() {
2350
+ if (!this._socket) return this._bufferedAmount;
2351
+ return this._socket._writableState.length + this._sender._bufferedBytes;
2352
+ }
2353
+ /**
2354
+ * @type {String}
2355
+ */
2356
+ get extensions() {
2357
+ return Object.keys(this._extensions).join();
2358
+ }
2359
+ /**
2360
+ * @type {Boolean}
2361
+ */
2362
+ get isPaused() {
2363
+ return this._paused;
2364
+ }
2365
+ /**
2366
+ * @type {Function}
2367
+ */
2368
+ /* istanbul ignore next */
2369
+ get onclose() {
2370
+ return null;
2371
+ }
2372
+ /**
2373
+ * @type {Function}
2374
+ */
2375
+ /* istanbul ignore next */
2376
+ get onerror() {
2377
+ return null;
2378
+ }
2379
+ /**
2380
+ * @type {Function}
2381
+ */
2382
+ /* istanbul ignore next */
2383
+ get onopen() {
2384
+ return null;
2385
+ }
2386
+ /**
2387
+ * @type {Function}
2388
+ */
2389
+ /* istanbul ignore next */
2390
+ get onmessage() {
2391
+ return null;
2392
+ }
2393
+ /**
2394
+ * @type {String}
2395
+ */
2396
+ get protocol() {
2397
+ return this._protocol;
2398
+ }
2399
+ /**
2400
+ * @type {Number}
2401
+ */
2402
+ get readyState() {
2403
+ return this._readyState;
2404
+ }
2405
+ /**
2406
+ * @type {String}
2407
+ */
2408
+ get url() {
2409
+ return this._url;
2410
+ }
2411
+ /**
2412
+ * Set up the socket and the internal resources.
2413
+ *
2414
+ * @param {Duplex} socket The network socket between the server and client
2415
+ * @param {Buffer} head The first packet of the upgraded stream
2416
+ * @param {Object} options Options object
2417
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2418
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2419
+ * multiple times in the same tick
2420
+ * @param {Function} [options.generateMask] The function used to generate the
2421
+ * masking key
2422
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
2423
+ * buffered data chunks
2424
+ * @param {Number} [options.maxFragments=0] The maximum number of message
2425
+ * fragments
2426
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
2427
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2428
+ * not to skip UTF-8 validation for text and close messages
2429
+ * @private
2430
+ */
2431
+ setSocket(socket, head, options) {
2432
+ const receiver = new Receiver2({
2433
+ allowSynchronousEvents: options.allowSynchronousEvents,
2434
+ binaryType: this.binaryType,
2435
+ extensions: this._extensions,
2436
+ isServer: this._isServer,
2437
+ maxBufferedChunks: options.maxBufferedChunks,
2438
+ maxFragments: options.maxFragments,
2439
+ maxPayload: options.maxPayload,
2440
+ skipUTF8Validation: options.skipUTF8Validation
2441
+ });
2442
+ const sender = new Sender2(socket, this._extensions, options.generateMask);
2443
+ this._receiver = receiver;
2444
+ this._sender = sender;
2445
+ this._socket = socket;
2446
+ receiver[kWebSocket] = this;
2447
+ sender[kWebSocket] = this;
2448
+ socket[kWebSocket] = this;
2449
+ receiver.on("conclude", receiverOnConclude);
2450
+ receiver.on("drain", receiverOnDrain);
2451
+ receiver.on("error", receiverOnError);
2452
+ receiver.on("message", receiverOnMessage);
2453
+ receiver.on("ping", receiverOnPing);
2454
+ receiver.on("pong", receiverOnPong);
2455
+ sender.onerror = senderOnError;
2456
+ if (socket.setTimeout) socket.setTimeout(0);
2457
+ if (socket.setNoDelay) socket.setNoDelay();
2458
+ if (head.length > 0) socket.unshift(head);
2459
+ socket.on("close", socketOnClose);
2460
+ socket.on("data", socketOnData);
2461
+ socket.on("end", socketOnEnd);
2462
+ socket.on("error", socketOnError);
2463
+ this._readyState = _WebSocket.OPEN;
2464
+ this.emit("open");
2465
+ }
2466
+ /**
2467
+ * Emit the `'close'` event.
2468
+ *
2469
+ * @private
2470
+ */
2471
+ emitClose() {
2472
+ if (!this._socket) {
2473
+ this._readyState = _WebSocket.CLOSED;
2474
+ this.emit("close", this._closeCode, this._closeMessage);
2475
+ return;
2476
+ }
2477
+ if (this._extensions[PerMessageDeflate2.extensionName]) {
2478
+ this._extensions[PerMessageDeflate2.extensionName].cleanup();
2479
+ }
2480
+ this._receiver.removeAllListeners();
2481
+ this._readyState = _WebSocket.CLOSED;
2482
+ this.emit("close", this._closeCode, this._closeMessage);
2483
+ }
2484
+ /**
2485
+ * Start a closing handshake.
2486
+ *
2487
+ * +----------+ +-----------+ +----------+
2488
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2489
+ * | +----------+ +-----------+ +----------+ |
2490
+ * +----------+ +-----------+ |
2491
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2492
+ * +----------+ +-----------+ |
2493
+ * | | | +---+ |
2494
+ * +------------------------+-->|fin| - - - -
2495
+ * | +---+ | +---+
2496
+ * - - - - -|fin|<---------------------+
2497
+ * +---+
2498
+ *
2499
+ * @param {Number} [code] Status code explaining why the connection is closing
2500
+ * @param {(String|Buffer)} [data] The reason why the connection is
2501
+ * closing
2502
+ * @public
2503
+ */
2504
+ close(code, data) {
2505
+ if (this.readyState === _WebSocket.CLOSED) return;
2506
+ if (this.readyState === _WebSocket.CONNECTING) {
2507
+ const msg = "WebSocket was closed before the connection was established";
2508
+ abortHandshake(this, this._req, msg);
2509
+ return;
2510
+ }
2511
+ if (this.readyState === _WebSocket.CLOSING) {
2512
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
2513
+ this._socket.end();
2514
+ }
2515
+ return;
2516
+ }
2517
+ this._sender.close(code, data, !this._isServer, (err) => {
2518
+ if (err) return;
2519
+ this._closeFrameSent = true;
2520
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2521
+ this._socket.end();
2522
+ }
2523
+ });
2524
+ this._readyState = _WebSocket.CLOSING;
2525
+ setCloseTimer(this);
2526
+ }
2527
+ /**
2528
+ * Pause the socket.
2529
+ *
2530
+ * @public
2531
+ */
2532
+ pause() {
2533
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2534
+ return;
2535
+ }
2536
+ this._paused = true;
2537
+ this._socket.pause();
2538
+ }
2539
+ /**
2540
+ * Send a ping.
2541
+ *
2542
+ * @param {*} [data] The data to send
2543
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2544
+ * @param {Function} [cb] Callback which is executed when the ping is sent
2545
+ * @public
2546
+ */
2547
+ ping(data, mask, cb) {
2548
+ if (this.readyState === _WebSocket.CONNECTING) {
2549
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2550
+ }
2551
+ if (typeof data === "function") {
2552
+ cb = data;
2553
+ data = mask = void 0;
2554
+ } else if (typeof mask === "function") {
2555
+ cb = mask;
2556
+ mask = void 0;
2557
+ }
2558
+ if (typeof data === "number") data = data.toString();
2559
+ if (this.readyState !== _WebSocket.OPEN) {
2560
+ sendAfterClose(this, data, cb);
2561
+ return;
2562
+ }
2563
+ if (mask === void 0) mask = !this._isServer;
2564
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2565
+ }
2566
+ /**
2567
+ * Send a pong.
2568
+ *
2569
+ * @param {*} [data] The data to send
2570
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2571
+ * @param {Function} [cb] Callback which is executed when the pong is sent
2572
+ * @public
2573
+ */
2574
+ pong(data, mask, cb) {
2575
+ if (this.readyState === _WebSocket.CONNECTING) {
2576
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2577
+ }
2578
+ if (typeof data === "function") {
2579
+ cb = data;
2580
+ data = mask = void 0;
2581
+ } else if (typeof mask === "function") {
2582
+ cb = mask;
2583
+ mask = void 0;
2584
+ }
2585
+ if (typeof data === "number") data = data.toString();
2586
+ if (this.readyState !== _WebSocket.OPEN) {
2587
+ sendAfterClose(this, data, cb);
2588
+ return;
2589
+ }
2590
+ if (mask === void 0) mask = !this._isServer;
2591
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2592
+ }
2593
+ /**
2594
+ * Resume the socket.
2595
+ *
2596
+ * @public
2597
+ */
2598
+ resume() {
2599
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2600
+ return;
2601
+ }
2602
+ this._paused = false;
2603
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
2604
+ }
2605
+ /**
2606
+ * Send a data message.
2607
+ *
2608
+ * @param {*} data The message to send
2609
+ * @param {Object} [options] Options object
2610
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2611
+ * text
2612
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
2613
+ * `data`
2614
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2615
+ * last one
2616
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2617
+ * @param {Function} [cb] Callback which is executed when data is written out
2618
+ * @public
2619
+ */
2620
+ send(data, options, cb) {
2621
+ if (this.readyState === _WebSocket.CONNECTING) {
2622
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2623
+ }
2624
+ if (typeof options === "function") {
2625
+ cb = options;
2626
+ options = {};
2627
+ }
2628
+ if (typeof data === "number") data = data.toString();
2629
+ if (this.readyState !== _WebSocket.OPEN) {
2630
+ sendAfterClose(this, data, cb);
2631
+ return;
2632
+ }
2633
+ const opts = {
2634
+ binary: typeof data !== "string",
2635
+ mask: !this._isServer,
2636
+ compress: true,
2637
+ fin: true,
2638
+ ...options
2639
+ };
2640
+ if (!this._extensions[PerMessageDeflate2.extensionName]) {
2641
+ opts.compress = false;
2642
+ }
2643
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
2644
+ }
2645
+ /**
2646
+ * Forcibly close the connection.
2647
+ *
2648
+ * @public
2649
+ */
2650
+ terminate() {
2651
+ if (this.readyState === _WebSocket.CLOSED) return;
2652
+ if (this.readyState === _WebSocket.CONNECTING) {
2653
+ const msg = "WebSocket was closed before the connection was established";
2654
+ abortHandshake(this, this._req, msg);
2655
+ return;
2656
+ }
2657
+ if (this._socket) {
2658
+ this._readyState = _WebSocket.CLOSING;
2659
+ this._socket.destroy();
2660
+ }
2661
+ }
2662
+ };
2663
+ Object.defineProperty(WebSocket2, "CONNECTING", {
2664
+ enumerable: true,
2665
+ value: readyStates.indexOf("CONNECTING")
2666
+ });
2667
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
2668
+ enumerable: true,
2669
+ value: readyStates.indexOf("CONNECTING")
2670
+ });
2671
+ Object.defineProperty(WebSocket2, "OPEN", {
2672
+ enumerable: true,
2673
+ value: readyStates.indexOf("OPEN")
2674
+ });
2675
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
2676
+ enumerable: true,
2677
+ value: readyStates.indexOf("OPEN")
2678
+ });
2679
+ Object.defineProperty(WebSocket2, "CLOSING", {
2680
+ enumerable: true,
2681
+ value: readyStates.indexOf("CLOSING")
2682
+ });
2683
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
2684
+ enumerable: true,
2685
+ value: readyStates.indexOf("CLOSING")
2686
+ });
2687
+ Object.defineProperty(WebSocket2, "CLOSED", {
2688
+ enumerable: true,
2689
+ value: readyStates.indexOf("CLOSED")
2690
+ });
2691
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
2692
+ enumerable: true,
2693
+ value: readyStates.indexOf("CLOSED")
2694
+ });
2695
+ [
2696
+ "binaryType",
2697
+ "bufferedAmount",
2698
+ "extensions",
2699
+ "isPaused",
2700
+ "protocol",
2701
+ "readyState",
2702
+ "url"
2703
+ ].forEach((property) => {
2704
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
2705
+ });
2706
+ ["open", "error", "close", "message"].forEach((method) => {
2707
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
2708
+ enumerable: true,
2709
+ get() {
2710
+ for (const listener of this.listeners(method)) {
2711
+ if (listener[kForOnEventAttribute]) return listener[kListener];
2712
+ }
2713
+ return null;
2714
+ },
2715
+ set(handler) {
2716
+ for (const listener of this.listeners(method)) {
2717
+ if (listener[kForOnEventAttribute]) {
2718
+ this.removeListener(method, listener);
2719
+ break;
2720
+ }
2721
+ }
2722
+ if (typeof handler !== "function") return;
2723
+ this.addEventListener(method, handler, {
2724
+ [kForOnEventAttribute]: true
2725
+ });
2726
+ }
2727
+ });
2728
+ });
2729
+ WebSocket2.prototype.addEventListener = addEventListener;
2730
+ WebSocket2.prototype.removeEventListener = removeEventListener;
2731
+ module2.exports = WebSocket2;
2732
+ function initAsClient(websocket, address, protocols, options) {
2733
+ const opts = {
2734
+ allowSynchronousEvents: true,
2735
+ autoPong: true,
2736
+ closeTimeout: CLOSE_TIMEOUT,
2737
+ protocolVersion: protocolVersions[1],
2738
+ maxBufferedChunks: 256 * 1024,
2739
+ maxFragments: 16 * 1024,
2740
+ maxPayload: 100 * 1024 * 1024,
2741
+ skipUTF8Validation: false,
2742
+ perMessageDeflate: true,
2743
+ followRedirects: false,
2744
+ maxRedirects: 10,
2745
+ ...options,
2746
+ socketPath: void 0,
2747
+ hostname: void 0,
2748
+ protocol: void 0,
2749
+ protocols: void 0,
2750
+ timeout: void 0,
2751
+ method: "GET",
2752
+ host: void 0,
2753
+ path: void 0,
2754
+ port: void 0
2755
+ };
2756
+ websocket._autoPong = opts.autoPong;
2757
+ websocket._closeTimeout = opts.closeTimeout;
2758
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2759
+ throw new RangeError(
2760
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2761
+ );
2762
+ }
2763
+ let parsedUrl;
2764
+ if (address instanceof URL) {
2765
+ parsedUrl = address;
2766
+ } else {
2767
+ try {
2768
+ parsedUrl = new URL(address);
2769
+ } catch {
2770
+ throw new SyntaxError(`Invalid URL: ${address}`);
2771
+ }
2772
+ }
2773
+ if (parsedUrl.protocol === "http:") {
2774
+ parsedUrl.protocol = "ws:";
2775
+ } else if (parsedUrl.protocol === "https:") {
2776
+ parsedUrl.protocol = "wss:";
2777
+ }
2778
+ websocket._url = parsedUrl.href;
2779
+ const isSecure = parsedUrl.protocol === "wss:";
2780
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2781
+ let invalidUrlMessage;
2782
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2783
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
2784
+ } else if (isIpcUrl && !parsedUrl.pathname) {
2785
+ invalidUrlMessage = "The URL's pathname is empty";
2786
+ } else if (parsedUrl.hash) {
2787
+ invalidUrlMessage = "The URL contains a fragment identifier";
2788
+ }
2789
+ if (invalidUrlMessage) {
2790
+ const err = new SyntaxError(invalidUrlMessage);
2791
+ if (websocket._redirects === 0) {
2792
+ throw err;
2793
+ } else {
2794
+ emitErrorAndClose(websocket, err);
2795
+ return;
2796
+ }
2797
+ }
2798
+ const defaultPort = isSecure ? 443 : 80;
2799
+ const key = randomBytes(16).toString("base64");
2800
+ const request = isSecure ? https.request : http.request;
2801
+ const protocolSet = /* @__PURE__ */ new Set();
2802
+ let perMessageDeflate;
2803
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2804
+ opts.defaultPort = opts.defaultPort || defaultPort;
2805
+ opts.port = parsedUrl.port || defaultPort;
2806
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2807
+ opts.headers = {
2808
+ ...opts.headers,
2809
+ "Sec-WebSocket-Version": opts.protocolVersion,
2810
+ "Sec-WebSocket-Key": key,
2811
+ Connection: "Upgrade",
2812
+ Upgrade: "websocket"
2813
+ };
2814
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2815
+ opts.timeout = opts.handshakeTimeout;
2816
+ if (opts.perMessageDeflate) {
2817
+ perMessageDeflate = new PerMessageDeflate2({
2818
+ ...opts.perMessageDeflate,
2819
+ isServer: false,
2820
+ maxPayload: opts.maxPayload
2821
+ });
2822
+ opts.headers["Sec-WebSocket-Extensions"] = format({
2823
+ [PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
2824
+ });
2825
+ }
2826
+ if (protocols.length) {
2827
+ for (const protocol of protocols) {
2828
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2829
+ throw new SyntaxError(
2830
+ "An invalid or duplicated subprotocol was specified"
2831
+ );
2832
+ }
2833
+ protocolSet.add(protocol);
2834
+ }
2835
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2836
+ }
2837
+ if (opts.origin) {
2838
+ if (opts.protocolVersion < 13) {
2839
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2840
+ } else {
2841
+ opts.headers.Origin = opts.origin;
2842
+ }
2843
+ }
2844
+ if (parsedUrl.username || parsedUrl.password) {
2845
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2846
+ }
2847
+ if (isIpcUrl) {
2848
+ const parts = opts.path.split(":");
2849
+ opts.socketPath = parts[0];
2850
+ opts.path = parts[1];
2851
+ }
2852
+ let req;
2853
+ if (opts.followRedirects) {
2854
+ if (websocket._redirects === 0) {
2855
+ websocket._originalIpc = isIpcUrl;
2856
+ websocket._originalSecure = isSecure;
2857
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2858
+ const headers = options && options.headers;
2859
+ options = { ...options, headers: {} };
2860
+ if (headers) {
2861
+ for (const [key2, value] of Object.entries(headers)) {
2862
+ options.headers[key2.toLowerCase()] = value;
2863
+ }
2864
+ }
2865
+ } else if (websocket.listenerCount("redirect") === 0) {
2866
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2867
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2868
+ delete opts.headers.authorization;
2869
+ delete opts.headers.cookie;
2870
+ if (!isSameHost) delete opts.headers.host;
2871
+ opts.auth = void 0;
2872
+ }
2873
+ }
2874
+ if (opts.auth && !options.headers.authorization) {
2875
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2876
+ }
2877
+ req = websocket._req = request(opts);
2878
+ if (websocket._redirects) {
2879
+ websocket.emit("redirect", websocket.url, req);
2880
+ }
2881
+ } else {
2882
+ req = websocket._req = request(opts);
2883
+ }
2884
+ if (opts.timeout) {
2885
+ req.on("timeout", () => {
2886
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2887
+ });
2888
+ }
2889
+ req.on("error", (err) => {
2890
+ if (req === null || req[kAborted]) return;
2891
+ req = websocket._req = null;
2892
+ emitErrorAndClose(websocket, err);
2893
+ });
2894
+ req.on("response", (res) => {
2895
+ const location = res.headers.location;
2896
+ const statusCode = res.statusCode;
2897
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2898
+ if (++websocket._redirects > opts.maxRedirects) {
2899
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2900
+ return;
2901
+ }
2902
+ req.abort();
2903
+ let addr;
2904
+ try {
2905
+ addr = new URL(location, address);
2906
+ } catch (e) {
2907
+ const err = new SyntaxError(`Invalid URL: ${location}`);
2908
+ emitErrorAndClose(websocket, err);
2909
+ return;
2910
+ }
2911
+ initAsClient(websocket, addr, protocols, options);
2912
+ } else if (!websocket.emit("unexpected-response", req, res)) {
2913
+ abortHandshake(
2914
+ websocket,
2915
+ req,
2916
+ `Unexpected server response: ${res.statusCode}`
2917
+ );
2918
+ }
2919
+ });
2920
+ req.on("upgrade", (res, socket, head) => {
2921
+ websocket.emit("upgrade", res);
2922
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
2923
+ req = websocket._req = null;
2924
+ const upgrade = res.headers.upgrade;
2925
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2926
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
2927
+ return;
2928
+ }
2929
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
2930
+ if (res.headers["sec-websocket-accept"] !== digest) {
2931
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2932
+ return;
2933
+ }
2934
+ const serverProt = res.headers["sec-websocket-protocol"];
2935
+ let protError;
2936
+ if (serverProt !== void 0) {
2937
+ if (!protocolSet.size) {
2938
+ protError = "Server sent a subprotocol but none was requested";
2939
+ } else if (!protocolSet.has(serverProt)) {
2940
+ protError = "Server sent an invalid subprotocol";
2941
+ }
2942
+ } else if (protocolSet.size) {
2943
+ protError = "Server sent no subprotocol";
2944
+ }
2945
+ if (protError) {
2946
+ abortHandshake(websocket, socket, protError);
2947
+ return;
2948
+ }
2949
+ if (serverProt) websocket._protocol = serverProt;
2950
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2951
+ if (secWebSocketExtensions !== void 0) {
2952
+ if (!perMessageDeflate) {
2953
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2954
+ abortHandshake(websocket, socket, message);
2955
+ return;
2956
+ }
2957
+ let extensions;
2958
+ try {
2959
+ extensions = parse(secWebSocketExtensions);
2960
+ } catch (err) {
2961
+ const message = "Invalid Sec-WebSocket-Extensions header";
2962
+ abortHandshake(websocket, socket, message);
2963
+ return;
2964
+ }
2965
+ const extensionNames = Object.keys(extensions);
2966
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
2967
+ const message = "Server indicated an extension that was not requested";
2968
+ abortHandshake(websocket, socket, message);
2969
+ return;
2970
+ }
2971
+ try {
2972
+ perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
2973
+ } catch (err) {
2974
+ const message = "Invalid Sec-WebSocket-Extensions header";
2975
+ abortHandshake(websocket, socket, message);
2976
+ return;
2977
+ }
2978
+ websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
2979
+ }
2980
+ websocket.setSocket(socket, head, {
2981
+ allowSynchronousEvents: opts.allowSynchronousEvents,
2982
+ generateMask: opts.generateMask,
2983
+ maxBufferedChunks: opts.maxBufferedChunks,
2984
+ maxFragments: opts.maxFragments,
2985
+ maxPayload: opts.maxPayload,
2986
+ skipUTF8Validation: opts.skipUTF8Validation
2987
+ });
2988
+ });
2989
+ if (opts.finishRequest) {
2990
+ opts.finishRequest(req, websocket);
2991
+ } else {
2992
+ req.end();
2993
+ }
2994
+ }
2995
+ function emitErrorAndClose(websocket, err) {
2996
+ websocket._readyState = WebSocket2.CLOSING;
2997
+ websocket._errorEmitted = true;
2998
+ websocket.emit("error", err);
2999
+ websocket.emitClose();
3000
+ }
3001
+ function netConnect(options) {
3002
+ options.path = options.socketPath;
3003
+ return net.connect(options);
3004
+ }
3005
+ function tlsConnect(options) {
3006
+ options.path = void 0;
3007
+ if (!options.servername && options.servername !== "") {
3008
+ options.servername = net.isIP(options.host) ? "" : options.host;
3009
+ }
3010
+ return tls.connect(options);
3011
+ }
3012
+ function abortHandshake(websocket, stream, message) {
3013
+ websocket._readyState = WebSocket2.CLOSING;
3014
+ const err = new Error(message);
3015
+ Error.captureStackTrace(err, abortHandshake);
3016
+ if (stream.setHeader) {
3017
+ stream[kAborted] = true;
3018
+ stream.abort();
3019
+ if (stream.socket && !stream.socket.destroyed) {
3020
+ stream.socket.destroy();
3021
+ }
3022
+ process.nextTick(emitErrorAndClose, websocket, err);
3023
+ } else {
3024
+ stream.destroy(err);
3025
+ stream.once("error", websocket.emit.bind(websocket, "error"));
3026
+ stream.once("close", websocket.emitClose.bind(websocket));
3027
+ }
3028
+ }
3029
+ function sendAfterClose(websocket, data, cb) {
3030
+ if (data) {
3031
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
3032
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
3033
+ else websocket._bufferedAmount += length;
3034
+ }
3035
+ if (cb) {
3036
+ const err = new Error(
3037
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
3038
+ );
3039
+ process.nextTick(cb, err);
3040
+ }
3041
+ }
3042
+ function receiverOnConclude(code, reason) {
3043
+ const websocket = this[kWebSocket];
3044
+ websocket._closeFrameReceived = true;
3045
+ websocket._closeMessage = reason;
3046
+ websocket._closeCode = code;
3047
+ if (websocket._socket[kWebSocket] === void 0) return;
3048
+ websocket._socket.removeListener("data", socketOnData);
3049
+ process.nextTick(resume, websocket._socket);
3050
+ if (code === 1005) websocket.close();
3051
+ else websocket.close(code, reason);
3052
+ }
3053
+ function receiverOnDrain() {
3054
+ const websocket = this[kWebSocket];
3055
+ if (!websocket.isPaused) websocket._socket.resume();
3056
+ }
3057
+ function receiverOnError(err) {
3058
+ const websocket = this[kWebSocket];
3059
+ if (websocket._socket[kWebSocket] !== void 0) {
3060
+ websocket._socket.removeListener("data", socketOnData);
3061
+ process.nextTick(resume, websocket._socket);
3062
+ websocket.close(err[kStatusCode]);
3063
+ }
3064
+ if (!websocket._errorEmitted) {
3065
+ websocket._errorEmitted = true;
3066
+ websocket.emit("error", err);
3067
+ }
3068
+ }
3069
+ function receiverOnFinish() {
3070
+ this[kWebSocket].emitClose();
3071
+ }
3072
+ function receiverOnMessage(data, isBinary) {
3073
+ this[kWebSocket].emit("message", data, isBinary);
3074
+ }
3075
+ function receiverOnPing(data) {
3076
+ const websocket = this[kWebSocket];
3077
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3078
+ websocket.emit("ping", data);
3079
+ }
3080
+ function receiverOnPong(data) {
3081
+ this[kWebSocket].emit("pong", data);
3082
+ }
3083
+ function resume(stream) {
3084
+ stream.resume();
3085
+ }
3086
+ function senderOnError(err) {
3087
+ const websocket = this[kWebSocket];
3088
+ if (websocket.readyState === WebSocket2.CLOSED) return;
3089
+ if (websocket.readyState === WebSocket2.OPEN) {
3090
+ websocket._readyState = WebSocket2.CLOSING;
3091
+ setCloseTimer(websocket);
3092
+ }
3093
+ this._socket.end();
3094
+ if (!websocket._errorEmitted) {
3095
+ websocket._errorEmitted = true;
3096
+ websocket.emit("error", err);
3097
+ }
3098
+ }
3099
+ function setCloseTimer(websocket) {
3100
+ websocket._closeTimer = setTimeout(
3101
+ websocket._socket.destroy.bind(websocket._socket),
3102
+ websocket._closeTimeout
3103
+ );
3104
+ }
3105
+ function socketOnClose() {
3106
+ const websocket = this[kWebSocket];
3107
+ this.removeListener("close", socketOnClose);
3108
+ this.removeListener("data", socketOnData);
3109
+ this.removeListener("end", socketOnEnd);
3110
+ websocket._readyState = WebSocket2.CLOSING;
3111
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
3112
+ const chunk = this.read(this._readableState.length);
3113
+ websocket._receiver.write(chunk);
3114
+ }
3115
+ websocket._receiver.end();
3116
+ this[kWebSocket] = void 0;
3117
+ clearTimeout(websocket._closeTimer);
3118
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3119
+ websocket.emitClose();
3120
+ } else {
3121
+ websocket._receiver.on("error", receiverOnFinish);
3122
+ websocket._receiver.on("finish", receiverOnFinish);
3123
+ }
3124
+ }
3125
+ function socketOnData(chunk) {
3126
+ if (!this[kWebSocket]._receiver.write(chunk)) {
3127
+ this.pause();
3128
+ }
3129
+ }
3130
+ function socketOnEnd() {
3131
+ const websocket = this[kWebSocket];
3132
+ websocket._readyState = WebSocket2.CLOSING;
3133
+ websocket._receiver.end();
3134
+ this.end();
3135
+ }
3136
+ function socketOnError() {
3137
+ const websocket = this[kWebSocket];
3138
+ this.removeListener("error", socketOnError);
3139
+ this.on("error", NOOP);
3140
+ if (websocket) {
3141
+ websocket._readyState = WebSocket2.CLOSING;
3142
+ this.destroy();
3143
+ }
3144
+ }
3145
+ }
3146
+ });
3147
+
3148
+ // ../../node_modules/ws/lib/stream.js
3149
+ var require_stream = __commonJS({
3150
+ "../../node_modules/ws/lib/stream.js"(exports2, module2) {
3151
+ "use strict";
3152
+ var WebSocket2 = require_websocket();
3153
+ var { Duplex } = require("stream");
3154
+ function emitClose(stream) {
3155
+ stream.emit("close");
3156
+ }
3157
+ function duplexOnEnd() {
3158
+ if (!this.destroyed && this._writableState.finished) {
3159
+ this.destroy();
3160
+ }
3161
+ }
3162
+ function duplexOnError(err) {
3163
+ this.removeListener("error", duplexOnError);
3164
+ this.destroy();
3165
+ if (this.listenerCount("error") === 0) {
3166
+ this.emit("error", err);
3167
+ }
3168
+ }
3169
+ function createWebSocketStream2(ws, options) {
3170
+ let terminateOnDestroy = true;
3171
+ const duplex = new Duplex({
3172
+ ...options,
3173
+ autoDestroy: false,
3174
+ emitClose: false,
3175
+ objectMode: false,
3176
+ writableObjectMode: false
3177
+ });
3178
+ ws.on("message", function message(msg, isBinary) {
3179
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3180
+ if (!duplex.push(data)) ws.pause();
3181
+ });
3182
+ ws.once("error", function error(err) {
3183
+ if (duplex.destroyed) return;
3184
+ terminateOnDestroy = false;
3185
+ duplex.destroy(err);
3186
+ });
3187
+ ws.once("close", function close() {
3188
+ if (duplex.destroyed) return;
3189
+ duplex.push(null);
3190
+ });
3191
+ duplex._destroy = function(err, callback) {
3192
+ if (ws.readyState === ws.CLOSED) {
3193
+ callback(err);
3194
+ process.nextTick(emitClose, duplex);
3195
+ return;
3196
+ }
3197
+ let called = false;
3198
+ ws.once("error", function error(err2) {
3199
+ called = true;
3200
+ callback(err2);
3201
+ });
3202
+ ws.once("close", function close() {
3203
+ if (!called) callback(err);
3204
+ process.nextTick(emitClose, duplex);
3205
+ });
3206
+ if (terminateOnDestroy) ws.terminate();
3207
+ };
3208
+ duplex._final = function(callback) {
3209
+ if (ws.readyState === ws.CONNECTING) {
3210
+ ws.once("open", function open() {
3211
+ duplex._final(callback);
3212
+ });
3213
+ return;
3214
+ }
3215
+ if (ws._socket === null) return;
3216
+ if (ws._socket._writableState.finished) {
3217
+ callback();
3218
+ if (duplex._readableState.endEmitted) duplex.destroy();
3219
+ } else {
3220
+ ws._socket.once("finish", function finish() {
3221
+ callback();
3222
+ });
3223
+ ws.close();
3224
+ }
3225
+ };
3226
+ duplex._read = function() {
3227
+ if (ws.isPaused) ws.resume();
3228
+ };
3229
+ duplex._write = function(chunk, encoding, callback) {
3230
+ if (ws.readyState === ws.CONNECTING) {
3231
+ ws.once("open", function open() {
3232
+ duplex._write(chunk, encoding, callback);
3233
+ });
3234
+ return;
3235
+ }
3236
+ ws.send(chunk, callback);
3237
+ };
3238
+ duplex.on("end", duplexOnEnd);
3239
+ duplex.on("error", duplexOnError);
3240
+ return duplex;
3241
+ }
3242
+ module2.exports = createWebSocketStream2;
3243
+ }
3244
+ });
3245
+
3246
+ // ../../node_modules/ws/lib/subprotocol.js
3247
+ var require_subprotocol = __commonJS({
3248
+ "../../node_modules/ws/lib/subprotocol.js"(exports2, module2) {
3249
+ "use strict";
3250
+ var { tokenChars } = require_validation();
3251
+ function parse(header) {
3252
+ const protocols = /* @__PURE__ */ new Set();
3253
+ let start = -1;
3254
+ let end = -1;
3255
+ let i = 0;
3256
+ for (i; i < header.length; i++) {
3257
+ const code = header.charCodeAt(i);
3258
+ if (end === -1 && tokenChars[code] === 1) {
3259
+ if (start === -1) start = i;
3260
+ } else if (i !== 0 && (code === 32 || code === 9)) {
3261
+ if (end === -1 && start !== -1) end = i;
3262
+ } else if (code === 44) {
3263
+ if (start === -1) {
3264
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3265
+ }
3266
+ if (end === -1) end = i;
3267
+ const protocol2 = header.slice(start, end);
3268
+ if (protocols.has(protocol2)) {
3269
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3270
+ }
3271
+ protocols.add(protocol2);
3272
+ start = end = -1;
3273
+ } else {
3274
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3275
+ }
3276
+ }
3277
+ if (start === -1 || end !== -1) {
3278
+ throw new SyntaxError("Unexpected end of input");
3279
+ }
3280
+ const protocol = header.slice(start, i);
3281
+ if (protocols.has(protocol)) {
3282
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3283
+ }
3284
+ protocols.add(protocol);
3285
+ return protocols;
3286
+ }
3287
+ module2.exports = { parse };
3288
+ }
3289
+ });
3290
+
3291
+ // ../../node_modules/ws/lib/websocket-server.js
3292
+ var require_websocket_server = __commonJS({
3293
+ "../../node_modules/ws/lib/websocket-server.js"(exports2, module2) {
3294
+ "use strict";
3295
+ var EventEmitter = require("events");
3296
+ var http = require("http");
3297
+ var { Duplex } = require("stream");
3298
+ var { createHash } = require("crypto");
3299
+ var extension2 = require_extension();
3300
+ var PerMessageDeflate2 = require_permessage_deflate();
3301
+ var subprotocol2 = require_subprotocol();
3302
+ var WebSocket2 = require_websocket();
3303
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3304
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3305
+ var RUNNING = 0;
3306
+ var CLOSING = 1;
3307
+ var CLOSED = 2;
3308
+ var WebSocketServer2 = class extends EventEmitter {
3309
+ /**
3310
+ * Create a `WebSocketServer` instance.
3311
+ *
3312
+ * @param {Object} options Configuration options
3313
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3314
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3315
+ * multiple times in the same tick
3316
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3317
+ * automatically send a pong in response to a ping
3318
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
3319
+ * pending connections
3320
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3321
+ * track clients
3322
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3323
+ * wait for the closing handshake to finish after `websocket.close()` is
3324
+ * called
3325
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
3326
+ * @param {String} [options.host] The hostname where to bind the server
3327
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
3328
+ * buffered data chunks
3329
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
3330
+ * fragments
3331
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3332
+ * size
3333
+ * @param {Boolean} [options.noServer=false] Enable no server mode
3334
+ * @param {String} [options.path] Accept only connections matching this path
3335
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3336
+ * permessage-deflate
3337
+ * @param {Number} [options.port] The port where to bind the server
3338
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3339
+ * server to use
3340
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3341
+ * not to skip UTF-8 validation for text and close messages
3342
+ * @param {Function} [options.verifyClient] A hook to reject connections
3343
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3344
+ * class to use. It must be the `WebSocket` class or class that extends it
3345
+ * @param {Function} [callback] A listener for the `listening` event
3346
+ */
3347
+ constructor(options, callback) {
3348
+ super();
3349
+ options = {
3350
+ allowSynchronousEvents: true,
3351
+ autoPong: true,
3352
+ maxBufferedChunks: 256 * 1024,
3353
+ maxFragments: 16 * 1024,
3354
+ maxPayload: 100 * 1024 * 1024,
3355
+ skipUTF8Validation: false,
3356
+ perMessageDeflate: false,
3357
+ handleProtocols: null,
3358
+ clientTracking: true,
3359
+ closeTimeout: CLOSE_TIMEOUT,
3360
+ verifyClient: null,
3361
+ noServer: false,
3362
+ backlog: null,
3363
+ // use default (511 as implemented in net.js)
3364
+ server: null,
3365
+ host: null,
3366
+ path: null,
3367
+ port: null,
3368
+ WebSocket: WebSocket2,
3369
+ ...options
3370
+ };
3371
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
3372
+ throw new TypeError(
3373
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
3374
+ );
3375
+ }
3376
+ if (options.port != null) {
3377
+ this._server = http.createServer((req, res) => {
3378
+ const body = http.STATUS_CODES[426];
3379
+ res.writeHead(426, {
3380
+ "Content-Length": body.length,
3381
+ "Content-Type": "text/plain"
3382
+ });
3383
+ res.end(body);
3384
+ });
3385
+ this._server.listen(
3386
+ options.port,
3387
+ options.host,
3388
+ options.backlog,
3389
+ callback
3390
+ );
3391
+ } else if (options.server) {
3392
+ this._server = options.server;
3393
+ }
3394
+ if (this._server) {
3395
+ const emitConnection = this.emit.bind(this, "connection");
3396
+ this._removeListeners = addListeners(this._server, {
3397
+ listening: this.emit.bind(this, "listening"),
3398
+ error: this.emit.bind(this, "error"),
3399
+ upgrade: (req, socket, head) => {
3400
+ this.handleUpgrade(req, socket, head, emitConnection);
3401
+ }
3402
+ });
3403
+ }
3404
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3405
+ if (options.clientTracking) {
3406
+ this.clients = /* @__PURE__ */ new Set();
3407
+ this._shouldEmitClose = false;
3408
+ }
3409
+ this.options = options;
3410
+ this._state = RUNNING;
3411
+ }
3412
+ /**
3413
+ * Returns the bound address, the address family name, and port of the server
3414
+ * as reported by the operating system if listening on an IP socket.
3415
+ * If the server is listening on a pipe or UNIX domain socket, the name is
3416
+ * returned as a string.
3417
+ *
3418
+ * @return {(Object|String|null)} The address of the server
3419
+ * @public
3420
+ */
3421
+ address() {
3422
+ if (this.options.noServer) {
3423
+ throw new Error('The server is operating in "noServer" mode');
3424
+ }
3425
+ if (!this._server) return null;
3426
+ return this._server.address();
3427
+ }
3428
+ /**
3429
+ * Stop the server from accepting new connections and emit the `'close'` event
3430
+ * when all existing connections are closed.
3431
+ *
3432
+ * @param {Function} [cb] A one-time listener for the `'close'` event
3433
+ * @public
3434
+ */
3435
+ close(cb) {
3436
+ if (this._state === CLOSED) {
3437
+ if (cb) {
3438
+ this.once("close", () => {
3439
+ cb(new Error("The server is not running"));
3440
+ });
3441
+ }
3442
+ process.nextTick(emitClose, this);
3443
+ return;
3444
+ }
3445
+ if (cb) this.once("close", cb);
3446
+ if (this._state === CLOSING) return;
3447
+ this._state = CLOSING;
3448
+ if (this.options.noServer || this.options.server) {
3449
+ if (this._server) {
3450
+ this._removeListeners();
3451
+ this._removeListeners = this._server = null;
3452
+ }
3453
+ if (this.clients) {
3454
+ if (!this.clients.size) {
3455
+ process.nextTick(emitClose, this);
3456
+ } else {
3457
+ this._shouldEmitClose = true;
3458
+ }
3459
+ } else {
3460
+ process.nextTick(emitClose, this);
3461
+ }
3462
+ } else {
3463
+ const server = this._server;
3464
+ this._removeListeners();
3465
+ this._removeListeners = this._server = null;
3466
+ server.close(() => {
3467
+ emitClose(this);
3468
+ });
3469
+ }
3470
+ }
3471
+ /**
3472
+ * See if a given request should be handled by this server instance.
3473
+ *
3474
+ * @param {http.IncomingMessage} req Request object to inspect
3475
+ * @return {Boolean} `true` if the request is valid, else `false`
3476
+ * @public
3477
+ */
3478
+ shouldHandle(req) {
3479
+ if (this.options.path) {
3480
+ const index = req.url.indexOf("?");
3481
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3482
+ if (pathname !== this.options.path) return false;
3483
+ }
3484
+ return true;
3485
+ }
3486
+ /**
3487
+ * Handle a HTTP Upgrade request.
3488
+ *
3489
+ * @param {http.IncomingMessage} req The request object
3490
+ * @param {Duplex} socket The network socket between the server and client
3491
+ * @param {Buffer} head The first packet of the upgraded stream
3492
+ * @param {Function} cb Callback
3493
+ * @public
3494
+ */
3495
+ handleUpgrade(req, socket, head, cb) {
3496
+ socket.on("error", socketOnError);
3497
+ const key = req.headers["sec-websocket-key"];
3498
+ const upgrade = req.headers.upgrade;
3499
+ const version = +req.headers["sec-websocket-version"];
3500
+ if (req.method !== "GET") {
3501
+ const message = "Invalid HTTP method";
3502
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3503
+ return;
3504
+ }
3505
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3506
+ const message = "Invalid Upgrade header";
3507
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3508
+ return;
3509
+ }
3510
+ if (key === void 0 || !keyRegex.test(key)) {
3511
+ const message = "Missing or invalid Sec-WebSocket-Key header";
3512
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3513
+ return;
3514
+ }
3515
+ if (version !== 13 && version !== 8) {
3516
+ const message = "Missing or invalid Sec-WebSocket-Version header";
3517
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
3518
+ "Sec-WebSocket-Version": "13, 8"
3519
+ });
3520
+ return;
3521
+ }
3522
+ if (!this.shouldHandle(req)) {
3523
+ abortHandshake(socket, 400);
3524
+ return;
3525
+ }
3526
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3527
+ let protocols = /* @__PURE__ */ new Set();
3528
+ if (secWebSocketProtocol !== void 0) {
3529
+ try {
3530
+ protocols = subprotocol2.parse(secWebSocketProtocol);
3531
+ } catch (err) {
3532
+ const message = "Invalid Sec-WebSocket-Protocol header";
3533
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3534
+ return;
3535
+ }
3536
+ }
3537
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3538
+ const extensions = {};
3539
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3540
+ const perMessageDeflate = new PerMessageDeflate2({
3541
+ ...this.options.perMessageDeflate,
3542
+ isServer: true,
3543
+ maxPayload: this.options.maxPayload
3544
+ });
3545
+ try {
3546
+ const offers = extension2.parse(secWebSocketExtensions);
3547
+ if (offers[PerMessageDeflate2.extensionName]) {
3548
+ perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
3549
+ extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
3550
+ }
3551
+ } catch (err) {
3552
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3553
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3554
+ return;
3555
+ }
3556
+ }
3557
+ if (this.options.verifyClient) {
3558
+ const info = {
3559
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3560
+ secure: !!(req.socket.authorized || req.socket.encrypted),
3561
+ req
3562
+ };
3563
+ if (this.options.verifyClient.length === 2) {
3564
+ this.options.verifyClient(info, (verified, code, message, headers) => {
3565
+ if (!verified) {
3566
+ return abortHandshake(socket, code || 401, message, headers);
3567
+ }
3568
+ this.completeUpgrade(
3569
+ extensions,
3570
+ key,
3571
+ protocols,
3572
+ req,
3573
+ socket,
3574
+ head,
3575
+ cb
3576
+ );
3577
+ });
3578
+ return;
3579
+ }
3580
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3581
+ }
3582
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3583
+ }
3584
+ /**
3585
+ * Upgrade the connection to WebSocket.
3586
+ *
3587
+ * @param {Object} extensions The accepted extensions
3588
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
3589
+ * @param {Set} protocols The subprotocols
3590
+ * @param {http.IncomingMessage} req The request object
3591
+ * @param {Duplex} socket The network socket between the server and client
3592
+ * @param {Buffer} head The first packet of the upgraded stream
3593
+ * @param {Function} cb Callback
3594
+ * @throws {Error} If called more than once with the same socket
3595
+ * @private
3596
+ */
3597
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3598
+ if (!socket.readable || !socket.writable) return socket.destroy();
3599
+ if (socket[kWebSocket]) {
3600
+ throw new Error(
3601
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
3602
+ );
3603
+ }
3604
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
3605
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
3606
+ const headers = [
3607
+ "HTTP/1.1 101 Switching Protocols",
3608
+ "Upgrade: websocket",
3609
+ "Connection: Upgrade",
3610
+ `Sec-WebSocket-Accept: ${digest}`
3611
+ ];
3612
+ const ws = new this.options.WebSocket(null, void 0, this.options);
3613
+ if (protocols.size) {
3614
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3615
+ if (protocol) {
3616
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3617
+ ws._protocol = protocol;
3618
+ }
3619
+ }
3620
+ if (extensions[PerMessageDeflate2.extensionName]) {
3621
+ const params = extensions[PerMessageDeflate2.extensionName].params;
3622
+ const value = extension2.format({
3623
+ [PerMessageDeflate2.extensionName]: [params]
3624
+ });
3625
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
3626
+ ws._extensions = extensions;
3627
+ }
3628
+ this.emit("headers", headers, req);
3629
+ socket.write(headers.concat("\r\n").join("\r\n"));
3630
+ socket.removeListener("error", socketOnError);
3631
+ ws.setSocket(socket, head, {
3632
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
3633
+ maxBufferedChunks: this.options.maxBufferedChunks,
3634
+ maxFragments: this.options.maxFragments,
3635
+ maxPayload: this.options.maxPayload,
3636
+ skipUTF8Validation: this.options.skipUTF8Validation
3637
+ });
3638
+ if (this.clients) {
3639
+ this.clients.add(ws);
3640
+ ws.on("close", () => {
3641
+ this.clients.delete(ws);
3642
+ if (this._shouldEmitClose && !this.clients.size) {
3643
+ process.nextTick(emitClose, this);
3644
+ }
3645
+ });
3646
+ }
3647
+ cb(ws, req);
3648
+ }
3649
+ };
3650
+ module2.exports = WebSocketServer2;
3651
+ function addListeners(server, map) {
3652
+ for (const event of Object.keys(map)) server.on(event, map[event]);
3653
+ return function removeListeners() {
3654
+ for (const event of Object.keys(map)) {
3655
+ server.removeListener(event, map[event]);
3656
+ }
3657
+ };
3658
+ }
3659
+ function emitClose(server) {
3660
+ server._state = CLOSED;
3661
+ server.emit("close");
3662
+ }
3663
+ function socketOnError() {
3664
+ this.destroy();
3665
+ }
3666
+ function abortHandshake(socket, code, message, headers) {
3667
+ message = message || http.STATUS_CODES[code];
3668
+ headers = {
3669
+ Connection: "close",
3670
+ "Content-Type": "text/html",
3671
+ "Content-Length": Buffer.byteLength(message),
3672
+ ...headers
3673
+ };
3674
+ socket.once("finish", socket.destroy);
3675
+ socket.end(
3676
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
3677
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
3678
+ );
3679
+ }
3680
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
3681
+ if (server.listenerCount("wsClientError")) {
3682
+ const err = new Error(message);
3683
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3684
+ server.emit("wsClientError", err, socket, req);
3685
+ } else {
3686
+ abortHandshake(socket, code, message, headers);
3687
+ }
3688
+ }
3689
+ }
3690
+ });
3691
+
3692
+ // ../../node_modules/ws/index.js
3693
+ var createWebSocketStream = require_stream();
3694
+ var extension = require_extension();
3695
+ var PerMessageDeflate = require_permessage_deflate();
3696
+ var Receiver = require_receiver();
3697
+ var Sender = require_sender();
3698
+ var subprotocol = require_subprotocol();
3699
+ var WebSocket = require_websocket();
3700
+ var WebSocketServer = require_websocket_server();
3701
+ WebSocket.createWebSocketStream = createWebSocketStream;
3702
+ WebSocket.extension = extension;
3703
+ WebSocket.PerMessageDeflate = PerMessageDeflate;
3704
+ WebSocket.Receiver = Receiver;
3705
+ WebSocket.Sender = Sender;
3706
+ WebSocket.Server = WebSocketServer;
3707
+ WebSocket.subprotocol = subprotocol;
3708
+ WebSocket.WebSocket = WebSocket;
3709
+ WebSocket.WebSocketServer = WebSocketServer;
3710
+ module.exports = WebSocket;