@deepgram/sdk 5.0.0-alpha.3 → 5.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/LICENSE +1 -1
  2. package/dist/browser/index.global.js +496 -1104
  3. package/dist/cjs/BaseClient.d.ts +7 -7
  4. package/dist/cjs/BaseClient.js +2 -2
  5. package/dist/cjs/Client.d.ts +1 -2
  6. package/dist/cjs/CustomClient.js +253 -249
  7. package/dist/cjs/api/resources/agent/client/Client.d.ts +1 -2
  8. package/dist/cjs/api/resources/agent/resources/v1/client/Client.d.ts +1 -2
  9. package/dist/cjs/api/resources/agent/resources/v1/client/Socket.d.ts +8 -8
  10. package/dist/cjs/api/resources/agent/resources/v1/client/Socket.js +9 -9
  11. package/dist/cjs/api/resources/agent/resources/v1/resources/settings/client/Client.d.ts +1 -2
  12. package/dist/cjs/api/resources/agent/resources/v1/resources/settings/resources/think/client/Client.d.ts +1 -2
  13. package/dist/cjs/api/resources/agent/resources/v1/resources/settings/resources/think/resources/models/client/Client.d.ts +1 -2
  14. package/dist/cjs/api/resources/auth/client/Client.d.ts +1 -2
  15. package/dist/cjs/api/resources/auth/resources/v1/client/Client.d.ts +1 -2
  16. package/dist/cjs/api/resources/auth/resources/v1/resources/tokens/client/Client.d.ts +1 -2
  17. package/dist/cjs/api/resources/listen/client/Client.d.ts +1 -2
  18. package/dist/cjs/api/resources/listen/resources/v1/client/Client.d.ts +1 -2
  19. package/dist/cjs/api/resources/listen/resources/v1/client/Client.js +29 -80
  20. package/dist/cjs/api/resources/listen/resources/v1/client/Socket.d.ts +4 -4
  21. package/dist/cjs/api/resources/listen/resources/v1/client/Socket.js +5 -5
  22. package/dist/cjs/api/resources/listen/resources/v1/resources/media/client/Client.d.ts +1 -2
  23. package/dist/cjs/api/resources/listen/resources/v1/resources/media/client/Client.js +76 -298
  24. package/dist/cjs/api/resources/listen/resources/v2/client/Client.d.ts +1 -2
  25. package/dist/cjs/api/resources/listen/resources/v2/client/Client.js +11 -26
  26. package/dist/cjs/api/resources/listen/resources/v2/client/Socket.d.ts +2 -2
  27. package/dist/cjs/api/resources/listen/resources/v2/client/Socket.js +3 -3
  28. package/dist/cjs/api/resources/manage/client/Client.d.ts +1 -2
  29. package/dist/cjs/api/resources/manage/resources/v1/client/Client.d.ts +1 -2
  30. package/dist/cjs/api/resources/manage/resources/v1/resources/models/client/Client.d.ts +1 -2
  31. package/dist/cjs/api/resources/manage/resources/v1/resources/models/client/Client.js +3 -4
  32. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/client/Client.d.ts +1 -2
  33. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/client/Client.js +4 -7
  34. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/billing/client/Client.d.ts +1 -2
  35. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/balances/client/Client.d.ts +1 -2
  36. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/breakdown/client/Client.d.ts +1 -2
  37. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/breakdown/client/Client.js +9 -27
  38. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/fields/client/Client.d.ts +1 -2
  39. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/fields/client/Client.js +4 -7
  40. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/purchases/client/Client.d.ts +1 -2
  41. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/purchases/client/Client.js +3 -4
  42. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/keys/client/Client.d.ts +1 -2
  43. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/keys/client/Client.js +3 -4
  44. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/members/client/Client.d.ts +1 -2
  45. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/members/resources/invites/client/Client.d.ts +1 -2
  46. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/members/resources/scopes/client/Client.d.ts +1 -2
  47. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/models/client/Client.d.ts +1 -2
  48. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/models/client/Client.js +3 -4
  49. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/requests/client/Client.d.ts +1 -2
  50. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/requests/client/Client.js +12 -31
  51. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/usage/client/Client.d.ts +1 -2
  52. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/usage/client/Client.js +46 -133
  53. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/usage/resources/breakdown/client/Client.d.ts +1 -2
  54. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/usage/resources/breakdown/client/Client.js +47 -136
  55. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/usage/resources/fields/client/Client.d.ts +1 -2
  56. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/usage/resources/fields/client/Client.js +4 -7
  57. package/dist/cjs/api/resources/read/client/Client.d.ts +1 -2
  58. package/dist/cjs/api/resources/read/resources/v1/client/Client.d.ts +1 -2
  59. package/dist/cjs/api/resources/read/resources/v1/resources/text/client/Client.d.ts +1 -2
  60. package/dist/cjs/api/resources/read/resources/v1/resources/text/client/Client.js +14 -52
  61. package/dist/cjs/api/resources/selfHosted/client/Client.d.ts +1 -2
  62. package/dist/cjs/api/resources/selfHosted/resources/v1/client/Client.d.ts +1 -2
  63. package/dist/cjs/api/resources/selfHosted/resources/v1/resources/distributionCredentials/client/Client.d.ts +1 -2
  64. package/dist/cjs/api/resources/selfHosted/resources/v1/resources/distributionCredentials/client/Client.js +4 -12
  65. package/dist/cjs/api/resources/speak/client/Client.d.ts +1 -2
  66. package/dist/cjs/api/resources/speak/resources/v1/client/Client.d.ts +1 -2
  67. package/dist/cjs/api/resources/speak/resources/v1/client/Client.js +6 -13
  68. package/dist/cjs/api/resources/speak/resources/v1/client/Socket.d.ts +4 -4
  69. package/dist/cjs/api/resources/speak/resources/v1/client/Socket.js +4 -4
  70. package/dist/cjs/api/resources/speak/resources/v1/resources/audio/client/Client.d.ts +1 -2
  71. package/dist/cjs/api/resources/speak/resources/v1/resources/audio/client/Client.js +11 -33
  72. package/dist/cjs/auth/HeaderAuthProvider.d.ts +14 -8
  73. package/dist/cjs/auth/HeaderAuthProvider.js +19 -9
  74. package/dist/cjs/core/fetcher/EndpointSupplier.d.ts +2 -2
  75. package/dist/cjs/core/fetcher/Fetcher.d.ts +1 -2
  76. package/dist/cjs/core/headers.d.ts +2 -2
  77. package/dist/cjs/core/websocket/ws.d.ts +1 -1
  78. package/dist/cjs/version.d.ts +1 -1
  79. package/dist/cjs/version.js +1 -1
  80. package/dist/esm/BaseClient.d.mts +7 -7
  81. package/dist/esm/BaseClient.mjs +2 -2
  82. package/dist/esm/Client.d.mts +1 -2
  83. package/dist/esm/CustomClient.mjs +254 -250
  84. package/dist/esm/api/resources/agent/client/Client.d.mts +1 -2
  85. package/dist/esm/api/resources/agent/resources/v1/client/Client.d.mts +1 -2
  86. package/dist/esm/api/resources/agent/resources/v1/client/Socket.d.mts +8 -8
  87. package/dist/esm/api/resources/agent/resources/v1/client/Socket.mjs +9 -9
  88. package/dist/esm/api/resources/agent/resources/v1/resources/settings/client/Client.d.mts +1 -2
  89. package/dist/esm/api/resources/agent/resources/v1/resources/settings/resources/think/client/Client.d.mts +1 -2
  90. package/dist/esm/api/resources/agent/resources/v1/resources/settings/resources/think/resources/models/client/Client.d.mts +1 -2
  91. package/dist/esm/api/resources/auth/client/Client.d.mts +1 -2
  92. package/dist/esm/api/resources/auth/resources/v1/client/Client.d.mts +1 -2
  93. package/dist/esm/api/resources/auth/resources/v1/resources/tokens/client/Client.d.mts +1 -2
  94. package/dist/esm/api/resources/listen/client/Client.d.mts +1 -2
  95. package/dist/esm/api/resources/listen/resources/v1/client/Client.d.mts +1 -2
  96. package/dist/esm/api/resources/listen/resources/v1/client/Client.mjs +29 -80
  97. package/dist/esm/api/resources/listen/resources/v1/client/Socket.d.mts +4 -4
  98. package/dist/esm/api/resources/listen/resources/v1/client/Socket.mjs +5 -5
  99. package/dist/esm/api/resources/listen/resources/v1/resources/media/client/Client.d.mts +1 -2
  100. package/dist/esm/api/resources/listen/resources/v1/resources/media/client/Client.mjs +76 -298
  101. package/dist/esm/api/resources/listen/resources/v2/client/Client.d.mts +1 -2
  102. package/dist/esm/api/resources/listen/resources/v2/client/Client.mjs +11 -26
  103. package/dist/esm/api/resources/listen/resources/v2/client/Socket.d.mts +2 -2
  104. package/dist/esm/api/resources/listen/resources/v2/client/Socket.mjs +3 -3
  105. package/dist/esm/api/resources/manage/client/Client.d.mts +1 -2
  106. package/dist/esm/api/resources/manage/resources/v1/client/Client.d.mts +1 -2
  107. package/dist/esm/api/resources/manage/resources/v1/resources/models/client/Client.d.mts +1 -2
  108. package/dist/esm/api/resources/manage/resources/v1/resources/models/client/Client.mjs +3 -4
  109. package/dist/esm/api/resources/manage/resources/v1/resources/projects/client/Client.d.mts +1 -2
  110. package/dist/esm/api/resources/manage/resources/v1/resources/projects/client/Client.mjs +4 -7
  111. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/billing/client/Client.d.mts +1 -2
  112. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/balances/client/Client.d.mts +1 -2
  113. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/breakdown/client/Client.d.mts +1 -2
  114. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/breakdown/client/Client.mjs +9 -27
  115. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/fields/client/Client.d.mts +1 -2
  116. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/fields/client/Client.mjs +4 -7
  117. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/purchases/client/Client.d.mts +1 -2
  118. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/purchases/client/Client.mjs +3 -4
  119. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/keys/client/Client.d.mts +1 -2
  120. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/keys/client/Client.mjs +3 -4
  121. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/members/client/Client.d.mts +1 -2
  122. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/members/resources/invites/client/Client.d.mts +1 -2
  123. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/members/resources/scopes/client/Client.d.mts +1 -2
  124. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/models/client/Client.d.mts +1 -2
  125. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/models/client/Client.mjs +3 -4
  126. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/requests/client/Client.d.mts +1 -2
  127. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/requests/client/Client.mjs +12 -31
  128. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/usage/client/Client.d.mts +1 -2
  129. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/usage/client/Client.mjs +46 -133
  130. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/usage/resources/breakdown/client/Client.d.mts +1 -2
  131. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/usage/resources/breakdown/client/Client.mjs +47 -136
  132. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/usage/resources/fields/client/Client.d.mts +1 -2
  133. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/usage/resources/fields/client/Client.mjs +4 -7
  134. package/dist/esm/api/resources/read/client/Client.d.mts +1 -2
  135. package/dist/esm/api/resources/read/resources/v1/client/Client.d.mts +1 -2
  136. package/dist/esm/api/resources/read/resources/v1/resources/text/client/Client.d.mts +1 -2
  137. package/dist/esm/api/resources/read/resources/v1/resources/text/client/Client.mjs +14 -52
  138. package/dist/esm/api/resources/selfHosted/client/Client.d.mts +1 -2
  139. package/dist/esm/api/resources/selfHosted/resources/v1/client/Client.d.mts +1 -2
  140. package/dist/esm/api/resources/selfHosted/resources/v1/resources/distributionCredentials/client/Client.d.mts +1 -2
  141. package/dist/esm/api/resources/selfHosted/resources/v1/resources/distributionCredentials/client/Client.mjs +4 -12
  142. package/dist/esm/api/resources/speak/client/Client.d.mts +1 -2
  143. package/dist/esm/api/resources/speak/resources/v1/client/Client.d.mts +1 -2
  144. package/dist/esm/api/resources/speak/resources/v1/client/Client.mjs +6 -13
  145. package/dist/esm/api/resources/speak/resources/v1/client/Socket.d.mts +4 -4
  146. package/dist/esm/api/resources/speak/resources/v1/client/Socket.mjs +4 -4
  147. package/dist/esm/api/resources/speak/resources/v1/resources/audio/client/Client.d.mts +1 -2
  148. package/dist/esm/api/resources/speak/resources/v1/resources/audio/client/Client.mjs +11 -33
  149. package/dist/esm/auth/HeaderAuthProvider.d.mts +14 -8
  150. package/dist/esm/auth/HeaderAuthProvider.mjs +19 -9
  151. package/dist/esm/core/fetcher/EndpointSupplier.d.mts +2 -2
  152. package/dist/esm/core/fetcher/Fetcher.d.mts +1 -2
  153. package/dist/esm/core/headers.d.mts +2 -2
  154. package/dist/esm/core/websocket/ws.d.mts +1 -1
  155. package/dist/esm/version.d.mts +1 -1
  156. package/dist/esm/version.mjs +1 -1
  157. package/package.json +10 -7
