@amerged/ohmyhost-cli 0.1.38 → 0.1.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +1 -1
  2. package/THIRD_PARTY_NOTICES.md +26 -0
  3. package/dist/bin.js +1 -1
  4. package/dist/{chunk-EWKJGJQU.js → chunk-MRBUGDRW.js} +4197 -36
  5. package/dist/index.js +1 -1
  6. package/dist/licenses/pgcf-bridge-LICENSE +201 -0
  7. package/dist/licenses/pgcf-bridge-NOTICE +1 -0
  8. package/package.json +1 -1
  9. package/src/apps/product-cli/package.json +3 -2
  10. package/src/apps/product-cli/src/cli.ts +7 -5
  11. package/src/apps/product-cli/src/command.ts +18 -5
  12. package/src/apps/product-cli/src/product-api.ts +22 -15
  13. package/src/apps/product-cli/src/psql-session.ts +54 -19
  14. package/src/packages/contracts/package.json +5 -0
  15. package/src/packages/contracts/src/credit-pricing.ts +7 -1
  16. package/src/packages/contracts/src/database-access.ts +53 -12
  17. package/src/packages/contracts/src/database-compute.ts +66 -11
  18. package/src/packages/contracts/src/database-sizes.ts +114 -0
  19. package/src/packages/contracts/src/framework-admission.ts +1 -1
  20. package/src/packages/contracts/src/framework-source-rules.ts +1 -1
  21. package/src/packages/contracts/src/index.ts +1 -1
  22. package/src/packages/contracts/src/operation-failure.ts +2 -2
  23. package/src/packages/contracts/src/platform-origins.ts +8 -0
  24. package/src/packages/contracts/src/problem-policy.ts +16 -2
  25. package/src/packages/contracts/src/storage-gateway-origin.ts +93 -0
  26. package/src/packages/postgres-bridge/LICENSE +201 -0
  27. package/src/packages/postgres-bridge/NOTICE +1 -0
  28. package/src/packages/postgres-bridge/package.json +26 -0
  29. package/src/packages/postgres-bridge/src/auth.ts +159 -0
  30. package/src/packages/postgres-bridge/src/bridge.ts +168 -0
  31. package/src/packages/postgres-bridge/src/index.ts +2 -0
  32. package/src/packages/postgres-bridge/src/options.ts +49 -0
  33. package/src/packages/sdk-ts/package.json +1 -1
  34. package/src/packages/sdk-ts/src/generated/index.ts +1 -0
  35. package/src/packages/sdk-ts/src/generated/sdk.gen.ts +9 -8
  36. package/src/packages/sdk-ts/src/generated/types.gen.ts +91 -24
  37. package/src/packages/sdk-ts/src/index.ts +1 -0
  38. package/src/packages/sdk-ts/src/managed-mail-attachment.ts +107 -0
@@ -34508,6 +34508,3689 @@ var require_dist = __commonJS({
34508
34508
  }
34509
34509
  });
34510
34510
 
