@inductiv/node-red-openai-api 6.22.0 → 6.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib.js CHANGED
@@ -406,7 +406,7 @@ var require_version = __commonJS({
406
406
  "use strict";
407
407
  Object.defineProperty(exports2, "__esModule", { value: true });
408
408
  exports2.VERSION = void 0;
409
- exports2.VERSION = "6.22.0";
409
+ exports2.VERSION = "6.27.0";
410
410
  }
411
411
  });
412
412
 
@@ -1175,24 +1175,17 @@ var require_stringify = __commonJS({
1175
1175
  }
1176
1176
  });
1177
1177
 
1178
- // node_modules/openai/internal/qs/index.js
1179
- var require_qs = __commonJS({
1180
- "node_modules/openai/internal/qs/index.js"(exports2) {
1178
+ // node_modules/openai/internal/utils/query.js
1179
+ var require_query = __commonJS({
1180
+ "node_modules/openai/internal/utils/query.js"(exports2) {
1181
1181
  "use strict";
1182
1182
  Object.defineProperty(exports2, "__esModule", { value: true });
1183
- exports2.formats = exports2.stringify = void 0;
1184
- var formats_1 = require_formats();
1185
- var formats = {
1186
- formatters: formats_1.formatters,
1187
- RFC1738: formats_1.RFC1738,
1188
- RFC3986: formats_1.RFC3986,
1189
- default: formats_1.default_format
1190
- };
1191
- exports2.formats = formats;
1192
- var stringify_1 = require_stringify();
1193
- Object.defineProperty(exports2, "stringify", { enumerable: true, get: function() {
1194
- return stringify_1.stringify;
1195
- } });
1183
+ exports2.stringifyQuery = stringifyQuery;
1184
+ var tslib_1 = require_tslib();
1185
+ var qs = tslib_1.__importStar(require_stringify());
1186
+ function stringifyQuery(query) {
1187
+ return qs.stringify(query, { arrayFormat: "brackets" });
1188
+ }
1196
1189
  }
1197
1190
  });
1198
1191
 
@@ -1426,7 +1419,7 @@ var require_streaming = __commonJS({
1426
1419
  this.controller = controller;
1427
1420
  tslib_1.__classPrivateFieldSet(this, _Stream_client, client, "f");
1428
1421
  }
1429
- static fromSSEResponse(response, controller, client) {
1422
+ static fromSSEResponse(response, controller, client, synthesizeEventData) {
1430
1423
  let consumed = false;
1431
1424
  const logger = client ? (0, log_1.loggerFor)(client) : console;
1432
1425
  async function* iterator() {
@@ -1455,7 +1448,7 @@ var require_streaming = __commonJS({
1455
1448
  if (data && data.error) {
1456
1449
  throw new error_2.APIError(void 0, data.error, void 0, response.headers);
1457
1450
  }
1458
- yield data;
1451
+ yield synthesizeEventData ? { event: sse.event, data } : data;
1459
1452
  } else {
1460
1453
  let data;
1461
1454
  try {
@@ -1693,9 +1686,9 @@ var require_parse = __commonJS({
1693
1686
  if (props.options.stream) {
1694
1687
  (0, log_1.loggerFor)(client).debug("response", response.status, response.url, response.headers, response.body);
1695
1688
  if (props.options.__streamClass) {
1696
- return props.options.__streamClass.fromSSEResponse(response, props.controller, client);
1689
+ return props.options.__streamClass.fromSSEResponse(response, props.controller, client, props.options.__synthesizeEventData);
1697
1690
  }
1698
- return streaming_1.Stream.fromSSEResponse(response, props.controller, client);
1691
+ return streaming_1.Stream.fromSSEResponse(response, props.controller, client, props.options.__synthesizeEventData);
1699
1692
  }
1700
1693
  if (response.status === 204) {
1701
1694
  return null;
@@ -4022,6 +4015,8 @@ var require_speech = __commonJS({
4022
4015
  /**
4023
4016
  * Generates audio from the input text.
4024
4017
  *
4018
+ * Returns the audio file content, or a stream of audio events.
4019
+ *
4025
4020
  * @example
4026
4021
  * ```ts
4027
4022
  * const speech = await client.audio.speech.create({
@@ -4338,7 +4333,7 @@ var require_sessions2 = __commonJS({
4338
4333
  var path_1 = require_path();
4339
4334
  var Sessions = class extends resource_1.APIResource {
4340
4335
  /**
4341
- * Create a ChatKit session
4336
+ * Create a ChatKit session.
4342
4337
  *
4343
4338
  * @example
4344
4339
  * ```ts
@@ -4357,7 +4352,9 @@ var require_sessions2 = __commonJS({
4357
4352
  });
4358
4353
  }
4359
4354
  /**
4360
- * Cancel a ChatKit session
4355
+ * Cancel an active ChatKit session and return its most recent metadata.
4356
+ *
4357
+ * Cancelling prevents new requests from using the issued client secret.
4361
4358
  *
4362
4359
  * @example
4363
4360
  * ```ts
@@ -4388,7 +4385,7 @@ var require_threads = __commonJS({
4388
4385
  var path_1 = require_path();
4389
4386
  var Threads = class extends resource_1.APIResource {
4390
4387
  /**
4391
- * Retrieve a ChatKit thread
4388
+ * Retrieve a ChatKit thread by its identifier.
4392
4389
  *
4393
4390
  * @example
4394
4391
  * ```ts
@@ -4403,7 +4400,7 @@ var require_threads = __commonJS({
4403
4400
  });
4404
4401
  }
4405
4402
  /**
4406
- * List ChatKit threads
4403
+ * List ChatKit threads with optional pagination and user filters.
4407
4404
  *
4408
4405
  * @example
4409
4406
  * ```ts
@@ -4421,7 +4418,7 @@ var require_threads = __commonJS({
4421
4418
  });
4422
4419
  }
4423
4420
  /**
4424
- * Delete a ChatKit thread
4421
+ * Delete a ChatKit thread along with its items and stored attachments.
4425
4422
  *
4426
4423
  * @example
4427
4424
  * ```ts
@@ -4437,7 +4434,7 @@ var require_threads = __commonJS({
4437
4434
  });
4438
4435
  }
4439
4436
  /**
4440
- * List ChatKit thread items
4437
+ * List items that belong to a ChatKit thread.
4441
4438
  *
4442
4439
  * @example
4443
4440
  * ```ts
@@ -4689,6 +4686,7 @@ var require_utils2 = __commonJS({
4689
4686
  tslib_1.__exportStar(require_log(), exports2);
4690
4687
  tslib_1.__exportStar(require_uuid(), exports2);
4691
4688
  tslib_1.__exportStar(require_sleep(), exports2);
4689
+ tslib_1.__exportStar(require_query(), exports2);
4692
4690
  }
4693
4691
  });
4694
4692
 
@@ -5271,7 +5269,8 @@ var require_runs = __commonJS({
5271
5269
  body,
5272
5270
  ...options,
5273
5271
  headers: (0, headers_1.buildHeaders)([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
5274
- stream: params.stream ?? false
5272
+ stream: params.stream ?? false,
5273
+ __synthesizeEventData: true
5275
5274
  });
5276
5275
  }
5277
5276
  /**
@@ -5400,7 +5399,8 @@ var require_runs = __commonJS({
5400
5399
  body,
5401
5400
  ...options,
5402
5401
  headers: (0, headers_1.buildHeaders)([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
5403
- stream: params.stream ?? false
5402
+ stream: params.stream ?? false,
5403
+ __synthesizeEventData: true
5404
5404
  });
5405
5405
  }
5406
5406
  /**
@@ -5498,7 +5498,8 @@ var require_threads2 = __commonJS({
5498
5498
  body,
5499
5499
  ...options,
5500
5500
  headers: (0, headers_1.buildHeaders)([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
5501
- stream: body.stream ?? false
5501
+ stream: body.stream ?? false,
5502
+ __synthesizeEventData: true
5502
5503
  });
5503
5504
  }
5504
5505
  /**
@@ -6215,13 +6216,7 @@ var require_permissions = __commonJS({
6215
6216
  * Organization owners can use this endpoint to view all permissions for a
6216
6217
  * fine-tuned model checkpoint.
6217
6218
  *
6218
- * @example
6219
- * ```ts
6220
- * const permission =
6221
- * await client.fineTuning.checkpoints.permissions.retrieve(
6222
- * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
6223
- * );
6224
- * ```
6219
+ * @deprecated Retrieve is deprecated. Please swap to the paginated list method instead.
6225
6220
  */
6226
6221
  retrieve(fineTunedModelCheckpoint, query = {}, options) {
6227
6222
  return this._client.get((0, path_1.path)`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, {
@@ -6229,6 +6224,25 @@ var require_permissions = __commonJS({
6229
6224
  ...options
6230
6225
  });
6231
6226
  }
6227
+ /**
6228
+ * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys).
6229
+ *
6230
+ * Organization owners can use this endpoint to view all permissions for a
6231
+ * fine-tuned model checkpoint.
6232
+ *
6233
+ * @example
6234
+ * ```ts
6235
+ * // Automatically fetches more pages as needed.
6236
+ * for await (const permissionListResponse of client.fineTuning.checkpoints.permissions.list(
6237
+ * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
6238
+ * )) {
6239
+ * // ...
6240
+ * }
6241
+ * ```
6242
+ */
6243
+ list(fineTunedModelCheckpoint, query = {}, options) {
6244
+ return this._client.getAPIList((0, path_1.path)`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, pagination_1.ConversationCursorPage, { query, ...options });
6245
+ }
6232
6246
  /**
6233
6247
  * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys).
6234
6248
  *
@@ -6681,6 +6695,20 @@ var require_client_secrets = __commonJS({
6681
6695
  /**
6682
6696
  * Create a Realtime client secret with an associated session configuration.
6683
6697
  *
6698
+ * Client secrets are short-lived tokens that can be passed to a client app, such
6699
+ * as a web frontend or mobile client, which grants access to the Realtime API
6700
+ * without leaking your main API key. You can configure a custom TTL for each
6701
+ * client secret.
6702
+ *
6703
+ * You can also attach session configuration options to the client secret, which
6704
+ * will be applied to any sessions created using that client secret, but these can
6705
+ * also be overridden by the client connection.
6706
+ *
6707
+ * [Learn more about authentication with client secrets over WebRTC](https://platform.openai.com/docs/guides/realtime-webrtc).
6708
+ *
6709
+ * Returns the created client secret and the effective session object. The client
6710
+ * secret is a string that looks like `ek_1234`.
6711
+ *
6684
6712
  * @example
6685
6713
  * ```ts
6686
6714
  * const clientSecret =
@@ -7206,7 +7234,10 @@ var require_input_tokens = __commonJS({
7206
7234
  var resource_1 = require_resource();
7207
7235
  var InputTokens = class extends resource_1.APIResource {
7208
7236
  /**
7209
- * Get input token counts
7237
+ * Returns input token counts of the request.
7238
+ *
7239
+ * Returns an object with `object` set to `response.input_tokens` and an
7240
+ * `input_tokens` count.
7210
7241
  *
7211
7242
  * @example
7212
7243
  * ```ts
@@ -7304,12 +7335,17 @@ var require_responses = __commonJS({
7304
7335
  return this._client.post((0, path_1.path)`/responses/${responseID}/cancel`, options);
7305
7336
  }
7306
7337
  /**
7307
- * Compact conversation
7338
+ * Compact a conversation. Returns a compacted response object.
7339
+ *
7340
+ * Learn when and how to compact long-running conversations in the
7341
+ * [conversation state guide](https://platform.openai.com/docs/guides/conversation-state#managing-the-context-window).
7342
+ * For ZDR-compatible compaction details, see
7343
+ * [Compaction (advanced)](https://platform.openai.com/docs/guides/conversation-state#compaction-advanced).
7308
7344
  *
7309
7345
  * @example
7310
7346
  * ```ts
7311
7347
  * const compactedResponse = await client.responses.compact({
7312
- * model: 'gpt-5.2',
7348
+ * model: 'gpt-5.4',
7313
7349
  * });
7314
7350
  * ```
7315
7351
  */
@@ -7334,7 +7370,7 @@ var require_content2 = __commonJS({
7334
7370
  var path_1 = require_path();
7335
7371
  var Content = class extends resource_1.APIResource {
7336
7372
  /**
7337
- * Get Skill Content
7373
+ * Download a skill zip bundle by its ID.
7338
7374
  */
7339
7375
  retrieve(skillID, options) {
7340
7376
  return this._client.get((0, path_1.path)`/skills/${skillID}/content`, {
@@ -7359,7 +7395,7 @@ var require_content3 = __commonJS({
7359
7395
  var path_1 = require_path();
7360
7396
  var Content = class extends resource_1.APIResource {
7361
7397
  /**
7362
- * Get Skill Version Content
7398
+ * Download a skill version zip bundle.
7363
7399
  */
7364
7400
  retrieve(version, params, options) {
7365
7401
  const { skill_id } = params;
@@ -7393,20 +7429,20 @@ var require_versions = __commonJS({
7393
7429
  this.content = new ContentAPI.Content(this._client);
7394
7430
  }
7395
7431
  /**
7396
- * Create Skill Version
7432
+ * Create a new immutable skill version.
7397
7433
  */
7398
7434
  create(skillID, body = {}, options) {
7399
7435
  return this._client.post((0, path_1.path)`/skills/${skillID}/versions`, (0, uploads_1.maybeMultipartFormRequestOptions)({ body, ...options }, this._client));
7400
7436
  }
7401
7437
  /**
7402
- * Get Skill Version
7438
+ * Get a specific skill version.
7403
7439
  */
7404
7440
  retrieve(version, params, options) {
7405
7441
  const { skill_id } = params;
7406
7442
  return this._client.get((0, path_1.path)`/skills/${skill_id}/versions/${version}`, options);
7407
7443
  }
7408
7444
  /**
7409
- * List Skill Versions
7445
+ * List skill versions for a skill.
7410
7446
  */
7411
7447
  list(skillID, query = {}, options) {
7412
7448
  return this._client.getAPIList((0, path_1.path)`/skills/${skillID}/versions`, pagination_1.CursorPage, {
@@ -7415,7 +7451,7 @@ var require_versions = __commonJS({
7415
7451
  });
7416
7452
  }
7417
7453
  /**
7418
- * Delete Skill Version
7454
+ * Delete a skill version.
7419
7455
  */
7420
7456
  delete(version, params, options) {
7421
7457
  const { skill_id } = params;
@@ -7449,31 +7485,31 @@ var require_skills = __commonJS({
7449
7485
  this.versions = new VersionsAPI.Versions(this._client);
7450
7486
  }
7451
7487
  /**
7452
- * Create Skill
7488
+ * Create a new skill.
7453
7489
  */
7454
7490
  create(body = {}, options) {
7455
7491
  return this._client.post("/skills", (0, uploads_1.maybeMultipartFormRequestOptions)({ body, ...options }, this._client));
7456
7492
  }
7457
7493
  /**
7458
- * Get Skill
7494
+ * Get a skill by its ID.
7459
7495
  */
7460
7496
  retrieve(skillID, options) {
7461
7497
  return this._client.get((0, path_1.path)`/skills/${skillID}`, options);
7462
7498
  }
7463
7499
  /**
7464
- * Update Skill Default Version
7500
+ * Update the default version pointer for a skill.
7465
7501
  */
7466
7502
  update(skillID, body, options) {
7467
7503
  return this._client.post((0, path_1.path)`/skills/${skillID}`, { body, ...options });
7468
7504
  }
7469
7505
  /**
7470
- * List Skills
7506
+ * List all skills for the current project.
7471
7507
  */
7472
7508
  list(query = {}, options) {
7473
7509
  return this._client.getAPIList("/skills", pagination_1.CursorPage, { query, ...options });
7474
7510
  }
7475
7511
  /**
7476
- * Delete Skill
7512
+ * Delete a skill by its ID.
7477
7513
  */
7478
7514
  delete(skillID, options) {
7479
7515
  return this._client.delete((0, path_1.path)`/skills/${skillID}`, options);
@@ -7552,12 +7588,16 @@ var require_uploads3 = __commonJS({
7552
7588
  * For guidance on the proper filename extensions for each purpose, please follow
7553
7589
  * the documentation on
7554
7590
  * [creating a File](https://platform.openai.com/docs/api-reference/files/create).
7591
+ *
7592
+ * Returns the Upload object with status `pending`.
7555
7593
  */
7556
7594
  create(body, options) {
7557
7595
  return this._client.post("/uploads", { body, ...options });
7558
7596
  }
7559
7597
  /**
7560
7598
  * Cancels the Upload. No Parts may be added after an Upload is cancelled.
7599
+ *
7600
+ * Returns the Upload object with status `cancelled`.
7561
7601
  */
7562
7602
  cancel(uploadID, options) {
7563
7603
  return this._client.post((0, path_1.path)`/uploads/${uploadID}/cancel`, options);
@@ -7575,7 +7615,9 @@ var require_uploads3 = __commonJS({
7575
7615
  *
7576
7616
  * The number of bytes uploaded upon completion must match the number of bytes
7577
7617
  * initially specified when creating the Upload object. No Parts may be added after
7578
- * an Upload is completed.
7618
+ * an Upload is completed. Returns the Upload object with status `completed`,
7619
+ * including an additional `file` property containing the created usable File
7620
+ * object.
7579
7621
  */
7580
7622
  complete(uploadID, body, options) {
7581
7623
  return this._client.post((0, path_1.path)`/uploads/${uploadID}/complete`, { body, ...options });
@@ -7990,31 +8032,33 @@ var require_videos = __commonJS({
7990
8032
  var path_1 = require_path();
7991
8033
  var Videos = class extends resource_1.APIResource {
7992
8034
  /**
7993
- * Create a video
8035
+ * Create a new video generation job from a prompt and optional reference assets.
7994
8036
  */
7995
8037
  create(body, options) {
7996
8038
  return this._client.post("/videos", (0, uploads_1.maybeMultipartFormRequestOptions)({ body, ...options }, this._client));
7997
8039
  }
7998
8040
  /**
7999
- * Retrieve a video
8041
+ * Fetch the latest metadata for a generated video.
8000
8042
  */
8001
8043
  retrieve(videoID, options) {
8002
8044
  return this._client.get((0, path_1.path)`/videos/${videoID}`, options);
8003
8045
  }
8004
8046
  /**
8005
- * List videos
8047
+ * List recently generated videos for the current project.
8006
8048
  */
8007
8049
  list(query = {}, options) {
8008
8050
  return this._client.getAPIList("/videos", pagination_1.ConversationCursorPage, { query, ...options });
8009
8051
  }
8010
8052
  /**
8011
- * Delete a video
8053
+ * Permanently delete a completed or failed video and its stored assets.
8012
8054
  */
8013
8055
  delete(videoID, options) {
8014
8056
  return this._client.delete((0, path_1.path)`/videos/${videoID}`, options);
8015
8057
  }
8016
8058
  /**
8017
- * Download video content
8059
+ * Download the generated video bytes or a derived preview asset.
8060
+ *
8061
+ * Streams the rendered video content for the specified video job.
8018
8062
  */
8019
8063
  downloadContent(videoID, query = {}, options) {
8020
8064
  return this._client.get((0, path_1.path)`/videos/${videoID}/content`, {
@@ -8025,7 +8069,7 @@ var require_videos = __commonJS({
8025
8069
  });
8026
8070
  }
8027
8071
  /**
8028
- * Create a video remix
8072
+ * Create a remix of a completed video using a refreshed prompt.
8029
8073
  */
8030
8074
  remix(videoID, body, options) {
8031
8075
  return this._client.post((0, path_1.path)`/videos/${videoID}/remix`, (0, uploads_1.maybeMultipartFormRequestOptions)({ body, ...options }, this._client));
@@ -8260,7 +8304,7 @@ var require_client = __commonJS({
8260
8304
  var detect_platform_1 = require_detect_platform();
8261
8305
  var Shims = tslib_1.__importStar(require_shims());
8262
8306
  var Opts = tslib_1.__importStar(require_request_options());
8263
- var qs = tslib_1.__importStar(require_qs());
8307
+ var query_1 = require_query();
8264
8308
  var version_1 = require_version();
8265
8309
  var Errors = tslib_1.__importStar(require_error());
8266
8310
  var Pagination = tslib_1.__importStar(require_pagination());
@@ -8397,7 +8441,7 @@ var require_client = __commonJS({
8397
8441
  return (0, headers_1.buildHeaders)([{ Authorization: `Bearer ${this.apiKey}` }]);
8398
8442
  }
8399
8443
  stringifyQuery(query) {
8400
- return qs.stringify(query, { arrayFormat: "brackets" });
8444
+ return (0, query_1.stringifyQuery)(query);
8401
8445
  }
8402
8446
  getUserAgent() {
8403
8447
  return `${this.constructor.name}/JS ${version_1.VERSION}`;
@@ -8640,7 +8684,7 @@ var require_client = __commonJS({
8640
8684
  timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
8641
8685
  }
8642
8686
  }
8643
- if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) {
8687
+ if (timeoutMillis === void 0) {
8644
8688
  const maxRetries = options.maxRetries ?? this.maxRetries;
8645
8689
  timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
8646
8690
  }
@@ -8721,6 +8765,11 @@ var require_client = __commonJS({
8721
8765
  return { bodyHeaders: void 0, body };
8722
8766
  } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) {
8723
8767
  return { bodyHeaders: void 0, body: Shims.ReadableStreamFrom(body) };
8768
+ } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") {
8769
+ return {
8770
+ bodyHeaders: { "content-type": "application/x-www-form-urlencoded" },
8771
+ body: this.stringifyQuery(body)
8772
+ };
8724
8773
  } else {
8725
8774
  return tslib_1.__classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { body, headers });
8726
8775
  }
@@ -9706,71 +9755,3977 @@ var require_methods17 = __commonJS({
9706
9755
  }
9707
9756
  });
9708
9757
 
9709
- // src/responses/methods.js
9710
- var require_methods18 = __commonJS({
9711
- "src/responses/methods.js"(exports2, module2) {
9712
- var OpenAI = require_openai().OpenAI;
9713
- async function streamResponse(parameters, response) {
9714
- const { _node, msg } = parameters;
9715
- _node.status({
9716
- fill: "green",
9717
- shape: "dot",
9718
- text: "OpenaiApi.status.streaming"
9719
- });
9720
- for await (const chunk of response) {
9721
- if (typeof chunk === "object") {
9722
- const newMsg = { ...msg, payload: chunk };
9723
- _node.send(newMsg);
9724
- }
9758
+ // node_modules/ws/lib/constants.js
9759
+ var require_constants = __commonJS({
9760
+ "node_modules/ws/lib/constants.js"(exports2, module2) {
9761
+ "use strict";
9762
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
9763
+ var hasBlob = typeof Blob !== "undefined";
9764
+ if (hasBlob) BINARY_TYPES.push("blob");
9765
+ module2.exports = {
9766
+ BINARY_TYPES,
9767
+ CLOSE_TIMEOUT: 3e4,
9768
+ EMPTY_BUFFER: Buffer.alloc(0),
9769
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
9770
+ hasBlob,
9771
+ kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
9772
+ kListener: Symbol("kListener"),
9773
+ kStatusCode: Symbol("status-code"),
9774
+ kWebSocket: Symbol("websocket"),
9775
+ NOOP: () => {
9725
9776
  }
9726
- _node.status({});
9727
- }
9728
- async function createModelResponse(parameters) {
9729
- const openai = new OpenAI(this.clientParams);
9730
- const response = await openai.responses.create(parameters.payload);
9731
- if (parameters.payload.stream) {
9732
- await streamResponse(parameters, response);
9777
+ };
9778
+ }
9779
+ });
9780
+
9781
+ // node_modules/ws/lib/buffer-util.js
9782
+ var require_buffer_util = __commonJS({
9783
+ "node_modules/ws/lib/buffer-util.js"(exports2, module2) {
9784
+ "use strict";
9785
+ var { EMPTY_BUFFER } = require_constants();
9786
+ var FastBuffer = Buffer[Symbol.species];
9787
+ function concat(list, totalLength) {
9788
+ if (list.length === 0) return EMPTY_BUFFER;
9789
+ if (list.length === 1) return list[0];
9790
+ const target = Buffer.allocUnsafe(totalLength);
9791
+ let offset = 0;
9792
+ for (let i = 0; i < list.length; i++) {
9793
+ const buf = list[i];
9794
+ target.set(buf, offset);
9795
+ offset += buf.length;
9796
+ }
9797
+ if (offset < totalLength) {
9798
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
9799
+ }
9800
+ return target;
9801
+ }
9802
+ function _mask(source, mask, output, offset, length) {
9803
+ for (let i = 0; i < length; i++) {
9804
+ output[offset + i] = source[i] ^ mask[i & 3];
9805
+ }
9806
+ }
9807
+ function _unmask(buffer, mask) {
9808
+ for (let i = 0; i < buffer.length; i++) {
9809
+ buffer[i] ^= mask[i & 3];
9810
+ }
9811
+ }
9812
+ function toArrayBuffer(buf) {
9813
+ if (buf.length === buf.buffer.byteLength) {
9814
+ return buf.buffer;
9815
+ }
9816
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
9817
+ }
9818
+ function toBuffer(data) {
9819
+ toBuffer.readOnly = true;
9820
+ if (Buffer.isBuffer(data)) return data;
9821
+ let buf;
9822
+ if (data instanceof ArrayBuffer) {
9823
+ buf = new FastBuffer(data);
9824
+ } else if (ArrayBuffer.isView(data)) {
9825
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
9733
9826
  } else {
9734
- return response;
9827
+ buf = Buffer.from(data);
9828
+ toBuffer.readOnly = false;
9735
9829
  }
9830
+ return buf;
9736
9831
  }
9737
- async function getModelResponse(parameters) {
9738
- const openai = new OpenAI(this.clientParams);
9739
- const { response_id, ...params } = parameters.payload;
9740
- const response = await openai.responses.retrieve(response_id, params);
9741
- if (params.stream) {
9742
- await streamResponse(parameters, response);
9743
- } else {
9744
- return response;
9832
+ module2.exports = {
9833
+ concat,
9834
+ mask: _mask,
9835
+ toArrayBuffer,
9836
+ toBuffer,
9837
+ unmask: _unmask
9838
+ };
9839
+ if (!process.env.WS_NO_BUFFER_UTIL) {
9840
+ try {
9841
+ const bufferUtil = require("bufferutil");
9842
+ module2.exports.mask = function(source, mask, output, offset, length) {
9843
+ if (length < 48) _mask(source, mask, output, offset, length);
9844
+ else bufferUtil.mask(source, mask, output, offset, length);
9845
+ };
9846
+ module2.exports.unmask = function(buffer, mask) {
9847
+ if (buffer.length < 32) _unmask(buffer, mask);
9848
+ else bufferUtil.unmask(buffer, mask);
9849
+ };
9850
+ } catch (e) {
9745
9851
  }
9746
9852
  }
9747
- async function deleteModelResponse(parameters) {
9748
- const openai = new OpenAI(this.clientParams);
9749
- const { response_id, ...params } = parameters.payload;
9750
- const response = await openai.responses.delete(response_id, params);
9751
- return response;
9853
+ }
9854
+ });
9855
+
9856
+ // node_modules/ws/lib/limiter.js
9857
+ var require_limiter = __commonJS({
9858
+ "node_modules/ws/lib/limiter.js"(exports2, module2) {
9859
+ "use strict";
9860
+ var kDone = Symbol("kDone");
9861
+ var kRun = Symbol("kRun");
9862
+ var Limiter = class {
9863
+ /**
9864
+ * Creates a new `Limiter`.
9865
+ *
9866
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
9867
+ * to run concurrently
9868
+ */
9869
+ constructor(concurrency) {
9870
+ this[kDone] = () => {
9871
+ this.pending--;
9872
+ this[kRun]();
9873
+ };
9874
+ this.concurrency = concurrency || Infinity;
9875
+ this.jobs = [];
9876
+ this.pending = 0;
9877
+ }
9878
+ /**
9879
+ * Adds a job to the queue.
9880
+ *
9881
+ * @param {Function} job The job to run
9882
+ * @public
9883
+ */
9884
+ add(job) {
9885
+ this.jobs.push(job);
9886
+ this[kRun]();
9887
+ }
9888
+ /**
9889
+ * Removes a job from the queue and runs it if possible.
9890
+ *
9891
+ * @private
9892
+ */
9893
+ [kRun]() {
9894
+ if (this.pending === this.concurrency) return;
9895
+ if (this.jobs.length) {
9896
+ const job = this.jobs.shift();
9897
+ this.pending++;
9898
+ job(this[kDone]);
9899
+ }
9900
+ }
9901
+ };
9902
+ module2.exports = Limiter;
9903
+ }
9904
+ });
9905
+
9906
+ // node_modules/ws/lib/permessage-deflate.js
9907
+ var require_permessage_deflate = __commonJS({
9908
+ "node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
9909
+ "use strict";
9910
+ var zlib = require("zlib");
9911
+ var bufferUtil = require_buffer_util();
9912
+ var Limiter = require_limiter();
9913
+ var { kStatusCode } = require_constants();
9914
+ var FastBuffer = Buffer[Symbol.species];
9915
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
9916
+ var kPerMessageDeflate = Symbol("permessage-deflate");
9917
+ var kTotalLength = Symbol("total-length");
9918
+ var kCallback = Symbol("callback");
9919
+ var kBuffers = Symbol("buffers");
9920
+ var kError = Symbol("error");
9921
+ var zlibLimiter;
9922
+ var PerMessageDeflate = class {
9923
+ /**
9924
+ * Creates a PerMessageDeflate instance.
9925
+ *
9926
+ * @param {Object} [options] Configuration options
9927
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
9928
+ * for, or request, a custom client window size
9929
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
9930
+ * acknowledge disabling of client context takeover
9931
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
9932
+ * calls to zlib
9933
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
9934
+ * use of a custom server window size
9935
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
9936
+ * disabling of server context takeover
9937
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
9938
+ * messages should not be compressed if context takeover is disabled
9939
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
9940
+ * deflate
9941
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
9942
+ * inflate
9943
+ * @param {Boolean} [isServer=false] Create the instance in either server or
9944
+ * client mode
9945
+ * @param {Number} [maxPayload=0] The maximum allowed message length
9946
+ */
9947
+ constructor(options, isServer, maxPayload) {
9948
+ this._maxPayload = maxPayload | 0;
9949
+ this._options = options || {};
9950
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
9951
+ this._isServer = !!isServer;
9952
+ this._deflate = null;
9953
+ this._inflate = null;
9954
+ this.params = null;
9955
+ if (!zlibLimiter) {
9956
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
9957
+ zlibLimiter = new Limiter(concurrency);
9958
+ }
9959
+ }
9960
+ /**
9961
+ * @type {String}
9962
+ */
9963
+ static get extensionName() {
9964
+ return "permessage-deflate";
9965
+ }
9966
+ /**
9967
+ * Create an extension negotiation offer.
9968
+ *
9969
+ * @return {Object} Extension parameters
9970
+ * @public
9971
+ */
9972
+ offer() {
9973
+ const params = {};
9974
+ if (this._options.serverNoContextTakeover) {
9975
+ params.server_no_context_takeover = true;
9976
+ }
9977
+ if (this._options.clientNoContextTakeover) {
9978
+ params.client_no_context_takeover = true;
9979
+ }
9980
+ if (this._options.serverMaxWindowBits) {
9981
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
9982
+ }
9983
+ if (this._options.clientMaxWindowBits) {
9984
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
9985
+ } else if (this._options.clientMaxWindowBits == null) {
9986
+ params.client_max_window_bits = true;
9987
+ }
9988
+ return params;
9989
+ }
9990
+ /**
9991
+ * Accept an extension negotiation offer/response.
9992
+ *
9993
+ * @param {Array} configurations The extension negotiation offers/reponse
9994
+ * @return {Object} Accepted configuration
9995
+ * @public
9996
+ */
9997
+ accept(configurations) {
9998
+ configurations = this.normalizeParams(configurations);
9999
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
10000
+ return this.params;
10001
+ }
10002
+ /**
10003
+ * Releases all resources used by the extension.
10004
+ *
10005
+ * @public
10006
+ */
10007
+ cleanup() {
10008
+ if (this._inflate) {
10009
+ this._inflate.close();
10010
+ this._inflate = null;
10011
+ }
10012
+ if (this._deflate) {
10013
+ const callback = this._deflate[kCallback];
10014
+ this._deflate.close();
10015
+ this._deflate = null;
10016
+ if (callback) {
10017
+ callback(
10018
+ new Error(
10019
+ "The deflate stream was closed while data was being processed"
10020
+ )
10021
+ );
10022
+ }
10023
+ }
10024
+ }
10025
+ /**
10026
+ * Accept an extension negotiation offer.
10027
+ *
10028
+ * @param {Array} offers The extension negotiation offers
10029
+ * @return {Object} Accepted configuration
10030
+ * @private
10031
+ */
10032
+ acceptAsServer(offers) {
10033
+ const opts = this._options;
10034
+ const accepted = offers.find((params) => {
10035
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
10036
+ return false;
10037
+ }
10038
+ return true;
10039
+ });
10040
+ if (!accepted) {
10041
+ throw new Error("None of the extension offers can be accepted");
10042
+ }
10043
+ if (opts.serverNoContextTakeover) {
10044
+ accepted.server_no_context_takeover = true;
10045
+ }
10046
+ if (opts.clientNoContextTakeover) {
10047
+ accepted.client_no_context_takeover = true;
10048
+ }
10049
+ if (typeof opts.serverMaxWindowBits === "number") {
10050
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
10051
+ }
10052
+ if (typeof opts.clientMaxWindowBits === "number") {
10053
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
10054
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
10055
+ delete accepted.client_max_window_bits;
10056
+ }
10057
+ return accepted;
10058
+ }
10059
+ /**
10060
+ * Accept the extension negotiation response.
10061
+ *
10062
+ * @param {Array} response The extension negotiation response
10063
+ * @return {Object} Accepted configuration
10064
+ * @private
10065
+ */
10066
+ acceptAsClient(response) {
10067
+ const params = response[0];
10068
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
10069
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
10070
+ }
10071
+ if (!params.client_max_window_bits) {
10072
+ if (typeof this._options.clientMaxWindowBits === "number") {
10073
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
10074
+ }
10075
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
10076
+ throw new Error(
10077
+ 'Unexpected or invalid parameter "client_max_window_bits"'
10078
+ );
10079
+ }
10080
+ return params;
10081
+ }
10082
+ /**
10083
+ * Normalize parameters.
10084
+ *
10085
+ * @param {Array} configurations The extension negotiation offers/reponse
10086
+ * @return {Array} The offers/response with normalized parameters
10087
+ * @private
10088
+ */
10089
+ normalizeParams(configurations) {
10090
+ configurations.forEach((params) => {
10091
+ Object.keys(params).forEach((key) => {
10092
+ let value = params[key];
10093
+ if (value.length > 1) {
10094
+ throw new Error(`Parameter "${key}" must have only a single value`);
10095
+ }
10096
+ value = value[0];
10097
+ if (key === "client_max_window_bits") {
10098
+ if (value !== true) {
10099
+ const num = +value;
10100
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
10101
+ throw new TypeError(
10102
+ `Invalid value for parameter "${key}": ${value}`
10103
+ );
10104
+ }
10105
+ value = num;
10106
+ } else if (!this._isServer) {
10107
+ throw new TypeError(
10108
+ `Invalid value for parameter "${key}": ${value}`
10109
+ );
10110
+ }
10111
+ } else if (key === "server_max_window_bits") {
10112
+ const num = +value;
10113
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
10114
+ throw new TypeError(
10115
+ `Invalid value for parameter "${key}": ${value}`
10116
+ );
10117
+ }
10118
+ value = num;
10119
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
10120
+ if (value !== true) {
10121
+ throw new TypeError(
10122
+ `Invalid value for parameter "${key}": ${value}`
10123
+ );
10124
+ }
10125
+ } else {
10126
+ throw new Error(`Unknown parameter "${key}"`);
10127
+ }
10128
+ params[key] = value;
10129
+ });
10130
+ });
10131
+ return configurations;
10132
+ }
10133
+ /**
10134
+ * Decompress data. Concurrency limited.
10135
+ *
10136
+ * @param {Buffer} data Compressed data
10137
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
10138
+ * @param {Function} callback Callback
10139
+ * @public
10140
+ */
10141
+ decompress(data, fin, callback) {
10142
+ zlibLimiter.add((done) => {
10143
+ this._decompress(data, fin, (err, result) => {
10144
+ done();
10145
+ callback(err, result);
10146
+ });
10147
+ });
10148
+ }
10149
+ /**
10150
+ * Compress data. Concurrency limited.
10151
+ *
10152
+ * @param {(Buffer|String)} data Data to compress
10153
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
10154
+ * @param {Function} callback Callback
10155
+ * @public
10156
+ */
10157
+ compress(data, fin, callback) {
10158
+ zlibLimiter.add((done) => {
10159
+ this._compress(data, fin, (err, result) => {
10160
+ done();
10161
+ callback(err, result);
10162
+ });
10163
+ });
10164
+ }
10165
+ /**
10166
+ * Decompress data.
10167
+ *
10168
+ * @param {Buffer} data Compressed data
10169
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
10170
+ * @param {Function} callback Callback
10171
+ * @private
10172
+ */
10173
+ _decompress(data, fin, callback) {
10174
+ const endpoint = this._isServer ? "client" : "server";
10175
+ if (!this._inflate) {
10176
+ const key = `${endpoint}_max_window_bits`;
10177
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
10178
+ this._inflate = zlib.createInflateRaw({
10179
+ ...this._options.zlibInflateOptions,
10180
+ windowBits
10181
+ });
10182
+ this._inflate[kPerMessageDeflate] = this;
10183
+ this._inflate[kTotalLength] = 0;
10184
+ this._inflate[kBuffers] = [];
10185
+ this._inflate.on("error", inflateOnError);
10186
+ this._inflate.on("data", inflateOnData);
10187
+ }
10188
+ this._inflate[kCallback] = callback;
10189
+ this._inflate.write(data);
10190
+ if (fin) this._inflate.write(TRAILER);
10191
+ this._inflate.flush(() => {
10192
+ const err = this._inflate[kError];
10193
+ if (err) {
10194
+ this._inflate.close();
10195
+ this._inflate = null;
10196
+ callback(err);
10197
+ return;
10198
+ }
10199
+ const data2 = bufferUtil.concat(
10200
+ this._inflate[kBuffers],
10201
+ this._inflate[kTotalLength]
10202
+ );
10203
+ if (this._inflate._readableState.endEmitted) {
10204
+ this._inflate.close();
10205
+ this._inflate = null;
10206
+ } else {
10207
+ this._inflate[kTotalLength] = 0;
10208
+ this._inflate[kBuffers] = [];
10209
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
10210
+ this._inflate.reset();
10211
+ }
10212
+ }
10213
+ callback(null, data2);
10214
+ });
10215
+ }
10216
+ /**
10217
+ * Compress data.
10218
+ *
10219
+ * @param {(Buffer|String)} data Data to compress
10220
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
10221
+ * @param {Function} callback Callback
10222
+ * @private
10223
+ */
10224
+ _compress(data, fin, callback) {
10225
+ const endpoint = this._isServer ? "server" : "client";
10226
+ if (!this._deflate) {
10227
+ const key = `${endpoint}_max_window_bits`;
10228
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
10229
+ this._deflate = zlib.createDeflateRaw({
10230
+ ...this._options.zlibDeflateOptions,
10231
+ windowBits
10232
+ });
10233
+ this._deflate[kTotalLength] = 0;
10234
+ this._deflate[kBuffers] = [];
10235
+ this._deflate.on("data", deflateOnData);
10236
+ }
10237
+ this._deflate[kCallback] = callback;
10238
+ this._deflate.write(data);
10239
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
10240
+ if (!this._deflate) {
10241
+ return;
10242
+ }
10243
+ let data2 = bufferUtil.concat(
10244
+ this._deflate[kBuffers],
10245
+ this._deflate[kTotalLength]
10246
+ );
10247
+ if (fin) {
10248
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
10249
+ }
10250
+ this._deflate[kCallback] = null;
10251
+ this._deflate[kTotalLength] = 0;
10252
+ this._deflate[kBuffers] = [];
10253
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
10254
+ this._deflate.reset();
10255
+ }
10256
+ callback(null, data2);
10257
+ });
10258
+ }
10259
+ };
10260
+ module2.exports = PerMessageDeflate;
10261
+ function deflateOnData(chunk) {
10262
+ this[kBuffers].push(chunk);
10263
+ this[kTotalLength] += chunk.length;
9752
10264
  }
9753
- async function cancelModelResponse(parameters) {
9754
- const openai = new OpenAI(this.clientParams);
9755
- const { response_id, ...params } = parameters.payload;
9756
- const response = await openai.responses.cancel(response_id, params);
9757
- return response;
10265
+ function inflateOnData(chunk) {
10266
+ this[kTotalLength] += chunk.length;
10267
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
10268
+ this[kBuffers].push(chunk);
10269
+ return;
10270
+ }
10271
+ this[kError] = new RangeError("Max payload size exceeded");
10272
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
10273
+ this[kError][kStatusCode] = 1009;
10274
+ this.removeListener("data", inflateOnData);
10275
+ this.reset();
9758
10276
  }
9759
- async function compactModelResponse(parameters) {
9760
- const openai = new OpenAI(this.clientParams);
9761
- const response = await openai.responses.compact(parameters.payload);
9762
- return response;
10277
+ function inflateOnError(err) {
10278
+ this[kPerMessageDeflate]._inflate = null;
10279
+ if (this[kError]) {
10280
+ this[kCallback](this[kError]);
10281
+ return;
10282
+ }
10283
+ err[kStatusCode] = 1007;
10284
+ this[kCallback](err);
9763
10285
  }
9764
- async function listInputItems(parameters) {
9765
- const openai = new OpenAI(this.clientParams);
9766
- const { response_id, ...params } = parameters.payload;
9767
- const list = await openai.responses.inputItems.list(response_id, params);
9768
- return [...list.data];
10286
+ }
10287
+ });
10288
+
10289
+ // node_modules/ws/lib/validation.js
10290
+ var require_validation = __commonJS({
10291
+ "node_modules/ws/lib/validation.js"(exports2, module2) {
10292
+ "use strict";
10293
+ var { isUtf8 } = require("buffer");
10294
+ var { hasBlob } = require_constants();
10295
+ var tokenChars = [
10296
+ 0,
10297
+ 0,
10298
+ 0,
10299
+ 0,
10300
+ 0,
10301
+ 0,
10302
+ 0,
10303
+ 0,
10304
+ 0,
10305
+ 0,
10306
+ 0,
10307
+ 0,
10308
+ 0,
10309
+ 0,
10310
+ 0,
10311
+ 0,
10312
+ // 0 - 15
10313
+ 0,
10314
+ 0,
10315
+ 0,
10316
+ 0,
10317
+ 0,
10318
+ 0,
10319
+ 0,
10320
+ 0,
10321
+ 0,
10322
+ 0,
10323
+ 0,
10324
+ 0,
10325
+ 0,
10326
+ 0,
10327
+ 0,
10328
+ 0,
10329
+ // 16 - 31
10330
+ 0,
10331
+ 1,
10332
+ 0,
10333
+ 1,
10334
+ 1,
10335
+ 1,
10336
+ 1,
10337
+ 1,
10338
+ 0,
10339
+ 0,
10340
+ 1,
10341
+ 1,
10342
+ 0,
10343
+ 1,
10344
+ 1,
10345
+ 0,
10346
+ // 32 - 47
10347
+ 1,
10348
+ 1,
10349
+ 1,
10350
+ 1,
10351
+ 1,
10352
+ 1,
10353
+ 1,
10354
+ 1,
10355
+ 1,
10356
+ 1,
10357
+ 0,
10358
+ 0,
10359
+ 0,
10360
+ 0,
10361
+ 0,
10362
+ 0,
10363
+ // 48 - 63
10364
+ 0,
10365
+ 1,
10366
+ 1,
10367
+ 1,
10368
+ 1,
10369
+ 1,
10370
+ 1,
10371
+ 1,
10372
+ 1,
10373
+ 1,
10374
+ 1,
10375
+ 1,
10376
+ 1,
10377
+ 1,
10378
+ 1,
10379
+ 1,
10380
+ // 64 - 79
10381
+ 1,
10382
+ 1,
10383
+ 1,
10384
+ 1,
10385
+ 1,
10386
+ 1,
10387
+ 1,
10388
+ 1,
10389
+ 1,
10390
+ 1,
10391
+ 1,
10392
+ 0,
10393
+ 0,
10394
+ 0,
10395
+ 1,
10396
+ 1,
10397
+ // 80 - 95
10398
+ 1,
10399
+ 1,
10400
+ 1,
10401
+ 1,
10402
+ 1,
10403
+ 1,
10404
+ 1,
10405
+ 1,
10406
+ 1,
10407
+ 1,
10408
+ 1,
10409
+ 1,
10410
+ 1,
10411
+ 1,
10412
+ 1,
10413
+ 1,
10414
+ // 96 - 111
10415
+ 1,
10416
+ 1,
10417
+ 1,
10418
+ 1,
10419
+ 1,
10420
+ 1,
10421
+ 1,
10422
+ 1,
10423
+ 1,
10424
+ 1,
10425
+ 1,
10426
+ 0,
10427
+ 1,
10428
+ 0,
10429
+ 1,
10430
+ 0
10431
+ // 112 - 127
10432
+ ];
10433
+ function isValidStatusCode(code) {
10434
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
10435
+ }
10436
+ function _isValidUTF8(buf) {
10437
+ const len = buf.length;
10438
+ let i = 0;
10439
+ while (i < len) {
10440
+ if ((buf[i] & 128) === 0) {
10441
+ i++;
10442
+ } else if ((buf[i] & 224) === 192) {
10443
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
10444
+ return false;
10445
+ }
10446
+ i += 2;
10447
+ } else if ((buf[i] & 240) === 224) {
10448
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
10449
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
10450
+ return false;
10451
+ }
10452
+ i += 3;
10453
+ } else if ((buf[i] & 248) === 240) {
10454
+ 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
10455
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
10456
+ return false;
10457
+ }
10458
+ i += 4;
10459
+ } else {
10460
+ return false;
10461
+ }
10462
+ }
10463
+ return true;
9769
10464
  }
9770
- async function countInputTokens(parameters) {
9771
- const openai = new OpenAI(this.clientParams);
9772
- const response = await openai.responses.inputTokens.count(parameters.payload);
9773
- return response;
10465
+ function isBlob(value) {
10466
+ 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");
10467
+ }
10468
+ module2.exports = {
10469
+ isBlob,
10470
+ isValidStatusCode,
10471
+ isValidUTF8: _isValidUTF8,
10472
+ tokenChars
10473
+ };
10474
+ if (isUtf8) {
10475
+ module2.exports.isValidUTF8 = function(buf) {
10476
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
10477
+ };
10478
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
10479
+ try {
10480
+ const isValidUTF8 = require("utf-8-validate");
10481
+ module2.exports.isValidUTF8 = function(buf) {
10482
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
10483
+ };
10484
+ } catch (e) {
10485
+ }
10486
+ }
10487
+ }
10488
+ });
10489
+
10490
+ // node_modules/ws/lib/receiver.js
10491
+ var require_receiver = __commonJS({
10492
+ "node_modules/ws/lib/receiver.js"(exports2, module2) {
10493
+ "use strict";
10494
+ var { Writable } = require("stream");
10495
+ var PerMessageDeflate = require_permessage_deflate();
10496
+ var {
10497
+ BINARY_TYPES,
10498
+ EMPTY_BUFFER,
10499
+ kStatusCode,
10500
+ kWebSocket
10501
+ } = require_constants();
10502
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
10503
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
10504
+ var FastBuffer = Buffer[Symbol.species];
10505
+ var GET_INFO = 0;
10506
+ var GET_PAYLOAD_LENGTH_16 = 1;
10507
+ var GET_PAYLOAD_LENGTH_64 = 2;
10508
+ var GET_MASK = 3;
10509
+ var GET_DATA = 4;
10510
+ var INFLATING = 5;
10511
+ var DEFER_EVENT = 6;
10512
+ var Receiver = class extends Writable {
10513
+ /**
10514
+ * Creates a Receiver instance.
10515
+ *
10516
+ * @param {Object} [options] Options object
10517
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
10518
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
10519
+ * multiple times in the same tick
10520
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
10521
+ * @param {Object} [options.extensions] An object containing the negotiated
10522
+ * extensions
10523
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
10524
+ * client or server mode
10525
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
10526
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
10527
+ * not to skip UTF-8 validation for text and close messages
10528
+ */
10529
+ constructor(options = {}) {
10530
+ super();
10531
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
10532
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
10533
+ this._extensions = options.extensions || {};
10534
+ this._isServer = !!options.isServer;
10535
+ this._maxPayload = options.maxPayload | 0;
10536
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
10537
+ this[kWebSocket] = void 0;
10538
+ this._bufferedBytes = 0;
10539
+ this._buffers = [];
10540
+ this._compressed = false;
10541
+ this._payloadLength = 0;
10542
+ this._mask = void 0;
10543
+ this._fragmented = 0;
10544
+ this._masked = false;
10545
+ this._fin = false;
10546
+ this._opcode = 0;
10547
+ this._totalPayloadLength = 0;
10548
+ this._messageLength = 0;
10549
+ this._fragments = [];
10550
+ this._errored = false;
10551
+ this._loop = false;
10552
+ this._state = GET_INFO;
10553
+ }
10554
+ /**
10555
+ * Implements `Writable.prototype._write()`.
10556
+ *
10557
+ * @param {Buffer} chunk The chunk of data to write
10558
+ * @param {String} encoding The character encoding of `chunk`
10559
+ * @param {Function} cb Callback
10560
+ * @private
10561
+ */
10562
+ _write(chunk, encoding, cb) {
10563
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
10564
+ this._bufferedBytes += chunk.length;
10565
+ this._buffers.push(chunk);
10566
+ this.startLoop(cb);
10567
+ }
10568
+ /**
10569
+ * Consumes `n` bytes from the buffered data.
10570
+ *
10571
+ * @param {Number} n The number of bytes to consume
10572
+ * @return {Buffer} The consumed bytes
10573
+ * @private
10574
+ */
10575
+ consume(n) {
10576
+ this._bufferedBytes -= n;
10577
+ if (n === this._buffers[0].length) return this._buffers.shift();
10578
+ if (n < this._buffers[0].length) {
10579
+ const buf = this._buffers[0];
10580
+ this._buffers[0] = new FastBuffer(
10581
+ buf.buffer,
10582
+ buf.byteOffset + n,
10583
+ buf.length - n
10584
+ );
10585
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
10586
+ }
10587
+ const dst = Buffer.allocUnsafe(n);
10588
+ do {
10589
+ const buf = this._buffers[0];
10590
+ const offset = dst.length - n;
10591
+ if (n >= buf.length) {
10592
+ dst.set(this._buffers.shift(), offset);
10593
+ } else {
10594
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
10595
+ this._buffers[0] = new FastBuffer(
10596
+ buf.buffer,
10597
+ buf.byteOffset + n,
10598
+ buf.length - n
10599
+ );
10600
+ }
10601
+ n -= buf.length;
10602
+ } while (n > 0);
10603
+ return dst;
10604
+ }
10605
+ /**
10606
+ * Starts the parsing loop.
10607
+ *
10608
+ * @param {Function} cb Callback
10609
+ * @private
10610
+ */
10611
+ startLoop(cb) {
10612
+ this._loop = true;
10613
+ do {
10614
+ switch (this._state) {
10615
+ case GET_INFO:
10616
+ this.getInfo(cb);
10617
+ break;
10618
+ case GET_PAYLOAD_LENGTH_16:
10619
+ this.getPayloadLength16(cb);
10620
+ break;
10621
+ case GET_PAYLOAD_LENGTH_64:
10622
+ this.getPayloadLength64(cb);
10623
+ break;
10624
+ case GET_MASK:
10625
+ this.getMask();
10626
+ break;
10627
+ case GET_DATA:
10628
+ this.getData(cb);
10629
+ break;
10630
+ case INFLATING:
10631
+ case DEFER_EVENT:
10632
+ this._loop = false;
10633
+ return;
10634
+ }
10635
+ } while (this._loop);
10636
+ if (!this._errored) cb();
10637
+ }
10638
+ /**
10639
+ * Reads the first two bytes of a frame.
10640
+ *
10641
+ * @param {Function} cb Callback
10642
+ * @private
10643
+ */
10644
+ getInfo(cb) {
10645
+ if (this._bufferedBytes < 2) {
10646
+ this._loop = false;
10647
+ return;
10648
+ }
10649
+ const buf = this.consume(2);
10650
+ if ((buf[0] & 48) !== 0) {
10651
+ const error = this.createError(
10652
+ RangeError,
10653
+ "RSV2 and RSV3 must be clear",
10654
+ true,
10655
+ 1002,
10656
+ "WS_ERR_UNEXPECTED_RSV_2_3"
10657
+ );
10658
+ cb(error);
10659
+ return;
10660
+ }
10661
+ const compressed = (buf[0] & 64) === 64;
10662
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
10663
+ const error = this.createError(
10664
+ RangeError,
10665
+ "RSV1 must be clear",
10666
+ true,
10667
+ 1002,
10668
+ "WS_ERR_UNEXPECTED_RSV_1"
10669
+ );
10670
+ cb(error);
10671
+ return;
10672
+ }
10673
+ this._fin = (buf[0] & 128) === 128;
10674
+ this._opcode = buf[0] & 15;
10675
+ this._payloadLength = buf[1] & 127;
10676
+ if (this._opcode === 0) {
10677
+ if (compressed) {
10678
+ const error = this.createError(
10679
+ RangeError,
10680
+ "RSV1 must be clear",
10681
+ true,
10682
+ 1002,
10683
+ "WS_ERR_UNEXPECTED_RSV_1"
10684
+ );
10685
+ cb(error);
10686
+ return;
10687
+ }
10688
+ if (!this._fragmented) {
10689
+ const error = this.createError(
10690
+ RangeError,
10691
+ "invalid opcode 0",
10692
+ true,
10693
+ 1002,
10694
+ "WS_ERR_INVALID_OPCODE"
10695
+ );
10696
+ cb(error);
10697
+ return;
10698
+ }
10699
+ this._opcode = this._fragmented;
10700
+ } else if (this._opcode === 1 || this._opcode === 2) {
10701
+ if (this._fragmented) {
10702
+ const error = this.createError(
10703
+ RangeError,
10704
+ `invalid opcode ${this._opcode}`,
10705
+ true,
10706
+ 1002,
10707
+ "WS_ERR_INVALID_OPCODE"
10708
+ );
10709
+ cb(error);
10710
+ return;
10711
+ }
10712
+ this._compressed = compressed;
10713
+ } else if (this._opcode > 7 && this._opcode < 11) {
10714
+ if (!this._fin) {
10715
+ const error = this.createError(
10716
+ RangeError,
10717
+ "FIN must be set",
10718
+ true,
10719
+ 1002,
10720
+ "WS_ERR_EXPECTED_FIN"
10721
+ );
10722
+ cb(error);
10723
+ return;
10724
+ }
10725
+ if (compressed) {
10726
+ const error = this.createError(
10727
+ RangeError,
10728
+ "RSV1 must be clear",
10729
+ true,
10730
+ 1002,
10731
+ "WS_ERR_UNEXPECTED_RSV_1"
10732
+ );
10733
+ cb(error);
10734
+ return;
10735
+ }
10736
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
10737
+ const error = this.createError(
10738
+ RangeError,
10739
+ `invalid payload length ${this._payloadLength}`,
10740
+ true,
10741
+ 1002,
10742
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
10743
+ );
10744
+ cb(error);
10745
+ return;
10746
+ }
10747
+ } else {
10748
+ const error = this.createError(
10749
+ RangeError,
10750
+ `invalid opcode ${this._opcode}`,
10751
+ true,
10752
+ 1002,
10753
+ "WS_ERR_INVALID_OPCODE"
10754
+ );
10755
+ cb(error);
10756
+ return;
10757
+ }
10758
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
10759
+ this._masked = (buf[1] & 128) === 128;
10760
+ if (this._isServer) {
10761
+ if (!this._masked) {
10762
+ const error = this.createError(
10763
+ RangeError,
10764
+ "MASK must be set",
10765
+ true,
10766
+ 1002,
10767
+ "WS_ERR_EXPECTED_MASK"
10768
+ );
10769
+ cb(error);
10770
+ return;
10771
+ }
10772
+ } else if (this._masked) {
10773
+ const error = this.createError(
10774
+ RangeError,
10775
+ "MASK must be clear",
10776
+ true,
10777
+ 1002,
10778
+ "WS_ERR_UNEXPECTED_MASK"
10779
+ );
10780
+ cb(error);
10781
+ return;
10782
+ }
10783
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
10784
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
10785
+ else this.haveLength(cb);
10786
+ }
10787
+ /**
10788
+ * Gets extended payload length (7+16).
10789
+ *
10790
+ * @param {Function} cb Callback
10791
+ * @private
10792
+ */
10793
+ getPayloadLength16(cb) {
10794
+ if (this._bufferedBytes < 2) {
10795
+ this._loop = false;
10796
+ return;
10797
+ }
10798
+ this._payloadLength = this.consume(2).readUInt16BE(0);
10799
+ this.haveLength(cb);
10800
+ }
10801
+ /**
10802
+ * Gets extended payload length (7+64).
10803
+ *
10804
+ * @param {Function} cb Callback
10805
+ * @private
10806
+ */
10807
+ getPayloadLength64(cb) {
10808
+ if (this._bufferedBytes < 8) {
10809
+ this._loop = false;
10810
+ return;
10811
+ }
10812
+ const buf = this.consume(8);
10813
+ const num = buf.readUInt32BE(0);
10814
+ if (num > Math.pow(2, 53 - 32) - 1) {
10815
+ const error = this.createError(
10816
+ RangeError,
10817
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
10818
+ false,
10819
+ 1009,
10820
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
10821
+ );
10822
+ cb(error);
10823
+ return;
10824
+ }
10825
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
10826
+ this.haveLength(cb);
10827
+ }
10828
+ /**
10829
+ * Payload length has been read.
10830
+ *
10831
+ * @param {Function} cb Callback
10832
+ * @private
10833
+ */
10834
+ haveLength(cb) {
10835
+ if (this._payloadLength && this._opcode < 8) {
10836
+ this._totalPayloadLength += this._payloadLength;
10837
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
10838
+ const error = this.createError(
10839
+ RangeError,
10840
+ "Max payload size exceeded",
10841
+ false,
10842
+ 1009,
10843
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
10844
+ );
10845
+ cb(error);
10846
+ return;
10847
+ }
10848
+ }
10849
+ if (this._masked) this._state = GET_MASK;
10850
+ else this._state = GET_DATA;
10851
+ }
10852
+ /**
10853
+ * Reads mask bytes.
10854
+ *
10855
+ * @private
10856
+ */
10857
+ getMask() {
10858
+ if (this._bufferedBytes < 4) {
10859
+ this._loop = false;
10860
+ return;
10861
+ }
10862
+ this._mask = this.consume(4);
10863
+ this._state = GET_DATA;
10864
+ }
10865
+ /**
10866
+ * Reads data bytes.
10867
+ *
10868
+ * @param {Function} cb Callback
10869
+ * @private
10870
+ */
10871
+ getData(cb) {
10872
+ let data = EMPTY_BUFFER;
10873
+ if (this._payloadLength) {
10874
+ if (this._bufferedBytes < this._payloadLength) {
10875
+ this._loop = false;
10876
+ return;
10877
+ }
10878
+ data = this.consume(this._payloadLength);
10879
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
10880
+ unmask(data, this._mask);
10881
+ }
10882
+ }
10883
+ if (this._opcode > 7) {
10884
+ this.controlMessage(data, cb);
10885
+ return;
10886
+ }
10887
+ if (this._compressed) {
10888
+ this._state = INFLATING;
10889
+ this.decompress(data, cb);
10890
+ return;
10891
+ }
10892
+ if (data.length) {
10893
+ this._messageLength = this._totalPayloadLength;
10894
+ this._fragments.push(data);
10895
+ }
10896
+ this.dataMessage(cb);
10897
+ }
10898
+ /**
10899
+ * Decompresses data.
10900
+ *
10901
+ * @param {Buffer} data Compressed data
10902
+ * @param {Function} cb Callback
10903
+ * @private
10904
+ */
10905
+ decompress(data, cb) {
10906
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
10907
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
10908
+ if (err) return cb(err);
10909
+ if (buf.length) {
10910
+ this._messageLength += buf.length;
10911
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
10912
+ const error = this.createError(
10913
+ RangeError,
10914
+ "Max payload size exceeded",
10915
+ false,
10916
+ 1009,
10917
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
10918
+ );
10919
+ cb(error);
10920
+ return;
10921
+ }
10922
+ this._fragments.push(buf);
10923
+ }
10924
+ this.dataMessage(cb);
10925
+ if (this._state === GET_INFO) this.startLoop(cb);
10926
+ });
10927
+ }
10928
+ /**
10929
+ * Handles a data message.
10930
+ *
10931
+ * @param {Function} cb Callback
10932
+ * @private
10933
+ */
10934
+ dataMessage(cb) {
10935
+ if (!this._fin) {
10936
+ this._state = GET_INFO;
10937
+ return;
10938
+ }
10939
+ const messageLength = this._messageLength;
10940
+ const fragments = this._fragments;
10941
+ this._totalPayloadLength = 0;
10942
+ this._messageLength = 0;
10943
+ this._fragmented = 0;
10944
+ this._fragments = [];
10945
+ if (this._opcode === 2) {
10946
+ let data;
10947
+ if (this._binaryType === "nodebuffer") {
10948
+ data = concat(fragments, messageLength);
10949
+ } else if (this._binaryType === "arraybuffer") {
10950
+ data = toArrayBuffer(concat(fragments, messageLength));
10951
+ } else if (this._binaryType === "blob") {
10952
+ data = new Blob(fragments);
10953
+ } else {
10954
+ data = fragments;
10955
+ }
10956
+ if (this._allowSynchronousEvents) {
10957
+ this.emit("message", data, true);
10958
+ this._state = GET_INFO;
10959
+ } else {
10960
+ this._state = DEFER_EVENT;
10961
+ setImmediate(() => {
10962
+ this.emit("message", data, true);
10963
+ this._state = GET_INFO;
10964
+ this.startLoop(cb);
10965
+ });
10966
+ }
10967
+ } else {
10968
+ const buf = concat(fragments, messageLength);
10969
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
10970
+ const error = this.createError(
10971
+ Error,
10972
+ "invalid UTF-8 sequence",
10973
+ true,
10974
+ 1007,
10975
+ "WS_ERR_INVALID_UTF8"
10976
+ );
10977
+ cb(error);
10978
+ return;
10979
+ }
10980
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
10981
+ this.emit("message", buf, false);
10982
+ this._state = GET_INFO;
10983
+ } else {
10984
+ this._state = DEFER_EVENT;
10985
+ setImmediate(() => {
10986
+ this.emit("message", buf, false);
10987
+ this._state = GET_INFO;
10988
+ this.startLoop(cb);
10989
+ });
10990
+ }
10991
+ }
10992
+ }
10993
+ /**
10994
+ * Handles a control message.
10995
+ *
10996
+ * @param {Buffer} data Data to handle
10997
+ * @return {(Error|RangeError|undefined)} A possible error
10998
+ * @private
10999
+ */
11000
+ controlMessage(data, cb) {
11001
+ if (this._opcode === 8) {
11002
+ if (data.length === 0) {
11003
+ this._loop = false;
11004
+ this.emit("conclude", 1005, EMPTY_BUFFER);
11005
+ this.end();
11006
+ } else {
11007
+ const code = data.readUInt16BE(0);
11008
+ if (!isValidStatusCode(code)) {
11009
+ const error = this.createError(
11010
+ RangeError,
11011
+ `invalid status code ${code}`,
11012
+ true,
11013
+ 1002,
11014
+ "WS_ERR_INVALID_CLOSE_CODE"
11015
+ );
11016
+ cb(error);
11017
+ return;
11018
+ }
11019
+ const buf = new FastBuffer(
11020
+ data.buffer,
11021
+ data.byteOffset + 2,
11022
+ data.length - 2
11023
+ );
11024
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
11025
+ const error = this.createError(
11026
+ Error,
11027
+ "invalid UTF-8 sequence",
11028
+ true,
11029
+ 1007,
11030
+ "WS_ERR_INVALID_UTF8"
11031
+ );
11032
+ cb(error);
11033
+ return;
11034
+ }
11035
+ this._loop = false;
11036
+ this.emit("conclude", code, buf);
11037
+ this.end();
11038
+ }
11039
+ this._state = GET_INFO;
11040
+ return;
11041
+ }
11042
+ if (this._allowSynchronousEvents) {
11043
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
11044
+ this._state = GET_INFO;
11045
+ } else {
11046
+ this._state = DEFER_EVENT;
11047
+ setImmediate(() => {
11048
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
11049
+ this._state = GET_INFO;
11050
+ this.startLoop(cb);
11051
+ });
11052
+ }
11053
+ }
11054
+ /**
11055
+ * Builds an error object.
11056
+ *
11057
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
11058
+ * @param {String} message The error message
11059
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
11060
+ * `message`
11061
+ * @param {Number} statusCode The status code
11062
+ * @param {String} errorCode The exposed error code
11063
+ * @return {(Error|RangeError)} The error
11064
+ * @private
11065
+ */
11066
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
11067
+ this._loop = false;
11068
+ this._errored = true;
11069
+ const err = new ErrorCtor(
11070
+ prefix ? `Invalid WebSocket frame: ${message}` : message
11071
+ );
11072
+ Error.captureStackTrace(err, this.createError);
11073
+ err.code = errorCode;
11074
+ err[kStatusCode] = statusCode;
11075
+ return err;
11076
+ }
11077
+ };
11078
+ module2.exports = Receiver;
11079
+ }
11080
+ });
11081
+
11082
+ // node_modules/ws/lib/sender.js
11083
+ var require_sender = __commonJS({
11084
+ "node_modules/ws/lib/sender.js"(exports2, module2) {
11085
+ "use strict";
11086
+ var { Duplex } = require("stream");
11087
+ var { randomFillSync } = require("crypto");
11088
+ var PerMessageDeflate = require_permessage_deflate();
11089
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
11090
+ var { isBlob, isValidStatusCode } = require_validation();
11091
+ var { mask: applyMask, toBuffer } = require_buffer_util();
11092
+ var kByteLength = Symbol("kByteLength");
11093
+ var maskBuffer = Buffer.alloc(4);
11094
+ var RANDOM_POOL_SIZE = 8 * 1024;
11095
+ var randomPool;
11096
+ var randomPoolPointer = RANDOM_POOL_SIZE;
11097
+ var DEFAULT = 0;
11098
+ var DEFLATING = 1;
11099
+ var GET_BLOB_DATA = 2;
11100
+ var Sender = class _Sender {
11101
+ /**
11102
+ * Creates a Sender instance.
11103
+ *
11104
+ * @param {Duplex} socket The connection socket
11105
+ * @param {Object} [extensions] An object containing the negotiated extensions
11106
+ * @param {Function} [generateMask] The function used to generate the masking
11107
+ * key
11108
+ */
11109
+ constructor(socket, extensions, generateMask) {
11110
+ this._extensions = extensions || {};
11111
+ if (generateMask) {
11112
+ this._generateMask = generateMask;
11113
+ this._maskBuffer = Buffer.alloc(4);
11114
+ }
11115
+ this._socket = socket;
11116
+ this._firstFragment = true;
11117
+ this._compress = false;
11118
+ this._bufferedBytes = 0;
11119
+ this._queue = [];
11120
+ this._state = DEFAULT;
11121
+ this.onerror = NOOP;
11122
+ this[kWebSocket] = void 0;
11123
+ }
11124
+ /**
11125
+ * Frames a piece of data according to the HyBi WebSocket protocol.
11126
+ *
11127
+ * @param {(Buffer|String)} data The data to frame
11128
+ * @param {Object} options Options object
11129
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
11130
+ * FIN bit
11131
+ * @param {Function} [options.generateMask] The function used to generate the
11132
+ * masking key
11133
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
11134
+ * `data`
11135
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
11136
+ * key
11137
+ * @param {Number} options.opcode The opcode
11138
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
11139
+ * modified
11140
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
11141
+ * RSV1 bit
11142
+ * @return {(Buffer|String)[]} The framed data
11143
+ * @public
11144
+ */
11145
+ static frame(data, options) {
11146
+ let mask;
11147
+ let merge = false;
11148
+ let offset = 2;
11149
+ let skipMasking = false;
11150
+ if (options.mask) {
11151
+ mask = options.maskBuffer || maskBuffer;
11152
+ if (options.generateMask) {
11153
+ options.generateMask(mask);
11154
+ } else {
11155
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
11156
+ if (randomPool === void 0) {
11157
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
11158
+ }
11159
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
11160
+ randomPoolPointer = 0;
11161
+ }
11162
+ mask[0] = randomPool[randomPoolPointer++];
11163
+ mask[1] = randomPool[randomPoolPointer++];
11164
+ mask[2] = randomPool[randomPoolPointer++];
11165
+ mask[3] = randomPool[randomPoolPointer++];
11166
+ }
11167
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
11168
+ offset = 6;
11169
+ }
11170
+ let dataLength;
11171
+ if (typeof data === "string") {
11172
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
11173
+ dataLength = options[kByteLength];
11174
+ } else {
11175
+ data = Buffer.from(data);
11176
+ dataLength = data.length;
11177
+ }
11178
+ } else {
11179
+ dataLength = data.length;
11180
+ merge = options.mask && options.readOnly && !skipMasking;
11181
+ }
11182
+ let payloadLength = dataLength;
11183
+ if (dataLength >= 65536) {
11184
+ offset += 8;
11185
+ payloadLength = 127;
11186
+ } else if (dataLength > 125) {
11187
+ offset += 2;
11188
+ payloadLength = 126;
11189
+ }
11190
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
11191
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
11192
+ if (options.rsv1) target[0] |= 64;
11193
+ target[1] = payloadLength;
11194
+ if (payloadLength === 126) {
11195
+ target.writeUInt16BE(dataLength, 2);
11196
+ } else if (payloadLength === 127) {
11197
+ target[2] = target[3] = 0;
11198
+ target.writeUIntBE(dataLength, 4, 6);
11199
+ }
11200
+ if (!options.mask) return [target, data];
11201
+ target[1] |= 128;
11202
+ target[offset - 4] = mask[0];
11203
+ target[offset - 3] = mask[1];
11204
+ target[offset - 2] = mask[2];
11205
+ target[offset - 1] = mask[3];
11206
+ if (skipMasking) return [target, data];
11207
+ if (merge) {
11208
+ applyMask(data, mask, target, offset, dataLength);
11209
+ return [target];
11210
+ }
11211
+ applyMask(data, mask, data, 0, dataLength);
11212
+ return [target, data];
11213
+ }
11214
+ /**
11215
+ * Sends a close message to the other peer.
11216
+ *
11217
+ * @param {Number} [code] The status code component of the body
11218
+ * @param {(String|Buffer)} [data] The message component of the body
11219
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
11220
+ * @param {Function} [cb] Callback
11221
+ * @public
11222
+ */
11223
+ close(code, data, mask, cb) {
11224
+ let buf;
11225
+ if (code === void 0) {
11226
+ buf = EMPTY_BUFFER;
11227
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
11228
+ throw new TypeError("First argument must be a valid error code number");
11229
+ } else if (data === void 0 || !data.length) {
11230
+ buf = Buffer.allocUnsafe(2);
11231
+ buf.writeUInt16BE(code, 0);
11232
+ } else {
11233
+ const length = Buffer.byteLength(data);
11234
+ if (length > 123) {
11235
+ throw new RangeError("The message must not be greater than 123 bytes");
11236
+ }
11237
+ buf = Buffer.allocUnsafe(2 + length);
11238
+ buf.writeUInt16BE(code, 0);
11239
+ if (typeof data === "string") {
11240
+ buf.write(data, 2);
11241
+ } else {
11242
+ buf.set(data, 2);
11243
+ }
11244
+ }
11245
+ const options = {
11246
+ [kByteLength]: buf.length,
11247
+ fin: true,
11248
+ generateMask: this._generateMask,
11249
+ mask,
11250
+ maskBuffer: this._maskBuffer,
11251
+ opcode: 8,
11252
+ readOnly: false,
11253
+ rsv1: false
11254
+ };
11255
+ if (this._state !== DEFAULT) {
11256
+ this.enqueue([this.dispatch, buf, false, options, cb]);
11257
+ } else {
11258
+ this.sendFrame(_Sender.frame(buf, options), cb);
11259
+ }
11260
+ }
11261
+ /**
11262
+ * Sends a ping message to the other peer.
11263
+ *
11264
+ * @param {*} data The message to send
11265
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
11266
+ * @param {Function} [cb] Callback
11267
+ * @public
11268
+ */
11269
+ ping(data, mask, cb) {
11270
+ let byteLength;
11271
+ let readOnly;
11272
+ if (typeof data === "string") {
11273
+ byteLength = Buffer.byteLength(data);
11274
+ readOnly = false;
11275
+ } else if (isBlob(data)) {
11276
+ byteLength = data.size;
11277
+ readOnly = false;
11278
+ } else {
11279
+ data = toBuffer(data);
11280
+ byteLength = data.length;
11281
+ readOnly = toBuffer.readOnly;
11282
+ }
11283
+ if (byteLength > 125) {
11284
+ throw new RangeError("The data size must not be greater than 125 bytes");
11285
+ }
11286
+ const options = {
11287
+ [kByteLength]: byteLength,
11288
+ fin: true,
11289
+ generateMask: this._generateMask,
11290
+ mask,
11291
+ maskBuffer: this._maskBuffer,
11292
+ opcode: 9,
11293
+ readOnly,
11294
+ rsv1: false
11295
+ };
11296
+ if (isBlob(data)) {
11297
+ if (this._state !== DEFAULT) {
11298
+ this.enqueue([this.getBlobData, data, false, options, cb]);
11299
+ } else {
11300
+ this.getBlobData(data, false, options, cb);
11301
+ }
11302
+ } else if (this._state !== DEFAULT) {
11303
+ this.enqueue([this.dispatch, data, false, options, cb]);
11304
+ } else {
11305
+ this.sendFrame(_Sender.frame(data, options), cb);
11306
+ }
11307
+ }
11308
+ /**
11309
+ * Sends a pong message to the other peer.
11310
+ *
11311
+ * @param {*} data The message to send
11312
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
11313
+ * @param {Function} [cb] Callback
11314
+ * @public
11315
+ */
11316
+ pong(data, mask, cb) {
11317
+ let byteLength;
11318
+ let readOnly;
11319
+ if (typeof data === "string") {
11320
+ byteLength = Buffer.byteLength(data);
11321
+ readOnly = false;
11322
+ } else if (isBlob(data)) {
11323
+ byteLength = data.size;
11324
+ readOnly = false;
11325
+ } else {
11326
+ data = toBuffer(data);
11327
+ byteLength = data.length;
11328
+ readOnly = toBuffer.readOnly;
11329
+ }
11330
+ if (byteLength > 125) {
11331
+ throw new RangeError("The data size must not be greater than 125 bytes");
11332
+ }
11333
+ const options = {
11334
+ [kByteLength]: byteLength,
11335
+ fin: true,
11336
+ generateMask: this._generateMask,
11337
+ mask,
11338
+ maskBuffer: this._maskBuffer,
11339
+ opcode: 10,
11340
+ readOnly,
11341
+ rsv1: false
11342
+ };
11343
+ if (isBlob(data)) {
11344
+ if (this._state !== DEFAULT) {
11345
+ this.enqueue([this.getBlobData, data, false, options, cb]);
11346
+ } else {
11347
+ this.getBlobData(data, false, options, cb);
11348
+ }
11349
+ } else if (this._state !== DEFAULT) {
11350
+ this.enqueue([this.dispatch, data, false, options, cb]);
11351
+ } else {
11352
+ this.sendFrame(_Sender.frame(data, options), cb);
11353
+ }
11354
+ }
11355
+ /**
11356
+ * Sends a data message to the other peer.
11357
+ *
11358
+ * @param {*} data The message to send
11359
+ * @param {Object} options Options object
11360
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
11361
+ * or text
11362
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
11363
+ * compress `data`
11364
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
11365
+ * last one
11366
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
11367
+ * `data`
11368
+ * @param {Function} [cb] Callback
11369
+ * @public
11370
+ */
11371
+ send(data, options, cb) {
11372
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
11373
+ let opcode = options.binary ? 2 : 1;
11374
+ let rsv1 = options.compress;
11375
+ let byteLength;
11376
+ let readOnly;
11377
+ if (typeof data === "string") {
11378
+ byteLength = Buffer.byteLength(data);
11379
+ readOnly = false;
11380
+ } else if (isBlob(data)) {
11381
+ byteLength = data.size;
11382
+ readOnly = false;
11383
+ } else {
11384
+ data = toBuffer(data);
11385
+ byteLength = data.length;
11386
+ readOnly = toBuffer.readOnly;
11387
+ }
11388
+ if (this._firstFragment) {
11389
+ this._firstFragment = false;
11390
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
11391
+ rsv1 = byteLength >= perMessageDeflate._threshold;
11392
+ }
11393
+ this._compress = rsv1;
11394
+ } else {
11395
+ rsv1 = false;
11396
+ opcode = 0;
11397
+ }
11398
+ if (options.fin) this._firstFragment = true;
11399
+ const opts = {
11400
+ [kByteLength]: byteLength,
11401
+ fin: options.fin,
11402
+ generateMask: this._generateMask,
11403
+ mask: options.mask,
11404
+ maskBuffer: this._maskBuffer,
11405
+ opcode,
11406
+ readOnly,
11407
+ rsv1
11408
+ };
11409
+ if (isBlob(data)) {
11410
+ if (this._state !== DEFAULT) {
11411
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
11412
+ } else {
11413
+ this.getBlobData(data, this._compress, opts, cb);
11414
+ }
11415
+ } else if (this._state !== DEFAULT) {
11416
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
11417
+ } else {
11418
+ this.dispatch(data, this._compress, opts, cb);
11419
+ }
11420
+ }
11421
+ /**
11422
+ * Gets the contents of a blob as binary data.
11423
+ *
11424
+ * @param {Blob} blob The blob
11425
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
11426
+ * the data
11427
+ * @param {Object} options Options object
11428
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
11429
+ * FIN bit
11430
+ * @param {Function} [options.generateMask] The function used to generate the
11431
+ * masking key
11432
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
11433
+ * `data`
11434
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
11435
+ * key
11436
+ * @param {Number} options.opcode The opcode
11437
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
11438
+ * modified
11439
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
11440
+ * RSV1 bit
11441
+ * @param {Function} [cb] Callback
11442
+ * @private
11443
+ */
11444
+ getBlobData(blob, compress, options, cb) {
11445
+ this._bufferedBytes += options[kByteLength];
11446
+ this._state = GET_BLOB_DATA;
11447
+ blob.arrayBuffer().then((arrayBuffer) => {
11448
+ if (this._socket.destroyed) {
11449
+ const err = new Error(
11450
+ "The socket was closed while the blob was being read"
11451
+ );
11452
+ process.nextTick(callCallbacks, this, err, cb);
11453
+ return;
11454
+ }
11455
+ this._bufferedBytes -= options[kByteLength];
11456
+ const data = toBuffer(arrayBuffer);
11457
+ if (!compress) {
11458
+ this._state = DEFAULT;
11459
+ this.sendFrame(_Sender.frame(data, options), cb);
11460
+ this.dequeue();
11461
+ } else {
11462
+ this.dispatch(data, compress, options, cb);
11463
+ }
11464
+ }).catch((err) => {
11465
+ process.nextTick(onError, this, err, cb);
11466
+ });
11467
+ }
11468
+ /**
11469
+ * Dispatches a message.
11470
+ *
11471
+ * @param {(Buffer|String)} data The message to send
11472
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
11473
+ * `data`
11474
+ * @param {Object} options Options object
11475
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
11476
+ * FIN bit
11477
+ * @param {Function} [options.generateMask] The function used to generate the
11478
+ * masking key
11479
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
11480
+ * `data`
11481
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
11482
+ * key
11483
+ * @param {Number} options.opcode The opcode
11484
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
11485
+ * modified
11486
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
11487
+ * RSV1 bit
11488
+ * @param {Function} [cb] Callback
11489
+ * @private
11490
+ */
11491
+ dispatch(data, compress, options, cb) {
11492
+ if (!compress) {
11493
+ this.sendFrame(_Sender.frame(data, options), cb);
11494
+ return;
11495
+ }
11496
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
11497
+ this._bufferedBytes += options[kByteLength];
11498
+ this._state = DEFLATING;
11499
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
11500
+ if (this._socket.destroyed) {
11501
+ const err = new Error(
11502
+ "The socket was closed while data was being compressed"
11503
+ );
11504
+ callCallbacks(this, err, cb);
11505
+ return;
11506
+ }
11507
+ this._bufferedBytes -= options[kByteLength];
11508
+ this._state = DEFAULT;
11509
+ options.readOnly = false;
11510
+ this.sendFrame(_Sender.frame(buf, options), cb);
11511
+ this.dequeue();
11512
+ });
11513
+ }
11514
+ /**
11515
+ * Executes queued send operations.
11516
+ *
11517
+ * @private
11518
+ */
11519
+ dequeue() {
11520
+ while (this._state === DEFAULT && this._queue.length) {
11521
+ const params = this._queue.shift();
11522
+ this._bufferedBytes -= params[3][kByteLength];
11523
+ Reflect.apply(params[0], this, params.slice(1));
11524
+ }
11525
+ }
11526
+ /**
11527
+ * Enqueues a send operation.
11528
+ *
11529
+ * @param {Array} params Send operation parameters.
11530
+ * @private
11531
+ */
11532
+ enqueue(params) {
11533
+ this._bufferedBytes += params[3][kByteLength];
11534
+ this._queue.push(params);
11535
+ }
11536
+ /**
11537
+ * Sends a frame.
11538
+ *
11539
+ * @param {(Buffer | String)[]} list The frame to send
11540
+ * @param {Function} [cb] Callback
11541
+ * @private
11542
+ */
11543
+ sendFrame(list, cb) {
11544
+ if (list.length === 2) {
11545
+ this._socket.cork();
11546
+ this._socket.write(list[0]);
11547
+ this._socket.write(list[1], cb);
11548
+ this._socket.uncork();
11549
+ } else {
11550
+ this._socket.write(list[0], cb);
11551
+ }
11552
+ }
11553
+ };
11554
+ module2.exports = Sender;
11555
+ function callCallbacks(sender, err, cb) {
11556
+ if (typeof cb === "function") cb(err);
11557
+ for (let i = 0; i < sender._queue.length; i++) {
11558
+ const params = sender._queue[i];
11559
+ const callback = params[params.length - 1];
11560
+ if (typeof callback === "function") callback(err);
11561
+ }
11562
+ }
11563
+ function onError(sender, err, cb) {
11564
+ callCallbacks(sender, err, cb);
11565
+ sender.onerror(err);
11566
+ }
11567
+ }
11568
+ });
11569
+
11570
+ // node_modules/ws/lib/event-target.js
11571
+ var require_event_target = __commonJS({
11572
+ "node_modules/ws/lib/event-target.js"(exports2, module2) {
11573
+ "use strict";
11574
+ var { kForOnEventAttribute, kListener } = require_constants();
11575
+ var kCode = Symbol("kCode");
11576
+ var kData = Symbol("kData");
11577
+ var kError = Symbol("kError");
11578
+ var kMessage = Symbol("kMessage");
11579
+ var kReason = Symbol("kReason");
11580
+ var kTarget = Symbol("kTarget");
11581
+ var kType = Symbol("kType");
11582
+ var kWasClean = Symbol("kWasClean");
11583
+ var Event = class {
11584
+ /**
11585
+ * Create a new `Event`.
11586
+ *
11587
+ * @param {String} type The name of the event
11588
+ * @throws {TypeError} If the `type` argument is not specified
11589
+ */
11590
+ constructor(type) {
11591
+ this[kTarget] = null;
11592
+ this[kType] = type;
11593
+ }
11594
+ /**
11595
+ * @type {*}
11596
+ */
11597
+ get target() {
11598
+ return this[kTarget];
11599
+ }
11600
+ /**
11601
+ * @type {String}
11602
+ */
11603
+ get type() {
11604
+ return this[kType];
11605
+ }
11606
+ };
11607
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
11608
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
11609
+ var CloseEvent = class extends Event {
11610
+ /**
11611
+ * Create a new `CloseEvent`.
11612
+ *
11613
+ * @param {String} type The name of the event
11614
+ * @param {Object} [options] A dictionary object that allows for setting
11615
+ * attributes via object members of the same name
11616
+ * @param {Number} [options.code=0] The status code explaining why the
11617
+ * connection was closed
11618
+ * @param {String} [options.reason=''] A human-readable string explaining why
11619
+ * the connection was closed
11620
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
11621
+ * connection was cleanly closed
11622
+ */
11623
+ constructor(type, options = {}) {
11624
+ super(type);
11625
+ this[kCode] = options.code === void 0 ? 0 : options.code;
11626
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
11627
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
11628
+ }
11629
+ /**
11630
+ * @type {Number}
11631
+ */
11632
+ get code() {
11633
+ return this[kCode];
11634
+ }
11635
+ /**
11636
+ * @type {String}
11637
+ */
11638
+ get reason() {
11639
+ return this[kReason];
11640
+ }
11641
+ /**
11642
+ * @type {Boolean}
11643
+ */
11644
+ get wasClean() {
11645
+ return this[kWasClean];
11646
+ }
11647
+ };
11648
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
11649
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
11650
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
11651
+ var ErrorEvent = class extends Event {
11652
+ /**
11653
+ * Create a new `ErrorEvent`.
11654
+ *
11655
+ * @param {String} type The name of the event
11656
+ * @param {Object} [options] A dictionary object that allows for setting
11657
+ * attributes via object members of the same name
11658
+ * @param {*} [options.error=null] The error that generated this event
11659
+ * @param {String} [options.message=''] The error message
11660
+ */
11661
+ constructor(type, options = {}) {
11662
+ super(type);
11663
+ this[kError] = options.error === void 0 ? null : options.error;
11664
+ this[kMessage] = options.message === void 0 ? "" : options.message;
11665
+ }
11666
+ /**
11667
+ * @type {*}
11668
+ */
11669
+ get error() {
11670
+ return this[kError];
11671
+ }
11672
+ /**
11673
+ * @type {String}
11674
+ */
11675
+ get message() {
11676
+ return this[kMessage];
11677
+ }
11678
+ };
11679
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
11680
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
11681
+ var MessageEvent = class extends Event {
11682
+ /**
11683
+ * Create a new `MessageEvent`.
11684
+ *
11685
+ * @param {String} type The name of the event
11686
+ * @param {Object} [options] A dictionary object that allows for setting
11687
+ * attributes via object members of the same name
11688
+ * @param {*} [options.data=null] The message content
11689
+ */
11690
+ constructor(type, options = {}) {
11691
+ super(type);
11692
+ this[kData] = options.data === void 0 ? null : options.data;
11693
+ }
11694
+ /**
11695
+ * @type {*}
11696
+ */
11697
+ get data() {
11698
+ return this[kData];
11699
+ }
11700
+ };
11701
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
11702
+ var EventTarget = {
11703
+ /**
11704
+ * Register an event listener.
11705
+ *
11706
+ * @param {String} type A string representing the event type to listen for
11707
+ * @param {(Function|Object)} handler The listener to add
11708
+ * @param {Object} [options] An options object specifies characteristics about
11709
+ * the event listener
11710
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
11711
+ * listener should be invoked at most once after being added. If `true`,
11712
+ * the listener would be automatically removed when invoked.
11713
+ * @public
11714
+ */
11715
+ addEventListener(type, handler, options = {}) {
11716
+ for (const listener of this.listeners(type)) {
11717
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
11718
+ return;
11719
+ }
11720
+ }
11721
+ let wrapper;
11722
+ if (type === "message") {
11723
+ wrapper = function onMessage(data, isBinary) {
11724
+ const event = new MessageEvent("message", {
11725
+ data: isBinary ? data : data.toString()
11726
+ });
11727
+ event[kTarget] = this;
11728
+ callListener(handler, this, event);
11729
+ };
11730
+ } else if (type === "close") {
11731
+ wrapper = function onClose(code, message) {
11732
+ const event = new CloseEvent("close", {
11733
+ code,
11734
+ reason: message.toString(),
11735
+ wasClean: this._closeFrameReceived && this._closeFrameSent
11736
+ });
11737
+ event[kTarget] = this;
11738
+ callListener(handler, this, event);
11739
+ };
11740
+ } else if (type === "error") {
11741
+ wrapper = function onError(error) {
11742
+ const event = new ErrorEvent("error", {
11743
+ error,
11744
+ message: error.message
11745
+ });
11746
+ event[kTarget] = this;
11747
+ callListener(handler, this, event);
11748
+ };
11749
+ } else if (type === "open") {
11750
+ wrapper = function onOpen() {
11751
+ const event = new Event("open");
11752
+ event[kTarget] = this;
11753
+ callListener(handler, this, event);
11754
+ };
11755
+ } else {
11756
+ return;
11757
+ }
11758
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
11759
+ wrapper[kListener] = handler;
11760
+ if (options.once) {
11761
+ this.once(type, wrapper);
11762
+ } else {
11763
+ this.on(type, wrapper);
11764
+ }
11765
+ },
11766
+ /**
11767
+ * Remove an event listener.
11768
+ *
11769
+ * @param {String} type A string representing the event type to remove
11770
+ * @param {(Function|Object)} handler The listener to remove
11771
+ * @public
11772
+ */
11773
+ removeEventListener(type, handler) {
11774
+ for (const listener of this.listeners(type)) {
11775
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
11776
+ this.removeListener(type, listener);
11777
+ break;
11778
+ }
11779
+ }
11780
+ }
11781
+ };
11782
+ module2.exports = {
11783
+ CloseEvent,
11784
+ ErrorEvent,
11785
+ Event,
11786
+ EventTarget,
11787
+ MessageEvent
11788
+ };
11789
+ function callListener(listener, thisArg, event) {
11790
+ if (typeof listener === "object" && listener.handleEvent) {
11791
+ listener.handleEvent.call(listener, event);
11792
+ } else {
11793
+ listener.call(thisArg, event);
11794
+ }
11795
+ }
11796
+ }
11797
+ });
11798
+
11799
+ // node_modules/ws/lib/extension.js
11800
+ var require_extension = __commonJS({
11801
+ "node_modules/ws/lib/extension.js"(exports2, module2) {
11802
+ "use strict";
11803
+ var { tokenChars } = require_validation();
11804
+ function push(dest, name, elem) {
11805
+ if (dest[name] === void 0) dest[name] = [elem];
11806
+ else dest[name].push(elem);
11807
+ }
11808
+ function parse(header) {
11809
+ const offers = /* @__PURE__ */ Object.create(null);
11810
+ let params = /* @__PURE__ */ Object.create(null);
11811
+ let mustUnescape = false;
11812
+ let isEscaping = false;
11813
+ let inQuotes = false;
11814
+ let extensionName;
11815
+ let paramName;
11816
+ let start = -1;
11817
+ let code = -1;
11818
+ let end = -1;
11819
+ let i = 0;
11820
+ for (; i < header.length; i++) {
11821
+ code = header.charCodeAt(i);
11822
+ if (extensionName === void 0) {
11823
+ if (end === -1 && tokenChars[code] === 1) {
11824
+ if (start === -1) start = i;
11825
+ } else if (i !== 0 && (code === 32 || code === 9)) {
11826
+ if (end === -1 && start !== -1) end = i;
11827
+ } else if (code === 59 || code === 44) {
11828
+ if (start === -1) {
11829
+ throw new SyntaxError(`Unexpected character at index ${i}`);
11830
+ }
11831
+ if (end === -1) end = i;
11832
+ const name = header.slice(start, end);
11833
+ if (code === 44) {
11834
+ push(offers, name, params);
11835
+ params = /* @__PURE__ */ Object.create(null);
11836
+ } else {
11837
+ extensionName = name;
11838
+ }
11839
+ start = end = -1;
11840
+ } else {
11841
+ throw new SyntaxError(`Unexpected character at index ${i}`);
11842
+ }
11843
+ } else if (paramName === void 0) {
11844
+ if (end === -1 && tokenChars[code] === 1) {
11845
+ if (start === -1) start = i;
11846
+ } else if (code === 32 || code === 9) {
11847
+ if (end === -1 && start !== -1) end = i;
11848
+ } else if (code === 59 || code === 44) {
11849
+ if (start === -1) {
11850
+ throw new SyntaxError(`Unexpected character at index ${i}`);
11851
+ }
11852
+ if (end === -1) end = i;
11853
+ push(params, header.slice(start, end), true);
11854
+ if (code === 44) {
11855
+ push(offers, extensionName, params);
11856
+ params = /* @__PURE__ */ Object.create(null);
11857
+ extensionName = void 0;
11858
+ }
11859
+ start = end = -1;
11860
+ } else if (code === 61 && start !== -1 && end === -1) {
11861
+ paramName = header.slice(start, i);
11862
+ start = end = -1;
11863
+ } else {
11864
+ throw new SyntaxError(`Unexpected character at index ${i}`);
11865
+ }
11866
+ } else {
11867
+ if (isEscaping) {
11868
+ if (tokenChars[code] !== 1) {
11869
+ throw new SyntaxError(`Unexpected character at index ${i}`);
11870
+ }
11871
+ if (start === -1) start = i;
11872
+ else if (!mustUnescape) mustUnescape = true;
11873
+ isEscaping = false;
11874
+ } else if (inQuotes) {
11875
+ if (tokenChars[code] === 1) {
11876
+ if (start === -1) start = i;
11877
+ } else if (code === 34 && start !== -1) {
11878
+ inQuotes = false;
11879
+ end = i;
11880
+ } else if (code === 92) {
11881
+ isEscaping = true;
11882
+ } else {
11883
+ throw new SyntaxError(`Unexpected character at index ${i}`);
11884
+ }
11885
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
11886
+ inQuotes = true;
11887
+ } else if (end === -1 && tokenChars[code] === 1) {
11888
+ if (start === -1) start = i;
11889
+ } else if (start !== -1 && (code === 32 || code === 9)) {
11890
+ if (end === -1) end = i;
11891
+ } else if (code === 59 || code === 44) {
11892
+ if (start === -1) {
11893
+ throw new SyntaxError(`Unexpected character at index ${i}`);
11894
+ }
11895
+ if (end === -1) end = i;
11896
+ let value = header.slice(start, end);
11897
+ if (mustUnescape) {
11898
+ value = value.replace(/\\/g, "");
11899
+ mustUnescape = false;
11900
+ }
11901
+ push(params, paramName, value);
11902
+ if (code === 44) {
11903
+ push(offers, extensionName, params);
11904
+ params = /* @__PURE__ */ Object.create(null);
11905
+ extensionName = void 0;
11906
+ }
11907
+ paramName = void 0;
11908
+ start = end = -1;
11909
+ } else {
11910
+ throw new SyntaxError(`Unexpected character at index ${i}`);
11911
+ }
11912
+ }
11913
+ }
11914
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
11915
+ throw new SyntaxError("Unexpected end of input");
11916
+ }
11917
+ if (end === -1) end = i;
11918
+ const token = header.slice(start, end);
11919
+ if (extensionName === void 0) {
11920
+ push(offers, token, params);
11921
+ } else {
11922
+ if (paramName === void 0) {
11923
+ push(params, token, true);
11924
+ } else if (mustUnescape) {
11925
+ push(params, paramName, token.replace(/\\/g, ""));
11926
+ } else {
11927
+ push(params, paramName, token);
11928
+ }
11929
+ push(offers, extensionName, params);
11930
+ }
11931
+ return offers;
11932
+ }
11933
+ function format(extensions) {
11934
+ return Object.keys(extensions).map((extension) => {
11935
+ let configurations = extensions[extension];
11936
+ if (!Array.isArray(configurations)) configurations = [configurations];
11937
+ return configurations.map((params) => {
11938
+ return [extension].concat(
11939
+ Object.keys(params).map((k) => {
11940
+ let values = params[k];
11941
+ if (!Array.isArray(values)) values = [values];
11942
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
11943
+ })
11944
+ ).join("; ");
11945
+ }).join(", ");
11946
+ }).join(", ");
11947
+ }
11948
+ module2.exports = { format, parse };
11949
+ }
11950
+ });
11951
+
11952
+ // node_modules/ws/lib/websocket.js
11953
+ var require_websocket = __commonJS({
11954
+ "node_modules/ws/lib/websocket.js"(exports2, module2) {
11955
+ "use strict";
11956
+ var EventEmitter = require("events");
11957
+ var https = require("https");
11958
+ var http = require("http");
11959
+ var net = require("net");
11960
+ var tls = require("tls");
11961
+ var { randomBytes, createHash } = require("crypto");
11962
+ var { Duplex, Readable } = require("stream");
11963
+ var { URL: URL2 } = require("url");
11964
+ var PerMessageDeflate = require_permessage_deflate();
11965
+ var Receiver = require_receiver();
11966
+ var Sender = require_sender();
11967
+ var { isBlob } = require_validation();
11968
+ var {
11969
+ BINARY_TYPES,
11970
+ CLOSE_TIMEOUT,
11971
+ EMPTY_BUFFER,
11972
+ GUID,
11973
+ kForOnEventAttribute,
11974
+ kListener,
11975
+ kStatusCode,
11976
+ kWebSocket,
11977
+ NOOP
11978
+ } = require_constants();
11979
+ var {
11980
+ EventTarget: { addEventListener, removeEventListener }
11981
+ } = require_event_target();
11982
+ var { format, parse } = require_extension();
11983
+ var { toBuffer } = require_buffer_util();
11984
+ var kAborted = Symbol("kAborted");
11985
+ var protocolVersions = [8, 13];
11986
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
11987
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
11988
+ var WebSocket = class _WebSocket extends EventEmitter {
11989
+ /**
11990
+ * Create a new `WebSocket`.
11991
+ *
11992
+ * @param {(String|URL)} address The URL to which to connect
11993
+ * @param {(String|String[])} [protocols] The subprotocols
11994
+ * @param {Object} [options] Connection options
11995
+ */
11996
+ constructor(address, protocols, options) {
11997
+ super();
11998
+ this._binaryType = BINARY_TYPES[0];
11999
+ this._closeCode = 1006;
12000
+ this._closeFrameReceived = false;
12001
+ this._closeFrameSent = false;
12002
+ this._closeMessage = EMPTY_BUFFER;
12003
+ this._closeTimer = null;
12004
+ this._errorEmitted = false;
12005
+ this._extensions = {};
12006
+ this._paused = false;
12007
+ this._protocol = "";
12008
+ this._readyState = _WebSocket.CONNECTING;
12009
+ this._receiver = null;
12010
+ this._sender = null;
12011
+ this._socket = null;
12012
+ if (address !== null) {
12013
+ this._bufferedAmount = 0;
12014
+ this._isServer = false;
12015
+ this._redirects = 0;
12016
+ if (protocols === void 0) {
12017
+ protocols = [];
12018
+ } else if (!Array.isArray(protocols)) {
12019
+ if (typeof protocols === "object" && protocols !== null) {
12020
+ options = protocols;
12021
+ protocols = [];
12022
+ } else {
12023
+ protocols = [protocols];
12024
+ }
12025
+ }
12026
+ initAsClient(this, address, protocols, options);
12027
+ } else {
12028
+ this._autoPong = options.autoPong;
12029
+ this._closeTimeout = options.closeTimeout;
12030
+ this._isServer = true;
12031
+ }
12032
+ }
12033
+ /**
12034
+ * For historical reasons, the custom "nodebuffer" type is used by the default
12035
+ * instead of "blob".
12036
+ *
12037
+ * @type {String}
12038
+ */
12039
+ get binaryType() {
12040
+ return this._binaryType;
12041
+ }
12042
+ set binaryType(type) {
12043
+ if (!BINARY_TYPES.includes(type)) return;
12044
+ this._binaryType = type;
12045
+ if (this._receiver) this._receiver._binaryType = type;
12046
+ }
12047
+ /**
12048
+ * @type {Number}
12049
+ */
12050
+ get bufferedAmount() {
12051
+ if (!this._socket) return this._bufferedAmount;
12052
+ return this._socket._writableState.length + this._sender._bufferedBytes;
12053
+ }
12054
+ /**
12055
+ * @type {String}
12056
+ */
12057
+ get extensions() {
12058
+ return Object.keys(this._extensions).join();
12059
+ }
12060
+ /**
12061
+ * @type {Boolean}
12062
+ */
12063
+ get isPaused() {
12064
+ return this._paused;
12065
+ }
12066
+ /**
12067
+ * @type {Function}
12068
+ */
12069
+ /* istanbul ignore next */
12070
+ get onclose() {
12071
+ return null;
12072
+ }
12073
+ /**
12074
+ * @type {Function}
12075
+ */
12076
+ /* istanbul ignore next */
12077
+ get onerror() {
12078
+ return null;
12079
+ }
12080
+ /**
12081
+ * @type {Function}
12082
+ */
12083
+ /* istanbul ignore next */
12084
+ get onopen() {
12085
+ return null;
12086
+ }
12087
+ /**
12088
+ * @type {Function}
12089
+ */
12090
+ /* istanbul ignore next */
12091
+ get onmessage() {
12092
+ return null;
12093
+ }
12094
+ /**
12095
+ * @type {String}
12096
+ */
12097
+ get protocol() {
12098
+ return this._protocol;
12099
+ }
12100
+ /**
12101
+ * @type {Number}
12102
+ */
12103
+ get readyState() {
12104
+ return this._readyState;
12105
+ }
12106
+ /**
12107
+ * @type {String}
12108
+ */
12109
+ get url() {
12110
+ return this._url;
12111
+ }
12112
+ /**
12113
+ * Set up the socket and the internal resources.
12114
+ *
12115
+ * @param {Duplex} socket The network socket between the server and client
12116
+ * @param {Buffer} head The first packet of the upgraded stream
12117
+ * @param {Object} options Options object
12118
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
12119
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
12120
+ * multiple times in the same tick
12121
+ * @param {Function} [options.generateMask] The function used to generate the
12122
+ * masking key
12123
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
12124
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
12125
+ * not to skip UTF-8 validation for text and close messages
12126
+ * @private
12127
+ */
12128
+ setSocket(socket, head, options) {
12129
+ const receiver = new Receiver({
12130
+ allowSynchronousEvents: options.allowSynchronousEvents,
12131
+ binaryType: this.binaryType,
12132
+ extensions: this._extensions,
12133
+ isServer: this._isServer,
12134
+ maxPayload: options.maxPayload,
12135
+ skipUTF8Validation: options.skipUTF8Validation
12136
+ });
12137
+ const sender = new Sender(socket, this._extensions, options.generateMask);
12138
+ this._receiver = receiver;
12139
+ this._sender = sender;
12140
+ this._socket = socket;
12141
+ receiver[kWebSocket] = this;
12142
+ sender[kWebSocket] = this;
12143
+ socket[kWebSocket] = this;
12144
+ receiver.on("conclude", receiverOnConclude);
12145
+ receiver.on("drain", receiverOnDrain);
12146
+ receiver.on("error", receiverOnError);
12147
+ receiver.on("message", receiverOnMessage);
12148
+ receiver.on("ping", receiverOnPing);
12149
+ receiver.on("pong", receiverOnPong);
12150
+ sender.onerror = senderOnError;
12151
+ if (socket.setTimeout) socket.setTimeout(0);
12152
+ if (socket.setNoDelay) socket.setNoDelay();
12153
+ if (head.length > 0) socket.unshift(head);
12154
+ socket.on("close", socketOnClose);
12155
+ socket.on("data", socketOnData);
12156
+ socket.on("end", socketOnEnd);
12157
+ socket.on("error", socketOnError);
12158
+ this._readyState = _WebSocket.OPEN;
12159
+ this.emit("open");
12160
+ }
12161
+ /**
12162
+ * Emit the `'close'` event.
12163
+ *
12164
+ * @private
12165
+ */
12166
+ emitClose() {
12167
+ if (!this._socket) {
12168
+ this._readyState = _WebSocket.CLOSED;
12169
+ this.emit("close", this._closeCode, this._closeMessage);
12170
+ return;
12171
+ }
12172
+ if (this._extensions[PerMessageDeflate.extensionName]) {
12173
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
12174
+ }
12175
+ this._receiver.removeAllListeners();
12176
+ this._readyState = _WebSocket.CLOSED;
12177
+ this.emit("close", this._closeCode, this._closeMessage);
12178
+ }
12179
+ /**
12180
+ * Start a closing handshake.
12181
+ *
12182
+ * +----------+ +-----------+ +----------+
12183
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
12184
+ * | +----------+ +-----------+ +----------+ |
12185
+ * +----------+ +-----------+ |
12186
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
12187
+ * +----------+ +-----------+ |
12188
+ * | | | +---+ |
12189
+ * +------------------------+-->|fin| - - - -
12190
+ * | +---+ | +---+
12191
+ * - - - - -|fin|<---------------------+
12192
+ * +---+
12193
+ *
12194
+ * @param {Number} [code] Status code explaining why the connection is closing
12195
+ * @param {(String|Buffer)} [data] The reason why the connection is
12196
+ * closing
12197
+ * @public
12198
+ */
12199
+ close(code, data) {
12200
+ if (this.readyState === _WebSocket.CLOSED) return;
12201
+ if (this.readyState === _WebSocket.CONNECTING) {
12202
+ const msg = "WebSocket was closed before the connection was established";
12203
+ abortHandshake(this, this._req, msg);
12204
+ return;
12205
+ }
12206
+ if (this.readyState === _WebSocket.CLOSING) {
12207
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
12208
+ this._socket.end();
12209
+ }
12210
+ return;
12211
+ }
12212
+ this._readyState = _WebSocket.CLOSING;
12213
+ this._sender.close(code, data, !this._isServer, (err) => {
12214
+ if (err) return;
12215
+ this._closeFrameSent = true;
12216
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
12217
+ this._socket.end();
12218
+ }
12219
+ });
12220
+ setCloseTimer(this);
12221
+ }
12222
+ /**
12223
+ * Pause the socket.
12224
+ *
12225
+ * @public
12226
+ */
12227
+ pause() {
12228
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
12229
+ return;
12230
+ }
12231
+ this._paused = true;
12232
+ this._socket.pause();
12233
+ }
12234
+ /**
12235
+ * Send a ping.
12236
+ *
12237
+ * @param {*} [data] The data to send
12238
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
12239
+ * @param {Function} [cb] Callback which is executed when the ping is sent
12240
+ * @public
12241
+ */
12242
+ ping(data, mask, cb) {
12243
+ if (this.readyState === _WebSocket.CONNECTING) {
12244
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
12245
+ }
12246
+ if (typeof data === "function") {
12247
+ cb = data;
12248
+ data = mask = void 0;
12249
+ } else if (typeof mask === "function") {
12250
+ cb = mask;
12251
+ mask = void 0;
12252
+ }
12253
+ if (typeof data === "number") data = data.toString();
12254
+ if (this.readyState !== _WebSocket.OPEN) {
12255
+ sendAfterClose(this, data, cb);
12256
+ return;
12257
+ }
12258
+ if (mask === void 0) mask = !this._isServer;
12259
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
12260
+ }
12261
+ /**
12262
+ * Send a pong.
12263
+ *
12264
+ * @param {*} [data] The data to send
12265
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
12266
+ * @param {Function} [cb] Callback which is executed when the pong is sent
12267
+ * @public
12268
+ */
12269
+ pong(data, mask, cb) {
12270
+ if (this.readyState === _WebSocket.CONNECTING) {
12271
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
12272
+ }
12273
+ if (typeof data === "function") {
12274
+ cb = data;
12275
+ data = mask = void 0;
12276
+ } else if (typeof mask === "function") {
12277
+ cb = mask;
12278
+ mask = void 0;
12279
+ }
12280
+ if (typeof data === "number") data = data.toString();
12281
+ if (this.readyState !== _WebSocket.OPEN) {
12282
+ sendAfterClose(this, data, cb);
12283
+ return;
12284
+ }
12285
+ if (mask === void 0) mask = !this._isServer;
12286
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
12287
+ }
12288
+ /**
12289
+ * Resume the socket.
12290
+ *
12291
+ * @public
12292
+ */
12293
+ resume() {
12294
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
12295
+ return;
12296
+ }
12297
+ this._paused = false;
12298
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
12299
+ }
12300
+ /**
12301
+ * Send a data message.
12302
+ *
12303
+ * @param {*} data The message to send
12304
+ * @param {Object} [options] Options object
12305
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
12306
+ * text
12307
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
12308
+ * `data`
12309
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
12310
+ * last one
12311
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
12312
+ * @param {Function} [cb] Callback which is executed when data is written out
12313
+ * @public
12314
+ */
12315
+ send(data, options, cb) {
12316
+ if (this.readyState === _WebSocket.CONNECTING) {
12317
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
12318
+ }
12319
+ if (typeof options === "function") {
12320
+ cb = options;
12321
+ options = {};
12322
+ }
12323
+ if (typeof data === "number") data = data.toString();
12324
+ if (this.readyState !== _WebSocket.OPEN) {
12325
+ sendAfterClose(this, data, cb);
12326
+ return;
12327
+ }
12328
+ const opts = {
12329
+ binary: typeof data !== "string",
12330
+ mask: !this._isServer,
12331
+ compress: true,
12332
+ fin: true,
12333
+ ...options
12334
+ };
12335
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
12336
+ opts.compress = false;
12337
+ }
12338
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
12339
+ }
12340
+ /**
12341
+ * Forcibly close the connection.
12342
+ *
12343
+ * @public
12344
+ */
12345
+ terminate() {
12346
+ if (this.readyState === _WebSocket.CLOSED) return;
12347
+ if (this.readyState === _WebSocket.CONNECTING) {
12348
+ const msg = "WebSocket was closed before the connection was established";
12349
+ abortHandshake(this, this._req, msg);
12350
+ return;
12351
+ }
12352
+ if (this._socket) {
12353
+ this._readyState = _WebSocket.CLOSING;
12354
+ this._socket.destroy();
12355
+ }
12356
+ }
12357
+ };
12358
+ Object.defineProperty(WebSocket, "CONNECTING", {
12359
+ enumerable: true,
12360
+ value: readyStates.indexOf("CONNECTING")
12361
+ });
12362
+ Object.defineProperty(WebSocket.prototype, "CONNECTING", {
12363
+ enumerable: true,
12364
+ value: readyStates.indexOf("CONNECTING")
12365
+ });
12366
+ Object.defineProperty(WebSocket, "OPEN", {
12367
+ enumerable: true,
12368
+ value: readyStates.indexOf("OPEN")
12369
+ });
12370
+ Object.defineProperty(WebSocket.prototype, "OPEN", {
12371
+ enumerable: true,
12372
+ value: readyStates.indexOf("OPEN")
12373
+ });
12374
+ Object.defineProperty(WebSocket, "CLOSING", {
12375
+ enumerable: true,
12376
+ value: readyStates.indexOf("CLOSING")
12377
+ });
12378
+ Object.defineProperty(WebSocket.prototype, "CLOSING", {
12379
+ enumerable: true,
12380
+ value: readyStates.indexOf("CLOSING")
12381
+ });
12382
+ Object.defineProperty(WebSocket, "CLOSED", {
12383
+ enumerable: true,
12384
+ value: readyStates.indexOf("CLOSED")
12385
+ });
12386
+ Object.defineProperty(WebSocket.prototype, "CLOSED", {
12387
+ enumerable: true,
12388
+ value: readyStates.indexOf("CLOSED")
12389
+ });
12390
+ [
12391
+ "binaryType",
12392
+ "bufferedAmount",
12393
+ "extensions",
12394
+ "isPaused",
12395
+ "protocol",
12396
+ "readyState",
12397
+ "url"
12398
+ ].forEach((property) => {
12399
+ Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
12400
+ });
12401
+ ["open", "error", "close", "message"].forEach((method) => {
12402
+ Object.defineProperty(WebSocket.prototype, `on${method}`, {
12403
+ enumerable: true,
12404
+ get() {
12405
+ for (const listener of this.listeners(method)) {
12406
+ if (listener[kForOnEventAttribute]) return listener[kListener];
12407
+ }
12408
+ return null;
12409
+ },
12410
+ set(handler) {
12411
+ for (const listener of this.listeners(method)) {
12412
+ if (listener[kForOnEventAttribute]) {
12413
+ this.removeListener(method, listener);
12414
+ break;
12415
+ }
12416
+ }
12417
+ if (typeof handler !== "function") return;
12418
+ this.addEventListener(method, handler, {
12419
+ [kForOnEventAttribute]: true
12420
+ });
12421
+ }
12422
+ });
12423
+ });
12424
+ WebSocket.prototype.addEventListener = addEventListener;
12425
+ WebSocket.prototype.removeEventListener = removeEventListener;
12426
+ module2.exports = WebSocket;
12427
+ function initAsClient(websocket, address, protocols, options) {
12428
+ const opts = {
12429
+ allowSynchronousEvents: true,
12430
+ autoPong: true,
12431
+ closeTimeout: CLOSE_TIMEOUT,
12432
+ protocolVersion: protocolVersions[1],
12433
+ maxPayload: 100 * 1024 * 1024,
12434
+ skipUTF8Validation: false,
12435
+ perMessageDeflate: true,
12436
+ followRedirects: false,
12437
+ maxRedirects: 10,
12438
+ ...options,
12439
+ socketPath: void 0,
12440
+ hostname: void 0,
12441
+ protocol: void 0,
12442
+ timeout: void 0,
12443
+ method: "GET",
12444
+ host: void 0,
12445
+ path: void 0,
12446
+ port: void 0
12447
+ };
12448
+ websocket._autoPong = opts.autoPong;
12449
+ websocket._closeTimeout = opts.closeTimeout;
12450
+ if (!protocolVersions.includes(opts.protocolVersion)) {
12451
+ throw new RangeError(
12452
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
12453
+ );
12454
+ }
12455
+ let parsedUrl;
12456
+ if (address instanceof URL2) {
12457
+ parsedUrl = address;
12458
+ } else {
12459
+ try {
12460
+ parsedUrl = new URL2(address);
12461
+ } catch (e) {
12462
+ throw new SyntaxError(`Invalid URL: ${address}`);
12463
+ }
12464
+ }
12465
+ if (parsedUrl.protocol === "http:") {
12466
+ parsedUrl.protocol = "ws:";
12467
+ } else if (parsedUrl.protocol === "https:") {
12468
+ parsedUrl.protocol = "wss:";
12469
+ }
12470
+ websocket._url = parsedUrl.href;
12471
+ const isSecure = parsedUrl.protocol === "wss:";
12472
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
12473
+ let invalidUrlMessage;
12474
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
12475
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
12476
+ } else if (isIpcUrl && !parsedUrl.pathname) {
12477
+ invalidUrlMessage = "The URL's pathname is empty";
12478
+ } else if (parsedUrl.hash) {
12479
+ invalidUrlMessage = "The URL contains a fragment identifier";
12480
+ }
12481
+ if (invalidUrlMessage) {
12482
+ const err = new SyntaxError(invalidUrlMessage);
12483
+ if (websocket._redirects === 0) {
12484
+ throw err;
12485
+ } else {
12486
+ emitErrorAndClose(websocket, err);
12487
+ return;
12488
+ }
12489
+ }
12490
+ const defaultPort = isSecure ? 443 : 80;
12491
+ const key = randomBytes(16).toString("base64");
12492
+ const request = isSecure ? https.request : http.request;
12493
+ const protocolSet = /* @__PURE__ */ new Set();
12494
+ let perMessageDeflate;
12495
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
12496
+ opts.defaultPort = opts.defaultPort || defaultPort;
12497
+ opts.port = parsedUrl.port || defaultPort;
12498
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
12499
+ opts.headers = {
12500
+ ...opts.headers,
12501
+ "Sec-WebSocket-Version": opts.protocolVersion,
12502
+ "Sec-WebSocket-Key": key,
12503
+ Connection: "Upgrade",
12504
+ Upgrade: "websocket"
12505
+ };
12506
+ opts.path = parsedUrl.pathname + parsedUrl.search;
12507
+ opts.timeout = opts.handshakeTimeout;
12508
+ if (opts.perMessageDeflate) {
12509
+ perMessageDeflate = new PerMessageDeflate(
12510
+ opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
12511
+ false,
12512
+ opts.maxPayload
12513
+ );
12514
+ opts.headers["Sec-WebSocket-Extensions"] = format({
12515
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
12516
+ });
12517
+ }
12518
+ if (protocols.length) {
12519
+ for (const protocol of protocols) {
12520
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
12521
+ throw new SyntaxError(
12522
+ "An invalid or duplicated subprotocol was specified"
12523
+ );
12524
+ }
12525
+ protocolSet.add(protocol);
12526
+ }
12527
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
12528
+ }
12529
+ if (opts.origin) {
12530
+ if (opts.protocolVersion < 13) {
12531
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
12532
+ } else {
12533
+ opts.headers.Origin = opts.origin;
12534
+ }
12535
+ }
12536
+ if (parsedUrl.username || parsedUrl.password) {
12537
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
12538
+ }
12539
+ if (isIpcUrl) {
12540
+ const parts = opts.path.split(":");
12541
+ opts.socketPath = parts[0];
12542
+ opts.path = parts[1];
12543
+ }
12544
+ let req;
12545
+ if (opts.followRedirects) {
12546
+ if (websocket._redirects === 0) {
12547
+ websocket._originalIpc = isIpcUrl;
12548
+ websocket._originalSecure = isSecure;
12549
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
12550
+ const headers = options && options.headers;
12551
+ options = { ...options, headers: {} };
12552
+ if (headers) {
12553
+ for (const [key2, value] of Object.entries(headers)) {
12554
+ options.headers[key2.toLowerCase()] = value;
12555
+ }
12556
+ }
12557
+ } else if (websocket.listenerCount("redirect") === 0) {
12558
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
12559
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
12560
+ delete opts.headers.authorization;
12561
+ delete opts.headers.cookie;
12562
+ if (!isSameHost) delete opts.headers.host;
12563
+ opts.auth = void 0;
12564
+ }
12565
+ }
12566
+ if (opts.auth && !options.headers.authorization) {
12567
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
12568
+ }
12569
+ req = websocket._req = request(opts);
12570
+ if (websocket._redirects) {
12571
+ websocket.emit("redirect", websocket.url, req);
12572
+ }
12573
+ } else {
12574
+ req = websocket._req = request(opts);
12575
+ }
12576
+ if (opts.timeout) {
12577
+ req.on("timeout", () => {
12578
+ abortHandshake(websocket, req, "Opening handshake has timed out");
12579
+ });
12580
+ }
12581
+ req.on("error", (err) => {
12582
+ if (req === null || req[kAborted]) return;
12583
+ req = websocket._req = null;
12584
+ emitErrorAndClose(websocket, err);
12585
+ });
12586
+ req.on("response", (res) => {
12587
+ const location = res.headers.location;
12588
+ const statusCode = res.statusCode;
12589
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
12590
+ if (++websocket._redirects > opts.maxRedirects) {
12591
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
12592
+ return;
12593
+ }
12594
+ req.abort();
12595
+ let addr;
12596
+ try {
12597
+ addr = new URL2(location, address);
12598
+ } catch (e) {
12599
+ const err = new SyntaxError(`Invalid URL: ${location}`);
12600
+ emitErrorAndClose(websocket, err);
12601
+ return;
12602
+ }
12603
+ initAsClient(websocket, addr, protocols, options);
12604
+ } else if (!websocket.emit("unexpected-response", req, res)) {
12605
+ abortHandshake(
12606
+ websocket,
12607
+ req,
12608
+ `Unexpected server response: ${res.statusCode}`
12609
+ );
12610
+ }
12611
+ });
12612
+ req.on("upgrade", (res, socket, head) => {
12613
+ websocket.emit("upgrade", res);
12614
+ if (websocket.readyState !== WebSocket.CONNECTING) return;
12615
+ req = websocket._req = null;
12616
+ const upgrade = res.headers.upgrade;
12617
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
12618
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
12619
+ return;
12620
+ }
12621
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
12622
+ if (res.headers["sec-websocket-accept"] !== digest) {
12623
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
12624
+ return;
12625
+ }
12626
+ const serverProt = res.headers["sec-websocket-protocol"];
12627
+ let protError;
12628
+ if (serverProt !== void 0) {
12629
+ if (!protocolSet.size) {
12630
+ protError = "Server sent a subprotocol but none was requested";
12631
+ } else if (!protocolSet.has(serverProt)) {
12632
+ protError = "Server sent an invalid subprotocol";
12633
+ }
12634
+ } else if (protocolSet.size) {
12635
+ protError = "Server sent no subprotocol";
12636
+ }
12637
+ if (protError) {
12638
+ abortHandshake(websocket, socket, protError);
12639
+ return;
12640
+ }
12641
+ if (serverProt) websocket._protocol = serverProt;
12642
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
12643
+ if (secWebSocketExtensions !== void 0) {
12644
+ if (!perMessageDeflate) {
12645
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
12646
+ abortHandshake(websocket, socket, message);
12647
+ return;
12648
+ }
12649
+ let extensions;
12650
+ try {
12651
+ extensions = parse(secWebSocketExtensions);
12652
+ } catch (err) {
12653
+ const message = "Invalid Sec-WebSocket-Extensions header";
12654
+ abortHandshake(websocket, socket, message);
12655
+ return;
12656
+ }
12657
+ const extensionNames = Object.keys(extensions);
12658
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
12659
+ const message = "Server indicated an extension that was not requested";
12660
+ abortHandshake(websocket, socket, message);
12661
+ return;
12662
+ }
12663
+ try {
12664
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
12665
+ } catch (err) {
12666
+ const message = "Invalid Sec-WebSocket-Extensions header";
12667
+ abortHandshake(websocket, socket, message);
12668
+ return;
12669
+ }
12670
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
12671
+ }
12672
+ websocket.setSocket(socket, head, {
12673
+ allowSynchronousEvents: opts.allowSynchronousEvents,
12674
+ generateMask: opts.generateMask,
12675
+ maxPayload: opts.maxPayload,
12676
+ skipUTF8Validation: opts.skipUTF8Validation
12677
+ });
12678
+ });
12679
+ if (opts.finishRequest) {
12680
+ opts.finishRequest(req, websocket);
12681
+ } else {
12682
+ req.end();
12683
+ }
12684
+ }
12685
+ function emitErrorAndClose(websocket, err) {
12686
+ websocket._readyState = WebSocket.CLOSING;
12687
+ websocket._errorEmitted = true;
12688
+ websocket.emit("error", err);
12689
+ websocket.emitClose();
12690
+ }
12691
+ function netConnect(options) {
12692
+ options.path = options.socketPath;
12693
+ return net.connect(options);
12694
+ }
12695
+ function tlsConnect(options) {
12696
+ options.path = void 0;
12697
+ if (!options.servername && options.servername !== "") {
12698
+ options.servername = net.isIP(options.host) ? "" : options.host;
12699
+ }
12700
+ return tls.connect(options);
12701
+ }
12702
+ function abortHandshake(websocket, stream, message) {
12703
+ websocket._readyState = WebSocket.CLOSING;
12704
+ const err = new Error(message);
12705
+ Error.captureStackTrace(err, abortHandshake);
12706
+ if (stream.setHeader) {
12707
+ stream[kAborted] = true;
12708
+ stream.abort();
12709
+ if (stream.socket && !stream.socket.destroyed) {
12710
+ stream.socket.destroy();
12711
+ }
12712
+ process.nextTick(emitErrorAndClose, websocket, err);
12713
+ } else {
12714
+ stream.destroy(err);
12715
+ stream.once("error", websocket.emit.bind(websocket, "error"));
12716
+ stream.once("close", websocket.emitClose.bind(websocket));
12717
+ }
12718
+ }
12719
+ function sendAfterClose(websocket, data, cb) {
12720
+ if (data) {
12721
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
12722
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
12723
+ else websocket._bufferedAmount += length;
12724
+ }
12725
+ if (cb) {
12726
+ const err = new Error(
12727
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
12728
+ );
12729
+ process.nextTick(cb, err);
12730
+ }
12731
+ }
12732
+ function receiverOnConclude(code, reason) {
12733
+ const websocket = this[kWebSocket];
12734
+ websocket._closeFrameReceived = true;
12735
+ websocket._closeMessage = reason;
12736
+ websocket._closeCode = code;
12737
+ if (websocket._socket[kWebSocket] === void 0) return;
12738
+ websocket._socket.removeListener("data", socketOnData);
12739
+ process.nextTick(resume, websocket._socket);
12740
+ if (code === 1005) websocket.close();
12741
+ else websocket.close(code, reason);
12742
+ }
12743
+ function receiverOnDrain() {
12744
+ const websocket = this[kWebSocket];
12745
+ if (!websocket.isPaused) websocket._socket.resume();
12746
+ }
12747
+ function receiverOnError(err) {
12748
+ const websocket = this[kWebSocket];
12749
+ if (websocket._socket[kWebSocket] !== void 0) {
12750
+ websocket._socket.removeListener("data", socketOnData);
12751
+ process.nextTick(resume, websocket._socket);
12752
+ websocket.close(err[kStatusCode]);
12753
+ }
12754
+ if (!websocket._errorEmitted) {
12755
+ websocket._errorEmitted = true;
12756
+ websocket.emit("error", err);
12757
+ }
12758
+ }
12759
+ function receiverOnFinish() {
12760
+ this[kWebSocket].emitClose();
12761
+ }
12762
+ function receiverOnMessage(data, isBinary) {
12763
+ this[kWebSocket].emit("message", data, isBinary);
12764
+ }
12765
+ function receiverOnPing(data) {
12766
+ const websocket = this[kWebSocket];
12767
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
12768
+ websocket.emit("ping", data);
12769
+ }
12770
+ function receiverOnPong(data) {
12771
+ this[kWebSocket].emit("pong", data);
12772
+ }
12773
+ function resume(stream) {
12774
+ stream.resume();
12775
+ }
12776
+ function senderOnError(err) {
12777
+ const websocket = this[kWebSocket];
12778
+ if (websocket.readyState === WebSocket.CLOSED) return;
12779
+ if (websocket.readyState === WebSocket.OPEN) {
12780
+ websocket._readyState = WebSocket.CLOSING;
12781
+ setCloseTimer(websocket);
12782
+ }
12783
+ this._socket.end();
12784
+ if (!websocket._errorEmitted) {
12785
+ websocket._errorEmitted = true;
12786
+ websocket.emit("error", err);
12787
+ }
12788
+ }
12789
+ function setCloseTimer(websocket) {
12790
+ websocket._closeTimer = setTimeout(
12791
+ websocket._socket.destroy.bind(websocket._socket),
12792
+ websocket._closeTimeout
12793
+ );
12794
+ }
12795
+ function socketOnClose() {
12796
+ const websocket = this[kWebSocket];
12797
+ this.removeListener("close", socketOnClose);
12798
+ this.removeListener("data", socketOnData);
12799
+ this.removeListener("end", socketOnEnd);
12800
+ websocket._readyState = WebSocket.CLOSING;
12801
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
12802
+ const chunk = this.read(this._readableState.length);
12803
+ websocket._receiver.write(chunk);
12804
+ }
12805
+ websocket._receiver.end();
12806
+ this[kWebSocket] = void 0;
12807
+ clearTimeout(websocket._closeTimer);
12808
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
12809
+ websocket.emitClose();
12810
+ } else {
12811
+ websocket._receiver.on("error", receiverOnFinish);
12812
+ websocket._receiver.on("finish", receiverOnFinish);
12813
+ }
12814
+ }
12815
+ function socketOnData(chunk) {
12816
+ if (!this[kWebSocket]._receiver.write(chunk)) {
12817
+ this.pause();
12818
+ }
12819
+ }
12820
+ function socketOnEnd() {
12821
+ const websocket = this[kWebSocket];
12822
+ websocket._readyState = WebSocket.CLOSING;
12823
+ websocket._receiver.end();
12824
+ this.end();
12825
+ }
12826
+ function socketOnError() {
12827
+ const websocket = this[kWebSocket];
12828
+ this.removeListener("error", socketOnError);
12829
+ this.on("error", NOOP);
12830
+ if (websocket) {
12831
+ websocket._readyState = WebSocket.CLOSING;
12832
+ this.destroy();
12833
+ }
12834
+ }
12835
+ }
12836
+ });
12837
+
12838
+ // node_modules/ws/lib/stream.js
12839
+ var require_stream = __commonJS({
12840
+ "node_modules/ws/lib/stream.js"(exports2, module2) {
12841
+ "use strict";
12842
+ var WebSocket = require_websocket();
12843
+ var { Duplex } = require("stream");
12844
+ function emitClose(stream) {
12845
+ stream.emit("close");
12846
+ }
12847
+ function duplexOnEnd() {
12848
+ if (!this.destroyed && this._writableState.finished) {
12849
+ this.destroy();
12850
+ }
12851
+ }
12852
+ function duplexOnError(err) {
12853
+ this.removeListener("error", duplexOnError);
12854
+ this.destroy();
12855
+ if (this.listenerCount("error") === 0) {
12856
+ this.emit("error", err);
12857
+ }
12858
+ }
12859
+ function createWebSocketStream(ws, options) {
12860
+ let terminateOnDestroy = true;
12861
+ const duplex = new Duplex({
12862
+ ...options,
12863
+ autoDestroy: false,
12864
+ emitClose: false,
12865
+ objectMode: false,
12866
+ writableObjectMode: false
12867
+ });
12868
+ ws.on("message", function message(msg, isBinary) {
12869
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
12870
+ if (!duplex.push(data)) ws.pause();
12871
+ });
12872
+ ws.once("error", function error(err) {
12873
+ if (duplex.destroyed) return;
12874
+ terminateOnDestroy = false;
12875
+ duplex.destroy(err);
12876
+ });
12877
+ ws.once("close", function close() {
12878
+ if (duplex.destroyed) return;
12879
+ duplex.push(null);
12880
+ });
12881
+ duplex._destroy = function(err, callback) {
12882
+ if (ws.readyState === ws.CLOSED) {
12883
+ callback(err);
12884
+ process.nextTick(emitClose, duplex);
12885
+ return;
12886
+ }
12887
+ let called = false;
12888
+ ws.once("error", function error(err2) {
12889
+ called = true;
12890
+ callback(err2);
12891
+ });
12892
+ ws.once("close", function close() {
12893
+ if (!called) callback(err);
12894
+ process.nextTick(emitClose, duplex);
12895
+ });
12896
+ if (terminateOnDestroy) ws.terminate();
12897
+ };
12898
+ duplex._final = function(callback) {
12899
+ if (ws.readyState === ws.CONNECTING) {
12900
+ ws.once("open", function open() {
12901
+ duplex._final(callback);
12902
+ });
12903
+ return;
12904
+ }
12905
+ if (ws._socket === null) return;
12906
+ if (ws._socket._writableState.finished) {
12907
+ callback();
12908
+ if (duplex._readableState.endEmitted) duplex.destroy();
12909
+ } else {
12910
+ ws._socket.once("finish", function finish() {
12911
+ callback();
12912
+ });
12913
+ ws.close();
12914
+ }
12915
+ };
12916
+ duplex._read = function() {
12917
+ if (ws.isPaused) ws.resume();
12918
+ };
12919
+ duplex._write = function(chunk, encoding, callback) {
12920
+ if (ws.readyState === ws.CONNECTING) {
12921
+ ws.once("open", function open() {
12922
+ duplex._write(chunk, encoding, callback);
12923
+ });
12924
+ return;
12925
+ }
12926
+ ws.send(chunk, callback);
12927
+ };
12928
+ duplex.on("end", duplexOnEnd);
12929
+ duplex.on("error", duplexOnError);
12930
+ return duplex;
12931
+ }
12932
+ module2.exports = createWebSocketStream;
12933
+ }
12934
+ });
12935
+
12936
+ // node_modules/ws/lib/subprotocol.js
12937
+ var require_subprotocol = __commonJS({
12938
+ "node_modules/ws/lib/subprotocol.js"(exports2, module2) {
12939
+ "use strict";
12940
+ var { tokenChars } = require_validation();
12941
+ function parse(header) {
12942
+ const protocols = /* @__PURE__ */ new Set();
12943
+ let start = -1;
12944
+ let end = -1;
12945
+ let i = 0;
12946
+ for (i; i < header.length; i++) {
12947
+ const code = header.charCodeAt(i);
12948
+ if (end === -1 && tokenChars[code] === 1) {
12949
+ if (start === -1) start = i;
12950
+ } else if (i !== 0 && (code === 32 || code === 9)) {
12951
+ if (end === -1 && start !== -1) end = i;
12952
+ } else if (code === 44) {
12953
+ if (start === -1) {
12954
+ throw new SyntaxError(`Unexpected character at index ${i}`);
12955
+ }
12956
+ if (end === -1) end = i;
12957
+ const protocol2 = header.slice(start, end);
12958
+ if (protocols.has(protocol2)) {
12959
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
12960
+ }
12961
+ protocols.add(protocol2);
12962
+ start = end = -1;
12963
+ } else {
12964
+ throw new SyntaxError(`Unexpected character at index ${i}`);
12965
+ }
12966
+ }
12967
+ if (start === -1 || end !== -1) {
12968
+ throw new SyntaxError("Unexpected end of input");
12969
+ }
12970
+ const protocol = header.slice(start, i);
12971
+ if (protocols.has(protocol)) {
12972
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
12973
+ }
12974
+ protocols.add(protocol);
12975
+ return protocols;
12976
+ }
12977
+ module2.exports = { parse };
12978
+ }
12979
+ });
12980
+
12981
+ // node_modules/ws/lib/websocket-server.js
12982
+ var require_websocket_server = __commonJS({
12983
+ "node_modules/ws/lib/websocket-server.js"(exports2, module2) {
12984
+ "use strict";
12985
+ var EventEmitter = require("events");
12986
+ var http = require("http");
12987
+ var { Duplex } = require("stream");
12988
+ var { createHash } = require("crypto");
12989
+ var extension = require_extension();
12990
+ var PerMessageDeflate = require_permessage_deflate();
12991
+ var subprotocol = require_subprotocol();
12992
+ var WebSocket = require_websocket();
12993
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
12994
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
12995
+ var RUNNING = 0;
12996
+ var CLOSING = 1;
12997
+ var CLOSED = 2;
12998
+ var WebSocketServer = class extends EventEmitter {
12999
+ /**
13000
+ * Create a `WebSocketServer` instance.
13001
+ *
13002
+ * @param {Object} options Configuration options
13003
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
13004
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
13005
+ * multiple times in the same tick
13006
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
13007
+ * automatically send a pong in response to a ping
13008
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
13009
+ * pending connections
13010
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
13011
+ * track clients
13012
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
13013
+ * wait for the closing handshake to finish after `websocket.close()` is
13014
+ * called
13015
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
13016
+ * @param {String} [options.host] The hostname where to bind the server
13017
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
13018
+ * size
13019
+ * @param {Boolean} [options.noServer=false] Enable no server mode
13020
+ * @param {String} [options.path] Accept only connections matching this path
13021
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
13022
+ * permessage-deflate
13023
+ * @param {Number} [options.port] The port where to bind the server
13024
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
13025
+ * server to use
13026
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
13027
+ * not to skip UTF-8 validation for text and close messages
13028
+ * @param {Function} [options.verifyClient] A hook to reject connections
13029
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
13030
+ * class to use. It must be the `WebSocket` class or class that extends it
13031
+ * @param {Function} [callback] A listener for the `listening` event
13032
+ */
13033
+ constructor(options, callback) {
13034
+ super();
13035
+ options = {
13036
+ allowSynchronousEvents: true,
13037
+ autoPong: true,
13038
+ maxPayload: 100 * 1024 * 1024,
13039
+ skipUTF8Validation: false,
13040
+ perMessageDeflate: false,
13041
+ handleProtocols: null,
13042
+ clientTracking: true,
13043
+ closeTimeout: CLOSE_TIMEOUT,
13044
+ verifyClient: null,
13045
+ noServer: false,
13046
+ backlog: null,
13047
+ // use default (511 as implemented in net.js)
13048
+ server: null,
13049
+ host: null,
13050
+ path: null,
13051
+ port: null,
13052
+ WebSocket,
13053
+ ...options
13054
+ };
13055
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
13056
+ throw new TypeError(
13057
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
13058
+ );
13059
+ }
13060
+ if (options.port != null) {
13061
+ this._server = http.createServer((req, res) => {
13062
+ const body = http.STATUS_CODES[426];
13063
+ res.writeHead(426, {
13064
+ "Content-Length": body.length,
13065
+ "Content-Type": "text/plain"
13066
+ });
13067
+ res.end(body);
13068
+ });
13069
+ this._server.listen(
13070
+ options.port,
13071
+ options.host,
13072
+ options.backlog,
13073
+ callback
13074
+ );
13075
+ } else if (options.server) {
13076
+ this._server = options.server;
13077
+ }
13078
+ if (this._server) {
13079
+ const emitConnection = this.emit.bind(this, "connection");
13080
+ this._removeListeners = addListeners(this._server, {
13081
+ listening: this.emit.bind(this, "listening"),
13082
+ error: this.emit.bind(this, "error"),
13083
+ upgrade: (req, socket, head) => {
13084
+ this.handleUpgrade(req, socket, head, emitConnection);
13085
+ }
13086
+ });
13087
+ }
13088
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
13089
+ if (options.clientTracking) {
13090
+ this.clients = /* @__PURE__ */ new Set();
13091
+ this._shouldEmitClose = false;
13092
+ }
13093
+ this.options = options;
13094
+ this._state = RUNNING;
13095
+ }
13096
+ /**
13097
+ * Returns the bound address, the address family name, and port of the server
13098
+ * as reported by the operating system if listening on an IP socket.
13099
+ * If the server is listening on a pipe or UNIX domain socket, the name is
13100
+ * returned as a string.
13101
+ *
13102
+ * @return {(Object|String|null)} The address of the server
13103
+ * @public
13104
+ */
13105
+ address() {
13106
+ if (this.options.noServer) {
13107
+ throw new Error('The server is operating in "noServer" mode');
13108
+ }
13109
+ if (!this._server) return null;
13110
+ return this._server.address();
13111
+ }
13112
+ /**
13113
+ * Stop the server from accepting new connections and emit the `'close'` event
13114
+ * when all existing connections are closed.
13115
+ *
13116
+ * @param {Function} [cb] A one-time listener for the `'close'` event
13117
+ * @public
13118
+ */
13119
+ close(cb) {
13120
+ if (this._state === CLOSED) {
13121
+ if (cb) {
13122
+ this.once("close", () => {
13123
+ cb(new Error("The server is not running"));
13124
+ });
13125
+ }
13126
+ process.nextTick(emitClose, this);
13127
+ return;
13128
+ }
13129
+ if (cb) this.once("close", cb);
13130
+ if (this._state === CLOSING) return;
13131
+ this._state = CLOSING;
13132
+ if (this.options.noServer || this.options.server) {
13133
+ if (this._server) {
13134
+ this._removeListeners();
13135
+ this._removeListeners = this._server = null;
13136
+ }
13137
+ if (this.clients) {
13138
+ if (!this.clients.size) {
13139
+ process.nextTick(emitClose, this);
13140
+ } else {
13141
+ this._shouldEmitClose = true;
13142
+ }
13143
+ } else {
13144
+ process.nextTick(emitClose, this);
13145
+ }
13146
+ } else {
13147
+ const server = this._server;
13148
+ this._removeListeners();
13149
+ this._removeListeners = this._server = null;
13150
+ server.close(() => {
13151
+ emitClose(this);
13152
+ });
13153
+ }
13154
+ }
13155
+ /**
13156
+ * See if a given request should be handled by this server instance.
13157
+ *
13158
+ * @param {http.IncomingMessage} req Request object to inspect
13159
+ * @return {Boolean} `true` if the request is valid, else `false`
13160
+ * @public
13161
+ */
13162
+ shouldHandle(req) {
13163
+ if (this.options.path) {
13164
+ const index = req.url.indexOf("?");
13165
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
13166
+ if (pathname !== this.options.path) return false;
13167
+ }
13168
+ return true;
13169
+ }
13170
+ /**
13171
+ * Handle a HTTP Upgrade request.
13172
+ *
13173
+ * @param {http.IncomingMessage} req The request object
13174
+ * @param {Duplex} socket The network socket between the server and client
13175
+ * @param {Buffer} head The first packet of the upgraded stream
13176
+ * @param {Function} cb Callback
13177
+ * @public
13178
+ */
13179
+ handleUpgrade(req, socket, head, cb) {
13180
+ socket.on("error", socketOnError);
13181
+ const key = req.headers["sec-websocket-key"];
13182
+ const upgrade = req.headers.upgrade;
13183
+ const version = +req.headers["sec-websocket-version"];
13184
+ if (req.method !== "GET") {
13185
+ const message = "Invalid HTTP method";
13186
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
13187
+ return;
13188
+ }
13189
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
13190
+ const message = "Invalid Upgrade header";
13191
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
13192
+ return;
13193
+ }
13194
+ if (key === void 0 || !keyRegex.test(key)) {
13195
+ const message = "Missing or invalid Sec-WebSocket-Key header";
13196
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
13197
+ return;
13198
+ }
13199
+ if (version !== 13 && version !== 8) {
13200
+ const message = "Missing or invalid Sec-WebSocket-Version header";
13201
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
13202
+ "Sec-WebSocket-Version": "13, 8"
13203
+ });
13204
+ return;
13205
+ }
13206
+ if (!this.shouldHandle(req)) {
13207
+ abortHandshake(socket, 400);
13208
+ return;
13209
+ }
13210
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
13211
+ let protocols = /* @__PURE__ */ new Set();
13212
+ if (secWebSocketProtocol !== void 0) {
13213
+ try {
13214
+ protocols = subprotocol.parse(secWebSocketProtocol);
13215
+ } catch (err) {
13216
+ const message = "Invalid Sec-WebSocket-Protocol header";
13217
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
13218
+ return;
13219
+ }
13220
+ }
13221
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
13222
+ const extensions = {};
13223
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
13224
+ const perMessageDeflate = new PerMessageDeflate(
13225
+ this.options.perMessageDeflate,
13226
+ true,
13227
+ this.options.maxPayload
13228
+ );
13229
+ try {
13230
+ const offers = extension.parse(secWebSocketExtensions);
13231
+ if (offers[PerMessageDeflate.extensionName]) {
13232
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
13233
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
13234
+ }
13235
+ } catch (err) {
13236
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
13237
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
13238
+ return;
13239
+ }
13240
+ }
13241
+ if (this.options.verifyClient) {
13242
+ const info = {
13243
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
13244
+ secure: !!(req.socket.authorized || req.socket.encrypted),
13245
+ req
13246
+ };
13247
+ if (this.options.verifyClient.length === 2) {
13248
+ this.options.verifyClient(info, (verified, code, message, headers) => {
13249
+ if (!verified) {
13250
+ return abortHandshake(socket, code || 401, message, headers);
13251
+ }
13252
+ this.completeUpgrade(
13253
+ extensions,
13254
+ key,
13255
+ protocols,
13256
+ req,
13257
+ socket,
13258
+ head,
13259
+ cb
13260
+ );
13261
+ });
13262
+ return;
13263
+ }
13264
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
13265
+ }
13266
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
13267
+ }
13268
+ /**
13269
+ * Upgrade the connection to WebSocket.
13270
+ *
13271
+ * @param {Object} extensions The accepted extensions
13272
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
13273
+ * @param {Set} protocols The subprotocols
13274
+ * @param {http.IncomingMessage} req The request object
13275
+ * @param {Duplex} socket The network socket between the server and client
13276
+ * @param {Buffer} head The first packet of the upgraded stream
13277
+ * @param {Function} cb Callback
13278
+ * @throws {Error} If called more than once with the same socket
13279
+ * @private
13280
+ */
13281
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
13282
+ if (!socket.readable || !socket.writable) return socket.destroy();
13283
+ if (socket[kWebSocket]) {
13284
+ throw new Error(
13285
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
13286
+ );
13287
+ }
13288
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
13289
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
13290
+ const headers = [
13291
+ "HTTP/1.1 101 Switching Protocols",
13292
+ "Upgrade: websocket",
13293
+ "Connection: Upgrade",
13294
+ `Sec-WebSocket-Accept: ${digest}`
13295
+ ];
13296
+ const ws = new this.options.WebSocket(null, void 0, this.options);
13297
+ if (protocols.size) {
13298
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
13299
+ if (protocol) {
13300
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
13301
+ ws._protocol = protocol;
13302
+ }
13303
+ }
13304
+ if (extensions[PerMessageDeflate.extensionName]) {
13305
+ const params = extensions[PerMessageDeflate.extensionName].params;
13306
+ const value = extension.format({
13307
+ [PerMessageDeflate.extensionName]: [params]
13308
+ });
13309
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
13310
+ ws._extensions = extensions;
13311
+ }
13312
+ this.emit("headers", headers, req);
13313
+ socket.write(headers.concat("\r\n").join("\r\n"));
13314
+ socket.removeListener("error", socketOnError);
13315
+ ws.setSocket(socket, head, {
13316
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
13317
+ maxPayload: this.options.maxPayload,
13318
+ skipUTF8Validation: this.options.skipUTF8Validation
13319
+ });
13320
+ if (this.clients) {
13321
+ this.clients.add(ws);
13322
+ ws.on("close", () => {
13323
+ this.clients.delete(ws);
13324
+ if (this._shouldEmitClose && !this.clients.size) {
13325
+ process.nextTick(emitClose, this);
13326
+ }
13327
+ });
13328
+ }
13329
+ cb(ws, req);
13330
+ }
13331
+ };
13332
+ module2.exports = WebSocketServer;
13333
+ function addListeners(server, map) {
13334
+ for (const event of Object.keys(map)) server.on(event, map[event]);
13335
+ return function removeListeners() {
13336
+ for (const event of Object.keys(map)) {
13337
+ server.removeListener(event, map[event]);
13338
+ }
13339
+ };
13340
+ }
13341
+ function emitClose(server) {
13342
+ server._state = CLOSED;
13343
+ server.emit("close");
13344
+ }
13345
+ function socketOnError() {
13346
+ this.destroy();
13347
+ }
13348
+ function abortHandshake(socket, code, message, headers) {
13349
+ message = message || http.STATUS_CODES[code];
13350
+ headers = {
13351
+ Connection: "close",
13352
+ "Content-Type": "text/html",
13353
+ "Content-Length": Buffer.byteLength(message),
13354
+ ...headers
13355
+ };
13356
+ socket.once("finish", socket.destroy);
13357
+ socket.end(
13358
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
13359
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
13360
+ );
13361
+ }
13362
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
13363
+ if (server.listenerCount("wsClientError")) {
13364
+ const err = new Error(message);
13365
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
13366
+ server.emit("wsClientError", err, socket, req);
13367
+ } else {
13368
+ abortHandshake(socket, code, message, headers);
13369
+ }
13370
+ }
13371
+ }
13372
+ });
13373
+
13374
+ // node_modules/ws/index.js
13375
+ var require_ws = __commonJS({
13376
+ "node_modules/ws/index.js"(exports2, module2) {
13377
+ "use strict";
13378
+ var WebSocket = require_websocket();
13379
+ WebSocket.createWebSocketStream = require_stream();
13380
+ WebSocket.Server = require_websocket_server();
13381
+ WebSocket.Receiver = require_receiver();
13382
+ WebSocket.Sender = require_sender();
13383
+ WebSocket.WebSocket = WebSocket;
13384
+ WebSocket.WebSocketServer = WebSocket.Server;
13385
+ module2.exports = WebSocket;
13386
+ }
13387
+ });
13388
+
13389
+ // src/responses/websocket.js
13390
+ var require_websocket2 = __commonJS({
13391
+ "src/responses/websocket.js"(exports2, module2) {
13392
+ "use strict";
13393
+ var EventEmitter = require("node:events");
13394
+ var { WebSocket } = require_ws();
13395
+ function buildResponsesWebSocketURL(clientParams) {
13396
+ const baseURL = clientParams.baseURL || "https://api.openai.com/v1";
13397
+ const path = "/responses";
13398
+ const url = new URL(baseURL + (baseURL.endsWith("/") ? path.slice(1) : path));
13399
+ const defaultQuery = clientParams.defaultQuery || {};
13400
+ for (const [key, value] of Object.entries(defaultQuery)) {
13401
+ if (value !== void 0 && value !== null) {
13402
+ url.searchParams.set(key, value);
13403
+ }
13404
+ }
13405
+ if (url.protocol === "https:") {
13406
+ url.protocol = "wss:";
13407
+ } else if (url.protocol === "http:") {
13408
+ url.protocol = "ws:";
13409
+ }
13410
+ return url;
13411
+ }
13412
+ function buildResponsesWebSocketHeaders(clientParams) {
13413
+ const headers = {};
13414
+ const defaultHeaders = clientParams.defaultHeaders || {};
13415
+ const hasAuthorizationOverride = Object.prototype.hasOwnProperty.call(
13416
+ defaultHeaders,
13417
+ "Authorization"
13418
+ );
13419
+ for (const [headerName, headerValue] of Object.entries(defaultHeaders)) {
13420
+ if (headerValue !== void 0 && headerValue !== null) {
13421
+ headers[headerName] = headerValue;
13422
+ }
13423
+ }
13424
+ if (!clientParams.defaultQuery && !hasAuthorizationOverride) {
13425
+ headers.Authorization = `Bearer ${clientParams.apiKey}`;
13426
+ }
13427
+ if (clientParams.organization) {
13428
+ headers["OpenAI-Organization"] = clientParams.organization;
13429
+ }
13430
+ return headers;
13431
+ }
13432
+ function createEventParseError(error) {
13433
+ const parseError = new Error("Could not parse Responses websocket event");
13434
+ parseError.cause = error;
13435
+ return parseError;
13436
+ }
13437
+ var ResponsesWebSocket = class extends EventEmitter {
13438
+ constructor(clientParams) {
13439
+ super();
13440
+ this.clientParams = clientParams;
13441
+ this.url = buildResponsesWebSocketURL(clientParams);
13442
+ this.headers = buildResponsesWebSocketHeaders(clientParams);
13443
+ this.socket = null;
13444
+ }
13445
+ async open() {
13446
+ if (this.socket) {
13447
+ throw new Error("Responses websocket connection is already open");
13448
+ }
13449
+ const socket = new WebSocket(this.url, { headers: this.headers });
13450
+ await new Promise((resolve, reject) => {
13451
+ socket.once("open", () => {
13452
+ this.socket = socket;
13453
+ this.attachSocketListeners(socket);
13454
+ resolve();
13455
+ });
13456
+ socket.once("error", reject);
13457
+ });
13458
+ return {
13459
+ url: this.url.toString()
13460
+ };
13461
+ }
13462
+ attachSocketListeners(socket) {
13463
+ socket.on("message", (data) => {
13464
+ let event;
13465
+ try {
13466
+ event = JSON.parse(data.toString());
13467
+ } catch (error) {
13468
+ this.emit("error", createEventParseError(error));
13469
+ return;
13470
+ }
13471
+ this.emit("event", event);
13472
+ });
13473
+ socket.on("error", (error) => {
13474
+ this.emit("error", error);
13475
+ });
13476
+ socket.on("close", (code, reason) => {
13477
+ if (this.socket === socket) {
13478
+ this.socket = null;
13479
+ }
13480
+ this.emit("close", {
13481
+ code,
13482
+ reason: reason.toString()
13483
+ });
13484
+ });
13485
+ }
13486
+ send(event) {
13487
+ if (!this.socket) {
13488
+ throw new Error("Responses websocket connection is not open");
13489
+ }
13490
+ this.socket.send(JSON.stringify(event));
13491
+ }
13492
+ async close(props = {}) {
13493
+ if (!this.socket) {
13494
+ throw new Error("Responses websocket connection is not open");
13495
+ }
13496
+ const socket = this.socket;
13497
+ const closeCode = props.code ?? 1e3;
13498
+ const closeReason = props.reason ?? "OK";
13499
+ await new Promise((resolve, reject) => {
13500
+ socket.once("close", resolve);
13501
+ socket.once("error", reject);
13502
+ socket.close(closeCode, closeReason);
13503
+ });
13504
+ return {
13505
+ code: closeCode,
13506
+ reason: closeReason
13507
+ };
13508
+ }
13509
+ };
13510
+ module2.exports = {
13511
+ ResponsesWebSocket
13512
+ };
13513
+ }
13514
+ });
13515
+
13516
+ // src/responses/methods.js
13517
+ var require_methods18 = __commonJS({
13518
+ "src/responses/methods.js"(exports2, module2) {
13519
+ var OpenAI = require_openai().OpenAI;
13520
+ var { ResponsesWebSocket } = require_websocket2();
13521
+ function getResponsesWebSocketConnections(node) {
13522
+ if (!node._responsesWebSocketConnections) {
13523
+ node._responsesWebSocketConnections = /* @__PURE__ */ new Map();
13524
+ }
13525
+ return node._responsesWebSocketConnections;
13526
+ }
13527
+ function ensureResponsesWebSocketCleanup(node) {
13528
+ if (node._responsesWebSocketCleanupRegistered) {
13529
+ return;
13530
+ }
13531
+ if (typeof node.registerCleanupHandler !== "function") {
13532
+ throw new Error("OpenAI API node does not support cleanup registration");
13533
+ }
13534
+ node._responsesWebSocketCleanupRegistered = true;
13535
+ node.registerCleanupHandler(async () => {
13536
+ const connections = getResponsesWebSocketConnections(node);
13537
+ const closeOperations = [];
13538
+ for (const connection of connections.values()) {
13539
+ closeOperations.push(
13540
+ connection.close({
13541
+ code: 1e3,
13542
+ reason: "Node-RED node closed"
13543
+ })
13544
+ );
13545
+ }
13546
+ await Promise.all(closeOperations);
13547
+ connections.clear();
13548
+ });
13549
+ }
13550
+ function requireConnectionId(payload) {
13551
+ if (typeof payload.connection_id !== "string" || payload.connection_id.trim() === "") {
13552
+ throw new Error("msg.payload.connection_id must be a non-empty string");
13553
+ }
13554
+ return payload.connection_id;
13555
+ }
13556
+ function createResponsesWebSocketEventMessage(connectionId, event) {
13557
+ return {
13558
+ payload: event,
13559
+ openai: {
13560
+ transport: "responses.websocket",
13561
+ direction: "server",
13562
+ connection_id: connectionId,
13563
+ event_type: event.type
13564
+ }
13565
+ };
13566
+ }
13567
+ function attachResponsesWebSocketListeners(node, connectionId, connection) {
13568
+ connection.on("event", (event) => {
13569
+ node.send(createResponsesWebSocketEventMessage(connectionId, event));
13570
+ });
13571
+ connection.on("error", (error) => {
13572
+ node.error(error);
13573
+ });
13574
+ connection.on("close", () => {
13575
+ const connections = getResponsesWebSocketConnections(node);
13576
+ connections.delete(connectionId);
13577
+ });
13578
+ }
13579
+ async function connectResponsesWebSocket(parameters) {
13580
+ const node = parameters._node;
13581
+ const payload = parameters.payload || {};
13582
+ const connectionId = requireConnectionId(payload);
13583
+ const connections = getResponsesWebSocketConnections(node);
13584
+ if (connections.has(connectionId)) {
13585
+ throw new Error(
13586
+ `Responses websocket connection '${connectionId}' is already open on this node`
13587
+ );
13588
+ }
13589
+ ensureResponsesWebSocketCleanup(node);
13590
+ const connection = new ResponsesWebSocket(this.clientParams);
13591
+ const connectionDetails = await connection.open();
13592
+ attachResponsesWebSocketListeners(node, connectionId, connection);
13593
+ connections.set(connectionId, connection);
13594
+ return {
13595
+ object: "response.websocket.connection",
13596
+ action: "connect",
13597
+ connection_id: connectionId,
13598
+ url: connectionDetails.url
13599
+ };
13600
+ }
13601
+ async function sendResponsesWebSocketEvent(parameters) {
13602
+ const node = parameters._node;
13603
+ const payload = parameters.payload || {};
13604
+ const connectionId = requireConnectionId(payload);
13605
+ const connections = getResponsesWebSocketConnections(node);
13606
+ const connection = connections.get(connectionId);
13607
+ if (!connection) {
13608
+ throw new Error(
13609
+ `Responses websocket connection '${connectionId}' is not open on this node`
13610
+ );
13611
+ }
13612
+ if (!payload.event || typeof payload.event !== "object" || Array.isArray(payload.event)) {
13613
+ throw new Error("msg.payload.event must be an object");
13614
+ }
13615
+ if (payload.event.type !== "response.create") {
13616
+ throw new Error("msg.payload.event.type must be 'response.create'");
13617
+ }
13618
+ connection.send(payload.event);
13619
+ return {
13620
+ object: "response.websocket.client_event",
13621
+ action: "send",
13622
+ connection_id: connectionId,
13623
+ event_type: payload.event.type
13624
+ };
13625
+ }
13626
+ async function closeResponsesWebSocket(parameters) {
13627
+ const node = parameters._node;
13628
+ const payload = parameters.payload || {};
13629
+ const connectionId = requireConnectionId(payload);
13630
+ const connections = getResponsesWebSocketConnections(node);
13631
+ const connection = connections.get(connectionId);
13632
+ if (!connection) {
13633
+ throw new Error(
13634
+ `Responses websocket connection '${connectionId}' is not open on this node`
13635
+ );
13636
+ }
13637
+ const closeDetails = await connection.close({
13638
+ code: payload.code,
13639
+ reason: payload.reason
13640
+ });
13641
+ connections.delete(connectionId);
13642
+ return {
13643
+ object: "response.websocket.connection",
13644
+ action: "close",
13645
+ connection_id: connectionId,
13646
+ code: closeDetails.code,
13647
+ reason: closeDetails.reason
13648
+ };
13649
+ }
13650
+ async function streamResponse(parameters, response) {
13651
+ const { _node, msg } = parameters;
13652
+ _node.status({
13653
+ fill: "green",
13654
+ shape: "dot",
13655
+ text: "OpenaiApi.status.streaming"
13656
+ });
13657
+ for await (const chunk of response) {
13658
+ if (typeof chunk === "object") {
13659
+ const newMsg = { ...msg, payload: chunk };
13660
+ _node.send(newMsg);
13661
+ }
13662
+ }
13663
+ _node.status({});
13664
+ }
13665
+ async function createModelResponse(parameters) {
13666
+ const openai = new OpenAI(this.clientParams);
13667
+ const response = await openai.responses.create(parameters.payload);
13668
+ if (parameters.payload.stream) {
13669
+ await streamResponse(parameters, response);
13670
+ } else {
13671
+ return response;
13672
+ }
13673
+ }
13674
+ async function getModelResponse(parameters) {
13675
+ const openai = new OpenAI(this.clientParams);
13676
+ const { response_id, ...params } = parameters.payload;
13677
+ const response = await openai.responses.retrieve(response_id, params);
13678
+ if (params.stream) {
13679
+ await streamResponse(parameters, response);
13680
+ } else {
13681
+ return response;
13682
+ }
13683
+ }
13684
+ async function deleteModelResponse(parameters) {
13685
+ const openai = new OpenAI(this.clientParams);
13686
+ const { response_id, ...params } = parameters.payload;
13687
+ const response = await openai.responses.delete(response_id, params);
13688
+ return response;
13689
+ }
13690
+ async function cancelModelResponse(parameters) {
13691
+ const openai = new OpenAI(this.clientParams);
13692
+ const { response_id, ...params } = parameters.payload;
13693
+ const response = await openai.responses.cancel(response_id, params);
13694
+ return response;
13695
+ }
13696
+ async function compactModelResponse(parameters) {
13697
+ const openai = new OpenAI(this.clientParams);
13698
+ const response = await openai.responses.compact(parameters.payload);
13699
+ return response;
13700
+ }
13701
+ async function listInputItems(parameters) {
13702
+ const openai = new OpenAI(this.clientParams);
13703
+ const { response_id, ...params } = parameters.payload;
13704
+ const list = await openai.responses.inputItems.list(response_id, params);
13705
+ return [...list.data];
13706
+ }
13707
+ async function countInputTokens(parameters) {
13708
+ const openai = new OpenAI(this.clientParams);
13709
+ const response = await openai.responses.inputTokens.count(parameters.payload);
13710
+ return response;
13711
+ }
13712
+ async function manageModelResponseWebSocket(parameters) {
13713
+ const payload = parameters.payload || {};
13714
+ if (typeof payload.action !== "string" || payload.action.trim() === "") {
13715
+ throw new Error(
13716
+ "msg.payload.action must be one of 'connect', 'send', or 'close'"
13717
+ );
13718
+ }
13719
+ if (payload.action === "connect") {
13720
+ return connectResponsesWebSocket.call(this, parameters);
13721
+ }
13722
+ if (payload.action === "send") {
13723
+ return sendResponsesWebSocketEvent.call(this, parameters);
13724
+ }
13725
+ if (payload.action === "close") {
13726
+ return closeResponsesWebSocket.call(this, parameters);
13727
+ }
13728
+ throw new Error("msg.payload.action must be one of 'connect', 'send', or 'close'");
9774
13729
  }
9775
13730
  module2.exports = {
9776
13731
  createModelResponse,
@@ -9779,7 +13734,8 @@ var require_methods18 = __commonJS({
9779
13734
  cancelModelResponse,
9780
13735
  compactModelResponse,
9781
13736
  listInputItems,
9782
- countInputTokens
13737
+ countInputTokens,
13738
+ manageModelResponseWebSocket
9783
13739
  };
9784
13740
  }
9785
13741
  });