@lynx-js/devtool-connector 0.19.1 → 0.19.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.
package/dist/t.js CHANGED
@@ -1,1351 +1,2548 @@
1
1
  import { __webpack_require__ } from "./rslib-runtime.js";
2
- import { randomUUID } from "node:crypto";
3
- import node_http from "node:http";
4
- import node_fs from "node:fs";
5
- import node_path from "node:path";
6
- import { fileURLToPath } from "node:url";
7
- import node_zlib from "node:zlib";
8
- import { Readable } from "node:stream";
9
- import { pipeline } from "node:stream/promises";
10
- import "./0.js";
11
- import { ansi_createDebug, isCustomizedMessage, isRegisterEvent, DAEMON_VERSION_PATH, isListClientsRequest, DAEMON_SHUTDOWN_PATH, DAEMON_INSPECTOR_PATH, DAEMON_PRODUCT, isPingEvent, DAEMON_WS_PATH, DAEMON_COMMAND_PATH_PREFIX, isControlRequest, CONNECTOR_VERSION } from "./2.js";
12
- import { isInitializeResponse } from "./hb.js";
13
- import { decodeCommandQuery, ActionCore } from "./f.js";
14
- import { Connector, throwClientDiscoveryFailures } from "./a.js";
15
- import { DaemonTransport, HDTTransport, ClientId, withTransports } from "./f1.js";
16
- const debug = ansi_createDebug("devtool-mcp-server:daemon:device-connection");
17
- class DeviceConnection {
18
- key;
19
- deviceId;
20
- port;
21
- #conn = null;
22
- #writer = null;
23
- #subscribers = new Map();
24
- #transport;
25
- #options;
26
- #disposed = false;
27
- #disposePromise = null;
28
- #terminalCause;
29
- #connectPromise = null;
30
- #readLoopPromise = null;
31
- #registered;
32
- #resolveRegistered;
33
- #rejectRegistered;
34
- #registrationSettled = false;
35
- appInfo = null;
36
- constructor(transport, options){
37
- this.#transport = transport;
38
- this.#options = options;
39
- this.deviceId = options.deviceId;
40
- this.port = options.port;
41
- this.key = `${transport.id}:${options.deviceId}:${options.port}`;
42
- this.#registered = new Promise((resolve, reject)=>{
43
- this.#resolveRegistered = resolve;
44
- this.#rejectRegistered = reject;
45
- });
46
- this.#registered.catch(()=>{});
47
- }
48
- async connect() {
49
- debug("connecting to %s", this.key);
50
- if (this.#disposed) throw new Error(`DeviceConnection ${this.key} was disposed before connect started`);
51
- try {
52
- this.#connectPromise = this.#transport.connect(this.#options);
53
- this.#conn = await this.#connectPromise;
54
- } catch (error) {
55
- this.#rejectRegistration(error);
56
- throw error;
57
- }
58
- if (this.#disposed) {
59
- const error = new Error(`DeviceConnection ${this.key} was disposed before connect completed`);
60
- this.#rejectRegistration(error);
61
- throw error;
2
+ import "./f1.js";
3
+ import { createRequire as __rspack_createRequire } from "node:module";
4
+ const __rspack_createRequire_require = __rspack_createRequire(import.meta.url);
5
+ __webpack_require__.add({
6
+ "../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/buffer-util.js" (module, __unused_rspack_exports, __webpack_require__) {
7
+ const { websocketMask, websocketUnmask } = __rspack_createRequire_require("http");
8
+ const { EMPTY_BUFFER } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/constants.js");
9
+ const FastBuffer = Buffer[Symbol.species];
10
+ function concat(list, totalLength) {
11
+ if (0 === list.length) return EMPTY_BUFFER;
12
+ if (1 === list.length) return list[0];
13
+ const target = Buffer.allocUnsafe(totalLength);
14
+ let offset = 0;
15
+ for(let i = 0; i < list.length; i++){
16
+ const buf = list[i];
17
+ target.set(buf, offset);
18
+ offset += buf.length;
19
+ }
20
+ if (offset < totalLength) return new FastBuffer(target.buffer, target.byteOffset, offset);
21
+ return target;
62
22
  }
63
- this.#writer = this.#conn.writable.getWriter();
64
- this.#readLoopPromise = this.#readLoop();
65
- debug("connected to %s", this.key);
66
- }
67
- waitUntilRegistered() {
68
- return this.#registered;
69
- }
70
- addSubscriber(subscriber) {
71
- if (this.#disposed) throw new Error(`Device connection ${this.key} is no longer active`);
72
- this.#subscribers.set(subscriber.id, subscriber);
73
- debug("subscriber %d added to %s (total: %d)", subscriber.id, this.key, this.#subscribers.size);
74
- }
75
- removeSubscriber(id) {
76
- this.#subscribers.delete(id);
77
- debug("subscriber %d removed from %s (total: %d)", id, this.key, this.#subscribers.size);
78
- }
79
- get subscriberCount() {
80
- return this.#subscribers.size;
81
- }
82
- get isDisposed() {
83
- return this.#disposed;
84
- }
85
- get transport() {
86
- return this.#transport;
87
- }
88
- get isPersistent() {
89
- return true === this.#transport.persistent;
90
- }
91
- async send(message) {
92
- if (this.#disposed) throw this.#terminalCause ?? new Error(`DeviceConnection ${this.key} is no longer active`);
93
- if (!this.#writer) throw new Error(`DeviceConnection ${this.key} is not connected`);
94
- try {
95
- await this.#writer.write(message);
96
- } catch (err) {
97
- debug("send to %s failed: %O", this.key, err);
98
- this.#terminate(err, false);
99
- throw this.#terminalCause ?? err;
23
+ function _mask(source, mask, output, offset, length) {
24
+ for(let i = 0; i < length; i++)output[offset + i] = source[i] ^ mask[3 & i];
100
25
  }
101
- }
102
- dispose() {
103
- this.#disposed = true;
104
- this.#rejectRegistration(new Error(`DeviceConnection ${this.key} was disposed before Register`));
105
- return this.#startDisposal(true);
106
- }
107
- async #disposeConnection(awaitReadLoop) {
108
- debug("disposing device connection %s", this.key);
109
- let disposeFailed = false;
110
- let disposeCause;
111
- try {
112
- if (!this.#conn && this.#connectPromise) this.#conn = await this.#connectPromise;
113
- } catch {}
114
- try {
115
- this.#writer?.releaseLock();
116
- } catch {}
117
- this.#writer = null;
118
- try {
119
- await this.#conn?.[Symbol.asyncDispose]();
120
- } catch (err) {
121
- debug("error disposing connection %s: %O", this.key, err);
122
- disposeFailed = true;
123
- disposeCause = err;
26
+ function _unmask(buffer, mask) {
27
+ for(let i = 0; i < buffer.length; i++)buffer[i] ^= mask[3 & i];
124
28
  }
125
- if (awaitReadLoop && !disposeFailed) await this.#readLoopPromise;
126
- this.#subscribers.clear();
127
- if (disposeFailed) throw disposeCause;
128
- }
129
- #startDisposal(awaitReadLoop) {
130
- if (!this.#disposePromise) {
131
- this.#disposePromise = this.#disposeConnection(awaitReadLoop);
132
- this.#disposePromise.catch((err)=>{
133
- debug("device connection %s disposal failed: %O", this.key, err);
134
- });
29
+ function toArrayBuffer(buf) {
30
+ if (buf.length === buf.buffer.byteLength) return buf.buffer;
31
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
135
32
  }
136
- return this.#disposePromise;
137
- }
138
- async #readLoop() {
139
- if (!this.#conn) return;
140
- let terminalCause;
141
- let readFailed = false;
142
- try {
143
- for await (const message of this.#conn.readable){
144
- if (null === this.appInfo) {
145
- const response = message;
146
- if (isInitializeResponse(response)) {
147
- this.#resolveRegistration(response.data.info);
148
- debug("captured appInfo for %s: %O", this.key, this.appInfo);
149
- continue;
150
- }
151
- }
152
- if (!isClientListMessage(message)) this.#broadcast(message);
33
+ function toBuffer(data) {
34
+ toBuffer.readOnly = true;
35
+ if (Buffer.isBuffer(data)) return data;
36
+ let buf;
37
+ if (data instanceof ArrayBuffer) buf = new FastBuffer(data);
38
+ else if (ArrayBuffer.isView(data)) buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
39
+ else {
40
+ buf = Buffer.from(data);
41
+ toBuffer.readOnly = false;
153
42
  }
154
- } catch (err) {
155
- readFailed = true;
156
- terminalCause = err;
157
- if (!this.#disposed) debug("read loop error on %s: %O", this.key, err);
43
+ return buf;
158
44
  }
159
- if (!this.#disposed) {
160
- debug("device connection %s closed by remote", this.key);
161
- this.#terminate(terminalCause ?? new Error(null === this.appInfo ? `Device connection ${this.key} closed before Register` : `Device connection ${this.key} closed by remote`), true, !readFailed);
45
+ module.exports = {
46
+ concat,
47
+ mask: _mask,
48
+ toArrayBuffer,
49
+ toBuffer,
50
+ unmask: _unmask
51
+ };
52
+ if (websocketMask) {
53
+ module.exports.mask = function(source, mask, output, offset, length) {
54
+ if (length < 24) _mask(source, mask, output, offset, length);
55
+ else websocketMask(source, mask, output, offset, length);
56
+ };
57
+ module.exports.unmask = function(buffer, mask) {
58
+ if (buffer.length < 24) _unmask(buffer, mask);
59
+ else websocketUnmask(buffer, mask);
60
+ };
61
+ } else if (!process.env.WS_NO_BUFFER_UTIL) try {
62
+ const bufferUtil = __webpack_require__("bufferutil");
63
+ module.exports.mask = function(source, mask, output, offset, length) {
64
+ if (length < 48) _mask(source, mask, output, offset, length);
65
+ else bufferUtil.mask(source, mask, output, offset, length);
66
+ };
67
+ module.exports.unmask = function(buffer, mask) {
68
+ if (buffer.length < 32) _unmask(buffer, mask);
69
+ else bufferUtil.unmask(buffer, mask);
70
+ };
71
+ } catch (e) {}
72
+ },
73
+ "../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/constants.js" (module) {
74
+ const BINARY_TYPES = [
75
+ 'nodebuffer',
76
+ 'arraybuffer',
77
+ 'fragments'
78
+ ];
79
+ const hasBlob = "u" > typeof Blob;
80
+ if (hasBlob) BINARY_TYPES.push('blob');
81
+ module.exports = {
82
+ BINARY_TYPES,
83
+ CLOSE_TIMEOUT: 30000,
84
+ EMPTY_BUFFER: Buffer.alloc(0),
85
+ GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
86
+ hasBlob,
87
+ kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),
88
+ kListener: Symbol('kListener'),
89
+ kStatusCode: Symbol('status-code'),
90
+ kWebSocket: Symbol('websocket'),
91
+ NOOP: ()=>{}
92
+ };
93
+ },
94
+ "../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/event-target.js" (module, __unused_rspack_exports, __webpack_require__) {
95
+ const { kForOnEventAttribute, kListener } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/constants.js");
96
+ const kCode = Symbol('kCode');
97
+ const kData = Symbol('kData');
98
+ const kError = Symbol('kError');
99
+ const kMessage = Symbol('kMessage');
100
+ const kReason = Symbol('kReason');
101
+ const kTarget = Symbol('kTarget');
102
+ const kType = Symbol('kType');
103
+ const kWasClean = Symbol('kWasClean');
104
+ class Event {
105
+ constructor(type){
106
+ this[kTarget] = null;
107
+ this[kType] = type;
108
+ }
109
+ get target() {
110
+ return this[kTarget];
111
+ }
112
+ get type() {
113
+ return this[kType];
114
+ }
162
115
  }
163
- }
164
- #terminate(cause, readLoopEnded, cleanEof = false) {
165
- if (this.#disposed) return;
166
- this.#disposed = true;
167
- this.#terminalCause = cause;
168
- this.#rejectRegistration(cause);
169
- this.#startDisposal(!readLoopEnded);
170
- this.#closeAllSubscribers(cleanEof ? void 0 : cause);
171
- }
172
- #resolveRegistration(appInfo) {
173
- if (this.#registrationSettled) return;
174
- this.#registrationSettled = true;
175
- this.appInfo = appInfo;
176
- this.#resolveRegistered(appInfo);
177
- }
178
- #rejectRegistration(reason) {
179
- if (this.#registrationSettled) return;
180
- this.#registrationSettled = true;
181
- this.#rejectRegistered(reason);
182
- }
183
- #closeAllSubscribers(cause) {
184
- for (const [, subscriber] of this.#subscribers)try {
185
- subscriber.close(cause);
186
- } catch (err) {
187
- debug("failed to close subscriber %d: %O", subscriber.id, err);
116
+ Object.defineProperty(Event.prototype, 'target', {
117
+ enumerable: true
118
+ });
119
+ Object.defineProperty(Event.prototype, 'type', {
120
+ enumerable: true
121
+ });
122
+ class CloseEvent extends Event {
123
+ constructor(type, options = {}){
124
+ super(type);
125
+ this[kCode] = void 0 === options.code ? 0 : options.code;
126
+ this[kReason] = void 0 === options.reason ? '' : options.reason;
127
+ this[kWasClean] = void 0 === options.wasClean ? false : options.wasClean;
128
+ }
129
+ get code() {
130
+ return this[kCode];
131
+ }
132
+ get reason() {
133
+ return this[kReason];
134
+ }
135
+ get wasClean() {
136
+ return this[kWasClean];
137
+ }
188
138
  }
189
- this.#subscribers.clear();
190
- }
191
- #broadcast(message) {
192
- for (const [, subscriber] of this.#subscribers)try {
193
- subscriber.send(message);
194
- } catch (err) {
195
- debug("failed to send to subscriber %d: %O", subscriber.id, err);
139
+ Object.defineProperty(CloseEvent.prototype, 'code', {
140
+ enumerable: true
141
+ });
142
+ Object.defineProperty(CloseEvent.prototype, 'reason', {
143
+ enumerable: true
144
+ });
145
+ Object.defineProperty(CloseEvent.prototype, 'wasClean', {
146
+ enumerable: true
147
+ });
148
+ class ErrorEvent extends Event {
149
+ constructor(type, options = {}){
150
+ super(type);
151
+ this[kError] = void 0 === options.error ? null : options.error;
152
+ this[kMessage] = void 0 === options.message ? '' : options.message;
153
+ }
154
+ get error() {
155
+ return this[kError];
156
+ }
157
+ get message() {
158
+ return this[kMessage];
159
+ }
196
160
  }
197
- }
198
- }
199
- function isClientListMessage(message) {
200
- return "object" == typeof message && null !== message && "ClientList" === message.event;
201
- }
202
- const tarball_cache_debug = ansi_createDebug("devtool-mcp-server:daemon:tarball-cache");
203
- const TAR_FILTER_PREFIX = "package/static-resources/devtool/lynx/";
204
- class TarballCache {
205
- #files = new Map();
206
- #pending = new Map();
207
- #done = false;
208
- #error = null;
209
- #loading = null;
210
- get(filePath) {
211
- return this.#files.get(filePath);
212
- }
213
- get isDone() {
214
- return this.#done;
215
- }
216
- waitFor(filePath) {
217
- const existing = this.#files.get(filePath);
218
- if (existing) return Promise.resolve(existing);
219
- if (this.#error) return Promise.reject(this.#error);
220
- if (this.#done) return Promise.resolve(null);
221
- return new Promise((resolve, reject)=>{
222
- let waiters = this.#pending.get(filePath);
223
- if (!waiters) {
224
- waiters = [];
225
- this.#pending.set(filePath, waiters);
226
- }
227
- waiters.push({
228
- resolve,
229
- reject
230
- });
161
+ Object.defineProperty(ErrorEvent.prototype, 'error', {
162
+ enumerable: true
231
163
  });
232
- }
233
- start(url) {
234
- if (this.#loading) return;
235
- this.#loading = this.#load(url);
236
- }
237
- async #load(url) {
238
- try {
239
- const response = await fetch(url);
240
- if (!response.ok) throw new Error(`Failed to fetch tarball: ${response.status}`);
241
- if (!response.body) throw new Error("No response body");
242
- await pipeline(Readable.fromWeb(response.body), node_zlib.createGunzip(), async (chunks)=>{
243
- let buf = Buffer.alloc(0);
244
- for await (const chunk of chunks){
245
- buf = Buffer.concat([
246
- buf,
247
- chunk
248
- ]);
249
- buf = this.#consumeTar(buf);
250
- }
251
- this.#consumeTar(buf);
252
- });
253
- } catch (err) {
254
- this.#error = err instanceof Error ? err : new Error(String(err));
255
- tarball_cache_debug("tarball stream error: %O", this.#error);
256
- } finally{
257
- this.#done = true;
258
- for (const [, waiters] of this.#pending)for (const { resolve, reject } of waiters)if (this.#error) reject(this.#error);
259
- else resolve(null);
260
- this.#pending.clear();
261
- tarball_cache_debug("tarball cache done: %d files", this.#files.size);
164
+ Object.defineProperty(ErrorEvent.prototype, 'message', {
165
+ enumerable: true
166
+ });
167
+ class MessageEvent extends Event {
168
+ constructor(type, options = {}){
169
+ super(type);
170
+ this[kData] = void 0 === options.data ? null : options.data;
171
+ }
172
+ get data() {
173
+ return this[kData];
174
+ }
262
175
  }
263
- }
264
- #consumeTar(buf) {
265
- while(buf.length >= 512){
266
- const header = buf.subarray(0, 512);
267
- if (header.every((b)=>0 === b)) {
268
- buf = buf.subarray(512);
269
- continue;
270
- }
271
- const rawName = header.subarray(0, 100).toString("utf-8").replace(/\0.*$/, "");
272
- const prefix = header.subarray(345, 500).toString("utf-8").replace(/\0.*$/, "");
273
- const name = prefix ? `${prefix}/${rawName}` : rawName;
274
- const sizeStr = header.subarray(124, 136).toString("utf-8").replace(/\0.*$/, "").trim();
275
- const size = parseInt(sizeStr, 8) || 0;
276
- const typeFlag = header[156];
277
- const paddedSize = 512 * Math.ceil(size / 512);
278
- if (buf.length < 512 + paddedSize) break;
279
- if ((48 === typeFlag || 0 === typeFlag) && name.startsWith(TAR_FILTER_PREFIX)) {
280
- const fileData = buf.subarray(512, 512 + size);
281
- const ext = node_path.extname(name).toLowerCase();
282
- if (".map" !== ext) {
283
- const gzipped = node_zlib.gzipSync(fileData, {
284
- level: node_zlib.constants.Z_BEST_SPEED
176
+ Object.defineProperty(MessageEvent.prototype, 'data', {
177
+ enumerable: true
178
+ });
179
+ const EventTarget = {
180
+ addEventListener (type, handler, options = {}) {
181
+ for (const listener of this.listeners(type))if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) return;
182
+ let wrapper;
183
+ if ('message' === type) wrapper = function(data, isBinary) {
184
+ const event = new MessageEvent('message', {
185
+ data: isBinary ? data : data.toString()
186
+ });
187
+ event[kTarget] = this;
188
+ callListener(handler, this, event);
189
+ };
190
+ else if ('close' === type) wrapper = function(code, message) {
191
+ const event = new CloseEvent('close', {
192
+ code,
193
+ reason: message.toString(),
194
+ wasClean: this._closeFrameReceived && this._closeFrameSent
285
195
  });
286
- const entry = {
287
- gzipped,
288
- rawSize: size
196
+ event[kTarget] = this;
197
+ callListener(handler, this, event);
198
+ };
199
+ else if ('error' === type) wrapper = function(error) {
200
+ const event = new ErrorEvent('error', {
201
+ error,
202
+ message: error.message
203
+ });
204
+ event[kTarget] = this;
205
+ callListener(handler, this, event);
206
+ };
207
+ else {
208
+ if ('open' !== type) return;
209
+ wrapper = function() {
210
+ const event = new Event('open');
211
+ event[kTarget] = this;
212
+ callListener(handler, this, event);
289
213
  };
290
- this.#files.set(name, entry);
291
- const waiters = this.#pending.get(name);
292
- if (waiters) {
293
- this.#pending.delete(name);
294
- for (const { resolve } of waiters)resolve(entry);
295
- }
214
+ }
215
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
216
+ wrapper[kListener] = handler;
217
+ if (options.once) this.once(type, wrapper);
218
+ else this.on(type, wrapper);
219
+ },
220
+ removeEventListener (type, handler) {
221
+ for (const listener of this.listeners(type))if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
222
+ this.removeListener(type, listener);
223
+ break;
296
224
  }
297
225
  }
298
- buf = buf.subarray(512 + paddedSize);
226
+ };
227
+ module.exports = {
228
+ CloseEvent,
229
+ ErrorEvent,
230
+ Event,
231
+ EventTarget,
232
+ MessageEvent
233
+ };
234
+ function callListener(listener, thisArg, event) {
235
+ if ('object' == typeof listener && listener.handleEvent) listener.handleEvent.call(listener, event);
236
+ else listener.call(thisArg, event);
299
237
  }
300
- return buf;
301
- }
302
- }
303
- const inspector_assets_debug = ansi_createDebug("devtool-mcp-server:daemon:inspector-assets");
304
- const HDT_RES_TARBALL_URL = "https://github.com/lynx-family/lynx-devtool/releases/download/devtools-frontend-lynx-7/devtool.frontend.lynx_1.0.1779085629.tar.gz";
305
- const HDT_RES_PATH_PREFIX = "/devtool-frontend/";
306
- const MIME_TYPES = {
307
- ".html": "text/html; charset=utf-8",
308
- ".js": "application/javascript; charset=utf-8",
309
- ".css": "text/css; charset=utf-8",
310
- ".json": "application/json; charset=utf-8",
311
- ".png": "image/png",
312
- ".jpg": "image/jpeg",
313
- ".svg": "image/svg+xml",
314
- ".woff2": "font/woff2",
315
- ".woff": "font/woff",
316
- ".ttf": "font/ttf"
317
- };
318
- class InspectorAssets {
319
- #hdtResCache = null;
320
- async createInspectorResponse() {
321
- const base = node_path.dirname(fileURLToPath(import.meta.url));
322
- const primary = node_path.resolve(base, "../../public");
323
- const secondary = node_path.resolve(base, "../public");
324
- const filePath = [
325
- primary,
326
- secondary
327
- ].map((directory)=>node_path.join(directory, "inspector-wrapper.html")).find((candidate)=>node_fs.existsSync(candidate)) ?? node_path.join(primary, "inspector-wrapper.html");
328
- try {
329
- const content = await node_fs.promises.readFile(filePath, "utf-8");
330
- return new Response(content, {
331
- status: 200,
332
- headers: {
333
- "Content-Type": "text/html; charset=utf-8",
334
- "Content-Length": String(Buffer.byteLength(content)),
335
- "Cache-Control": "no-store",
336
- "Content-Security-Policy": "frame-ancestors 'self'"
238
+ },
239
+ "../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/extension.js" (module, __unused_rspack_exports, __webpack_require__) {
240
+ const { tokenChars } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/validation.js");
241
+ function push(dest, name, elem) {
242
+ if (void 0 === dest[name]) dest[name] = [
243
+ elem
244
+ ];
245
+ else dest[name].push(elem);
246
+ }
247
+ function parse(header) {
248
+ const offers = Object.create(null);
249
+ let params = Object.create(null);
250
+ let mustUnescape = false;
251
+ let isEscaping = false;
252
+ let inQuotes = false;
253
+ let extensionName;
254
+ let paramName;
255
+ let start = -1;
256
+ let code = -1;
257
+ let end = -1;
258
+ let i = 0;
259
+ for(; i < header.length; i++){
260
+ code = header.charCodeAt(i);
261
+ if (void 0 === extensionName) if (-1 === end && 1 === tokenChars[code]) {
262
+ if (-1 === start) start = i;
263
+ } else if (0 !== i && (0x20 === code || 0x09 === code)) {
264
+ if (-1 === end && -1 !== start) end = i;
265
+ } else if (0x3b === code || 0x2c === code) {
266
+ if (-1 === start) throw new SyntaxError(`Unexpected character at index ${i}`);
267
+ if (-1 === end) end = i;
268
+ const name = header.slice(start, end);
269
+ if (0x2c === code) {
270
+ push(offers, name, params);
271
+ params = Object.create(null);
272
+ } else extensionName = name;
273
+ start = end = -1;
274
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
275
+ else if (void 0 === paramName) if (-1 === end && 1 === tokenChars[code]) {
276
+ if (-1 === start) start = i;
277
+ } else if (0x20 === code || 0x09 === code) {
278
+ if (-1 === end && -1 !== start) end = i;
279
+ } else if (0x3b === code || 0x2c === code) {
280
+ if (-1 === start) throw new SyntaxError(`Unexpected character at index ${i}`);
281
+ if (-1 === end) end = i;
282
+ push(params, header.slice(start, end), true);
283
+ if (0x2c === code) {
284
+ push(offers, extensionName, params);
285
+ params = Object.create(null);
286
+ extensionName = void 0;
287
+ }
288
+ start = end = -1;
289
+ } else if (0x3d === code && -1 !== start && -1 === end) {
290
+ paramName = header.slice(start, i);
291
+ start = end = -1;
292
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
293
+ else if (isEscaping) {
294
+ if (1 !== tokenChars[code]) throw new SyntaxError(`Unexpected character at index ${i}`);
295
+ if (-1 === start) start = i;
296
+ else if (!mustUnescape) mustUnescape = true;
297
+ isEscaping = false;
298
+ } else if (inQuotes) if (1 === tokenChars[code]) {
299
+ if (-1 === start) start = i;
300
+ } else if (0x22 === code && -1 !== start) {
301
+ inQuotes = false;
302
+ end = i;
303
+ } else if (0x5c === code) isEscaping = true;
304
+ else throw new SyntaxError(`Unexpected character at index ${i}`);
305
+ else if (0x22 === code && 0x3d === header.charCodeAt(i - 1)) inQuotes = true;
306
+ else if (-1 === end && 1 === tokenChars[code]) {
307
+ if (-1 === start) start = i;
308
+ } else if (-1 !== start && (0x20 === code || 0x09 === code)) {
309
+ if (-1 === end) end = i;
310
+ } else if (0x3b === code || 0x2c === code) {
311
+ if (-1 === start) throw new SyntaxError(`Unexpected character at index ${i}`);
312
+ if (-1 === end) end = i;
313
+ let value = header.slice(start, end);
314
+ if (mustUnescape) {
315
+ value = value.replace(/\\/g, '');
316
+ mustUnescape = false;
317
+ }
318
+ push(params, paramName, value);
319
+ if (0x2c === code) {
320
+ push(offers, extensionName, params);
321
+ params = Object.create(null);
322
+ extensionName = void 0;
323
+ }
324
+ paramName = void 0;
325
+ start = end = -1;
326
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
327
+ }
328
+ if (-1 === start || inQuotes || 0x20 === code || 0x09 === code) throw new SyntaxError('Unexpected end of input');
329
+ if (-1 === end) end = i;
330
+ const token = header.slice(start, end);
331
+ if (void 0 === extensionName) push(offers, token, params);
332
+ else {
333
+ if (void 0 === paramName) push(params, token, true);
334
+ else mustUnescape ? push(params, paramName, token.replace(/\\/g, '')) : push(params, paramName, token);
335
+ push(offers, extensionName, params);
336
+ }
337
+ return offers;
338
+ }
339
+ function format(extensions) {
340
+ return Object.keys(extensions).map((extension)=>{
341
+ let configurations = extensions[extension];
342
+ if (!Array.isArray(configurations)) configurations = [
343
+ configurations
344
+ ];
345
+ return configurations.map((params)=>[
346
+ extension
347
+ ].concat(Object.keys(params).map((k)=>{
348
+ let values = params[k];
349
+ if (!Array.isArray(values)) values = [
350
+ values
351
+ ];
352
+ return values.map((v)=>true === v ? k : `${k}=${v}`).join('; ');
353
+ })).join('; ')).join(', ');
354
+ }).join(', ');
355
+ }
356
+ module.exports = {
357
+ format,
358
+ parse
359
+ };
360
+ },
361
+ "../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/limiter.js" (module) {
362
+ const kDone = Symbol('kDone');
363
+ const kRun = Symbol('kRun');
364
+ class Limiter {
365
+ constructor(concurrency){
366
+ this[kDone] = ()=>{
367
+ this.pending--;
368
+ this[kRun]();
369
+ };
370
+ this.concurrency = concurrency || 1 / 0;
371
+ this.jobs = [];
372
+ this.pending = 0;
373
+ }
374
+ add(job) {
375
+ this.jobs.push(job);
376
+ this[kRun]();
377
+ }
378
+ [kRun]() {
379
+ if (this.pending === this.concurrency) return;
380
+ if (this.jobs.length) {
381
+ const job = this.jobs.shift();
382
+ this.pending++;
383
+ job(this[kDone]);
337
384
  }
338
- });
339
- } catch (error) {
340
- inspector_assets_debug("failed to serve Inspector wrapper: %O", error);
341
- return new Response("Not found", {
342
- status: 404
343
- });
385
+ }
344
386
  }
345
- }
346
- async createHdtResourceResponse(pathname, acceptEncoding) {
347
- try {
348
- const relativePath = pathname.slice(HDT_RES_PATH_PREFIX.length);
349
- if (!pathname.startsWith(HDT_RES_PATH_PREFIX) || relativePath.includes("..")) return new Response("Not found", {
350
- status: 404
351
- });
352
- const ext = node_path.extname(relativePath).toLowerCase();
353
- if (".map" === ext) return new Response("Not found", {
354
- status: 404
355
- });
356
- if (!this.#hdtResCache) {
357
- this.#hdtResCache = new TarballCache();
358
- this.#hdtResCache.start(HDT_RES_TARBALL_URL);
359
- }
360
- const tarPath = relativePath;
361
- const entry = this.#hdtResCache.get(tarPath) ?? await this.#hdtResCache.waitFor(tarPath);
362
- if (!entry) return new Response("Not found", {
363
- status: 404
364
- });
365
- const acceptsGzip = acceptEncoding?.includes("gzip") ?? false;
366
- const body = acceptsGzip ? entry.gzipped : node_zlib.gunzipSync(entry.gzipped);
367
- return new Response(Uint8Array.from(body), {
368
- status: 200,
369
- headers: {
370
- "Content-Type": MIME_TYPES[ext] ?? "application/octet-stream",
371
- ...acceptsGzip ? {
372
- "Content-Encoding": "gzip"
373
- } : {},
374
- "Content-Length": String(body.length),
375
- "Cache-Control": "public, max-age=31536000, immutable"
387
+ module.exports = Limiter;
388
+ },
389
+ "../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/permessage-deflate.js" (module, __unused_rspack_exports, __webpack_require__) {
390
+ const zlib = __rspack_createRequire_require("zlib");
391
+ const bufferUtil = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/buffer-util.js");
392
+ const Limiter = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/limiter.js");
393
+ const { kStatusCode } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/constants.js");
394
+ const FastBuffer = Buffer[Symbol.species];
395
+ const TRAILER = Buffer.from([
396
+ 0x00,
397
+ 0x00,
398
+ 0xff,
399
+ 0xff
400
+ ]);
401
+ const kPerMessageDeflate = Symbol('permessage-deflate');
402
+ const kTotalLength = Symbol('total-length');
403
+ const kCallback = Symbol('callback');
404
+ const kBuffers = Symbol('buffers');
405
+ const kError = Symbol('error');
406
+ let zlibLimiter;
407
+ class PerMessageDeflate {
408
+ constructor(options){
409
+ this._options = options || {};
410
+ this._threshold = void 0 !== this._options.threshold ? this._options.threshold : 1024;
411
+ this._maxPayload = 0 | this._options.maxPayload;
412
+ this._isServer = !!this._options.isServer;
413
+ this._deflate = null;
414
+ this._inflate = null;
415
+ this.params = null;
416
+ if (!zlibLimiter) {
417
+ const concurrency = void 0 !== this._options.concurrencyLimit ? this._options.concurrencyLimit : 10;
418
+ zlibLimiter = new Limiter(concurrency);
376
419
  }
377
- });
378
- } catch (error) {
379
- inspector_assets_debug("failed to serve hdt-res file: %O", error);
380
- return new Response("Failed to load resource", {
381
- status: 502
382
- });
420
+ }
421
+ static get extensionName() {
422
+ return 'permessage-deflate';
423
+ }
424
+ offer() {
425
+ const params = {};
426
+ if (this._options.serverNoContextTakeover) params.server_no_context_takeover = true;
427
+ if (this._options.clientNoContextTakeover) params.client_no_context_takeover = true;
428
+ if (this._options.serverMaxWindowBits) params.server_max_window_bits = this._options.serverMaxWindowBits;
429
+ if (this._options.clientMaxWindowBits) params.client_max_window_bits = this._options.clientMaxWindowBits;
430
+ else if (null == this._options.clientMaxWindowBits) params.client_max_window_bits = true;
431
+ return params;
432
+ }
433
+ accept(configurations) {
434
+ configurations = this.normalizeParams(configurations);
435
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
436
+ return this.params;
437
+ }
438
+ cleanup() {
439
+ if (this._inflate) {
440
+ this._inflate.close();
441
+ this._inflate = null;
442
+ }
443
+ if (this._deflate) {
444
+ const callback = this._deflate[kCallback];
445
+ this._deflate.close();
446
+ this._deflate = null;
447
+ if (callback) callback(new Error('The deflate stream was closed while data was being processed'));
448
+ }
449
+ }
450
+ acceptAsServer(offers) {
451
+ const opts = this._options;
452
+ const accepted = offers.find((params)=>{
453
+ if (false === opts.serverNoContextTakeover && params.server_no_context_takeover || params.server_max_window_bits && (false === opts.serverMaxWindowBits || 'number' == typeof opts.serverMaxWindowBits && opts.serverMaxWindowBits > params.server_max_window_bits) || 'number' == typeof opts.clientMaxWindowBits && ('number' == typeof params.client_max_window_bits ? opts.clientMaxWindowBits > params.client_max_window_bits : !params.client_max_window_bits)) return false;
454
+ return true;
455
+ });
456
+ if (!accepted) throw new Error('None of the extension offers can be accepted');
457
+ if (opts.serverNoContextTakeover) accepted.server_no_context_takeover = true;
458
+ if (opts.clientNoContextTakeover) accepted.client_no_context_takeover = true;
459
+ if ('number' == typeof opts.serverMaxWindowBits) accepted.server_max_window_bits = opts.serverMaxWindowBits;
460
+ if ('number' == typeof opts.clientMaxWindowBits) accepted.client_max_window_bits = opts.clientMaxWindowBits;
461
+ else if (true === accepted.client_max_window_bits || false === opts.clientMaxWindowBits) delete accepted.client_max_window_bits;
462
+ return accepted;
463
+ }
464
+ acceptAsClient(response) {
465
+ const params = response[0];
466
+ if (false === this._options.clientNoContextTakeover && params.client_no_context_takeover) throw new Error('Unexpected parameter "client_no_context_takeover"');
467
+ if (params.client_max_window_bits) {
468
+ if (false === this._options.clientMaxWindowBits || 'number' == typeof this._options.clientMaxWindowBits && params.client_max_window_bits > this._options.clientMaxWindowBits) throw new Error('Unexpected or invalid parameter "client_max_window_bits"');
469
+ } else if ('number' == typeof this._options.clientMaxWindowBits) params.client_max_window_bits = this._options.clientMaxWindowBits;
470
+ return params;
471
+ }
472
+ normalizeParams(configurations) {
473
+ configurations.forEach((params)=>{
474
+ Object.keys(params).forEach((key)=>{
475
+ let value = params[key];
476
+ if (value.length > 1) throw new Error(`Parameter "${key}" must have only a single value`);
477
+ value = value[0];
478
+ if ('client_max_window_bits' === key) {
479
+ if (true !== value) {
480
+ const num = +value;
481
+ if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
482
+ value = num;
483
+ } else if (!this._isServer) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
484
+ } else if ('server_max_window_bits' === key) {
485
+ const num = +value;
486
+ if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
487
+ value = num;
488
+ } else if ('client_no_context_takeover' === key || 'server_no_context_takeover' === key) {
489
+ if (true !== value) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
490
+ } else throw new Error(`Unknown parameter "${key}"`);
491
+ params[key] = value;
492
+ });
493
+ });
494
+ return configurations;
495
+ }
496
+ decompress(data, fin, callback) {
497
+ zlibLimiter.add((done)=>{
498
+ this._decompress(data, fin, (err, result)=>{
499
+ done();
500
+ callback(err, result);
501
+ });
502
+ });
503
+ }
504
+ compress(data, fin, callback) {
505
+ zlibLimiter.add((done)=>{
506
+ this._compress(data, fin, (err, result)=>{
507
+ done();
508
+ callback(err, result);
509
+ });
510
+ });
511
+ }
512
+ _decompress(data, fin, callback) {
513
+ const endpoint = this._isServer ? 'client' : 'server';
514
+ if (!this._inflate) {
515
+ const key = `${endpoint}_max_window_bits`;
516
+ const windowBits = 'number' != typeof this.params[key] ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
517
+ this._inflate = zlib.createInflateRaw({
518
+ ...this._options.zlibInflateOptions,
519
+ windowBits
520
+ });
521
+ this._inflate[kPerMessageDeflate] = this;
522
+ this._inflate[kTotalLength] = 0;
523
+ this._inflate[kBuffers] = [];
524
+ this._inflate.on('error', inflateOnError);
525
+ this._inflate.on('data', inflateOnData);
526
+ }
527
+ this._inflate[kCallback] = callback;
528
+ this._inflate.write(data);
529
+ if (fin) this._inflate.write(TRAILER);
530
+ this._inflate.flush(()=>{
531
+ const err = this._inflate[kError];
532
+ if (err) {
533
+ this._inflate.close();
534
+ this._inflate = null;
535
+ callback(err);
536
+ return;
537
+ }
538
+ const data = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
539
+ if (this._inflate._readableState.endEmitted) {
540
+ this._inflate.close();
541
+ this._inflate = null;
542
+ } else {
543
+ this._inflate[kTotalLength] = 0;
544
+ this._inflate[kBuffers] = [];
545
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) this._inflate.reset();
546
+ }
547
+ callback(null, data);
548
+ });
549
+ }
550
+ _compress(data, fin, callback) {
551
+ const endpoint = this._isServer ? 'server' : 'client';
552
+ if (!this._deflate) {
553
+ const key = `${endpoint}_max_window_bits`;
554
+ const windowBits = 'number' != typeof this.params[key] ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
555
+ this._deflate = zlib.createDeflateRaw({
556
+ ...this._options.zlibDeflateOptions,
557
+ windowBits
558
+ });
559
+ this._deflate[kTotalLength] = 0;
560
+ this._deflate[kBuffers] = [];
561
+ this._deflate.on('data', deflateOnData);
562
+ }
563
+ this._deflate[kCallback] = callback;
564
+ this._deflate.write(data);
565
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, ()=>{
566
+ if (!this._deflate) return;
567
+ let data = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
568
+ if (fin) data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);
569
+ this._deflate[kCallback] = null;
570
+ this._deflate[kTotalLength] = 0;
571
+ this._deflate[kBuffers] = [];
572
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) this._deflate.reset();
573
+ callback(null, data);
574
+ });
575
+ }
383
576
  }
384
- }
385
- }
386
- const static_server_debug = ansi_createDebug("devtool-mcp-server:daemon:static-server");
387
- class StaticServer {
388
- #assets;
389
- #resourcePrefix;
390
- constructor(assets = new InspectorAssets(), resourcePrefix = HDT_RES_PATH_PREFIX){
391
- this.#assets = assets;
392
- this.#resourcePrefix = resourcePrefix;
393
- }
394
- tryHandle(req, res) {
395
- if ("GET" !== req.method) return false;
396
- const pathname = new URL(req.url ?? "/", "http://127.0.0.1").pathname;
397
- if (pathname === DAEMON_INSPECTOR_PATH) {
398
- this.#serveResponse(res, this.#assets.createInspectorResponse());
399
- return true;
577
+ module.exports = PerMessageDeflate;
578
+ function deflateOnData(chunk) {
579
+ this[kBuffers].push(chunk);
580
+ this[kTotalLength] += chunk.length;
400
581
  }
401
- if (pathname.startsWith(this.#resourcePrefix)) {
402
- this.#serveResponse(res, this.#assets.createHdtResourceResponse(pathname, req.headers["accept-encoding"]));
403
- return true;
582
+ function inflateOnData(chunk) {
583
+ this[kTotalLength] += chunk.length;
584
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) return void this[kBuffers].push(chunk);
585
+ this[kError] = new RangeError('Max payload size exceeded');
586
+ this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';
587
+ this[kError][kStatusCode] = 1009;
588
+ this.removeListener('data', inflateOnData);
589
+ this.reset();
404
590
  }
405
- return false;
406
- }
407
- async #serveResponse(res, responsePromise) {
408
- try {
409
- const response = await responsePromise;
410
- const body = Buffer.from(await response.arrayBuffer());
411
- if (res.destroyed || res.headersSent || res.writableEnded) return;
412
- res.writeHead(response.status, Object.fromEntries(response.headers));
413
- res.end(body);
414
- } catch (error) {
415
- static_server_debug("failed to write static response: %O", error);
416
- if (res.destroyed || res.headersSent || res.writableEnded) return;
417
- res.writeHead(500);
418
- res.end("Failed to write response");
591
+ function inflateOnError(err) {
592
+ this[kPerMessageDeflate]._inflate = null;
593
+ if (this[kError]) return void this[kCallback](this[kError]);
594
+ err[kStatusCode] = 1007;
595
+ this[kCallback](err);
419
596
  }
420
- }
421
- }
422
- const websocket_server = __webpack_require__("../../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/websocket-server.js");
423
- const server_debug = ansi_createDebug("devtool-mcp-server:daemon:server");
424
- const IDLE_TIMEOUT_MS = 300000;
425
- const DEVICE_CONN_GRACE_MS = 30000;
426
- const DEVICE_DISCOVERY_TIMEOUT_MS = 2500;
427
- const DEVICE_CONN_SETUP_TIMEOUT_MS = 5000;
428
- class DevtoolDaemon {
429
- #httpServer;
430
- #wss = null;
431
- #transports;
432
- #hdtTransports;
433
- #deviceConnections = new Map();
434
- #pendingDeviceConnections = new Map();
435
- #deviceConnectionCleanupTimers = new Map();
436
- #wsClients = new Map();
437
- #commandControllers = new Set();
438
- #nextClientId = 0;
439
- #activeCommandRequests = 0;
440
- #idleTimer = null;
441
- #idleTimeoutMs;
442
- #closed = false;
443
- #closePromise = null;
444
- #shutdownAccepted = false;
445
- #onIdle;
446
- #onShutdown;
447
- staticServer = new StaticServer();
448
- actionCore = new ActionCore();
449
- identity = {
450
- product: DAEMON_PRODUCT,
451
- version: CONNECTOR_VERSION,
452
- lifecycleProtocol: 1,
453
- commandProtocol: 1
454
- };
455
- #commandConnector = null;
456
- #instanceId = randomUUID();
457
- #startedAt = Date.now();
458
- constructor(transports, options){
459
- this.#transports = transports;
460
- this.#hdtTransports = transports.filter((t)=>t instanceof HDTTransport);
461
- this.#onIdle = options?.onIdle;
462
- this.#onShutdown = options?.onShutdown;
463
- this.#idleTimeoutMs = options?.idleTimeoutMs ?? IDLE_TIMEOUT_MS;
464
- this.#httpServer = node_http.createServer((req, res)=>{
465
- const isCommandRequest = this.#isCommandRequest(req.url);
466
- const isShutdownRequest = this.#isShutdownRequest(req.url);
467
- if ((isCommandRequest || isShutdownRequest) && !this.#isTrustedLocalRequest(req)) return void this.#sendJson(res, 403, {
468
- ok: false,
469
- error: "Daemon control requests require a same-origin loopback Host and Origin."
470
- });
471
- if (isCommandRequest && "POST" === req.method && !this.#hasJsonContentType(req)) return void this.#sendJson(res, 415, {
472
- ok: false,
473
- error: "POST /command requests require Content-Type: application/json."
474
- });
475
- if ("GET" === req.method && this.#isVersionRequest(req.url)) {
476
- this.#setVersionCorsHeaders(res);
477
- this.#sendJson(res, 200, {
478
- ...this.identity,
479
- instanceId: this.#instanceId,
480
- startedAt: this.#startedAt
597
+ },
598
+ "../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/receiver.js" (module, __unused_rspack_exports, __webpack_require__) {
599
+ const { Writable } = __rspack_createRequire_require("stream");
600
+ const PerMessageDeflate = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/permessage-deflate.js");
601
+ const { BINARY_TYPES, EMPTY_BUFFER, kStatusCode, kWebSocket } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/constants.js");
602
+ const { concat, toArrayBuffer, unmask } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/buffer-util.js");
603
+ const { isValidStatusCode, isValidUTF8 } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/validation.js");
604
+ const FastBuffer = Buffer[Symbol.species];
605
+ const GET_INFO = 0;
606
+ const GET_PAYLOAD_LENGTH_16 = 1;
607
+ const GET_PAYLOAD_LENGTH_64 = 2;
608
+ const GET_MASK = 3;
609
+ const GET_DATA = 4;
610
+ const INFLATING = 5;
611
+ const DEFER_EVENT = 6;
612
+ class Receiver extends Writable {
613
+ constructor(options = {}){
614
+ super();
615
+ this._allowSynchronousEvents = void 0 !== options.allowSynchronousEvents ? options.allowSynchronousEvents : true;
616
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
617
+ this._extensions = options.extensions || {};
618
+ this._isServer = !!options.isServer;
619
+ this._maxBufferedChunks = 0 | options.maxBufferedChunks;
620
+ this._maxFragments = 0 | options.maxFragments;
621
+ this._maxPayload = 0 | options.maxPayload;
622
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
623
+ this[kWebSocket] = void 0;
624
+ this._bufferedBytes = 0;
625
+ this._buffers = [];
626
+ this._compressed = false;
627
+ this._payloadLength = 0;
628
+ this._mask = void 0;
629
+ this._fragmented = 0;
630
+ this._masked = false;
631
+ this._fin = false;
632
+ this._opcode = 0;
633
+ this._totalPayloadLength = 0;
634
+ this._messageLength = 0;
635
+ this._numFragments = 0;
636
+ this._fragments = [];
637
+ this._errored = false;
638
+ this._loop = false;
639
+ this._state = GET_INFO;
640
+ }
641
+ _write(chunk, encoding, cb) {
642
+ if (0x08 === this._opcode && this._state == GET_INFO) return cb();
643
+ if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) return void cb(this.createError(RangeError, 'Too many buffered chunks', false, 1008, 'WS_ERR_TOO_MANY_BUFFERED_PARTS'));
644
+ this._bufferedBytes += chunk.length;
645
+ this._buffers.push(chunk);
646
+ this.startLoop(cb);
647
+ }
648
+ consume(n) {
649
+ this._bufferedBytes -= n;
650
+ if (n === this._buffers[0].length) return this._buffers.shift();
651
+ if (n < this._buffers[0].length) {
652
+ const buf = this._buffers[0];
653
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
654
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
655
+ }
656
+ const dst = Buffer.allocUnsafe(n);
657
+ do {
658
+ const buf = this._buffers[0];
659
+ const offset = dst.length - n;
660
+ if (n >= buf.length) dst.set(this._buffers.shift(), offset);
661
+ else {
662
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
663
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
664
+ }
665
+ n -= buf.length;
666
+ }while (n > 0);
667
+ return dst;
668
+ }
669
+ startLoop(cb) {
670
+ this._loop = true;
671
+ do switch(this._state){
672
+ case GET_INFO:
673
+ this.getInfo(cb);
674
+ break;
675
+ case GET_PAYLOAD_LENGTH_16:
676
+ this.getPayloadLength16(cb);
677
+ break;
678
+ case GET_PAYLOAD_LENGTH_64:
679
+ this.getPayloadLength64(cb);
680
+ break;
681
+ case GET_MASK:
682
+ this.getMask();
683
+ break;
684
+ case GET_DATA:
685
+ this.getData(cb);
686
+ break;
687
+ case INFLATING:
688
+ case DEFER_EVENT:
689
+ this._loop = false;
690
+ return;
691
+ }
692
+ while (this._loop);
693
+ if (!this._errored) cb();
694
+ }
695
+ getInfo(cb) {
696
+ if (this._bufferedBytes < 2) {
697
+ this._loop = false;
698
+ return;
699
+ }
700
+ const buf = this.consume(2);
701
+ if ((0x30 & buf[0]) !== 0x00) {
702
+ const error = this.createError(RangeError, 'RSV2 and RSV3 must be clear', true, 1002, 'WS_ERR_UNEXPECTED_RSV_2_3');
703
+ cb(error);
704
+ return;
705
+ }
706
+ const compressed = (0x40 & buf[0]) === 0x40;
707
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
708
+ const error = this.createError(RangeError, 'RSV1 must be clear', true, 1002, 'WS_ERR_UNEXPECTED_RSV_1');
709
+ cb(error);
710
+ return;
711
+ }
712
+ this._fin = (0x80 & buf[0]) === 0x80;
713
+ this._opcode = 0x0f & buf[0];
714
+ this._payloadLength = 0x7f & buf[1];
715
+ if (0x00 === this._opcode) {
716
+ if (compressed) {
717
+ const error = this.createError(RangeError, 'RSV1 must be clear', true, 1002, 'WS_ERR_UNEXPECTED_RSV_1');
718
+ cb(error);
719
+ return;
720
+ }
721
+ if (!this._fragmented) {
722
+ const error = this.createError(RangeError, 'invalid opcode 0', true, 1002, 'WS_ERR_INVALID_OPCODE');
723
+ cb(error);
724
+ return;
725
+ }
726
+ this._opcode = this._fragmented;
727
+ } else if (0x01 === this._opcode || 0x02 === this._opcode) {
728
+ if (this._fragmented) {
729
+ const error = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, 'WS_ERR_INVALID_OPCODE');
730
+ cb(error);
731
+ return;
732
+ }
733
+ this._compressed = compressed;
734
+ } else if (this._opcode > 0x07 && this._opcode < 0x0b) {
735
+ if (!this._fin) {
736
+ const error = this.createError(RangeError, 'FIN must be set', true, 1002, 'WS_ERR_EXPECTED_FIN');
737
+ cb(error);
738
+ return;
739
+ }
740
+ if (compressed) {
741
+ const error = this.createError(RangeError, 'RSV1 must be clear', true, 1002, 'WS_ERR_UNEXPECTED_RSV_1');
742
+ cb(error);
743
+ return;
744
+ }
745
+ if (this._payloadLength > 0x7d || 0x08 === this._opcode && 1 === this._payloadLength) {
746
+ const error = this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH');
747
+ cb(error);
748
+ return;
749
+ }
750
+ } else {
751
+ const error = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, 'WS_ERR_INVALID_OPCODE');
752
+ cb(error);
753
+ return;
754
+ }
755
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
756
+ this._masked = (0x80 & buf[1]) === 0x80;
757
+ if (this._isServer) {
758
+ if (!this._masked) {
759
+ const error = this.createError(RangeError, 'MASK must be set', true, 1002, 'WS_ERR_EXPECTED_MASK');
760
+ cb(error);
761
+ return;
762
+ }
763
+ } else if (this._masked) {
764
+ const error = this.createError(RangeError, 'MASK must be clear', true, 1002, 'WS_ERR_UNEXPECTED_MASK');
765
+ cb(error);
766
+ return;
767
+ }
768
+ if (126 === this._payloadLength) this._state = GET_PAYLOAD_LENGTH_16;
769
+ else if (127 === this._payloadLength) this._state = GET_PAYLOAD_LENGTH_64;
770
+ else this.haveLength(cb);
771
+ }
772
+ getPayloadLength16(cb) {
773
+ if (this._bufferedBytes < 2) {
774
+ this._loop = false;
775
+ return;
776
+ }
777
+ this._payloadLength = this.consume(2).readUInt16BE(0);
778
+ this.haveLength(cb);
779
+ }
780
+ getPayloadLength64(cb) {
781
+ if (this._bufferedBytes < 8) {
782
+ this._loop = false;
783
+ return;
784
+ }
785
+ const buf = this.consume(8);
786
+ const num = buf.readUInt32BE(0);
787
+ if (num > Math.pow(2, 21) - 1) {
788
+ const error = this.createError(RangeError, 'Unsupported WebSocket frame: payload length > 2^53 - 1', false, 1009, 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH');
789
+ cb(error);
790
+ return;
791
+ }
792
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
793
+ this.haveLength(cb);
794
+ }
795
+ haveLength(cb) {
796
+ if (this._payloadLength && this._opcode < 0x08) {
797
+ this._totalPayloadLength += this._payloadLength;
798
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
799
+ const error = this.createError(RangeError, 'Max payload size exceeded', false, 1009, 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH');
800
+ cb(error);
801
+ return;
802
+ }
803
+ }
804
+ if (this._masked) this._state = GET_MASK;
805
+ else this._state = GET_DATA;
806
+ }
807
+ getMask() {
808
+ if (this._bufferedBytes < 4) {
809
+ this._loop = false;
810
+ return;
811
+ }
812
+ this._mask = this.consume(4);
813
+ this._state = GET_DATA;
814
+ }
815
+ getData(cb) {
816
+ let data = EMPTY_BUFFER;
817
+ if (this._payloadLength) {
818
+ if (this._bufferedBytes < this._payloadLength) {
819
+ this._loop = false;
820
+ return;
821
+ }
822
+ data = this.consume(this._payloadLength);
823
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) unmask(data, this._mask);
824
+ }
825
+ this._mask = void 0;
826
+ if (this._opcode > 0x07) return void this.controlMessage(data, cb);
827
+ if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {
828
+ const error = this.createError(RangeError, 'Too many message fragments', false, 1008, 'WS_ERR_TOO_MANY_BUFFERED_PARTS');
829
+ cb(error);
830
+ return;
831
+ }
832
+ if (this._compressed) {
833
+ this._state = INFLATING;
834
+ this.decompress(data, cb);
835
+ return;
836
+ }
837
+ if (data.length) {
838
+ this._messageLength = this._totalPayloadLength;
839
+ this._fragments.push(data);
840
+ }
841
+ this.dataMessage(cb);
842
+ }
843
+ decompress(data, cb) {
844
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
845
+ perMessageDeflate.decompress(data, this._fin, (err, buf)=>{
846
+ if (err) return cb(err);
847
+ if (buf.length) {
848
+ this._messageLength += buf.length;
849
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
850
+ const error = this.createError(RangeError, 'Max payload size exceeded', false, 1009, 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH');
851
+ cb(error);
852
+ return;
853
+ }
854
+ this._fragments.push(buf);
855
+ }
856
+ this.dataMessage(cb);
857
+ if (this._state === GET_INFO) this.startLoop(cb);
858
+ });
859
+ }
860
+ dataMessage(cb) {
861
+ if (!this._fin) {
862
+ this._state = GET_INFO;
863
+ return;
864
+ }
865
+ const messageLength = this._messageLength;
866
+ const fragments = this._fragments;
867
+ this._totalPayloadLength = 0;
868
+ this._messageLength = 0;
869
+ this._fragmented = 0;
870
+ this._numFragments = 0;
871
+ this._fragments = [];
872
+ if (2 === this._opcode) {
873
+ let data;
874
+ data = 'nodebuffer' === this._binaryType ? concat(fragments, messageLength) : 'arraybuffer' === this._binaryType ? toArrayBuffer(concat(fragments, messageLength)) : 'blob' === this._binaryType ? new Blob(fragments) : fragments;
875
+ if (this._allowSynchronousEvents) {
876
+ this.emit('message', data, true);
877
+ this._state = GET_INFO;
878
+ } else {
879
+ this._state = DEFER_EVENT;
880
+ setImmediate(()=>{
881
+ this.emit('message', data, true);
882
+ this._state = GET_INFO;
883
+ this.startLoop(cb);
884
+ });
885
+ }
886
+ } else {
887
+ const buf = concat(fragments, messageLength);
888
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
889
+ const error = this.createError(Error, 'invalid UTF-8 sequence', true, 1007, 'WS_ERR_INVALID_UTF8');
890
+ cb(error);
891
+ return;
892
+ }
893
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
894
+ this.emit('message', buf, false);
895
+ this._state = GET_INFO;
896
+ } else {
897
+ this._state = DEFER_EVENT;
898
+ setImmediate(()=>{
899
+ this.emit('message', buf, false);
900
+ this._state = GET_INFO;
901
+ this.startLoop(cb);
902
+ });
903
+ }
904
+ }
905
+ }
906
+ controlMessage(data, cb) {
907
+ if (0x08 === this._opcode) {
908
+ if (0 === data.length) {
909
+ this._loop = false;
910
+ this.emit('conclude', 1005, EMPTY_BUFFER);
911
+ this.end();
912
+ } else {
913
+ const code = data.readUInt16BE(0);
914
+ if (!isValidStatusCode(code)) {
915
+ const error = this.createError(RangeError, `invalid status code ${code}`, true, 1002, 'WS_ERR_INVALID_CLOSE_CODE');
916
+ cb(error);
917
+ return;
918
+ }
919
+ const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
920
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
921
+ const error = this.createError(Error, 'invalid UTF-8 sequence', true, 1007, 'WS_ERR_INVALID_UTF8');
922
+ cb(error);
923
+ return;
924
+ }
925
+ this._loop = false;
926
+ this.emit('conclude', code, buf);
927
+ this.end();
928
+ }
929
+ this._state = GET_INFO;
930
+ return;
931
+ }
932
+ if (this._allowSynchronousEvents) {
933
+ this.emit(0x09 === this._opcode ? 'ping' : 'pong', data);
934
+ this._state = GET_INFO;
935
+ } else {
936
+ this._state = DEFER_EVENT;
937
+ setImmediate(()=>{
938
+ this.emit(0x09 === this._opcode ? 'ping' : 'pong', data);
939
+ this._state = GET_INFO;
940
+ this.startLoop(cb);
941
+ });
942
+ }
943
+ }
944
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
945
+ this._loop = false;
946
+ this._errored = true;
947
+ const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
948
+ Error.captureStackTrace(err, this.createError);
949
+ err.code = errorCode;
950
+ err[kStatusCode] = statusCode;
951
+ return err;
952
+ }
953
+ }
954
+ module.exports = Receiver;
955
+ },
956
+ "../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/sender.js" (module, __unused_rspack_exports, __webpack_require__) {
957
+ const { Duplex } = __rspack_createRequire_require("stream");
958
+ const { randomFillSync } = __rspack_createRequire_require("crypto");
959
+ const { types: { isUint8Array } } = __rspack_createRequire_require("util");
960
+ const PerMessageDeflate = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/permessage-deflate.js");
961
+ const { EMPTY_BUFFER, kWebSocket, NOOP } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/constants.js");
962
+ const { isBlob, isValidStatusCode } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/validation.js");
963
+ const { mask: applyMask, toBuffer } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/buffer-util.js");
964
+ const kByteLength = Symbol('kByteLength');
965
+ const maskBuffer = Buffer.alloc(4);
966
+ const RANDOM_POOL_SIZE = 8192;
967
+ let randomPool;
968
+ let randomPoolPointer = RANDOM_POOL_SIZE;
969
+ const DEFAULT = 0;
970
+ const DEFLATING = 1;
971
+ const GET_BLOB_DATA = 2;
972
+ class Sender {
973
+ constructor(socket, extensions, generateMask){
974
+ this._extensions = extensions || {};
975
+ if (generateMask) {
976
+ this._generateMask = generateMask;
977
+ this._maskBuffer = Buffer.alloc(4);
978
+ }
979
+ this._socket = socket;
980
+ this._firstFragment = true;
981
+ this._compress = false;
982
+ this._bufferedBytes = 0;
983
+ this._queue = [];
984
+ this._state = DEFAULT;
985
+ this.onerror = NOOP;
986
+ this[kWebSocket] = void 0;
987
+ }
988
+ static frame(data, options) {
989
+ let mask;
990
+ let merge = false;
991
+ let offset = 2;
992
+ let skipMasking = false;
993
+ if (options.mask) {
994
+ mask = options.maskBuffer || maskBuffer;
995
+ if (options.generateMask) options.generateMask(mask);
996
+ else {
997
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
998
+ if (void 0 === randomPool) randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
999
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1000
+ randomPoolPointer = 0;
1001
+ }
1002
+ mask[0] = randomPool[randomPoolPointer++];
1003
+ mask[1] = randomPool[randomPoolPointer++];
1004
+ mask[2] = randomPool[randomPoolPointer++];
1005
+ mask[3] = randomPool[randomPoolPointer++];
1006
+ }
1007
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1008
+ offset = 6;
1009
+ }
1010
+ let dataLength;
1011
+ if ('string' == typeof data) if ((!options.mask || skipMasking) && void 0 !== options[kByteLength]) dataLength = options[kByteLength];
1012
+ else {
1013
+ data = Buffer.from(data);
1014
+ dataLength = data.length;
1015
+ }
1016
+ else {
1017
+ dataLength = data.length;
1018
+ merge = options.mask && options.readOnly && !skipMasking;
1019
+ }
1020
+ let payloadLength = dataLength;
1021
+ if (dataLength >= 65536) {
1022
+ offset += 8;
1023
+ payloadLength = 127;
1024
+ } else if (dataLength > 125) {
1025
+ offset += 2;
1026
+ payloadLength = 126;
1027
+ }
1028
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1029
+ target[0] = options.fin ? 0x80 | options.opcode : options.opcode;
1030
+ if (options.rsv1) target[0] |= 0x40;
1031
+ target[1] = payloadLength;
1032
+ if (126 === payloadLength) target.writeUInt16BE(dataLength, 2);
1033
+ else if (127 === payloadLength) {
1034
+ target[2] = target[3] = 0;
1035
+ target.writeUIntBE(dataLength, 4, 6);
1036
+ }
1037
+ if (!options.mask) return dataLength ? [
1038
+ target,
1039
+ data
1040
+ ] : [
1041
+ target
1042
+ ];
1043
+ target[1] |= 0x80;
1044
+ target[offset - 4] = mask[0];
1045
+ target[offset - 3] = mask[1];
1046
+ target[offset - 2] = mask[2];
1047
+ target[offset - 1] = mask[3];
1048
+ if (!dataLength) return [
1049
+ target
1050
+ ];
1051
+ if (skipMasking) return [
1052
+ target,
1053
+ data
1054
+ ];
1055
+ if (merge) {
1056
+ applyMask(data, mask, target, offset, dataLength);
1057
+ return [
1058
+ target
1059
+ ];
1060
+ }
1061
+ applyMask(data, mask, data, 0, dataLength);
1062
+ return [
1063
+ target,
1064
+ data
1065
+ ];
1066
+ }
1067
+ close(code, data, mask, cb) {
1068
+ let buf;
1069
+ if (void 0 === code) buf = EMPTY_BUFFER;
1070
+ else if ('number' == typeof code && isValidStatusCode(code)) if (void 0 !== data && data.length) {
1071
+ const length = Buffer.byteLength(data);
1072
+ if (length > 123) throw new RangeError('The message must not be greater than 123 bytes');
1073
+ buf = Buffer.allocUnsafe(2 + length);
1074
+ buf.writeUInt16BE(code, 0);
1075
+ if ('string' == typeof data) buf.write(data, 2);
1076
+ else if (isUint8Array(data)) buf.set(data, 2);
1077
+ else throw new TypeError('Second argument must be a string or a Uint8Array');
1078
+ } else {
1079
+ buf = Buffer.allocUnsafe(2);
1080
+ buf.writeUInt16BE(code, 0);
1081
+ }
1082
+ else throw new TypeError('First argument must be a valid error code number');
1083
+ const options = {
1084
+ [kByteLength]: buf.length,
1085
+ fin: true,
1086
+ generateMask: this._generateMask,
1087
+ mask,
1088
+ maskBuffer: this._maskBuffer,
1089
+ opcode: 0x08,
1090
+ readOnly: false,
1091
+ rsv1: false
1092
+ };
1093
+ if (this._state !== DEFAULT) this.enqueue([
1094
+ this.dispatch,
1095
+ buf,
1096
+ false,
1097
+ options,
1098
+ cb
1099
+ ]);
1100
+ else this.sendFrame(Sender.frame(buf, options), cb);
1101
+ }
1102
+ ping(data, mask, cb) {
1103
+ let byteLength;
1104
+ let readOnly;
1105
+ if ('string' == typeof data) {
1106
+ byteLength = Buffer.byteLength(data);
1107
+ readOnly = false;
1108
+ } else if (isBlob(data)) {
1109
+ byteLength = data.size;
1110
+ readOnly = false;
1111
+ } else {
1112
+ data = toBuffer(data);
1113
+ byteLength = data.length;
1114
+ readOnly = toBuffer.readOnly;
1115
+ }
1116
+ if (byteLength > 125) throw new RangeError('The data size must not be greater than 125 bytes');
1117
+ const options = {
1118
+ [kByteLength]: byteLength,
1119
+ fin: true,
1120
+ generateMask: this._generateMask,
1121
+ mask,
1122
+ maskBuffer: this._maskBuffer,
1123
+ opcode: 0x09,
1124
+ readOnly,
1125
+ rsv1: false
1126
+ };
1127
+ if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
1128
+ this.getBlobData,
1129
+ data,
1130
+ false,
1131
+ options,
1132
+ cb
1133
+ ]);
1134
+ else this.getBlobData(data, false, options, cb);
1135
+ else if (this._state !== DEFAULT) this.enqueue([
1136
+ this.dispatch,
1137
+ data,
1138
+ false,
1139
+ options,
1140
+ cb
1141
+ ]);
1142
+ else this.sendFrame(Sender.frame(data, options), cb);
1143
+ }
1144
+ pong(data, mask, cb) {
1145
+ let byteLength;
1146
+ let readOnly;
1147
+ if ('string' == typeof data) {
1148
+ byteLength = Buffer.byteLength(data);
1149
+ readOnly = false;
1150
+ } else if (isBlob(data)) {
1151
+ byteLength = data.size;
1152
+ readOnly = false;
1153
+ } else {
1154
+ data = toBuffer(data);
1155
+ byteLength = data.length;
1156
+ readOnly = toBuffer.readOnly;
1157
+ }
1158
+ if (byteLength > 125) throw new RangeError('The data size must not be greater than 125 bytes');
1159
+ const options = {
1160
+ [kByteLength]: byteLength,
1161
+ fin: true,
1162
+ generateMask: this._generateMask,
1163
+ mask,
1164
+ maskBuffer: this._maskBuffer,
1165
+ opcode: 0x0a,
1166
+ readOnly,
1167
+ rsv1: false
1168
+ };
1169
+ if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
1170
+ this.getBlobData,
1171
+ data,
1172
+ false,
1173
+ options,
1174
+ cb
1175
+ ]);
1176
+ else this.getBlobData(data, false, options, cb);
1177
+ else if (this._state !== DEFAULT) this.enqueue([
1178
+ this.dispatch,
1179
+ data,
1180
+ false,
1181
+ options,
1182
+ cb
1183
+ ]);
1184
+ else this.sendFrame(Sender.frame(data, options), cb);
1185
+ }
1186
+ send(data, options, cb) {
1187
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1188
+ let opcode = options.binary ? 2 : 1;
1189
+ let rsv1 = options.compress;
1190
+ let byteLength;
1191
+ let readOnly;
1192
+ if ('string' == typeof data) {
1193
+ byteLength = Buffer.byteLength(data);
1194
+ readOnly = false;
1195
+ } else if (isBlob(data)) {
1196
+ byteLength = data.size;
1197
+ readOnly = false;
1198
+ } else {
1199
+ data = toBuffer(data);
1200
+ byteLength = data.length;
1201
+ readOnly = toBuffer.readOnly;
1202
+ }
1203
+ if (this._firstFragment) {
1204
+ this._firstFragment = false;
1205
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? 'server_no_context_takeover' : 'client_no_context_takeover']) rsv1 = byteLength >= perMessageDeflate._threshold;
1206
+ this._compress = rsv1;
1207
+ } else {
1208
+ rsv1 = false;
1209
+ opcode = 0;
1210
+ }
1211
+ if (options.fin) this._firstFragment = true;
1212
+ const opts = {
1213
+ [kByteLength]: byteLength,
1214
+ fin: options.fin,
1215
+ generateMask: this._generateMask,
1216
+ mask: options.mask,
1217
+ maskBuffer: this._maskBuffer,
1218
+ opcode,
1219
+ readOnly,
1220
+ rsv1
1221
+ };
1222
+ if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
1223
+ this.getBlobData,
1224
+ data,
1225
+ this._compress,
1226
+ opts,
1227
+ cb
1228
+ ]);
1229
+ else this.getBlobData(data, this._compress, opts, cb);
1230
+ else if (this._state !== DEFAULT) this.enqueue([
1231
+ this.dispatch,
1232
+ data,
1233
+ this._compress,
1234
+ opts,
1235
+ cb
1236
+ ]);
1237
+ else this.dispatch(data, this._compress, opts, cb);
1238
+ }
1239
+ getBlobData(blob, compress, options, cb) {
1240
+ this._bufferedBytes += options[kByteLength];
1241
+ this._state = GET_BLOB_DATA;
1242
+ blob.arrayBuffer().then((arrayBuffer)=>{
1243
+ if (this._socket.destroyed) {
1244
+ const err = new Error('The socket was closed while the blob was being read');
1245
+ process.nextTick(callCallbacks, this, err, cb);
1246
+ return;
1247
+ }
1248
+ this._bufferedBytes -= options[kByteLength];
1249
+ const data = toBuffer(arrayBuffer);
1250
+ if (compress) this.dispatch(data, compress, options, cb);
1251
+ else {
1252
+ this._state = DEFAULT;
1253
+ this.sendFrame(Sender.frame(data, options), cb);
1254
+ this.dequeue();
1255
+ }
1256
+ }).catch((err)=>{
1257
+ process.nextTick(onError, this, err, cb);
481
1258
  });
482
- return;
483
1259
  }
484
- if ("OPTIONS" === req.method && this.#isVersionRequest(req.url)) {
485
- this.#setVersionCorsHeaders(res);
486
- res.writeHead(204, {
487
- "access-control-allow-methods": "GET",
488
- "cache-control": "no-store"
1260
+ dispatch(data, compress, options, cb) {
1261
+ if (!compress) return void this.sendFrame(Sender.frame(data, options), cb);
1262
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1263
+ this._bufferedBytes += options[kByteLength];
1264
+ this._state = DEFLATING;
1265
+ perMessageDeflate.compress(data, options.fin, (_, buf)=>{
1266
+ if (this._socket.destroyed) {
1267
+ const err = new Error('The socket was closed while data was being compressed');
1268
+ callCallbacks(this, err, cb);
1269
+ return;
1270
+ }
1271
+ this._bufferedBytes -= options[kByteLength];
1272
+ this._state = DEFAULT;
1273
+ options.readOnly = false;
1274
+ this.sendFrame(Sender.frame(buf, options), cb);
1275
+ this.dequeue();
489
1276
  });
490
- res.end();
491
- return;
492
- }
493
- if (this.staticServer.tryHandle(req, res)) return;
494
- if ("POST" === req.method && isCommandRequest && this.#acceptsEventStream(req)) return void this.#trackCommandRequest(()=>this.#handleCommandStream(req, res));
495
- if ("POST" === req.method && isCommandRequest) return void this.#trackCommandRequest(()=>this.#handleCommandRequest(req, res));
496
- if ("GET" === req.method && isCommandRequest) return void this.#trackCommandRequest(()=>this.#handleCommandStream(req, res));
497
- if ("POST" === req.method && isShutdownRequest) return void this.#handleShutdownRequest(req, res);
498
- res.writeHead(404);
499
- res.end();
500
- });
501
- }
502
- async start(port) {
503
- const wss = new websocket_server({
504
- noServer: true
505
- });
506
- this.#wss = wss;
507
- this.#httpServer.on("upgrade", (request, socket, head)=>{
508
- if (this.#closed || !request.url?.startsWith(DAEMON_WS_PATH) || !this.#isTrustedLocalRequest(request)) return void socket.destroy();
509
- wss.handleUpgrade(request, socket, head, (ws)=>{
510
- if (this.#closed) return void ws.terminate();
511
- this.#handleConnection(ws);
1277
+ }
1278
+ dequeue() {
1279
+ while(this._state === DEFAULT && this._queue.length){
1280
+ const params = this._queue.shift();
1281
+ this._bufferedBytes -= params[3][kByteLength];
1282
+ Reflect.apply(params[0], this, params.slice(1));
1283
+ }
1284
+ }
1285
+ enqueue(params) {
1286
+ this._bufferedBytes += params[3][kByteLength];
1287
+ this._queue.push(params);
1288
+ }
1289
+ sendFrame(list, cb) {
1290
+ if (2 === list.length) {
1291
+ this._socket.cork();
1292
+ this._socket.write(list[0]);
1293
+ this._socket.write(list[1], cb);
1294
+ this._socket.uncork();
1295
+ } else this._socket.write(list[0], cb);
1296
+ }
1297
+ }
1298
+ module.exports = Sender;
1299
+ function callCallbacks(sender, err, cb) {
1300
+ if ('function' == typeof cb) cb(err);
1301
+ for(let i = 0; i < sender._queue.length; i++){
1302
+ const params = sender._queue[i];
1303
+ const callback = params[params.length - 1];
1304
+ if ('function' == typeof callback) callback(err);
1305
+ }
1306
+ }
1307
+ function onError(sender, err, cb) {
1308
+ callCallbacks(sender, err, cb);
1309
+ sender.onerror(err);
1310
+ }
1311
+ },
1312
+ "../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/stream.js" (module, __unused_rspack_exports, __webpack_require__) {
1313
+ __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/websocket.js");
1314
+ const { Duplex } = __rspack_createRequire_require("stream");
1315
+ function emitClose(stream) {
1316
+ stream.emit('close');
1317
+ }
1318
+ function duplexOnEnd() {
1319
+ if (!this.destroyed && this._writableState.finished) this.destroy();
1320
+ }
1321
+ function duplexOnError(err) {
1322
+ this.removeListener('error', duplexOnError);
1323
+ this.destroy();
1324
+ if (0 === this.listenerCount('error')) this.emit('error', err);
1325
+ }
1326
+ function createWebSocketStream(ws, options) {
1327
+ let terminateOnDestroy = true;
1328
+ const duplex = new Duplex({
1329
+ ...options,
1330
+ autoDestroy: false,
1331
+ emitClose: false,
1332
+ objectMode: false,
1333
+ writableObjectMode: false
512
1334
  });
513
- });
514
- return new Promise((resolve, reject)=>{
515
- this.#httpServer.once("error", reject);
516
- this.#httpServer.listen(port, "127.0.0.1", ()=>{
517
- this.#httpServer.removeListener("error", reject);
518
- this.#resetIdleTimer();
519
- const address = this.#httpServer.address();
520
- this.#commandConnector = new Connector([
521
- new DaemonTransport(`ws://127.0.0.1:${address.port}${DAEMON_WS_PATH}`)
522
- ]);
523
- server_debug("daemon listening on ws://127.0.0.1:%d%s", address.port, DAEMON_WS_PATH);
524
- resolve(address.port);
1335
+ ws.on('message', function(msg, isBinary) {
1336
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
1337
+ if (!duplex.push(data)) ws.pause();
525
1338
  });
526
- });
527
- }
528
- close() {
529
- this.#closePromise ??= this.#close();
530
- return this.#closePromise;
531
- }
532
- async #close() {
533
- this.#closed = true;
534
- this.#clearIdleTimer();
535
- for (const controller of this.#commandControllers)controller.abort(new Error("Connector daemon is shutting down."));
536
- this.#commandControllers.clear();
537
- for (const [, client] of this.#wsClients)client.close();
538
- this.#wsClients.clear();
539
- for (const ws of this.#wss?.clients ?? [])ws.terminate();
540
- for (const [, timer] of this.#deviceConnectionCleanupTimers)clearTimeout(timer);
541
- this.#deviceConnectionCleanupTimers.clear();
542
- const shutdownResults = await Promise.allSettled([
543
- ...Array.from(this.#deviceConnections.values(), (conn)=>conn.dispose()),
544
- ...this.#pendingDeviceConnections.values(),
545
- ...this.#transports.map((transport)=>Promise.resolve().then(()=>transport.close()))
546
- ]);
547
- for (const result of shutdownResults)if ("rejected" === result.status) server_debug("device connection did not settle cleanly during daemon shutdown: %O", result.reason);
548
- const lateDisposalResults = await Promise.allSettled(Array.from(this.#deviceConnections.values(), (conn)=>conn.dispose()));
549
- for (const result of lateDisposalResults)if ("rejected" === result.status) server_debug("failed to dispose late device connection during daemon shutdown: %O", result.reason);
550
- this.#deviceConnections.clear();
551
- this.#wss?.close();
552
- return new Promise((resolve)=>{
553
- this.#httpServer.close(()=>resolve());
554
- });
555
- }
556
- #isVersionRequest(url) {
557
- return new URL(url ?? "/", "http://127.0.0.1").pathname === DAEMON_VERSION_PATH;
558
- }
559
- #isShutdownRequest(url) {
560
- return new URL(url ?? "/", "http://127.0.0.1").pathname === DAEMON_SHUTDOWN_PATH;
561
- }
562
- #isCommandRequest(url) {
563
- return new URL(url ?? "/", "http://127.0.0.1").pathname.startsWith(DAEMON_COMMAND_PATH_PREFIX);
564
- }
565
- #setVersionCorsHeaders(res) {
566
- res.setHeader("access-control-allow-origin", "*");
567
- res.setHeader("access-control-allow-private-network", "true");
568
- }
569
- #isTrustedLocalRequest(req) {
570
- const host = req.headers.host;
571
- if (!host) return false;
572
- let requestOrigin;
573
- try {
574
- requestOrigin = new URL(`http://${host}`);
575
- } catch {
576
- return false;
1339
+ ws.once('error', function(err) {
1340
+ if (duplex.destroyed) return;
1341
+ terminateOnDestroy = false;
1342
+ duplex.destroy(err);
1343
+ });
1344
+ ws.once('close', function() {
1345
+ if (duplex.destroyed) return;
1346
+ duplex.push(null);
1347
+ });
1348
+ duplex._destroy = function(err, callback) {
1349
+ if (ws.readyState === ws.CLOSED) {
1350
+ callback(err);
1351
+ process.nextTick(emitClose, duplex);
1352
+ return;
1353
+ }
1354
+ let called = false;
1355
+ ws.once('error', function(err) {
1356
+ called = true;
1357
+ callback(err);
1358
+ });
1359
+ ws.once('close', function() {
1360
+ if (!called) callback(err);
1361
+ process.nextTick(emitClose, duplex);
1362
+ });
1363
+ if (terminateOnDestroy) ws.terminate();
1364
+ };
1365
+ duplex._final = function(callback) {
1366
+ if (ws.readyState === ws.CONNECTING) return void ws.once('open', function() {
1367
+ duplex._final(callback);
1368
+ });
1369
+ if (null === ws._socket) return;
1370
+ if (ws._socket._writableState.finished) {
1371
+ callback();
1372
+ if (duplex._readableState.endEmitted) duplex.destroy();
1373
+ } else {
1374
+ ws._socket.once('finish', function() {
1375
+ callback();
1376
+ });
1377
+ ws.close();
1378
+ }
1379
+ };
1380
+ duplex._read = function() {
1381
+ if (ws.isPaused) ws.resume();
1382
+ };
1383
+ duplex._write = function(chunk, encoding, callback) {
1384
+ if (ws.readyState === ws.CONNECTING) return void ws.once('open', function() {
1385
+ duplex._write(chunk, encoding, callback);
1386
+ });
1387
+ ws.send(chunk, callback);
1388
+ };
1389
+ duplex.on('end', duplexOnEnd);
1390
+ duplex.on('error', duplexOnError);
1391
+ return duplex;
577
1392
  }
578
- if ("127.0.0.1" !== requestOrigin.hostname && "localhost" !== requestOrigin.hostname) return false;
579
- const origin = req.headers.origin;
580
- if (!origin) return true;
581
- try {
582
- const originUrl = new URL(origin);
583
- return "http:" === originUrl.protocol && originUrl.host.toLowerCase() === requestOrigin.host.toLowerCase();
584
- } catch {
585
- return false;
1393
+ module.exports = createWebSocketStream;
1394
+ },
1395
+ "../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/subprotocol.js" (module, __unused_rspack_exports, __webpack_require__) {
1396
+ const { tokenChars } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/validation.js");
1397
+ function parse(header) {
1398
+ const protocols = new Set();
1399
+ let start = -1;
1400
+ let end = -1;
1401
+ let i = 0;
1402
+ for(i; i < header.length; i++){
1403
+ const code = header.charCodeAt(i);
1404
+ if (-1 === end && 1 === tokenChars[code]) {
1405
+ if (-1 === start) start = i;
1406
+ } else if (0 !== i && (0x20 === code || 0x09 === code)) {
1407
+ if (-1 === end && -1 !== start) end = i;
1408
+ } else if (0x2c === code) {
1409
+ if (-1 === start) throw new SyntaxError(`Unexpected character at index ${i}`);
1410
+ if (-1 === end) end = i;
1411
+ const protocol = header.slice(start, end);
1412
+ if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
1413
+ protocols.add(protocol);
1414
+ start = end = -1;
1415
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
1416
+ }
1417
+ if (-1 === start || -1 !== end) throw new SyntaxError('Unexpected end of input');
1418
+ const protocol = header.slice(start, i);
1419
+ if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
1420
+ protocols.add(protocol);
1421
+ return protocols;
586
1422
  }
587
- }
588
- #hasJsonContentType(req) {
589
- return req.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase() === "application/json";
590
- }
591
- #acceptsEventStream(req) {
592
- const accept = req.headers.accept;
593
- const values = Array.isArray(accept) ? accept : [
594
- accept ?? ""
1423
+ module.exports = {
1424
+ parse
1425
+ };
1426
+ },
1427
+ "../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/validation.js" (module, __unused_rspack_exports, __webpack_require__) {
1428
+ const { isUtf8 } = __rspack_createRequire_require("buffer");
1429
+ const { hasBlob } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/constants.js");
1430
+ const tokenChars = [
1431
+ 0,
1432
+ 0,
1433
+ 0,
1434
+ 0,
1435
+ 0,
1436
+ 0,
1437
+ 0,
1438
+ 0,
1439
+ 0,
1440
+ 0,
1441
+ 0,
1442
+ 0,
1443
+ 0,
1444
+ 0,
1445
+ 0,
1446
+ 0,
1447
+ 0,
1448
+ 0,
1449
+ 0,
1450
+ 0,
1451
+ 0,
1452
+ 0,
1453
+ 0,
1454
+ 0,
1455
+ 0,
1456
+ 0,
1457
+ 0,
1458
+ 0,
1459
+ 0,
1460
+ 0,
1461
+ 0,
1462
+ 0,
1463
+ 0,
1464
+ 1,
1465
+ 0,
1466
+ 1,
1467
+ 1,
1468
+ 1,
1469
+ 1,
1470
+ 1,
1471
+ 0,
1472
+ 0,
1473
+ 1,
1474
+ 1,
1475
+ 0,
1476
+ 1,
1477
+ 1,
1478
+ 0,
1479
+ 1,
1480
+ 1,
1481
+ 1,
1482
+ 1,
1483
+ 1,
1484
+ 1,
1485
+ 1,
1486
+ 1,
1487
+ 1,
1488
+ 1,
1489
+ 0,
1490
+ 0,
1491
+ 0,
1492
+ 0,
1493
+ 0,
1494
+ 0,
1495
+ 0,
1496
+ 1,
1497
+ 1,
1498
+ 1,
1499
+ 1,
1500
+ 1,
1501
+ 1,
1502
+ 1,
1503
+ 1,
1504
+ 1,
1505
+ 1,
1506
+ 1,
1507
+ 1,
1508
+ 1,
1509
+ 1,
1510
+ 1,
1511
+ 1,
1512
+ 1,
1513
+ 1,
1514
+ 1,
1515
+ 1,
1516
+ 1,
1517
+ 1,
1518
+ 1,
1519
+ 1,
1520
+ 1,
1521
+ 1,
1522
+ 0,
1523
+ 0,
1524
+ 0,
1525
+ 1,
1526
+ 1,
1527
+ 1,
1528
+ 1,
1529
+ 1,
1530
+ 1,
1531
+ 1,
1532
+ 1,
1533
+ 1,
1534
+ 1,
1535
+ 1,
1536
+ 1,
1537
+ 1,
1538
+ 1,
1539
+ 1,
1540
+ 1,
1541
+ 1,
1542
+ 1,
1543
+ 1,
1544
+ 1,
1545
+ 1,
1546
+ 1,
1547
+ 1,
1548
+ 1,
1549
+ 1,
1550
+ 1,
1551
+ 1,
1552
+ 1,
1553
+ 1,
1554
+ 0,
1555
+ 1,
1556
+ 0,
1557
+ 1,
1558
+ 0
595
1559
  ];
596
- return values.some((value)=>value.split(",").some((mediaType)=>mediaType.trim().toLowerCase().startsWith("text/event-stream")));
597
- }
598
- async #handleShutdownRequest(req, res) {
599
- let parsed;
600
- try {
601
- const body = await this.#readBody(req);
602
- parsed = "" === body.trim() ? {} : JSON.parse(body);
603
- } catch (error) {
604
- this.#sendJson(res, 400, {
605
- ok: false,
606
- error: `Invalid shutdown request: ${error instanceof Error ? error.message : String(error)}`
607
- });
608
- return;
1560
+ function isValidStatusCode(code) {
1561
+ return code >= 1000 && code <= 1014 && 1004 !== code && 1005 !== code && 1006 !== code || code >= 3000 && code <= 4999;
609
1562
  }
610
- if ("object" != typeof parsed || null === parsed || Array.isArray(parsed)) return void this.#sendJson(res, 400, {
611
- ok: false,
612
- error: "Shutdown request body must be a JSON object."
613
- });
614
- const { expectedInstanceId } = parsed;
615
- if ("string" != typeof expectedInstanceId || "" === expectedInstanceId) return void this.#sendJson(res, 428, {
616
- ok: false,
617
- error: "Shutdown requires the expected daemon instance ID."
618
- });
619
- if (expectedInstanceId !== this.#instanceId) return void this.#sendJson(res, 409, {
620
- ok: false,
621
- error: "Daemon instance changed before shutdown.",
622
- instanceId: this.#instanceId
623
- });
624
- if (this.#shutdownAccepted) return void this.#sendJson(res, 202, {
625
- ok: true,
626
- alreadyStopping: true
627
- });
628
- this.#shutdownAccepted = true;
629
- this.#sendJson(res, 202, {
630
- ok: true
631
- }, ()=>{
632
- this.close().catch((err)=>{
633
- server_debug("failed to close daemon after shutdown request: %O", err);
634
- }).finally(()=>{
635
- this.#onShutdown?.();
636
- });
637
- });
638
- }
639
- async #handleCommandRequest(req, res) {
640
- const pathname = new URL(req.url ?? "/", "http://127.0.0.1").pathname;
641
- let action;
642
- try {
643
- action = decodeURIComponent(pathname.slice(DAEMON_COMMAND_PATH_PREFIX.length));
644
- } catch {
645
- this.#sendJson(res, 400, {
646
- ok: false,
647
- action: "",
648
- error: {
649
- message: "Command action path contains invalid percent encoding.",
650
- reason: "bad-path",
651
- recoverable: false,
652
- nextActions: []
653
- }
654
- });
655
- return;
1563
+ function _isValidUTF8(buf) {
1564
+ const len = buf.length;
1565
+ let i = 0;
1566
+ while(i < len)if ((0x80 & buf[i]) === 0) i++;
1567
+ else if ((0xe0 & buf[i]) === 0xc0) {
1568
+ if (i + 1 === len || (0xc0 & buf[i + 1]) !== 0x80 || (0xfe & buf[i]) === 0xc0) return false;
1569
+ i += 2;
1570
+ } else if ((0xf0 & buf[i]) === 0xe0) {
1571
+ if (i + 2 >= len || (0xc0 & buf[i + 1]) !== 0x80 || (0xc0 & buf[i + 2]) !== 0x80 || 0xe0 === buf[i] && (0xe0 & buf[i + 1]) === 0x80 || 0xed === buf[i] && (0xe0 & buf[i + 1]) === 0xa0) return false;
1572
+ i += 3;
1573
+ } else {
1574
+ if ((0xf8 & buf[i]) !== 0xf0) return false;
1575
+ if (i + 3 >= len || (0xc0 & buf[i + 1]) !== 0x80 || (0xc0 & buf[i + 2]) !== 0x80 || (0xc0 & buf[i + 3]) !== 0x80 || 0xf0 === buf[i] && (0xf0 & buf[i + 1]) === 0x80 || 0xf4 === buf[i] && buf[i + 1] > 0x8f || buf[i] > 0xf4) return false;
1576
+ i += 4;
1577
+ }
1578
+ return true;
1579
+ }
1580
+ function isBlob(value) {
1581
+ return hasBlob && 'object' == typeof value && 'function' == typeof value.arrayBuffer && 'string' == typeof value.type && 'function' == typeof value.stream && ('Blob' === value[Symbol.toStringTag] || 'File' === value[Symbol.toStringTag]);
656
1582
  }
657
- const controller = new AbortController();
658
- this.#commandControllers.add(controller);
659
- const onDisconnect = ()=>controller.abort(new Error("HTTP command client disconnected."));
660
- req.once("aborted", onDisconnect);
661
- res.once("close", onDisconnect);
662
- try {
663
- let params = {};
664
- try {
665
- const body = await this.#readBody(req, controller.signal);
666
- if ("" !== body.trim()) {
667
- const parsed = JSON.parse(body);
668
- if ("object" != typeof parsed || null === parsed || Array.isArray(parsed)) return void this.#sendJson(res, 200, {
669
- ok: false,
670
- action,
671
- error: {
672
- message: "Request body must be a JSON object.",
673
- reason: "bad-params",
674
- recoverable: false,
675
- nextActions: []
1583
+ module.exports = {
1584
+ isBlob,
1585
+ isValidStatusCode,
1586
+ isValidUTF8: _isValidUTF8,
1587
+ tokenChars
1588
+ };
1589
+ if (isUtf8) module.exports.isValidUTF8 = function(buf) {
1590
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
1591
+ };
1592
+ else if (!process.env.WS_NO_UTF_8_VALIDATE) try {
1593
+ const isValidUTF8 = __webpack_require__("utf-8-validate");
1594
+ module.exports.isValidUTF8 = function(buf) {
1595
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
1596
+ };
1597
+ } catch (e) {}
1598
+ },
1599
+ "../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/websocket-server.js" (module, __unused_rspack_exports, __webpack_require__) {
1600
+ const EventEmitter = __rspack_createRequire_require("events");
1601
+ const http = __rspack_createRequire_require("http");
1602
+ const { Duplex } = __rspack_createRequire_require("stream");
1603
+ const { createHash } = __rspack_createRequire_require("crypto");
1604
+ const extension = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/extension.js");
1605
+ const PerMessageDeflate = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/permessage-deflate.js");
1606
+ const subprotocol = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/subprotocol.js");
1607
+ const WebSocket = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/websocket.js");
1608
+ const { CLOSE_TIMEOUT, GUID, kWebSocket } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/constants.js");
1609
+ const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
1610
+ const RUNNING = 0;
1611
+ const CLOSING = 1;
1612
+ const CLOSED = 2;
1613
+ class WebSocketServer extends EventEmitter {
1614
+ constructor(options, callback){
1615
+ super();
1616
+ options = {
1617
+ allowSynchronousEvents: true,
1618
+ autoPong: true,
1619
+ maxBufferedChunks: 262144,
1620
+ maxFragments: 16384,
1621
+ maxPayload: 104857600,
1622
+ maxPendingAutoPongs: 60,
1623
+ skipUTF8Validation: false,
1624
+ perMessageDeflate: false,
1625
+ handleProtocols: null,
1626
+ clientTracking: true,
1627
+ closeTimeout: CLOSE_TIMEOUT,
1628
+ verifyClient: null,
1629
+ noServer: false,
1630
+ backlog: null,
1631
+ server: null,
1632
+ host: null,
1633
+ path: null,
1634
+ port: null,
1635
+ WebSocket,
1636
+ ...options
1637
+ };
1638
+ if (null == options.port && !options.server && !options.noServer || null != options.port && (options.server || options.noServer) || options.server && options.noServer) throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');
1639
+ if (null != options.port) {
1640
+ this._server = http.createServer((req, res)=>{
1641
+ const body = http.STATUS_CODES[426];
1642
+ res.writeHead(426, {
1643
+ 'Content-Length': body.length,
1644
+ 'Content-Type': 'text/plain'
1645
+ });
1646
+ res.end(body);
1647
+ });
1648
+ this._server.listen(options.port, options.host, options.backlog, callback);
1649
+ } else if (options.server) this._server = options.server;
1650
+ if (this._server) {
1651
+ const emitConnection = this.emit.bind(this, 'connection');
1652
+ this._removeListeners = addListeners(this._server, {
1653
+ listening: this.emit.bind(this, 'listening'),
1654
+ error: this.emit.bind(this, 'error'),
1655
+ upgrade: (req, socket, head)=>{
1656
+ this.handleUpgrade(req, socket, head, emitConnection);
676
1657
  }
677
1658
  });
678
- params = parsed;
679
- }
680
- } catch (error) {
681
- if (controller.signal.aborted) return;
682
- this.#sendJson(res, 200, {
683
- ok: false,
684
- action,
685
- error: {
686
- message: `Invalid JSON body: ${error instanceof Error ? error.message : String(error)}`,
687
- reason: "bad-params",
688
- recoverable: false,
689
- nextActions: []
1659
+ }
1660
+ if (true === options.perMessageDeflate) options.perMessageDeflate = {};
1661
+ if (options.clientTracking) {
1662
+ this.clients = new Set();
1663
+ this._shouldEmitClose = false;
1664
+ }
1665
+ this.options = options;
1666
+ this._state = RUNNING;
1667
+ }
1668
+ address() {
1669
+ if (this.options.noServer) throw new Error('The server is operating in "noServer" mode');
1670
+ if (!this._server) return null;
1671
+ return this._server.address();
1672
+ }
1673
+ close(cb) {
1674
+ if (this._state === CLOSED) {
1675
+ if (cb) this.once('close', ()=>{
1676
+ cb(new Error('The server is not running'));
1677
+ });
1678
+ process.nextTick(emitClose, this);
1679
+ return;
1680
+ }
1681
+ if (cb) this.once('close', cb);
1682
+ if (this._state === CLOSING) return;
1683
+ this._state = CLOSING;
1684
+ if (this.options.noServer || this.options.server) {
1685
+ if (this._server) {
1686
+ this._removeListeners();
1687
+ this._removeListeners = this._server = null;
690
1688
  }
691
- });
692
- return;
693
- }
694
- const result = await this.actionCore.execute(action, params, {
695
- connector: this.#requireCommandConnector()
696
- }, controller.signal);
697
- if (!controller.signal.aborted && !res.destroyed) this.#sendJson(res, 200, result);
698
- } finally{
699
- req.off("aborted", onDisconnect);
700
- res.off("close", onDisconnect);
701
- this.#commandControllers.delete(controller);
702
- if (controller.signal.aborted && !res.destroyed && !res.writableEnded) res.destroy();
703
- }
704
- }
705
- async #handleCommandStream(req, res) {
706
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
707
- let action;
708
- try {
709
- action = decodeURIComponent(url.pathname.slice(DAEMON_COMMAND_PATH_PREFIX.length));
710
- } catch {
711
- this.#sendJson(res, 400, {
712
- ok: false,
713
- action: "",
714
- error: {
715
- message: "Command action path contains invalid percent encoding.",
716
- reason: "bad-path",
717
- recoverable: false,
718
- nextActions: []
1689
+ if (this.clients) if (this.clients.size) this._shouldEmitClose = true;
1690
+ else process.nextTick(emitClose, this);
1691
+ else process.nextTick(emitClose, this);
1692
+ } else {
1693
+ const server = this._server;
1694
+ this._removeListeners();
1695
+ this._removeListeners = this._server = null;
1696
+ server.close(()=>{
1697
+ emitClose(this);
1698
+ });
719
1699
  }
720
- });
721
- return;
722
- }
723
- if (!this.actionCore.hasStream(action)) return void this.#sendJson(res, 404, {
724
- ok: false,
725
- action,
726
- error: {
727
- message: `Unknown stream action: ${action}`,
728
- reason: "unknown-action",
729
- recoverable: false,
730
- nextActions: this.actionCore.streamActions().map((name)=>`GET /command/${name}`)
731
1700
  }
732
- });
733
- const controller = new AbortController();
734
- this.#commandControllers.add(controller);
735
- const onDisconnect = ()=>controller.abort(new Error("SSE command client disconnected."));
736
- req.once("aborted", onDisconnect);
737
- res.once("close", onDisconnect);
738
- try {
739
- let params;
740
- try {
741
- params = "POST" === req.method ? await this.#readCommandStreamBody(req, controller.signal) : decodeCommandQuery(url.searchParams);
742
- } catch (error) {
743
- if (controller.signal.aborted) return;
744
- res.writeHead(200, {
745
- "content-type": "text/event-stream; charset=utf-8",
746
- "cache-control": "no-store",
747
- connection: "keep-alive"
748
- });
749
- res.end(`data: ${JSON.stringify({
750
- ok: false,
751
- action,
752
- error: {
753
- message: `Invalid JSON body: ${error instanceof Error ? error.message : String(error)}`,
754
- reason: "bad-params",
755
- recoverable: false,
756
- nextActions: []
1701
+ shouldHandle(req) {
1702
+ if (this.options.path) {
1703
+ const index = req.url.indexOf('?');
1704
+ const pathname = -1 !== index ? req.url.slice(0, index) : req.url;
1705
+ if (pathname !== this.options.path) return false;
1706
+ }
1707
+ return true;
1708
+ }
1709
+ handleUpgrade(req, socket, head, cb) {
1710
+ socket.on('error', socketOnError);
1711
+ const key = req.headers['sec-websocket-key'];
1712
+ const upgrade = req.headers.upgrade;
1713
+ const version = +req.headers['sec-websocket-version'];
1714
+ if ('GET' !== req.method) {
1715
+ const message = 'Invalid HTTP method';
1716
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
1717
+ return;
1718
+ }
1719
+ if (void 0 === upgrade || 'websocket' !== upgrade.toLowerCase()) {
1720
+ const message = 'Invalid Upgrade header';
1721
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
1722
+ return;
1723
+ }
1724
+ if (void 0 === key || !keyRegex.test(key)) {
1725
+ const message = 'Missing or invalid Sec-WebSocket-Key header';
1726
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
1727
+ return;
1728
+ }
1729
+ if (13 !== version && 8 !== version) {
1730
+ const message = 'Missing or invalid Sec-WebSocket-Version header';
1731
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
1732
+ 'Sec-WebSocket-Version': '13, 8'
1733
+ });
1734
+ return;
1735
+ }
1736
+ if (!this.shouldHandle(req)) return void abortHandshake(socket, 400);
1737
+ const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
1738
+ let protocols = new Set();
1739
+ if (void 0 !== secWebSocketProtocol) try {
1740
+ protocols = subprotocol.parse(secWebSocketProtocol);
1741
+ } catch (err) {
1742
+ const message = 'Invalid Sec-WebSocket-Protocol header';
1743
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
1744
+ return;
1745
+ }
1746
+ const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
1747
+ const extensions = {};
1748
+ if (this.options.perMessageDeflate && void 0 !== secWebSocketExtensions) {
1749
+ const perMessageDeflate = new PerMessageDeflate({
1750
+ ...this.options.perMessageDeflate,
1751
+ isServer: true,
1752
+ maxPayload: this.options.maxPayload
1753
+ });
1754
+ try {
1755
+ const offers = extension.parse(secWebSocketExtensions);
1756
+ if (offers[PerMessageDeflate.extensionName]) {
1757
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
1758
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
1759
+ }
1760
+ } catch (err) {
1761
+ const message = 'Invalid or unacceptable Sec-WebSocket-Extensions header';
1762
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
1763
+ return;
757
1764
  }
758
- })}\n\n`);
759
- return;
760
- }
761
- controller.signal.throwIfAborted();
762
- res.writeHead(200, {
763
- "content-type": "text/event-stream; charset=utf-8",
764
- "cache-control": "no-store",
765
- connection: "keep-alive",
766
- "x-accel-buffering": "no"
767
- });
768
- for await (const event of this.actionCore.stream(action, params, {
769
- connector: this.#requireCommandConnector()
770
- }, controller.signal)){
771
- if (controller.signal.aborted) break;
772
- if (!res.write(`data: ${JSON.stringify(event)}\n\n`)) {
773
- const drained = await this.#waitForDrain(res, controller.signal);
774
- if (!drained) break;
775
- }
776
- }
777
- } catch (error) {
778
- if (!controller.signal.aborted) server_debug("command stream %s failed: %O", action, error);
779
- } finally{
780
- req.off("aborted", onDisconnect);
781
- res.off("close", onDisconnect);
782
- this.#commandControllers.delete(controller);
783
- if (!res.destroyed && !res.writableEnded) res.end();
1765
+ }
1766
+ if (this.options.verifyClient) {
1767
+ const info = {
1768
+ origin: req.headers[`${8 === version ? 'sec-websocket-origin' : 'origin'}`],
1769
+ secure: !!(req.socket.authorized || req.socket.encrypted),
1770
+ req
1771
+ };
1772
+ if (2 === this.options.verifyClient.length) return void this.options.verifyClient(info, (verified, code, message, headers)=>{
1773
+ if (!verified) return abortHandshake(socket, code || 401, message, headers);
1774
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
1775
+ });
1776
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
1777
+ }
1778
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
1779
+ }
1780
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
1781
+ if (!socket.readable || !socket.writable) return socket.destroy();
1782
+ if (socket[kWebSocket]) throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");
1783
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
1784
+ const digest = createHash('sha1').update(key + GUID).digest('base64');
1785
+ const headers = [
1786
+ 'HTTP/1.1 101 Switching Protocols',
1787
+ 'Upgrade: websocket',
1788
+ 'Connection: Upgrade',
1789
+ `Sec-WebSocket-Accept: ${digest}`
1790
+ ];
1791
+ const ws = new this.options.WebSocket(null, void 0, this.options);
1792
+ if (protocols.size) {
1793
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
1794
+ if (protocol) {
1795
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
1796
+ ws._protocol = protocol;
1797
+ }
1798
+ }
1799
+ if (extensions[PerMessageDeflate.extensionName]) {
1800
+ const params = extensions[PerMessageDeflate.extensionName].params;
1801
+ const value = extension.format({
1802
+ [PerMessageDeflate.extensionName]: [
1803
+ params
1804
+ ]
1805
+ });
1806
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
1807
+ ws._extensions = extensions;
1808
+ }
1809
+ this.emit('headers', headers, req);
1810
+ socket.write(headers.concat('\r\n').join('\r\n'));
1811
+ socket.removeListener('error', socketOnError);
1812
+ ws.setSocket(socket, head, {
1813
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
1814
+ maxBufferedChunks: this.options.maxBufferedChunks,
1815
+ maxFragments: this.options.maxFragments,
1816
+ maxPayload: this.options.maxPayload,
1817
+ skipUTF8Validation: this.options.skipUTF8Validation
1818
+ });
1819
+ if (this.clients) {
1820
+ this.clients.add(ws);
1821
+ ws.on('close', ()=>{
1822
+ this.clients.delete(ws);
1823
+ if (this._shouldEmitClose && !this.clients.size) process.nextTick(emitClose, this);
1824
+ });
1825
+ }
1826
+ cb(ws, req);
1827
+ }
784
1828
  }