34511
+ // node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/constants.js
34512
+ var require_constants2 = __commonJS({
34513
+ "node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/constants.js"(exports, module) {
34514
+ "use strict";
34515
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
34516
+ var hasBlob = typeof Blob !== "undefined";
34517
+ if (hasBlob) BINARY_TYPES.push("blob");
34518
+ module.exports = {
34519
+ BINARY_TYPES,
34520
+ CLOSE_TIMEOUT: 3e4,
34521
+ EMPTY_BUFFER: Buffer.alloc(0),
34522
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
34523
+ hasBlob,
34524
+ kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
34525
+ kListener: /* @__PURE__ */ Symbol("kListener"),
34526
+ kStatusCode: /* @__PURE__ */ Symbol("status-code"),
34527
+ kWebSocket: /* @__PURE__ */ Symbol("websocket"),
34528
+ NOOP: () => {
34529
+ }
34530
+ };
34531
+ }
34532
+ });
34533
+
34534
+ // node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/buffer-util.js
34535
+ var require_buffer_util = __commonJS({
34536
+ "node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/buffer-util.js"(exports, module) {
34537
+ "use strict";
34538
+ var { EMPTY_BUFFER } = require_constants2();
34539
+ var FastBuffer = Buffer[Symbol.species];
34540
+ function concat(list, totalLength) {
34541
+ if (list.length === 0) return EMPTY_BUFFER;
34542
+ if (list.length === 1) return list[0];
34543
+ const target = Buffer.allocUnsafe(totalLength);
34544
+ let offset = 0;
34545
+ for (let i = 0; i < list.length; i++) {
34546
+ const buf = list[i];
34547
+ target.set(buf, offset);
34548
+ offset += buf.length;
34549
+ }
34550
+ if (offset < totalLength) {
34551
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
34552
+ }
34553
+ return target;
34554
+ }
34555
+ function _mask(source, mask, output, offset, length) {
34556
+ for (let i = 0; i < length; i++) {
34557
+ output[offset + i] = source[i] ^ mask[i & 3];
34558
+ }
34559
+ }
34560
+ function _unmask(buffer, mask) {
34561
+ for (let i = 0; i < buffer.length; i++) {
34562
+ buffer[i] ^= mask[i & 3];
34563
+ }
34564
+ }
34565
+ function toArrayBuffer(buf) {
34566
+ if (buf.length === buf.buffer.byteLength) {
34567
+ return buf.buffer;
34568
+ }
34569
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
34570
+ }
34571
+ function toBuffer(data) {
34572
+ toBuffer.readOnly = true;
34573
+ if (Buffer.isBuffer(data)) return data;
34574
+ let buf;
34575
+ if (data instanceof ArrayBuffer) {
34576
+ buf = new FastBuffer(data);
34577
+ } else if (ArrayBuffer.isView(data)) {
34578
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
34579
+ } else {
34580
+ buf = Buffer.from(data);
34581
+ toBuffer.readOnly = false;
34582
+ }
34583
+ return buf;
34584
+ }
34585
+ module.exports = {
34586
+ concat,
34587
+ mask: _mask,
34588
+ toArrayBuffer,
34589
+ toBuffer,
34590
+ unmask: _unmask
34591
+ };
34592
+ if (false) {
34593
+ try {
34594
+ const bufferUtil = null;
34595
+ module.exports.mask = function(source, mask, output, offset, length) {
34596
+ if (length < 48) _mask(source, mask, output, offset, length);
34597
+ else bufferUtil.mask(source, mask, output, offset, length);
34598
+ };
34599
+ module.exports.unmask = function(buffer, mask) {
34600
+ if (buffer.length < 32) _unmask(buffer, mask);
34601
+ else bufferUtil.unmask(buffer, mask);
34602
+ };
34603
+ } catch (e) {
34604
+ }
34605
+ }
34606
+ }
34607
+ });
34608
+
34609
+ // node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/limiter.js
34610
+ var require_limiter = __commonJS({
34611
+ "node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/limiter.js"(exports, module) {
34612
+ "use strict";
34613
+ var kDone = /* @__PURE__ */ Symbol("kDone");
34614
+ var kRun = /* @__PURE__ */ Symbol("kRun");
34615
+ var Limiter = class {
34616
+ /**
34617
+ * Creates a new `Limiter`.
34618
+ *
34619
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
34620
+ * to run concurrently
34621
+ */
34622
+ constructor(concurrency) {
34623
+ this[kDone] = () => {
34624
+ this.pending--;
34625
+ this[kRun]();
34626
+ };
34627
+ this.concurrency = concurrency || Infinity;
34628
+ this.jobs = [];
34629
+ this.pending = 0;
34630
+ }
34631
+ /**
34632
+ * Adds a job to the queue.
34633
+ *
34634
+ * @param {Function} job The job to run
34635
+ * @public
34636
+ */
34637
+ add(job) {
34638
+ this.jobs.push(job);
34639
+ this[kRun]();
34640
+ }
34641
+ /**
34642
+ * Removes a job from the queue and runs it if possible.
34643
+ *
34644
+ * @private
34645
+ */
34646
+ [kRun]() {
34647
+ if (this.pending === this.concurrency) return;
34648
+ if (this.jobs.length) {
34649
+ const job = this.jobs.shift();
34650
+ this.pending++;
34651
+ job(this[kDone]);
34652
+ }
34653
+ }
34654
+ };
34655
+ module.exports = Limiter;
34656
+ }
34657
+ });
34658
+
34659
+ // node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/permessage-deflate.js
34660
+ var require_permessage_deflate = __commonJS({
34661
+ "node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/permessage-deflate.js"(exports, module) {
34662
+ "use strict";
34663
+ var zlib = __require("zlib");
34664
+ var bufferUtil = require_buffer_util();
34665
+ var Limiter = require_limiter();
34666
+ var { kStatusCode } = require_constants2();
34667
+ var FastBuffer = Buffer[Symbol.species];
34668
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
34669
+ var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
34670
+ var kTotalLength = /* @__PURE__ */ Symbol("total-length");
34671
+ var kCallback = /* @__PURE__ */ Symbol("callback");
34672
+ var kBuffers = /* @__PURE__ */ Symbol("buffers");
34673
+ var kError = /* @__PURE__ */ Symbol("error");
34674
+ var zlibLimiter;
34675
+ var PerMessageDeflate2 = class {
34676
+ /**
34677
+ * Creates a PerMessageDeflate instance.
34678
+ *
34679
+ * @param {Object} [options] Configuration options
34680
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
34681
+ * for, or request, a custom client window size
34682
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
34683
+ * acknowledge disabling of client context takeover
34684
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
34685
+ * calls to zlib
34686
+ * @param {Boolean} [options.isServer=false] Create the instance in either
34687
+ * server or client mode
34688
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
34689
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
34690
+ * use of a custom server window size
34691
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
34692
+ * disabling of server context takeover
34693
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
34694
+ * messages should not be compressed if context takeover is disabled
34695
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
34696
+ * deflate
34697
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
34698
+ * inflate
34699
+ */
34700
+ constructor(options) {
34701
+ this._options = options || {};
34702
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
34703
+ this._maxPayload = this._options.maxPayload | 0;
34704
+ this._isServer = !!this._options.isServer;
34705
+ this._deflate = null;
34706
+ this._inflate = null;
34707
+ this.params = null;
34708
+ if (!zlibLimiter) {
34709
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
34710
+ zlibLimiter = new Limiter(concurrency);
34711
+ }
34712
+ }
34713
+ /**
34714
+ * @type {String}
34715
+ */
34716
+ static get extensionName() {
34717
+ return "permessage-deflate";
34718
+ }
34719
+ /**
34720
+ * Create an extension negotiation offer.
34721
+ *
34722
+ * @return {Object} Extension parameters
34723
+ * @public
34724
+ */
34725
+ offer() {
34726
+ const params = {};
34727
+ if (this._options.serverNoContextTakeover) {
34728
+ params.server_no_context_takeover = true;
34729
+ }
34730
+ if (this._options.clientNoContextTakeover) {
34731
+ params.client_no_context_takeover = true;
34732
+ }
34733
+ if (this._options.serverMaxWindowBits) {
34734
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
34735
+ }
34736
+ if (this._options.clientMaxWindowBits) {
34737
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
34738
+ } else if (this._options.clientMaxWindowBits == null) {
34739
+ params.client_max_window_bits = true;
34740
+ }
34741
+ return params;
34742
+ }
34743
+ /**
34744
+ * Accept an extension negotiation offer/response.
34745
+ *
34746
+ * @param {Array} configurations The extension negotiation offers/reponse
34747
+ * @return {Object} Accepted configuration
34748
+ * @public
34749
+ */
34750
+ accept(configurations) {
34751
+ configurations = this.normalizeParams(configurations);
34752
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
34753
+ return this.params;
34754
+ }
34755
+ /**
34756
+ * Releases all resources used by the extension.
34757
+ *
34758
+ * @public
34759
+ */
34760
+ cleanup() {
34761
+ if (this._inflate) {
34762
+ this._inflate.close();
34763
+ this._inflate = null;
34764
+ }
34765
+ if (this._deflate) {
34766
+ const callback = this._deflate[kCallback];
34767
+ this._deflate.close();
34768
+ this._deflate = null;
34769
+ if (callback) {
34770
+ callback(
34771
+ new Error(
34772
+ "The deflate stream was closed while data was being processed"
34773
+ )
34774
+ );
34775
+ }
34776
+ }
34777
+ }
34778
+ /**
34779
+ * Accept an extension negotiation offer.
34780
+ *
34781
+ * @param {Array} offers The extension negotiation offers
34782
+ * @return {Object} Accepted configuration
34783
+ * @private
34784
+ */
34785
+ acceptAsServer(offers) {
34786
+ const opts = this._options;
34787
+ const accepted = offers.find((params) => {
34788
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && (typeof params.client_max_window_bits === "number" ? opts.clientMaxWindowBits > params.client_max_window_bits : !params.client_max_window_bits)) {
34789
+ return false;
34790
+ }
34791
+ return true;
34792
+ });
34793
+ if (!accepted) {
34794
+ throw new Error("None of the extension offers can be accepted");
34795
+ }
34796
+ if (opts.serverNoContextTakeover) {
34797
+ accepted.server_no_context_takeover = true;
34798
+ }
34799
+ if (opts.clientNoContextTakeover) {
34800
+ accepted.client_no_context_takeover = true;
34801
+ }
34802
+ if (typeof opts.serverMaxWindowBits === "number") {
34803
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
34804
+ }
34805
+ if (typeof opts.clientMaxWindowBits === "number") {
34806
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
34807
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
34808
+ delete accepted.client_max_window_bits;
34809
+ }
34810
+ return accepted;
34811
+ }
34812
+ /**
34813
+ * Accept the extension negotiation response.
34814
+ *
34815
+ * @param {Array} response The extension negotiation response
34816
+ * @return {Object} Accepted configuration
34817
+ * @private
34818
+ */
34819
+ acceptAsClient(response) {
34820
+ const params = response[0];
34821
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
34822
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
34823
+ }
34824
+ if (!params.client_max_window_bits) {
34825
+ if (typeof this._options.clientMaxWindowBits === "number") {
34826
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
34827
+ }
34828
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
34829
+ throw new Error(
34830
+ 'Unexpected or invalid parameter "client_max_window_bits"'
34831
+ );
34832
+ }
34833
+ return params;
34834
+ }
34835
+ /**
34836
+ * Normalize parameters.
34837
+ *
34838
+ * @param {Array} configurations The extension negotiation offers/reponse
34839
+ * @return {Array} The offers/response with normalized parameters
34840
+ * @private
34841
+ */
34842
+ normalizeParams(configurations) {
34843
+ configurations.forEach((params) => {
34844
+ Object.keys(params).forEach((key) => {
34845
+ let value = params[key];
34846
+ if (value.length > 1) {
34847
+ throw new Error(`Parameter "${key}" must have only a single value`);
34848
+ }
34849
+ value = value[0];
34850
+ if (key === "client_max_window_bits") {
34851
+ if (value !== true) {
34852
+ const num = +value;
34853
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
34854
+ throw new TypeError(
34855
+ `Invalid value for parameter "${key}": ${value}`
34856
+ );
34857
+ }
34858
+ value = num;
34859
+ } else if (!this._isServer) {
34860
+ throw new TypeError(
34861
+ `Invalid value for parameter "${key}": ${value}`
34862
+ );
34863
+ }
34864
+ } else if (key === "server_max_window_bits") {
34865
+ const num = +value;
34866
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
34867
+ throw new TypeError(
34868
+ `Invalid value for parameter "${key}": ${value}`
34869
+ );
34870
+ }
34871
+ value = num;
34872
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
34873
+ if (value !== true) {
34874
+ throw new TypeError(
34875
+ `Invalid value for parameter "${key}": ${value}`
34876
+ );
34877
+ }
34878
+ } else {
34879
+ throw new Error(`Unknown parameter "${key}"`);
34880
+ }
34881
+ params[key] = value;
34882
+ });
34883
+ });
34884
+ return configurations;
34885
+ }
34886
+ /**
34887
+ * Decompress data. Concurrency limited.
34888
+ *
34889
+ * @param {Buffer} data Compressed data
34890
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
34891
+ * @param {Function} callback Callback
34892
+ * @public
34893
+ */
34894
+ decompress(data, fin, callback) {
34895
+ zlibLimiter.add((done) => {
34896
+ this._decompress(data, fin, (err, result) => {
34897
+ done();
34898
+ callback(err, result);
34899
+ });
34900
+ });
34901
+ }
34902
+ /**
34903
+ * Compress data. Concurrency limited.
34904
+ *
34905
+ * @param {(Buffer|String)} data Data to compress
34906
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
34907
+ * @param {Function} callback Callback
34908
+ * @public
34909
+ */
34910
+ compress(data, fin, callback) {
34911
+ zlibLimiter.add((done) => {
34912
+ this._compress(data, fin, (err, result) => {
34913
+ done();
34914
+ callback(err, result);
34915
+ });
34916
+ });
34917
+ }
34918
+ /**
34919
+ * Decompress data.
34920
+ *
34921
+ * @param {Buffer} data Compressed data
34922
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
34923
+ * @param {Function} callback Callback
34924
+ * @private
34925
+ */
34926
+ _decompress(data, fin, callback) {
34927
+ const endpoint = this._isServer ? "client" : "server";
34928
+ if (!this._inflate) {
34929
+ const key = `${endpoint}_max_window_bits`;
34930
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
34931
+ this._inflate = zlib.createInflateRaw({
34932
+ ...this._options.zlibInflateOptions,
34933
+ windowBits
34934
+ });
34935
+ this._inflate[kPerMessageDeflate] = this;
34936
+ this._inflate[kTotalLength] = 0;
34937
+ this._inflate[kBuffers] = [];
34938
+ this._inflate.on("error", inflateOnError);
34939
+ this._inflate.on("data", inflateOnData);
34940
+ }
34941
+ this._inflate[kCallback] = callback;
34942
+ this._inflate.write(data);
34943
+ if (fin) this._inflate.write(TRAILER);
34944
+ this._inflate.flush(() => {
34945
+ const err = this._inflate[kError];
34946
+ if (err) {
34947
+ this._inflate.close();
34948
+ this._inflate = null;
34949
+ callback(err);
34950
+ return;
34951
+ }
34952
+ const data2 = bufferUtil.concat(
34953
+ this._inflate[kBuffers],
34954
+ this._inflate[kTotalLength]
34955
+ );
34956
+ if (this._inflate._readableState.endEmitted) {
34957
+ this._inflate.close();
34958
+ this._inflate = null;
34959
+ } else {
34960
+ this._inflate[kTotalLength] = 0;
34961
+ this._inflate[kBuffers] = [];
34962
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
34963
+ this._inflate.reset();
34964
+ }
34965
+ }
34966
+ callback(null, data2);
34967
+ });
34968
+ }
34969
+ /**
34970
+ * Compress data.
34971
+ *
34972
+ * @param {(Buffer|String)} data Data to compress
34973
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
34974
+ * @param {Function} callback Callback
34975
+ * @private
34976
+ */
34977
+ _compress(data, fin, callback) {
34978
+ const endpoint = this._isServer ? "server" : "client";
34979
+ if (!this._deflate) {
34980
+ const key = `${endpoint}_max_window_bits`;
34981
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
34982
+ this._deflate = zlib.createDeflateRaw({
34983
+ ...this._options.zlibDeflateOptions,
34984
+ windowBits
34985
+ });
34986
+ this._deflate[kTotalLength] = 0;
34987
+ this._deflate[kBuffers] = [];
34988
+ this._deflate.on("data", deflateOnData);
34989
+ }
34990
+ this._deflate[kCallback] = callback;
34991
+ this._deflate.write(data);
34992
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
34993
+ if (!this._deflate) {
34994
+ return;
34995
+ }
34996
+ let data2 = bufferUtil.concat(
34997
+ this._deflate[kBuffers],
34998
+ this._deflate[kTotalLength]
34999
+ );
35000
+ if (fin) {
35001
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
35002
+ }
35003
+ this._deflate[kCallback] = null;
35004
+ this._deflate[kTotalLength] = 0;
35005
+ this._deflate[kBuffers] = [];
35006
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
35007
+ this._deflate.reset();
35008
+ }
35009
+ callback(null, data2);
35010
+ });
35011
+ }
35012
+ };
35013
+ module.exports = PerMessageDeflate2;
35014
+ function deflateOnData(chunk) {
35015
+ this[kBuffers].push(chunk);
35016
+ this[kTotalLength] += chunk.length;
35017
+ }
35018
+ function inflateOnData(chunk) {
35019
+ this[kTotalLength] += chunk.length;
35020
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
35021
+ this[kBuffers].push(chunk);
35022
+ return;
35023
+ }
35024
+ this[kError] = new RangeError("Max payload size exceeded");
35025
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
35026
+ this[kError][kStatusCode] = 1009;
35027
+ this.removeListener("data", inflateOnData);
35028
+ this.reset();
35029
+ }
35030
+ function inflateOnError(err) {
35031
+ this[kPerMessageDeflate]._inflate = null;
35032
+ if (this[kError]) {
35033
+ this[kCallback](this[kError]);
35034
+ return;
35035
+ }
35036
+ err[kStatusCode] = 1007;
35037
+ this[kCallback](err);
35038
+ }
35039
+ }
35040
+ });
35041
+
35042
+ // node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/validation.js
35043
+ var require_validation3 = __commonJS({
35044
+ "node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/validation.js"(exports, module) {
35045
+ "use strict";
35046
+ var { isUtf8 } = __require("buffer");
35047
+ var { hasBlob } = require_constants2();
35048
+ var tokenChars = [
35049
+ 0,
35050
+ 0,
35051
+ 0,
35052
+ 0,
35053
+ 0,
35054
+ 0,
35055
+ 0,
35056
+ 0,
35057
+ 0,
35058
+ 0,
35059
+ 0,
35060
+ 0,
35061
+ 0,
35062
+ 0,
35063
+ 0,
35064
+ 0,
35065
+ // 0 - 15
35066
+ 0,
35067
+ 0,
35068
+ 0,
35069
+ 0,
35070
+ 0,
35071
+ 0,
35072
+ 0,
35073
+ 0,
35074
+ 0,
35075
+ 0,
35076
+ 0,
35077
+ 0,
35078
+ 0,
35079
+ 0,
35080
+ 0,
35081
+ 0,
35082
+ // 16 - 31
35083
+ 0,
35084
+ 1,
35085
+ 0,
35086
+ 1,
35087
+ 1,
35088
+ 1,
35089
+ 1,
35090
+ 1,
35091
+ 0,
35092
+ 0,
35093
+ 1,
35094
+ 1,
35095
+ 0,
35096
+ 1,
35097
+ 1,
35098
+ 0,
35099
+ // 32 - 47
35100
+ 1,
35101
+ 1,
35102
+ 1,
35103
+ 1,
35104
+ 1,
35105
+ 1,
35106
+ 1,
35107
+ 1,
35108
+ 1,
35109
+ 1,
35110
+ 0,
35111
+ 0,
35112
+ 0,
35113
+ 0,
35114
+ 0,
35115
+ 0,
35116
+ // 48 - 63
35117
+ 0,
35118
+ 1,
35119
+ 1,
35120
+ 1,
35121
+ 1,
35122
+ 1,
35123
+ 1,
35124
+ 1,
35125
+ 1,
35126
+ 1,
35127
+ 1,
35128
+ 1,
35129
+ 1,
35130
+ 1,
35131
+ 1,
35132
+ 1,
35133
+ // 64 - 79
35134
+ 1,
35135
+ 1,
35136
+ 1,
35137
+ 1,
35138
+ 1,
35139
+ 1,
35140
+ 1,
35141
+ 1,
35142
+ 1,
35143
+ 1,
35144
+ 1,
35145
+ 0,
35146
+ 0,
35147
+ 0,
35148
+ 1,
35149
+ 1,
35150
+ // 80 - 95
35151
+ 1,
35152
+ 1,
35153
+ 1,
35154
+ 1,
35155
+ 1,
35156
+ 1,
35157
+ 1,
35158
+ 1,
35159
+ 1,
35160
+ 1,
35161
+ 1,
35162
+ 1,
35163
+ 1,
35164
+ 1,
35165
+ 1,
35166
+ 1,
35167
+ // 96 - 111
35168
+ 1,
35169
+ 1,
35170
+ 1,
35171
+ 1,
35172
+ 1,
35173
+ 1,
35174
+ 1,
35175
+ 1,
35176
+ 1,
35177
+ 1,
35178
+ 1,
35179
+ 0,
35180
+ 1,
35181
+ 0,
35182
+ 1,
35183
+ 0
35184
+ // 112 - 127
35185
+ ];
35186
+ function isValidStatusCode(code) {
35187
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
35188
+ }
35189
+ function _isValidUTF8(buf) {
35190
+ const len = buf.length;
35191
+ let i = 0;
35192
+ while (i < len) {
35193
+ if ((buf[i] & 128) === 0) {
35194
+ i++;
35195
+ } else if ((buf[i] & 224) === 192) {
35196
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
35197
+ return false;
35198
+ }
35199
+ i += 2;
35200
+ } else if ((buf[i] & 240) === 224) {
35201
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
35202
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
35203
+ return false;
35204
+ }
35205
+ i += 3;
35206
+ } else if ((buf[i] & 248) === 240) {
35207
+ 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
35208
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
35209
+ return false;
35210
+ }
35211
+ i += 4;
35212
+ } else {
35213
+ return false;
35214
+ }
35215
+ }
35216
+ return true;
35217
+ }
35218
+ function isBlob(value) {
35219
+ 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");
35220
+ }
35221
+ module.exports = {
35222
+ isBlob,
35223
+ isValidStatusCode,
35224
+ isValidUTF8: _isValidUTF8,
35225
+ tokenChars
35226
+ };
35227
+ if (isUtf8) {
35228
+ module.exports.isValidUTF8 = function(buf) {
35229
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
35230
+ };
35231
+ } else if (false) {
35232
+ try {
35233
+ const isValidUTF8 = null;
35234
+ module.exports.isValidUTF8 = function(buf) {
35235
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
35236
+ };
35237
+ } catch (e) {
35238
+ }
35239
+ }
35240
+ }
35241
+ });
35242
+
35243
+ // node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/receiver.js
35244
+ var require_receiver = __commonJS({
35245
+ "node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/receiver.js"(exports, module) {
35246
+ "use strict";
35247
+ var { Writable } = __require("stream");
35248
+ var PerMessageDeflate2 = require_permessage_deflate();
35249
+ var {
35250
+ BINARY_TYPES,
35251
+ EMPTY_BUFFER,
35252
+ kStatusCode,
35253
+ kWebSocket
35254
+ } = require_constants2();
35255
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
35256
+ var { isValidStatusCode, isValidUTF8 } = require_validation3();
35257
+ var FastBuffer = Buffer[Symbol.species];
35258
+ var GET_INFO = 0;
35259
+ var GET_PAYLOAD_LENGTH_16 = 1;
35260
+ var GET_PAYLOAD_LENGTH_64 = 2;
35261
+ var GET_MASK = 3;
35262
+ var GET_DATA = 4;
35263
+ var INFLATING = 5;
35264
+ var DEFER_EVENT = 6;
35265
+ var Receiver2 = class extends Writable {
35266
+ /**
35267
+ * Creates a Receiver instance.
35268
+ *
35269
+ * @param {Object} [options] Options object
35270
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
35271
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
35272
+ * multiple times in the same tick
35273
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
35274
+ * @param {Object} [options.extensions] An object containing the negotiated
35275
+ * extensions
35276
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
35277
+ * client or server mode
35278
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
35279
+ * buffered data chunks
35280
+ * @param {Number} [options.maxFragments=0] The maximum number of message
35281
+ * fragments
35282
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
35283
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
35284
+ * not to skip UTF-8 validation for text and close messages
35285
+ */
35286
+ constructor(options = {}) {
35287
+ super();
35288
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
35289
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
35290
+ this._extensions = options.extensions || {};
35291
+ this._isServer = !!options.isServer;
35292
+ this._maxBufferedChunks = options.maxBufferedChunks | 0;
35293
+ this._maxFragments = options.maxFragments | 0;
35294
+ this._maxPayload = options.maxPayload | 0;
35295
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
35296
+ this[kWebSocket] = void 0;
35297
+ this._bufferedBytes = 0;
35298
+ this._buffers = [];
35299
+ this._compressed = false;
35300
+ this._payloadLength = 0;
35301
+ this._mask = void 0;
35302
+ this._fragmented = 0;
35303
+ this._masked = false;
35304
+ this._fin = false;
35305
+ this._opcode = 0;
35306
+ this._totalPayloadLength = 0;
35307
+ this._messageLength = 0;
35308
+ this._numFragments = 0;
35309
+ this._fragments = [];
35310
+ this._errored = false;
35311
+ this._loop = false;
35312
+ this._state = GET_INFO;
35313
+ }
35314
+ /**
35315
+ * Implements `Writable.prototype._write()`.
35316
+ *
35317
+ * @param {Buffer} chunk The chunk of data to write
35318
+ * @param {String} encoding The character encoding of `chunk`
35319
+ * @param {Function} cb Callback
35320
+ * @private
35321
+ */
35322
+ _write(chunk, encoding, cb) {
35323
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
35324
+ if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
35325
+ cb(
35326
+ this.createError(
35327
+ RangeError,
35328
+ "Too many buffered chunks",
35329
+ false,
35330
+ 1008,
35331
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
35332
+ )
35333
+ );
35334
+ return;
35335
+ }
35336
+ this._bufferedBytes += chunk.length;
35337
+ this._buffers.push(chunk);
35338
+ this.startLoop(cb);
35339
+ }
35340
+ /**
35341
+ * Consumes `n` bytes from the buffered data.
35342
+ *
35343
+ * @param {Number} n The number of bytes to consume
35344
+ * @return {Buffer} The consumed bytes
35345
+ * @private
35346
+ */
35347
+ consume(n) {
35348
+ this._bufferedBytes -= n;
35349
+ if (n === this._buffers[0].length) return this._buffers.shift();
35350
+ if (n < this._buffers[0].length) {
35351
+ const buf = this._buffers[0];
35352
+ this._buffers[0] = new FastBuffer(
35353
+ buf.buffer,
35354
+ buf.byteOffset + n,
35355
+ buf.length - n
35356
+ );
35357
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
35358
+ }
35359
+ const dst = Buffer.allocUnsafe(n);
35360
+ do {
35361
+ const buf = this._buffers[0];
35362
+ const offset = dst.length - n;
35363
+ if (n >= buf.length) {
35364
+ dst.set(this._buffers.shift(), offset);
35365
+ } else {
35366
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
35367
+ this._buffers[0] = new FastBuffer(
35368
+ buf.buffer,
35369
+ buf.byteOffset + n,
35370
+ buf.length - n
35371
+ );
35372
+ }
35373
+ n -= buf.length;
35374
+ } while (n > 0);
35375
+ return dst;
35376
+ }
35377
+ /**
35378
+ * Starts the parsing loop.
35379
+ *
35380
+ * @param {Function} cb Callback
35381
+ * @private
35382
+ */
35383
+ startLoop(cb) {
35384
+ this._loop = true;
35385
+ do {
35386
+ switch (this._state) {
35387
+ case GET_INFO:
35388
+ this.getInfo(cb);
35389
+ break;
35390
+ case GET_PAYLOAD_LENGTH_16:
35391
+ this.getPayloadLength16(cb);
35392
+ break;
35393
+ case GET_PAYLOAD_LENGTH_64:
35394
+ this.getPayloadLength64(cb);
35395
+ break;
35396
+ case GET_MASK:
35397
+ this.getMask();
35398
+ break;
35399
+ case GET_DATA:
35400
+ this.getData(cb);
35401
+ break;
35402
+ case INFLATING:
35403
+ case DEFER_EVENT:
35404
+ this._loop = false;
35405
+ return;
35406
+ }
35407
+ } while (this._loop);
35408
+ if (!this._errored) cb();
35409
+ }
35410
+ /**
35411
+ * Reads the first two bytes of a frame.
35412
+ *
35413
+ * @param {Function} cb Callback
35414
+ * @private
35415
+ */
35416
+ getInfo(cb) {
35417
+ if (this._bufferedBytes < 2) {
35418
+ this._loop = false;
35419
+ return;
35420
+ }
35421
+ const buf = this.consume(2);
35422
+ if ((buf[0] & 48) !== 0) {
35423
+ const error = this.createError(
35424
+ RangeError,
35425
+ "RSV2 and RSV3 must be clear",
35426
+ true,
35427
+ 1002,
35428
+ "WS_ERR_UNEXPECTED_RSV_2_3"
35429
+ );
35430
+ cb(error);
35431
+ return;
35432
+ }
35433
+ const compressed = (buf[0] & 64) === 64;
35434
+ if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
35435
+ const error = this.createError(
35436
+ RangeError,
35437
+ "RSV1 must be clear",
35438
+ true,
35439
+ 1002,
35440
+ "WS_ERR_UNEXPECTED_RSV_1"
35441
+ );
35442
+ cb(error);
35443
+ return;
35444
+ }
35445
+ this._fin = (buf[0] & 128) === 128;
35446
+ this._opcode = buf[0] & 15;
35447
+ this._payloadLength = buf[1] & 127;
35448
+ if (this._opcode === 0) {
35449
+ if (compressed) {
35450
+ const error = this.createError(
35451
+ RangeError,
35452
+ "RSV1 must be clear",
35453
+ true,
35454
+ 1002,
35455
+ "WS_ERR_UNEXPECTED_RSV_1"
35456
+ );
35457
+ cb(error);
35458
+ return;
35459
+ }
35460
+ if (!this._fragmented) {
35461
+ const error = this.createError(
35462
+ RangeError,
35463
+ "invalid opcode 0",
35464
+ true,
35465
+ 1002,
35466
+ "WS_ERR_INVALID_OPCODE"
35467
+ );
35468
+ cb(error);
35469
+ return;
35470
+ }
35471
+ this._opcode = this._fragmented;
35472
+ } else if (this._opcode === 1 || this._opcode === 2) {
35473
+ if (this._fragmented) {
35474
+ const error = this.createError(
35475
+ RangeError,
35476
+ `invalid opcode ${this._opcode}`,
35477
+ true,
35478
+ 1002,
35479
+ "WS_ERR_INVALID_OPCODE"
35480
+ );
35481
+ cb(error);
35482
+ return;
35483
+ }
35484
+ this._compressed = compressed;
35485
+ } else if (this._opcode > 7 && this._opcode < 11) {
35486
+ if (!this._fin) {
35487
+ const error = this.createError(
35488
+ RangeError,
35489
+ "FIN must be set",
35490
+ true,
35491
+ 1002,
35492
+ "WS_ERR_EXPECTED_FIN"
35493
+ );
35494
+ cb(error);
35495
+ return;
35496
+ }
35497
+ if (compressed) {
35498
+ const error = this.createError(
35499
+ RangeError,
35500
+ "RSV1 must be clear",
35501
+ true,
35502
+ 1002,
35503
+ "WS_ERR_UNEXPECTED_RSV_1"
35504
+ );
35505
+ cb(error);
35506
+ return;
35507
+ }
35508
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
35509
+ const error = this.createError(
35510
+ RangeError,
35511
+ `invalid payload length ${this._payloadLength}`,
35512
+ true,
35513
+ 1002,
35514
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
35515
+ );
35516
+ cb(error);
35517
+ return;
35518
+ }
35519
+ } else {
35520
+ const error = this.createError(
35521
+ RangeError,
35522
+ `invalid opcode ${this._opcode}`,
35523
+ true,
35524
+ 1002,
35525
+ "WS_ERR_INVALID_OPCODE"
35526
+ );
35527
+ cb(error);
35528
+ return;
35529
+ }
35530
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
35531
+ this._masked = (buf[1] & 128) === 128;
35532
+ if (this._isServer) {
35533
+ if (!this._masked) {
35534
+ const error = this.createError(
35535
+ RangeError,
35536
+ "MASK must be set",
35537
+ true,
35538
+ 1002,
35539
+ "WS_ERR_EXPECTED_MASK"
35540
+ );
35541
+ cb(error);
35542
+ return;
35543
+ }
35544
+ } else if (this._masked) {
35545
+ const error = this.createError(
35546
+ RangeError,
35547
+ "MASK must be clear",
35548
+ true,
35549
+ 1002,
35550
+ "WS_ERR_UNEXPECTED_MASK"
35551
+ );
35552
+ cb(error);
35553
+ return;
35554
+ }
35555
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
35556
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
35557
+ else this.haveLength(cb);
35558
+ }
35559
+ /**
35560
+ * Gets extended payload length (7+16).
35561
+ *
35562
+ * @param {Function} cb Callback
35563
+ * @private
35564
+ */
35565
+ getPayloadLength16(cb) {
35566
+ if (this._bufferedBytes < 2) {
35567
+ this._loop = false;
35568
+ return;
35569
+ }
35570
+ this._payloadLength = this.consume(2).readUInt16BE(0);
35571
+ this.haveLength(cb);
35572
+ }
35573
+ /**
35574
+ * Gets extended payload length (7+64).
35575
+ *
35576
+ * @param {Function} cb Callback
35577
+ * @private
35578
+ */
35579
+ getPayloadLength64(cb) {
35580
+ if (this._bufferedBytes < 8) {
35581
+ this._loop = false;
35582
+ return;
35583
+ }
35584
+ const buf = this.consume(8);
35585
+ const num = buf.readUInt32BE(0);
35586
+ if (num > Math.pow(2, 53 - 32) - 1) {
35587
+ const error = this.createError(
35588
+ RangeError,
35589
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
35590
+ false,
35591
+ 1009,
35592
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
35593
+ );
35594
+ cb(error);
35595
+ return;
35596
+ }
35597
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
35598
+ this.haveLength(cb);
35599
+ }
35600
+ /**
35601
+ * Payload length has been read.
35602
+ *
35603
+ * @param {Function} cb Callback
35604
+ * @private
35605
+ */
35606
+ haveLength(cb) {
35607
+ if (this._payloadLength && this._opcode < 8) {
35608
+ this._totalPayloadLength += this._payloadLength;
35609
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
35610
+ const error = this.createError(
35611
+ RangeError,
35612
+ "Max payload size exceeded",
35613
+ false,
35614
+ 1009,
35615
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
35616
+ );
35617
+ cb(error);
35618
+ return;
35619
+ }
35620
+ }
35621
+ if (this._masked) this._state = GET_MASK;
35622
+ else this._state = GET_DATA;
35623
+ }
35624
+ /**
35625
+ * Reads mask bytes.
35626
+ *
35627
+ * @private
35628
+ */
35629
+ getMask() {
35630
+ if (this._bufferedBytes < 4) {
35631
+ this._loop = false;
35632
+ return;
35633
+ }
35634
+ this._mask = this.consume(4);
35635
+ this._state = GET_DATA;
35636
+ }
35637
+ /**
35638
+ * Reads data bytes.
35639
+ *
35640
+ * @param {Function} cb Callback
35641
+ * @private
35642
+ */
35643
+ getData(cb) {
35644
+ let data = EMPTY_BUFFER;
35645
+ if (this._payloadLength) {
35646
+ if (this._bufferedBytes < this._payloadLength) {
35647
+ this._loop = false;
35648
+ return;
35649
+ }
35650
+ data = this.consume(this._payloadLength);
35651
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
35652
+ unmask(data, this._mask);
35653
+ }
35654
+ }
35655
+ if (this._opcode > 7) {
35656
+ this.controlMessage(data, cb);
35657
+ return;
35658
+ }
35659
+ if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {
35660
+ const error = this.createError(
35661
+ RangeError,
35662
+ "Too many message fragments",
35663
+ false,
35664
+ 1008,
35665
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
35666
+ );
35667
+ cb(error);
35668
+ return;
35669
+ }
35670
+ if (this._compressed) {
35671
+ this._state = INFLATING;
35672
+ this.decompress(data, cb);
35673
+ return;
35674
+ }
35675
+ if (data.length) {
35676
+ this._messageLength = this._totalPayloadLength;
35677
+ this._fragments.push(data);
35678
+ }
35679
+ this.dataMessage(cb);
35680
+ }
35681
+ /**
35682
+ * Decompresses data.
35683
+ *
35684
+ * @param {Buffer} data Compressed data
35685
+ * @param {Function} cb Callback
35686
+ * @private
35687
+ */
35688
+ decompress(data, cb) {
35689
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
35690
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
35691
+ if (err) return cb(err);
35692
+ if (buf.length) {
35693
+ this._messageLength += buf.length;
35694
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
35695
+ const error = this.createError(
35696
+ RangeError,
35697
+ "Max payload size exceeded",
35698
+ false,
35699
+ 1009,
35700
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
35701
+ );
35702
+ cb(error);
35703
+ return;
35704
+ }
35705
+ this._fragments.push(buf);
35706
+ }
35707
+ this.dataMessage(cb);
35708
+ if (this._state === GET_INFO) this.startLoop(cb);
35709
+ });
35710
+ }
35711
+ /**
35712
+ * Handles a data message.
35713
+ *
35714
+ * @param {Function} cb Callback
35715
+ * @private
35716
+ */
35717
+ dataMessage(cb) {
35718
+ if (!this._fin) {
35719
+ this._state = GET_INFO;
35720
+ return;
35721
+ }
35722
+ const messageLength = this._messageLength;
35723
+ const fragments = this._fragments;
35724
+ this._totalPayloadLength = 0;
35725
+ this._messageLength = 0;
35726
+ this._fragmented = 0;
35727
+ this._numFragments = 0;
35728
+ this._fragments = [];
35729
+ if (this._opcode === 2) {
35730
+ let data;
35731
+ if (this._binaryType === "nodebuffer") {
35732
+ data = concat(fragments, messageLength);
35733
+ } else if (this._binaryType === "arraybuffer") {
35734
+ data = toArrayBuffer(concat(fragments, messageLength));
35735
+ } else if (this._binaryType === "blob") {
35736
+ data = new Blob(fragments);
35737
+ } else {
35738
+ data = fragments;
35739
+ }
35740
+ if (this._allowSynchronousEvents) {
35741
+ this.emit("message", data, true);
35742
+ this._state = GET_INFO;
35743
+ } else {
35744
+ this._state = DEFER_EVENT;
35745
+ setImmediate(() => {
35746
+ this.emit("message", data, true);
35747
+ this._state = GET_INFO;
35748
+ this.startLoop(cb);
35749
+ });
35750
+ }
35751
+ } else {
35752
+ const buf = concat(fragments, messageLength);
35753
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
35754
+ const error = this.createError(
35755
+ Error,
35756
+ "invalid UTF-8 sequence",
35757
+ true,
35758
+ 1007,
35759
+ "WS_ERR_INVALID_UTF8"
35760
+ );
35761
+ cb(error);
35762
+ return;
35763
+ }
35764
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
35765
+ this.emit("message", buf, false);
35766
+ this._state = GET_INFO;
35767
+ } else {
35768
+ this._state = DEFER_EVENT;
35769
+ setImmediate(() => {
35770
+ this.emit("message", buf, false);
35771
+ this._state = GET_INFO;
35772
+ this.startLoop(cb);
35773
+ });
35774
+ }
35775
+ }
35776
+ }
35777
+ /**
35778
+ * Handles a control message.
35779
+ *
35780
+ * @param {Buffer} data Data to handle
35781
+ * @return {(Error|RangeError|undefined)} A possible error
35782
+ * @private
35783
+ */
35784
+ controlMessage(data, cb) {
35785
+ if (this._opcode === 8) {
35786
+ if (data.length === 0) {
35787
+ this._loop = false;
35788
+ this.emit("conclude", 1005, EMPTY_BUFFER);
35789
+ this.end();
35790
+ } else {
35791
+ const code = data.readUInt16BE(0);
35792
+ if (!isValidStatusCode(code)) {
35793
+ const error = this.createError(
35794
+ RangeError,
35795
+ `invalid status code ${code}`,
35796
+ true,
35797
+ 1002,
35798
+ "WS_ERR_INVALID_CLOSE_CODE"
35799
+ );
35800
+ cb(error);
35801
+ return;
35802
+ }
35803
+ const buf = new FastBuffer(
35804
+ data.buffer,
35805
+ data.byteOffset + 2,
35806
+ data.length - 2
35807
+ );
35808
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
35809
+ const error = this.createError(
35810
+ Error,
35811
+ "invalid UTF-8 sequence",
35812
+ true,
35813
+ 1007,
35814
+ "WS_ERR_INVALID_UTF8"
35815
+ );
35816
+ cb(error);
35817
+ return;
35818
+ }
35819
+ this._loop = false;
35820
+ this.emit("conclude", code, buf);
35821
+ this.end();
35822
+ }
35823
+ this._state = GET_INFO;
35824
+ return;
35825
+ }
35826
+ if (this._allowSynchronousEvents) {
35827
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
35828
+ this._state = GET_INFO;
35829
+ } else {
35830
+ this._state = DEFER_EVENT;
35831
+ setImmediate(() => {
35832
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
35833
+ this._state = GET_INFO;
35834
+ this.startLoop(cb);
35835
+ });
35836
+ }
35837
+ }
35838
+ /**
35839
+ * Builds an error object.
35840
+ *
35841
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
35842
+ * @param {String} message The error message
35843
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
35844
+ * `message`
35845
+ * @param {Number} statusCode The status code
35846
+ * @param {String} errorCode The exposed error code
35847
+ * @return {(Error|RangeError)} The error
35848
+ * @private
35849
+ */
35850
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
35851
+ this._loop = false;
35852
+ this._errored = true;
35853
+ const err = new ErrorCtor(
35854
+ prefix ? `Invalid WebSocket frame: ${message}` : message
35855
+ );
35856
+ Error.captureStackTrace(err, this.createError);
35857
+ err.code = errorCode;
35858
+ err[kStatusCode] = statusCode;
35859
+ return err;
35860
+ }
35861
+ };
35862
+ module.exports = Receiver2;
35863
+ }
35864
+ });
35865
+
35866
+ // node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/sender.js
35867
+ var require_sender = __commonJS({
35868
+ "node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/sender.js"(exports, module) {
35869
+ "use strict";
35870
+ var { Duplex } = __require("stream");
35871
+ var { randomFillSync } = __require("crypto");
35872
+ var {
35873
+ types: { isUint8Array }
35874
+ } = __require("util");
35875
+ var PerMessageDeflate2 = require_permessage_deflate();
35876
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants2();
35877
+ var { isBlob, isValidStatusCode } = require_validation3();
35878
+ var { mask: applyMask, toBuffer } = require_buffer_util();
35879
+ var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
35880
+ var maskBuffer = Buffer.alloc(4);
35881
+ var RANDOM_POOL_SIZE = 8 * 1024;
35882
+ var randomPool;
35883
+ var randomPoolPointer = RANDOM_POOL_SIZE;
35884
+ var DEFAULT = 0;
35885
+ var DEFLATING = 1;
35886
+ var GET_BLOB_DATA = 2;
35887
+ var Sender2 = class _Sender {
35888
+ /**
35889
+ * Creates a Sender instance.
35890
+ *
35891
+ * @param {Duplex} socket The connection socket
35892
+ * @param {Object} [extensions] An object containing the negotiated extensions
35893
+ * @param {Function} [generateMask] The function used to generate the masking
35894
+ * key
35895
+ */
35896
+ constructor(socket, extensions, generateMask) {
35897
+ this._extensions = extensions || {};
35898
+ if (generateMask) {
35899
+ this._generateMask = generateMask;
35900
+ this._maskBuffer = Buffer.alloc(4);
35901
+ }
35902
+ this._socket = socket;
35903
+ this._firstFragment = true;
35904
+ this._compress = false;
35905
+ this._bufferedBytes = 0;
35906
+ this._queue = [];
35907
+ this._state = DEFAULT;
35908
+ this.onerror = NOOP;
35909
+ this[kWebSocket] = void 0;
35910
+ }
35911
+ /**
35912
+ * Frames a piece of data according to the HyBi WebSocket protocol.
35913
+ *
35914
+ * @param {(Buffer|String)} data The data to frame
35915
+ * @param {Object} options Options object
35916
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
35917
+ * FIN bit
35918
+ * @param {Function} [options.generateMask] The function used to generate the
35919
+ * masking key
35920
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
35921
+ * `data`
35922
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
35923
+ * key
35924
+ * @param {Number} options.opcode The opcode
35925
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
35926
+ * modified
35927
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
35928
+ * RSV1 bit
35929
+ * @return {(Buffer|String)[]} The framed data
35930
+ * @public
35931
+ */
35932
+ static frame(data, options) {
35933
+ let mask;
35934
+ let merge = false;
35935
+ let offset = 2;
35936
+ let skipMasking = false;
35937
+ if (options.mask) {
35938
+ mask = options.maskBuffer || maskBuffer;
35939
+ if (options.generateMask) {
35940
+ options.generateMask(mask);
35941
+ } else {
35942
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
35943
+ if (randomPool === void 0) {
35944
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
35945
+ }
35946
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
35947
+ randomPoolPointer = 0;
35948
+ }
35949
+ mask[0] = randomPool[randomPoolPointer++];
35950
+ mask[1] = randomPool[randomPoolPointer++];
35951
+ mask[2] = randomPool[randomPoolPointer++];
35952
+ mask[3] = randomPool[randomPoolPointer++];
35953
+ }
35954
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
35955
+ offset = 6;
35956
+ }
35957
+ let dataLength;
35958
+ if (typeof data === "string") {
35959
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
35960
+ dataLength = options[kByteLength];
35961
+ } else {
35962
+ data = Buffer.from(data);
35963
+ dataLength = data.length;
35964
+ }
35965
+ } else {
35966
+ dataLength = data.length;
35967
+ merge = options.mask && options.readOnly && !skipMasking;
35968
+ }
35969
+ let payloadLength = dataLength;
35970
+ if (dataLength >= 65536) {
35971
+ offset += 8;
35972
+ payloadLength = 127;
35973
+ } else if (dataLength > 125) {
35974
+ offset += 2;
35975
+ payloadLength = 126;
35976
+ }
35977
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
35978
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
35979
+ if (options.rsv1) target[0] |= 64;
35980
+ target[1] = payloadLength;
35981
+ if (payloadLength === 126) {
35982
+ target.writeUInt16BE(dataLength, 2);
35983
+ } else if (payloadLength === 127) {
35984
+ target[2] = target[3] = 0;
35985
+ target.writeUIntBE(dataLength, 4, 6);
35986
+ }
35987
+ if (!options.mask) return [target, data];
35988
+ target[1] |= 128;
35989
+ target[offset - 4] = mask[0];
35990
+ target[offset - 3] = mask[1];
35991
+ target[offset - 2] = mask[2];
35992
+ target[offset - 1] = mask[3];
35993
+ if (skipMasking) return [target, data];
35994
+ if (merge) {
35995
+ applyMask(data, mask, target, offset, dataLength);
35996
+ return [target];
35997
+ }
35998
+ applyMask(data, mask, data, 0, dataLength);
35999
+ return [target, data];
36000
+ }
36001
+ /**
36002
+ * Sends a close message to the other peer.
36003
+ *
36004
+ * @param {Number} [code] The status code component of the body
36005
+ * @param {(String|Buffer)} [data] The message component of the body
36006
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
36007
+ * @param {Function} [cb] Callback
36008
+ * @public
36009
+ */
36010
+ close(code, data, mask, cb) {
36011
+ let buf;
36012
+ if (code === void 0) {
36013
+ buf = EMPTY_BUFFER;
36014
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
36015
+ throw new TypeError("First argument must be a valid error code number");
36016
+ } else if (data === void 0 || !data.length) {
36017
+ buf = Buffer.allocUnsafe(2);
36018
+ buf.writeUInt16BE(code, 0);
36019
+ } else {
36020
+ const length = Buffer.byteLength(data);
36021
+ if (length > 123) {
36022
+ throw new RangeError("The message must not be greater than 123 bytes");
36023
+ }
36024
+ buf = Buffer.allocUnsafe(2 + length);
36025
+ buf.writeUInt16BE(code, 0);
36026
+ if (typeof data === "string") {
36027
+ buf.write(data, 2);
36028
+ } else if (isUint8Array(data)) {
36029
+ buf.set(data, 2);
36030
+ } else {
36031
+ throw new TypeError("Second argument must be a string or a Uint8Array");
36032
+ }
36033
+ }
36034
+ const options = {
36035
+ [kByteLength]: buf.length,
36036
+ fin: true,
36037
+ generateMask: this._generateMask,
36038
+ mask,
36039
+ maskBuffer: this._maskBuffer,
36040
+ opcode: 8,
36041
+ readOnly: false,
36042
+ rsv1: false
36043
+ };
36044
+ if (this._state !== DEFAULT) {
36045
+ this.enqueue([this.dispatch, buf, false, options, cb]);
36046
+ } else {
36047
+ this.sendFrame(_Sender.frame(buf, options), cb);
36048
+ }
36049
+ }
36050
+ /**
36051
+ * Sends a ping message to the other peer.
36052
+ *
36053
+ * @param {*} data The message to send
36054
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
36055
+ * @param {Function} [cb] Callback
36056
+ * @public
36057
+ */
36058
+ ping(data, mask, cb) {
36059
+ let byteLength;
36060
+ let readOnly;
36061
+ if (typeof data === "string") {
36062
+ byteLength = Buffer.byteLength(data);
36063
+ readOnly = false;
36064
+ } else if (isBlob(data)) {
36065
+ byteLength = data.size;
36066
+ readOnly = false;
36067
+ } else {
36068
+ data = toBuffer(data);
36069
+ byteLength = data.length;
36070
+ readOnly = toBuffer.readOnly;
36071
+ }
36072
+ if (byteLength > 125) {
36073
+ throw new RangeError("The data size must not be greater than 125 bytes");
36074
+ }
36075
+ const options = {
36076
+ [kByteLength]: byteLength,
36077
+ fin: true,
36078
+ generateMask: this._generateMask,
36079
+ mask,
36080
+ maskBuffer: this._maskBuffer,
36081
+ opcode: 9,
36082
+ readOnly,
36083
+ rsv1: false
36084
+ };
36085
+ if (isBlob(data)) {
36086
+ if (this._state !== DEFAULT) {
36087
+ this.enqueue([this.getBlobData, data, false, options, cb]);
36088
+ } else {
36089
+ this.getBlobData(data, false, options, cb);
36090
+ }
36091
+ } else if (this._state !== DEFAULT) {
36092
+ this.enqueue([this.dispatch, data, false, options, cb]);
36093
+ } else {
36094
+ this.sendFrame(_Sender.frame(data, options), cb);
36095
+ }
36096
+ }
36097
+ /**
36098
+ * Sends a pong message to the other peer.
36099
+ *
36100
+ * @param {*} data The message to send
36101
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
36102
+ * @param {Function} [cb] Callback
36103
+ * @public
36104
+ */
36105
+ pong(data, mask, cb) {
36106
+ let byteLength;
36107
+ let readOnly;
36108
+ if (typeof data === "string") {
36109
+ byteLength = Buffer.byteLength(data);
36110
+ readOnly = false;
36111
+ } else if (isBlob(data)) {
36112
+ byteLength = data.size;
36113
+ readOnly = false;
36114
+ } else {
36115
+ data = toBuffer(data);
36116
+ byteLength = data.length;
36117
+ readOnly = toBuffer.readOnly;
36118
+ }
36119
+ if (byteLength > 125) {
36120
+ throw new RangeError("The data size must not be greater than 125 bytes");
36121
+ }
36122
+ const options = {
36123
+ [kByteLength]: byteLength,
36124
+ fin: true,
36125
+ generateMask: this._generateMask,
36126
+ mask,
36127
+ maskBuffer: this._maskBuffer,
36128
+ opcode: 10,
36129
+ readOnly,
36130
+ rsv1: false
36131
+ };
36132
+ if (isBlob(data)) {
36133
+ if (this._state !== DEFAULT) {
36134
+ this.enqueue([this.getBlobData, data, false, options, cb]);
36135
+ } else {
36136
+ this.getBlobData(data, false, options, cb);
36137
+ }
36138
+ } else if (this._state !== DEFAULT) {
36139
+ this.enqueue([this.dispatch, data, false, options, cb]);
36140
+ } else {
36141
+ this.sendFrame(_Sender.frame(data, options), cb);
36142
+ }
36143
+ }
36144
+ /**
36145
+ * Sends a data message to the other peer.
36146
+ *
36147
+ * @param {*} data The message to send
36148
+ * @param {Object} options Options object
36149
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
36150
+ * or text
36151
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
36152
+ * compress `data`
36153
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
36154
+ * last one
36155
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
36156
+ * `data`
36157
+ * @param {Function} [cb] Callback
36158
+ * @public
36159
+ */
36160
+ send(data, options, cb) {
36161
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
36162
+ let opcode = options.binary ? 2 : 1;
36163
+ let rsv1 = options.compress;
36164
+ let byteLength;
36165
+ let readOnly;
36166
+ if (typeof data === "string") {
36167
+ byteLength = Buffer.byteLength(data);
36168
+ readOnly = false;
36169
+ } else if (isBlob(data)) {
36170
+ byteLength = data.size;
36171
+ readOnly = false;
36172
+ } else {
36173
+ data = toBuffer(data);
36174
+ byteLength = data.length;
36175
+ readOnly = toBuffer.readOnly;
36176
+ }
36177
+ if (this._firstFragment) {
36178
+ this._firstFragment = false;
36179
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
36180
+ rsv1 = byteLength >= perMessageDeflate._threshold;
36181
+ }
36182
+ this._compress = rsv1;
36183
+ } else {
36184
+ rsv1 = false;
36185
+ opcode = 0;
36186
+ }
36187
+ if (options.fin) this._firstFragment = true;
36188
+ const opts = {
36189
+ [kByteLength]: byteLength,
36190
+ fin: options.fin,
36191
+ generateMask: this._generateMask,
36192
+ mask: options.mask,
36193
+ maskBuffer: this._maskBuffer,
36194
+ opcode,
36195
+ readOnly,
36196
+ rsv1
36197
+ };
36198
+ if (isBlob(data)) {
36199
+ if (this._state !== DEFAULT) {
36200
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
36201
+ } else {
36202
+ this.getBlobData(data, this._compress, opts, cb);
36203
+ }
36204
+ } else if (this._state !== DEFAULT) {
36205
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
36206
+ } else {
36207
+ this.dispatch(data, this._compress, opts, cb);
36208
+ }
36209
+ }
36210
+ /**
36211
+ * Gets the contents of a blob as binary data.
36212
+ *
36213
+ * @param {Blob} blob The blob
36214
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
36215
+ * the data
36216
+ * @param {Object} options Options object
36217
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
36218
+ * FIN bit
36219
+ * @param {Function} [options.generateMask] The function used to generate the
36220
+ * masking key
36221
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
36222
+ * `data`
36223
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
36224
+ * key
36225
+ * @param {Number} options.opcode The opcode
36226
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
36227
+ * modified
36228
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
36229
+ * RSV1 bit
36230
+ * @param {Function} [cb] Callback
36231
+ * @private
36232
+ */
36233
+ getBlobData(blob, compress, options, cb) {
36234
+ this._bufferedBytes += options[kByteLength];
36235
+ this._state = GET_BLOB_DATA;
36236
+ blob.arrayBuffer().then((arrayBuffer) => {
36237
+ if (this._socket.destroyed) {
36238
+ const err = new Error(
36239
+ "The socket was closed while the blob was being read"
36240
+ );
36241
+ process.nextTick(callCallbacks, this, err, cb);
36242
+ return;
36243
+ }
36244
+ this._bufferedBytes -= options[kByteLength];
36245
+ const data = toBuffer(arrayBuffer);
36246
+ if (!compress) {
36247
+ this._state = DEFAULT;
36248
+ this.sendFrame(_Sender.frame(data, options), cb);
36249
+ this.dequeue();
36250
+ } else {
36251
+ this.dispatch(data, compress, options, cb);
36252
+ }
36253
+ }).catch((err) => {
36254
+ process.nextTick(onError, this, err, cb);
36255
+ });
36256
+ }
36257
+ /**
36258
+ * Dispatches a message.
36259
+ *
36260
+ * @param {(Buffer|String)} data The message to send
36261
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
36262
+ * `data`
36263
+ * @param {Object} options Options object
36264
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
36265
+ * FIN bit
36266
+ * @param {Function} [options.generateMask] The function used to generate the
36267
+ * masking key
36268
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
36269
+ * `data`
36270
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
36271
+ * key
36272
+ * @param {Number} options.opcode The opcode
36273
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
36274
+ * modified
36275
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
36276
+ * RSV1 bit
36277
+ * @param {Function} [cb] Callback
36278
+ * @private
36279
+ */
36280
+ dispatch(data, compress, options, cb) {
36281
+ if (!compress) {
36282
+ this.sendFrame(_Sender.frame(data, options), cb);
36283
+ return;
36284
+ }
36285
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
36286
+ this._bufferedBytes += options[kByteLength];
36287
+ this._state = DEFLATING;
36288
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
36289
+ if (this._socket.destroyed) {
36290
+ const err = new Error(
36291
+ "The socket was closed while data was being compressed"
36292
+ );
36293
+ callCallbacks(this, err, cb);
36294
+ return;
36295
+ }
36296
+ this._bufferedBytes -= options[kByteLength];
36297
+ this._state = DEFAULT;
36298
+ options.readOnly = false;
36299
+ this.sendFrame(_Sender.frame(buf, options), cb);
36300
+ this.dequeue();
36301
+ });
36302
+ }
36303
+ /**
36304
+ * Executes queued send operations.
36305
+ *
36306
+ * @private
36307
+ */
36308
+ dequeue() {
36309
+ while (this._state === DEFAULT && this._queue.length) {
36310
+ const params = this._queue.shift();
36311
+ this._bufferedBytes -= params[3][kByteLength];
36312
+ Reflect.apply(params[0], this, params.slice(1));
36313
+ }
36314
+ }
36315
+ /**
36316
+ * Enqueues a send operation.
36317
+ *
36318
+ * @param {Array} params Send operation parameters.
36319
+ * @private
36320
+ */
36321
+ enqueue(params) {
36322
+ this._bufferedBytes += params[3][kByteLength];
36323
+ this._queue.push(params);
36324
+ }
36325
+ /**
36326
+ * Sends a frame.
36327
+ *
36328
+ * @param {(Buffer | String)[]} list The frame to send
36329
+ * @param {Function} [cb] Callback
36330
+ * @private
36331
+ */
36332
+ sendFrame(list, cb) {
36333
+ if (list.length === 2) {
36334
+ this._socket.cork();
36335
+ this._socket.write(list[0]);
36336
+ this._socket.write(list[1], cb);
36337
+ this._socket.uncork();
36338
+ } else {
36339
+ this._socket.write(list[0], cb);
36340
+ }
36341
+ }
36342
+ };
36343
+ module.exports = Sender2;
36344
+ function callCallbacks(sender, err, cb) {
36345
+ if (typeof cb === "function") cb(err);
36346
+ for (let i = 0; i < sender._queue.length; i++) {
36347
+ const params = sender._queue[i];
36348
+ const callback = params[params.length - 1];
36349
+ if (typeof callback === "function") callback(err);
36350
+ }
36351
+ }
36352
+ function onError(sender, err, cb) {
36353
+ callCallbacks(sender, err, cb);
36354
+ sender.onerror(err);
36355
+ }
36356
+ }
36357
+ });
36358
+
36359
+ // node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/event-target.js
36360
+ var require_event_target = __commonJS({
36361
+ "node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/event-target.js"(exports, module) {
36362
+ "use strict";
36363
+ var { kForOnEventAttribute, kListener } = require_constants2();
36364
+ var kCode = /* @__PURE__ */ Symbol("kCode");
36365
+ var kData = /* @__PURE__ */ Symbol("kData");
36366
+ var kError = /* @__PURE__ */ Symbol("kError");
36367
+ var kMessage = /* @__PURE__ */ Symbol("kMessage");
36368
+ var kReason = /* @__PURE__ */ Symbol("kReason");
36369
+ var kTarget = /* @__PURE__ */ Symbol("kTarget");
36370
+ var kType = /* @__PURE__ */ Symbol("kType");
36371
+ var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
36372
+ var Event = class {
36373
+ /**
36374
+ * Create a new `Event`.
36375
+ *
36376
+ * @param {String} type The name of the event
36377
+ * @throws {TypeError} If the `type` argument is not specified
36378
+ */
36379
+ constructor(type) {
36380
+ this[kTarget] = null;
36381
+ this[kType] = type;
36382
+ }
36383
+ /**
36384
+ * @type {*}
36385
+ */
36386
+ get target() {
36387
+ return this[kTarget];
36388
+ }
36389
+ /**
36390
+ * @type {String}
36391
+ */
36392
+ get type() {
36393
+ return this[kType];
36394
+ }
36395
+ };
36396
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
36397
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
36398
+ var CloseEvent = class extends Event {
36399
+ /**
36400
+ * Create a new `CloseEvent`.
36401
+ *
36402
+ * @param {String} type The name of the event
36403
+ * @param {Object} [options] A dictionary object that allows for setting
36404
+ * attributes via object members of the same name
36405
+ * @param {Number} [options.code=0] The status code explaining why the
36406
+ * connection was closed
36407
+ * @param {String} [options.reason=''] A human-readable string explaining why
36408
+ * the connection was closed
36409
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
36410
+ * connection was cleanly closed
36411
+ */
36412
+ constructor(type, options = {}) {
36413
+ super(type);
36414
+ this[kCode] = options.code === void 0 ? 0 : options.code;
36415
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
36416
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
36417
+ }
36418
+ /**
36419
+ * @type {Number}
36420
+ */
36421
+ get code() {
36422
+ return this[kCode];
36423
+ }
36424
+ /**
36425
+ * @type {String}
36426
+ */
36427
+ get reason() {
36428
+ return this[kReason];
36429
+ }
36430
+ /**
36431
+ * @type {Boolean}
36432
+ */
36433
+ get wasClean() {
36434
+ return this[kWasClean];
36435
+ }
36436
+ };
36437
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
36438
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
36439
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
36440
+ var ErrorEvent = class extends Event {
36441
+ /**
36442
+ * Create a new `ErrorEvent`.
36443
+ *
36444
+ * @param {String} type The name of the event
36445
+ * @param {Object} [options] A dictionary object that allows for setting
36446
+ * attributes via object members of the same name
36447
+ * @param {*} [options.error=null] The error that generated this event
36448
+ * @param {String} [options.message=''] The error message
36449
+ */
36450
+ constructor(type, options = {}) {
36451
+ super(type);
36452
+ this[kError] = options.error === void 0 ? null : options.error;
36453
+ this[kMessage] = options.message === void 0 ? "" : options.message;
36454
+ }
36455
+ /**
36456
+ * @type {*}
36457
+ */
36458
+ get error() {
36459
+ return this[kError];
36460
+ }
36461
+ /**
36462
+ * @type {String}
36463
+ */
36464
+ get message() {
36465
+ return this[kMessage];
36466
+ }
36467
+ };
36468
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
36469
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
36470
+ var MessageEvent = class extends Event {
36471
+ /**
36472
+ * Create a new `MessageEvent`.
36473
+ *
36474
+ * @param {String} type The name of the event
36475
+ * @param {Object} [options] A dictionary object that allows for setting
36476
+ * attributes via object members of the same name
36477
+ * @param {*} [options.data=null] The message content
36478
+ */
36479
+ constructor(type, options = {}) {
36480
+ super(type);
36481
+ this[kData] = options.data === void 0 ? null : options.data;
36482
+ }
36483
+ /**
36484
+ * @type {*}
36485
+ */
36486
+ get data() {
36487
+ return this[kData];
36488
+ }
36489
+ };
36490
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
36491
+ var EventTarget = {
36492
+ /**
36493
+ * Register an event listener.
36494
+ *
36495
+ * @param {String} type A string representing the event type to listen for
36496
+ * @param {(Function|Object)} handler The listener to add
36497
+ * @param {Object} [options] An options object specifies characteristics about
36498
+ * the event listener
36499
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
36500
+ * listener should be invoked at most once after being added. If `true`,
36501
+ * the listener would be automatically removed when invoked.
36502
+ * @public
36503
+ */
36504
+ addEventListener(type, handler, options = {}) {
36505
+ for (const listener of this.listeners(type)) {
36506
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
36507
+ return;
36508
+ }
36509
+ }
36510
+ let wrapper;
36511
+ if (type === "message") {
36512
+ wrapper = function onMessage(data, isBinary) {
36513
+ const event = new MessageEvent("message", {
36514
+ data: isBinary ? data : data.toString()
36515
+ });
36516
+ event[kTarget] = this;
36517
+ callListener(handler, this, event);
36518
+ };
36519
+ } else if (type === "close") {
36520
+ wrapper = function onClose(code, message) {
36521
+ const event = new CloseEvent("close", {
36522
+ code,
36523
+ reason: message.toString(),
36524
+ wasClean: this._closeFrameReceived && this._closeFrameSent
36525
+ });
36526
+ event[kTarget] = this;
36527
+ callListener(handler, this, event);
36528
+ };
36529
+ } else if (type === "error") {
36530
+ wrapper = function onError(error) {
36531
+ const event = new ErrorEvent("error", {
36532
+ error,
36533
+ message: error.message
36534
+ });
36535
+ event[kTarget] = this;
36536
+ callListener(handler, this, event);
36537
+ };
36538
+ } else if (type === "open") {
36539
+ wrapper = function onOpen() {
36540
+ const event = new Event("open");
36541
+ event[kTarget] = this;
36542
+ callListener(handler, this, event);
36543
+ };
36544
+ } else {
36545
+ return;
36546
+ }
36547
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
36548
+ wrapper[kListener] = handler;
36549
+ if (options.once) {
36550
+ this.once(type, wrapper);
36551
+ } else {
36552
+ this.on(type, wrapper);
36553
+ }
36554
+ },
36555
+ /**
36556
+ * Remove an event listener.
36557
+ *
36558
+ * @param {String} type A string representing the event type to remove
36559
+ * @param {(Function|Object)} handler The listener to remove
36560
+ * @public
36561
+ */
36562
+ removeEventListener(type, handler) {
36563
+ for (const listener of this.listeners(type)) {
36564
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
36565
+ this.removeListener(type, listener);
36566
+ break;
36567
+ }
36568
+ }
36569
+ }
36570
+ };
36571
+ module.exports = {
36572
+ CloseEvent,
36573
+ ErrorEvent,
36574
+ Event,
36575
+ EventTarget,
36576
+ MessageEvent
36577
+ };
36578
+ function callListener(listener, thisArg, event) {
36579
+ if (typeof listener === "object" && listener.handleEvent) {
36580
+ listener.handleEvent.call(listener, event);
36581
+ } else {
36582
+ listener.call(thisArg, event);
36583
+ }
36584
+ }
36585
+ }
36586
+ });
36587
+
36588
+ // node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/extension.js
36589
+ var require_extension = __commonJS({
36590
+ "node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/extension.js"(exports, module) {
36591
+ "use strict";
36592
+ var { tokenChars } = require_validation3();
36593
+ function push(dest, name, elem) {
36594
+ if (dest[name] === void 0) dest[name] = [elem];
36595
+ else dest[name].push(elem);
36596
+ }
36597
+ function parse(header) {
36598
+ const offers = /* @__PURE__ */ Object.create(null);
36599
+ let params = /* @__PURE__ */ Object.create(null);
36600
+ let mustUnescape = false;
36601
+ let isEscaping = false;
36602
+ let inQuotes = false;
36603
+ let extensionName;
36604
+ let paramName;
36605
+ let start = -1;
36606
+ let code = -1;
36607
+ let end = -1;
36608
+ let i = 0;
36609
+ for (; i < header.length; i++) {
36610
+ code = header.charCodeAt(i);
36611
+ if (extensionName === void 0) {
36612
+ if (end === -1 && tokenChars[code] === 1) {
36613
+ if (start === -1) start = i;
36614
+ } else if (i !== 0 && (code === 32 || code === 9)) {
36615
+ if (end === -1 && start !== -1) end = i;
36616
+ } else if (code === 59 || code === 44) {
36617
+ if (start === -1) {
36618
+ throw new SyntaxError(`Unexpected character at index ${i}`);
36619
+ }
36620
+ if (end === -1) end = i;
36621
+ const name = header.slice(start, end);
36622
+ if (code === 44) {
36623
+ push(offers, name, params);
36624
+ params = /* @__PURE__ */ Object.create(null);
36625
+ } else {
36626
+ extensionName = name;
36627
+ }
36628
+ start = end = -1;
36629
+ } else {
36630
+ throw new SyntaxError(`Unexpected character at index ${i}`);
36631
+ }
36632
+ } else if (paramName === void 0) {
36633
+ if (end === -1 && tokenChars[code] === 1) {
36634
+ if (start === -1) start = i;
36635
+ } else if (code === 32 || code === 9) {
36636
+ if (end === -1 && start !== -1) end = i;
36637
+ } else if (code === 59 || code === 44) {
36638
+ if (start === -1) {
36639
+ throw new SyntaxError(`Unexpected character at index ${i}`);
36640
+ }
36641
+ if (end === -1) end = i;
36642
+ push(params, header.slice(start, end), true);
36643
+ if (code === 44) {
36644
+ push(offers, extensionName, params);
36645
+ params = /* @__PURE__ */ Object.create(null);
36646
+ extensionName = void 0;
36647
+ }
36648
+ start = end = -1;
36649
+ } else if (code === 61 && start !== -1 && end === -1) {
36650
+ paramName = header.slice(start, i);
36651
+ start = end = -1;
36652
+ } else {
36653
+ throw new SyntaxError(`Unexpected character at index ${i}`);
36654
+ }
36655
+ } else {
36656
+ if (isEscaping) {
36657
+ if (tokenChars[code] !== 1) {
36658
+ throw new SyntaxError(`Unexpected character at index ${i}`);
36659
+ }
36660
+ if (start === -1) start = i;
36661
+ else if (!mustUnescape) mustUnescape = true;
36662
+ isEscaping = false;
36663
+ } else if (inQuotes) {
36664
+ if (tokenChars[code] === 1) {
36665
+ if (start === -1) start = i;
36666
+ } else if (code === 34 && start !== -1) {
36667
+ inQuotes = false;
36668
+ end = i;
36669
+ } else if (code === 92) {
36670
+ isEscaping = true;
36671
+ } else {
36672
+ throw new SyntaxError(`Unexpected character at index ${i}`);
36673
+ }
36674
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
36675
+ inQuotes = true;
36676
+ } else if (end === -1 && tokenChars[code] === 1) {
36677
+ if (start === -1) start = i;
36678
+ } else if (start !== -1 && (code === 32 || code === 9)) {
36679
+ if (end === -1) end = i;
36680
+ } else if (code === 59 || code === 44) {
36681
+ if (start === -1) {
36682
+ throw new SyntaxError(`Unexpected character at index ${i}`);
36683
+ }
36684
+ if (end === -1) end = i;
36685
+ let value = header.slice(start, end);
36686
+ if (mustUnescape) {
36687
+ value = value.replace(/\\/g, "");
36688
+ mustUnescape = false;
36689
+ }
36690
+ push(params, paramName, value);
36691
+ if (code === 44) {
36692
+ push(offers, extensionName, params);
36693
+ params = /* @__PURE__ */ Object.create(null);
36694
+ extensionName = void 0;
36695
+ }
36696
+ paramName = void 0;
36697
+ start = end = -1;
36698
+ } else {
36699
+ throw new SyntaxError(`Unexpected character at index ${i}`);
36700
+ }
36701
+ }
36702
+ }
36703
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
36704
+ throw new SyntaxError("Unexpected end of input");
36705
+ }
36706
+ if (end === -1) end = i;
36707
+ const token = header.slice(start, end);
36708
+ if (extensionName === void 0) {
36709
+ push(offers, token, params);
36710
+ } else {
36711
+ if (paramName === void 0) {
36712
+ push(params, token, true);
36713
+ } else if (mustUnescape) {
36714
+ push(params, paramName, token.replace(/\\/g, ""));
36715
+ } else {
36716
+ push(params, paramName, token);
36717
+ }
36718
+ push(offers, extensionName, params);
36719
+ }
36720
+ return offers;
36721
+ }
36722
+ function format(extensions) {
36723
+ return Object.keys(extensions).map((extension2) => {
36724
+ let configurations = extensions[extension2];
36725
+ if (!Array.isArray(configurations)) configurations = [configurations];
36726
+ return configurations.map((params) => {
36727
+ return [extension2].concat(
36728
+ Object.keys(params).map((k) => {
36729
+ let values = params[k];
36730
+ if (!Array.isArray(values)) values = [values];
36731
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
36732
+ })
36733
+ ).join("; ");
36734
+ }).join(", ");
36735
+ }).join(", ");
36736
+ }
36737
+ module.exports = { format, parse };
36738
+ }
36739
+ });
36740
+
36741
+ // node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/websocket.js
36742
+ var require_websocket = __commonJS({
36743
+ "node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/websocket.js"(exports, module) {
36744
+ "use strict";
36745
+ var EventEmitter = __require("events");
36746
+ var https2 = __require("https");
36747
+ var http = __require("http");
36748
+ var net = __require("net");
36749
+ var tls = __require("tls");
36750
+ var { randomBytes, createHash: createHash5 } = __require("crypto");
36751
+ var { Duplex, Readable } = __require("stream");
36752
+ var { URL: URL2 } = __require("url");
36753
+ var PerMessageDeflate2 = require_permessage_deflate();
36754
+ var Receiver2 = require_receiver();
36755
+ var Sender2 = require_sender();
36756
+ var { isBlob } = require_validation3();
36757
+ var {
36758
+ BINARY_TYPES,
36759
+ CLOSE_TIMEOUT,
36760
+ EMPTY_BUFFER,
36761
+ GUID,
36762
+ kForOnEventAttribute,
36763
+ kListener,
36764
+ kStatusCode,
36765
+ kWebSocket,
36766
+ NOOP
36767
+ } = require_constants2();
36768
+ var {
36769
+ EventTarget: { addEventListener, removeEventListener }
36770
+ } = require_event_target();
36771
+ var { format, parse } = require_extension();
36772
+ var { toBuffer } = require_buffer_util();
36773
+ var kAborted = /* @__PURE__ */ Symbol("kAborted");
36774
+ var protocolVersions = [8, 13];
36775
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
36776
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
36777
+ var WebSocket2 = class _WebSocket extends EventEmitter {
36778
+ /**
36779
+ * Create a new `WebSocket`.
36780
+ *
36781
+ * @param {(String|URL)} address The URL to which to connect
36782
+ * @param {(String|String[])} [protocols] The subprotocols
36783
+ * @param {Object} [options] Connection options
36784
+ */
36785
+ constructor(address, protocols, options) {
36786
+ super();
36787
+ this._binaryType = BINARY_TYPES[0];
36788
+ this._closeCode = 1006;
36789
+ this._closeFrameReceived = false;
36790
+ this._closeFrameSent = false;
36791
+ this._closeMessage = EMPTY_BUFFER;
36792
+ this._closeTimer = null;
36793
+ this._errorEmitted = false;
36794
+ this._extensions = {};
36795
+ this._paused = false;
36796
+ this._protocol = "";
36797
+ this._readyState = _WebSocket.CONNECTING;
36798
+ this._receiver = null;
36799
+ this._sender = null;
36800
+ this._socket = null;
36801
+ if (address !== null) {
36802
+ this._bufferedAmount = 0;
36803
+ this._isServer = false;
36804
+ this._redirects = 0;
36805
+ if (protocols === void 0) {
36806
+ if (!options || options.protocols === void 0) {
36807
+ protocols = [];
36808
+ } else if (Array.isArray(options.protocols)) {
36809
+ protocols = options.protocols;
36810
+ } else {
36811
+ protocols = [options.protocols];
36812
+ }
36813
+ } else if (!Array.isArray(protocols)) {
36814
+ if (typeof protocols === "object" && protocols !== null) {
36815
+ options = protocols;
36816
+ if (options.protocols === void 0) {
36817
+ protocols = [];
36818
+ } else if (Array.isArray(options.protocols)) {
36819
+ protocols = options.protocols;
36820
+ } else {
36821
+ protocols = [options.protocols];
36822
+ }
36823
+ } else {
36824
+ protocols = [protocols];
36825
+ }
36826
+ }
36827
+ initAsClient(this, address, protocols, options);
36828
+ } else {
36829
+ this._autoPong = options.autoPong;
36830
+ this._closeTimeout = options.closeTimeout;
36831
+ this._isServer = true;
36832
+ }
36833
+ }
36834
+ /**
36835
+ * For historical reasons, the custom "nodebuffer" type is used by the default
36836
+ * instead of "blob".
36837
+ *
36838
+ * @type {String}
36839
+ */
36840
+ get binaryType() {
36841
+ return this._binaryType;
36842
+ }
36843
+ set binaryType(type) {
36844
+ if (!BINARY_TYPES.includes(type)) return;
36845
+ this._binaryType = type;
36846
+ if (this._receiver) this._receiver._binaryType = type;
36847
+ }
36848
+ /**
36849
+ * @type {Number}
36850
+ */
36851
+ get bufferedAmount() {
36852
+ if (!this._socket) return this._bufferedAmount;
36853
+ return this._socket._writableState.length + this._sender._bufferedBytes;
36854
+ }
36855
+ /**
36856
+ * @type {String}
36857
+ */
36858
+ get extensions() {
36859
+ return Object.keys(this._extensions).join();
36860
+ }
36861
+ /**
36862
+ * @type {Boolean}
36863
+ */
36864
+ get isPaused() {
36865
+ return this._paused;
36866
+ }
36867
+ /**
36868
+ * @type {Function}
36869
+ */
36870
+ /* istanbul ignore next */
36871
+ get onclose() {
36872
+ return null;
36873
+ }
36874
+ /**
36875
+ * @type {Function}
36876
+ */
36877
+ /* istanbul ignore next */
36878
+ get onerror() {
36879
+ return null;
36880
+ }
36881
+ /**
36882
+ * @type {Function}
36883
+ */
36884
+ /* istanbul ignore next */
36885
+ get onopen() {
36886
+ return null;
36887
+ }
36888
+ /**
36889
+ * @type {Function}
36890
+ */
36891
+ /* istanbul ignore next */
36892
+ get onmessage() {
36893
+ return null;
36894
+ }
36895
+ /**
36896
+ * @type {String}
36897
+ */
36898
+ get protocol() {
36899
+ return this._protocol;
36900
+ }
36901
+ /**
36902
+ * @type {Number}
36903
+ */
36904
+ get readyState() {
36905
+ return this._readyState;
36906
+ }
36907
+ /**
36908
+ * @type {String}
36909
+ */
36910
+ get url() {
36911
+ return this._url;
36912
+ }
36913
+ /**
36914
+ * Set up the socket and the internal resources.
36915
+ *
36916
+ * @param {Duplex} socket The network socket between the server and client
36917
+ * @param {Buffer} head The first packet of the upgraded stream
36918
+ * @param {Object} options Options object
36919
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
36920
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
36921
+ * multiple times in the same tick
36922
+ * @param {Function} [options.generateMask] The function used to generate the
36923
+ * masking key
36924
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
36925
+ * buffered data chunks
36926
+ * @param {Number} [options.maxFragments=0] The maximum number of message
36927
+ * fragments
36928
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
36929
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
36930
+ * not to skip UTF-8 validation for text and close messages
36931
+ * @private
36932
+ */
36933
+ setSocket(socket, head, options) {
36934
+ const receiver = new Receiver2({
36935
+ allowSynchronousEvents: options.allowSynchronousEvents,
36936
+ binaryType: this.binaryType,
36937
+ extensions: this._extensions,
36938
+ isServer: this._isServer,
36939
+ maxBufferedChunks: options.maxBufferedChunks,
36940
+ maxFragments: options.maxFragments,
36941
+ maxPayload: options.maxPayload,
36942
+ skipUTF8Validation: options.skipUTF8Validation
36943
+ });
36944
+ const sender = new Sender2(socket, this._extensions, options.generateMask);
36945
+ this._receiver = receiver;
36946
+ this._sender = sender;
36947
+ this._socket = socket;
36948
+ receiver[kWebSocket] = this;
36949
+ sender[kWebSocket] = this;
36950
+ socket[kWebSocket] = this;
36951
+ receiver.on("conclude", receiverOnConclude);
36952
+ receiver.on("drain", receiverOnDrain);
36953
+ receiver.on("error", receiverOnError);
36954
+ receiver.on("message", receiverOnMessage);
36955
+ receiver.on("ping", receiverOnPing);
36956
+ receiver.on("pong", receiverOnPong);
36957
+ sender.onerror = senderOnError;
36958
+ if (socket.setTimeout) socket.setTimeout(0);
36959
+ if (socket.setNoDelay) socket.setNoDelay();
36960
+ if (head.length > 0) socket.unshift(head);
36961
+ socket.on("close", socketOnClose);
36962
+ socket.on("data", socketOnData);
36963
+ socket.on("end", socketOnEnd);
36964
+ socket.on("error", socketOnError);
36965
+ this._readyState = _WebSocket.OPEN;
36966
+ this.emit("open");
36967
+ }
36968
+ /**
36969
+ * Emit the `'close'` event.
36970
+ *
36971
+ * @private
36972
+ */
36973
+ emitClose() {
36974
+ if (!this._socket) {
36975
+ this._readyState = _WebSocket.CLOSED;
36976
+ this.emit("close", this._closeCode, this._closeMessage);
36977
+ return;
36978
+ }
36979
+ if (this._extensions[PerMessageDeflate2.extensionName]) {
36980
+ this._extensions[PerMessageDeflate2.extensionName].cleanup();
36981
+ }
36982
+ this._receiver.removeAllListeners();
36983
+ this._readyState = _WebSocket.CLOSED;
36984
+ this.emit("close", this._closeCode, this._closeMessage);
36985
+ }
36986
+ /**
36987
+ * Start a closing handshake.
36988
+ *
36989
+ * +----------+ +-----------+ +----------+
36990
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
36991
+ * | +----------+ +-----------+ +----------+ |
36992
+ * +----------+ +-----------+ |
36993
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
36994
+ * +----------+ +-----------+ |
36995
+ * | | | +---+ |
36996
+ * +------------------------+-->|fin| - - - -
36997
+ * | +---+ | +---+
36998
+ * - - - - -|fin|<---------------------+
36999
+ * +---+
37000
+ *
37001
+ * @param {Number} [code] Status code explaining why the connection is closing
37002
+ * @param {(String|Buffer)} [data] The reason why the connection is
37003
+ * closing
37004
+ * @public
37005
+ */
37006
+ close(code, data) {
37007
+ if (this.readyState === _WebSocket.CLOSED) return;
37008
+ if (this.readyState === _WebSocket.CONNECTING) {
37009
+ const msg = "WebSocket was closed before the connection was established";
37010
+ abortHandshake(this, this._req, msg);
37011
+ return;
37012
+ }
37013
+ if (this.readyState === _WebSocket.CLOSING) {
37014
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
37015
+ this._socket.end();
37016
+ }
37017
+ return;
37018
+ }
37019
+ this._sender.close(code, data, !this._isServer, (err) => {
37020
+ if (err) return;
37021
+ this._closeFrameSent = true;
37022
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
37023
+ this._socket.end();
37024
+ }
37025
+ });
37026
+ this._readyState = _WebSocket.CLOSING;
37027
+ setCloseTimer(this);
37028
+ }
37029
+ /**
37030
+ * Pause the socket.
37031
+ *
37032
+ * @public
37033
+ */
37034
+ pause() {
37035
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
37036
+ return;
37037
+ }
37038
+ this._paused = true;
37039
+ this._socket.pause();
37040
+ }
37041
+ /**
37042
+ * Send a ping.
37043
+ *
37044
+ * @param {*} [data] The data to send
37045
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
37046
+ * @param {Function} [cb] Callback which is executed when the ping is sent
37047
+ * @public
37048
+ */
37049
+ ping(data, mask, cb) {
37050
+ if (this.readyState === _WebSocket.CONNECTING) {
37051
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
37052
+ }
37053
+ if (typeof data === "function") {
37054
+ cb = data;
37055
+ data = mask = void 0;
37056
+ } else if (typeof mask === "function") {
37057
+ cb = mask;
37058
+ mask = void 0;
37059
+ }
37060
+ if (typeof data === "number") data = data.toString();
37061
+ if (this.readyState !== _WebSocket.OPEN) {
37062
+ sendAfterClose(this, data, cb);
37063
+ return;
37064
+ }
37065
+ if (mask === void 0) mask = !this._isServer;
37066
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
37067
+ }
37068
+ /**
37069
+ * Send a pong.
37070
+ *
37071
+ * @param {*} [data] The data to send
37072
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
37073
+ * @param {Function} [cb] Callback which is executed when the pong is sent
37074
+ * @public
37075
+ */
37076
+ pong(data, mask, cb) {
37077
+ if (this.readyState === _WebSocket.CONNECTING) {
37078
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
37079
+ }
37080
+ if (typeof data === "function") {
37081
+ cb = data;
37082
+ data = mask = void 0;
37083
+ } else if (typeof mask === "function") {
37084
+ cb = mask;
37085
+ mask = void 0;
37086
+ }
37087
+ if (typeof data === "number") data = data.toString();
37088
+ if (this.readyState !== _WebSocket.OPEN) {
37089
+ sendAfterClose(this, data, cb);
37090
+ return;
37091
+ }
37092
+ if (mask === void 0) mask = !this._isServer;
37093
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
37094
+ }
37095
+ /**
37096
+ * Resume the socket.
37097
+ *
37098
+ * @public
37099
+ */
37100
+ resume() {
37101
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
37102
+ return;
37103
+ }
37104
+ this._paused = false;
37105
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
37106
+ }
37107
+ /**
37108
+ * Send a data message.
37109
+ *
37110
+ * @param {*} data The message to send
37111
+ * @param {Object} [options] Options object
37112
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
37113
+ * text
37114
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
37115
+ * `data`
37116
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
37117
+ * last one
37118
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
37119
+ * @param {Function} [cb] Callback which is executed when data is written out
37120
+ * @public
37121
+ */
37122
+ send(data, options, cb) {
37123
+ if (this.readyState === _WebSocket.CONNECTING) {
37124
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
37125
+ }
37126
+ if (typeof options === "function") {
37127
+ cb = options;
37128
+ options = {};
37129
+ }
37130
+ if (typeof data === "number") data = data.toString();
37131
+ if (this.readyState !== _WebSocket.OPEN) {
37132
+ sendAfterClose(this, data, cb);
37133
+ return;
37134
+ }
37135
+ const opts = {
37136
+ binary: typeof data !== "string",
37137
+ mask: !this._isServer,
37138
+ compress: true,
37139
+ fin: true,
37140
+ ...options
37141
+ };
37142
+ if (!this._extensions[PerMessageDeflate2.extensionName]) {
37143
+ opts.compress = false;
37144
+ }
37145
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
37146
+ }
37147
+ /**
37148
+ * Forcibly close the connection.
37149
+ *
37150
+ * @public
37151
+ */
37152
+ terminate() {
37153
+ if (this.readyState === _WebSocket.CLOSED) return;
37154
+ if (this.readyState === _WebSocket.CONNECTING) {
37155
+ const msg = "WebSocket was closed before the connection was established";
37156
+ abortHandshake(this, this._req, msg);
37157
+ return;
37158
+ }
37159
+ if (this._socket) {
37160
+ this._readyState = _WebSocket.CLOSING;
37161
+ this._socket.destroy();
37162
+ }
37163
+ }
37164
+ };
37165
+ Object.defineProperty(WebSocket2, "CONNECTING", {
37166
+ enumerable: true,
37167
+ value: readyStates.indexOf("CONNECTING")
37168
+ });
37169
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
37170
+ enumerable: true,
37171
+ value: readyStates.indexOf("CONNECTING")
37172
+ });
37173
+ Object.defineProperty(WebSocket2, "OPEN", {
37174
+ enumerable: true,
37175
+ value: readyStates.indexOf("OPEN")
37176
+ });
37177
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
37178
+ enumerable: true,
37179
+ value: readyStates.indexOf("OPEN")
37180
+ });
37181
+ Object.defineProperty(WebSocket2, "CLOSING", {
37182
+ enumerable: true,
37183
+ value: readyStates.indexOf("CLOSING")
37184
+ });
37185
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
37186
+ enumerable: true,
37187
+ value: readyStates.indexOf("CLOSING")
37188
+ });
37189
+ Object.defineProperty(WebSocket2, "CLOSED", {
37190
+ enumerable: true,
37191
+ value: readyStates.indexOf("CLOSED")
37192
+ });
37193
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
37194
+ enumerable: true,
37195
+ value: readyStates.indexOf("CLOSED")
37196
+ });
37197
+ [
37198
+ "binaryType",
37199
+ "bufferedAmount",
37200
+ "extensions",
37201
+ "isPaused",
37202
+ "protocol",
37203
+ "readyState",
37204
+ "url"
37205
+ ].forEach((property) => {
37206
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
37207
+ });
37208
+ ["open", "error", "close", "message"].forEach((method) => {
37209
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
37210
+ enumerable: true,
37211
+ get() {
37212
+ for (const listener of this.listeners(method)) {
37213
+ if (listener[kForOnEventAttribute]) return listener[kListener];
37214
+ }
37215
+ return null;
37216
+ },
37217
+ set(handler) {
37218
+ for (const listener of this.listeners(method)) {
37219
+ if (listener[kForOnEventAttribute]) {
37220
+ this.removeListener(method, listener);
37221
+ break;
37222
+ }
37223
+ }
37224
+ if (typeof handler !== "function") return;
37225
+ this.addEventListener(method, handler, {
37226
+ [kForOnEventAttribute]: true
37227
+ });
37228
+ }
37229
+ });
37230
+ });
37231
+ WebSocket2.prototype.addEventListener = addEventListener;
37232
+ WebSocket2.prototype.removeEventListener = removeEventListener;
37233
+ module.exports = WebSocket2;
37234
+ function initAsClient(websocket, address, protocols, options) {
37235
+ const opts = {
37236
+ allowSynchronousEvents: true,
37237
+ autoPong: true,
37238
+ closeTimeout: CLOSE_TIMEOUT,
37239
+ protocolVersion: protocolVersions[1],
37240
+ maxBufferedChunks: 256 * 1024,
37241
+ maxFragments: 16 * 1024,
37242
+ maxPayload: 100 * 1024 * 1024,
37243
+ skipUTF8Validation: false,
37244
+ perMessageDeflate: true,
37245
+ followRedirects: false,
37246
+ maxRedirects: 10,
37247
+ ...options,
37248
+ socketPath: void 0,
37249
+ hostname: void 0,
37250
+ protocol: void 0,
37251
+ protocols: void 0,
37252
+ timeout: void 0,
37253
+ method: "GET",
37254
+ host: void 0,
37255
+ path: void 0,
37256
+ port: void 0
37257
+ };
37258
+ websocket._autoPong = opts.autoPong;
37259
+ websocket._closeTimeout = opts.closeTimeout;
37260
+ if (!protocolVersions.includes(opts.protocolVersion)) {
37261
+ throw new RangeError(
37262
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
37263
+ );
37264
+ }
37265
+ let parsedUrl;
37266
+ if (address instanceof URL2) {
37267
+ parsedUrl = address;
37268
+ } else {
37269
+ try {
37270
+ parsedUrl = new URL2(address);
37271
+ } catch {
37272
+ throw new SyntaxError(`Invalid URL: ${address}`);
37273
+ }
37274
+ }
37275
+ if (parsedUrl.protocol === "http:") {
37276
+ parsedUrl.protocol = "ws:";
37277
+ } else if (parsedUrl.protocol === "https:") {
37278
+ parsedUrl.protocol = "wss:";
37279
+ }
37280
+ websocket._url = parsedUrl.href;
37281
+ const isSecure = parsedUrl.protocol === "wss:";
37282
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
37283
+ let invalidUrlMessage;
37284
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
37285
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
37286
+ } else if (isIpcUrl && !parsedUrl.pathname) {
37287
+ invalidUrlMessage = "The URL's pathname is empty";
37288
+ } else if (parsedUrl.hash) {
37289
+ invalidUrlMessage = "The URL contains a fragment identifier";
37290
+ }
37291
+ if (invalidUrlMessage) {
37292
+ const err = new SyntaxError(invalidUrlMessage);
37293
+ if (websocket._redirects === 0) {
37294
+ throw err;
37295
+ } else {
37296
+ emitErrorAndClose(websocket, err);
37297
+ return;
37298
+ }
37299
+ }
37300
+ const defaultPort = isSecure ? 443 : 80;
37301
+ const key = randomBytes(16).toString("base64");
37302
+ const request = isSecure ? https2.request : http.request;
37303
+ const protocolSet = /* @__PURE__ */ new Set();
37304
+ let perMessageDeflate;
37305
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
37306
+ opts.defaultPort = opts.defaultPort || defaultPort;
37307
+ opts.port = parsedUrl.port || defaultPort;
37308
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
37309
+ opts.headers = {
37310
+ ...opts.headers,
37311
+ "Sec-WebSocket-Version": opts.protocolVersion,
37312
+ "Sec-WebSocket-Key": key,
37313
+ Connection: "Upgrade",
37314
+ Upgrade: "websocket"
37315
+ };
37316
+ opts.path = parsedUrl.pathname + parsedUrl.search;
37317
+ opts.timeout = opts.handshakeTimeout;
37318
+ if (opts.perMessageDeflate) {
37319
+ perMessageDeflate = new PerMessageDeflate2({
37320
+ ...opts.perMessageDeflate,
37321
+ isServer: false,
37322
+ maxPayload: opts.maxPayload
37323
+ });
37324
+ opts.headers["Sec-WebSocket-Extensions"] = format({
37325
+ [PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
37326
+ });
37327
+ }
37328
+ if (protocols.length) {
37329
+ for (const protocol of protocols) {
37330
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
37331
+ throw new SyntaxError(
37332
+ "An invalid or duplicated subprotocol was specified"
37333
+ );
37334
+ }
37335
+ protocolSet.add(protocol);
37336
+ }
37337
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
37338
+ }
37339
+ if (opts.origin) {
37340
+ if (opts.protocolVersion < 13) {
37341
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
37342
+ } else {
37343
+ opts.headers.Origin = opts.origin;
37344
+ }
37345
+ }
37346
+ if (parsedUrl.username || parsedUrl.password) {
37347
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
37348
+ }
37349
+ if (isIpcUrl) {
37350
+ const parts = opts.path.split(":");
37351
+ opts.socketPath = parts[0];
37352
+ opts.path = parts[1];
37353
+ }
37354
+ let req;
37355
+ if (opts.followRedirects) {
37356
+ if (websocket._redirects === 0) {
37357
+ websocket._originalIpc = isIpcUrl;
37358
+ websocket._originalSecure = isSecure;
37359
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
37360
+ const headers = options && options.headers;
37361
+ options = { ...options, headers: {} };
37362
+ if (headers) {
37363
+ for (const [key2, value] of Object.entries(headers)) {
37364
+ options.headers[key2.toLowerCase()] = value;
37365
+ }
37366
+ }
37367
+ } else if (websocket.listenerCount("redirect") === 0) {
37368
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
37369
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
37370
+ delete opts.headers.authorization;
37371
+ delete opts.headers.cookie;
37372
+ if (!isSameHost) delete opts.headers.host;
37373
+ opts.auth = void 0;
37374
+ }
37375
+ }
37376
+ if (opts.auth && !options.headers.authorization) {
37377
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
37378
+ }
37379
+ req = websocket._req = request(opts);
37380
+ if (websocket._redirects) {
37381
+ websocket.emit("redirect", websocket.url, req);
37382
+ }
37383
+ } else {
37384
+ req = websocket._req = request(opts);
37385
+ }
37386
+ if (opts.timeout) {
37387
+ req.on("timeout", () => {
37388
+ abortHandshake(websocket, req, "Opening handshake has timed out");
37389
+ });
37390
+ }
37391
+ req.on("error", (err) => {
37392
+ if (req === null || req[kAborted]) return;
37393
+ req = websocket._req = null;
37394
+ emitErrorAndClose(websocket, err);
37395
+ });
37396
+ req.on("response", (res) => {
37397
+ const location = res.headers.location;
37398
+ const statusCode = res.statusCode;
37399
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
37400
+ if (++websocket._redirects > opts.maxRedirects) {
37401
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
37402
+ return;
37403
+ }
37404
+ req.abort();
37405
+ let addr;
37406
+ try {
37407
+ addr = new URL2(location, address);
37408
+ } catch (e) {
37409
+ const err = new SyntaxError(`Invalid URL: ${location}`);
37410
+ emitErrorAndClose(websocket, err);
37411
+ return;
37412
+ }
37413
+ initAsClient(websocket, addr, protocols, options);
37414
+ } else if (!websocket.emit("unexpected-response", req, res)) {
37415
+ abortHandshake(
37416
+ websocket,
37417
+ req,
37418
+ `Unexpected server response: ${res.statusCode}`
37419
+ );
37420
+ }
37421
+ });
37422
+ req.on("upgrade", (res, socket, head) => {
37423
+ websocket.emit("upgrade", res);
37424
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
37425
+ req = websocket._req = null;
37426
+ const upgrade = res.headers.upgrade;
37427
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
37428
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
37429
+ return;
37430
+ }
37431
+ const digest2 = createHash5("sha1").update(key + GUID).digest("base64");
37432
+ if (res.headers["sec-websocket-accept"] !== digest2) {
37433
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
37434
+ return;
37435
+ }
37436
+ const serverProt = res.headers["sec-websocket-protocol"];
37437
+ let protError;
37438
+ if (serverProt !== void 0) {
37439
+ if (!protocolSet.size) {
37440
+ protError = "Server sent a subprotocol but none was requested";
37441
+ } else if (!protocolSet.has(serverProt)) {
37442
+ protError = "Server sent an invalid subprotocol";
37443
+ }
37444
+ } else if (protocolSet.size) {
37445
+ protError = "Server sent no subprotocol";
37446
+ }
37447
+ if (protError) {
37448
+ abortHandshake(websocket, socket, protError);
37449
+ return;
37450
+ }
37451
+ if (serverProt) websocket._protocol = serverProt;
37452
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
37453
+ if (secWebSocketExtensions !== void 0) {
37454
+ if (!perMessageDeflate) {
37455
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
37456
+ abortHandshake(websocket, socket, message);
37457
+ return;
37458
+ }
37459
+ let extensions;
37460
+ try {
37461
+ extensions = parse(secWebSocketExtensions);
37462
+ } catch (err) {
37463
+ const message = "Invalid Sec-WebSocket-Extensions header";
37464
+ abortHandshake(websocket, socket, message);
37465
+ return;
37466
+ }
37467
+ const extensionNames = Object.keys(extensions);
37468
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
37469
+ const message = "Server indicated an extension that was not requested";
37470
+ abortHandshake(websocket, socket, message);
37471
+ return;
37472
+ }
37473
+ try {
37474
+ perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
37475
+ } catch (err) {
37476
+ const message = "Invalid Sec-WebSocket-Extensions header";
37477
+ abortHandshake(websocket, socket, message);
37478
+ return;
37479
+ }
37480
+ websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
37481
+ }
37482
+ websocket.setSocket(socket, head, {
37483
+ allowSynchronousEvents: opts.allowSynchronousEvents,
37484
+ generateMask: opts.generateMask,
37485
+ maxBufferedChunks: opts.maxBufferedChunks,
37486
+ maxFragments: opts.maxFragments,
37487
+ maxPayload: opts.maxPayload,
37488
+ skipUTF8Validation: opts.skipUTF8Validation
37489
+ });
37490
+ });
37491
+ if (opts.finishRequest) {
37492
+ opts.finishRequest(req, websocket);
37493
+ } else {
37494
+ req.end();
37495
+ }
37496
+ }
37497
+ function emitErrorAndClose(websocket, err) {
37498
+ websocket._readyState = WebSocket2.CLOSING;
37499
+ websocket._errorEmitted = true;
37500
+ websocket.emit("error", err);
37501
+ websocket.emitClose();
37502
+ }
37503
+ function netConnect(options) {
37504
+ options.path = options.socketPath;
37505
+ return net.connect(options);
37506
+ }
37507
+ function tlsConnect(options) {
37508
+ options.path = void 0;
37509
+ if (!options.servername && options.servername !== "") {
37510
+ options.servername = net.isIP(options.host) ? "" : options.host;
37511
+ }
37512
+ return tls.connect(options);
37513
+ }
37514
+ function abortHandshake(websocket, stream, message) {
37515
+ websocket._readyState = WebSocket2.CLOSING;
37516
+ const err = new Error(message);
37517
+ Error.captureStackTrace(err, abortHandshake);
37518
+ if (stream.setHeader) {
37519
+ stream[kAborted] = true;
37520
+ stream.abort();
37521
+ if (stream.socket && !stream.socket.destroyed) {
37522
+ stream.socket.destroy();
37523
+ }
37524
+ process.nextTick(emitErrorAndClose, websocket, err);
37525
+ } else {
37526
+ stream.destroy(err);
37527
+ stream.once("error", websocket.emit.bind(websocket, "error"));
37528
+ stream.once("close", websocket.emitClose.bind(websocket));
37529
+ }
37530
+ }
37531
+ function sendAfterClose(websocket, data, cb) {
37532
+ if (data) {
37533
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
37534
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
37535
+ else websocket._bufferedAmount += length;
37536
+ }
37537
+ if (cb) {
37538
+ const err = new Error(
37539
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
37540
+ );
37541
+ process.nextTick(cb, err);
37542
+ }
37543
+ }
37544
+ function receiverOnConclude(code, reason) {
37545
+ const websocket = this[kWebSocket];
37546
+ websocket._closeFrameReceived = true;
37547
+ websocket._closeMessage = reason;
37548
+ websocket._closeCode = code;
37549
+ if (websocket._socket[kWebSocket] === void 0) return;
37550
+ websocket._socket.removeListener("data", socketOnData);
37551
+ process.nextTick(resume, websocket._socket);
37552
+ if (code === 1005) websocket.close();
37553
+ else websocket.close(code, reason);
37554
+ }
37555
+ function receiverOnDrain() {
37556
+ const websocket = this[kWebSocket];
37557
+ if (!websocket.isPaused) websocket._socket.resume();
37558
+ }
37559
+ function receiverOnError(err) {
37560
+ const websocket = this[kWebSocket];
37561
+ if (websocket._socket[kWebSocket] !== void 0) {
37562
+ websocket._socket.removeListener("data", socketOnData);
37563
+ process.nextTick(resume, websocket._socket);
37564
+ websocket.close(err[kStatusCode]);
37565
+ }
37566
+ if (!websocket._errorEmitted) {
37567
+ websocket._errorEmitted = true;
37568
+ websocket.emit("error", err);
37569
+ }
37570
+ }
37571
+ function receiverOnFinish() {
37572
+ this[kWebSocket].emitClose();
37573
+ }
37574
+ function receiverOnMessage(data, isBinary) {
37575
+ this[kWebSocket].emit("message", data, isBinary);
37576
+ }
37577
+ function receiverOnPing(data) {
37578
+ const websocket = this[kWebSocket];
37579
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
37580
+ websocket.emit("ping", data);
37581
+ }
37582
+ function receiverOnPong(data) {
37583
+ this[kWebSocket].emit("pong", data);
37584
+ }
37585
+ function resume(stream) {
37586
+ stream.resume();
37587
+ }
37588
+ function senderOnError(err) {
37589
+ const websocket = this[kWebSocket];
37590
+ if (websocket.readyState === WebSocket2.CLOSED) return;
37591
+ if (websocket.readyState === WebSocket2.OPEN) {
37592
+ websocket._readyState = WebSocket2.CLOSING;
37593
+ setCloseTimer(websocket);
37594
+ }
37595
+ this._socket.end();
37596
+ if (!websocket._errorEmitted) {
37597
+ websocket._errorEmitted = true;
37598
+ websocket.emit("error", err);
37599
+ }
37600
+ }
37601
+ function setCloseTimer(websocket) {
37602
+ websocket._closeTimer = setTimeout(
37603
+ websocket._socket.destroy.bind(websocket._socket),
37604
+ websocket._closeTimeout
37605
+ );
37606
+ }
37607
+ function socketOnClose() {
37608
+ const websocket = this[kWebSocket];
37609
+ this.removeListener("close", socketOnClose);
37610
+ this.removeListener("data", socketOnData);
37611
+ this.removeListener("end", socketOnEnd);
37612
+ websocket._readyState = WebSocket2.CLOSING;
37613
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
37614
+ const chunk = this.read(this._readableState.length);
37615
+ websocket._receiver.write(chunk);
37616
+ }
37617
+ websocket._receiver.end();
37618
+ this[kWebSocket] = void 0;
37619
+ clearTimeout(websocket._closeTimer);
37620
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
37621
+ websocket.emitClose();
37622
+ } else {
37623
+ websocket._receiver.on("error", receiverOnFinish);
37624
+ websocket._receiver.on("finish", receiverOnFinish);
37625
+ }
37626
+ }
37627
+ function socketOnData(chunk) {
37628
+ if (!this[kWebSocket]._receiver.write(chunk)) {
37629
+ this.pause();
37630
+ }
37631
+ }
37632
+ function socketOnEnd() {
37633
+ const websocket = this[kWebSocket];
37634
+ websocket._readyState = WebSocket2.CLOSING;
37635
+ websocket._receiver.end();
37636
+ this.end();
37637
+ }
37638
+ function socketOnError() {
37639
+ const websocket = this[kWebSocket];
37640
+ this.removeListener("error", socketOnError);
37641
+ this.on("error", NOOP);
37642
+ if (websocket) {
37643
+ websocket._readyState = WebSocket2.CLOSING;
37644
+ this.destroy();
37645
+ }
37646
+ }
37647
+ }
37648
+ });
37649
+
37650
+ // node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/stream.js
37651
+ var require_stream = __commonJS({
37652
+ "node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/stream.js"(exports, module) {
37653
+ "use strict";
37654
+ var WebSocket2 = require_websocket();
37655
+ var { Duplex } = __require("stream");
37656
+ function emitClose(stream) {
37657
+ stream.emit("close");
37658
+ }
37659
+ function duplexOnEnd() {
37660
+ if (!this.destroyed && this._writableState.finished) {
37661
+ this.destroy();
37662
+ }
37663
+ }
37664
+ function duplexOnError(err) {
37665
+ this.removeListener("error", duplexOnError);
37666
+ this.destroy();
37667
+ if (this.listenerCount("error") === 0) {
37668
+ this.emit("error", err);
37669
+ }
37670
+ }
37671
+ function createWebSocketStream2(ws, options) {
37672
+ let terminateOnDestroy = true;
37673
+ const duplex = new Duplex({
37674
+ ...options,
37675
+ autoDestroy: false,
37676
+ emitClose: false,
37677
+ objectMode: false,
37678
+ writableObjectMode: false
37679
+ });
37680
+ ws.on("message", function message(msg, isBinary) {
37681
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
37682
+ if (!duplex.push(data)) ws.pause();
37683
+ });
37684
+ ws.once("error", function error(err) {
37685
+ if (duplex.destroyed) return;
37686
+ terminateOnDestroy = false;
37687
+ duplex.destroy(err);
37688
+ });
37689
+ ws.once("close", function close() {
37690
+ if (duplex.destroyed) return;
37691
+ duplex.push(null);
37692
+ });
37693
+ duplex._destroy = function(err, callback) {
37694
+ if (ws.readyState === ws.CLOSED) {
37695
+ callback(err);
37696
+ process.nextTick(emitClose, duplex);
37697
+ return;
37698
+ }
37699
+ let called = false;
37700
+ ws.once("error", function error(err2) {
37701
+ called = true;
37702
+ callback(err2);
37703
+ });
37704
+ ws.once("close", function close() {
37705
+ if (!called) callback(err);
37706
+ process.nextTick(emitClose, duplex);
37707
+ });
37708
+ if (terminateOnDestroy) ws.terminate();
37709
+ };
37710
+ duplex._final = function(callback) {
37711
+ if (ws.readyState === ws.CONNECTING) {
37712
+ ws.once("open", function open5() {
37713
+ duplex._final(callback);
37714
+ });
37715
+ return;
37716
+ }
37717
+ if (ws._socket === null) return;
37718
+ if (ws._socket._writableState.finished) {
37719
+ callback();
37720
+ if (duplex._readableState.endEmitted) duplex.destroy();
37721
+ } else {
37722
+ ws._socket.once("finish", function finish() {
37723
+ callback();
37724
+ });
37725
+ ws.close();
37726
+ }
37727
+ };
37728
+ duplex._read = function() {
37729
+ if (ws.isPaused) ws.resume();
37730
+ };
37731
+ duplex._write = function(chunk, encoding, callback) {
37732
+ if (ws.readyState === ws.CONNECTING) {
37733
+ ws.once("open", function open5() {
37734
+ duplex._write(chunk, encoding, callback);
37735
+ });
37736
+ return;
37737
+ }
37738
+ ws.send(chunk, callback);
37739
+ };
37740
+ duplex.on("end", duplexOnEnd);
37741
+ duplex.on("error", duplexOnError);
37742
+ return duplex;
37743
+ }
37744
+ module.exports = createWebSocketStream2;
37745
+ }
37746
+ });
37747
+
37748
+ // node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/subprotocol.js
37749
+ var require_subprotocol = __commonJS({
37750
+ "node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/subprotocol.js"(exports, module) {
37751
+ "use strict";
37752
+ var { tokenChars } = require_validation3();
37753
+ function parse(header) {
37754
+ const protocols = /* @__PURE__ */ new Set();
37755
+ let start = -1;
37756
+ let end = -1;
37757
+ let i = 0;
37758
+ for (i; i < header.length; i++) {
37759
+ const code = header.charCodeAt(i);
37760
+ if (end === -1 && tokenChars[code] === 1) {
37761
+ if (start === -1) start = i;
37762
+ } else if (i !== 0 && (code === 32 || code === 9)) {
37763
+ if (end === -1 && start !== -1) end = i;
37764
+ } else if (code === 44) {
37765
+ if (start === -1) {
37766
+ throw new SyntaxError(`Unexpected character at index ${i}`);
37767
+ }
37768
+ if (end === -1) end = i;
37769
+ const protocol2 = header.slice(start, end);
37770
+ if (protocols.has(protocol2)) {
37771
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
37772
+ }
37773
+ protocols.add(protocol2);
37774
+ start = end = -1;
37775
+ } else {
37776
+ throw new SyntaxError(`Unexpected character at index ${i}`);
37777
+ }
37778
+ }
37779
+ if (start === -1 || end !== -1) {
37780
+ throw new SyntaxError("Unexpected end of input");
37781
+ }
37782
+ const protocol = header.slice(start, i);
37783
+ if (protocols.has(protocol)) {
37784
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
37785
+ }
37786
+ protocols.add(protocol);
37787
+ return protocols;
37788
+ }
37789
+ module.exports = { parse };
37790
+ }
37791
+ });
37792
+
37793
+ // node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/websocket-server.js
37794
+ var require_websocket_server = __commonJS({
37795
+ "node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/websocket-server.js"(exports, module) {
37796
+ "use strict";
37797
+ var EventEmitter = __require("events");
37798
+ var http = __require("http");
37799
+ var { Duplex } = __require("stream");
37800
+ var { createHash: createHash5 } = __require("crypto");
37801
+ var extension2 = require_extension();
37802
+ var PerMessageDeflate2 = require_permessage_deflate();
37803
+ var subprotocol2 = require_subprotocol();
37804
+ var WebSocket2 = require_websocket();
37805
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants2();
37806
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
37807
+ var RUNNING = 0;
37808
+ var CLOSING = 1;
37809
+ var CLOSED = 2;
37810
+ var WebSocketServer2 = class extends EventEmitter {
37811
+ /**
37812
+ * Create a `WebSocketServer` instance.
37813
+ *
37814
+ * @param {Object} options Configuration options
37815
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
37816
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
37817
+ * multiple times in the same tick
37818
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
37819
+ * automatically send a pong in response to a ping
37820
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
37821
+ * pending connections
37822
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
37823
+ * track clients
37824
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
37825
+ * wait for the closing handshake to finish after `websocket.close()` is
37826
+ * called
37827
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
37828
+ * @param {String} [options.host] The hostname where to bind the server
37829
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
37830
+ * buffered data chunks
37831
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
37832
+ * fragments
37833
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
37834
+ * size
37835
+ * @param {Boolean} [options.noServer=false] Enable no server mode
37836
+ * @param {String} [options.path] Accept only connections matching this path
37837
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
37838
+ * permessage-deflate
37839
+ * @param {Number} [options.port] The port where to bind the server
37840
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
37841
+ * server to use
37842
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
37843
+ * not to skip UTF-8 validation for text and close messages
37844
+ * @param {Function} [options.verifyClient] A hook to reject connections
37845
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
37846
+ * class to use. It must be the `WebSocket` class or class that extends it
37847
+ * @param {Function} [callback] A listener for the `listening` event
37848
+ */
37849
+ constructor(options, callback) {
37850
+ super();
37851
+ options = {
37852
+ allowSynchronousEvents: true,
37853
+ autoPong: true,
37854
+ maxBufferedChunks: 256 * 1024,
37855
+ maxFragments: 16 * 1024,
37856
+ maxPayload: 100 * 1024 * 1024,
37857
+ skipUTF8Validation: false,
37858
+ perMessageDeflate: false,
37859
+ handleProtocols: null,
37860
+ clientTracking: true,
37861
+ closeTimeout: CLOSE_TIMEOUT,
37862
+ verifyClient: null,
37863
+ noServer: false,
37864
+ backlog: null,
37865
+ // use default (511 as implemented in net.js)
37866
+ server: null,
37867
+ host: null,
37868
+ path: null,
37869
+ port: null,
37870
+ WebSocket: WebSocket2,
37871
+ ...options
37872
+ };
37873
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
37874
+ throw new TypeError(
37875
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
37876
+ );
37877
+ }
37878
+ if (options.port != null) {
37879
+ this._server = http.createServer((req, res) => {
37880
+ const body = http.STATUS_CODES[426];
37881
+ res.writeHead(426, {
37882
+ "Content-Length": body.length,
37883
+ "Content-Type": "text/plain"
37884
+ });
37885
+ res.end(body);
37886
+ });
37887
+ this._server.listen(
37888
+ options.port,
37889
+ options.host,
37890
+ options.backlog,
37891
+ callback
37892
+ );
37893
+ } else if (options.server) {
37894
+ this._server = options.server;
37895
+ }
37896
+ if (this._server) {
37897
+ const emitConnection = this.emit.bind(this, "connection");
37898
+ this._removeListeners = addListeners(this._server, {
37899
+ listening: this.emit.bind(this, "listening"),
37900
+ error: this.emit.bind(this, "error"),
37901
+ upgrade: (req, socket, head) => {
37902
+ this.handleUpgrade(req, socket, head, emitConnection);
37903
+ }
37904
+ });
37905
+ }
37906
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
37907
+ if (options.clientTracking) {
37908
+ this.clients = /* @__PURE__ */ new Set();
37909
+ this._shouldEmitClose = false;
37910
+ }
37911
+ this.options = options;
37912
+ this._state = RUNNING;
37913
+ }
37914
+ /**
37915
+ * Returns the bound address, the address family name, and port of the server
37916
+ * as reported by the operating system if listening on an IP socket.
37917
+ * If the server is listening on a pipe or UNIX domain socket, the name is
37918
+ * returned as a string.
37919
+ *
37920
+ * @return {(Object|String|null)} The address of the server
37921
+ * @public
37922
+ */
37923
+ address() {
37924
+ if (this.options.noServer) {
37925
+ throw new Error('The server is operating in "noServer" mode');
37926
+ }
37927
+ if (!this._server) return null;
37928
+ return this._server.address();
37929
+ }
37930
+ /**
37931
+ * Stop the server from accepting new connections and emit the `'close'` event
37932
+ * when all existing connections are closed.
37933
+ *
37934
+ * @param {Function} [cb] A one-time listener for the `'close'` event
37935
+ * @public
37936
+ */
37937
+ close(cb) {
37938
+ if (this._state === CLOSED) {
37939
+ if (cb) {
37940
+ this.once("close", () => {
37941
+ cb(new Error("The server is not running"));
37942
+ });
37943
+ }
37944
+ process.nextTick(emitClose, this);
37945
+ return;
37946
+ }
37947
+ if (cb) this.once("close", cb);
37948
+ if (this._state === CLOSING) return;
37949
+ this._state = CLOSING;
37950
+ if (this.options.noServer || this.options.server) {
37951
+ if (this._server) {
37952
+ this._removeListeners();
37953
+ this._removeListeners = this._server = null;
37954
+ }
37955
+ if (this.clients) {
37956
+ if (!this.clients.size) {
37957
+ process.nextTick(emitClose, this);
37958
+ } else {
37959
+ this._shouldEmitClose = true;
37960
+ }
37961
+ } else {
37962
+ process.nextTick(emitClose, this);
37963
+ }
37964
+ } else {
37965
+ const server = this._server;
37966
+ this._removeListeners();
37967
+ this._removeListeners = this._server = null;
37968
+ server.close(() => {
37969
+ emitClose(this);
37970
+ });
37971
+ }
37972
+ }
37973
+ /**
37974
+ * See if a given request should be handled by this server instance.
37975
+ *
37976
+ * @param {http.IncomingMessage} req Request object to inspect
37977
+ * @return {Boolean} `true` if the request is valid, else `false`
37978
+ * @public
37979
+ */
37980
+ shouldHandle(req) {
37981
+ if (this.options.path) {
37982
+ const index = req.url.indexOf("?");
37983
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
37984
+ if (pathname !== this.options.path) return false;
37985
+ }
37986
+ return true;
37987
+ }
37988
+ /**
37989
+ * Handle a HTTP Upgrade request.
37990
+ *
37991
+ * @param {http.IncomingMessage} req The request object
37992
+ * @param {Duplex} socket The network socket between the server and client
37993
+ * @param {Buffer} head The first packet of the upgraded stream
37994
+ * @param {Function} cb Callback
37995
+ * @public
37996
+ */
37997
+ handleUpgrade(req, socket, head, cb) {
37998
+ socket.on("error", socketOnError);
37999
+ const key = req.headers["sec-websocket-key"];
38000
+ const upgrade = req.headers.upgrade;
38001
+ const version2 = +req.headers["sec-websocket-version"];
38002
+ if (req.method !== "GET") {
38003
+ const message = "Invalid HTTP method";
38004
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
38005
+ return;
38006
+ }
38007
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
38008
+ const message = "Invalid Upgrade header";
38009
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
38010
+ return;
38011
+ }
38012
+ if (key === void 0 || !keyRegex.test(key)) {
38013
+ const message = "Missing or invalid Sec-WebSocket-Key header";
38014
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
38015
+ return;
38016
+ }
38017
+ if (version2 !== 13 && version2 !== 8) {
38018
+ const message = "Missing or invalid Sec-WebSocket-Version header";
38019
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
38020
+ "Sec-WebSocket-Version": "13, 8"
38021
+ });
38022
+ return;
38023
+ }
38024
+ if (!this.shouldHandle(req)) {
38025
+ abortHandshake(socket, 400);
38026
+ return;
38027
+ }
38028
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
38029
+ let protocols = /* @__PURE__ */ new Set();
38030
+ if (secWebSocketProtocol !== void 0) {
38031
+ try {
38032
+ protocols = subprotocol2.parse(secWebSocketProtocol);
38033
+ } catch (err) {
38034
+ const message = "Invalid Sec-WebSocket-Protocol header";
38035
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
38036
+ return;
38037
+ }
38038
+ }
38039
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
38040
+ const extensions = {};
38041
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
38042
+ const perMessageDeflate = new PerMessageDeflate2({
38043
+ ...this.options.perMessageDeflate,
38044
+ isServer: true,
38045
+ maxPayload: this.options.maxPayload
38046
+ });
38047
+ try {
38048
+ const offers = extension2.parse(secWebSocketExtensions);
38049
+ if (offers[PerMessageDeflate2.extensionName]) {
38050
+ perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
38051
+ extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
38052
+ }
38053
+ } catch (err) {
38054
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
38055
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
38056
+ return;
38057
+ }
38058
+ }
38059
+ if (this.options.verifyClient) {
38060
+ const info = {
38061
+ origin: req.headers[`${version2 === 8 ? "sec-websocket-origin" : "origin"}`],
38062
+ secure: !!(req.socket.authorized || req.socket.encrypted),
38063
+ req
38064
+ };
38065
+ if (this.options.verifyClient.length === 2) {
38066
+ this.options.verifyClient(info, (verified, code, message, headers) => {
38067
+ if (!verified) {
38068
+ return abortHandshake(socket, code || 401, message, headers);
38069
+ }
38070
+ this.completeUpgrade(
38071
+ extensions,
38072
+ key,
38073
+ protocols,
38074
+ req,
38075
+ socket,
38076
+ head,
38077
+ cb
38078
+ );
38079
+ });
38080
+ return;
38081
+ }
38082
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
38083
+ }
38084
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
38085
+ }
38086
+ /**
38087
+ * Upgrade the connection to WebSocket.
38088
+ *
38089
+ * @param {Object} extensions The accepted extensions
38090
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
38091
+ * @param {Set} protocols The subprotocols
38092
+ * @param {http.IncomingMessage} req The request object
38093
+ * @param {Duplex} socket The network socket between the server and client
38094
+ * @param {Buffer} head The first packet of the upgraded stream
38095
+ * @param {Function} cb Callback
38096
+ * @throws {Error} If called more than once with the same socket
38097
+ * @private
38098
+ */
38099
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
38100
+ if (!socket.readable || !socket.writable) return socket.destroy();
38101
+ if (socket[kWebSocket]) {
38102
+ throw new Error(
38103
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
38104
+ );
38105
+ }
38106
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
38107
+ const digest2 = createHash5("sha1").update(key + GUID).digest("base64");
38108
+ const headers = [
38109
+ "HTTP/1.1 101 Switching Protocols",
38110
+ "Upgrade: websocket",
38111
+ "Connection: Upgrade",
38112
+ `Sec-WebSocket-Accept: ${digest2}`
38113
+ ];
38114
+ const ws = new this.options.WebSocket(null, void 0, this.options);
38115
+ if (protocols.size) {
38116
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
38117
+ if (protocol) {
38118
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
38119
+ ws._protocol = protocol;
38120
+ }
38121
+ }
38122
+ if (extensions[PerMessageDeflate2.extensionName]) {
38123
+ const params = extensions[PerMessageDeflate2.extensionName].params;
38124
+ const value = extension2.format({
38125
+ [PerMessageDeflate2.extensionName]: [params]
38126
+ });
38127
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
38128
+ ws._extensions = extensions;
38129
+ }
38130
+ this.emit("headers", headers, req);
38131
+ socket.write(headers.concat("\r\n").join("\r\n"));
38132
+ socket.removeListener("error", socketOnError);
38133
+ ws.setSocket(socket, head, {
38134
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
38135
+ maxBufferedChunks: this.options.maxBufferedChunks,
38136
+ maxFragments: this.options.maxFragments,
38137
+ maxPayload: this.options.maxPayload,
38138
+ skipUTF8Validation: this.options.skipUTF8Validation
38139
+ });
38140
+ if (this.clients) {
38141
+ this.clients.add(ws);
38142
+ ws.on("close", () => {
38143
+ this.clients.delete(ws);
38144
+ if (this._shouldEmitClose && !this.clients.size) {
38145
+ process.nextTick(emitClose, this);
38146
+ }
38147
+ });
38148
+ }
38149
+ cb(ws, req);
38150
+ }
38151
+ };
38152
+ module.exports = WebSocketServer2;
38153
+ function addListeners(server, map) {
38154
+ for (const event of Object.keys(map)) server.on(event, map[event]);
38155
+ return function removeListeners() {
38156
+ for (const event of Object.keys(map)) {
38157
+ server.removeListener(event, map[event]);
38158
+ }
38159
+ };
38160
+ }
38161
+ function emitClose(server) {
38162
+ server._state = CLOSED;
38163
+ server.emit("close");
38164
+ }
38165
+ function socketOnError() {
38166
+ this.destroy();
38167
+ }
38168
+ function abortHandshake(socket, code, message, headers) {
38169
+ message = message || http.STATUS_CODES[code];
38170
+ headers = {
38171
+ Connection: "close",
38172
+ "Content-Type": "text/html",
38173
+ "Content-Length": Buffer.byteLength(message),
38174
+ ...headers
38175
+ };
38176
+ socket.once("finish", socket.destroy);
38177
+ socket.end(
38178
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
38179
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
38180
+ );
38181
+ }
38182
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
38183
+ if (server.listenerCount("wsClientError")) {
38184
+ const err = new Error(message);
38185
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
38186
+ server.emit("wsClientError", err, socket, req);
38187
+ } else {
38188
+ abortHandshake(socket, code, message, headers);
38189
+ }
38190
+ }
38191
+ }
38192
+ });
38193
+
34511
38194
  // apps/product-cli/dist/source-workspace.js
