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