@@ -61,6 +61,8 @@ const json_js_1 = require("./core/json.js");
61
61
  const core = __importStar(require("./core/index.js"));
62
62
  const environments = __importStar(require("./environments.js"));
63
63
  const index_js_1 = require("./core/runtime/index.js");
64
+ // Default WebSocket connection timeout in milliseconds
65
+ const DEFAULT_CONNECTION_TIMEOUT_MS = 10000;
64
66
  // Import ws library for Node.js (will be undefined in browser)
65
67
  let NodeWebSocket;
66
68
  try {
@@ -75,29 +77,55 @@ catch (_a) {
75
77
  }
76
78
  // Helper function to generate UUID that works in both Node.js and browser
77
79
  function generateUUID() {
78
- // In Node.js, use the crypto module
80
+ // Try global crypto.randomUUID first (works in both Node.js 14.18+ and modern browsers)
81
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
82
+ return crypto.randomUUID();
83
+ }
84
+ // Fallback for Node.js: use the crypto module
79
85
  if (index_js_1.RUNTIME.type === "node") {
80
86
  try {
81
87
  // eslint-disable-next-line @typescript-eslint/no-require-imports
82
- const crypto = require("crypto");
83
- return crypto.randomUUID();
88
+ const nodeCrypto = require("crypto");
89
+ return nodeCrypto.randomUUID();
84
90
  }
85
91
  catch (_a) {
86
92
  // Fallback if crypto module is not available
87
93
  }
88
94
  }
89
- // In browser or as fallback, use global crypto if available
90
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
91
- return crypto.randomUUID();
92
- }
93
- // Fallback UUID generation (RFC4122 version 4)
94
- // This is a simple fallback that should work everywhere
95
+ // Final fallback: manual UUID generation (RFC4122 version 4)
96
+ // This should work everywhere but is less secure than crypto.randomUUID()
95
97
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
96
98
  const r = (Math.random() * 16) | 0;