785
- }
786
- #waitForDrain(res, signal) {
787
- if (signal.aborted || res.destroyed) return Promise.resolve(false);
788
- return new Promise((resolve)=>{
789
- let settled = false;
790
- const finish = (drained)=>{
791
- if (settled) return;
792
- settled = true;
793
- res.off("drain", onDrain);
794
- res.off("close", onClose);
795
- res.off("error", onClose);
796
- signal.removeEventListener("abort", onAbort);
797
- resolve(drained);
798
- };
799
- const onDrain = ()=>finish(true);
800
- const onAbort = ()=>finish(false);
801
- const onClose = ()=>finish(false);
802
- res.once("drain", onDrain);
803
- res.once("close", onClose);
804
- res.once("error", onClose);
805
- signal.addEventListener("abort", onAbort, {
806
- once: true
807
- });
808
- if (signal.aborted || res.destroyed) finish(false);
809
- });
810
- }
811
- #requireCommandConnector() {
812
- if (!this.#commandConnector) throw new Error("Connector daemon has not started its command transport.");
813
- return this.#commandConnector;
814
- }
815
- #readBody(req, signal) {
816
- return new Promise((resolve, reject)=>{
817
- const chunks = [];
818
- let size = 0;
819
- let settled = false;
820
- const maxSize = 8388608;
821
- const cleanup = ()=>{
822
- req.off("data", onData);
823
- req.off("end", onEnd);
824
- req.off("error", onError);
825
- req.off("aborted", onAborted);
826
- signal?.removeEventListener("abort", onSignalAbort);
1829
+ module.exports = WebSocketServer;
1830
+ function addListeners(server, map) {
1831
+ for (const event of Object.keys(map))server.on(event, map[event]);
1832
+ return function() {
1833
+ for (const event of Object.keys(map))server.removeListener(event, map[event]);
827
1834
  };
828
- const finish = (callback)=>{
829
- if (settled) return;
830
- settled = true;
831
- cleanup();
832
- callback();
1835
+ }
1836
+ function emitClose(server) {
1837
+ server._state = CLOSED;
1838
+ server.emit('close');
1839
+ }
1840
+ function socketOnError() {
1841
+ this.destroy();
1842
+ }
1843
+ function abortHandshake(socket, code, message, headers) {
1844
+ message = message || http.STATUS_CODES[code];
1845
+ headers = {
1846
+ Connection: 'close',
1847
+ 'Content-Type': 'text/html',
1848
+ 'Content-Length': Buffer.byteLength(message),
1849
+ ...headers
833
1850
  };
834
- const onData = (chunk)=>{
835
- size += chunk.length;
836
- if (size > maxSize) {
837
- finish(()=>reject(new Error("Request body exceeds 8 MiB.")));
838
- req.destroy();
1851
+ socket.once('finish', socket.destroy);
1852
+ socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + Object.keys(headers).map((h)=>`${h}: ${headers[h]}`).join('\r\n') + '\r\n\r\n' + message);
1853
+ }
1854
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
1855
+ if (server.listenerCount('wsClientError')) {
1856
+ const err = new Error(message);
1857
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
1858
+ server.emit('wsClientError', err, socket, req);
1859
+ } else abortHandshake(socket, code, message, headers);
1860
+ }
1861
+ },
1862
+ "../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/websocket.js" (module, __unused_rspack_exports, __webpack_require__) {
1863
+ const EventEmitter = __rspack_createRequire_require("events");
1864
+ const https = __rspack_createRequire_require("https");
1865
+ const http = __rspack_createRequire_require("http");
1866
+ const net = __rspack_createRequire_require("net");
1867
+ const querystring = __rspack_createRequire_require("querystring");
1868
+ const tls = __rspack_createRequire_require("tls");
1869
+ const { randomBytes, createHash } = __rspack_createRequire_require("crypto");
1870
+ const { Duplex, Readable } = __rspack_createRequire_require("stream");
1871
+ const { URL } = __rspack_createRequire_require("url");
1872
+ const PerMessageDeflate = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/permessage-deflate.js");
1873
+ const Receiver = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/receiver.js");
1874
+ const Sender = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/sender.js");
1875
+ const { isBlob } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/validation.js");
1876
+ const { BINARY_TYPES, CLOSE_TIMEOUT, EMPTY_BUFFER, GUID, kForOnEventAttribute, kListener, kStatusCode, kWebSocket, NOOP } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/constants.js");
1877
+ const { EventTarget: { addEventListener, removeEventListener } } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/event-target.js");
1878
+ const { format, parse } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/extension.js");
1879
+ const { toBuffer } = __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/buffer-util.js");
1880
+ const kAborted = Symbol('kAborted');
1881
+ const protocolVersions = [
1882
+ 8,
1883
+ 13
1884
+ ];
1885
+ const readyStates = [
1886
+ 'CONNECTING',
1887
+ 'OPEN',
1888
+ 'CLOSING',
1889
+ 'CLOSED'
1890
+ ];
1891
+ const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
1892
+ class WebSocket extends EventEmitter {
1893
+ constructor(address, protocols, options){
1894
+ super();
1895
+ this._binaryType = BINARY_TYPES[0];
1896
+ this._closeCode = 1006;
1897
+ this._closeFrameReceived = false;
1898
+ this._closeFrameSent = false;
1899
+ this._closeMessage = EMPTY_BUFFER;
1900
+ this._closeTimer = null;
1901
+ this._errorEmitted = false;
1902
+ this._extensions = {};
1903
+ this._paused = false;
1904
+ this._protocol = '';
1905
+ this._readyState = WebSocket.CONNECTING;
1906
+ this._receiver = null;
1907
+ this._sender = null;
1908
+ this._socket = null;
1909
+ if (null !== address) {
1910
+ this._bufferedAmount = 0;
1911
+ this._isServer = false;
1912
+ this._redirects = 0;
1913
+ if (void 0 === protocols) protocols = options && void 0 !== options.protocols ? Array.isArray(options.protocols) ? options.protocols : [
1914
+ options.protocols
1915
+ ] : [];
1916
+ else if (!Array.isArray(protocols)) if ('object' == typeof protocols && null !== protocols) {
1917
+ options = protocols;
1918
+ protocols = void 0 === options.protocols ? [] : Array.isArray(options.protocols) ? options.protocols : [
1919
+ options.protocols
1920
+ ];
1921
+ } else protocols = [
1922
+ protocols
1923
+ ];
1924
+ options = initAsClient(this, address, protocols, options);
1925
+ } else this._isServer = true;
1926
+ if (options.autoPong) {
1927
+ this._autoPong = true;
1928
+ this._autoPongComplete = ()=>autoPongComplete(this);
1929
+ this._pendingAutoPongs = 0;
1930
+ this._maxPendingAutoPongs = 0 | options.maxPendingAutoPongs;
1931
+ }
1932
+ this._closeTimeout = options.closeTimeout;
1933
+ }
1934
+ get binaryType() {
1935
+ return this._binaryType;
1936
+ }
1937
+ set binaryType(type) {
1938
+ if (!BINARY_TYPES.includes(type)) return;
1939
+ this._binaryType = type;
1940
+ if (this._receiver) this._receiver._binaryType = type;
1941
+ }
1942
+ get bufferedAmount() {
1943
+ if (!this._socket) return this._bufferedAmount;
1944
+ return this._socket._writableState.length + this._sender._bufferedBytes;
1945
+ }
1946
+ get extensions() {
1947
+ return Object.keys(this._extensions).join();
1948
+ }
1949
+ get isPaused() {
1950
+ return this._paused;
1951
+ }
1952
+ get onclose() {
1953
+ return null;
1954
+ }
1955
+ get onerror() {
1956
+ return null;
1957
+ }
1958
+ get onopen() {
1959
+ return null;
1960
+ }
1961
+ get onmessage() {
1962
+ return null;
1963
+ }
1964
+ get protocol() {
1965
+ return this._protocol;
1966
+ }
1967
+ get readyState() {
1968
+ return this._readyState;
1969
+ }
1970
+ get url() {
1971
+ return this._url;
1972
+ }
1973
+ setSocket(socket, head, options) {
1974
+ const receiver = new Receiver({
1975
+ allowSynchronousEvents: options.allowSynchronousEvents,
1976
+ binaryType: this.binaryType,
1977
+ extensions: this._extensions,
1978
+ isServer: this._isServer,
1979
+ maxBufferedChunks: options.maxBufferedChunks,
1980
+ maxFragments: options.maxFragments,
1981
+ maxPayload: options.maxPayload,
1982
+ skipUTF8Validation: options.skipUTF8Validation
1983
+ });
1984
+ const sender = new Sender(socket, this._extensions, options.generateMask);
1985
+ this._receiver = receiver;
1986
+ this._sender = sender;
1987
+ this._socket = socket;
1988
+ receiver[kWebSocket] = this;
1989
+ sender[kWebSocket] = this;
1990
+ socket[kWebSocket] = this;
1991
+ receiver.on('conclude', receiverOnConclude);
1992
+ receiver.on('drain', receiverOnDrain);
1993
+ receiver.on('error', receiverOnError);
1994
+ receiver.on('message', receiverOnMessage);
1995
+ receiver.on('ping', receiverOnPing);
1996
+ receiver.on('pong', receiverOnPong);
1997
+ sender.onerror = senderOnError;
1998
+ if (socket.setTimeout) socket.setTimeout(0);
1999
+ if (socket.setNoDelay) socket.setNoDelay();
2000
+ if (head.length > 0) socket.unshift(head);
2001
+ socket.on('close', socketOnClose);
2002
+ socket.on('data', socketOnData);
2003
+ socket.on('end', socketOnEnd);
2004
+ socket.on('error', socketOnError);
2005
+ this._readyState = WebSocket.OPEN;
2006
+ this.emit('open');
2007
+ }
2008
+ emitClose() {
2009
+ if (!this._socket) {
2010
+ this._readyState = WebSocket.CLOSED;
2011
+ this.emit('close', this._closeCode, this._closeMessage);
839
2012
  return;
840
2013
  }
841
- chunks.push(chunk);
842
- };
843
- const onEnd = ()=>finish(()=>resolve(Buffer.concat(chunks).toString("utf8")));
844
- const onError = (error)=>finish(()=>reject(error));
845
- const onAborted = ()=>finish(()=>reject(new Error("Request body was aborted.")));
846
- const onSignalAbort = ()=>{
847
- finish(()=>reject(signal?.reason ?? new Error("Request was aborted.")));
848
- if (!req.destroyed) req.destroy();
849
- };
850
- req.on("data", onData);
851
- req.once("end", onEnd);
852
- req.once("error", onError);
853
- req.once("aborted", onAborted);
854
- signal?.addEventListener("abort", onSignalAbort, {
855
- once: true
856
- });
857
- if (signal?.aborted) onSignalAbort();
858
- });
859
- }
860
- async #readCommandStreamBody(req, signal) {
861
- const body = await this.#readBody(req, signal);
862
- if ("" === body.trim()) return {};
863
- const parsed = JSON.parse(body);
864
- if ("object" != typeof parsed || null === parsed || Array.isArray(parsed)) throw new Error("Request body must be a JSON object.");
865
- return parsed;
866
- }
867
- #sendJson(res, statusCode, data, callback) {
868
- const body = JSON.stringify(data);
869
- res.writeHead(statusCode, {
870
- "content-type": "application/json; charset=utf-8",
871
- "content-length": Buffer.byteLength(body),
872
- "cache-control": "no-store"
873
- });
874
- res.end(body, callback);
875
- }
876
- #trackCommandRequest(handler) {
877
- this.#activeCommandRequests += 1;
878
- this.#clearIdleTimer();
879
- handler().catch((error)=>{
880
- server_debug("command request failed: %O", error);
881
- }).finally(()=>{
882
- this.#activeCommandRequests -= 1;
883
- this.#resetIdleTimer();
884
- });
885
- }
886
- #handleConnection(ws) {
887
- if (this.#closed) return void ws.terminate();
888
- const clientId = ++this.#nextClientId;
889
- server_debug("new ws client %d", clientId);
890
- this.#clearIdleTimer();
891
- let closing = false;
892
- const closeListeners = new Set();
893
- const notifyCloseListeners = ()=>{
894
- for (const listener of closeListeners){
895
- closeListeners.delete(listener);
896
- listener();
2014
+ if (this._extensions[PerMessageDeflate.extensionName]) this._extensions[PerMessageDeflate.extensionName].cleanup();
2015
+ this._receiver.removeAllListeners();
2016
+ this._readyState = WebSocket.CLOSED;
2017
+ this.emit('close', this._closeCode, this._closeMessage);
897
2018
  }
898
- };
899
- const session = {
900
- id: clientId,
901
- get isClosing () {
902
- return closing;
903
- },
904
- subscriptions: new Set(),
905
- onClose (listener) {
906
- if (closing) {
907
- listener();
908
- return ()=>{};
909
- }
910
- closeListeners.add(listener);
911
- return ()=>{
912
- closeListeners.delete(listener);
2019
+ close(code, data) {
2020
+ if (this.readyState === WebSocket.CLOSED) return;
2021
+ if (this.readyState === WebSocket.CONNECTING) {
2022
+ const msg = 'WebSocket was closed before the connection was established';
2023
+ abortHandshake(this, this._req, msg);
2024
+ return;
2025
+ }
2026
+ if (this.readyState === WebSocket.CLOSING) {
2027
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) this._socket.end();
2028
+ return;
2029
+ }
2030
+ this._sender.close(code, data, !this._isServer, (err)=>{
2031
+ if (err) return;
2032
+ this._closeFrameSent = true;
2033
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) this._socket.end();
2034
+ });
2035
+ this._readyState = WebSocket.CLOSING;
2036
+ setCloseTimer(this);
2037
+ }
2038
+ pause() {
2039
+ if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
2040
+ this._paused = true;
2041
+ this._socket.pause();
2042
+ }
2043
+ ping(data, mask, cb) {
2044
+ if (this.readyState === WebSocket.CONNECTING) throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
2045
+ if ('function' == typeof data) {
2046
+ cb = data;
2047
+ data = mask = void 0;
2048
+ } else if ('function' == typeof mask) {
2049
+ cb = mask;
2050
+ mask = void 0;
2051
+ }
2052
+ if ('number' == typeof data) data = data.toString();
2053
+ if (this.readyState !== WebSocket.OPEN) return void sendAfterClose(this, data, cb);
2054
+ if (void 0 === mask) mask = !this._isServer;
2055
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2056
+ }
2057
+ pong(data, mask, cb) {
2058
+ if (this.readyState === WebSocket.CONNECTING) throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
2059
+ if ('function' == typeof data) {
2060
+ cb = data;
2061
+ data = mask = void 0;
2062
+ } else if ('function' == typeof mask) {
2063
+ cb = mask;
2064
+ mask = void 0;
2065
+ }
2066
+ if ('number' == typeof data) data = data.toString();
2067
+ if (this.readyState !== WebSocket.OPEN) return void sendAfterClose(this, data, cb);
2068
+ if (void 0 === mask) mask = !this._isServer;
2069
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2070
+ }
2071
+ resume() {
2072
+ if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
2073
+ this._paused = false;
2074
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
2075
+ }
2076
+ send(data, options, cb) {
2077
+ if (this.readyState === WebSocket.CONNECTING) throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
2078
+ if ('function' == typeof options) {
2079
+ cb = options;
2080
+ options = {};
2081
+ }
2082
+ if ('number' == typeof data) data = data.toString();
2083
+ if (this.readyState !== WebSocket.OPEN) return void sendAfterClose(this, data, cb);
2084
+ const opts = {
2085
+ binary: 'string' != typeof data,
2086
+ mask: !this._isServer,
2087
+ compress: true,
2088
+ fin: true,
2089
+ ...options
913
2090
  };
914
- },
915
- send (message) {
916
- if (!closing && 1 === ws.readyState) ws.send(JSON.stringify(message));
917
- },
918
- close: (cause)=>{
919
- if (closing) return;
920
- closing = true;
921
- this.#wsClients.delete(clientId);
922
- notifyCloseListeners();
923
- if (void 0 === cause) ws.close(1001, "device disconnected");
924
- else ws.close(1011, websocketCloseReason(cause));
2091
+ if (!this._extensions[PerMessageDeflate.extensionName]) opts.compress = false;
2092
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
925
2093
  }
926
- };
927
- session.send({
928
- event: "Initialize",
929
- data: clientId
930
- });
931
- ws.on("message", (raw)=>{
932
- try {
933
- const msg = JSON.parse(String(raw));
934
- this.#handleMessage(session, msg);
935
- } catch (err) {
936
- server_debug("failed to parse message from client %d: %O", clientId, err);
2094
+ terminate() {
2095
+ if (this.readyState === WebSocket.CLOSED) return;
2096
+ if (this.readyState === WebSocket.CONNECTING) {
2097
+ const msg = 'WebSocket was closed before the connection was established';
2098
+ abortHandshake(this, this._req, msg);
2099
+ return;
2100
+ }
2101
+ if (this._socket) {
2102
+ this._readyState = WebSocket.CLOSING;
2103
+ this._socket.destroy();
2104
+ }
937
2105
  }
2106
+ }
2107
+ Object.defineProperty(WebSocket, 'CONNECTING', {
2108
+ enumerable: true,
2109
+ value: readyStates.indexOf('CONNECTING')
938
2110
  });
939
- ws.on("close", ()=>{
940
- server_debug("ws client %d disconnected", clientId);
941
- closing = true;
942
- this.#wsClients.delete(clientId);
943
- notifyCloseListeners();
944
- for (const deviceConn of session.subscriptions){
945
- deviceConn.removeSubscriber(clientId);
946
- if (!this.#closed && 0 === deviceConn.subscriberCount) this.#scheduleDeviceConnectionCleanup(deviceConn);
947
- }
948
- session.subscriptions.clear();
949
- this.#resetIdleTimer();
2111
+ Object.defineProperty(WebSocket.prototype, 'CONNECTING', {
2112
+ enumerable: true,
2113
+ value: readyStates.indexOf('CONNECTING')
950
2114
  });
951
- ws.on("error", (err)=>{
952
- server_debug("ws client %d error: %O", clientId, err);
2115
+ Object.defineProperty(WebSocket, 'OPEN', {
2116
+ enumerable: true,
2117
+ value: readyStates.indexOf('OPEN')
953
2118
  });
954
- }
955
- #handleMessage(session, msg) {
956
- if (session.isClosing) return void server_debug("ignoring message from closing client %d", session.id);
957
- if (this.#closed) return void session.close();
958
- if (isRegisterEvent(msg)) {
959
- this.#wsClients.set(session.id, session);
960
- server_debug("client %d registered", session.id);
961
- return;
962
- }
963
- if (isListClientsRequest(msg)) return void this.#sendClientList(session);
964
- if (isPingEvent(msg)) return void session.send({
965
- event: "Pong"
2119
+ Object.defineProperty(WebSocket.prototype, 'OPEN', {
2120
+ enumerable: true,
2121
+ value: readyStates.indexOf('OPEN')
966
2122
  });
967
- if (isControlRequest(msg)) return void this.#handleControlRequest(session, msg);
968
- if (isCustomizedMessage(msg)) return void this.#handleCustomizedMessage(session, msg);
969
- server_debug("unknown message from client %d: %O", session.id, msg);
970
- }
971
- async #handleCustomizedMessage(session, msg) {
972
- const targetPort = msg.to ?? msg.data?.data?.client_id;
973
- if ("number" != typeof targetPort && "string" != typeof targetPort) return void server_debug("cannot determine target from message: %O", msg);
974
- for (const deviceConn of session.subscriptions)if (deviceConn.port === targetPort) {
975
- try {
976
- await deviceConn.send({
977
- ...msg,
978
- data: {
979
- ...msg.data,
980
- sender: targetPort
2123
+ Object.defineProperty(WebSocket, 'CLOSING', {
2124
+ enumerable: true,
2125
+ value: readyStates.indexOf('CLOSING')
2126
+ });
2127
+ Object.defineProperty(WebSocket.prototype, 'CLOSING', {
2128
+ enumerable: true,
2129
+ value: readyStates.indexOf('CLOSING')
2130
+ });
2131
+ Object.defineProperty(WebSocket, 'CLOSED', {
2132
+ enumerable: true,
2133
+ value: readyStates.indexOf('CLOSED')
2134
+ });
2135
+ Object.defineProperty(WebSocket.prototype, 'CLOSED', {
2136
+ enumerable: true,
2137
+ value: readyStates.indexOf('CLOSED')
2138
+ });
2139
+ [
2140
+ 'binaryType',
2141
+ 'bufferedAmount',
2142
+ 'extensions',
2143
+ 'isPaused',
2144
+ 'protocol',
2145
+ 'readyState',
2146
+ 'url'
2147
+ ].forEach((property)=>{
2148
+ Object.defineProperty(WebSocket.prototype, property, {
2149
+ enumerable: true
2150
+ });
2151
+ });
2152
+ [
2153
+ 'open',
2154
+ 'error',
2155
+ 'close',
2156
+ 'message'
2157
+ ].forEach((method)=>{
2158
+ Object.defineProperty(WebSocket.prototype, `on${method}`, {
2159
+ enumerable: true,
2160
+ get () {
2161
+ for (const listener of this.listeners(method))if (listener[kForOnEventAttribute]) return listener[kListener];
2162
+ return null;
2163
+ },
2164
+ set (handler) {
2165
+ for (const listener of this.listeners(method))if (listener[kForOnEventAttribute]) {
2166
+ this.removeListener(method, listener);
2167
+ break;
981
2168
  }
2169
+ if ('function' != typeof handler) return;
2170
+ this.addEventListener(method, handler, {
2171
+ [kForOnEventAttribute]: true
2172
+ });
2173
+ }
2174
+ });
2175
+ });
2176
+ WebSocket.prototype.addEventListener = addEventListener;
2177
+ WebSocket.prototype.removeEventListener = removeEventListener;
2178
+ module.exports = WebSocket;
2179
+ function initAsClient(websocket, address, protocols, options) {
2180
+ const opts = {
2181
+ allowSynchronousEvents: true,
2182
+ autoPong: true,
2183
+ closeTimeout: CLOSE_TIMEOUT,
2184
+ protocolVersion: protocolVersions[1],
2185
+ maxBufferedChunks: 262144,
2186
+ maxFragments: 16384,
2187
+ maxPayload: 104857600,
2188
+ maxPendingAutoPongs: 60,
2189
+ skipUTF8Validation: false,
2190
+ perMessageDeflate: true,
2191
+ followRedirects: false,
2192
+ maxRedirects: 10,
2193
+ ...options,
2194
+ socketPath: void 0,
2195
+ hostname: void 0,
2196
+ protocol: void 0,
2197
+ protocols: void 0,
2198
+ timeout: void 0,
2199
+ method: 'GET',
2200
+ host: void 0,
2201
+ path: void 0,
2202
+ port: void 0
2203
+ };
2204
+ if (!protocolVersions.includes(opts.protocolVersion)) throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(', ')})`);
2205
+ let parsedUrl;
2206
+ if (address instanceof URL) parsedUrl = address;
2207
+ else try {
2208
+ parsedUrl = new URL(address);
2209
+ } catch {
2210
+ throw new SyntaxError(`Invalid URL: ${address}`);
2211
+ }
2212
+ if ('http:' === parsedUrl.protocol || 'https:' === parsedUrl.protocol) {
2213
+ parsedUrl = new URL(parsedUrl);
2214
+ parsedUrl.protocol = 'http:' === parsedUrl.protocol ? 'ws:' : 'wss:';
2215
+ }
2216
+ websocket._url = parsedUrl.href;
2217
+ const isSecure = 'wss:' === parsedUrl.protocol;
2218
+ const isIpcUrl = 'ws+unix:' === parsedUrl.protocol;
2219
+ let invalidUrlMessage;
2220
+ if ('ws:' === parsedUrl.protocol || isSecure || isIpcUrl) {
2221
+ if (isIpcUrl && !parsedUrl.pathname) invalidUrlMessage = "The URL's pathname is empty";
2222
+ else if (parsedUrl.hash) invalidUrlMessage = 'The URL contains a fragment identifier';
2223
+ } else invalidUrlMessage = 'The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"';
2224
+ if (invalidUrlMessage) {
2225
+ const err = new SyntaxError(invalidUrlMessage);
2226
+ if (0 !== websocket._redirects) return void emitErrorAndClose(websocket, err);
2227
+ else throw err;
2228
+ }
2229
+ const defaultPort = isSecure ? 443 : 80;
2230
+ const key = randomBytes(16).toString('base64');
2231
+ const request = isSecure ? https.request : http.request;
2232
+ const protocolSet = new Set();
2233
+ let perMessageDeflate;
2234
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2235
+ opts.defaultPort = opts.defaultPort || defaultPort;
2236
+ opts.port = parsedUrl.port || defaultPort;
2237
+ opts.host = parsedUrl.hostname.startsWith('[') ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2238
+ opts.headers = {
2239
+ ...opts.headers,
2240
+ 'Sec-WebSocket-Version': opts.protocolVersion,
2241
+ 'Sec-WebSocket-Key': key,
2242
+ Connection: 'Upgrade',
2243
+ Upgrade: 'websocket'
2244
+ };
2245
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2246
+ opts.timeout = opts.handshakeTimeout;
2247
+ if (opts.perMessageDeflate) {
2248
+ perMessageDeflate = new PerMessageDeflate({
2249
+ ...opts.perMessageDeflate,
2250
+ isServer: false,
2251
+ maxPayload: opts.maxPayload
2252
+ });
2253
+ opts.headers['Sec-WebSocket-Extensions'] = format({
2254
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
982
2255
  });
983
- } catch (err) {
984
- server_debug("failed to forward message to %s: %O", deviceConn.key, err);
985
- session.close(err);
986
2256
  }
987
- return;
988
- }
989
- server_debug("no matching device connection for client %d, target %o", session.id, targetPort);
990
- }
991
- async #handleControlRequest(session, req) {
992
- const { id, method, params } = req.data;
993
- try {
994
- let result;
995
- let transports;
996
- switch(method){
997
- case "listClients":
998
- {
999
- const clients = await this.#discoverClients();
1000
- result = clients;
1001
- transports = clients.transports;
1002
- break;
2257
+ if (protocols.length) {
2258
+ for (const protocol of protocols){
2259
+ if ('string' != typeof protocol || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) throw new SyntaxError('An invalid or duplicated subprotocol was specified');
2260
+ protocolSet.add(protocol);
2261
+ }
2262
+ opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');
2263
+ }
2264
+ if (opts.origin) if (opts.protocolVersion < 13) opts.headers['Sec-WebSocket-Origin'] = opts.origin;
2265
+ else opts.headers.Origin = opts.origin;
2266
+ if (parsedUrl.username || parsedUrl.password) {
2267
+ const username = querystring.unescape(parsedUrl.username);
2268
+ const password = querystring.unescape(parsedUrl.password);
2269
+ opts.auth = `${username}:${password}`;
2270
+ }
2271
+ if (isIpcUrl) {
2272
+ const i = opts.path.indexOf(':');
2273
+ if (-1 === i) {
2274
+ opts.socketPath = opts.path;
2275
+ opts.path = '';
2276
+ } else {
2277
+ opts.socketPath = opts.path.slice(0, i);
2278
+ opts.path = opts.path.slice(i + 1);
2279
+ }
2280
+ }
2281
+ let req;
2282
+ if (opts.followRedirects) {
2283
+ if (0 === websocket._redirects) {
2284
+ websocket._originalIpc = isIpcUrl;
2285
+ websocket._originalSecure = isSecure;
2286
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2287
+ const headers = options && options.headers;
2288
+ options = {
2289
+ ...options,
2290
+ headers: {}
2291
+ };
2292
+ if (headers) for (const [key, value] of Object.entries(headers))options.headers[key.toLowerCase()] = value;
2293
+ } else if (0 === websocket.listenerCount('redirect')) {
2294
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2295
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2296
+ delete opts.headers.authorization;
2297
+ delete opts.headers.cookie;
2298
+ if (!isSameHost) delete opts.headers.host;
2299
+ opts.auth = void 0;
1003
2300
  }
1004
- case "listDevices":
1005
- {
1006
- const devices = [];
1007
- const allResults = await Promise.allSettled(this.#transports.map((t)=>t.listDevices()));
1008
- for (const r of allResults)if ("fulfilled" === r.status) devices.push(...r.value);
1009
- result = devices;
1010
- break;
2301
+ }
2302
+ if (opts.auth && !options.headers.authorization) options.headers.authorization = 'Basic ' + Buffer.from(opts.auth).toString('base64');
2303
+ req = websocket._req = request(opts);
2304
+ if (websocket._redirects) websocket.emit('redirect', websocket.url, req);
2305
+ } else req = websocket._req = request(opts);
2306
+ if (opts.timeout) req.on('timeout', ()=>{
2307
+ abortHandshake(websocket, req, 'Opening handshake has timed out');
2308
+ });
2309
+ req.on('error', (err)=>{
2310
+ if (null === req || req[kAborted]) return;
2311
+ req = websocket._req = null;
2312
+ emitErrorAndClose(websocket, err);
2313
+ });
2314
+ req.on('response', (res)=>{
2315
+ const location = res.headers.location;
2316
+ const statusCode = res.statusCode;
2317
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2318
+ if (++websocket._redirects > opts.maxRedirects) return void abortHandshake(websocket, req, 'Maximum redirects exceeded');
2319
+ req.abort();
2320
+ let addr;
2321
+ try {
2322
+ addr = new URL(location, address);
2323
+ } catch (e) {
2324
+ const err = new SyntaxError(`Invalid URL: ${location}`);
2325
+ emitErrorAndClose(websocket, err);
2326
+ return;
1011
2327
  }
1012
- case "listAvailableApps":
1013
- {
1014
- const deviceId = params?.deviceId;
1015
- if (!deviceId) throw new Error("deviceId is required");
1016
- const transport = await this.#findTransportWithDeviceId(deviceId);
1017
- result = await transport.listAvailableApps(deviceId);
1018
- break;
2328
+ initAsClient(websocket, addr, protocols, options);
2329
+ } else if (!websocket.emit('unexpected-response', req, res)) abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
2330
+ });
2331
+ req.on('upgrade', (res, socket, head)=>{
2332
+ websocket.emit('upgrade', res);
2333
+ if (websocket.readyState !== WebSocket.CONNECTING) return;
2334
+ req = websocket._req = null;
2335
+ const upgrade = res.headers.upgrade;
2336
+ if (void 0 === upgrade || 'websocket' !== upgrade.toLowerCase()) return void abortHandshake(websocket, socket, 'Invalid Upgrade header');
2337
+ const digest = createHash('sha1').update(key + GUID).digest('base64');
2338
+ if (res.headers['sec-websocket-accept'] !== digest) return void abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
2339
+ const serverProt = res.headers['sec-websocket-protocol'];
2340
+ let protError;
2341
+ if (void 0 !== serverProt) if (protocolSet.size) {
2342
+ if (!protocolSet.has(serverProt)) protError = 'Server sent an invalid subprotocol';
2343
+ } else protError = 'Server sent a subprotocol but none was requested';
2344
+ else if (protocolSet.size) protError = 'Server sent no subprotocol';
2345
+ if (protError) return void abortHandshake(websocket, socket, protError);
2346
+ if (serverProt) websocket._protocol = serverProt;
2347
+ const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
2348
+ if (void 0 !== secWebSocketExtensions) {
2349
+ if (!perMessageDeflate) {
2350
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2351
+ abortHandshake(websocket, socket, message);
2352
+ return;
1019
2353
  }
1020
- case "openApp":
1021
- {
1022
- const p = params ?? {};
1023
- if (!p.deviceId || !p.packageName) throw new Error("deviceId and packageName are required");
1024
- const abortController = new AbortController();
1025
- const removeCloseListener = session.onClose(()=>{
1026
- abortController.abort(new Error(`Daemon client ${session.id} disconnected before openApp completed`));
1027
- });
1028
- try {
1029
- const transport = await this.#findTransportWithDeviceId(p.deviceId);
1030
- abortController.signal.throwIfAborted();
1031
- await transport.openApp(p.deviceId, p.packageName, {
1032
- withDataCleared: p.withDataCleared,
1033
- schema: p.schema,
1034
- restart: p.restart,
1035
- signal: abortController.signal
1036
- });
1037
- } finally{
1038
- removeCloseListener();
1039
- }
1040
- result = null;
1041
- break;
2354
+ let extensions;
2355
+ try {
2356
+ extensions = parse(secWebSocketExtensions);
2357
+ } catch (err) {
2358
+ const message = 'Invalid Sec-WebSocket-Extensions header';
2359
+ abortHandshake(websocket, socket, message);
2360
+ return;
1042
2361
  }
1043
- case "subscribe":
1044
- {
1045
- const s = params ?? {};
1046
- if (!s.transportId || !s.deviceId || void 0 === s.port) throw new Error("transportId, deviceId, and port are required");
1047
- let conn = this.#findActiveDeviceConnection(s.transportId, s.deviceId, s.port);
1048
- if (conn) this.#clearDeviceConnectionCleanup(conn.key);
1049
- else {
1050
- const transport = await this.#findTransportWithDeviceId(s.deviceId, s.transportId);
1051
- conn = await this.#getOrCreateDeviceConnection(transport, s.deviceId, s.port);
1052
- }
1053
- if (session.isClosing || this.#wsClients.get(session.id) !== session) {
1054
- if (0 === conn.subscriberCount) this.#scheduleDeviceConnectionCleanup(conn);
1055
- throw new Error(`Daemon client ${session.id} disconnected before subscription`);
1056
- }
1057
- conn.addSubscriber(session);
1058
- session.subscriptions.add(conn);
1059
- result = null;
1060
- break;
2362
+ const extensionNames = Object.keys(extensions);
2363
+ if (1 !== extensionNames.length || extensionNames[0] !== PerMessageDeflate.extensionName) {
2364
+ const message = 'Server indicated an extension that was not requested';
2365
+ abortHandshake(websocket, socket, message);
2366
+ return;
1061
2367
  }
1062
- default:
1063
- throw new Error(`Unknown control method: ${method}`);
1064
- }
1065
- session.send({
1066
- event: "ControlResponse",
1067
- data: {
1068
- id,
1069
- result,
1070
- ...transports ? {
1071
- transports
1072
- } : {}
1073
- }
1074
- });
1075
- } catch (err) {
1076
- const message = err instanceof Error ? err.message : String(err);
1077
- session.send({
1078
- event: "ControlResponse",
1079
- data: {
1080
- id,
1081
- error: message
2368
+ try {
2369
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2370
+ } catch (err) {
2371
+ const message = 'Invalid Sec-WebSocket-Extensions header';
2372
+ abortHandshake(websocket, socket, message);
2373
+ return;
2374
+ }
2375
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
1082
2376
  }
2377
+ websocket.setSocket(socket, head, {
2378
+ allowSynchronousEvents: opts.allowSynchronousEvents,
2379
+ generateMask: opts.generateMask,
2380
+ maxBufferedChunks: opts.maxBufferedChunks,
2381
+ maxFragments: opts.maxFragments,
2382
+ maxPayload: opts.maxPayload,
2383
+ skipUTF8Validation: opts.skipUTF8Validation
2384
+ });
1083
2385
  });
2386
+ if (opts.finishRequest) opts.finishRequest(req, websocket);
2387
+ else req.end();
2388
+ return opts;
1084
2389
  }
1085
- }
1086
- async #sendClientList(session) {
1087
- try {
1088
- const clients = await this.#discoverClients();
1089
- session.send({
1090
- event: "ClientList",
1091
- data: clients
1092
- });
1093
- } catch (err) {
1094
- server_debug("failed to send client list: %O", err);
1095
- session.send({
1096
- event: "ClientList",
1097
- data: []
1098
- });
2390
+ function emitErrorAndClose(websocket, err) {
2391
+ websocket._readyState = WebSocket.CLOSING;
2392
+ websocket._errorEmitted = true;
2393
+ websocket.emit('error', err);
2394
+ websocket.emitClose();
1099
2395
  }
1100
- }
1101
- async #discoverClients() {
1102
- const entries = [];
1103
- const transports = [];
1104
- const discoveryFailures = [];
1105
- let lowerAuthorityFulfilled = false;
1106
- const hdtClientResults = await Promise.allSettled(this.#hdtTransports.map(async (transport)=>({
1107
- clients: await transport.listClients(),
1108
- id: transport.id
1109
- })));
1110
- const fulfilledHDTClientResults = hdtClientResults.filter((r)=>"fulfilled" === r.status);
1111
- discoveryFailures.push(...hdtClientResults.filter((r)=>"rejected" === r.status).map((r)=>r.reason));
1112
- const hdtClients = fulfilledHDTClientResults.flatMap((r)=>r.value.clients);
1113
- if (fulfilledHDTClientResults.length > 0) {
1114
- server_debug("Using clients from HDT transport: %o", hdtClients);
1115
- return withTransports(hdtClients.map(({ id, info })=>({
1116
- id,
1117
- info,
1118
- type: "runtime"
1119
- })), fulfilledHDTClientResults.map((r)=>r.value.id));
2396
+ function netConnect(options) {
2397
+ options.path = options.socketPath;
2398
+ return net.connect(options);
1120
2399
  }
1121
- if ([
1122
- ...this.#deviceConnections.values()
1123
- ].some((conn)=>conn.transport instanceof HDTTransport && !conn.isDisposed)) throwClientDiscoveryFailures(discoveryFailures);
1124
- const clientListTransports = this.#transports.filter((t)=>!(t instanceof HDTTransport) && "function" == typeof t.listClients);
1125
- const clientListResults = await Promise.allSettled(clientListTransports.map(async (t)=>({
1126
- clients: await t.listClients(),
1127
- id: t.id
1128
- })));
1129
- for (const r of clientListResults)if ("fulfilled" === r.status) {
1130
- lowerAuthorityFulfilled = true;
1131
- transports.push(r.value.id);
1132
- for (const { id, info } of r.value.clients)entries.push({
1133
- id,
1134
- info,
1135
- type: "runtime"
1136
- });
1137
- } else discoveryFailures.push(r.reason);
1138
- for (const [, conn] of this.#deviceConnections)if (conn.appInfo && !conn.isDisposed) {
1139
- const id = ClientId.serialize(conn.transport.id, conn.deviceId, conn.port);
1140
- if (entries.some((e)=>e.id === id)) continue;
1141
- entries.push({
1142
- id,
1143
- info: conn.appInfo,
1144
- type: "runtime"
1145
- });
2400
+ function tlsConnect(options) {
2401
+ options.path = void 0;
2402
+ if (!options.servername && '' !== options.servername) options.servername = net.isIP(options.host) ? '' : options.host;
2403
+ return tls.connect(options);
1146
2404
  }
1147
- const allDevices = [];
1148
- const transportResults = await Promise.allSettled(this.#transports.filter((transport)=>"function" != typeof transport.listClients).map(async (transport)=>({
1149
- transport,
1150
- devices: await transport.listDevices()
1151
- })));
1152
- for (const r of transportResults)if ("fulfilled" === r.status) {
1153
- lowerAuthorityFulfilled = true;
1154
- transports.push(r.value.transport.id);
1155
- allDevices.push(r.value);
1156
- } else discoveryFailures.push(r.reason);
1157
- const MIN_PORT = 8901;
1158
- const PORTS = Array.from({
1159
- length: 10
1160
- }, (_, i)=>MIN_PORT + i);
1161
- const existingKeys = new Set(Array.from(this.#deviceConnections.entries()).filter(([, connection])=>!connection.isDisposed).map(([key])=>key));
1162
- const probeResults = await Promise.allSettled(allDevices.flatMap(({ transport, devices })=>devices.flatMap((device)=>PORTS.filter((port)=>!existingKeys.has(this.#deviceConnectionKey(transport, device.id, port))).map((port)=>this.#getOrCreateDeviceConnection(transport, device.id, port)))));
1163
- for (const r of probeResults)if ("fulfilled" === r.status) {
1164
- const conn = r.value;
1165
- if (conn.appInfo && !conn.isDisposed) {
1166
- const clientId = ClientId.serialize(conn.transport.id, conn.deviceId, conn.port);
1167
- if (!entries.some((e)=>e.id === clientId)) entries.push({
1168
- id: clientId,
1169
- info: conn.appInfo,
1170
- type: "runtime"
1171
- });
2405
+ function abortHandshake(websocket, stream, message) {
2406
+ websocket._readyState = WebSocket.CLOSING;
2407
+ const err = new Error(message);
2408
+ Error.captureStackTrace(err, abortHandshake);
2409
+ if (stream.setHeader) {
2410
+ stream[kAborted] = true;
2411
+ stream.abort();
2412
+ if (stream.socket && !stream.socket.destroyed) stream.socket.destroy();
2413
+ process.nextTick(emitErrorAndClose, websocket, err);
2414
+ } else {
2415
+ stream.destroy(err);
2416
+ stream.once('error', websocket.emit.bind(websocket, 'error'));
2417
+ stream.once('close', websocket.emitClose.bind(websocket));
1172
2418
  }
1173
2419
  }
1174
- if (0 === entries.length && !lowerAuthorityFulfilled && discoveryFailures.length > 0) throwClientDiscoveryFailures(discoveryFailures);
1175
- return withTransports(entries, transports);
1176
- }
1177
- #deviceConnectionKey(transport, deviceId, port) {
1178
- return `${transport.id}:${deviceId}:${port}`;
1179
- }
1180
- #findActiveDeviceConnection(transportId, deviceId, port) {
1181
- const conn = this.#deviceConnections.get(`${transportId}:${deviceId}:${port}`);
1182
- return conn && !conn.isDisposed ? conn : void 0;
1183
- }
1184
- async #getOrCreateDeviceConnection(transport, deviceId, port) {
1185
- const key = this.#deviceConnectionKey(transport, deviceId, port);
1186
- if (this.#closed) throw new Error(`DevTool daemon closed while acquiring device connection ${key}`);
1187
- this.#clearDeviceConnectionCleanup(key);
1188
- const existing = this.#deviceConnections.get(key);
1189
- if (existing && !existing.isDisposed) return existing;
1190
- const pending = this.#pendingDeviceConnections.get(key);
1191
- if (pending) return await pending;
1192
- const connectionPromise = (async ()=>{
1193
- if (existing) {
1194
- await existing.dispose();
1195
- if (this.#deviceConnections.get(key) === existing) this.#deviceConnections.delete(key);
1196
- }
1197
- if (this.#closed) throw new Error(`DevTool daemon closed while acquiring device connection ${key}`);
1198
- const setupAbortController = new AbortController();
1199
- const setupTimeout = setTimeout(()=>{
1200
- setupAbortController.abort(createDeviceConnectionSetupTimeoutError(key));
1201
- }, DEVICE_CONN_SETUP_TIMEOUT_MS);
1202
- const registerAbortController = new AbortController();
1203
- let registerTimeout;
1204
- const conn = new DeviceConnection(transport, {
1205
- deviceId,
1206
- port,
1207
- signal: setupAbortController.signal
1208
- });
1209
- const connectPromise = conn.connect();
1210
- try {
1211
- await withAbortSignal(connectPromise, setupAbortController.signal);
1212
- if (this.#closed) throw new Error(`DevTool daemon closed while acquiring device connection ${key}`);
1213
- await withAbortSignal(conn.send({
1214
- event: "Initialize",
1215
- data: port
1216
- }), setupAbortController.signal);
1217
- if (!(transport instanceof HDTTransport)) {
1218
- clearTimeout(setupTimeout);
1219
- registerTimeout = setTimeout(()=>{
1220
- registerAbortController.abort(createDeviceRegisterTimeoutError(key));
1221
- }, DEVICE_DISCOVERY_TIMEOUT_MS);
1222
- await withAbortSignal(conn.waitUntilRegistered(), registerAbortController.signal);
1223
- if (conn.isDisposed) throw new Error(`Device connection ${key} closed immediately after Register`);
1224
- }
1225
- if (this.#closed) throw new Error(`DevTool daemon closed while acquiring device connection ${key}`);
1226
- this.#deviceConnections.set(key, conn);
1227
- if (0 === conn.subscriberCount) this.#scheduleDeviceConnectionCleanup(conn);
1228
- return conn;
1229
- } catch (err) {
1230
- server_debug("failed to connect to %s: %O", key, err);
1231
- this.#deviceConnections.set(key, conn);
1232
- conn.dispose().catch((disposeError)=>{
1233
- server_debug("failed to dispose device connection %s after setup failure: %O", key, disposeError);
1234
- });
1235
- throw err;
1236
- } finally{
1237
- clearTimeout(setupTimeout);
1238
- if (registerTimeout) clearTimeout(registerTimeout);
2420
+ function sendAfterClose(websocket, data, cb) {
2421
+ if (data) {
2422
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
2423
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
2424
+ else websocket._bufferedAmount += length;
2425
+ }
2426
+ if (cb) {
2427
+ const err = new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);
2428
+ process.nextTick(cb, err);
1239
2429
  }
1240
- })().finally(()=>{
1241
- this.#pendingDeviceConnections.delete(key);
1242
- });
1243
- this.#pendingDeviceConnections.set(key, connectionPromise);
1244
- return await connectionPromise;
1245
- }
1246
- #scheduleDeviceConnectionCleanup(conn) {
1247
- const { key } = conn;
1248
- if (this.#deviceConnections.get(key) !== conn) return void server_debug("skipping cleanup for stale connection %s", key);
1249
- if (conn.isPersistent) {
1250
- this.#clearDeviceConnectionCleanup(key);
1251
- server_debug("skipping cleanup for persistent connection %s", key);
1252
- return;
1253
2430
  }
1254
- server_debug("scheduling cleanup for %s in %dms", key, DEVICE_CONN_GRACE_MS);
1255
- this.#clearDeviceConnectionCleanup(key);
1256
- const timer = setTimeout(()=>{
1257
- this.#deviceConnectionCleanupTimers.delete(key);
1258
- if (this.#deviceConnections.get(key) === conn && 0 === conn.subscriberCount) {
1259
- server_debug("disposing idle device connection %s", key);
1260
- conn.dispose().then(()=>{
1261
- if (this.#deviceConnections.get(key) === conn) this.#deviceConnections.delete(key);
1262
- }, (err)=>{
1263
- server_debug("failed to retire idle device connection %s: %O", key, err);
1264
- });
2431
+ function receiverOnConclude(code, reason) {
2432
+ const websocket = this[kWebSocket];
2433
+ websocket._closeFrameReceived = true;
2434
+ websocket._closeCode = code;
2435
+ if (0 === reason.length) websocket._closeMessage = EMPTY_BUFFER;
2436
+ else {
2437
+ websocket._closeMessage = Buffer.allocUnsafeSlow(reason.length);
2438
+ websocket._closeMessage.set(reason);
1265
2439
  }
1266
- }, DEVICE_CONN_GRACE_MS);
1267
- this.#deviceConnectionCleanupTimers.set(key, timer);
1268
- }
1269
- #clearDeviceConnectionCleanup(key) {
1270
- const timer = this.#deviceConnectionCleanupTimers.get(key);
1271
- if (!timer) return;
1272
- clearTimeout(timer);
1273
- this.#deviceConnectionCleanupTimers.delete(key);
1274
- }
1275
- async #findTransportWithDeviceId(deviceId, transportId) {
1276
- if (void 0 !== transportId) {
1277
- const matchedById = this.#transports.find((t)=>t.id === transportId);
1278
- if (matchedById) return matchedById;
1279
- throw new Error(`Transport with id: ${transportId} not found`);
2440
+ if (void 0 === websocket._socket[kWebSocket]) return;
2441
+ websocket._socket.removeListener('data', socketOnData);
2442
+ process.nextTick(resume, websocket._socket);
2443
+ if (1005 === code) websocket.close();
2444
+ else websocket.close(code, reason);
1280
2445
  }
1281
- for (const transport of this.#transports)try {
1282
- const devices = await transport.listDevices();
1283
- if (devices.some(({ id })=>id === deviceId)) return transport;
1284
- } catch {}
1285
- throw new Error(`Device with id: ${deviceId} not found`);
1286
- }
1287
- #resetIdleTimer() {
1288
- this.#clearIdleTimer();
1289
- if (0 === this.#wsClients.size && 0 === this.#activeCommandRequests && !this.#closed) {
1290
- server_debug("no clients connected, starting idle timer (%dms)", this.#idleTimeoutMs);
1291
- this.#idleTimer = setTimeout(()=>{
1292
- if (0 === this.#wsClients.size && 0 === this.#activeCommandRequests) {
1293
- if (this.#transports.some((transport)=>transport.active)) return void this.#resetIdleTimer();
1294
- server_debug("idle timeout reached, shutting down daemon");
1295
- this.#onIdle?.();
1296
- }
1297
- }, this.#idleTimeoutMs);
2446
+ function receiverOnDrain() {
2447
+ const websocket = this[kWebSocket];
2448
+ if (!websocket.isPaused) websocket._socket.resume();
1298
2449
  }
1299
- }
1300
- #clearIdleTimer() {
1301
- if (this.#idleTimer) {
1302
- clearTimeout(this.#idleTimer);
1303
- this.#idleTimer = null;
2450
+ function receiverOnError(err) {
2451
+ const websocket = this[kWebSocket];
2452
+ if (void 0 !== websocket._socket[kWebSocket]) {
2453
+ websocket._socket.removeListener('data', socketOnData);
2454
+ process.nextTick(resume, websocket._socket);
2455
+ websocket.close(err[kStatusCode]);
2456
+ }
2457
+ if (!websocket._errorEmitted) {
2458
+ websocket._errorEmitted = true;
2459
+ websocket.emit('error', err);
2460
+ }
2461
+ }
2462
+ function receiverOnFinish() {
2463
+ this[kWebSocket].emitClose();
2464
+ }
2465
+ function receiverOnMessage(data, isBinary) {
2466
+ this[kWebSocket].emit('message', data, isBinary);
2467
+ }
2468
+ function receiverOnPing(data) {
2469
+ const websocket = this[kWebSocket];
2470
+ if (websocket._autoPong && websocket.readyState === WebSocket.OPEN) if (websocket._maxPendingAutoPongs > 0 && websocket._pendingAutoPongs >= websocket._maxPendingAutoPongs) websocket.terminate();
2471
+ else {
2472
+ websocket._pendingAutoPongs++;
2473
+ websocket.pong(data, !this._isServer, websocket._autoPongComplete);
2474
+ }
2475
+ websocket.emit('ping', data);
2476
+ }
2477
+ function autoPongComplete(websocket) {
2478
+ websocket._pendingAutoPongs--;
2479
+ }
2480
+ function receiverOnPong(data) {
2481
+ this[kWebSocket].emit('pong', data);
2482
+ }
2483
+ function resume(stream) {
2484
+ stream.resume();
2485
+ }
2486
+ function senderOnError(err) {
2487
+ const websocket = this[kWebSocket];
2488
+ if (websocket.readyState === WebSocket.CLOSED) return;
2489
+ if (websocket.readyState === WebSocket.OPEN) {
2490
+ websocket._readyState = WebSocket.CLOSING;
2491
+ setCloseTimer(websocket);
2492
+ }
2493
+ this._socket.end();
2494
+ if (!websocket._errorEmitted) {
2495
+ websocket._errorEmitted = true;
2496
+ websocket.emit('error', err);
2497
+ }
2498
+ }
2499
+ function setCloseTimer(websocket) {
2500
+ websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout);
2501
+ }
2502
+ function socketOnClose() {
2503
+ const websocket = this[kWebSocket];
2504
+ this.removeListener('close', socketOnClose);
2505
+ this.removeListener('data', socketOnData);
2506
+ this.removeListener('end', socketOnEnd);
2507
+ websocket._readyState = WebSocket.CLOSING;
2508
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && 0 !== this._readableState.length) {
2509
+ const chunk = this.read(this._readableState.length);
2510
+ websocket._receiver.write(chunk);
2511
+ }
2512
+ websocket._receiver.end();
2513
+ this[kWebSocket] = void 0;
2514
+ clearTimeout(websocket._closeTimer);
2515
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) websocket.emitClose();
2516
+ else {
2517
+ websocket._receiver.on('error', receiverOnFinish);
2518
+ websocket._receiver.on('finish', receiverOnFinish);
2519
+ }
2520
+ }
2521
+ function socketOnData(chunk) {
2522
+ if (!this[kWebSocket]._receiver.write(chunk)) this.pause();
2523
+ }
2524
+ function socketOnEnd() {
2525
+ const websocket = this[kWebSocket];
2526
+ websocket._readyState = WebSocket.CLOSING;
2527
+ websocket._receiver.end();
2528
+ this.end();
2529
+ }
2530
+ function socketOnError() {
2531
+ const websocket = this[kWebSocket];
2532
+ this.removeListener('error', socketOnError);
2533
+ this.on('error', NOOP);
2534
+ if (websocket) {
2535
+ websocket._readyState = WebSocket.CLOSING;
2536
+ this.destroy();
2537
+ }
1304
2538
  }
1305
2539
  }
1306
- }
1307
- function websocketCloseReason(cause) {
1308
- let summary;
1309
- if (cause instanceof Error) {
1310
- const code = cause.code;
1311
- const codeText = "string" == typeof code || "number" == typeof code ? ` (${code})` : "";
1312
- summary = `${cause.name}${codeText}: ${cause.message}`;
1313
- } else summary = String(cause);
1314
- const truncated = Buffer.byteLength(summary) > 123;
1315
- const suffix = truncated ? "…" : "";
1316
- const maxBytes = 123 - Buffer.byteLength(suffix);
1317
- let reason = "";
1318
- let byteLength = 0;
1319
- for (const character of summary){
1320
- const characterBytes = Buffer.byteLength(character);
1321
- if (byteLength + characterBytes > maxBytes) break;
1322
- reason += character;
1323
- byteLength += characterBytes;
1324
- }
1325
- return reason + suffix;
1326
- }
1327
- function createDeviceConnectionSetupTimeoutError(key) {
1328
- return new Error(`Timed out setting up device connection ${key} after ${DEVICE_CONN_SETUP_TIMEOUT_MS}ms`);
1329
- }
1330
- function createDeviceRegisterTimeoutError(key) {
1331
- return new Error(`Timed out waiting for Register from device connection ${key} after ${DEVICE_DISCOVERY_TIMEOUT_MS}ms`);
1332
- }
1333
- async function withAbortSignal(promise, signal) {
1334
- signal.throwIfAborted();
1335
- return await new Promise((resolve, reject)=>{
1336
- const abortHandler = ()=>{
1337
- reject(signal.reason ?? new Error("The operation was aborted"));
1338
- };
1339
- signal.addEventListener("abort", abortHandler, {
1340
- once: true
1341
- });
1342
- promise.then((value)=>{
1343
- signal.removeEventListener("abort", abortHandler);
1344
- resolve(value);
1345
- }, (error)=>{
1346
- signal.removeEventListener("abort", abortHandler);
1347
- reject(error);
1348
- });
1349
- });
1350
- }
1351
- export { DeviceConnection, DevtoolDaemon, HDT_RES_PATH_PREFIX, InspectorAssets, StaticServer, TarballCache };
2540
+ });
2541
+ __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/stream.js");
2542
+ __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/extension.js");
2543
+ __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/permessage-deflate.js");
2544
+ __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/receiver.js");
2545
+ __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/sender.js");
2546
+ __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/subprotocol.js");
2547
+ __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/websocket.js");
2548
+ __webpack_require__("../../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/websocket-server.js");