34512
38195
  var import_ignore = __toESM(require_ignore(), 1);
34513
38196
  var import_isomorphic_git = __toESM(require_isomorphic_git(), 1);
@@ -34910,7 +38593,7 @@ var FRAMEWORK_CONVERSION_DETAILS = Object.freeze({
34910
38593
  },
34911
38594
  better_auth_version_required: {
34912
38595
  paths: ["manifest"],
34913
- template: '"{{path}}" must declare better-auth at exactly 1.7.1 in dependencies because ohmyhost.yaml sets auth.provider: better-auth. Pin that version or set auth.provider: none, commit and push the change, then plan the new commit.'
38596
+ template: '"{{path}}" must declare better-auth at exactly 1.7.7 in dependencies because ohmyhost.yaml sets auth.provider: better-auth. Pin that version or set auth.provider: none, commit and push the change, then plan the new commit.'
34914
38597
  },
34915
38598
  package_manifest_invalid: {
34916
38599
  paths: ["manifest"],
@@ -35272,8 +38955,8 @@ var failures = {
35272
38955
  "The built Worker could not be loaded: top-level code throws or calls fetch, timers or random values outside a handler, an import cannot be resolved, a Worker module such as src/ohmyhost/companion.ts has no default export, or the bundle is too large. Fix that, save or push the corrected version and plan its commit; replaying this operation cannot pass. If none of this applies, report the operation ID through feedback."
35273
38956
  ],
35274
38957
  storage_jurisdiction_conflict: [
35275
- "storage.jurisdiction must equal the project's hosting region.",
35276
- "Set storage.jurisdiction in ohmyhost.yaml to the project's region (us or eu) shown by 'ohmyhost project status', save or push the corrected version, then plan its commit (for a promotion, deploy it to Dev and promote again); the unchanged commit fails again. A project cannot move its files between regions; do not delete or recreate the project to change it."
38958
+ "storage.jurisdiction must match the project's recorded storage jurisdiction.",
38959
+ "Read 'Storage jurisdiction' in 'ohmyhost project context --project ULID --json' and set storage.jurisdiction in ohmyhost.yaml to that recorded value (us or eu). Existing R2 buckets and reservations keep their jurisdiction after a project-region migration; only new storage without a recorded bucket uses the project region. If context reports unavailable, report the request ID through feedback rather than guessing. Save or push the corrected version and plan its commit; for promotion, deploy it to Dev and promote again. Do not delete or recreate the project to move files."
35277
38960
  ],
35278
38961
  provider_state_absent: [
35279
38962
  "Reconciliation confirmed that the required deployment resources are absent.",
@@ -36439,6 +40122,8 @@ function assertPublishedCreditRateCards(value) {
36439
40122
  meters.add(identity);
36440
40123
  for (const key of ["units_per_charge", "provider_cost_micros", "credit_micros"]) {
36441
40124
  const amount = rate[key];
40125
+ if (key === "provider_cost_micros" && amount === null && rate["meter"] === "pgcf.memory.active")
40126
+ continue;
36442
40127
  if (typeof amount !== "string" || !/^(0|[1-9][0-9]{0,18})$/u.test(amount) || BigInt(amount) > 9223372036854775807n || key === "units_per_charge" && amount === "0")
36443
40128
  throw new TypeError("Invalid rate amount");
36444
40129
  }
@@ -36567,6 +40252,18 @@ var PROBLEM_POLICY = {
36567
40252
  title: "Performance requires Paid access",
36568
40253
  restAction: "Performance compute needs active Paid and usable credits or grace; repeating unchanged does not help. Read 'ohmyhost credits account --organization ULID --json'. On Free, the Owner may start Paid with 'ohmyhost billing checkout --offer paid'; without usable credits, they may add credits. Until then, keep standard compute."
36569
40254
  },
40255
+ compute_paid_required: {
40256
+ status: 403,
40257
+ retryable: false,
40258
+ action: "Database sizes above 256 MiB require active Paid access. Read the account status; keep the existing database until the owner chooses an eligible size or Paid access.",
40259
+ title: "Database size requires Paid access"
40260
+ },
40261
+ compute_storage_shrink_requires_migration: {
40262
+ status: 409,
40263
+ retryable: false,
40264
+ action: "This size includes less storage than the current volume. Keep the current database and plan an explicit data migration to a fresh smaller volume; do not retry the resize or delete data automatically.",
40265
+ title: "Smaller storage requires a data migration"
40266
+ },
36570
40267
  compute_performance_unavailable: {
36571
40268
  status: 503,
36572
40269
  retryable: false,
@@ -36746,9 +40443,9 @@ var PROBLEM_POLICY = {
36746
40443
  storage_jurisdiction_conflict: {
36747
40444
  status: 409,
36748
40445
  retryable: false,
36749
- action: "Set storage.jurisdiction in ohmyhost.yaml to the project's region (us or eu) shown by 'ohmyhost project status', save or push the corrected version, then plan its commit (for a promotion, deploy it to Dev and promote again); the unchanged commit fails again. A project cannot move its files between regions; do not delete or recreate the project to change it.",
40446
+ action: "Read 'Storage jurisdiction' in 'ohmyhost project context --project ULID --json' and set storage.jurisdiction in ohmyhost.yaml to that recorded value (us or eu). Existing R2 buckets and reservations keep their jurisdiction after a project-region migration; only new storage without a recorded bucket uses the project region. If context reports unavailable, report the request ID through feedback rather than guessing. Save or push the corrected version and plan its commit; for promotion, deploy it to Dev and promote again. Do not delete or recreate the project to move files.",
36750
40447
  title: "Storage jurisdiction conflict",
36751
- restAction: "Set storage.jurisdiction in ohmyhost.yaml to the project's region (us or eu) shown by 'ohmyhost project status', save or push the corrected version, then plan its commit (for a promotion, deploy it to Dev and promote again); the unchanged commit fails again. A project cannot move its files between regions; do not delete or recreate the project to change it."
40448
+ restAction: "Read 'Storage jurisdiction' in 'ohmyhost project context --project ULID --json' and set storage.jurisdiction in ohmyhost.yaml to that recorded value (us or eu). Existing R2 buckets and reservations keep their jurisdiction after a project-region migration; only new storage without a recorded bucket uses the project region. If context reports unavailable, report the request ID through feedback rather than guessing. Save or push the corrected version and plan its commit; for promotion, deploy it to Dev and promote again. Do not delete or recreate the project to move files."
36752
40449
  },
36753
40450
  shared_data_requires_promotion: {
36754
40451
  status: 409,
@@ -38768,6 +42465,67 @@ function isUserSecretName(value, action = "set") {
38768
42465
  return action === "delete" ? !INSTALLED_PLATFORM_KEYS.has(value) : !value.startsWith("OHMYHOST_") && !FIXED_PLATFORM_NAMES.has(value);
38769
42466
  }
38770
42467
 
42468
+ // packages/contracts/dist/database-sizes.js
42469
+ var DATABASE_SIZES = Object.freeze([
42470
+ Object.freeze({
42471
+ memoryMiB: 256,
42472
+ storageMiB: 500,
42473
+ cpuMillicores: 250,
42474
+ maxConnections: 20,
42475
+ sizeClassId: "r256-s500m",
42476
+ creditsPerAwakeHour: 10,
42477
+ paidRequired: false
42478
+ }),
42479
+ Object.freeze({
42480
+ memoryMiB: 512,
42481
+ storageMiB: 1024,
42482
+ cpuMillicores: 250,
42483
+ maxConnections: 40,
42484
+ sizeClassId: "r512-s1g",
42485
+ creditsPerAwakeHour: 20,
42486
+ paidRequired: true
42487
+ }),
42488
+ Object.freeze({
42489
+ memoryMiB: 1024,
42490
+ storageMiB: 2048,
42491
+ cpuMillicores: 500,
42492
+ maxConnections: 80,
42493
+ sizeClassId: "r1024-s2g",
42494
+ creditsPerAwakeHour: 40,
42495
+ paidRequired: true
42496
+ }),
42497
+ Object.freeze({
42498
+ memoryMiB: 2048,
42499
+ storageMiB: 4096,
42500
+ cpuMillicores: 1e3,
42501
+ maxConnections: 160,
42502
+ sizeClassId: "r2048-s4g",
42503
+ creditsPerAwakeHour: 80,
42504
+ paidRequired: true
42505
+ }),
42506
+ Object.freeze({
42507
+ memoryMiB: 4096,
42508
+ storageMiB: 8192,
42509
+ cpuMillicores: 2e3,
42510
+ maxConnections: 200,
42511
+ sizeClassId: "r4096-s8g",
42512
+ creditsPerAwakeHour: 160,
42513
+ paidRequired: true
42514
+ })
42515
+ ]);
42516
+ function databaseSizeForMemory(value) {
42517
+ const size = DATABASE_SIZES.find((candidate) => candidate.memoryMiB === value);
42518
+ if (size === void 0)
42519
+ throw new TypeError("Unsupported database memory size");
42520
+ return size;
42521
+ }
42522
+ function databaseSizeForClass(value) {
42523
+ const size = DATABASE_SIZES.find((candidate) => candidate.sizeClassId === value);
42524
+ if (size === void 0)
42525
+ throw new TypeError("Unsupported database size class");
42526
+ return size;
42527
+ }
42528
+
38771
42529
  // packages/workos-auth-contracts/dist/parsing.js
38772
42530
  var WorkosContractError = class extends Error {
38773
42531
  code;
@@ -39759,15 +43517,23 @@ var parseProductCliCommand = (argv) => {
39759
43517
  "--project",
39760
43518
  "--environment",
39761
43519
  "--profile",
43520
+ "--memory-mib",
39762
43521
  "--idempotency-key"
39763
43522
  ]);
39764
- if (!options["--project"] || !options["--idempotency-key"] || options["--profile"] !== "standard" && options["--profile"] !== "performance" || options["--environment"] !== "dev" && options["--environment"] !== "prod")
43523
+ if (!options["--project"] || !options["--idempotency-key"] || options["--profile"] === void 0 === (options["--memory-mib"] === void 0) || options["--profile"] !== void 0 && options["--profile"] !== "standard" && options["--profile"] !== "performance" || options["--environment"] !== "dev" && options["--environment"] !== "prod")
39765
43524
  throw new InvalidCommandError();
43525
+ let selection;
43526
+ if (options["--memory-mib"] !== void 0) {
43527
+ if (!/^(256|512|1024|2048|4096)$/u.test(options["--memory-mib"]))
43528
+ throw new InvalidCommandError();
43529
+ selection = { memoryMiB: databaseSizeForMemory(Number(options["--memory-mib"])).memoryMiB };
43530
+ } else
43531
+ selection = { profile: options["--profile"] };
39766
43532
  return {
39767
43533
  kind: "database-compute-set",
39768
43534
  projectId: options["--project"],
39769
43535
  environment: options["--environment"],
39770
- profile: options["--profile"],
43536
+ ...selection,
39771
43537
  idempotencyKey: options["--idempotency-key"],
39772
43538
  wait,
39773
43539
  credentialStore
@@ -40823,16 +44589,16 @@ var ACCESS_KEYS = [
40823
44589
  ];
40824
44590
  var ACCESS_ROLE_PATTERN = /^ohmyho_da_[0-7][0-9a-hjkmnp-tv-z]{25}_[0-9a-z]{8}$/u;
40825
44591
  function assertProjectDatabaseAccess(value) {
40826
- if (!record2(value) || !exact2(value, ACCESS_KEYS))
44592
+ if (!record2(value) || !exact2(value, accessKeys(value)))
40827
44593
  throw new TypeError("Invalid database access");
40828
44594
  assertAccessFields(value);
40829
44595
  }
40830
44596
  function assertProjectDatabaseAccessCredential(value) {
40831
- if (!record2(value) || !exact2(value, [...ACCESS_KEYS, "connection_uri", "psql_command"]))
44597
+ if (!record2(value) || !exact2(value, [...accessKeys(value), "connection_uri", "psql_command"]))
40832
44598
  throw new TypeError("Invalid database access credential");
40833
44599
  assertAccessFields(value);
40834
44600
  const uri = value["connection_uri"];
40835
- if (typeof uri !== "string" || value["psql_command"] !== `psql '${uri}'`)
44601
+ if (typeof uri !== "string" || (value["provider"] === "pgcf" ? typeof value["psql_command"] !== "string" || !new RegExp(`^ohmyhost database psql --project [0-7][0-9A-HJKMNP-TV-Z]{25} --environment ${value["environment"]} --mode ${value["mode"]}$`, "u").test(value["psql_command"]) : value["psql_command"] !== `psql '${uri}'`))
40836
44602
  throw new TypeError("Invalid database access credential");
40837
44603
  let parsed;
40838
44604
  try {
@@ -40840,7 +44606,7 @@ function assertProjectDatabaseAccessCredential(value) {
40840
44606
  } catch {
40841
44607
  throw new TypeError("Invalid database access credential");
40842
44608
  }
40843
- if (parsed.protocol !== "postgresql:" || decodeURIComponent(parsed.username) !== value["role_name"] || parsed.password === "" || parsed.hostname !== value["host"] || parsed.host !== value["host"] || decodeURIComponent(parsed.pathname.slice(1)) !== "neondb" || parsed.search !== "?sslmode=require")
44609
+ if ((value["provider"] === "pgcf" ? !["postgres:", "postgresql:"].includes(parsed.protocol) : parsed.protocol !== "postgresql:") || decodeURIComponent(parsed.username) !== value["role_name"] || parsed.password === "" || parsed.hostname !== value["host"] || (value["provider"] === "pgcf" ? parsed.port !== "" && parsed.port !== "5432" : parsed.host !== value["host"]) || decodeURIComponent(parsed.pathname.slice(1)) !== value["database"] || parsed.hash !== "" || (value["provider"] === "pgcf" ? !["", "?sslmode=require", "?sslmode=verify-full"].includes(parsed.search) : parsed.search !== "?sslmode=require"))
40844
44610
  throw new TypeError("Invalid database access credential");
40845
44611
  }
40846
44612
  function assertProjectDatabaseAccessPage(value) {
@@ -40849,9 +44615,12 @@ function assertProjectDatabaseAccessPage(value) {
40849
44615
  for (const item of value["items"])
40850
44616
  assertProjectDatabaseAccess(item);
40851
44617
  }
44618
+ function accessKeys(value) {
44619
+ return value["provider"] === "pgcf" ? [...ACCESS_KEYS, "provider", "transport", "websocket_url"] : ACCESS_KEYS;
44620
+ }
40852
44621
  function assertAccessFields(value) {
40853
44622
  const revoked = value["revoked_at"], reason = value["revocation_reason"];
40854
- if (typeof value["access_id"] !== "string" || !/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/u.test(value["access_id"]) || !["dev", "prod"].includes(String(value["environment"])) || !["read", "write"].includes(String(value["mode"])) || typeof value["role_name"] !== "string" || !ACCESS_ROLE_PATTERN.test(value["role_name"]) || typeof value["host"] !== "string" || !/^[a-z0-9]([a-z0-9.-]{0,251}[a-z0-9])?$/u.test(value["host"]) || value["database"] !== "neondb" || value["label"] !== null && accessLabel(value["label"]) !== value["label"] || !["active", "expired", "revoked"].includes(String(value["state"])) || !timestamp2(value["issued_at"]) || !timestamp2(value["expires_at"]) || Date.parse(String(value["expires_at"])) <= Date.parse(String(value["issued_at"])) || revoked !== null && !timestamp2(revoked) || revoked === null !== (reason === null) || reason !== null && !["principal", "expired", "budget", "creation_failed", "data_change"].includes(String(reason)) || value["state"] === "revoked" !== (revoked !== null))
44623
+ if (typeof value["access_id"] !== "string" || !/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/u.test(value["access_id"]) || !["dev", "prod"].includes(String(value["environment"])) || !["read", "write"].includes(String(value["mode"])) || typeof value["role_name"] !== "string" || !ACCESS_ROLE_PATTERN.test(value["role_name"]) || typeof value["host"] !== "string" || !/^[a-z0-9]([a-z0-9.-]{0,251}[a-z0-9])?$/u.test(value["host"]) || (value["provider"] === "pgcf" ? typeof value["database"] !== "string" || !/^[a-z][a-z0-9]{19}$/u.test(value["database"]) || value["transport"] !== "wss" || value["websocket_url"] !== `wss://${value["host"]}/` : value["database"] !== "neondb") || value["label"] !== null && accessLabel(value["label"]) !== value["label"] || !["active", "expired", "revoked"].includes(String(value["state"])) || !timestamp2(value["issued_at"]) || !timestamp2(value["expires_at"]) || Date.parse(String(value["expires_at"])) <= Date.parse(String(value["issued_at"])) || revoked !== null && !timestamp2(revoked) || revoked === null !== (reason === null) || reason !== null && !["principal", "expired", "budget", "creation_failed", "data_change"].includes(String(reason)) || value["state"] === "revoked" !== (revoked !== null))
40855
44624
  throw new TypeError("Invalid database access");
40856
44625
  }
40857
44626
  function accessLabel(value) {
@@ -40900,6 +44669,10 @@ function assertDatabaseCompute(value) {
40900
44669
  const db = value["database"];
40901
44670
  if (db === null)
40902
44671
  return;
44672
+ if (record3(db) && db["provider"] === "pgcf") {
44673
+ assertPgcfCompute(db);
44674
+ return;
44675
+ }
40903
44676
  if (!record3(db) || !exact3(db, [
40904
44677
  "disabled",
40905
44678
  "max_cu",
@@ -40913,6 +44686,24 @@ function assertDatabaseCompute(value) {
40913
44686
  ]) || typeof db["min_cu"] !== "number" || typeof db["max_cu"] !== "number" || !Number.isFinite(db["min_cu"]) || !Number.isFinite(db["max_cu"]) || db["min_cu"] < 0.25 || db["max_cu"] < db["min_cu"] || db["max_cu"] > Number.MAX_SAFE_INTEGER / 4096 || db["min_memory_gb"] !== db["min_cu"] * 4 || db["max_memory_gb"] !== db["max_cu"] * 4 || !Number.isSafeInteger(db["suspend_timeout_seconds"]) || Number(db["suspend_timeout_seconds"]) < -1 || Number(db["suspend_timeout_seconds"]) > 604800 || !["init", "active", "idle"].includes(String(db["state"])) || db["pending_state"] !== null && !["init", "active", "idle"].includes(String(db["pending_state"])) || typeof db["disabled"] !== "boolean" || typeof db["region"] !== "string" || !/^aws-[a-z0-9]+(?:-[a-z0-9]+)*-[0-9]+$/u.test(db["region"]))
40914
44687
  throw new TypeError("Invalid database compute configuration");
40915
44688
  }
44689
+ function assertPgcfCompute(db) {
44690
+ const size = databaseSizeForClass(db["size_class_id"]);
44691
+ const states = ["provisioning", "cold", "warm", "suspended", "error"];
44692
+ if (!exact3(db, [
44693
+ "cpu_millicores",
44694
+ "disabled",
44695
+ "max_connections",
44696
+ "memory_mib",
44697
+ "pending_state",
44698
+ "provider",
44699
+ "region",
44700
+ "size_class_id",
44701
+ "state",
44702
+ "storage_mib",
44703
+ "suspend_timeout_seconds"
44704
+ ]) || db["memory_mib"] !== size.memoryMiB || db["cpu_millicores"] !== size.cpuMillicores || db["storage_mib"] !== size.storageMiB || db["max_connections"] !== size.maxConnections || !Number.isSafeInteger(db["suspend_timeout_seconds"]) || Number(db["suspend_timeout_seconds"]) < 60 || Number(db["suspend_timeout_seconds"]) > 900 || !states.includes(String(db["state"])) || db["pending_state"] !== null && !states.includes(String(db["pending_state"])) || typeof db["disabled"] !== "boolean" || !["us", "eu"].includes(String(db["region"])))
44705
+ throw new TypeError("Invalid fixed database compute configuration");
44706
+ }
40916
44707
  function record3(v) {
40917
44708
  return typeof v === "object" && v !== null && !Array.isArray(v);
40918
44709
  }
@@ -40923,7 +44714,7 @@ function exact3(v, keys) {
40923
44714
  // apps/product-cli/package.json
40924
44715
  var package_default = {
40925
44716
  name: "@ohmyhost/product-cli",
40926
- version: "0.1.38",
44717
+ version: "0.1.40",
40927
44718
  private: true,
40928
44719
  ohmyhost: {
40929
44720
  deployment: "production",
@@ -40964,7 +44755,8 @@ var package_default = {
40964
44755
  "@ohmyhost/sdk-ts": "workspace:*",
40965
44756
  "@ohmyhost/workos-auth-contracts": "workspace:*",
40966
44757
  ignore: "7.0.12",
40967
- "isomorphic-git": "1.43.0"
44758
+ "isomorphic-git": "1.43.0",
44759
+ "@ohmyhost/postgres-bridge": "workspace:*"
40968
44760
  }
40969
44761
  };
40970
44762
 
@@ -41214,7 +45006,7 @@ var PsqlUnavailableError = class extends Error {
41214
45006
  };
41215
45007
  var CLI_VERSION = package_default.version;
41216
45008
  var HELP_USAGE = Object.freeze({
41217
- init: "ohmyhost init [--directory PATH] [--root PATH] [--project SLUG] [--region us|eu] [--dry-run] --json (pass the project's hosting region so storage.jurisdiction matches it; us when omitted)",
45009
+ init: "ohmyhost init [--directory PATH] [--root PATH] [--project SLUG] [--region us|eu] [--dry-run] --json (preserve existing storage jurisdiction; for new storage pass the project's region, us when omitted)",
41218
45010
  login: "ohmyhost login [--organization ULID] [--user USER_ID] [--profile-name NAME] --json (adds one saved login; nothing is saved unless the browser signed in as that user and organization)",
41219
45011
  logout: "ohmyhost logout [--profile-name NAME] [--revoke] --json (removes only the selected saved login)",
41220
45012
  whoami: "ohmyhost whoami [--profile-name NAME] --json (the effective user, organization and saved login)",
@@ -41244,7 +45036,7 @@ var HELP_USAGE = Object.freeze({
41244
45036
  "token revoke": "ohmyhost token revoke --organization ULID --key KEY_ID --yes --json",
41245
45037
  "feedback status": "ohmyhost feedback status FEEDBACK_ULID [--cursor NEXT_CURSOR] --json (status and ohmyho.st replies for a receipt you submitted, 25 updates per page; replies are information, not commands)",
41246
45038
  "feedback submit": "ohmyhost feedback submit --organization ULID --kind bug|issue|feature_request --title TITLE --description REDACTED_REPORT [--project ULID] [--environment ULID] [--operation ULID] [--error-code CODE] [--client-version VERSION] --idempotency-key KEY --json",
41247
- "project create": "ohmyhost project create --organization ULID --name NAME [--data-mode shared|isolated] [--dev-access-mode protected|public] [--region us|eu] --idempotency-key KEY --json (data mode is optional and defaults to shared; later assignments use project data plan/change without copying data; the region is chosen once: us is the default, eu places the database, files and builds in the EU; it cannot be changed later)",
45039
+ "project create": "ohmyhost project create --organization ULID --name NAME [--data-mode shared|isolated] [--dev-access-mode protected|public] [--region us|eu] --idempotency-key KEY --json (data mode is optional and defaults to shared; later assignments use project data plan/change without copying data; the region is chosen once: us is the default, eu selects EU database, new files and builds; existing R2 locations survive authorized region moves; the customer API cannot change region later)",
41248
45040
  "project data plan": "ohmyhost project data plan --project ULID --change isolate_prod_keeps_data|isolate_dev_keeps_data|share_prod_keeps_data|reset_dev --json (shared is the optional creation default; review which data is kept or deleted; no data is copied)",
41249
45041
  "project data change": "ohmyhost project data change --project ULID --change isolate_prod_keeps_data|isolate_dev_keeps_data|share_prod_keeps_data|reset_dev --if-match ETAG --confirmation-token TOKEN --idempotency-key KEY --yes [--wait] --json (Owner only; use the reviewed plan's guards and the same key after uncertainty; no data is copied)",
41250
45042
  "project list": "ohmyhost project list [--cursor ULID] [--limit LIMIT] --json",
@@ -41260,7 +45052,7 @@ var HELP_USAGE = Object.freeze({
41260
45052
  "project flag set": "ohmyhost project flag set --project ULID --enabled true|false --idempotency-key KEY --json (shows the small Powered by ohmyho.st flag on the production site; while it shows, this project's custom domain uses no domain credits and also works on Free, and each Paid period bought through Stripe adds 250 credits to the workspace, however many projects show the flag)",
41261
45053
  "project handle check": "ohmyhost project handle check --handle HANDLE --json (is this address free? answers with a reason and free alternatives; the address becomes HANDLE.check.omh.st)",
41262
45054
  "project handle set": "ohmyhost project handle set --project ULID --handle HANDLE --if-match ETAG --idempotency-key KEY --json (moves the project to a free address; the old one stops working and anyone may claim it)",
41263
- "database compute set": "ohmyhost database compute set --project ULID --environment dev|prod --profile standard|performance --idempotency-key KEY --yes [--wait] --json\n standard: Free 0.25 CU/1 GB, Paid 0.5 CU/2 GB. performance: Paid 1 CU/4 GB, 2.5x database compute credits per equal active minute. All profiles use the provider-default idle suspension.",
45055
+ "database compute set": "ohmyhost database compute set --project ULID --environment dev|prod --memory-mib 256|512|1024|2048|4096 --idempotency-key KEY --yes [--wait] --json\n 10/20/40/80/160 credits per active hour, prorated; includes 500 MiB/1/2/4/8 GiB total disk and seven-day backups. Free supports 256 MiB; larger sizes require Paid. Sleep after 300 idle seconds. No separate database CPU, network or connection charge. Smaller disk requires a separate data migration. Transitional --profile standard|performance is accepted only for legacy provider use; never combine it with --memory-mib.",
41264
45056
  "database compute get": "ohmyhost database compute get --project ULID [--environment dev|prod] --json",
41265
45057
  "database write": "ohmyhost database write --project ULID --environment dev|prod --statement-file PATH --idempotency-key KEY [--parameters-json JSON] --yes --json",
41266
45058
  "database query": "ohmyhost database query --project ULID --environment dev|prod --statement SQL [--parameters-json JSON] --json",
@@ -42249,7 +46041,8 @@ var ProductCli = class {
42249
46041
  exitCode = await spawnPsql({
42250
46042
  host: credential.host,
42251
46043
  user: credential.role_name,
42252
- password: new URL(credential.connection_uri).password,
46044
+ password: decodeURIComponent(new URL(credential.connection_uri).password),
46045
+ ...credential.provider === "pgcf" ? { websocketUrl: credential.websocket_url } : {},
42253
46046
  database: credential.database,
42254
46047
  mode: credential.mode,
42255
46048
  signal
@@ -45783,9 +49576,7 @@ var changeDatabaseCompute = (parameters, options) => {
45783
49576
  { in: "headers", key: "X-Request-Id" },
45784
49577
  { in: "headers", key: "Idempotency-Key" },
45785
49578
  { in: "path", key: "project_id" },
45786
- { in: "body", key: "environment" },
45787
- { in: "body", key: "profile" },
45788
- { in: "body", key: "confirm" }
49579
+ { key: "body", map: "body" }
45789
49580
  ]
45790
49581
  }
45791
49582
  ]);
@@ -47007,9 +50798,11 @@ var GeneratedSdkProductApi = class {
47007
50798
  async changeDatabaseCompute(input) {
47008
50799
  return changeDatabaseCompute({
47009
50800
  project_id: input.projectId,
47010
- environment: input.environment,
47011
- profile: input.profile,
47012
- confirm: true,
50801
+ body: {
50802
+ environment: input.environment,
50803
+ ...input.memoryMiB === void 0 ? { profile: input.profile } : { memory_mib: input.memoryMiB },
50804
+ confirm: true
50805
+ },
47013
50806
  "Idempotency-Key": input.idempotencyKey
47014
50807
  }, { client: this.#client });
47015
50808
  }
@@ -48122,7 +51915,7 @@ function normalizeEgressOrigins(value) {
48122
51915
  }
48123
51916
  function forbiddenEgressHostname(hostname) {
48124
51917
  const normalized = hostname.toLowerCase();
48125
- return /^ohmyho-(?:mail|storage)-gateway-[a-z0-9][a-z0-9-]*\.[a-z0-9][a-z0-9-]*\.workers\.dev\.?$/u.test(normalized) || normalized === "localhost" || normalized.endsWith(".localhost") || normalized.endsWith(".local") || normalized.endsWith(".internal") || /^\d{1,3}(?:\.\d{1,3}){3}$/u.test(normalized) || normalized.startsWith("[") || normalized.endsWith("]");
51918
+ return /(?:^|\.)ohmyho-(?:mail|storage)-gateway-[a-z0-9][a-z0-9-]*\.[a-z0-9][a-z0-9-]*\.workers\.dev\.?$/u.test(normalized) || normalized === "localhost" || normalized.endsWith(".localhost") || normalized.endsWith(".local") || normalized.endsWith(".internal") || /^\d{1,3}(?:\.\d{1,3}){3}$/u.test(normalized) || normalized.startsWith("[") || normalized.endsWith("]");
48126
51919
  }
48127
51920
  function parseOhmyhostConfigYaml(source) {
48128
51921
  if (typeof source !== "string") {
@@ -48163,7 +51956,7 @@ function classifyFrameworkFamily(dependencies) {
48163
51956
  }
48164
51957
 
48165
51958
  // packages/contracts/dist/framework-source-rules.js
48166
- var MANAGED_BETTER_AUTH_VERSION = "1.7.1";
51959
+ var MANAGED_BETTER_AUTH_VERSION = "1.7.7";
48167
51960
  var MAXIMUM_FRAMEWORK_CONFIG_BYTES = 256 * 1024;
48168
51961
  var WORKER_MODULE_PATH = "src/ohmyhost/worker.ts";
48169
51962
  var VITE_COMPANION_ENTRY_PATH = "src/ohmyhost/companion.ts";
@@ -50405,19 +54198,387 @@ var DeviceFlowSession = class {
50405
54198
 
50406
54199
  // apps/product-cli/dist/psql-session.js
50407
54200
  import { spawn } from "node:child_process";
50408
- var runLocalPsql = (input) => new Promise((resolve7, reject) => {
50409
- const child = spawn("psql", ["-h", input.host, "-U", input.user, "-d", input.database], {
50410
- stdio: "inherit",
50411
- signal: input.signal,
50412
- env: { ...process.env, PGPASSWORD: input.password, PGSSLMODE: "require" }
54201
+
54202
+ // packages/postgres-bridge/dist/bridge.js
54203
+ import { createServer } from "node:net";
54204
+
54205
+ // node_modules/.pnpm/ws@8.22.0/node_modules/ws/wrapper.mjs
54206
+ var import_stream = __toESM(require_stream(), 1);
54207
+ var import_extension = __toESM(require_extension(), 1);
54208
+ var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
54209
+ var import_receiver = __toESM(require_receiver(), 1);
54210
+ var import_sender = __toESM(require_sender(), 1);
54211
+ var import_subprotocol = __toESM(require_subprotocol(), 1);
54212
+ var import_websocket = __toESM(require_websocket(), 1);
54213
+ var import_websocket_server = __toESM(require_websocket_server(), 1);
54214
+ var wrapper_default = import_websocket.default;
54215
+
54216
+ // packages/postgres-bridge/dist/options.js
54217
+ var isDatabaseId = (value) => /^[a-z][a-z0-9]{19}$/u.test(value);
54218
+ var isRoleName = (value) => /^[a-z][a-z0-9_]{0,62}$/u.test(value);
54219
+ function validateOptions(value) {
54220
+ let endpoint;
54221
+ try {
54222
+ endpoint = new URL(value.endpoint);
54223
+ } catch {
54224
+ throw new Error("invalid_endpoint");
54225
+ }
54226
+ if (endpoint.protocol !== "wss:" || !endpoint.hostname || endpoint.username || endpoint.password || endpoint.search || endpoint.hash || endpoint.pathname !== "/" || value.endpoint.length > 2048 || /[\s\\?#@]/.test(value.endpoint))
54227
+ throw new Error("invalid_endpoint");
54228
+ if (!isDatabaseId(value.database))
54229
+ throw new Error("invalid_database");
54230
+ if (!isRoleName(value.user))
54231
+ throw new Error("invalid_user");
54232
+ if (!Number.isInteger(value.port) || value.port < 0 || value.port > 65535)
54233
+ throw new Error("invalid_port");
54234
+ return {
54235
+ endpoint: endpoint.href,
54236
+ database: value.database,
54237
+ user: value.user,
54238
+ port: value.port
54239
+ };
54240
+ }
54241
+ function upstreamUrl(options) {
54242
+ const url = new URL(options.endpoint);
54243
+ url.pathname = "/v2";
54244
+ url.searchParams.set("database", options.database);
54245
+ url.searchParams.set("user", options.user);
54246
+ return url.href;
54247
+ }
54248
+
54249
+ // packages/postgres-bridge/dist/auth.js
54250
+ import { Transform } from "node:stream";
54251
+ var AUTH_BYTES = 64 * 1024;
54252
+ var SSL_REQUEST = 80877103;
54253
+ var GSS_REQUEST = 80877104;
54254
+ var BackendAuthentication = class extends Transform {
54255
+ frame = Buffer.alloc(AUTH_BYTES);
54256
+ length = 0;
54257
+ target = 5;
54258
+ offered = false;
54259
+ typed = false;
54260
+ preludes = 0;
54261
+ authenticated = false;
54262
+ constructor() {
54263
+ super({ highWaterMark: AUTH_BYTES });
54264
+ }
54265
+ expectPrelude() {
54266
+ if (this.typed || this.authenticated || this.preludes >= 2)
54267
+ throw new Error("invalid_auth_prelude");
54268
+ this.preludes++;
54269
+ }
54270
+ authentication(frame) {
54271
+ if (frame.length < 9)
54272
+ throw new Error("invalid_auth_frame");
54273
+ const code = frame.readUInt32BE(5);
54274
+ if (code === 3)
54275
+ throw new Error("cleartext_auth_refused");
54276
+ if (code !== 0 && code !== 10 && code !== 11 && code !== 12)
54277
+ throw new Error("unsupported_authentication");
54278
+ if (code === 0) {
54279
+ if (frame.length !== 9)
54280
+ throw new Error("invalid_auth_frame");
54281
+ this.authenticated = true;
54282
+ return frame;
54283
+ }
54284
+ if (code !== 10)
54285
+ return frame;
54286
+ if (this.offered)
54287
+ throw new Error("duplicate_sasl_offer");
54288
+ this.offered = true;
54289
+ const bytes = frame.subarray(9);
54290
+ if (bytes.length < 2 || bytes.at(-1) !== 0 || bytes.at(-2) !== 0)
54291
+ throw new Error("invalid_sasl_offer");
54292
+ const names = bytes.subarray(0, -2).toString("ascii").split("\0");
54293
+ if (bytes.some((value) => value > 127) || names.length > 16 || names.some((name) => !/^[A-Z0-9_-]{1,128}$/.test(name)) || new Set(names).size !== names.length || !names.includes("SCRAM-SHA-256"))
54294
+ throw new Error("invalid_sasl_offer");
54295
+ const retained = names.filter((name) => name !== "SCRAM-SHA-256-PLUS");
54296
+ if (retained.length === names.length)
54297
+ return frame;
54298
+ const mechanisms = Buffer.from(retained.join("\0") + "\0\0");
54299
+ const rewritten = Buffer.alloc(9 + mechanisms.length);
54300
+ rewritten[0] = 82;
54301
+ rewritten.writeUInt32BE(8 + mechanisms.length, 1);
54302
+ rewritten.writeUInt32BE(10, 5);
54303
+ mechanisms.copy(rewritten, 9);
54304
+ return rewritten;
54305
+ }
54306
+ _transform(chunk, _encoding, callback) {
54307
+ try {
54308
+ let offset = 0;
54309
+ while (offset < chunk.length) {
54310
+ if (this.authenticated) {
54311
+ this.push(chunk.subarray(offset));
54312
+ break;
54313
+ }
54314
+ if (this.preludes && this.length === 0) {
54315
+ if (chunk[offset] !== 78)
54316
+ throw new Error("invalid_auth_prelude");
54317
+ this.preludes--;
54318
+ this.push(chunk.subarray(offset, ++offset));
54319
+ continue;
54320
+ }
54321
+ this.typed = true;
54322
+ const count = Math.min(this.target - this.length, chunk.length - offset);
54323
+ chunk.copy(this.frame, this.length, offset, offset + count);
54324
+ this.length += count;
54325
+ offset += count;
54326
+ if (this.length !== this.target)
54327
+ continue;
54328
+ if (this.target === 5) {
54329
+ const length = this.frame.readUInt32BE(1);
54330
+ if (length < 4 || length + 1 > AUTH_BYTES)
54331
+ throw new Error("invalid_auth_frame");
54332
+ this.target = length + 1;
54333
+ if (this.length !== this.target)
54334
+ continue;
54335
+ }
54336
+ const frame = Buffer.from(this.frame.subarray(0, this.target));
54337
+ this.push(frame[0] === 82 ? this.authentication(frame) : frame);
54338
+ this.length = 0;
54339
+ this.target = 5;
54340
+ }
54341
+ callback();
54342
+ } catch (error) {
54343
+ callback(error instanceof Error ? error : new Error("invalid_auth_frame"));
54344
+ }
54345
+ }
54346
+ _flush(callback) {
54347
+ callback(this.length || this.preludes ? new Error("truncated_auth_frame") : void 0);
54348
+ }
54349
+ };
54350
+ var FrontendPrelude = class extends Transform {
54351
+ header = Buffer.alloc(8);
54352
+ length = 0;
54353
+ startup = false;
54354
+ count = 0;
54355
+ backend;
54356
+ constructor(backend) {
54357
+ super({ highWaterMark: AUTH_BYTES });
54358
+ this.backend = backend;
54359
+ }
54360
+ _transform(chunk, _encoding, callback) {
54361
+ try {
54362
+ let offset = 0;
54363
+ while (offset < chunk.length) {
54364
+ if (this.startup || this.backend.authenticated) {
54365
+ if (this.length) {
54366
+ this.push(Buffer.from(this.header.subarray(0, this.length)));
54367
+ this.length = 0;
54368
+ }
54369
+ this.push(chunk.subarray(offset));
54370
+ break;
54371
+ }
54372
+ const count = Math.min(8 - this.length, chunk.length - offset);
54373
+ chunk.copy(this.header, this.length, offset, offset + count);
54374
+ this.length += count;
54375
+ offset += count;
54376
+ if (this.length !== 8)
54377
+ continue;
54378
+ const code = this.header.readUInt32BE(4);
54379
+ if (code === SSL_REQUEST || code === GSS_REQUEST) {
54380
+ if (this.header.readUInt32BE(0) !== 8 || ++this.count > 2)
54381
+ throw new Error("invalid_frontend_prelude");
54382
+ this.backend.expectPrelude();
54383
+ } else
54384
+ this.startup = true;
54385
+ this.push(Buffer.from(this.header));
54386
+ this.length = 0;
54387
+ }
54388
+ callback();
54389
+ } catch (error) {
54390
+ callback(error instanceof Error ? error : new Error("invalid_frontend_prelude"));
54391
+ }
54392
+ }
54393
+ _flush(callback) {
54394
+ if (this.backend.authenticated && this.length) {
54395
+ this.push(Buffer.from(this.header.subarray(0, this.length)));
54396
+ this.length = 0;
54397
+ }
54398
+ callback(this.length ? new Error("truncated_frontend_prelude") : void 0);
54399
+ }
54400
+ };
54401
+
54402
+ // packages/postgres-bridge/dist/bridge.js
54403
+ var STREAM_BYTES = 64 * 1024;
54404
+ var MESSAGE_BYTES = 1024 * 1024;
54405
+ var CLIENT_LIMIT = 16;
54406
+ var HANDSHAKE_MS = 65e3;
54407
+ var FRAGMENT_LIMIT = 128;
54408
+ var HALF_CLOSE_MS = 1e4;
54409
+ var UPSTREAM_OPTIONS = Object.freeze({
54410
+ rejectUnauthorized: true,
54411
+ followRedirects: false,
54412
+ perMessageDeflate: false,
54413
+ autoPong: false,
54414
+ allowSynchronousEvents: false,
54415
+ maxFragments: FRAGMENT_LIMIT,
54416
+ maxBufferedChunks: 256,
54417
+ maxPayload: MESSAGE_BYTES,
54418
+ handshakeTimeout: HANDSHAKE_MS
54419
+ });
54420
+ var connectUpstream = (url) => {
54421
+ if (new URL(url).protocol !== "wss:")
54422
+ throw new Error("invalid_endpoint");
54423
+ return new wrapper_default(url, UPSTREAM_OPTIONS);
54424
+ };
54425
+ async function startBridge(raw, hooks = {}) {
54426
+ const options = validateOptions(raw);
54427
+ const sessions = /* @__PURE__ */ new Set();
54428
+ const endings = /* @__PURE__ */ new Set();
54429
+ let closing;
54430
+ const server = createServer({ highWaterMark: STREAM_BYTES, allowHalfOpen: true }, (local) => {
54431
+ local.on("error", () => {
54432
+ });
54433
+ if (closing || sessions.size >= CLIENT_LIMIT) {
54434
+ local.destroy();
54435
+ return;
54436
+ }
54437
+ let upstream;
54438
+ try {
54439
+ upstream = (hooks.connect ?? connectUpstream)(upstreamUrl(options));
54440
+ } catch {
54441
+ local.destroy();
54442
+ return;
54443
+ }
54444
+ const stream = (0, import_stream.default)(upstream, {
54445
+ highWaterMark: STREAM_BYTES
54446
+ });
54447
+ const authentication = new BackendAuthentication();
54448
+ const frontend = new FrontendPrelude(authentication);
54449
+ const session = { local, upstream, stream, authentication, frontend };
54450
+ sessions.add(session);
54451
+ const ended = new Promise((resolve7) => upstream.once("close", () => resolve7()));
54452
+ endings.add(ended);
54453
+ void ended.then(() => endings.delete(ended));
54454
+ let finished = false;
54455
+ let halfCloseTimer;
54456
+ const finish = () => {
54457
+ if (finished)
54458
+ return;
54459
+ finished = true;
54460
+ if (halfCloseTimer)
54461
+ clearTimeout(halfCloseTimer);
54462
+ local.unpipe(frontend);
54463
+ frontend.unpipe(stream);
54464
+ stream.unpipe(authentication);
54465
+ authentication.unpipe(local);
54466
+ local.destroy();
54467
+ frontend.destroy();
54468
+ authentication.destroy();
54469
+ stream.destroy();
54470
+ upstream.terminate();
54471
+ sessions.delete(session);
54472
+ hooks.disconnected?.();
54473
+ };
54474
+ stream.on("error", finish);
54475
+ authentication.on("error", finish);
54476
+ frontend.on("error", finish);
54477
+ upstream.on("error", finish);
54478
+ local.once("error", finish);
54479
+ local.once("close", finish);
54480
+ local.once("end", () => {
54481
+ if (finished)
54482
+ return;
54483
+ halfCloseTimer = setTimeout(finish, HALF_CLOSE_MS + (upstream.readyState === wrapper_default.CONNECTING ? HANDSHAKE_MS : 0));
54484
+ });
54485
+ stream.once("close", finish);
54486
+ upstream.once("close", () => {
54487
+ if (local.destroyed)
54488
+ finish();
54489
+ });
54490
+ authentication.once("end", () => local.end());
54491
+ upstream.prependListener("message", (_data, binary) => {
54492
+ if (!binary)
54493
+ finish();
54494
+ });
54495
+ upstream.on("ping", (data) => {
54496
+ if (upstream.bufferedAmount >= STREAM_BYTES) {
54497
+ finish();
54498
+ return;
54499
+ }
54500
+ upstream.pong(data, true, (error) => {
54501
+ if (error)
54502
+ finish();
54503
+ });
54504
+ });
54505
+ local.setNoDelay(true);
54506
+ hooks.session?.(session);
54507
+ local.pipe(frontend);
54508
+ frontend.pipe(stream, { end: false });
54509
+ stream.pipe(authentication).pipe(local);
50413
54510
  });
50414
- child.once("error", (error) => {
50415
- reject(error.code === "ENOENT" ? new PsqlUnavailableError() : error);
54511
+ server.maxConnections = CLIENT_LIMIT;
54512
+ await new Promise((resolve7, reject) => {
54513
+ const failed = () => reject(new Error("listener_failed"));
54514
+ server.once("error", failed);
54515
+ server.listen(options.port, [127, 0, 0, 1].join("."), () => {
54516
+ server.removeListener("error", failed);
54517
+ resolve7();
54518
+ });
50416
54519
  });
50417
- child.once("close", (code, signalName) => {
50418
- resolve7(code ?? (signalName === null ? 1 : 130));
54520
+ const address = server.address();
54521
+ const bridge = {
54522
+ host: address.address,
54523
+ port: address.port,
54524
+ get clients() {
54525
+ return sessions.size;
54526
+ },
54527
+ close() {
54528
+ closing ??= (async () => {
54529
+ const listener = new Promise((resolve7) => server.close(() => resolve7()));
54530
+ for (const session of [...sessions])
54531
+ session.local.destroy();
54532
+ await listener;
54533
+ await Promise.all([...endings]);
54534
+ })();
54535
+ return closing;
54536
+ }
54537
+ };
54538
+ server.on("error", bridge.close);
54539
+ return bridge;
54540
+ }
54541
+
54542
+ // apps/product-cli/dist/psql-session.js
54543
+ var runLocalPsql = async (input) => {
54544
+ input.signal.throwIfAborted();
54545
+ if (input.websocketUrl !== void 0 && input.websocketUrl !== `wss://${input.host}/`)
54546
+ throw new Error("Invalid PGCF transport");
54547
+ const bridge = input.websocketUrl === void 0 ? null : await startBridge({
54548
+ endpoint: input.websocketUrl,
54549
+ database: input.database,
54550
+ user: input.user,
54551
+ port: 0
50419
54552
  });
50420
- });
54553
+ try {
54554
+ input.signal.throwIfAborted();
54555
+ const environment = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^PG[A-Z_]+$/iu.test(key)));
54556
+ return await new Promise((resolve7, reject) => {
54557
+ const child = spawn("psql", ["-h", bridge?.host ?? input.host, "-U", input.user, "-d", input.database], {
54558
+ stdio: "inherit",
54559
+ signal: input.signal,
54560
+ env: {
54561
+ ...environment,
54562
+ PGPASSWORD: input.password,
54563
+ PGSSLMODE: bridge ? "disable" : "require",
54564
+ ...bridge ? {
54565
+ PGPORT: String(bridge.port),
54566
+ PGCHANNELBINDING: "disable",
54567
+ PGGSSENCMODE: "disable"
54568
+ } : {}
54569
+ }
54570
+ });
54571
+ child.once("error", (error) => {
54572
+ reject(error.code === "ENOENT" ? new PsqlUnavailableError() : error);
54573
+ });
54574
+ child.once("close", (code, signalName) => {
54575
+ resolve7(code ?? (signalName === null ? 1 : 130));
54576
+ });
54577
+ });
54578
+ } finally {
54579
+ await bridge?.close();
54580
+ }
54581
+ };
50421
54582
 
50422
54583
  // apps/product-cli/dist/composition.js
50423
54584
  var ProductApiAuthenticationError = class extends Error {