97
99
  const v = c === "x" ? r : (r & 0x3) | 0x8;
98
100
  return v.toString(16);
99
101
  });
100
102
  }
103
+ /**
104
+ * Wrapper auth provider that adds "Token " prefix to API keys.
105
+ * The auto-generated HeaderAuthProvider doesn't add the prefix, so we wrap it here.
106
+ */
107
+ class ApiKeyAuthProviderWrapper {
108
+ constructor(originalProvider) {
109
+ this.originalProvider = originalProvider;
110
+ }
111
+ getAuthRequest(arg) {
112
+ return __awaiter(this, void 0, void 0, function* () {
113
+ var _a, _b;
114
+ const authRequest = yield this.originalProvider.getAuthRequest(arg);
115
+ const authHeader = ((_a = authRequest.headers) === null || _a === void 0 ? void 0 : _a.Authorization) || ((_b = authRequest.headers) === null || _b === void 0 ? void 0 : _b.authorization);
116
+ // If the header doesn't already have a scheme prefix, add "Token " prefix for API keys
117
+ if (authHeader && typeof authHeader === "string") {
118
+ // Only add prefix if it doesn't already have Bearer or Token prefix
119
+ if (!authHeader.startsWith("Bearer ") && !authHeader.startsWith("Token ") && !authHeader.startsWith("token ")) {
120
+ return {
121
+ headers: Object.assign(Object.assign({}, authRequest.headers), { Authorization: `Token ${authHeader}` }),
122
+ };
123
+ }
124
+ }
125
+ return authRequest;
126
+ });
127
+ }
128
+ }
101
129
  /**
102
130
  * Wrapper auth provider that checks for accessToken first (Bearer scheme)
103
131
  * before falling back to the original auth provider (Token scheme for API keys).
@@ -135,7 +163,10 @@ class CustomDeepgramClient extends Client_1.DeepgramClient {
135
163
  const optionsWithSessionId = Object.assign(Object.assign({}, options), { headers: Object.assign(Object.assign({}, options.headers), { "x-deepgram-session-id": sessionId }) });
136
164
  super(optionsWithSessionId);
137
165
  this._sessionId = sessionId;
138
- // Wrap the auth provider to handle accessToken if provided
166
+ // Always wrap the auth provider to add "Token " prefix to API keys
167
+ // The auto-generated HeaderAuthProvider doesn't add the prefix
168
+ this._options.authProvider = new ApiKeyAuthProviderWrapper(this._options.authProvider);
169
+ // Wrap again to handle accessToken if provided
139
170
  // This ensures accessToken takes priority over apiKey/env var
140
171
  if (options.accessToken != null) {
141
172
  this._options.authProvider = new AccessTokenAuthProviderWrapper(this._options.authProvider, options.accessToken);
@@ -184,6 +215,11 @@ class CustomDeepgramClient extends Client_1.DeepgramClient {
184
215
  exports.CustomDeepgramClient = CustomDeepgramClient;
185
216
  /**
186
217
  * Wrapper for AgentClient that ensures custom websocket implementation is used.
218
+ *
219
+ * This wrapper exists to guarantee that our custom WebSocket implementation
220
+ * (from ws.ts) continues to be used even after the SDK code is auto-generated
221
+ * by Fern. Without this wrapper, Fern regeneration could overwrite the client
222
+ * with a different WebSocket implementation.
187
223
  */
