benchgo-plugin 0.0.0-stage → 0.0.2

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