openclaw-overlay-plugin 0.8.16 → 0.8.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/src/cli.js CHANGED
@@ -1,42 +1,13 @@
1
1
  #!/usr/bin/env node
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
3
  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
- });
14
4
  var __esm = (fn, res) => function __init() {
15
5
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
16
6
  };
17
- var __commonJS = (cb, mod) => function __require2() {
18
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
- };
20
7
  var __export = (target, all) => {
21
8
  for (var name in all)
22
9
  __defProp(target, name, { get: all[name], enumerable: true });
23
10
  };
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
11
 
41
12
  // src/scripts/output.ts
42
13
  function ok(data) {
@@ -2861,3780 +2832,136 @@ var init_poll = __esm({
2861
2832
  }
2862
2833
  });
2863
2834
 
2864
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/constants.js
2865
- var require_constants = __commonJS({
2866
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/constants.js"(exports, module) {
2867
- "use strict";
2868
- var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
2869
- var hasBlob = typeof Blob !== "undefined";
2870
- if (hasBlob) BINARY_TYPES.push("blob");
2871
- module.exports = {
2872
- BINARY_TYPES,
2873
- CLOSE_TIMEOUT: 3e4,
2874
- EMPTY_BUFFER: Buffer.alloc(0),
2875
- GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
2876
- hasBlob,
2877
- kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
2878
- kListener: /* @__PURE__ */ Symbol("kListener"),
2879
- kStatusCode: /* @__PURE__ */ Symbol("status-code"),
2880
- kWebSocket: /* @__PURE__ */ Symbol("websocket"),
2881
- NOOP: () => {
2882
- }
2883
- };
2835
+ // src/scripts/messaging/connect.ts
2836
+ import fs10 from "node:fs";
2837
+ import debug2 from "debug";
2838
+ async function cmdConnect(onMessage, signal) {
2839
+ let WebSocketClient;
2840
+ try {
2841
+ const ws = await import("ws");
2842
+ WebSocketClient = ws.default || ws.WebSocket || ws;
2843
+ } catch {
2844
+ return fail("WebSocket client not available. Install it: npm install ws");
2884
2845
  }
2885
- });
2886
-
2887
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/buffer-util.js
2888
- var require_buffer_util = __commonJS({
2889
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/buffer-util.js"(exports, module) {
2890
- "use strict";
2891
- var { EMPTY_BUFFER } = require_constants();
2892
- var FastBuffer = Buffer[Symbol.species];
2893
- function concat(list, totalLength) {
2894
- if (list.length === 0) return EMPTY_BUFFER;
2895
- if (list.length === 1) return list[0];
2896
- const target = Buffer.allocUnsafe(totalLength);
2897
- let offset = 0;
2898
- for (let i = 0; i < list.length; i++) {
2899
- const buf = list[i];
2900
- target.set(buf, offset);
2901
- offset += buf.length;
2902
- }
2903
- if (offset < totalLength) {
2904
- return new FastBuffer(target.buffer, target.byteOffset, offset);
2905
- }
2906
- return target;
2907
- }
2908
- function _mask(source, mask, output, offset, length) {
2909
- for (let i = 0; i < length; i++) {
2910
- output[offset + i] = source[i] ^ mask[i & 3];
2911
- }
2912
- }
2913
- function _unmask(buffer, mask) {
2914
- for (let i = 0; i < buffer.length; i++) {
2915
- buffer[i] ^= mask[i & 3];
2916
- }
2917
- }
2918
- function toArrayBuffer(buf) {
2919
- if (buf.length === buf.buffer.byteLength) {
2920
- return buf.buffer;
2921
- }
2922
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
2923
- }
2924
- function toBuffer(data) {
2925
- toBuffer.readOnly = true;
2926
- if (Buffer.isBuffer(data)) return data;
2927
- let buf;
2928
- if (data instanceof ArrayBuffer) {
2929
- buf = new FastBuffer(data);
2930
- } else if (ArrayBuffer.isView(data)) {
2931
- buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
2932
- } else {
2933
- buf = Buffer.from(data);
2934
- toBuffer.readOnly = false;
2935
- }
2936
- return buf;
2937
- }
2938
- module.exports = {
2939
- concat,
2940
- mask: _mask,
2941
- toArrayBuffer,
2942
- toBuffer,
2943
- unmask: _unmask
2944
- };
2945
- if (!process.env.WS_NO_BUFFER_UTIL) {
2846
+ const { identityKey, privKey } = await loadIdentity();
2847
+ const wsUrl = OVERLAY_URL.replace(/^http/, "ws") + "/relay/subscribe?identity=" + identityKey;
2848
+ log2("Connecting to WebSocket relay: %s", wsUrl);
2849
+ let reconnectDelay = 1e3;
2850
+ let shouldReconnect = true;
2851
+ let currentWs = null;
2852
+ function shutdown() {
2853
+ shouldReconnect = false;
2854
+ if (currentWs) {
2946
2855
  try {
2947
- const bufferUtil = __require("bufferutil");
2948
- module.exports.mask = function(source, mask, output, offset, length) {
2949
- if (length < 48) _mask(source, mask, output, offset, length);
2950
- else bufferUtil.mask(source, mask, output, offset, length);
2951
- };
2952
- module.exports.unmask = function(buffer, mask) {
2953
- if (buffer.length < 32) _unmask(buffer, mask);
2954
- else bufferUtil.unmask(buffer, mask);
2955
- };
2956
- } catch (e) {
2856
+ currentWs.close();
2857
+ } catch {
2957
2858
  }
2958
2859
  }
2860
+ if (!onMessage) {
2861
+ process.exit(0);
2862
+ }
2959
2863
  }
2960
- });
2961
-
2962
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/limiter.js
2963
- var require_limiter = __commonJS({
2964
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/limiter.js"(exports, module) {
2965
- "use strict";
2966
- var kDone = /* @__PURE__ */ Symbol("kDone");
2967
- var kRun = /* @__PURE__ */ Symbol("kRun");
2968
- var Limiter = class {
2969
- /**
2970
- * Creates a new `Limiter`.
2971
- *
2972
- * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
2973
- * to run concurrently
2974
- */
2975
- constructor(concurrency) {
2976
- this[kDone] = () => {
2977
- this.pending--;
2978
- this[kRun]();
2979
- };
2980
- this.concurrency = concurrency || Infinity;
2981
- this.jobs = [];
2982
- this.pending = 0;
2983
- }
2984
- /**
2985
- * Adds a job to the queue.
2986
- *
2987
- * @param {Function} job The job to run
2988
- * @public
2989
- */
2990
- add(job) {
2991
- this.jobs.push(job);
2992
- this[kRun]();
2993
- }
2994
- /**
2995
- * Removes a job from the queue and runs it if possible.
2996
- *
2997
- * @private
2998
- */
2999
- [kRun]() {
3000
- if (this.pending === this.concurrency) return;
3001
- if (this.jobs.length) {
3002
- const job = this.jobs.shift();
3003
- this.pending++;
3004
- job(this[kDone]);
3005
- }
3006
- }
3007
- };
3008
- module.exports = Limiter;
2864
+ if (!onMessage) {
2865
+ process.on("SIGINT", shutdown);
2866
+ process.on("SIGTERM", shutdown);
3009
2867
  }
3010
- });
3011
-
3012
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/permessage-deflate.js
3013
- var require_permessage_deflate = __commonJS({
3014
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/permessage-deflate.js"(exports, module) {
3015
- "use strict";
3016
- var zlib = __require("zlib");
3017
- var bufferUtil = require_buffer_util();
3018
- var Limiter = require_limiter();
3019
- var { kStatusCode } = require_constants();
3020
- var FastBuffer = Buffer[Symbol.species];
3021
- var TRAILER = Buffer.from([0, 0, 255, 255]);
3022
- var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
3023
- var kTotalLength = /* @__PURE__ */ Symbol("total-length");
3024
- var kCallback = /* @__PURE__ */ Symbol("callback");
3025
- var kBuffers = /* @__PURE__ */ Symbol("buffers");
3026
- var kError = /* @__PURE__ */ Symbol("error");
3027
- var zlibLimiter;
3028
- var PerMessageDeflate2 = class {
3029
- /**
3030
- * Creates a PerMessageDeflate instance.
3031
- *
3032
- * @param {Object} [options] Configuration options
3033
- * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
3034
- * for, or request, a custom client window size
3035
- * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
3036
- * acknowledge disabling of client context takeover
3037
- * @param {Number} [options.concurrencyLimit=10] The number of concurrent
3038
- * calls to zlib
3039
- * @param {Boolean} [options.isServer=false] Create the instance in either
3040
- * server or client mode
3041
- * @param {Number} [options.maxPayload=0] The maximum allowed message length
3042
- * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
3043
- * use of a custom server window size
3044
- * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
3045
- * disabling of server context takeover
3046
- * @param {Number} [options.threshold=1024] Size (in bytes) below which
3047
- * messages should not be compressed if context takeover is disabled
3048
- * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
3049
- * deflate
3050
- * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
3051
- * inflate
3052
- */
3053
- constructor(options) {
3054
- this._options = options || {};
3055
- this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
3056
- this._maxPayload = this._options.maxPayload | 0;
3057
- this._isServer = !!this._options.isServer;
3058
- this._deflate = null;
3059
- this._inflate = null;
3060
- this.params = null;
3061
- if (!zlibLimiter) {
3062
- const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
3063
- zlibLimiter = new Limiter(concurrency);
3064
- }
3065
- }
3066
- /**
3067
- * @type {String}
3068
- */
3069
- static get extensionName() {
3070
- return "permessage-deflate";
3071
- }
3072
- /**
3073
- * Create an extension negotiation offer.
3074
- *
3075
- * @return {Object} Extension parameters
3076
- * @public
3077
- */
3078
- offer() {
3079
- const params = {};
3080
- if (this._options.serverNoContextTakeover) {
3081
- params.server_no_context_takeover = true;
3082
- }
3083
- if (this._options.clientNoContextTakeover) {
3084
- params.client_no_context_takeover = true;
3085
- }
3086
- if (this._options.serverMaxWindowBits) {
3087
- params.server_max_window_bits = this._options.serverMaxWindowBits;
3088
- }
3089
- if (this._options.clientMaxWindowBits) {
3090
- params.client_max_window_bits = this._options.clientMaxWindowBits;
3091
- } else if (this._options.clientMaxWindowBits == null) {
3092
- params.client_max_window_bits = true;
3093
- }
3094
- return params;
3095
- }
3096
- /**
3097
- * Accept an extension negotiation offer/response.
3098
- *
3099
- * @param {Array} configurations The extension negotiation offers/reponse
3100
- * @return {Object} Accepted configuration
3101
- * @public
3102
- */
3103
- accept(configurations) {
3104
- configurations = this.normalizeParams(configurations);
3105
- this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
3106
- return this.params;
3107
- }
3108
- /**
3109
- * Releases all resources used by the extension.
3110
- *
3111
- * @public
3112
- */
3113
- cleanup() {
3114
- if (this._inflate) {
3115
- this._inflate.close();
3116
- this._inflate = null;
3117
- }
3118
- if (this._deflate) {
3119
- const callback = this._deflate[kCallback];
3120
- this._deflate.close();
3121
- this._deflate = null;
3122
- if (callback) {
3123
- callback(
3124
- new Error(
3125
- "The deflate stream was closed while data was being processed"
3126
- )
3127
- );
3128
- }
3129
- }
3130
- }
3131
- /**
3132
- * Accept an extension negotiation offer.
3133
- *
3134
- * @param {Array} offers The extension negotiation offers
3135
- * @return {Object} Accepted configuration
3136
- * @private
3137
- */
3138
- acceptAsServer(offers) {
3139
- const opts = this._options;
3140
- const accepted = offers.find((params) => {
3141
- if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
3142
- return false;
3143
- }
3144
- return true;
3145
- });
3146
- if (!accepted) {
3147
- throw new Error("None of the extension offers can be accepted");
3148
- }
3149
- if (opts.serverNoContextTakeover) {
3150
- accepted.server_no_context_takeover = true;
3151
- }
3152
- if (opts.clientNoContextTakeover) {
3153
- accepted.client_no_context_takeover = true;
3154
- }
3155
- if (typeof opts.serverMaxWindowBits === "number") {
3156
- accepted.server_max_window_bits = opts.serverMaxWindowBits;
3157
- }
3158
- if (typeof opts.clientMaxWindowBits === "number") {
3159
- accepted.client_max_window_bits = opts.clientMaxWindowBits;
3160
- } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
3161
- delete accepted.client_max_window_bits;
3162
- }
3163
- return accepted;
3164
- }
3165
- /**
3166
- * Accept the extension negotiation response.
3167
- *
3168
- * @param {Array} response The extension negotiation response
3169
- * @return {Object} Accepted configuration
3170
- * @private
3171
- */
3172
- acceptAsClient(response) {
3173
- const params = response[0];
3174
- if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
3175
- throw new Error('Unexpected parameter "client_no_context_takeover"');
3176
- }
3177
- if (!params.client_max_window_bits) {
3178
- if (typeof this._options.clientMaxWindowBits === "number") {
3179
- params.client_max_window_bits = this._options.clientMaxWindowBits;
3180
- }
3181
- } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
3182
- throw new Error(
3183
- 'Unexpected or invalid parameter "client_max_window_bits"'
3184
- );
2868
+ if (signal) {
2869
+ signal.addEventListener("abort", () => {
2870
+ shouldReconnect = false;
2871
+ if (currentWs) {
2872
+ try {
2873
+ currentWs.close();
2874
+ } catch {
3185
2875
  }
3186
- return params;
3187
- }
3188
- /**
3189
- * Normalize parameters.
3190
- *
3191
- * @param {Array} configurations The extension negotiation offers/reponse
3192
- * @return {Array} The offers/response with normalized parameters
3193
- * @private
3194
- */
3195
- normalizeParams(configurations) {
3196
- configurations.forEach((params) => {
3197
- Object.keys(params).forEach((key) => {
3198
- let value = params[key];
3199
- if (value.length > 1) {
3200
- throw new Error(`Parameter "${key}" must have only a single value`);
3201
- }
3202
- value = value[0];
3203
- if (key === "client_max_window_bits") {
3204
- if (value !== true) {
3205
- const num = +value;
3206
- if (!Number.isInteger(num) || num < 8 || num > 15) {
3207
- throw new TypeError(
3208
- `Invalid value for parameter "${key}": ${value}`
3209
- );
3210
- }
3211
- value = num;
3212
- } else if (!this._isServer) {
3213
- throw new TypeError(
3214
- `Invalid value for parameter "${key}": ${value}`
3215
- );
3216
- }
3217
- } else if (key === "server_max_window_bits") {
3218
- const num = +value;
3219
- if (!Number.isInteger(num) || num < 8 || num > 15) {
3220
- throw new TypeError(
3221
- `Invalid value for parameter "${key}": ${value}`
3222
- );
3223
- }
3224
- value = num;
3225
- } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
3226
- if (value !== true) {
3227
- throw new TypeError(
3228
- `Invalid value for parameter "${key}": ${value}`
3229
- );
3230
- }
3231
- } else {
3232
- throw new Error(`Unknown parameter "${key}"`);
3233
- }
3234
- params[key] = value;
3235
- });
3236
- });
3237
- return configurations;
3238
- }
3239
- /**
3240
- * Decompress data. Concurrency limited.
3241
- *
3242
- * @param {Buffer} data Compressed data
3243
- * @param {Boolean} fin Specifies whether or not this is the last fragment
3244
- * @param {Function} callback Callback
3245
- * @public
3246
- */
3247
- decompress(data, fin, callback) {
3248
- zlibLimiter.add((done) => {
3249
- this._decompress(data, fin, (err, result) => {
3250
- done();
3251
- callback(err, result);
3252
- });
3253
- });
3254
- }
3255
- /**
3256
- * Compress data. Concurrency limited.
3257
- *
3258
- * @param {(Buffer|String)} data Data to compress
3259
- * @param {Boolean} fin Specifies whether or not this is the last fragment
3260
- * @param {Function} callback Callback
3261
- * @public
3262
- */
3263
- compress(data, fin, callback) {
3264
- zlibLimiter.add((done) => {
3265
- this._compress(data, fin, (err, result) => {
3266
- done();
3267
- callback(err, result);
3268
- });
3269
- });
3270
2876
  }
3271
- /**
3272
- * Decompress data.
3273
- *
3274
- * @param {Buffer} data Compressed data
3275
- * @param {Boolean} fin Specifies whether or not this is the last fragment
3276
- * @param {Function} callback Callback
3277
- * @private
3278
- */
3279
- _decompress(data, fin, callback) {
3280
- const endpoint = this._isServer ? "client" : "server";
3281
- if (!this._inflate) {
3282
- const key = `${endpoint}_max_window_bits`;
3283
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
3284
- this._inflate = zlib.createInflateRaw({
3285
- ...this._options.zlibInflateOptions,
3286
- windowBits
3287
- });
3288
- this._inflate[kPerMessageDeflate] = this;
3289
- this._inflate[kTotalLength] = 0;
3290
- this._inflate[kBuffers] = [];
3291
- this._inflate.on("error", inflateOnError);
3292
- this._inflate.on("data", inflateOnData);
3293
- }
3294
- this._inflate[kCallback] = callback;
3295
- this._inflate.write(data);
3296
- if (fin) this._inflate.write(TRAILER);
3297
- this._inflate.flush(() => {
3298
- const err = this._inflate[kError];
3299
- if (err) {
3300
- this._inflate.close();
3301
- this._inflate = null;
3302
- callback(err);
3303
- return;
2877
+ });
2878
+ }
2879
+ function connect() {
2880
+ if (signal?.aborted) return;
2881
+ const ws = new WebSocketClient(wsUrl);
2882
+ currentWs = ws;
2883
+ ws.on("open", () => {
2884
+ log2("WebSocket connection established!");
2885
+ reconnectDelay = 1e3;
2886
+ const logMsg = { event: "connected", identity: identityKey, overlay: OVERLAY_URL };
2887
+ if (onMessage) onMessage(logMsg);
2888
+ else console.error(JSON.stringify(logMsg));
2889
+ });
2890
+ ws.on("message", async (data) => {
2891
+ log2("Incoming WebSocket message received");
2892
+ try {
2893
+ const envelope = JSON.parse(data.toString());
2894
+ log2("Message type: %s", envelope.type);
2895
+ if (envelope.type === "message") {
2896
+ const result = await processMessage(envelope.message, identityKey, privKey);
2897
+ log2("Processed message: %s", result.id);
2898
+ if (onMessage) onMessage(result);
2899
+ else console.log(JSON.stringify(result));
2900
+ ensureStateDir();
2901
+ try {
2902
+ fs10.appendFileSync(PATHS.notifications, JSON.stringify({ ...result, _ts: Date.now() }) + "\n");
2903
+ } catch {
3304
2904
  }
3305
- const data2 = bufferUtil.concat(
3306
- this._inflate[kBuffers],
3307
- this._inflate[kTotalLength]
3308
- );
3309
- if (this._inflate._readableState.endEmitted) {
3310
- this._inflate.close();
3311
- this._inflate = null;
3312
- } else {
3313
- this._inflate[kTotalLength] = 0;
3314
- this._inflate[kBuffers] = [];
3315
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
3316
- this._inflate.reset();
2905
+ if (result.ack) {
2906
+ try {
2907
+ await fetch(OVERLAY_URL + "/relay/ack", {
2908
+ method: "POST",
2909
+ headers: { "Content-Type": "application/json" },
2910
+ body: JSON.stringify({ identity: identityKey, messageIds: [result.id] })
2911
+ });
2912
+ } catch (ackErr) {
2913
+ const log3 = { event: "ack-error", id: result.id, message: String(ackErr) };
2914
+ if (onMessage) onMessage(log3);
2915
+ else console.error(JSON.stringify(log3));
3317
2916
  }
3318
2917
  }
3319
- callback(null, data2);
3320
- });
3321
- }
3322
- /**
3323
- * Compress data.
3324
- *
3325
- * @param {(Buffer|String)} data Data to compress
3326
- * @param {Boolean} fin Specifies whether or not this is the last fragment
3327
- * @param {Function} callback Callback
3328
- * @private
3329
- */
3330
- _compress(data, fin, callback) {
3331
- const endpoint = this._isServer ? "server" : "client";
3332
- if (!this._deflate) {
3333
- const key = `${endpoint}_max_window_bits`;
3334
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
3335
- this._deflate = zlib.createDeflateRaw({
3336
- ...this._options.zlibDeflateOptions,
3337
- windowBits
3338
- });
3339
- this._deflate[kTotalLength] = 0;
3340
- this._deflate[kBuffers] = [];
3341
- this._deflate.on("data", deflateOnData);
3342
2918
  }
3343
- this._deflate[kCallback] = callback;
3344
- this._deflate.write(data);
3345
- this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
3346
- if (!this._deflate) {
3347
- return;
3348
- }
3349
- let data2 = bufferUtil.concat(
3350
- this._deflate[kBuffers],
3351
- this._deflate[kTotalLength]
3352
- );
3353
- if (fin) {
3354
- data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
3355
- }
3356
- this._deflate[kCallback] = null;
3357
- this._deflate[kTotalLength] = 0;
3358
- this._deflate[kBuffers] = [];
3359
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
3360
- this._deflate.reset();
2919
+ if (envelope.type === "service-announced") {
2920
+ const svc = envelope.service || {};
2921
+ const announcement = {
2922
+ event: "service-announced",
2923
+ serviceId: svc.serviceId,
2924
+ name: svc.name,
2925
+ description: svc.description,
2926
+ priceSats: svc.pricingSats,
2927
+ provider: svc.identityKey,
2928
+ txid: envelope.txid,
2929
+ _ts: Date.now()
2930
+ };
2931
+ if (onMessage) onMessage(announcement);
2932
+ else console.log(JSON.stringify(announcement));
2933
+ ensureStateDir();
2934
+ try {
2935
+ fs10.appendFileSync(PATHS.notifications, JSON.stringify(announcement) + "\n");
2936
+ } catch {
3361
2937
  }
3362
- callback(null, data2);
3363
- });
3364
- }
3365
- };
3366
- module.exports = PerMessageDeflate2;
3367
- function deflateOnData(chunk) {
3368
- this[kBuffers].push(chunk);
3369
- this[kTotalLength] += chunk.length;
3370
- }
3371
- function inflateOnData(chunk) {
3372
- this[kTotalLength] += chunk.length;
3373
- if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
3374
- this[kBuffers].push(chunk);
3375
- return;
2938
+ }
2939
+ } catch (err) {
2940
+ const log3 = { event: "process-error", message: String(err) };
2941
+ if (onMessage) onMessage(log3);
2942
+ else console.error(JSON.stringify(log3));
3376
2943
  }
3377
- this[kError] = new RangeError("Max payload size exceeded");
3378
- this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
3379
- this[kError][kStatusCode] = 1009;
3380
- this.removeListener("data", inflateOnData);
3381
- this.reset();
3382
- }
3383
- function inflateOnError(err) {
3384
- this[kPerMessageDeflate]._inflate = null;
3385
- if (this[kError]) {
3386
- this[kCallback](this[kError]);
3387
- return;
2944
+ });
2945
+ ws.on("close", () => {
2946
+ currentWs = null;
2947
+ if (shouldReconnect && !signal?.aborted) {
2948
+ const log3 = { event: "disconnected", reconnectMs: reconnectDelay };
2949
+ if (onMessage) onMessage(log3);
2950
+ else console.error(JSON.stringify(log3));
2951
+ setTimeout(connect, reconnectDelay);
2952
+ reconnectDelay = Math.min(reconnectDelay * 2, 3e4);
3388
2953
  }
3389
- err[kStatusCode] = 1007;
3390
- this[kCallback](err);
3391
- }
2954
+ });
2955
+ ws.on("error", (err) => {
2956
+ const log3 = { event: "error", message: err.message };
2957
+ if (onMessage) onMessage(log3);
2958
+ else console.error(JSON.stringify(log3));
2959
+ });
3392
2960
  }
3393
- });
3394
-
3395
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/validation.js
3396
- var require_validation = __commonJS({
3397
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/validation.js"(exports, module) {
3398
- "use strict";
3399
- var { isUtf8 } = __require("buffer");
3400
- var { hasBlob } = require_constants();
3401
- var tokenChars = [
3402
- 0,
3403
- 0,
3404
- 0,
3405
- 0,
3406
- 0,
3407
- 0,
3408
- 0,
3409
- 0,
3410
- 0,
3411
- 0,
3412
- 0,
3413
- 0,
3414
- 0,
3415
- 0,
3416
- 0,
3417
- 0,
3418
- // 0 - 15
3419
- 0,
3420
- 0,
3421
- 0,
3422
- 0,
3423
- 0,
3424
- 0,
3425
- 0,
3426
- 0,
3427
- 0,
3428
- 0,
3429
- 0,
3430
- 0,
3431
- 0,
3432
- 0,
3433
- 0,
3434
- 0,
3435
- // 16 - 31
3436
- 0,
3437
- 1,
3438
- 0,
3439
- 1,
3440
- 1,
3441
- 1,
3442
- 1,
3443
- 1,
3444
- 0,
3445
- 0,
3446
- 1,
3447
- 1,
3448
- 0,
3449
- 1,
3450
- 1,
3451
- 0,
3452
- // 32 - 47
3453
- 1,
3454
- 1,
3455
- 1,
3456
- 1,
3457
- 1,
3458
- 1,
3459
- 1,
3460
- 1,
3461
- 1,
3462
- 1,
3463
- 0,
3464
- 0,
3465
- 0,
3466
- 0,
3467
- 0,
3468
- 0,
3469
- // 48 - 63
3470
- 0,
3471
- 1,
3472
- 1,
3473
- 1,
3474
- 1,
3475
- 1,
3476
- 1,
3477
- 1,
3478
- 1,
3479
- 1,
3480
- 1,
3481
- 1,
3482
- 1,
3483
- 1,
3484
- 1,
3485
- 1,
3486
- // 64 - 79
3487
- 1,
3488
- 1,
3489
- 1,
3490
- 1,
3491
- 1,
3492
- 1,
3493
- 1,
3494
- 1,
3495
- 1,
3496
- 1,
3497
- 1,
3498
- 0,
3499
- 0,
3500
- 0,
3501
- 1,
3502
- 1,
3503
- // 80 - 95
3504
- 1,
3505
- 1,
3506
- 1,
3507
- 1,
3508
- 1,
3509
- 1,
3510
- 1,
3511
- 1,
3512
- 1,
3513
- 1,
3514
- 1,
3515
- 1,
3516
- 1,
3517
- 1,
3518
- 1,
3519
- 1,
3520
- // 96 - 111
3521
- 1,
3522
- 1,
3523
- 1,
3524
- 1,
3525
- 1,
3526
- 1,
3527
- 1,
3528
- 1,
3529
- 1,
3530
- 1,
3531
- 1,
3532
- 0,
3533
- 1,
3534
- 0,
3535
- 1,
3536
- 0
3537
- // 112 - 127
3538
- ];
3539
- function isValidStatusCode(code) {
3540
- return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
3541
- }
3542
- function _isValidUTF8(buf) {
3543
- const len = buf.length;
3544
- let i = 0;
3545
- while (i < len) {
3546
- if ((buf[i] & 128) === 0) {
3547
- i++;
3548
- } else if ((buf[i] & 224) === 192) {
3549
- if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
3550
- return false;
3551
- }
3552
- i += 2;
3553
- } else if ((buf[i] & 240) === 224) {
3554
- if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
3555
- buf[i] === 237 && (buf[i + 1] & 224) === 160) {
3556
- return false;
3557
- }
3558
- i += 3;
3559
- } else if ((buf[i] & 248) === 240) {
3560
- 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
3561
- buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
3562
- return false;
3563
- }
3564
- i += 4;
3565
- } else {
3566
- return false;
3567
- }
3568
- }
3569
- return true;
3570
- }
3571
- function isBlob(value) {
3572
- 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");
3573
- }
3574
- module.exports = {
3575
- isBlob,
3576
- isValidStatusCode,
3577
- isValidUTF8: _isValidUTF8,
3578
- tokenChars
3579
- };
3580
- if (isUtf8) {
3581
- module.exports.isValidUTF8 = function(buf) {
3582
- return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
3583
- };
3584
- } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
3585
- try {
3586
- const isValidUTF8 = __require("utf-8-validate");
3587
- module.exports.isValidUTF8 = function(buf) {
3588
- return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
3589
- };
3590
- } catch (e) {
3591
- }
3592
- }
3593
- }
3594
- });
3595
-
3596
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/receiver.js
3597
- var require_receiver = __commonJS({
3598
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/receiver.js"(exports, module) {
3599
- "use strict";
3600
- var { Writable } = __require("stream");
3601
- var PerMessageDeflate2 = require_permessage_deflate();
3602
- var {
3603
- BINARY_TYPES,
3604
- EMPTY_BUFFER,
3605
- kStatusCode,
3606
- kWebSocket
3607
- } = require_constants();
3608
- var { concat, toArrayBuffer, unmask } = require_buffer_util();
3609
- var { isValidStatusCode, isValidUTF8 } = require_validation();
3610
- var FastBuffer = Buffer[Symbol.species];
3611
- var GET_INFO = 0;
3612
- var GET_PAYLOAD_LENGTH_16 = 1;
3613
- var GET_PAYLOAD_LENGTH_64 = 2;
3614
- var GET_MASK = 3;
3615
- var GET_DATA = 4;
3616
- var INFLATING = 5;
3617
- var DEFER_EVENT = 6;
3618
- var Receiver2 = class extends Writable {
3619
- /**
3620
- * Creates a Receiver instance.
3621
- *
3622
- * @param {Object} [options] Options object
3623
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3624
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3625
- * multiple times in the same tick
3626
- * @param {String} [options.binaryType=nodebuffer] The type for binary data
3627
- * @param {Object} [options.extensions] An object containing the negotiated
3628
- * extensions
3629
- * @param {Boolean} [options.isServer=false] Specifies whether to operate in
3630
- * client or server mode
3631
- * @param {Number} [options.maxPayload=0] The maximum allowed message length
3632
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3633
- * not to skip UTF-8 validation for text and close messages
3634
- */
3635
- constructor(options = {}) {
3636
- super();
3637
- this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
3638
- this._binaryType = options.binaryType || BINARY_TYPES[0];
3639
- this._extensions = options.extensions || {};
3640
- this._isServer = !!options.isServer;
3641
- this._maxPayload = options.maxPayload | 0;
3642
- this._skipUTF8Validation = !!options.skipUTF8Validation;
3643
- this[kWebSocket] = void 0;
3644
- this._bufferedBytes = 0;
3645
- this._buffers = [];
3646
- this._compressed = false;
3647
- this._payloadLength = 0;
3648
- this._mask = void 0;
3649
- this._fragmented = 0;
3650
- this._masked = false;
3651
- this._fin = false;
3652
- this._opcode = 0;
3653
- this._totalPayloadLength = 0;
3654
- this._messageLength = 0;
3655
- this._fragments = [];
3656
- this._errored = false;
3657
- this._loop = false;
3658
- this._state = GET_INFO;
3659
- }
3660
- /**
3661
- * Implements `Writable.prototype._write()`.
3662
- *
3663
- * @param {Buffer} chunk The chunk of data to write
3664
- * @param {String} encoding The character encoding of `chunk`
3665
- * @param {Function} cb Callback
3666
- * @private
3667
- */
3668
- _write(chunk, encoding, cb) {
3669
- if (this._opcode === 8 && this._state == GET_INFO) return cb();
3670
- this._bufferedBytes += chunk.length;
3671
- this._buffers.push(chunk);
3672
- this.startLoop(cb);
3673
- }
3674
- /**
3675
- * Consumes `n` bytes from the buffered data.
3676
- *
3677
- * @param {Number} n The number of bytes to consume
3678
- * @return {Buffer} The consumed bytes
3679
- * @private
3680
- */
3681
- consume(n) {
3682
- this._bufferedBytes -= n;
3683
- if (n === this._buffers[0].length) return this._buffers.shift();
3684
- if (n < this._buffers[0].length) {
3685
- const buf = this._buffers[0];
3686
- this._buffers[0] = new FastBuffer(
3687
- buf.buffer,
3688
- buf.byteOffset + n,
3689
- buf.length - n
3690
- );
3691
- return new FastBuffer(buf.buffer, buf.byteOffset, n);
3692
- }
3693
- const dst = Buffer.allocUnsafe(n);
3694
- do {
3695
- const buf = this._buffers[0];
3696
- const offset = dst.length - n;
3697
- if (n >= buf.length) {
3698
- dst.set(this._buffers.shift(), offset);
3699
- } else {
3700
- dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
3701
- this._buffers[0] = new FastBuffer(
3702
- buf.buffer,
3703
- buf.byteOffset + n,
3704
- buf.length - n
3705
- );
3706
- }
3707
- n -= buf.length;
3708
- } while (n > 0);
3709
- return dst;
3710
- }
3711
- /**
3712
- * Starts the parsing loop.
3713
- *
3714
- * @param {Function} cb Callback
3715
- * @private
3716
- */
3717
- startLoop(cb) {
3718
- this._loop = true;
3719
- do {
3720
- switch (this._state) {
3721
- case GET_INFO:
3722
- this.getInfo(cb);
3723
- break;
3724
- case GET_PAYLOAD_LENGTH_16:
3725
- this.getPayloadLength16(cb);
3726
- break;
3727
- case GET_PAYLOAD_LENGTH_64:
3728
- this.getPayloadLength64(cb);
3729
- break;
3730
- case GET_MASK:
3731
- this.getMask();
3732
- break;
3733
- case GET_DATA:
3734
- this.getData(cb);
3735
- break;
3736
- case INFLATING:
3737
- case DEFER_EVENT:
3738
- this._loop = false;
3739
- return;
3740
- }
3741
- } while (this._loop);
3742
- if (!this._errored) cb();
3743
- }
3744
- /**
3745
- * Reads the first two bytes of a frame.
3746
- *
3747
- * @param {Function} cb Callback
3748
- * @private
3749
- */
3750
- getInfo(cb) {
3751
- if (this._bufferedBytes < 2) {
3752
- this._loop = false;
3753
- return;
3754
- }
3755
- const buf = this.consume(2);
3756
- if ((buf[0] & 48) !== 0) {
3757
- const error = this.createError(
3758
- RangeError,
3759
- "RSV2 and RSV3 must be clear",
3760
- true,
3761
- 1002,
3762
- "WS_ERR_UNEXPECTED_RSV_2_3"
3763
- );
3764
- cb(error);
3765
- return;
3766
- }
3767
- const compressed = (buf[0] & 64) === 64;
3768
- if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
3769
- const error = this.createError(
3770
- RangeError,
3771
- "RSV1 must be clear",
3772
- true,
3773
- 1002,
3774
- "WS_ERR_UNEXPECTED_RSV_1"
3775
- );
3776
- cb(error);
3777
- return;
3778
- }
3779
- this._fin = (buf[0] & 128) === 128;
3780
- this._opcode = buf[0] & 15;
3781
- this._payloadLength = buf[1] & 127;
3782
- if (this._opcode === 0) {
3783
- if (compressed) {
3784
- const error = this.createError(
3785
- RangeError,
3786
- "RSV1 must be clear",
3787
- true,
3788
- 1002,
3789
- "WS_ERR_UNEXPECTED_RSV_1"
3790
- );
3791
- cb(error);
3792
- return;
3793
- }
3794
- if (!this._fragmented) {
3795
- const error = this.createError(
3796
- RangeError,
3797
- "invalid opcode 0",
3798
- true,
3799
- 1002,
3800
- "WS_ERR_INVALID_OPCODE"
3801
- );
3802
- cb(error);
3803
- return;
3804
- }
3805
- this._opcode = this._fragmented;
3806
- } else if (this._opcode === 1 || this._opcode === 2) {
3807
- if (this._fragmented) {
3808
- const error = this.createError(
3809
- RangeError,
3810
- `invalid opcode ${this._opcode}`,
3811
- true,
3812
- 1002,
3813
- "WS_ERR_INVALID_OPCODE"
3814
- );
3815
- cb(error);
3816
- return;
3817
- }
3818
- this._compressed = compressed;
3819
- } else if (this._opcode > 7 && this._opcode < 11) {
3820
- if (!this._fin) {
3821
- const error = this.createError(
3822
- RangeError,
3823
- "FIN must be set",
3824
- true,
3825
- 1002,
3826
- "WS_ERR_EXPECTED_FIN"
3827
- );
3828
- cb(error);
3829
- return;
3830
- }
3831
- if (compressed) {
3832
- const error = this.createError(
3833
- RangeError,
3834
- "RSV1 must be clear",
3835
- true,
3836
- 1002,
3837
- "WS_ERR_UNEXPECTED_RSV_1"
3838
- );
3839
- cb(error);
3840
- return;
3841
- }
3842
- if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
3843
- const error = this.createError(
3844
- RangeError,
3845
- `invalid payload length ${this._payloadLength}`,
3846
- true,
3847
- 1002,
3848
- "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
3849
- );
3850
- cb(error);
3851
- return;
3852
- }
3853
- } else {
3854
- const error = this.createError(
3855
- RangeError,
3856
- `invalid opcode ${this._opcode}`,
3857
- true,
3858
- 1002,
3859
- "WS_ERR_INVALID_OPCODE"
3860
- );
3861
- cb(error);
3862
- return;
3863
- }
3864
- if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
3865
- this._masked = (buf[1] & 128) === 128;
3866
- if (this._isServer) {
3867
- if (!this._masked) {
3868
- const error = this.createError(
3869
- RangeError,
3870
- "MASK must be set",
3871
- true,
3872
- 1002,
3873
- "WS_ERR_EXPECTED_MASK"
3874
- );
3875
- cb(error);
3876
- return;
3877
- }
3878
- } else if (this._masked) {
3879
- const error = this.createError(
3880
- RangeError,
3881
- "MASK must be clear",
3882
- true,
3883
- 1002,
3884
- "WS_ERR_UNEXPECTED_MASK"
3885
- );
3886
- cb(error);
3887
- return;
3888
- }
3889
- if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
3890
- else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
3891
- else this.haveLength(cb);
3892
- }
3893
- /**
3894
- * Gets extended payload length (7+16).
3895
- *
3896
- * @param {Function} cb Callback
3897
- * @private
3898
- */
3899
- getPayloadLength16(cb) {
3900
- if (this._bufferedBytes < 2) {
3901
- this._loop = false;
3902
- return;
3903
- }
3904
- this._payloadLength = this.consume(2).readUInt16BE(0);
3905
- this.haveLength(cb);
3906
- }
3907
- /**
3908
- * Gets extended payload length (7+64).
3909
- *
3910
- * @param {Function} cb Callback
3911
- * @private
3912
- */
3913
- getPayloadLength64(cb) {
3914
- if (this._bufferedBytes < 8) {
3915
- this._loop = false;
3916
- return;
3917
- }
3918
- const buf = this.consume(8);
3919
- const num = buf.readUInt32BE(0);
3920
- if (num > Math.pow(2, 53 - 32) - 1) {
3921
- const error = this.createError(
3922
- RangeError,
3923
- "Unsupported WebSocket frame: payload length > 2^53 - 1",
3924
- false,
3925
- 1009,
3926
- "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
3927
- );
3928
- cb(error);
3929
- return;
3930
- }
3931
- this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
3932
- this.haveLength(cb);
3933
- }
3934
- /**
3935
- * Payload length has been read.
3936
- *
3937
- * @param {Function} cb Callback
3938
- * @private
3939
- */
3940
- haveLength(cb) {
3941
- if (this._payloadLength && this._opcode < 8) {
3942
- this._totalPayloadLength += this._payloadLength;
3943
- if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
3944
- const error = this.createError(
3945
- RangeError,
3946
- "Max payload size exceeded",
3947
- false,
3948
- 1009,
3949
- "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
3950
- );
3951
- cb(error);
3952
- return;
3953
- }
3954
- }
3955
- if (this._masked) this._state = GET_MASK;
3956
- else this._state = GET_DATA;
3957
- }
3958
- /**
3959
- * Reads mask bytes.
3960
- *
3961
- * @private
3962
- */
3963
- getMask() {
3964
- if (this._bufferedBytes < 4) {
3965
- this._loop = false;
3966
- return;
3967
- }
3968
- this._mask = this.consume(4);
3969
- this._state = GET_DATA;
3970
- }
3971
- /**
3972
- * Reads data bytes.
3973
- *
3974
- * @param {Function} cb Callback
3975
- * @private
3976
- */
3977
- getData(cb) {
3978
- let data = EMPTY_BUFFER;
3979
- if (this._payloadLength) {
3980
- if (this._bufferedBytes < this._payloadLength) {
3981
- this._loop = false;
3982
- return;
3983
- }
3984
- data = this.consume(this._payloadLength);
3985
- if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
3986
- unmask(data, this._mask);
3987
- }
3988
- }
3989
- if (this._opcode > 7) {
3990
- this.controlMessage(data, cb);
3991
- return;
3992
- }
3993
- if (this._compressed) {
3994
- this._state = INFLATING;
3995
- this.decompress(data, cb);
3996
- return;
3997
- }
3998
- if (data.length) {
3999
- this._messageLength = this._totalPayloadLength;
4000
- this._fragments.push(data);
4001
- }
4002
- this.dataMessage(cb);
4003
- }
4004
- /**
4005
- * Decompresses data.
4006
- *
4007
- * @param {Buffer} data Compressed data
4008
- * @param {Function} cb Callback
4009
- * @private
4010
- */
4011
- decompress(data, cb) {
4012
- const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
4013
- perMessageDeflate.decompress(data, this._fin, (err, buf) => {
4014
- if (err) return cb(err);
4015
- if (buf.length) {
4016
- this._messageLength += buf.length;
4017
- if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
4018
- const error = this.createError(
4019
- RangeError,
4020
- "Max payload size exceeded",
4021
- false,
4022
- 1009,
4023
- "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
4024
- );
4025
- cb(error);
4026
- return;
4027
- }
4028
- this._fragments.push(buf);
4029
- }
4030
- this.dataMessage(cb);
4031
- if (this._state === GET_INFO) this.startLoop(cb);
4032
- });
4033
- }
4034
- /**
4035
- * Handles a data message.
4036
- *
4037
- * @param {Function} cb Callback
4038
- * @private
4039
- */
4040
- dataMessage(cb) {
4041
- if (!this._fin) {
4042
- this._state = GET_INFO;
4043
- return;
4044
- }
4045
- const messageLength = this._messageLength;
4046
- const fragments = this._fragments;
4047
- this._totalPayloadLength = 0;
4048
- this._messageLength = 0;
4049
- this._fragmented = 0;
4050
- this._fragments = [];
4051
- if (this._opcode === 2) {
4052
- let data;
4053
- if (this._binaryType === "nodebuffer") {
4054
- data = concat(fragments, messageLength);
4055
- } else if (this._binaryType === "arraybuffer") {
4056
- data = toArrayBuffer(concat(fragments, messageLength));
4057
- } else if (this._binaryType === "blob") {
4058
- data = new Blob(fragments);
4059
- } else {
4060
- data = fragments;
4061
- }
4062
- if (this._allowSynchronousEvents) {
4063
- this.emit("message", data, true);
4064
- this._state = GET_INFO;
4065
- } else {
4066
- this._state = DEFER_EVENT;
4067
- setImmediate(() => {
4068
- this.emit("message", data, true);
4069
- this._state = GET_INFO;
4070
- this.startLoop(cb);
4071
- });
4072
- }
4073
- } else {
4074
- const buf = concat(fragments, messageLength);
4075
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
4076
- const error = this.createError(
4077
- Error,
4078
- "invalid UTF-8 sequence",
4079
- true,
4080
- 1007,
4081
- "WS_ERR_INVALID_UTF8"
4082
- );
4083
- cb(error);
4084
- return;
4085
- }
4086
- if (this._state === INFLATING || this._allowSynchronousEvents) {
4087
- this.emit("message", buf, false);
4088
- this._state = GET_INFO;
4089
- } else {
4090
- this._state = DEFER_EVENT;
4091
- setImmediate(() => {
4092
- this.emit("message", buf, false);
4093
- this._state = GET_INFO;
4094
- this.startLoop(cb);
4095
- });
4096
- }
4097
- }
4098
- }
4099
- /**
4100
- * Handles a control message.
4101
- *
4102
- * @param {Buffer} data Data to handle
4103
- * @return {(Error|RangeError|undefined)} A possible error
4104
- * @private
4105
- */
4106
- controlMessage(data, cb) {
4107
- if (this._opcode === 8) {
4108
- if (data.length === 0) {
4109
- this._loop = false;
4110
- this.emit("conclude", 1005, EMPTY_BUFFER);
4111
- this.end();
4112
- } else {
4113
- const code = data.readUInt16BE(0);
4114
- if (!isValidStatusCode(code)) {
4115
- const error = this.createError(
4116
- RangeError,
4117
- `invalid status code ${code}`,
4118
- true,
4119
- 1002,
4120
- "WS_ERR_INVALID_CLOSE_CODE"
4121
- );
4122
- cb(error);
4123
- return;
4124
- }
4125
- const buf = new FastBuffer(
4126
- data.buffer,
4127
- data.byteOffset + 2,
4128
- data.length - 2
4129
- );
4130
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
4131
- const error = this.createError(
4132
- Error,
4133
- "invalid UTF-8 sequence",
4134
- true,
4135
- 1007,
4136
- "WS_ERR_INVALID_UTF8"
4137
- );
4138
- cb(error);
4139
- return;
4140
- }
4141
- this._loop = false;
4142
- this.emit("conclude", code, buf);
4143
- this.end();
4144
- }
4145
- this._state = GET_INFO;
4146
- return;
4147
- }
4148
- if (this._allowSynchronousEvents) {
4149
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
4150
- this._state = GET_INFO;
4151
- } else {
4152
- this._state = DEFER_EVENT;
4153
- setImmediate(() => {
4154
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
4155
- this._state = GET_INFO;
4156
- this.startLoop(cb);
4157
- });
4158
- }
4159
- }
4160
- /**
4161
- * Builds an error object.
4162
- *
4163
- * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
4164
- * @param {String} message The error message
4165
- * @param {Boolean} prefix Specifies whether or not to add a default prefix to
4166
- * `message`
4167
- * @param {Number} statusCode The status code
4168
- * @param {String} errorCode The exposed error code
4169
- * @return {(Error|RangeError)} The error
4170
- * @private
4171
- */
4172
- createError(ErrorCtor, message, prefix, statusCode, errorCode) {
4173
- this._loop = false;
4174
- this._errored = true;
4175
- const err = new ErrorCtor(
4176
- prefix ? `Invalid WebSocket frame: ${message}` : message
4177
- );
4178
- Error.captureStackTrace(err, this.createError);
4179
- err.code = errorCode;
4180
- err[kStatusCode] = statusCode;
4181
- return err;
4182
- }
4183
- };
4184
- module.exports = Receiver2;
4185
- }
4186
- });
4187
-
4188
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/sender.js
4189
- var require_sender = __commonJS({
4190
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/sender.js"(exports, module) {
4191
- "use strict";
4192
- var { Duplex } = __require("stream");
4193
- var { randomFillSync } = __require("crypto");
4194
- var PerMessageDeflate2 = require_permessage_deflate();
4195
- var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
4196
- var { isBlob, isValidStatusCode } = require_validation();
4197
- var { mask: applyMask, toBuffer } = require_buffer_util();
4198
- var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
4199
- var maskBuffer = Buffer.alloc(4);
4200
- var RANDOM_POOL_SIZE = 8 * 1024;
4201
- var randomPool;
4202
- var randomPoolPointer = RANDOM_POOL_SIZE;
4203
- var DEFAULT = 0;
4204
- var DEFLATING = 1;
4205
- var GET_BLOB_DATA = 2;
4206
- var Sender2 = class _Sender {
4207
- /**
4208
- * Creates a Sender instance.
4209
- *
4210
- * @param {Duplex} socket The connection socket
4211
- * @param {Object} [extensions] An object containing the negotiated extensions
4212
- * @param {Function} [generateMask] The function used to generate the masking
4213
- * key
4214
- */
4215
- constructor(socket, extensions, generateMask) {
4216
- this._extensions = extensions || {};
4217
- if (generateMask) {
4218
- this._generateMask = generateMask;
4219
- this._maskBuffer = Buffer.alloc(4);
4220
- }
4221
- this._socket = socket;
4222
- this._firstFragment = true;
4223
- this._compress = false;
4224
- this._bufferedBytes = 0;
4225
- this._queue = [];
4226
- this._state = DEFAULT;
4227
- this.onerror = NOOP;
4228
- this[kWebSocket] = void 0;
4229
- }
4230
- /**
4231
- * Frames a piece of data according to the HyBi WebSocket protocol.
4232
- *
4233
- * @param {(Buffer|String)} data The data to frame
4234
- * @param {Object} options Options object
4235
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
4236
- * FIN bit
4237
- * @param {Function} [options.generateMask] The function used to generate the
4238
- * masking key
4239
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
4240
- * `data`
4241
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
4242
- * key
4243
- * @param {Number} options.opcode The opcode
4244
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
4245
- * modified
4246
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
4247
- * RSV1 bit
4248
- * @return {(Buffer|String)[]} The framed data
4249
- * @public
4250
- */
4251
- static frame(data, options) {
4252
- let mask;
4253
- let merge = false;
4254
- let offset = 2;
4255
- let skipMasking = false;
4256
- if (options.mask) {
4257
- mask = options.maskBuffer || maskBuffer;
4258
- if (options.generateMask) {
4259
- options.generateMask(mask);
4260
- } else {
4261
- if (randomPoolPointer === RANDOM_POOL_SIZE) {
4262
- if (randomPool === void 0) {
4263
- randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
4264
- }
4265
- randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
4266
- randomPoolPointer = 0;
4267
- }
4268
- mask[0] = randomPool[randomPoolPointer++];
4269
- mask[1] = randomPool[randomPoolPointer++];
4270
- mask[2] = randomPool[randomPoolPointer++];
4271
- mask[3] = randomPool[randomPoolPointer++];
4272
- }
4273
- skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
4274
- offset = 6;
4275
- }
4276
- let dataLength;
4277
- if (typeof data === "string") {
4278
- if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
4279
- dataLength = options[kByteLength];
4280
- } else {
4281
- data = Buffer.from(data);
4282
- dataLength = data.length;
4283
- }
4284
- } else {
4285
- dataLength = data.length;
4286
- merge = options.mask && options.readOnly && !skipMasking;
4287
- }
4288
- let payloadLength = dataLength;
4289
- if (dataLength >= 65536) {
4290
- offset += 8;
4291
- payloadLength = 127;
4292
- } else if (dataLength > 125) {
4293
- offset += 2;
4294
- payloadLength = 126;
4295
- }
4296
- const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
4297
- target[0] = options.fin ? options.opcode | 128 : options.opcode;
4298
- if (options.rsv1) target[0] |= 64;
4299
- target[1] = payloadLength;
4300
- if (payloadLength === 126) {
4301
- target.writeUInt16BE(dataLength, 2);
4302
- } else if (payloadLength === 127) {
4303
- target[2] = target[3] = 0;
4304
- target.writeUIntBE(dataLength, 4, 6);
4305
- }
4306
- if (!options.mask) return [target, data];
4307
- target[1] |= 128;
4308
- target[offset - 4] = mask[0];
4309
- target[offset - 3] = mask[1];
4310
- target[offset - 2] = mask[2];
4311
- target[offset - 1] = mask[3];
4312
- if (skipMasking) return [target, data];
4313
- if (merge) {
4314
- applyMask(data, mask, target, offset, dataLength);
4315
- return [target];
4316
- }
4317
- applyMask(data, mask, data, 0, dataLength);
4318
- return [target, data];
4319
- }
4320
- /**
4321
- * Sends a close message to the other peer.
4322
- *
4323
- * @param {Number} [code] The status code component of the body
4324
- * @param {(String|Buffer)} [data] The message component of the body
4325
- * @param {Boolean} [mask=false] Specifies whether or not to mask the message
4326
- * @param {Function} [cb] Callback
4327
- * @public
4328
- */
4329
- close(code, data, mask, cb) {
4330
- let buf;
4331
- if (code === void 0) {
4332
- buf = EMPTY_BUFFER;
4333
- } else if (typeof code !== "number" || !isValidStatusCode(code)) {
4334
- throw new TypeError("First argument must be a valid error code number");
4335
- } else if (data === void 0 || !data.length) {
4336
- buf = Buffer.allocUnsafe(2);
4337
- buf.writeUInt16BE(code, 0);
4338
- } else {
4339
- const length = Buffer.byteLength(data);
4340
- if (length > 123) {
4341
- throw new RangeError("The message must not be greater than 123 bytes");
4342
- }
4343
- buf = Buffer.allocUnsafe(2 + length);
4344
- buf.writeUInt16BE(code, 0);
4345
- if (typeof data === "string") {
4346
- buf.write(data, 2);
4347
- } else {
4348
- buf.set(data, 2);
4349
- }
4350
- }
4351
- const options = {
4352
- [kByteLength]: buf.length,
4353
- fin: true,
4354
- generateMask: this._generateMask,
4355
- mask,
4356
- maskBuffer: this._maskBuffer,
4357
- opcode: 8,
4358
- readOnly: false,
4359
- rsv1: false
4360
- };
4361
- if (this._state !== DEFAULT) {
4362
- this.enqueue([this.dispatch, buf, false, options, cb]);
4363
- } else {
4364
- this.sendFrame(_Sender.frame(buf, options), cb);
4365
- }
4366
- }
4367
- /**
4368
- * Sends a ping message to the other peer.
4369
- *
4370
- * @param {*} data The message to send
4371
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
4372
- * @param {Function} [cb] Callback
4373
- * @public
4374
- */
4375
- ping(data, mask, cb) {
4376
- let byteLength;
4377
- let readOnly;
4378
- if (typeof data === "string") {
4379
- byteLength = Buffer.byteLength(data);
4380
- readOnly = false;
4381
- } else if (isBlob(data)) {
4382
- byteLength = data.size;
4383
- readOnly = false;
4384
- } else {
4385
- data = toBuffer(data);
4386
- byteLength = data.length;
4387
- readOnly = toBuffer.readOnly;
4388
- }
4389
- if (byteLength > 125) {
4390
- throw new RangeError("The data size must not be greater than 125 bytes");
4391
- }
4392
- const options = {
4393
- [kByteLength]: byteLength,
4394
- fin: true,
4395
- generateMask: this._generateMask,
4396
- mask,
4397
- maskBuffer: this._maskBuffer,
4398
- opcode: 9,
4399
- readOnly,
4400
- rsv1: false
4401
- };
4402
- if (isBlob(data)) {
4403
- if (this._state !== DEFAULT) {
4404
- this.enqueue([this.getBlobData, data, false, options, cb]);
4405
- } else {
4406
- this.getBlobData(data, false, options, cb);
4407
- }
4408
- } else if (this._state !== DEFAULT) {
4409
- this.enqueue([this.dispatch, data, false, options, cb]);
4410
- } else {
4411
- this.sendFrame(_Sender.frame(data, options), cb);
4412
- }
4413
- }
4414
- /**
4415
- * Sends a pong message to the other peer.
4416
- *
4417
- * @param {*} data The message to send
4418
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
4419
- * @param {Function} [cb] Callback
4420
- * @public
4421
- */
4422
- pong(data, mask, cb) {
4423
- let byteLength;
4424
- let readOnly;
4425
- if (typeof data === "string") {
4426
- byteLength = Buffer.byteLength(data);
4427
- readOnly = false;
4428
- } else if (isBlob(data)) {
4429
- byteLength = data.size;
4430
- readOnly = false;
4431
- } else {
4432
- data = toBuffer(data);
4433
- byteLength = data.length;
4434
- readOnly = toBuffer.readOnly;
4435
- }
4436
- if (byteLength > 125) {
4437
- throw new RangeError("The data size must not be greater than 125 bytes");
4438
- }
4439
- const options = {
4440
- [kByteLength]: byteLength,
4441
- fin: true,
4442
- generateMask: this._generateMask,
4443
- mask,
4444
- maskBuffer: this._maskBuffer,
4445
- opcode: 10,
4446
- readOnly,
4447
- rsv1: false
4448
- };
4449
- if (isBlob(data)) {
4450
- if (this._state !== DEFAULT) {
4451
- this.enqueue([this.getBlobData, data, false, options, cb]);
4452
- } else {
4453
- this.getBlobData(data, false, options, cb);
4454
- }
4455
- } else if (this._state !== DEFAULT) {
4456
- this.enqueue([this.dispatch, data, false, options, cb]);
4457
- } else {
4458
- this.sendFrame(_Sender.frame(data, options), cb);
4459
- }
4460
- }
4461
- /**
4462
- * Sends a data message to the other peer.
4463
- *
4464
- * @param {*} data The message to send
4465
- * @param {Object} options Options object
4466
- * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
4467
- * or text
4468
- * @param {Boolean} [options.compress=false] Specifies whether or not to
4469
- * compress `data`
4470
- * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
4471
- * last one
4472
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
4473
- * `data`
4474
- * @param {Function} [cb] Callback
4475
- * @public
4476
- */
4477
- send(data, options, cb) {
4478
- const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
4479
- let opcode = options.binary ? 2 : 1;
4480
- let rsv1 = options.compress;
4481
- let byteLength;
4482
- let readOnly;
4483
- if (typeof data === "string") {
4484
- byteLength = Buffer.byteLength(data);
4485
- readOnly = false;
4486
- } else if (isBlob(data)) {
4487
- byteLength = data.size;
4488
- readOnly = false;
4489
- } else {
4490
- data = toBuffer(data);
4491
- byteLength = data.length;
4492
- readOnly = toBuffer.readOnly;
4493
- }
4494
- if (this._firstFragment) {
4495
- this._firstFragment = false;
4496
- if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
4497
- rsv1 = byteLength >= perMessageDeflate._threshold;
4498
- }
4499
- this._compress = rsv1;
4500
- } else {
4501
- rsv1 = false;
4502
- opcode = 0;
4503
- }
4504
- if (options.fin) this._firstFragment = true;
4505
- const opts = {
4506
- [kByteLength]: byteLength,
4507
- fin: options.fin,
4508
- generateMask: this._generateMask,
4509
- mask: options.mask,
4510
- maskBuffer: this._maskBuffer,
4511
- opcode,
4512
- readOnly,
4513
- rsv1
4514
- };
4515
- if (isBlob(data)) {
4516
- if (this._state !== DEFAULT) {
4517
- this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
4518
- } else {
4519
- this.getBlobData(data, this._compress, opts, cb);
4520
- }
4521
- } else if (this._state !== DEFAULT) {
4522
- this.enqueue([this.dispatch, data, this._compress, opts, cb]);
4523
- } else {
4524
- this.dispatch(data, this._compress, opts, cb);
4525
- }
4526
- }
4527
- /**
4528
- * Gets the contents of a blob as binary data.
4529
- *
4530
- * @param {Blob} blob The blob
4531
- * @param {Boolean} [compress=false] Specifies whether or not to compress
4532
- * the data
4533
- * @param {Object} options Options object
4534
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
4535
- * FIN bit
4536
- * @param {Function} [options.generateMask] The function used to generate the
4537
- * masking key
4538
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
4539
- * `data`
4540
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
4541
- * key
4542
- * @param {Number} options.opcode The opcode
4543
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
4544
- * modified
4545
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
4546
- * RSV1 bit
4547
- * @param {Function} [cb] Callback
4548
- * @private
4549
- */
4550
- getBlobData(blob, compress, options, cb) {
4551
- this._bufferedBytes += options[kByteLength];
4552
- this._state = GET_BLOB_DATA;
4553
- blob.arrayBuffer().then((arrayBuffer) => {
4554
- if (this._socket.destroyed) {
4555
- const err = new Error(
4556
- "The socket was closed while the blob was being read"
4557
- );
4558
- process.nextTick(callCallbacks, this, err, cb);
4559
- return;
4560
- }
4561
- this._bufferedBytes -= options[kByteLength];
4562
- const data = toBuffer(arrayBuffer);
4563
- if (!compress) {
4564
- this._state = DEFAULT;
4565
- this.sendFrame(_Sender.frame(data, options), cb);
4566
- this.dequeue();
4567
- } else {
4568
- this.dispatch(data, compress, options, cb);
4569
- }
4570
- }).catch((err) => {
4571
- process.nextTick(onError, this, err, cb);
4572
- });
4573
- }
4574
- /**
4575
- * Dispatches a message.
4576
- *
4577
- * @param {(Buffer|String)} data The message to send
4578
- * @param {Boolean} [compress=false] Specifies whether or not to compress
4579
- * `data`
4580
- * @param {Object} options Options object
4581
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
4582
- * FIN bit
4583
- * @param {Function} [options.generateMask] The function used to generate the
4584
- * masking key
4585
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
4586
- * `data`
4587
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
4588
- * key
4589
- * @param {Number} options.opcode The opcode
4590
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
4591
- * modified
4592
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
4593
- * RSV1 bit
4594
- * @param {Function} [cb] Callback
4595
- * @private
4596
- */
4597
- dispatch(data, compress, options, cb) {
4598
- if (!compress) {
4599
- this.sendFrame(_Sender.frame(data, options), cb);
4600
- return;
4601
- }
4602
- const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
4603
- this._bufferedBytes += options[kByteLength];
4604
- this._state = DEFLATING;
4605
- perMessageDeflate.compress(data, options.fin, (_, buf) => {
4606
- if (this._socket.destroyed) {
4607
- const err = new Error(
4608
- "The socket was closed while data was being compressed"
4609
- );
4610
- callCallbacks(this, err, cb);
4611
- return;
4612
- }
4613
- this._bufferedBytes -= options[kByteLength];
4614
- this._state = DEFAULT;
4615
- options.readOnly = false;
4616
- this.sendFrame(_Sender.frame(buf, options), cb);
4617
- this.dequeue();
4618
- });
4619
- }
4620
- /**
4621
- * Executes queued send operations.
4622
- *
4623
- * @private
4624
- */
4625
- dequeue() {
4626
- while (this._state === DEFAULT && this._queue.length) {
4627
- const params = this._queue.shift();
4628
- this._bufferedBytes -= params[3][kByteLength];
4629
- Reflect.apply(params[0], this, params.slice(1));
4630
- }
4631
- }
4632
- /**
4633
- * Enqueues a send operation.
4634
- *
4635
- * @param {Array} params Send operation parameters.
4636
- * @private
4637
- */
4638
- enqueue(params) {
4639
- this._bufferedBytes += params[3][kByteLength];
4640
- this._queue.push(params);
4641
- }
4642
- /**
4643
- * Sends a frame.
4644
- *
4645
- * @param {(Buffer | String)[]} list The frame to send
4646
- * @param {Function} [cb] Callback
4647
- * @private
4648
- */
4649
- sendFrame(list, cb) {
4650
- if (list.length === 2) {
4651
- this._socket.cork();
4652
- this._socket.write(list[0]);
4653
- this._socket.write(list[1], cb);
4654
- this._socket.uncork();
4655
- } else {
4656
- this._socket.write(list[0], cb);
4657
- }
4658
- }
4659
- };
4660
- module.exports = Sender2;
4661
- function callCallbacks(sender, err, cb) {
4662
- if (typeof cb === "function") cb(err);
4663
- for (let i = 0; i < sender._queue.length; i++) {
4664
- const params = sender._queue[i];
4665
- const callback = params[params.length - 1];
4666
- if (typeof callback === "function") callback(err);
4667
- }
4668
- }
4669
- function onError(sender, err, cb) {
4670
- callCallbacks(sender, err, cb);
4671
- sender.onerror(err);
4672
- }
4673
- }
4674
- });
4675
-
4676
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/event-target.js
4677
- var require_event_target = __commonJS({
4678
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/event-target.js"(exports, module) {
4679
- "use strict";
4680
- var { kForOnEventAttribute, kListener } = require_constants();
4681
- var kCode = /* @__PURE__ */ Symbol("kCode");
4682
- var kData = /* @__PURE__ */ Symbol("kData");
4683
- var kError = /* @__PURE__ */ Symbol("kError");
4684
- var kMessage = /* @__PURE__ */ Symbol("kMessage");
4685
- var kReason = /* @__PURE__ */ Symbol("kReason");
4686
- var kTarget = /* @__PURE__ */ Symbol("kTarget");
4687
- var kType = /* @__PURE__ */ Symbol("kType");
4688
- var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
4689
- var Event = class {
4690
- /**
4691
- * Create a new `Event`.
4692
- *
4693
- * @param {String} type The name of the event
4694
- * @throws {TypeError} If the `type` argument is not specified
4695
- */
4696
- constructor(type) {
4697
- this[kTarget] = null;
4698
- this[kType] = type;
4699
- }
4700
- /**
4701
- * @type {*}
4702
- */
4703
- get target() {
4704
- return this[kTarget];
4705
- }
4706
- /**
4707
- * @type {String}
4708
- */
4709
- get type() {
4710
- return this[kType];
4711
- }
4712
- };
4713
- Object.defineProperty(Event.prototype, "target", { enumerable: true });
4714
- Object.defineProperty(Event.prototype, "type", { enumerable: true });
4715
- var CloseEvent = class extends Event {
4716
- /**
4717
- * Create a new `CloseEvent`.
4718
- *
4719
- * @param {String} type The name of the event
4720
- * @param {Object} [options] A dictionary object that allows for setting
4721
- * attributes via object members of the same name
4722
- * @param {Number} [options.code=0] The status code explaining why the
4723
- * connection was closed
4724
- * @param {String} [options.reason=''] A human-readable string explaining why
4725
- * the connection was closed
4726
- * @param {Boolean} [options.wasClean=false] Indicates whether or not the
4727
- * connection was cleanly closed
4728
- */
4729
- constructor(type, options = {}) {
4730
- super(type);
4731
- this[kCode] = options.code === void 0 ? 0 : options.code;
4732
- this[kReason] = options.reason === void 0 ? "" : options.reason;
4733
- this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
4734
- }
4735
- /**
4736
- * @type {Number}
4737
- */
4738
- get code() {
4739
- return this[kCode];
4740
- }
4741
- /**
4742
- * @type {String}
4743
- */
4744
- get reason() {
4745
- return this[kReason];
4746
- }
4747
- /**
4748
- * @type {Boolean}
4749
- */
4750
- get wasClean() {
4751
- return this[kWasClean];
4752
- }
4753
- };
4754
- Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
4755
- Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
4756
- Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
4757
- var ErrorEvent = class extends Event {
4758
- /**
4759
- * Create a new `ErrorEvent`.
4760
- *
4761
- * @param {String} type The name of the event
4762
- * @param {Object} [options] A dictionary object that allows for setting
4763
- * attributes via object members of the same name
4764
- * @param {*} [options.error=null] The error that generated this event
4765
- * @param {String} [options.message=''] The error message
4766
- */
4767
- constructor(type, options = {}) {
4768
- super(type);
4769
- this[kError] = options.error === void 0 ? null : options.error;
4770
- this[kMessage] = options.message === void 0 ? "" : options.message;
4771
- }
4772
- /**
4773
- * @type {*}
4774
- */
4775
- get error() {
4776
- return this[kError];
4777
- }
4778
- /**
4779
- * @type {String}
4780
- */
4781
- get message() {
4782
- return this[kMessage];
4783
- }
4784
- };
4785
- Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
4786
- Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
4787
- var MessageEvent = class extends Event {
4788
- /**
4789
- * Create a new `MessageEvent`.
4790
- *
4791
- * @param {String} type The name of the event
4792
- * @param {Object} [options] A dictionary object that allows for setting
4793
- * attributes via object members of the same name
4794
- * @param {*} [options.data=null] The message content
4795
- */
4796
- constructor(type, options = {}) {
4797
- super(type);
4798
- this[kData] = options.data === void 0 ? null : options.data;
4799
- }
4800
- /**
4801
- * @type {*}
4802
- */
4803
- get data() {
4804
- return this[kData];
4805
- }
4806
- };
4807
- Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
4808
- var EventTarget = {
4809
- /**
4810
- * Register an event listener.
4811
- *
4812
- * @param {String} type A string representing the event type to listen for
4813
- * @param {(Function|Object)} handler The listener to add
4814
- * @param {Object} [options] An options object specifies characteristics about
4815
- * the event listener
4816
- * @param {Boolean} [options.once=false] A `Boolean` indicating that the
4817
- * listener should be invoked at most once after being added. If `true`,
4818
- * the listener would be automatically removed when invoked.
4819
- * @public
4820
- */
4821
- addEventListener(type, handler, options = {}) {
4822
- for (const listener of this.listeners(type)) {
4823
- if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
4824
- return;
4825
- }
4826
- }
4827
- let wrapper;
4828
- if (type === "message") {
4829
- wrapper = function onMessage(data, isBinary) {
4830
- const event = new MessageEvent("message", {
4831
- data: isBinary ? data : data.toString()
4832
- });
4833
- event[kTarget] = this;
4834
- callListener(handler, this, event);
4835
- };
4836
- } else if (type === "close") {
4837
- wrapper = function onClose(code, message) {
4838
- const event = new CloseEvent("close", {
4839
- code,
4840
- reason: message.toString(),
4841
- wasClean: this._closeFrameReceived && this._closeFrameSent
4842
- });
4843
- event[kTarget] = this;
4844
- callListener(handler, this, event);
4845
- };
4846
- } else if (type === "error") {
4847
- wrapper = function onError(error) {
4848
- const event = new ErrorEvent("error", {
4849
- error,
4850
- message: error.message
4851
- });
4852
- event[kTarget] = this;
4853
- callListener(handler, this, event);
4854
- };
4855
- } else if (type === "open") {
4856
- wrapper = function onOpen() {
4857
- const event = new Event("open");
4858
- event[kTarget] = this;
4859
- callListener(handler, this, event);
4860
- };
4861
- } else {
4862
- return;
4863
- }
4864
- wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
4865
- wrapper[kListener] = handler;
4866
- if (options.once) {
4867
- this.once(type, wrapper);
4868
- } else {
4869
- this.on(type, wrapper);
4870
- }
4871
- },
4872
- /**
4873
- * Remove an event listener.
4874
- *
4875
- * @param {String} type A string representing the event type to remove
4876
- * @param {(Function|Object)} handler The listener to remove
4877
- * @public
4878
- */
4879
- removeEventListener(type, handler) {
4880
- for (const listener of this.listeners(type)) {
4881
- if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
4882
- this.removeListener(type, listener);
4883
- break;
4884
- }
4885
- }
4886
- }
4887
- };
4888
- module.exports = {
4889
- CloseEvent,
4890
- ErrorEvent,
4891
- Event,
4892
- EventTarget,
4893
- MessageEvent
4894
- };
4895
- function callListener(listener, thisArg, event) {
4896
- if (typeof listener === "object" && listener.handleEvent) {
4897
- listener.handleEvent.call(listener, event);
4898
- } else {
4899
- listener.call(thisArg, event);
4900
- }
4901
- }
4902
- }
4903
- });
4904
-
4905
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/extension.js
4906
- var require_extension = __commonJS({
4907
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/extension.js"(exports, module) {
4908
- "use strict";
4909
- var { tokenChars } = require_validation();
4910
- function push(dest, name, elem) {
4911
- if (dest[name] === void 0) dest[name] = [elem];
4912
- else dest[name].push(elem);
4913
- }
4914
- function parse(header) {
4915
- const offers = /* @__PURE__ */ Object.create(null);
4916
- let params = /* @__PURE__ */ Object.create(null);
4917
- let mustUnescape = false;
4918
- let isEscaping = false;
4919
- let inQuotes = false;
4920
- let extensionName;
4921
- let paramName;
4922
- let start = -1;
4923
- let code = -1;
4924
- let end = -1;
4925
- let i = 0;
4926
- for (; i < header.length; i++) {
4927
- code = header.charCodeAt(i);
4928
- if (extensionName === void 0) {
4929
- if (end === -1 && tokenChars[code] === 1) {
4930
- if (start === -1) start = i;
4931
- } else if (i !== 0 && (code === 32 || code === 9)) {
4932
- if (end === -1 && start !== -1) end = i;
4933
- } else if (code === 59 || code === 44) {
4934
- if (start === -1) {
4935
- throw new SyntaxError(`Unexpected character at index ${i}`);
4936
- }
4937
- if (end === -1) end = i;
4938
- const name = header.slice(start, end);
4939
- if (code === 44) {
4940
- push(offers, name, params);
4941
- params = /* @__PURE__ */ Object.create(null);
4942
- } else {
4943
- extensionName = name;
4944
- }
4945
- start = end = -1;
4946
- } else {
4947
- throw new SyntaxError(`Unexpected character at index ${i}`);
4948
- }
4949
- } else if (paramName === void 0) {
4950
- if (end === -1 && tokenChars[code] === 1) {
4951
- if (start === -1) start = i;
4952
- } else if (code === 32 || code === 9) {
4953
- if (end === -1 && start !== -1) end = i;
4954
- } else if (code === 59 || code === 44) {
4955
- if (start === -1) {
4956
- throw new SyntaxError(`Unexpected character at index ${i}`);
4957
- }
4958
- if (end === -1) end = i;
4959
- push(params, header.slice(start, end), true);
4960
- if (code === 44) {
4961
- push(offers, extensionName, params);
4962
- params = /* @__PURE__ */ Object.create(null);
4963
- extensionName = void 0;
4964
- }
4965
- start = end = -1;
4966
- } else if (code === 61 && start !== -1 && end === -1) {
4967
- paramName = header.slice(start, i);
4968
- start = end = -1;
4969
- } else {
4970
- throw new SyntaxError(`Unexpected character at index ${i}`);
4971
- }
4972
- } else {
4973
- if (isEscaping) {
4974
- if (tokenChars[code] !== 1) {
4975
- throw new SyntaxError(`Unexpected character at index ${i}`);
4976
- }
4977
- if (start === -1) start = i;
4978
- else if (!mustUnescape) mustUnescape = true;
4979
- isEscaping = false;
4980
- } else if (inQuotes) {
4981
- if (tokenChars[code] === 1) {
4982
- if (start === -1) start = i;
4983
- } else if (code === 34 && start !== -1) {
4984
- inQuotes = false;
4985
- end = i;
4986
- } else if (code === 92) {
4987
- isEscaping = true;
4988
- } else {
4989
- throw new SyntaxError(`Unexpected character at index ${i}`);
4990
- }
4991
- } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
4992
- inQuotes = true;
4993
- } else if (end === -1 && tokenChars[code] === 1) {
4994
- if (start === -1) start = i;
4995
- } else if (start !== -1 && (code === 32 || code === 9)) {
4996
- if (end === -1) end = i;
4997
- } else if (code === 59 || code === 44) {
4998
- if (start === -1) {
4999
- throw new SyntaxError(`Unexpected character at index ${i}`);
5000
- }
5001
- if (end === -1) end = i;
5002
- let value = header.slice(start, end);
5003
- if (mustUnescape) {
5004
- value = value.replace(/\\/g, "");
5005
- mustUnescape = false;
5006
- }
5007
- push(params, paramName, value);
5008
- if (code === 44) {
5009
- push(offers, extensionName, params);
5010
- params = /* @__PURE__ */ Object.create(null);
5011
- extensionName = void 0;
5012
- }
5013
- paramName = void 0;
5014
- start = end = -1;
5015
- } else {
5016
- throw new SyntaxError(`Unexpected character at index ${i}`);
5017
- }
5018
- }
5019
- }
5020
- if (start === -1 || inQuotes || code === 32 || code === 9) {
5021
- throw new SyntaxError("Unexpected end of input");
5022
- }
5023
- if (end === -1) end = i;
5024
- const token = header.slice(start, end);
5025
- if (extensionName === void 0) {
5026
- push(offers, token, params);
5027
- } else {
5028
- if (paramName === void 0) {
5029
- push(params, token, true);
5030
- } else if (mustUnescape) {
5031
- push(params, paramName, token.replace(/\\/g, ""));
5032
- } else {
5033
- push(params, paramName, token);
5034
- }
5035
- push(offers, extensionName, params);
5036
- }
5037
- return offers;
5038
- }
5039
- function format(extensions) {
5040
- return Object.keys(extensions).map((extension2) => {
5041
- let configurations = extensions[extension2];
5042
- if (!Array.isArray(configurations)) configurations = [configurations];
5043
- return configurations.map((params) => {
5044
- return [extension2].concat(
5045
- Object.keys(params).map((k) => {
5046
- let values = params[k];
5047
- if (!Array.isArray(values)) values = [values];
5048
- return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
5049
- })
5050
- ).join("; ");
5051
- }).join(", ");
5052
- }).join(", ");
5053
- }
5054
- module.exports = { format, parse };
5055
- }
5056
- });
5057
-
5058
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket.js
5059
- var require_websocket = __commonJS({
5060
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket.js"(exports, module) {
5061
- "use strict";
5062
- var EventEmitter = __require("events");
5063
- var https = __require("https");
5064
- var http = __require("http");
5065
- var net = __require("net");
5066
- var tls = __require("tls");
5067
- var { randomBytes, createHash } = __require("crypto");
5068
- var { Duplex, Readable } = __require("stream");
5069
- var { URL } = __require("url");
5070
- var PerMessageDeflate2 = require_permessage_deflate();
5071
- var Receiver2 = require_receiver();
5072
- var Sender2 = require_sender();
5073
- var { isBlob } = require_validation();
5074
- var {
5075
- BINARY_TYPES,
5076
- CLOSE_TIMEOUT,
5077
- EMPTY_BUFFER,
5078
- GUID,
5079
- kForOnEventAttribute,
5080
- kListener,
5081
- kStatusCode,
5082
- kWebSocket,
5083
- NOOP
5084
- } = require_constants();
5085
- var {
5086
- EventTarget: { addEventListener, removeEventListener }
5087
- } = require_event_target();
5088
- var { format, parse } = require_extension();
5089
- var { toBuffer } = require_buffer_util();
5090
- var kAborted = /* @__PURE__ */ Symbol("kAborted");
5091
- var protocolVersions = [8, 13];
5092
- var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
5093
- var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
5094
- var WebSocket2 = class _WebSocket extends EventEmitter {
5095
- /**
5096
- * Create a new `WebSocket`.
5097
- *
5098
- * @param {(String|URL)} address The URL to which to connect
5099
- * @param {(String|String[])} [protocols] The subprotocols
5100
- * @param {Object} [options] Connection options
5101
- */
5102
- constructor(address, protocols, options) {
5103
- super();
5104
- this._binaryType = BINARY_TYPES[0];
5105
- this._closeCode = 1006;
5106
- this._closeFrameReceived = false;
5107
- this._closeFrameSent = false;
5108
- this._closeMessage = EMPTY_BUFFER;
5109
- this._closeTimer = null;
5110
- this._errorEmitted = false;
5111
- this._extensions = {};
5112
- this._paused = false;
5113
- this._protocol = "";
5114
- this._readyState = _WebSocket.CONNECTING;
5115
- this._receiver = null;
5116
- this._sender = null;
5117
- this._socket = null;
5118
- if (address !== null) {
5119
- this._bufferedAmount = 0;
5120
- this._isServer = false;
5121
- this._redirects = 0;
5122
- if (protocols === void 0) {
5123
- protocols = [];
5124
- } else if (!Array.isArray(protocols)) {
5125
- if (typeof protocols === "object" && protocols !== null) {
5126
- options = protocols;
5127
- protocols = [];
5128
- } else {
5129
- protocols = [protocols];
5130
- }
5131
- }
5132
- initAsClient(this, address, protocols, options);
5133
- } else {
5134
- this._autoPong = options.autoPong;
5135
- this._closeTimeout = options.closeTimeout;
5136
- this._isServer = true;
5137
- }
5138
- }
5139
- /**
5140
- * For historical reasons, the custom "nodebuffer" type is used by the default
5141
- * instead of "blob".
5142
- *
5143
- * @type {String}
5144
- */
5145
- get binaryType() {
5146
- return this._binaryType;
5147
- }
5148
- set binaryType(type) {
5149
- if (!BINARY_TYPES.includes(type)) return;
5150
- this._binaryType = type;
5151
- if (this._receiver) this._receiver._binaryType = type;
5152
- }
5153
- /**
5154
- * @type {Number}
5155
- */
5156
- get bufferedAmount() {
5157
- if (!this._socket) return this._bufferedAmount;
5158
- return this._socket._writableState.length + this._sender._bufferedBytes;
5159
- }
5160
- /**
5161
- * @type {String}
5162
- */
5163
- get extensions() {
5164
- return Object.keys(this._extensions).join();
5165
- }
5166
- /**
5167
- * @type {Boolean}
5168
- */
5169
- get isPaused() {
5170
- return this._paused;
5171
- }
5172
- /**
5173
- * @type {Function}
5174
- */
5175
- /* istanbul ignore next */
5176
- get onclose() {
5177
- return null;
5178
- }
5179
- /**
5180
- * @type {Function}
5181
- */
5182
- /* istanbul ignore next */
5183
- get onerror() {
5184
- return null;
5185
- }
5186
- /**
5187
- * @type {Function}
5188
- */
5189
- /* istanbul ignore next */
5190
- get onopen() {
5191
- return null;
5192
- }
5193
- /**
5194
- * @type {Function}
5195
- */
5196
- /* istanbul ignore next */
5197
- get onmessage() {
5198
- return null;
5199
- }
5200
- /**
5201
- * @type {String}
5202
- */
5203
- get protocol() {
5204
- return this._protocol;
5205
- }
5206
- /**
5207
- * @type {Number}
5208
- */
5209
- get readyState() {
5210
- return this._readyState;
5211
- }
5212
- /**
5213
- * @type {String}
5214
- */
5215
- get url() {
5216
- return this._url;
5217
- }
5218
- /**
5219
- * Set up the socket and the internal resources.
5220
- *
5221
- * @param {Duplex} socket The network socket between the server and client
5222
- * @param {Buffer} head The first packet of the upgraded stream
5223
- * @param {Object} options Options object
5224
- * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
5225
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
5226
- * multiple times in the same tick
5227
- * @param {Function} [options.generateMask] The function used to generate the
5228
- * masking key
5229
- * @param {Number} [options.maxPayload=0] The maximum allowed message size
5230
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
5231
- * not to skip UTF-8 validation for text and close messages
5232
- * @private
5233
- */
5234
- setSocket(socket, head, options) {
5235
- const receiver = new Receiver2({
5236
- allowSynchronousEvents: options.allowSynchronousEvents,
5237
- binaryType: this.binaryType,
5238
- extensions: this._extensions,
5239
- isServer: this._isServer,
5240
- maxPayload: options.maxPayload,
5241
- skipUTF8Validation: options.skipUTF8Validation
5242
- });
5243
- const sender = new Sender2(socket, this._extensions, options.generateMask);
5244
- this._receiver = receiver;
5245
- this._sender = sender;
5246
- this._socket = socket;
5247
- receiver[kWebSocket] = this;
5248
- sender[kWebSocket] = this;
5249
- socket[kWebSocket] = this;
5250
- receiver.on("conclude", receiverOnConclude);
5251
- receiver.on("drain", receiverOnDrain);
5252
- receiver.on("error", receiverOnError);
5253
- receiver.on("message", receiverOnMessage);
5254
- receiver.on("ping", receiverOnPing);
5255
- receiver.on("pong", receiverOnPong);
5256
- sender.onerror = senderOnError;
5257
- if (socket.setTimeout) socket.setTimeout(0);
5258
- if (socket.setNoDelay) socket.setNoDelay();
5259
- if (head.length > 0) socket.unshift(head);
5260
- socket.on("close", socketOnClose);
5261
- socket.on("data", socketOnData);
5262
- socket.on("end", socketOnEnd);
5263
- socket.on("error", socketOnError);
5264
- this._readyState = _WebSocket.OPEN;
5265
- this.emit("open");
5266
- }
5267
- /**
5268
- * Emit the `'close'` event.
5269
- *
5270
- * @private
5271
- */
5272
- emitClose() {
5273
- if (!this._socket) {
5274
- this._readyState = _WebSocket.CLOSED;
5275
- this.emit("close", this._closeCode, this._closeMessage);
5276
- return;
5277
- }
5278
- if (this._extensions[PerMessageDeflate2.extensionName]) {
5279
- this._extensions[PerMessageDeflate2.extensionName].cleanup();
5280
- }
5281
- this._receiver.removeAllListeners();
5282
- this._readyState = _WebSocket.CLOSED;
5283
- this.emit("close", this._closeCode, this._closeMessage);
5284
- }
5285
- /**
5286
- * Start a closing handshake.
5287
- *
5288
- * +----------+ +-----------+ +----------+
5289
- * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
5290
- * | +----------+ +-----------+ +----------+ |
5291
- * +----------+ +-----------+ |
5292
- * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
5293
- * +----------+ +-----------+ |
5294
- * | | | +---+ |
5295
- * +------------------------+-->|fin| - - - -
5296
- * | +---+ | +---+
5297
- * - - - - -|fin|<---------------------+
5298
- * +---+
5299
- *
5300
- * @param {Number} [code] Status code explaining why the connection is closing
5301
- * @param {(String|Buffer)} [data] The reason why the connection is
5302
- * closing
5303
- * @public
5304
- */
5305
- close(code, data) {
5306
- if (this.readyState === _WebSocket.CLOSED) return;
5307
- if (this.readyState === _WebSocket.CONNECTING) {
5308
- const msg = "WebSocket was closed before the connection was established";
5309
- abortHandshake(this, this._req, msg);
5310
- return;
5311
- }
5312
- if (this.readyState === _WebSocket.CLOSING) {
5313
- if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
5314
- this._socket.end();
5315
- }
5316
- return;
5317
- }
5318
- this._readyState = _WebSocket.CLOSING;
5319
- this._sender.close(code, data, !this._isServer, (err) => {
5320
- if (err) return;
5321
- this._closeFrameSent = true;
5322
- if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
5323
- this._socket.end();
5324
- }
5325
- });
5326
- setCloseTimer(this);
5327
- }
5328
- /**
5329
- * Pause the socket.
5330
- *
5331
- * @public
5332
- */
5333
- pause() {
5334
- if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
5335
- return;
5336
- }
5337
- this._paused = true;
5338
- this._socket.pause();
5339
- }
5340
- /**
5341
- * Send a ping.
5342
- *
5343
- * @param {*} [data] The data to send
5344
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
5345
- * @param {Function} [cb] Callback which is executed when the ping is sent
5346
- * @public
5347
- */
5348
- ping(data, mask, cb) {
5349
- if (this.readyState === _WebSocket.CONNECTING) {
5350
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
5351
- }
5352
- if (typeof data === "function") {
5353
- cb = data;
5354
- data = mask = void 0;
5355
- } else if (typeof mask === "function") {
5356
- cb = mask;
5357
- mask = void 0;
5358
- }
5359
- if (typeof data === "number") data = data.toString();
5360
- if (this.readyState !== _WebSocket.OPEN) {
5361
- sendAfterClose(this, data, cb);
5362
- return;
5363
- }
5364
- if (mask === void 0) mask = !this._isServer;
5365
- this._sender.ping(data || EMPTY_BUFFER, mask, cb);
5366
- }
5367
- /**
5368
- * Send a pong.
5369
- *
5370
- * @param {*} [data] The data to send
5371
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
5372
- * @param {Function} [cb] Callback which is executed when the pong is sent
5373
- * @public
5374
- */
5375
- pong(data, mask, cb) {
5376
- if (this.readyState === _WebSocket.CONNECTING) {
5377
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
5378
- }
5379
- if (typeof data === "function") {
5380
- cb = data;
5381
- data = mask = void 0;
5382
- } else if (typeof mask === "function") {
5383
- cb = mask;
5384
- mask = void 0;
5385
- }
5386
- if (typeof data === "number") data = data.toString();
5387
- if (this.readyState !== _WebSocket.OPEN) {
5388
- sendAfterClose(this, data, cb);
5389
- return;
5390
- }
5391
- if (mask === void 0) mask = !this._isServer;
5392
- this._sender.pong(data || EMPTY_BUFFER, mask, cb);
5393
- }
5394
- /**
5395
- * Resume the socket.
5396
- *
5397
- * @public
5398
- */
5399
- resume() {
5400
- if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
5401
- return;
5402
- }
5403
- this._paused = false;
5404
- if (!this._receiver._writableState.needDrain) this._socket.resume();
5405
- }
5406
- /**
5407
- * Send a data message.
5408
- *
5409
- * @param {*} data The message to send
5410
- * @param {Object} [options] Options object
5411
- * @param {Boolean} [options.binary] Specifies whether `data` is binary or
5412
- * text
5413
- * @param {Boolean} [options.compress] Specifies whether or not to compress
5414
- * `data`
5415
- * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
5416
- * last one
5417
- * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
5418
- * @param {Function} [cb] Callback which is executed when data is written out
5419
- * @public
5420
- */
5421
- send(data, options, cb) {
5422
- if (this.readyState === _WebSocket.CONNECTING) {
5423
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
5424
- }
5425
- if (typeof options === "function") {
5426
- cb = options;
5427
- options = {};
5428
- }
5429
- if (typeof data === "number") data = data.toString();
5430
- if (this.readyState !== _WebSocket.OPEN) {
5431
- sendAfterClose(this, data, cb);
5432
- return;
5433
- }
5434
- const opts = {
5435
- binary: typeof data !== "string",
5436
- mask: !this._isServer,
5437
- compress: true,
5438
- fin: true,
5439
- ...options
5440
- };
5441
- if (!this._extensions[PerMessageDeflate2.extensionName]) {
5442
- opts.compress = false;
5443
- }
5444
- this._sender.send(data || EMPTY_BUFFER, opts, cb);
5445
- }
5446
- /**
5447
- * Forcibly close the connection.
5448
- *
5449
- * @public
5450
- */
5451
- terminate() {
5452
- if (this.readyState === _WebSocket.CLOSED) return;
5453
- if (this.readyState === _WebSocket.CONNECTING) {
5454
- const msg = "WebSocket was closed before the connection was established";
5455
- abortHandshake(this, this._req, msg);
5456
- return;
5457
- }
5458
- if (this._socket) {
5459
- this._readyState = _WebSocket.CLOSING;
5460
- this._socket.destroy();
5461
- }
5462
- }
5463
- };
5464
- Object.defineProperty(WebSocket2, "CONNECTING", {
5465
- enumerable: true,
5466
- value: readyStates.indexOf("CONNECTING")
5467
- });
5468
- Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
5469
- enumerable: true,
5470
- value: readyStates.indexOf("CONNECTING")
5471
- });
5472
- Object.defineProperty(WebSocket2, "OPEN", {
5473
- enumerable: true,
5474
- value: readyStates.indexOf("OPEN")
5475
- });
5476
- Object.defineProperty(WebSocket2.prototype, "OPEN", {
5477
- enumerable: true,
5478
- value: readyStates.indexOf("OPEN")
5479
- });
5480
- Object.defineProperty(WebSocket2, "CLOSING", {
5481
- enumerable: true,
5482
- value: readyStates.indexOf("CLOSING")
5483
- });
5484
- Object.defineProperty(WebSocket2.prototype, "CLOSING", {
5485
- enumerable: true,
5486
- value: readyStates.indexOf("CLOSING")
5487
- });
5488
- Object.defineProperty(WebSocket2, "CLOSED", {
5489
- enumerable: true,
5490
- value: readyStates.indexOf("CLOSED")
5491
- });
5492
- Object.defineProperty(WebSocket2.prototype, "CLOSED", {
5493
- enumerable: true,
5494
- value: readyStates.indexOf("CLOSED")
5495
- });
5496
- [
5497
- "binaryType",
5498
- "bufferedAmount",
5499
- "extensions",
5500
- "isPaused",
5501
- "protocol",
5502
- "readyState",
5503
- "url"
5504
- ].forEach((property) => {
5505
- Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
5506
- });
5507
- ["open", "error", "close", "message"].forEach((method) => {
5508
- Object.defineProperty(WebSocket2.prototype, `on${method}`, {
5509
- enumerable: true,
5510
- get() {
5511
- for (const listener of this.listeners(method)) {
5512
- if (listener[kForOnEventAttribute]) return listener[kListener];
5513
- }
5514
- return null;
5515
- },
5516
- set(handler) {
5517
- for (const listener of this.listeners(method)) {
5518
- if (listener[kForOnEventAttribute]) {
5519
- this.removeListener(method, listener);
5520
- break;
5521
- }
5522
- }
5523
- if (typeof handler !== "function") return;
5524
- this.addEventListener(method, handler, {
5525
- [kForOnEventAttribute]: true
5526
- });
5527
- }
5528
- });
5529
- });
5530
- WebSocket2.prototype.addEventListener = addEventListener;
5531
- WebSocket2.prototype.removeEventListener = removeEventListener;
5532
- module.exports = WebSocket2;
5533
- function initAsClient(websocket, address, protocols, options) {
5534
- const opts = {
5535
- allowSynchronousEvents: true,
5536
- autoPong: true,
5537
- closeTimeout: CLOSE_TIMEOUT,
5538
- protocolVersion: protocolVersions[1],
5539
- maxPayload: 100 * 1024 * 1024,
5540
- skipUTF8Validation: false,
5541
- perMessageDeflate: true,
5542
- followRedirects: false,
5543
- maxRedirects: 10,
5544
- ...options,
5545
- socketPath: void 0,
5546
- hostname: void 0,
5547
- protocol: void 0,
5548
- timeout: void 0,
5549
- method: "GET",
5550
- host: void 0,
5551
- path: void 0,
5552
- port: void 0
5553
- };
5554
- websocket._autoPong = opts.autoPong;
5555
- websocket._closeTimeout = opts.closeTimeout;
5556
- if (!protocolVersions.includes(opts.protocolVersion)) {
5557
- throw new RangeError(
5558
- `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
5559
- );
5560
- }
5561
- let parsedUrl;
5562
- if (address instanceof URL) {
5563
- parsedUrl = address;
5564
- } else {
5565
- try {
5566
- parsedUrl = new URL(address);
5567
- } catch {
5568
- throw new SyntaxError(`Invalid URL: ${address}`);
5569
- }
5570
- }
5571
- if (parsedUrl.protocol === "http:") {
5572
- parsedUrl.protocol = "ws:";
5573
- } else if (parsedUrl.protocol === "https:") {
5574
- parsedUrl.protocol = "wss:";
5575
- }
5576
- websocket._url = parsedUrl.href;
5577
- const isSecure = parsedUrl.protocol === "wss:";
5578
- const isIpcUrl = parsedUrl.protocol === "ws+unix:";
5579
- let invalidUrlMessage;
5580
- if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
5581
- invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
5582
- } else if (isIpcUrl && !parsedUrl.pathname) {
5583
- invalidUrlMessage = "The URL's pathname is empty";
5584
- } else if (parsedUrl.hash) {
5585
- invalidUrlMessage = "The URL contains a fragment identifier";
5586
- }
5587
- if (invalidUrlMessage) {
5588
- const err = new SyntaxError(invalidUrlMessage);
5589
- if (websocket._redirects === 0) {
5590
- throw err;
5591
- } else {
5592
- emitErrorAndClose(websocket, err);
5593
- return;
5594
- }
5595
- }
5596
- const defaultPort = isSecure ? 443 : 80;
5597
- const key = randomBytes(16).toString("base64");
5598
- const request = isSecure ? https.request : http.request;
5599
- const protocolSet = /* @__PURE__ */ new Set();
5600
- let perMessageDeflate;
5601
- opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
5602
- opts.defaultPort = opts.defaultPort || defaultPort;
5603
- opts.port = parsedUrl.port || defaultPort;
5604
- opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
5605
- opts.headers = {
5606
- ...opts.headers,
5607
- "Sec-WebSocket-Version": opts.protocolVersion,
5608
- "Sec-WebSocket-Key": key,
5609
- Connection: "Upgrade",
5610
- Upgrade: "websocket"
5611
- };
5612
- opts.path = parsedUrl.pathname + parsedUrl.search;
5613
- opts.timeout = opts.handshakeTimeout;
5614
- if (opts.perMessageDeflate) {
5615
- perMessageDeflate = new PerMessageDeflate2({
5616
- ...opts.perMessageDeflate,
5617
- isServer: false,
5618
- maxPayload: opts.maxPayload
5619
- });
5620
- opts.headers["Sec-WebSocket-Extensions"] = format({
5621
- [PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
5622
- });
5623
- }
5624
- if (protocols.length) {
5625
- for (const protocol of protocols) {
5626
- if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
5627
- throw new SyntaxError(
5628
- "An invalid or duplicated subprotocol was specified"
5629
- );
5630
- }
5631
- protocolSet.add(protocol);
5632
- }
5633
- opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
5634
- }
5635
- if (opts.origin) {
5636
- if (opts.protocolVersion < 13) {
5637
- opts.headers["Sec-WebSocket-Origin"] = opts.origin;
5638
- } else {
5639
- opts.headers.Origin = opts.origin;
5640
- }
5641
- }
5642
- if (parsedUrl.username || parsedUrl.password) {
5643
- opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
5644
- }
5645
- if (isIpcUrl) {
5646
- const parts = opts.path.split(":");
5647
- opts.socketPath = parts[0];
5648
- opts.path = parts[1];
5649
- }
5650
- let req;
5651
- if (opts.followRedirects) {
5652
- if (websocket._redirects === 0) {
5653
- websocket._originalIpc = isIpcUrl;
5654
- websocket._originalSecure = isSecure;
5655
- websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
5656
- const headers = options && options.headers;
5657
- options = { ...options, headers: {} };
5658
- if (headers) {
5659
- for (const [key2, value] of Object.entries(headers)) {
5660
- options.headers[key2.toLowerCase()] = value;
5661
- }
5662
- }
5663
- } else if (websocket.listenerCount("redirect") === 0) {
5664
- const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
5665
- if (!isSameHost || websocket._originalSecure && !isSecure) {
5666
- delete opts.headers.authorization;
5667
- delete opts.headers.cookie;
5668
- if (!isSameHost) delete opts.headers.host;
5669
- opts.auth = void 0;
5670
- }
5671
- }
5672
- if (opts.auth && !options.headers.authorization) {
5673
- options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
5674
- }
5675
- req = websocket._req = request(opts);
5676
- if (websocket._redirects) {
5677
- websocket.emit("redirect", websocket.url, req);
5678
- }
5679
- } else {
5680
- req = websocket._req = request(opts);
5681
- }
5682
- if (opts.timeout) {
5683
- req.on("timeout", () => {
5684
- abortHandshake(websocket, req, "Opening handshake has timed out");
5685
- });
5686
- }
5687
- req.on("error", (err) => {
5688
- if (req === null || req[kAborted]) return;
5689
- req = websocket._req = null;
5690
- emitErrorAndClose(websocket, err);
5691
- });
5692
- req.on("response", (res) => {
5693
- const location = res.headers.location;
5694
- const statusCode = res.statusCode;
5695
- if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
5696
- if (++websocket._redirects > opts.maxRedirects) {
5697
- abortHandshake(websocket, req, "Maximum redirects exceeded");
5698
- return;
5699
- }
5700
- req.abort();
5701
- let addr;
5702
- try {
5703
- addr = new URL(location, address);
5704
- } catch (e) {
5705
- const err = new SyntaxError(`Invalid URL: ${location}`);
5706
- emitErrorAndClose(websocket, err);
5707
- return;
5708
- }
5709
- initAsClient(websocket, addr, protocols, options);
5710
- } else if (!websocket.emit("unexpected-response", req, res)) {
5711
- abortHandshake(
5712
- websocket,
5713
- req,
5714
- `Unexpected server response: ${res.statusCode}`
5715
- );
5716
- }
5717
- });
5718
- req.on("upgrade", (res, socket, head) => {
5719
- websocket.emit("upgrade", res);
5720
- if (websocket.readyState !== WebSocket2.CONNECTING) return;
5721
- req = websocket._req = null;
5722
- const upgrade = res.headers.upgrade;
5723
- if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
5724
- abortHandshake(websocket, socket, "Invalid Upgrade header");
5725
- return;
5726
- }
5727
- const digest = createHash("sha1").update(key + GUID).digest("base64");
5728
- if (res.headers["sec-websocket-accept"] !== digest) {
5729
- abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
5730
- return;
5731
- }
5732
- const serverProt = res.headers["sec-websocket-protocol"];
5733
- let protError;
5734
- if (serverProt !== void 0) {
5735
- if (!protocolSet.size) {
5736
- protError = "Server sent a subprotocol but none was requested";
5737
- } else if (!protocolSet.has(serverProt)) {
5738
- protError = "Server sent an invalid subprotocol";
5739
- }
5740
- } else if (protocolSet.size) {
5741
- protError = "Server sent no subprotocol";
5742
- }
5743
- if (protError) {
5744
- abortHandshake(websocket, socket, protError);
5745
- return;
5746
- }
5747
- if (serverProt) websocket._protocol = serverProt;
5748
- const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
5749
- if (secWebSocketExtensions !== void 0) {
5750
- if (!perMessageDeflate) {
5751
- const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
5752
- abortHandshake(websocket, socket, message);
5753
- return;
5754
- }
5755
- let extensions;
5756
- try {
5757
- extensions = parse(secWebSocketExtensions);
5758
- } catch (err) {
5759
- const message = "Invalid Sec-WebSocket-Extensions header";
5760
- abortHandshake(websocket, socket, message);
5761
- return;
5762
- }
5763
- const extensionNames = Object.keys(extensions);
5764
- if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
5765
- const message = "Server indicated an extension that was not requested";
5766
- abortHandshake(websocket, socket, message);
5767
- return;
5768
- }
5769
- try {
5770
- perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
5771
- } catch (err) {
5772
- const message = "Invalid Sec-WebSocket-Extensions header";
5773
- abortHandshake(websocket, socket, message);
5774
- return;
5775
- }
5776
- websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
5777
- }
5778
- websocket.setSocket(socket, head, {
5779
- allowSynchronousEvents: opts.allowSynchronousEvents,
5780
- generateMask: opts.generateMask,
5781
- maxPayload: opts.maxPayload,
5782
- skipUTF8Validation: opts.skipUTF8Validation
5783
- });
5784
- });
5785
- if (opts.finishRequest) {
5786
- opts.finishRequest(req, websocket);
5787
- } else {
5788
- req.end();
5789
- }
5790
- }
5791
- function emitErrorAndClose(websocket, err) {
5792
- websocket._readyState = WebSocket2.CLOSING;
5793
- websocket._errorEmitted = true;
5794
- websocket.emit("error", err);
5795
- websocket.emitClose();
5796
- }
5797
- function netConnect(options) {
5798
- options.path = options.socketPath;
5799
- return net.connect(options);
5800
- }
5801
- function tlsConnect(options) {
5802
- options.path = void 0;
5803
- if (!options.servername && options.servername !== "") {
5804
- options.servername = net.isIP(options.host) ? "" : options.host;
5805
- }
5806
- return tls.connect(options);
5807
- }
5808
- function abortHandshake(websocket, stream, message) {
5809
- websocket._readyState = WebSocket2.CLOSING;
5810
- const err = new Error(message);
5811
- Error.captureStackTrace(err, abortHandshake);
5812
- if (stream.setHeader) {
5813
- stream[kAborted] = true;
5814
- stream.abort();
5815
- if (stream.socket && !stream.socket.destroyed) {
5816
- stream.socket.destroy();
5817
- }
5818
- process.nextTick(emitErrorAndClose, websocket, err);
5819
- } else {
5820
- stream.destroy(err);
5821
- stream.once("error", websocket.emit.bind(websocket, "error"));
5822
- stream.once("close", websocket.emitClose.bind(websocket));
5823
- }
5824
- }
5825
- function sendAfterClose(websocket, data, cb) {
5826
- if (data) {
5827
- const length = isBlob(data) ? data.size : toBuffer(data).length;
5828
- if (websocket._socket) websocket._sender._bufferedBytes += length;
5829
- else websocket._bufferedAmount += length;
5830
- }
5831
- if (cb) {
5832
- const err = new Error(
5833
- `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
5834
- );
5835
- process.nextTick(cb, err);
5836
- }
5837
- }
5838
- function receiverOnConclude(code, reason) {
5839
- const websocket = this[kWebSocket];
5840
- websocket._closeFrameReceived = true;
5841
- websocket._closeMessage = reason;
5842
- websocket._closeCode = code;
5843
- if (websocket._socket[kWebSocket] === void 0) return;
5844
- websocket._socket.removeListener("data", socketOnData);
5845
- process.nextTick(resume, websocket._socket);
5846
- if (code === 1005) websocket.close();
5847
- else websocket.close(code, reason);
5848
- }
5849
- function receiverOnDrain() {
5850
- const websocket = this[kWebSocket];
5851
- if (!websocket.isPaused) websocket._socket.resume();
5852
- }
5853
- function receiverOnError(err) {
5854
- const websocket = this[kWebSocket];
5855
- if (websocket._socket[kWebSocket] !== void 0) {
5856
- websocket._socket.removeListener("data", socketOnData);
5857
- process.nextTick(resume, websocket._socket);
5858
- websocket.close(err[kStatusCode]);
5859
- }
5860
- if (!websocket._errorEmitted) {
5861
- websocket._errorEmitted = true;
5862
- websocket.emit("error", err);
5863
- }
5864
- }
5865
- function receiverOnFinish() {
5866
- this[kWebSocket].emitClose();
5867
- }
5868
- function receiverOnMessage(data, isBinary) {
5869
- this[kWebSocket].emit("message", data, isBinary);
5870
- }
5871
- function receiverOnPing(data) {
5872
- const websocket = this[kWebSocket];
5873
- if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
5874
- websocket.emit("ping", data);
5875
- }
5876
- function receiverOnPong(data) {
5877
- this[kWebSocket].emit("pong", data);
5878
- }
5879
- function resume(stream) {
5880
- stream.resume();
5881
- }
5882
- function senderOnError(err) {
5883
- const websocket = this[kWebSocket];
5884
- if (websocket.readyState === WebSocket2.CLOSED) return;
5885
- if (websocket.readyState === WebSocket2.OPEN) {
5886
- websocket._readyState = WebSocket2.CLOSING;
5887
- setCloseTimer(websocket);
5888
- }
5889
- this._socket.end();
5890
- if (!websocket._errorEmitted) {
5891
- websocket._errorEmitted = true;
5892
- websocket.emit("error", err);
5893
- }
5894
- }
5895
- function setCloseTimer(websocket) {
5896
- websocket._closeTimer = setTimeout(
5897
- websocket._socket.destroy.bind(websocket._socket),
5898
- websocket._closeTimeout
5899
- );
5900
- }
5901
- function socketOnClose() {
5902
- const websocket = this[kWebSocket];
5903
- this.removeListener("close", socketOnClose);
5904
- this.removeListener("data", socketOnData);
5905
- this.removeListener("end", socketOnEnd);
5906
- websocket._readyState = WebSocket2.CLOSING;
5907
- if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
5908
- const chunk = this.read(this._readableState.length);
5909
- websocket._receiver.write(chunk);
5910
- }
5911
- websocket._receiver.end();
5912
- this[kWebSocket] = void 0;
5913
- clearTimeout(websocket._closeTimer);
5914
- if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
5915
- websocket.emitClose();
5916
- } else {
5917
- websocket._receiver.on("error", receiverOnFinish);
5918
- websocket._receiver.on("finish", receiverOnFinish);
5919
- }
5920
- }
5921
- function socketOnData(chunk) {
5922
- if (!this[kWebSocket]._receiver.write(chunk)) {
5923
- this.pause();
5924
- }
5925
- }
5926
- function socketOnEnd() {
5927
- const websocket = this[kWebSocket];
5928
- websocket._readyState = WebSocket2.CLOSING;
5929
- websocket._receiver.end();
5930
- this.end();
5931
- }
5932
- function socketOnError() {
5933
- const websocket = this[kWebSocket];
5934
- this.removeListener("error", socketOnError);
5935
- this.on("error", NOOP);
5936
- if (websocket) {
5937
- websocket._readyState = WebSocket2.CLOSING;
5938
- this.destroy();
5939
- }
5940
- }
5941
- }
5942
- });
5943
-
5944
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/stream.js
5945
- var require_stream = __commonJS({
5946
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/stream.js"(exports, module) {
5947
- "use strict";
5948
- var WebSocket2 = require_websocket();
5949
- var { Duplex } = __require("stream");
5950
- function emitClose(stream) {
5951
- stream.emit("close");
5952
- }
5953
- function duplexOnEnd() {
5954
- if (!this.destroyed && this._writableState.finished) {
5955
- this.destroy();
5956
- }
5957
- }
5958
- function duplexOnError(err) {
5959
- this.removeListener("error", duplexOnError);
5960
- this.destroy();
5961
- if (this.listenerCount("error") === 0) {
5962
- this.emit("error", err);
5963
- }
5964
- }
5965
- function createWebSocketStream2(ws, options) {
5966
- let terminateOnDestroy = true;
5967
- const duplex = new Duplex({
5968
- ...options,
5969
- autoDestroy: false,
5970
- emitClose: false,
5971
- objectMode: false,
5972
- writableObjectMode: false
5973
- });
5974
- ws.on("message", function message(msg, isBinary) {
5975
- const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
5976
- if (!duplex.push(data)) ws.pause();
5977
- });
5978
- ws.once("error", function error(err) {
5979
- if (duplex.destroyed) return;
5980
- terminateOnDestroy = false;
5981
- duplex.destroy(err);
5982
- });
5983
- ws.once("close", function close() {
5984
- if (duplex.destroyed) return;
5985
- duplex.push(null);
5986
- });
5987
- duplex._destroy = function(err, callback) {
5988
- if (ws.readyState === ws.CLOSED) {
5989
- callback(err);
5990
- process.nextTick(emitClose, duplex);
5991
- return;
5992
- }
5993
- let called = false;
5994
- ws.once("error", function error(err2) {
5995
- called = true;
5996
- callback(err2);
5997
- });
5998
- ws.once("close", function close() {
5999
- if (!called) callback(err);
6000
- process.nextTick(emitClose, duplex);
6001
- });
6002
- if (terminateOnDestroy) ws.terminate();
6003
- };
6004
- duplex._final = function(callback) {
6005
- if (ws.readyState === ws.CONNECTING) {
6006
- ws.once("open", function open() {
6007
- duplex._final(callback);
6008
- });
6009
- return;
6010
- }
6011
- if (ws._socket === null) return;
6012
- if (ws._socket._writableState.finished) {
6013
- callback();
6014
- if (duplex._readableState.endEmitted) duplex.destroy();
6015
- } else {
6016
- ws._socket.once("finish", function finish() {
6017
- callback();
6018
- });
6019
- ws.close();
6020
- }
6021
- };
6022
- duplex._read = function() {
6023
- if (ws.isPaused) ws.resume();
6024
- };
6025
- duplex._write = function(chunk, encoding, callback) {
6026
- if (ws.readyState === ws.CONNECTING) {
6027
- ws.once("open", function open() {
6028
- duplex._write(chunk, encoding, callback);
6029
- });
6030
- return;
6031
- }
6032
- ws.send(chunk, callback);
6033
- };
6034
- duplex.on("end", duplexOnEnd);
6035
- duplex.on("error", duplexOnError);
6036
- return duplex;
6037
- }
6038
- module.exports = createWebSocketStream2;
6039
- }
6040
- });
6041
-
6042
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/subprotocol.js
6043
- var require_subprotocol = __commonJS({
6044
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/subprotocol.js"(exports, module) {
6045
- "use strict";
6046
- var { tokenChars } = require_validation();
6047
- function parse(header) {
6048
- const protocols = /* @__PURE__ */ new Set();
6049
- let start = -1;
6050
- let end = -1;
6051
- let i = 0;
6052
- for (i; i < header.length; i++) {
6053
- const code = header.charCodeAt(i);
6054
- if (end === -1 && tokenChars[code] === 1) {
6055
- if (start === -1) start = i;
6056
- } else if (i !== 0 && (code === 32 || code === 9)) {
6057
- if (end === -1 && start !== -1) end = i;
6058
- } else if (code === 44) {
6059
- if (start === -1) {
6060
- throw new SyntaxError(`Unexpected character at index ${i}`);
6061
- }
6062
- if (end === -1) end = i;
6063
- const protocol2 = header.slice(start, end);
6064
- if (protocols.has(protocol2)) {
6065
- throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
6066
- }
6067
- protocols.add(protocol2);
6068
- start = end = -1;
6069
- } else {
6070
- throw new SyntaxError(`Unexpected character at index ${i}`);
6071
- }
6072
- }
6073
- if (start === -1 || end !== -1) {
6074
- throw new SyntaxError("Unexpected end of input");
6075
- }
6076
- const protocol = header.slice(start, i);
6077
- if (protocols.has(protocol)) {
6078
- throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
6079
- }
6080
- protocols.add(protocol);
6081
- return protocols;
6082
- }
6083
- module.exports = { parse };
6084
- }
6085
- });
6086
-
6087
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket-server.js
6088
- var require_websocket_server = __commonJS({
6089
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket-server.js"(exports, module) {
6090
- "use strict";
6091
- var EventEmitter = __require("events");
6092
- var http = __require("http");
6093
- var { Duplex } = __require("stream");
6094
- var { createHash } = __require("crypto");
6095
- var extension2 = require_extension();
6096
- var PerMessageDeflate2 = require_permessage_deflate();
6097
- var subprotocol2 = require_subprotocol();
6098
- var WebSocket2 = require_websocket();
6099
- var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
6100
- var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
6101
- var RUNNING = 0;
6102
- var CLOSING = 1;
6103
- var CLOSED = 2;
6104
- var WebSocketServer2 = class extends EventEmitter {
6105
- /**
6106
- * Create a `WebSocketServer` instance.
6107
- *
6108
- * @param {Object} options Configuration options
6109
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
6110
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
6111
- * multiple times in the same tick
6112
- * @param {Boolean} [options.autoPong=true] Specifies whether or not to
6113
- * automatically send a pong in response to a ping
6114
- * @param {Number} [options.backlog=511] The maximum length of the queue of
6115
- * pending connections
6116
- * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
6117
- * track clients
6118
- * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
6119
- * wait for the closing handshake to finish after `websocket.close()` is
6120
- * called
6121
- * @param {Function} [options.handleProtocols] A hook to handle protocols
6122
- * @param {String} [options.host] The hostname where to bind the server
6123
- * @param {Number} [options.maxPayload=104857600] The maximum allowed message
6124
- * size
6125
- * @param {Boolean} [options.noServer=false] Enable no server mode
6126
- * @param {String} [options.path] Accept only connections matching this path
6127
- * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
6128
- * permessage-deflate
6129
- * @param {Number} [options.port] The port where to bind the server
6130
- * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
6131
- * server to use
6132
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
6133
- * not to skip UTF-8 validation for text and close messages
6134
- * @param {Function} [options.verifyClient] A hook to reject connections
6135
- * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
6136
- * class to use. It must be the `WebSocket` class or class that extends it
6137
- * @param {Function} [callback] A listener for the `listening` event
6138
- */
6139
- constructor(options, callback) {
6140
- super();
6141
- options = {
6142
- allowSynchronousEvents: true,
6143
- autoPong: true,
6144
- maxPayload: 100 * 1024 * 1024,
6145
- skipUTF8Validation: false,
6146
- perMessageDeflate: false,
6147
- handleProtocols: null,
6148
- clientTracking: true,
6149
- closeTimeout: CLOSE_TIMEOUT,
6150
- verifyClient: null,
6151
- noServer: false,
6152
- backlog: null,
6153
- // use default (511 as implemented in net.js)
6154
- server: null,
6155
- host: null,
6156
- path: null,
6157
- port: null,
6158
- WebSocket: WebSocket2,
6159
- ...options
6160
- };
6161
- if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
6162
- throw new TypeError(
6163
- 'One and only one of the "port", "server", or "noServer" options must be specified'
6164
- );
6165
- }
6166
- if (options.port != null) {
6167
- this._server = http.createServer((req, res) => {
6168
- const body = http.STATUS_CODES[426];
6169
- res.writeHead(426, {
6170
- "Content-Length": body.length,
6171
- "Content-Type": "text/plain"
6172
- });
6173
- res.end(body);
6174
- });
6175
- this._server.listen(
6176
- options.port,
6177
- options.host,
6178
- options.backlog,
6179
- callback
6180
- );
6181
- } else if (options.server) {
6182
- this._server = options.server;
6183
- }
6184
- if (this._server) {
6185
- const emitConnection = this.emit.bind(this, "connection");
6186
- this._removeListeners = addListeners(this._server, {
6187
- listening: this.emit.bind(this, "listening"),
6188
- error: this.emit.bind(this, "error"),
6189
- upgrade: (req, socket, head) => {
6190
- this.handleUpgrade(req, socket, head, emitConnection);
6191
- }
6192
- });
6193
- }
6194
- if (options.perMessageDeflate === true) options.perMessageDeflate = {};
6195
- if (options.clientTracking) {
6196
- this.clients = /* @__PURE__ */ new Set();
6197
- this._shouldEmitClose = false;
6198
- }
6199
- this.options = options;
6200
- this._state = RUNNING;
6201
- }
6202
- /**
6203
- * Returns the bound address, the address family name, and port of the server
6204
- * as reported by the operating system if listening on an IP socket.
6205
- * If the server is listening on a pipe or UNIX domain socket, the name is
6206
- * returned as a string.
6207
- *
6208
- * @return {(Object|String|null)} The address of the server
6209
- * @public
6210
- */
6211
- address() {
6212
- if (this.options.noServer) {
6213
- throw new Error('The server is operating in "noServer" mode');
6214
- }
6215
- if (!this._server) return null;
6216
- return this._server.address();
6217
- }
6218
- /**
6219
- * Stop the server from accepting new connections and emit the `'close'` event
6220
- * when all existing connections are closed.
6221
- *
6222
- * @param {Function} [cb] A one-time listener for the `'close'` event
6223
- * @public
6224
- */
6225
- close(cb) {
6226
- if (this._state === CLOSED) {
6227
- if (cb) {
6228
- this.once("close", () => {
6229
- cb(new Error("The server is not running"));
6230
- });
6231
- }
6232
- process.nextTick(emitClose, this);
6233
- return;
6234
- }
6235
- if (cb) this.once("close", cb);
6236
- if (this._state === CLOSING) return;
6237
- this._state = CLOSING;
6238
- if (this.options.noServer || this.options.server) {
6239
- if (this._server) {
6240
- this._removeListeners();
6241
- this._removeListeners = this._server = null;
6242
- }
6243
- if (this.clients) {
6244
- if (!this.clients.size) {
6245
- process.nextTick(emitClose, this);
6246
- } else {
6247
- this._shouldEmitClose = true;
6248
- }
6249
- } else {
6250
- process.nextTick(emitClose, this);
6251
- }
6252
- } else {
6253
- const server = this._server;
6254
- this._removeListeners();
6255
- this._removeListeners = this._server = null;
6256
- server.close(() => {
6257
- emitClose(this);
6258
- });
6259
- }
6260
- }
6261
- /**
6262
- * See if a given request should be handled by this server instance.
6263
- *
6264
- * @param {http.IncomingMessage} req Request object to inspect
6265
- * @return {Boolean} `true` if the request is valid, else `false`
6266
- * @public
6267
- */
6268
- shouldHandle(req) {
6269
- if (this.options.path) {
6270
- const index = req.url.indexOf("?");
6271
- const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
6272
- if (pathname !== this.options.path) return false;
6273
- }
6274
- return true;
6275
- }
6276
- /**
6277
- * Handle a HTTP Upgrade request.
6278
- *
6279
- * @param {http.IncomingMessage} req The request object
6280
- * @param {Duplex} socket The network socket between the server and client
6281
- * @param {Buffer} head The first packet of the upgraded stream
6282
- * @param {Function} cb Callback
6283
- * @public
6284
- */
6285
- handleUpgrade(req, socket, head, cb) {
6286
- socket.on("error", socketOnError);
6287
- const key = req.headers["sec-websocket-key"];
6288
- const upgrade = req.headers.upgrade;
6289
- const version = +req.headers["sec-websocket-version"];
6290
- if (req.method !== "GET") {
6291
- const message = "Invalid HTTP method";
6292
- abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
6293
- return;
6294
- }
6295
- if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
6296
- const message = "Invalid Upgrade header";
6297
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
6298
- return;
6299
- }
6300
- if (key === void 0 || !keyRegex.test(key)) {
6301
- const message = "Missing or invalid Sec-WebSocket-Key header";
6302
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
6303
- return;
6304
- }
6305
- if (version !== 13 && version !== 8) {
6306
- const message = "Missing or invalid Sec-WebSocket-Version header";
6307
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
6308
- "Sec-WebSocket-Version": "13, 8"
6309
- });
6310
- return;
6311
- }
6312
- if (!this.shouldHandle(req)) {
6313
- abortHandshake(socket, 400);
6314
- return;
6315
- }
6316
- const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
6317
- let protocols = /* @__PURE__ */ new Set();
6318
- if (secWebSocketProtocol !== void 0) {
6319
- try {
6320
- protocols = subprotocol2.parse(secWebSocketProtocol);
6321
- } catch (err) {
6322
- const message = "Invalid Sec-WebSocket-Protocol header";
6323
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
6324
- return;
6325
- }
6326
- }
6327
- const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
6328
- const extensions = {};
6329
- if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
6330
- const perMessageDeflate = new PerMessageDeflate2({
6331
- ...this.options.perMessageDeflate,
6332
- isServer: true,
6333
- maxPayload: this.options.maxPayload
6334
- });
6335
- try {
6336
- const offers = extension2.parse(secWebSocketExtensions);
6337
- if (offers[PerMessageDeflate2.extensionName]) {
6338
- perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
6339
- extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
6340
- }
6341
- } catch (err) {
6342
- const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
6343
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
6344
- return;
6345
- }
6346
- }
6347
- if (this.options.verifyClient) {
6348
- const info = {
6349
- origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
6350
- secure: !!(req.socket.authorized || req.socket.encrypted),
6351
- req
6352
- };
6353
- if (this.options.verifyClient.length === 2) {
6354
- this.options.verifyClient(info, (verified, code, message, headers) => {
6355
- if (!verified) {
6356
- return abortHandshake(socket, code || 401, message, headers);
6357
- }
6358
- this.completeUpgrade(
6359
- extensions,
6360
- key,
6361
- protocols,
6362
- req,
6363
- socket,
6364
- head,
6365
- cb
6366
- );
6367
- });
6368
- return;
6369
- }
6370
- if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
6371
- }
6372
- this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
6373
- }
6374
- /**
6375
- * Upgrade the connection to WebSocket.
6376
- *
6377
- * @param {Object} extensions The accepted extensions
6378
- * @param {String} key The value of the `Sec-WebSocket-Key` header
6379
- * @param {Set} protocols The subprotocols
6380
- * @param {http.IncomingMessage} req The request object
6381
- * @param {Duplex} socket The network socket between the server and client
6382
- * @param {Buffer} head The first packet of the upgraded stream
6383
- * @param {Function} cb Callback
6384
- * @throws {Error} If called more than once with the same socket
6385
- * @private
6386
- */
6387
- completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
6388
- if (!socket.readable || !socket.writable) return socket.destroy();
6389
- if (socket[kWebSocket]) {
6390
- throw new Error(
6391
- "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
6392
- );
6393
- }
6394
- if (this._state > RUNNING) return abortHandshake(socket, 503);
6395
- const digest = createHash("sha1").update(key + GUID).digest("base64");
6396
- const headers = [
6397
- "HTTP/1.1 101 Switching Protocols",
6398
- "Upgrade: websocket",
6399
- "Connection: Upgrade",
6400
- `Sec-WebSocket-Accept: ${digest}`
6401
- ];
6402
- const ws = new this.options.WebSocket(null, void 0, this.options);
6403
- if (protocols.size) {
6404
- const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
6405
- if (protocol) {
6406
- headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
6407
- ws._protocol = protocol;
6408
- }
6409
- }
6410
- if (extensions[PerMessageDeflate2.extensionName]) {
6411
- const params = extensions[PerMessageDeflate2.extensionName].params;
6412
- const value = extension2.format({
6413
- [PerMessageDeflate2.extensionName]: [params]
6414
- });
6415
- headers.push(`Sec-WebSocket-Extensions: ${value}`);
6416
- ws._extensions = extensions;
6417
- }
6418
- this.emit("headers", headers, req);
6419
- socket.write(headers.concat("\r\n").join("\r\n"));
6420
- socket.removeListener("error", socketOnError);
6421
- ws.setSocket(socket, head, {
6422
- allowSynchronousEvents: this.options.allowSynchronousEvents,
6423
- maxPayload: this.options.maxPayload,
6424
- skipUTF8Validation: this.options.skipUTF8Validation
6425
- });
6426
- if (this.clients) {
6427
- this.clients.add(ws);
6428
- ws.on("close", () => {
6429
- this.clients.delete(ws);
6430
- if (this._shouldEmitClose && !this.clients.size) {
6431
- process.nextTick(emitClose, this);
6432
- }
6433
- });
6434
- }
6435
- cb(ws, req);
6436
- }
6437
- };
6438
- module.exports = WebSocketServer2;
6439
- function addListeners(server, map) {
6440
- for (const event of Object.keys(map)) server.on(event, map[event]);
6441
- return function removeListeners() {
6442
- for (const event of Object.keys(map)) {
6443
- server.removeListener(event, map[event]);
6444
- }
6445
- };
6446
- }
6447
- function emitClose(server) {
6448
- server._state = CLOSED;
6449
- server.emit("close");
6450
- }
6451
- function socketOnError() {
6452
- this.destroy();
6453
- }
6454
- function abortHandshake(socket, code, message, headers) {
6455
- message = message || http.STATUS_CODES[code];
6456
- headers = {
6457
- Connection: "close",
6458
- "Content-Type": "text/html",
6459
- "Content-Length": Buffer.byteLength(message),
6460
- ...headers
6461
- };
6462
- socket.once("finish", socket.destroy);
6463
- socket.end(
6464
- `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
6465
- ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
6466
- );
6467
- }
6468
- function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
6469
- if (server.listenerCount("wsClientError")) {
6470
- const err = new Error(message);
6471
- Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
6472
- server.emit("wsClientError", err, socket, req);
6473
- } else {
6474
- abortHandshake(socket, code, message, headers);
6475
- }
6476
- }
6477
- }
6478
- });
6479
-
6480
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/wrapper.mjs
6481
- var wrapper_exports = {};
6482
- __export(wrapper_exports, {
6483
- PerMessageDeflate: () => import_permessage_deflate.default,
6484
- Receiver: () => import_receiver.default,
6485
- Sender: () => import_sender.default,
6486
- WebSocket: () => import_websocket.default,
6487
- WebSocketServer: () => import_websocket_server.default,
6488
- createWebSocketStream: () => import_stream.default,
6489
- default: () => wrapper_default,
6490
- extension: () => import_extension.default,
6491
- subprotocol: () => import_subprotocol.default
6492
- });
6493
- var import_stream, import_extension, import_permessage_deflate, import_receiver, import_sender, import_subprotocol, import_websocket, import_websocket_server, wrapper_default;
6494
- var init_wrapper = __esm({
6495
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/wrapper.mjs"() {
6496
- import_stream = __toESM(require_stream(), 1);
6497
- import_extension = __toESM(require_extension(), 1);
6498
- import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
6499
- import_receiver = __toESM(require_receiver(), 1);
6500
- import_sender = __toESM(require_sender(), 1);
6501
- import_subprotocol = __toESM(require_subprotocol(), 1);
6502
- import_websocket = __toESM(require_websocket(), 1);
6503
- import_websocket_server = __toESM(require_websocket_server(), 1);
6504
- wrapper_default = import_websocket.default;
6505
- }
6506
- });
6507
-
6508
- // src/scripts/messaging/connect.ts
6509
- import fs10 from "node:fs";
6510
- import debug2 from "debug";
6511
- async function cmdConnect(onMessage, signal) {
6512
- let WebSocketClient;
6513
- try {
6514
- const ws = await Promise.resolve().then(() => (init_wrapper(), wrapper_exports));
6515
- WebSocketClient = ws.default || ws.WebSocket || ws;
6516
- } catch {
6517
- return fail("WebSocket client not available. Install it: npm install ws");
6518
- }
6519
- const { identityKey, privKey } = await loadIdentity();
6520
- const wsUrl = OVERLAY_URL.replace(/^http/, "ws") + "/relay/subscribe?identity=" + identityKey;
6521
- log2("Connecting to WebSocket relay: %s", wsUrl);
6522
- let reconnectDelay = 1e3;
6523
- let shouldReconnect = true;
6524
- let currentWs = null;
6525
- function shutdown() {
6526
- shouldReconnect = false;
6527
- if (currentWs) {
6528
- try {
6529
- currentWs.close();
6530
- } catch {
6531
- }
6532
- }
6533
- if (!onMessage) {
6534
- process.exit(0);
6535
- }
6536
- }
6537
- if (!onMessage) {
6538
- process.on("SIGINT", shutdown);
6539
- process.on("SIGTERM", shutdown);
6540
- }
6541
- if (signal) {
6542
- signal.addEventListener("abort", () => {
6543
- shouldReconnect = false;
6544
- if (currentWs) {
6545
- try {
6546
- currentWs.close();
6547
- } catch {
6548
- }
6549
- }
6550
- });
6551
- }
6552
- function connect() {
6553
- if (signal?.aborted) return;
6554
- const ws = new WebSocketClient(wsUrl);
6555
- currentWs = ws;
6556
- ws.on("open", () => {
6557
- log2("WebSocket connection established!");
6558
- reconnectDelay = 1e3;
6559
- const logMsg = { event: "connected", identity: identityKey, overlay: OVERLAY_URL };
6560
- if (onMessage) onMessage(logMsg);
6561
- else console.error(JSON.stringify(logMsg));
6562
- });
6563
- ws.on("message", async (data) => {
6564
- log2("Incoming WebSocket message received");
6565
- try {
6566
- const envelope = JSON.parse(data.toString());
6567
- log2("Message type: %s", envelope.type);
6568
- if (envelope.type === "message") {
6569
- const result = await processMessage(envelope.message, identityKey, privKey);
6570
- log2("Processed message: %s", result.id);
6571
- if (onMessage) onMessage(result);
6572
- else console.log(JSON.stringify(result));
6573
- ensureStateDir();
6574
- try {
6575
- fs10.appendFileSync(PATHS.notifications, JSON.stringify({ ...result, _ts: Date.now() }) + "\n");
6576
- } catch {
6577
- }
6578
- if (result.ack) {
6579
- try {
6580
- await fetch(OVERLAY_URL + "/relay/ack", {
6581
- method: "POST",
6582
- headers: { "Content-Type": "application/json" },
6583
- body: JSON.stringify({ identity: identityKey, messageIds: [result.id] })
6584
- });
6585
- } catch (ackErr) {
6586
- const log3 = { event: "ack-error", id: result.id, message: String(ackErr) };
6587
- if (onMessage) onMessage(log3);
6588
- else console.error(JSON.stringify(log3));
6589
- }
6590
- }
6591
- }
6592
- if (envelope.type === "service-announced") {
6593
- const svc = envelope.service || {};
6594
- const announcement = {
6595
- event: "service-announced",
6596
- serviceId: svc.serviceId,
6597
- name: svc.name,
6598
- description: svc.description,
6599
- priceSats: svc.pricingSats,
6600
- provider: svc.identityKey,
6601
- txid: envelope.txid,
6602
- _ts: Date.now()
6603
- };
6604
- if (onMessage) onMessage(announcement);
6605
- else console.log(JSON.stringify(announcement));
6606
- ensureStateDir();
6607
- try {
6608
- fs10.appendFileSync(PATHS.notifications, JSON.stringify(announcement) + "\n");
6609
- } catch {
6610
- }
6611
- }
6612
- } catch (err) {
6613
- const log3 = { event: "process-error", message: String(err) };
6614
- if (onMessage) onMessage(log3);
6615
- else console.error(JSON.stringify(log3));
6616
- }
6617
- });
6618
- ws.on("close", () => {
6619
- currentWs = null;
6620
- if (shouldReconnect && !signal?.aborted) {
6621
- const log3 = { event: "disconnected", reconnectMs: reconnectDelay };
6622
- if (onMessage) onMessage(log3);
6623
- else console.error(JSON.stringify(log3));
6624
- setTimeout(connect, reconnectDelay);
6625
- reconnectDelay = Math.min(reconnectDelay * 2, 3e4);
6626
- }
6627
- });
6628
- ws.on("error", (err) => {
6629
- const log3 = { event: "error", message: err.message };
6630
- if (onMessage) onMessage(log3);
6631
- else console.error(JSON.stringify(log3));
6632
- });
6633
- }
6634
- connect();
6635
- return new Promise((resolve) => {
6636
- if (signal) {
6637
- signal.addEventListener("abort", () => resolve());
2961
+ connect();
2962
+ return new Promise((resolve) => {
2963
+ if (signal) {
2964
+ signal.addEventListener("abort", () => resolve());
6638
2965
  }
6639
2966
  });
6640
2967
  }
@@ -6944,12 +3271,7 @@ async function cmdXVerifyComplete(tweetUrl) {
6944
3271
  const tweetId = tweetIdMatch[1];
6945
3272
  let tweetData;
6946
3273
  try {
6947
- const { execSync } = await import("child_process");
6948
- const birdOutput = execSync(`bird read ${tweetUrl} --json 2>/dev/null`, {
6949
- encoding: "utf-8",
6950
- timeout: 3e4
6951
- });
6952
- tweetData = JSON.parse(birdOutput);
3274
+ return fail('X verification via "bird" CLI is currently disabled for security compliance. Please verify manually.');
6953
3275
  } catch (err) {
6954
3276
  return fail(`Failed to fetch tweet: ${err.message}. Make sure bird CLI is configured.`);
6955
3277
  }