188
224
  class WrappedAgentClient extends Client_js_1.AgentClient {
189
225
  get v1() {
@@ -192,6 +228,11 @@ class WrappedAgentClient extends Client_js_1.AgentClient {
192
228
  }
193
229
  /**
194
230
  * Wrapper for ListenClient that ensures custom websocket implementation is used.
231
+ *
232
+ * This wrapper exists to guarantee that our custom WebSocket implementation
233
+ * (from ws.ts) continues to be used even after the SDK code is auto-generated
234
+ * by Fern. Without this wrapper, Fern regeneration could overwrite the client
235
+ * with a different WebSocket implementation.
195
236
  */
196
237
  class WrappedListenClient extends Client_js_2.ListenClient {
197
238
  get v1() {
@@ -203,6 +244,11 @@ class WrappedListenClient extends Client_js_2.ListenClient {
203
244
  }
204
245
  /**
205
246
  * Wrapper for SpeakClient that ensures custom websocket implementation is used.
247
+ *
248
+ * This wrapper exists to guarantee that our custom WebSocket implementation
249
+ * (from ws.ts) continues to be used even after the SDK code is auto-generated
250
+ * by Fern. Without this wrapper, Fern regeneration could overwrite the client
251
+ * with a different WebSocket implementation.
206
252
  */
207
253
  class WrappedSpeakClient extends Client_js_3.SpeakClient {
208
254
  get v1() {
@@ -292,35 +338,108 @@ function getWebSocketOptions(headers) {
292
338
  }
293
339
  return options;
294
340
  }
341
+ /**
342
+ * Helper function to setup binary-aware message handling for WebSocket sockets.
343
+ * Handles both text (JSON) and binary messages correctly.
344
+ */
345
+ function setupBinaryHandling(socket, eventHandlers) {
346
+ var _a;
347
+ const binaryAwareHandler = (event) => {
348
+ var _a, _b, _c;
349
+ // Handle both text (JSON) and binary messages
350
+ if (typeof event.data === "string") {
351
+ try {
352
+ const data = (0, json_js_1.fromJson)(event.data);
353
+ (_a = eventHandlers.message) === null || _a === void 0 ? void 0 : _a.call(eventHandlers, data);
354
+ }
355
+ catch (error) {
356
+ // If JSON parsing fails, pass the raw string
357
+ (_b = eventHandlers.message) === null || _b === void 0 ? void 0 : _b.call(eventHandlers, event.data);
358
+ }
359
+ }
360
+ else {
361
+ // Binary data - pass through as-is
362
+ (_c = eventHandlers.message) === null || _c === void 0 ? void 0 : _c.call(eventHandlers, event.data);
363
+ }
364
+ };
365
+ // Remove the original handler and add our binary-aware one
366
+ const socketAny = socket;
367
+ if ((_a = socketAny._listeners) === null || _a === void 0 ? void 0 : _a.message) {
368
+ // Remove all message listeners
369
+ socketAny._listeners.message.forEach((listener) => {
370
+ socket.removeEventListener("message", listener);
371
+ });
372
+ }
373
+ // Add our binary-aware handler
374
+ socket.addEventListener("message", binaryAwareHandler);
375
+ return binaryAwareHandler;
376
+ }
377
+ /**
378
+ * Helper function to reset socket connection state before connecting.
379
+ * Ensures _connectLock is reset if the socket is in CLOSED state.
380
+ */
381
+ function resetSocketConnectionState(socket) {
382
+ if (socket.readyState === socket.CLOSED) {
383
+ // Force a fresh reconnect to ensure _connectLock is reset
384
+ socket._connectLock = false;
385
+ socket._shouldReconnect = true;
386
+ }
387
+ }
388
+ /**
389
+ * Helper function to create a WebSocket connection with common setup logic.
390
+ * Handles authentication, header merging, and WebSocket configuration.
391
+ * This reduces duplication across all Wrapped*Client classes.
392
+ */
393
+ function createWebSocketConnection(_a) {
394
+ return __awaiter(this, arguments, void 0, function* ({ options, urlPath, environmentKey, queryParams, headers, debug, reconnectAttempts, }) {
395
+ var _b, _c, _d, _e, _f, _g;
396
+ // Get Authorization from authProvider (cast to any to access internal property)
397
+ const authRequest = yield ((_b = options.authProvider) === null || _b === void 0 ? void 0 : _b.getAuthRequest());
398
+ // Merge headers from options (which includes session ID), auth headers, and request headers
399
+ const mergedHeaders = (0, headers_js_1.mergeHeaders)((_c = options.headers) !== null && _c !== void 0 ? _c : {}, (_d = authRequest === null || authRequest === void 0 ? void 0 : authRequest.headers) !== null && _d !== void 0 ? _d : {}, headers);
400
+ // Resolve any Suppliers in headers to actual values
401
+ const _headers = yield resolveHeaders(mergedHeaders);
402
+ // Get WebSocket options with proper header handling
403
+ const wsOptions = getWebSocketOptions(_headers);
404
+ // Get the appropriate base URL for the environment
405
+ const baseUrl = (_e = (yield core.Supplier.get(options.baseUrl))) !== null && _e !== void 0 ? _e : ((_f = (yield core.Supplier.get(options.environment))) !== null && _f !== void 0 ? _f : environments.DeepgramEnvironment.Production)[environmentKey];
406
+ // Create and return the ReconnectingWebSocket
407
+ return new ws_js_1.ReconnectingWebSocket({
408
+ url: core.url.join(baseUrl, urlPath),
409
+ protocols: (_g = wsOptions.protocols) !== null && _g !== void 0 ? _g : [],
410
+ queryParameters: queryParams,
411
+ headers: wsOptions.headers,
412
+ options: {
413
+ WebSocket: wsOptions.WebSocket,
414
+ debug: debug !== null && debug !== void 0 ? debug : false,
415
+ maxRetries: reconnectAttempts !== null && reconnectAttempts !== void 0 ? reconnectAttempts : 30,
416
+ startClosed: true,
417
+ connectionTimeout: DEFAULT_CONNECTION_TIMEOUT_MS,
418
+ },
419
+ });
420
+ });
421
+ }
295
422
  /**
296
423
  * Wrapper for Agent V1Client that overrides connect to use custom websocket.
424
+ *
425
+ * This wrapper ensures that the connect() method uses our custom ReconnectingWebSocket
426
+ * implementation instead of any auto-generated WebSocket handling. This guarantees
427
+ * consistent behavior across Fern regenerations and allows us to customize
428
+ * connection setup, authentication, and header handling.
297
429
  */
298
430
  class WrappedAgentV1Client extends Client_js_4.V1Client {
299
431
  connect() {
300
432
  return __awaiter(this, arguments, void 0, function* (args = {}) {
301
- var _a, _b, _c, _d, _e, _f;
302
433
  const { headers, debug, reconnectAttempts } = args;
303
- // Get Authorization from authProvider (matching the working version)
304
- const authRequest = yield ((_a = this._options.authProvider) === null || _a === void 0 ? void 0 : _a.getAuthRequest());
305
- // Merge headers from options (which includes session ID), auth headers, and request headers
306
- const mergedHeaders = (0, headers_js_1.mergeHeaders)((_b = this._options.headers) !== null && _b !== void 0 ? _b : {}, (_c = authRequest === null || authRequest === void 0 ? void 0 : authRequest.headers) !== null && _c !== void 0 ? _c : {}, headers);
307
- // Resolve any Suppliers in headers to actual values
308
- const _headers = yield resolveHeaders(mergedHeaders);
309
- // Get WebSocket options with proper header handling
310
- const wsOptions = getWebSocketOptions(_headers);
311
- // Explicitly use the custom ReconnectingWebSocket from ws.ts
312
- const socket = new ws_js_1.ReconnectingWebSocket({
313
- url: core.url.join((_d = (yield core.Supplier.get(this._options.baseUrl))) !== null && _d !== void 0 ? _d : ((_e = (yield core.Supplier.get(this._options.environment))) !== null && _e !== void 0 ? _e : environments.DeepgramEnvironment.Production).agent, "/v1/agent/converse"),
314
- protocols: (_f = wsOptions.protocols) !== null && _f !== void 0 ? _f : [],
315
- queryParameters: {},
316
- headers: wsOptions.headers,
317
- options: {
318
- WebSocket: wsOptions.WebSocket,
319
- debug: debug !== null && debug !== void 0 ? debug : false,
320
- maxRetries: reconnectAttempts !== null && reconnectAttempts !== void 0 ? reconnectAttempts : 30,
321
- startClosed: true,
322
- connectionTimeout: 10000, // Increase timeout to 10 seconds
323
- },
434
+ // Use shared connection helper
435
+ const socket = yield createWebSocketConnection({
436
+ options: this._options,
437
+ urlPath: "/v1/agent/converse",
438
+ environmentKey: 'agent',
439
+ queryParams: {},
440
+ headers,
441
+ debug,
442
+ reconnectAttempts,
324
443
  });
325
444
  return new WrappedAgentV1Socket({ socket });
326
445
  });
@@ -328,6 +447,11 @@ class WrappedAgentV1Client extends Client_js_4.V1Client {
328
447
  }
329
448
  /**
330
449
  * Wrapper for Agent V1Socket that handles binary messages correctly.
450
+ *
451
+ * This wrapper ensures that both text (JSON) and binary WebSocket messages are
452
+ * handled properly. The auto-generated socket class may not handle binary data
453
+ * correctly, so we override the message handling to support both formats.
454
+ * This is critical for audio and other binary data streaming.
331
455
  */
332
456
  class WrappedAgentV1Socket extends Socket_js_1.V1Socket {
333
457
  constructor(args) {
@@ -335,50 +459,10 @@ class WrappedAgentV1Socket extends Socket_js_1.V1Socket {
335
459
  this.setupBinaryHandling();
336
460
  }
337
461
  setupBinaryHandling() {
338
- var _a;
339
- // Create a binary-aware message handler
340
- this.binaryAwareHandler = (event) => {
341
- var _a, _b, _c, _d, _e, _f;
342
- // Handle both text (JSON) and binary messages
343
- if (typeof event.data === "string") {
344
- try {
345
- const data = (0, json_js_1.fromJson)(event.data);
346
- (_b = (_a = this.eventHandlers).message) === null || _b === void 0 ? void 0 : _b.call(_a, data);
347
- }
348
- catch (error) {
349
- // If JSON parsing fails, pass the raw string
350
- (_d = (_c = this.eventHandlers).message) === null || _d === void 0 ? void 0 : _d.call(_c, event.data);
351
- }
352
- }
353
- else {
354
- // Binary data - pass through as-is
355
- (_f = (_e = this.eventHandlers).message) === null || _f === void 0 ? void 0 : _f.call(_e, event.data);
356
- }
357
- };
358
- // Remove the original handler and add our binary-aware one
359
- // The original handler was added in super() constructor
360
- // We need to replace it
361
- const socketAny = this.socket;
362
- if ((_a = socketAny._listeners) === null || _a === void 0 ? void 0 : _a.message) {
363
- // Remove all message listeners
364
- socketAny._listeners.message.forEach((listener) => {
365
- this.socket.removeEventListener("message", listener);
366
- });
367
- }
368
- // Add our binary-aware handler
369
- if (this.binaryAwareHandler) {
370
- this.socket.addEventListener("message", this.binaryAwareHandler);
371
- }
462
+ this.binaryAwareHandler = setupBinaryHandling(this.socket, this.eventHandlers);
372
463
  }
373
464
  connect() {
374
- // Ensure socket is ready to connect - if _connectLock is stuck, force reconnect
375
- // by closing and reconnecting
376
- if (this.socket.readyState === this.socket.CLOSED) {
377
- // Force a fresh reconnect to ensure _connectLock is reset
378
- this.socket._connectLock = false;
379
- this.socket._shouldReconnect = true;
380
- }
381
- // Call parent connect, but then ensure our binary handler is still active
465
+ resetSocketConnectionState(this.socket);
382
466
  super.connect();
383
467
  // Re-setup binary handling in case connect() re-registered handlers
384
468
  this.setupBinaryHandling();
@@ -387,11 +471,15 @@ class WrappedAgentV1Socket extends Socket_js_1.V1Socket {
387
471
  }
388
472
  /**
389
473
  * Wrapper for Listen V1Client that overrides connect to use custom websocket.
474
+ *
475
+ * This wrapper ensures that the connect() method uses our custom ReconnectingWebSocket
476
+ * implementation instead of any auto-generated WebSocket handling. This guarantees
477
+ * consistent behavior across Fern regenerations and allows us to customize
478
+ * connection setup, authentication, and header handling.
390
479
  */
391
480
  class WrappedListenV1Client extends Client_js_5.V1Client {
392
481
  connect(args) {
393
482
  return __awaiter(this, void 0, void 0, function* () {
394
- var _a, _b, _c, _d;
395
483
  // Extract all the args (same as the original implementation)
396
484
  const { callback, callback_method: callbackMethod, channels, diarize, dictation, encoding, endpointing, extra, interim_results: interimResults, keyterm, keywords, language, mip_opt_out: mipOptOut, model, multichannel, numerals, profanity_filter: profanityFilter, punctuate, redact, replace, sample_rate: sampleRate, search, smart_format: smartFormat, tag, utterance_end_ms: utteranceEndMs, vad_events: vadEvents, version, headers, debug, reconnectAttempts, } = args;
397
485
  // Build query params (same as original)
@@ -449,27 +537,15 @@ class WrappedListenV1Client extends Client_js_5.V1Client {
449
537
  _queryParams.vad_events = vadEvents;
450
538
  if (version != null)
451
539
  _queryParams.version = version;
452
- // Get Authorization from authProvider (matching the working version)
453
- const authRequest = yield this._options.authProvider.getAuthRequest();
454
- // Merge headers from options (which includes session ID), auth headers, and request headers
455
- const mergedHeaders = (0, headers_js_1.mergeHeaders)((_a = this._options.headers) !== null && _a !== void 0 ? _a : {}, authRequest.headers, headers);
456
- // Resolve any Suppliers in headers to actual values
457
- const _headers = yield resolveHeaders(mergedHeaders);
458
- // Get WebSocket options with proper header handling
459
- const wsOptions = getWebSocketOptions(_headers);
460
- // Explicitly use the custom ReconnectingWebSocket from ws.ts
461
- const socket = new ws_js_1.ReconnectingWebSocket({
462
- url: core.url.join((_b = (yield core.Supplier.get(this._options.baseUrl))) !== null && _b !== void 0 ? _b : ((_c = (yield core.Supplier.get(this._options.environment))) !== null && _c !== void 0 ? _c : environments.DeepgramEnvironment.Production).production, "/v1/listen"),
463
- protocols: (_d = wsOptions.protocols) !== null && _d !== void 0 ? _d : [],
464
- queryParameters: _queryParams,
465
- headers: wsOptions.headers,
466
- options: {
467
- WebSocket: wsOptions.WebSocket,
468
- debug: debug !== null && debug !== void 0 ? debug : false,
469
- maxRetries: reconnectAttempts !== null && reconnectAttempts !== void 0 ? reconnectAttempts : 30,
470
- startClosed: true,
471
- connectionTimeout: 10000, // Increase timeout to 10 seconds
472
- },
540
+ // Use shared connection helper
541
+ const socket = yield createWebSocketConnection({
542
+ options: this._options,
543
+ urlPath: "/v1/listen",
544
+ environmentKey: 'production',
545
+ queryParams: _queryParams,
546
+ headers,
547
+ debug,
548
+ reconnectAttempts,
473
549
  });
474
550
  return new WrappedListenV1Socket({ socket });
475
551
  });
@@ -477,6 +553,11 @@ class WrappedListenV1Client extends Client_js_5.V1Client {
477
553
  }
478
554
  /**
479
555
  * Wrapper for Listen V1Socket that handles binary messages correctly.
556
+ *
557
+ * This wrapper ensures that both text (JSON) and binary WebSocket messages are
558
+ * handled properly. The auto-generated socket class may not handle binary data
559
+ * correctly, so we override the message handling to support both formats.
560
+ * This is critical for audio and other binary data streaming.
480
561
  */
481
562
  class WrappedListenV1Socket extends Socket_js_2.V1Socket {
482
563
  constructor(args) {
@@ -484,44 +565,10 @@ class WrappedListenV1Socket extends Socket_js_2.V1Socket {
484
565
  this.setupBinaryHandling();
485
566
  }
486
567
  setupBinaryHandling() {
487
- var _a;
488
- // Create a binary-aware message handler
489
- this.binaryAwareHandler = (event) => {
490
- var _a, _b, _c, _d, _e, _f;
491
- // Handle both text (JSON) and binary messages
492
- if (typeof event.data === "string") {
493
- try {
494
- const data = (0, json_js_1.fromJson)(event.data);
495
- (_b = (_a = this.eventHandlers).message) === null || _b === void 0 ? void 0 : _b.call(_a, data);
496
- }
497
- catch (error) {
498
- // If JSON parsing fails, pass the raw string
499
- (_d = (_c = this.eventHandlers).message) === null || _d === void 0 ? void 0 : _d.call(_c, event.data);
500
- }
501
- }
502
- else {
503
- // Binary data - pass through as-is
504
- (_f = (_e = this.eventHandlers).message) === null || _f === void 0 ? void 0 : _f.call(_e, event.data);
505
- }
506
- };
507
- // Remove the original handler and add our binary-aware one
508
- const socketAny = this.socket;
509
- if ((_a = socketAny._listeners) === null || _a === void 0 ? void 0 : _a.message) {
510
- socketAny._listeners.message.forEach((listener) => {
511
- this.socket.removeEventListener("message", listener);
512
- });
513
- }
514
- if (this.binaryAwareHandler) {
515
- this.socket.addEventListener("message", this.binaryAwareHandler);
516
- }
568
+ this.binaryAwareHandler = setupBinaryHandling(this.socket, this.eventHandlers);
517
569
  }
518
570
  connect() {
519
- // Ensure socket is ready to connect - if _connectLock is stuck, force reconnect
520
- if (this.socket.readyState === this.socket.CLOSED) {
521
- // Force a fresh reconnect to ensure _connectLock is reset
522
- this.socket._connectLock = false;
523
- this.socket._shouldReconnect = true;
524
- }
571
+ resetSocketConnectionState(this.socket);
525
572
  super.connect();
526
573
  this.setupBinaryHandling();
527
574
  return this;
@@ -529,11 +576,15 @@ class WrappedListenV1Socket extends Socket_js_2.V1Socket {
529
576
  }
530
577
  /**
531
578
  * Wrapper for Listen V2Client that overrides connect to use custom websocket.
579
+ *
580
+ * This wrapper ensures that the connect() method uses our custom ReconnectingWebSocket
581
+ * implementation instead of any auto-generated WebSocket handling. This guarantees
582
+ * consistent behavior across Fern regenerations and allows us to customize
583
+ * connection setup, authentication, and header handling.
532
584
  */
533
585
  class WrappedListenV2Client extends Client_js_6.V2Client {
534
586
  connect(args) {
535
587
  return __awaiter(this, void 0, void 0, function* () {
536
- var _a, _b, _c, _d, _e, _f;
537
588
  const { model, encoding, sample_rate: sampleRate, eager_eot_threshold: eagerEotThreshold, eot_threshold: eotThreshold, eot_timeout_ms: eotTimeoutMs, keyterm, mip_opt_out: mipOptOut, tag, headers, debug, reconnectAttempts, } = args;
538
589
  const _queryParams = {};
539
590
  _queryParams.model = model;
@@ -553,34 +604,28 @@ class WrappedListenV2Client extends Client_js_6.V2Client {
553
604
  _queryParams.mip_opt_out = mipOptOut;
554
605
  if (tag != null)
555
606
  _queryParams.tag = tag;
556
- // Get Authorization from authProvider (matching the working version)
557
- const authRequest = yield ((_a = this._options.authProvider) === null || _a === void 0 ? void 0 : _a.getAuthRequest());
558
- // Merge headers from options (which includes session ID), auth headers, and request headers
559
- const mergedHeaders = (0, headers_js_1.mergeHeaders)((_b = this._options.headers) !== null && _b !== void 0 ? _b : {}, (_c = authRequest === null || authRequest === void 0 ? void 0 : authRequest.headers) !== null && _c !== void 0 ? _c : {}, headers);
560
- // Resolve any Suppliers in headers to actual values
561
- const _headers = yield resolveHeaders(mergedHeaders);
562
- // Get WebSocket options with proper header handling
563
- const wsOptions = getWebSocketOptions(_headers);
564
- // Explicitly use the custom ReconnectingWebSocket from ws.ts
565
- const socket = new ws_js_1.ReconnectingWebSocket({
566
- url: core.url.join((_d = (yield core.Supplier.get(this._options.baseUrl))) !== null && _d !== void 0 ? _d : ((_e = (yield core.Supplier.get(this._options.environment))) !== null && _e !== void 0 ? _e : environments.DeepgramEnvironment.Production).production, "/v2/listen"),
567
- protocols: (_f = wsOptions.protocols) !== null && _f !== void 0 ? _f : [],
568
- queryParameters: _queryParams,
569
- headers: wsOptions.headers,
570
- options: {
571
- WebSocket: wsOptions.WebSocket,
572
- debug: debug !== null && debug !== void 0 ? debug : false,
573
- maxRetries: reconnectAttempts !== null && reconnectAttempts !== void 0 ? reconnectAttempts : 30,
574
- startClosed: true,
575
- connectionTimeout: 10000, // Increase timeout to 10 seconds
576
- },
607
+ // Use shared connection helper
608
+ const socket = yield createWebSocketConnection({
609
+ options: this._options,
610
+ urlPath: "/v2/listen",
611
+ environmentKey: 'production',
612
+ queryParams: _queryParams,
613
+ headers,
614
+ debug,
615
+ reconnectAttempts,
577
616
  });
578
617
  return new WrappedListenV2Socket({ socket });
579
618
  });
580
619
  }
581
620
  }
582
621
  /**
583
- * Wrapper for Listen V2Socket that handles binary messages correctly.
622
+ * Wrapper for Listen V2Socket that handles binary messages correctly and adds ping support.
623
+ *
624
+ * This wrapper ensures that both text (JSON) and binary WebSocket messages are
625
+ * handled properly. The auto-generated socket class may not handle binary data
626
+ * correctly, so we override the message handling to support both formats.
627
+ * Additionally, this wrapper adds a ping() method for sending WebSocket ping
628
+ * frames to keep connections alive (Node.js only).
584
629
  */
585
630
  class WrappedListenV2Socket extends Socket_js_3.V2Socket {
586
631
  constructor(args) {
@@ -588,56 +633,56 @@ class WrappedListenV2Socket extends Socket_js_3.V2Socket {
588
633
  this.setupBinaryHandling();
589
634
  }
590
635
  setupBinaryHandling() {
591
- var _a;
592
- // Create a binary-aware message handler
593
- this.binaryAwareHandler = (event) => {
594
- var _a, _b, _c, _d, _e, _f;
595
- // Handle both text (JSON) and binary messages
596
- if (typeof event.data === "string") {
597
- try {
598
- const data = (0, json_js_1.fromJson)(event.data);
599
- (_b = (_a = this.eventHandlers).message) === null || _b === void 0 ? void 0 : _b.call(_a, data);
600
- }
601
- catch (error) {
602
- // If JSON parsing fails, pass the raw string
603
- (_d = (_c = this.eventHandlers).message) === null || _d === void 0 ? void 0 : _d.call(_c, event.data);
604
- }
605
- }
606
- else {
607
- // Binary data - pass through as-is
608
- (_f = (_e = this.eventHandlers).message) === null || _f === void 0 ? void 0 : _f.call(_e, event.data);
609
- }
610
- };
611
- // Remove the original handler and add our binary-aware one
612
- const socketAny = this.socket;
613
- if ((_a = socketAny._listeners) === null || _a === void 0 ? void 0 : _a.message) {
614
- socketAny._listeners.message.forEach((listener) => {
615
- this.socket.removeEventListener("message", listener);
616
- });
617
- }
618
- if (this.binaryAwareHandler) {
619
- this.socket.addEventListener("message", this.binaryAwareHandler);
620
- }
636
+ this.binaryAwareHandler = setupBinaryHandling(this.socket, this.eventHandlers);
621
637
  }
622
638
  connect() {
623
- // Ensure socket is ready to connect - if _connectLock is stuck, force reconnect
624
- if (this.socket.readyState === this.socket.CLOSED) {
625
- // Force a fresh reconnect to ensure _connectLock is reset
626
- this.socket._connectLock = false;
627
- this.socket._shouldReconnect = true;
628
- }
639
+ resetSocketConnectionState(this.socket);
629
640
  super.connect();
630
641
  this.setupBinaryHandling();
631
642
  return this;
632
643
  }
644
+ /**
645
+ * Send a WebSocket ping frame to keep the connection alive.
646
+ *
647
+ * In Node.js, this uses the native WebSocket ping() method from the 'ws' library.
648
+ * In browsers, WebSocket ping/pong is handled automatically by the browser and
649
+ * cannot be manually triggered, so this method will throw an error.
650
+ *
651
+ * @param data Optional data to send with the ping (Node.js only)
652
+ * @throws Error if not in Node.js environment or WebSocket is not connected
653
+ */
654
+ ping(data) {
655
+ const ws = this.socket._ws;
656
+ if (!ws) {
657
+ throw new Error("WebSocket is not connected. Call connect() and waitForOpen() first.");
658
+ }
659
+ if (ws.readyState !== ws.OPEN) {
660
+ throw new Error("WebSocket is not in OPEN state.");
661
+ }
662
+ // Check if we're in Node.js and the WebSocket has a ping method (from 'ws' library)
663
+ if (index_js_1.RUNTIME.type === "node" && typeof ws.ping === "function") {
664
+ // Call the native ping method from the 'ws' library
665
+ ws.ping(data);
666
+ }
667
+ else {
668
+ // In browsers, WebSocket ping/pong is automatic and not exposed to JavaScript
669
+ throw new Error("WebSocket ping is not supported in browser environments. " +
670
+ "Browser WebSocket connections handle ping/pong automatically. " +
671
+ "If you need keepalive in the browser, consider sending periodic audio data or using a timer.");
672
+ }
673
+ }
633
674
  }
634
675
  /**
635
676
  * Wrapper for Speak V1Client that overrides connect to use custom websocket.
677
+ *
678
+ * This wrapper ensures that the connect() method uses our custom ReconnectingWebSocket
679
+ * implementation instead of any auto-generated WebSocket handling. This guarantees
680
+ * consistent behavior across Fern regenerations and allows us to customize
681
+ * connection setup, authentication, and header handling.
636
682
  */
637
683
  class WrappedSpeakV1Client extends Client_js_7.V1Client {
638
684
  connect(args) {
639
685
  return __awaiter(this, void 0, void 0, function* () {
640
- var _a, _b, _c, _d;
641
686
  const { encoding, mip_opt_out: mipOptOut, model, sample_rate: sampleRate, headers, debug, reconnectAttempts, } = args;
642
687
  const _queryParams = {};
643
688
  if (encoding != null)
@@ -648,27 +693,15 @@ class WrappedSpeakV1Client extends Client_js_7.V1Client {
648
693
  _queryParams.model = model;
649
694
  if (sampleRate != null)
650
695
  _queryParams.sample_rate = sampleRate;
651
- // Get Authorization from authProvider (matching the working version)
652
- const authRequest = yield this._options.authProvider.getAuthRequest();
653
- // Merge headers from options (which includes session ID), auth headers, and request headers
654
- const mergedHeaders = (0, headers_js_1.mergeHeaders)((_a = this._options.headers) !== null && _a !== void 0 ? _a : {}, authRequest.headers, headers);
655
- // Resolve any Suppliers in headers to actual values
656
- const _headers = yield resolveHeaders(mergedHeaders);
657
- // Get WebSocket options with proper header handling
658
- const wsOptions = getWebSocketOptions(_headers);
659
- // Explicitly use the custom ReconnectingWebSocket from ws.ts
660
- const socket = new ws_js_1.ReconnectingWebSocket({
661
- url: core.url.join((_b = (yield core.Supplier.get(this._options.baseUrl))) !== null && _b !== void 0 ? _b : ((_c = (yield core.Supplier.get(this._options.environment))) !== null && _c !== void 0 ? _c : environments.DeepgramEnvironment.Production).production, "/v1/speak"),
662
- protocols: (_d = wsOptions.protocols) !== null && _d !== void 0 ? _d : [],
663
- queryParameters: _queryParams,
664
- headers: wsOptions.headers,
665
- options: {
666
- WebSocket: wsOptions.WebSocket,
667
- debug: debug !== null && debug !== void 0 ? debug : false,
668
- maxRetries: reconnectAttempts !== null && reconnectAttempts !== void 0 ? reconnectAttempts : 30,
669
- startClosed: true,
670
- connectionTimeout: 10000, // Increase timeout to 10 seconds
671
- },
696
+ // Use shared connection helper
697
+ const socket = yield createWebSocketConnection({
698
+ options: this._options,
699
+ urlPath: "/v1/speak",
700
+ environmentKey: 'production',
701
+ queryParams: _queryParams,
702
+ headers,
703
+ debug,
704
+ reconnectAttempts,
672
705
  });
673
706
  return new WrappedSpeakV1Socket({ socket });
674
707
  });
@@ -676,6 +709,11 @@ class WrappedSpeakV1Client extends Client_js_7.V1Client {
676
709
  }
677
710
  /**
678
711
  * Wrapper for Speak V1Socket that handles binary messages correctly.
712
+ *
713
+ * This wrapper ensures that both text (JSON) and binary WebSocket messages are
714
+ * handled properly. The auto-generated socket class may not handle binary data
715
+ * correctly, so we override the message handling to support both formats.
716
+ * This is critical for audio and other binary data streaming.
679
717
  */
680
718
  class WrappedSpeakV1Socket extends Socket_js_4.V1Socket {
681
719
  constructor(args) {
@@ -683,44 +721,10 @@ class WrappedSpeakV1Socket extends Socket_js_4.V1Socket {
683
721
  this.setupBinaryHandling();
684
722
  }
685
723
  setupBinaryHandling() {
686
- var _a;
687
- // Create a binary-aware message handler
688
- this.binaryAwareHandler = (event) => {
689
- var _a, _b, _c, _d, _e, _f;
690
- // Handle both text (JSON) and binary messages
691
- if (typeof event.data === "string") {
692
- try {
693
- const data = (0, json_js_1.fromJson)(event.data);
694
- (_b = (_a = this.eventHandlers).message) === null || _b === void 0 ? void 0 : _b.call(_a, data);
695
- }
696
- catch (error) {
697
- // If JSON parsing fails, pass the raw string
698
- (_d = (_c = this.eventHandlers).message) === null || _d === void 0 ? void 0 : _d.call(_c, event.data);
699
- }
700
- }
701
- else {
702
- // Binary data - pass through as-is
703
- (_f = (_e = this.eventHandlers).message) === null || _f === void 0 ? void 0 : _f.call(_e, event.data);
704
- }
705
- };
706
- // Remove the original handler and add our binary-aware one
707
- const socketAny = this.socket;
708
- if ((_a = socketAny._listeners) === null || _a === void 0 ? void 0 : _a.message) {
709
- socketAny._listeners.message.forEach((listener) => {
710
- this.socket.removeEventListener("message", listener);
711
- });
712
- }
713
- if (this.binaryAwareHandler) {
714
- this.socket.addEventListener("message", this.binaryAwareHandler);
715
- }
724
+ this.binaryAwareHandler = setupBinaryHandling(this.socket, this.eventHandlers);
716
725
  }
717
726
  connect() {
718
- // Ensure socket is ready to connect - if _connectLock is stuck, force reconnect
719
- if (this.socket.readyState === this.socket.CLOSED) {
720
- // Force a fresh reconnect to ensure _connectLock is reset
721
- this.socket._connectLock = false;
722
- this.socket._shouldReconnect = true;
723
- }
727
+ resetSocketConnectionState(this.socket);
724
728
  super.connect();
725
729
  this.setupBinaryHandling();
726
730
  return this;