@cartesia/cartesia-js 1.0.0 → 1.0.2

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 (62) hide show
  1. package/.turbo/turbo-build.log +50 -50
  2. package/CHANGELOG.md +12 -0
  3. package/LICENSE.md +21 -0
  4. package/README.md +92 -19
  5. package/dist/{chunk-PQ6CIPFW.js → chunk-6YQ6KDIQ.js} +44 -5
  6. package/dist/{chunk-RO7TY474.js → chunk-BHY7MNGT.js} +11 -6
  7. package/dist/{chunk-F4QWVJY3.js → chunk-EDAAHENY.js} +2 -2
  8. package/dist/{chunk-WIFMLPT5.js → chunk-GHY2WEOK.js} +13 -0
  9. package/dist/{chunk-FN7BK4PS.js → chunk-IZBPLCGW.js} +97 -75
  10. package/dist/{chunk-JYLAM6VU.js → chunk-LZO6K34D.js} +2 -2
  11. package/dist/{chunk-3FL2SNIR.js → chunk-NQVZNVOU.js} +1 -1
  12. package/dist/{chunk-IEN4NCER.js → chunk-NVOCUUOF.js} +3 -3
  13. package/dist/chunk-PISCPZK4.js +40 -0
  14. package/dist/{chunk-SGXUEFII.js → chunk-UCYL2SOX.js} +18 -15
  15. package/dist/index.cjs +186 -103
  16. package/dist/index.d.cts +4 -4
  17. package/dist/index.d.ts +4 -4
  18. package/dist/index.js +15 -9
  19. package/dist/lib/client.cjs +35 -10
  20. package/dist/lib/client.d.cts +2 -2
  21. package/dist/lib/client.d.ts +2 -2
  22. package/dist/lib/client.js +2 -2
  23. package/dist/lib/constants.js +1 -1
  24. package/dist/lib/index.cjs +181 -102
  25. package/dist/lib/index.js +8 -8
  26. package/dist/react/index.cjs +286 -158
  27. package/dist/react/index.d.cts +5 -4
  28. package/dist/react/index.d.ts +5 -4
  29. package/dist/react/index.js +115 -66
  30. package/dist/react/utils.js +2 -2
  31. package/dist/tts/index.cjs +165 -89
  32. package/dist/tts/index.js +6 -6
  33. package/dist/tts/player.cjs +5 -0
  34. package/dist/tts/player.js +4 -3
  35. package/dist/tts/source.cjs +50 -4
  36. package/dist/tts/source.d.cts +16 -6
  37. package/dist/tts/source.d.ts +16 -6
  38. package/dist/tts/source.js +4 -2
  39. package/dist/tts/utils.cjs +18 -6
  40. package/dist/tts/utils.d.cts +7 -5
  41. package/dist/tts/utils.d.ts +7 -5
  42. package/dist/tts/utils.js +3 -2
  43. package/dist/tts/websocket.cjs +165 -89
  44. package/dist/tts/websocket.d.cts +12 -8
  45. package/dist/tts/websocket.d.ts +12 -8
  46. package/dist/tts/websocket.js +5 -5
  47. package/dist/types/index.d.cts +65 -5
  48. package/dist/types/index.d.ts +65 -5
  49. package/dist/voices/index.cjs +31 -23
  50. package/dist/voices/index.d.cts +2 -1
  51. package/dist/voices/index.d.ts +2 -1
  52. package/dist/voices/index.js +3 -3
  53. package/package.json +1 -1
  54. package/src/index.ts +2 -0
  55. package/src/lib/client.ts +10 -10
  56. package/src/react/index.ts +115 -64
  57. package/src/tts/source.ts +53 -7
  58. package/src/tts/utils.ts +26 -12
  59. package/src/tts/websocket.ts +42 -23
  60. package/src/types/index.ts +89 -4
  61. package/src/voices/index.ts +22 -15
  62. package/dist/chunk-PQ5EVEEH.js +0 -34
@@ -1,7 +1,9 @@
1
1
  import {
2
+ ENCODING_MAP,
2
3
  Source
3
- } from "../chunk-PQ6CIPFW.js";
4
- import "../chunk-WIFMLPT5.js";
4
+ } from "../chunk-6YQ6KDIQ.js";
5
+ import "../chunk-GHY2WEOK.js";
5
6
  export {
7
+ ENCODING_MAP,
6
8
  Source as default
7
9
  };
@@ -41,16 +41,28 @@ __export(utils_exports, {
41
41
  });
42
42
  module.exports = __toCommonJS(utils_exports);
43
43
  var import_base64_js = __toESM(require("base64-js"), 1);
44
- function base64ToArray(b64) {
44
+
45
+ // src/tts/source.ts
46
+ var import_emittery = __toESM(require("emittery"), 1);
47
+ var ENCODING_MAP = {
48
+ pcm_f32le: { arrayType: Float32Array, bytesPerElement: 4 },
49
+ pcm_s16le: { arrayType: Int16Array, bytesPerElement: 2 },
50
+ pcm_alaw: { arrayType: Uint8Array, bytesPerElement: 1 },
51
+ pcm_mulaw: { arrayType: Uint8Array, bytesPerElement: 1 }
52
+ };
53
+
54
+ // src/tts/utils.ts
55
+ function base64ToArray(b64, encoding) {
45
56
  const byteArrays = filterSentinel(b64).map((b) => import_base64_js.default.toByteArray(b));
57
+ const { arrayType: ArrayType, bytesPerElement } = ENCODING_MAP[encoding];
46
58
  const totalLength = byteArrays.reduce(
47
- (acc, arr) => acc + arr.length / Float32Array.BYTES_PER_ELEMENT,
59
+ (acc, arr) => acc + arr.length / bytesPerElement,
48
60
  0
49
61
  );
50
- const result = new Float32Array(totalLength);
62
+ const result = new ArrayType(totalLength);
51
63
  let offset = 0;
52
64
  for (const arr of byteArrays) {
53
- const floats = new Float32Array(arr.buffer);
65
+ const floats = new ArrayType(arr.buffer);
54
66
  result.set(floats, offset);
55
67
  offset += floats.length;
56
68
  }
@@ -81,10 +93,10 @@ function createMessageHandlerForContextId(contextId, handler) {
81
93
  let chunk;
82
94
  if (message.done) {
83
95
  chunk = getSentinel();
84
- } else {
96
+ } else if (message.type === "chunk") {
85
97
  chunk = message.data;
86
98
  }
87
- handler({ chunk, message: event.data });
99
+ handler({ chunk, message: event.data, data: message });
88
100
  };
89
101
  }
90
102
  function getSentinel() {
@@ -1,14 +1,15 @@
1
1
  import emittery__default from 'emittery';
2
- import { Chunk, Sentinel, EmitteryCallbacks } from '../types/index.cjs';
2
+ import { Chunk, TypedArray, WebSocketResponse, Sentinel, EmitteryCallbacks } from '../types/index.cjs';
3
3
 
4
4
  /**
5
- * Convert base64-encoded audio buffer(s) to a Float32Array.
5
+ * Convert base64-encoded audio buffer(s) to a TypedArray.
6
6
  *
7
7
  * @param b64 The base64-encoded audio buffer, or an array of base64-encoded
8
8
  * audio buffers.
9
- * @returns The audio buffer(s) as a Float32Array.
9
+ * @param encoding The encoding of the audio buffer(s).
10
+ * @returns The audio buffer(s) as a TypedArray.
10
11
  */
11
- declare function base64ToArray(b64: Chunk[]): Float32Array;
12
+ declare function base64ToArray(b64: Chunk[], encoding: string): TypedArray;
12
13
  /**
13
14
  * Schedule an audio buffer to play at a given time in the passed context.
14
15
  *
@@ -28,8 +29,9 @@ declare function playAudioBuffer(floats: Float32Array, context: AudioContext, st
28
29
  * @returns A message event handler.
29
30
  */
30
31
  declare function createMessageHandlerForContextId(contextId: string, handler: ({ chunk, message, }: {
31
- chunk: Chunk;
32
+ chunk?: Chunk;
32
33
  message: string;
34
+ data: WebSocketResponse;
33
35
  }) => void): (event: MessageEvent) => void;
34
36
  /**
35
37
  * Get a sentinel value that indicates the end of a stream.
@@ -1,14 +1,15 @@
1
1
  import emittery__default from 'emittery';
2
- import { Chunk, Sentinel, EmitteryCallbacks } from '../types/index.js';
2
+ import { Chunk, TypedArray, WebSocketResponse, Sentinel, EmitteryCallbacks } from '../types/index.js';
3
3
 
4
4
  /**
5
- * Convert base64-encoded audio buffer(s) to a Float32Array.
5
+ * Convert base64-encoded audio buffer(s) to a TypedArray.
6
6
  *
7
7
  * @param b64 The base64-encoded audio buffer, or an array of base64-encoded
8
8
  * audio buffers.
9
- * @returns The audio buffer(s) as a Float32Array.
9
+ * @param encoding The encoding of the audio buffer(s).
10
+ * @returns The audio buffer(s) as a TypedArray.
10
11
  */
11
- declare function base64ToArray(b64: Chunk[]): Float32Array;
12
+ declare function base64ToArray(b64: Chunk[], encoding: string): TypedArray;
12
13
  /**
13
14
  * Schedule an audio buffer to play at a given time in the passed context.
14
15
  *
@@ -28,8 +29,9 @@ declare function playAudioBuffer(floats: Float32Array, context: AudioContext, st
28
29
  * @returns A message event handler.
29
30
  */
30
31
  declare function createMessageHandlerForContextId(contextId: string, handler: ({ chunk, message, }: {
31
- chunk: Chunk;
32
+ chunk?: Chunk;
32
33
  message: string;
34
+ data: WebSocketResponse;
33
35
  }) => void): (event: MessageEvent) => void;
34
36
  /**
35
37
  * Get a sentinel value that indicates the end of a stream.
package/dist/tts/utils.js CHANGED
@@ -7,8 +7,9 @@ import {
7
7
  isComplete,
8
8
  isSentinel,
9
9
  playAudioBuffer
10
- } from "../chunk-RO7TY474.js";
11
- import "../chunk-WIFMLPT5.js";
10
+ } from "../chunk-BHY7MNGT.js";
11
+ import "../chunk-6YQ6KDIQ.js";
12
+ import "../chunk-GHY2WEOK.js";
12
13
  export {
13
14
  base64ToArray,
14
15
  createMessageHandlerForContextId,
@@ -22,6 +22,18 @@ var __spreadValues = (a, b) => {
22
22
  return a;
23
23
  };
24
24
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
+ var __objRest = (source, exclude) => {
26
+ var target = {};
27
+ for (var prop in source)
28
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
29
+ target[prop] = source[prop];
30
+ if (source != null && __getOwnPropSymbols)
31
+ for (var prop of __getOwnPropSymbols(source)) {
32
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
33
+ target[prop] = source[prop];
34
+ }
35
+ return target;
36
+ };
25
37
  var __export = (target, all) => {
26
38
  for (var name in all)
27
39
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -113,26 +125,37 @@ var constructApiUrl = (baseUrl, path, { websocket = false } = {}) => {
113
125
  // src/lib/client.ts
114
126
  var Client = class {
115
127
  constructor(options = {}) {
116
- if (!(options.apiKey || process.env.CARTESIA_API_KEY)) {
128
+ const apiKey = options.apiKey || process.env.CARTESIA_API_KEY;
129
+ if (!apiKey) {
117
130
  throw new Error("Missing Cartesia API key.");
118
131
  }
119
- this.apiKey = options.apiKey || process.env.CARTESIA_API_KEY;
132
+ this.apiKey = typeof apiKey === "function" ? apiKey : () => __async(this, null, function* () {
133
+ return apiKey;
134
+ });
120
135
  this.baseUrl = options.baseUrl || BASE_URL;
121
136
  }
122
- fetch(path, options = {}) {
123
- const url = constructApiUrl(this.baseUrl, path);
124
- return (0, import_cross_fetch.default)(url.toString(), __spreadProps(__spreadValues({}, options), {
125
- headers: __spreadValues({
126
- "X-API-Key": this.apiKey,
127
- "Cartesia-Version": CARTESIA_VERSION
128
- }, options.headers)
129
- }));
137
+ _fetch(_0) {
138
+ return __async(this, arguments, function* (path, options = {}) {
139
+ const url = constructApiUrl(this.baseUrl, path);
140
+ const headers = new Headers(options.headers);
141
+ headers.set("X-API-Key", yield this.apiKey());
142
+ headers.set("Cartesia-Version", CARTESIA_VERSION);
143
+ return (0, import_cross_fetch.default)(url.toString(), __spreadProps(__spreadValues({}, options), {
144
+ headers
145
+ }));
146
+ });
130
147
  }
131
148
  };
132
149
 
133
150
  // src/tts/source.ts
134
151
  var import_emittery = __toESM(require("emittery"), 1);
135
- var _emitter, _buffer, _readIndex, _writeIndex, _closed, _sampleRate;
152
+ var ENCODING_MAP = {
153
+ pcm_f32le: { arrayType: Float32Array, bytesPerElement: 4 },
154
+ pcm_s16le: { arrayType: Int16Array, bytesPerElement: 2 },
155
+ pcm_alaw: { arrayType: Uint8Array, bytesPerElement: 1 },
156
+ pcm_mulaw: { arrayType: Uint8Array, bytesPerElement: 1 }
157
+ };
158
+ var _emitter, _buffer, _readIndex, _writeIndex, _closed, _sampleRate, _encoding, _container, _createBuffer, createBuffer_fn;
136
159
  var Source = class {
137
160
  /**
138
161
  * Create a new Source.
@@ -140,23 +163,44 @@ var Source = class {
140
163
  * @param options - Options for the Source.
141
164
  * @param options.sampleRate - The sample rate of the audio.
142
165
  */
143
- constructor({ sampleRate }) {
166
+ constructor({
167
+ sampleRate,
168
+ encoding,
169
+ container
170
+ }) {
171
+ /**
172
+ * Create a new buffer for the source.
173
+ *
174
+ * @param size - The size of the buffer to create.
175
+ * @returns The new buffer as a TypedArray based on the encoding.
176
+ */
177
+ __privateAdd(this, _createBuffer);
144
178
  __privateAdd(this, _emitter, new import_emittery.default());
145
179
  __privateAdd(this, _buffer, void 0);
146
180
  __privateAdd(this, _readIndex, 0);
147
181
  __privateAdd(this, _writeIndex, 0);
148
182
  __privateAdd(this, _closed, false);
149
183
  __privateAdd(this, _sampleRate, void 0);
184
+ __privateAdd(this, _encoding, void 0);
185
+ __privateAdd(this, _container, void 0);
150
186
  this.on = __privateGet(this, _emitter).on.bind(__privateGet(this, _emitter));
151
187
  this.once = __privateGet(this, _emitter).once.bind(__privateGet(this, _emitter));
152
188
  this.events = __privateGet(this, _emitter).events.bind(__privateGet(this, _emitter));
153
189
  this.off = __privateGet(this, _emitter).off.bind(__privateGet(this, _emitter));
154
190
  __privateSet(this, _sampleRate, sampleRate);
155
- __privateSet(this, _buffer, new Float32Array(1024));
191
+ __privateSet(this, _encoding, encoding);
192
+ __privateSet(this, _container, container);
193
+ __privateSet(this, _buffer, __privateMethod(this, _createBuffer, createBuffer_fn).call(this, 1024));
156
194
  }
157
195
  get sampleRate() {
158
196
  return __privateGet(this, _sampleRate);
159
197
  }
198
+ get encoding() {
199
+ return __privateGet(this, _encoding);
200
+ }
201
+ get container() {
202
+ return __privateGet(this, _container);
203
+ }
160
204
  /**
161
205
  * Append audio to the buffer.
162
206
  *
@@ -170,7 +214,7 @@ var Source = class {
170
214
  while (newCapacity < requiredCapacity) {
171
215
  newCapacity *= 2;
172
216
  }
173
- const newBuffer = new Float32Array(newCapacity);
217
+ const newBuffer = __privateMethod(this, _createBuffer, createBuffer_fn).call(this, newCapacity);
174
218
  newBuffer.set(__privateGet(this, _buffer));
175
219
  __privateSet(this, _buffer, newBuffer);
176
220
  }
@@ -218,6 +262,9 @@ var Source = class {
218
262
  get readIndex() {
219
263
  return __privateGet(this, _readIndex);
220
264
  }
265
+ get writeIndex() {
266
+ return __privateGet(this, _writeIndex);
267
+ }
221
268
  /**
222
269
  * Close the source. This signals that no more audio will be enqueued.
223
270
  *
@@ -239,19 +286,27 @@ _readIndex = new WeakMap();
239
286
  _writeIndex = new WeakMap();
240
287
  _closed = new WeakMap();
241
288
  _sampleRate = new WeakMap();
289
+ _encoding = new WeakMap();
290
+ _container = new WeakMap();
291
+ _createBuffer = new WeakSet();
292
+ createBuffer_fn = function(size) {
293
+ const { arrayType: ArrayType } = ENCODING_MAP[__privateGet(this, _encoding)];
294
+ return new ArrayType(size);
295
+ };
242
296
 
243
297
  // src/tts/utils.ts
244
298
  var import_base64_js = __toESM(require("base64-js"), 1);
245
- function base64ToArray(b64) {
299
+ function base64ToArray(b64, encoding) {
246
300
  const byteArrays = filterSentinel(b64).map((b) => import_base64_js.default.toByteArray(b));
301
+ const { arrayType: ArrayType, bytesPerElement } = ENCODING_MAP[encoding];
247
302
  const totalLength = byteArrays.reduce(
248
- (acc, arr) => acc + arr.length / Float32Array.BYTES_PER_ELEMENT,
303
+ (acc, arr) => acc + arr.length / bytesPerElement,
249
304
  0
250
305
  );
251
- const result = new Float32Array(totalLength);
306
+ const result = new ArrayType(totalLength);
252
307
  let offset = 0;
253
308
  for (const arr of byteArrays) {
254
- const floats = new Float32Array(arr.buffer);
309
+ const floats = new ArrayType(arr.buffer);
255
310
  result.set(floats, offset);
256
311
  offset += floats.length;
257
312
  }
@@ -269,10 +324,10 @@ function createMessageHandlerForContextId(contextId, handler) {
269
324
  let chunk;
270
325
  if (message.done) {
271
326
  chunk = getSentinel();
272
- } else {
327
+ } else if (message.type === "chunk") {
273
328
  chunk = message.data;
274
329
  }
275
- handler({ chunk, message: event.data });
330
+ handler({ chunk, message: event.data, data: message });
276
331
  };
277
332
  }
278
333
  function getSentinel() {
@@ -296,14 +351,14 @@ function getEmitteryCallbacks(emitter) {
296
351
  }
297
352
 
298
353
  // src/tts/websocket.ts
299
- var _isConnected, _sampleRate2, _generateId, generateId_fn;
354
+ var _isConnected, _sampleRate2, _container2, _encoding2, _generateId, generateId_fn;
300
355
  var WebSocket = class extends Client {
301
356
  /**
302
357
  * Create a new WebSocket client.
303
358
  *
304
359
  * @param args - Arguments to pass to the Client constructor.
305
360
  */
306
- constructor({ sampleRate }, ...args) {
361
+ constructor({ sampleRate, container, encoding }, ...args) {
307
362
  super(...args);
308
363
  /**
309
364
  * Generate a unique ID suitable for a streaming context.
@@ -316,12 +371,16 @@ var WebSocket = class extends Client {
316
371
  __privateAdd(this, _generateId);
317
372
  __privateAdd(this, _isConnected, false);
318
373
  __privateAdd(this, _sampleRate2, void 0);
374
+ __privateAdd(this, _container2, void 0);
375
+ __privateAdd(this, _encoding2, void 0);
319
376
  __privateSet(this, _sampleRate2, sampleRate);
377
+ __privateSet(this, _container2, container != null ? container : "raw");
378
+ __privateSet(this, _encoding2, encoding != null ? encoding : "pcm_f32le");
320
379
  }
321
380
  /**
322
381
  * Send a message over the WebSocket to start a stream.
323
382
  *
324
- * @param inputs - Stream options.
383
+ * @param inputs - Stream options. Defined in the StreamRequest type.
325
384
  * @param options - Options for the stream.
326
385
  * @param options.timeout - The maximum time to wait for a chunk before cancelling the stream.
327
386
  * If set to `0`, the stream will not time out.
@@ -329,26 +388,30 @@ var WebSocket = class extends Client {
329
388
  * @returns An Emittery instance that emits messages from the WebSocket.
330
389
  * @returns An abort function that can be called to cancel the stream.
331
390
  */
332
- send(inputs, { timeout = 0 } = {}) {
333
- var _a, _b, _c, _d;
391
+ send(_a, { timeout = 0 } = {}) {
392
+ var inputs = __objRest(_a, []);
393
+ var _a2, _b, _c, _d;
334
394
  if (!__privateGet(this, _isConnected)) {
335
395
  throw new Error("Not connected to WebSocket. Call .connect() first.");
336
396
  }
337
- const contextId = __privateMethod(this, _generateId, generateId_fn).call(this);
338
- (_a = this.socket) == null ? void 0 : _a.send(
339
- JSON.stringify(__spreadProps(__spreadValues({
340
- context_id: contextId
341
- }, inputs), {
342
- output_format: {
343
- container: "raw",
344
- encoding: "pcm_f32le",
345
- sample_rate: __privateGet(this, _sampleRate2)
346
- }
347
- }))
397
+ if (!inputs.context_id) {
398
+ inputs.context_id = __privateMethod(this, _generateId, generateId_fn).call(this);
399
+ }
400
+ if (!inputs.output_format) {
401
+ inputs.output_format = {
402
+ container: __privateGet(this, _container2),
403
+ encoding: __privateGet(this, _encoding2),
404
+ sample_rate: __privateGet(this, _sampleRate2)
405
+ };
406
+ }
407
+ (_a2 = this.socket) == null ? void 0 : _a2.send(
408
+ JSON.stringify(__spreadValues({}, inputs))
348
409
  );
349
410
  const emitter = new import_emittery2.default();
350
411
  const source = new Source({
351
- sampleRate: __privateGet(this, _sampleRate2)
412
+ sampleRate: __privateGet(this, _sampleRate2),
413
+ encoding: __privateGet(this, _encoding2),
414
+ container: __privateGet(this, _container2)
352
415
  });
353
416
  const streamCompleteController = new AbortController();
354
417
  let timeoutId = null;
@@ -356,19 +419,26 @@ var WebSocket = class extends Client {
356
419
  timeoutId = setTimeout(streamCompleteController.abort, timeout);
357
420
  }
358
421
  const handleMessage = createMessageHandlerForContextId(
359
- contextId,
360
- (_0) => __async(this, [_0], function* ({ chunk, message }) {
422
+ inputs.context_id,
423
+ (_0) => __async(this, [_0], function* ({ chunk, message, data }) {
361
424
  emitter.emit("message", message);
425
+ if (data.type === "timestamps") {
426
+ emitter.emit("timestamps", data.word_timestamps);
427
+ return;
428
+ }
362
429
  if (isSentinel(chunk)) {
363
430
  yield source.close();
364
431
  streamCompleteController.abort();
365
432
  return;
366
433
  }
367
- yield source.enqueue(base64ToArray([chunk]));
368
434
  if (timeoutId) {
369
435
  clearTimeout(timeoutId);
370
436
  timeoutId = setTimeout(streamCompleteController.abort, timeout);
371
437
  }
438
+ if (!chunk) {
439
+ return;
440
+ }
441
+ yield source.enqueue(base64ToArray([chunk], __privateGet(this, _encoding2)));
372
442
  })
373
443
  );
374
444
  (_b = this.socket) == null ? void 0 : _b.addEventListener("message", handleMessage, {
@@ -411,56 +481,60 @@ var WebSocket = class extends Client {
411
481
  * @throws {Error} If the WebSocket fails to connect.
412
482
  */
413
483
  connect() {
414
- const url = constructApiUrl(this.baseUrl, "/tts/websocket", {
415
- websocket: true
484
+ return __async(this, null, function* () {
485
+ const emitter = new import_emittery2.default();
486
+ this.socket = new import_partysocket.WebSocket(() => __async(this, null, function* () {
487
+ const url = constructApiUrl(this.baseUrl, "/tts/websocket", {
488
+ websocket: true
489
+ });
490
+ url.searchParams.set("api_key", yield this.apiKey());
491
+ url.searchParams.set("cartesia_version", CARTESIA_VERSION);
492
+ return url.toString();
493
+ }));
494
+ this.socket.onopen = () => {
495
+ __privateSet(this, _isConnected, true);
496
+ emitter.emit("open");
497
+ };
498
+ this.socket.onclose = () => {
499
+ __privateSet(this, _isConnected, false);
500
+ emitter.emit("close");
501
+ };
502
+ return new Promise(
503
+ (resolve, reject) => {
504
+ var _a, _b, _c;
505
+ (_a = this.socket) == null ? void 0 : _a.addEventListener(
506
+ "open",
507
+ () => {
508
+ resolve(getEmitteryCallbacks(emitter));
509
+ },
510
+ {
511
+ once: true
512
+ }
513
+ );
514
+ const aborter = new AbortController();
515
+ (_b = this.socket) == null ? void 0 : _b.addEventListener(
516
+ "error",
517
+ () => {
518
+ aborter.abort();
519
+ reject(new Error("WebSocket failed to connect."));
520
+ },
521
+ {
522
+ signal: aborter.signal
523
+ }
524
+ );
525
+ (_c = this.socket) == null ? void 0 : _c.addEventListener(
526
+ "close",
527
+ () => {
528
+ aborter.abort();
529
+ reject(new Error("WebSocket closed before it could connect."));
530
+ },
531
+ {
532
+ signal: aborter.signal
533
+ }
534
+ );
535
+ }
536
+ );
416
537
  });
417
- url.searchParams.set("api_key", this.apiKey);
418
- url.searchParams.set("cartesia_version", CARTESIA_VERSION);
419
- const emitter = new import_emittery2.default();
420
- this.socket = new import_partysocket.WebSocket(url.toString());
421
- this.socket.onopen = () => {
422
- __privateSet(this, _isConnected, true);
423
- emitter.emit("open");
424
- };
425
- this.socket.onclose = () => {
426
- __privateSet(this, _isConnected, false);
427
- emitter.emit("close");
428
- };
429
- return new Promise(
430
- (resolve, reject) => {
431
- var _a, _b, _c;
432
- (_a = this.socket) == null ? void 0 : _a.addEventListener(
433
- "open",
434
- () => {
435
- resolve(getEmitteryCallbacks(emitter));
436
- },
437
- {
438
- once: true
439
- }
440
- );
441
- const aborter = new AbortController();
442
- (_b = this.socket) == null ? void 0 : _b.addEventListener(
443
- "error",
444
- () => {
445
- aborter.abort();
446
- reject(new Error("WebSocket failed to connect."));
447
- },
448
- {
449
- signal: aborter.signal
450
- }
451
- );
452
- (_c = this.socket) == null ? void 0 : _c.addEventListener(
453
- "close",
454
- () => {
455
- aborter.abort();
456
- reject(new Error("WebSocket closed before it could connect."));
457
- },
458
- {
459
- signal: aborter.signal
460
- }
461
- );
462
- }
463
- );
464
538
  }
465
539
  /**
466
540
  * Disconnect from the Cartesia streaming WebSocket.
@@ -472,6 +546,8 @@ var WebSocket = class extends Client {
472
546
  };
473
547
  _isConnected = new WeakMap();
474
548
  _sampleRate2 = new WeakMap();
549
+ _container2 = new WeakMap();
550
+ _encoding2 = new WeakMap();
475
551
  _generateId = new WeakSet();
476
552
  generateId_fn = function() {
477
553
  return (0, import_human_id.humanId)({
@@ -1,7 +1,7 @@
1
1
  import * as emittery from 'emittery';
2
2
  import { WebSocket as WebSocket$1 } from 'partysocket';
3
3
  import { Client } from '../lib/client.cjs';
4
- import { WebSocketOptions, StreamRequest, EmitteryCallbacks, ConnectionEventData } from '../types/index.cjs';
4
+ import { WebSocketOptions, StreamRequest, StreamOptions, WordTimestamps, EmitteryCallbacks, ConnectionEventData } from '../types/index.cjs';
5
5
  import Source from './source.cjs';
6
6
 
7
7
  declare class WebSocket extends Client {
@@ -12,11 +12,11 @@ declare class WebSocket extends Client {
12
12
  *
13
13
  * @param args - Arguments to pass to the Client constructor.
14
14
  */
15
- constructor({ sampleRate }: WebSocketOptions, ...args: ConstructorParameters<typeof Client>);
15
+ constructor({ sampleRate, container, encoding }: WebSocketOptions, ...args: ConstructorParameters<typeof Client>);
16
16
  /**
17
17
  * Send a message over the WebSocket to start a stream.
18
18
  *
19
- * @param inputs - Stream options.
19
+ * @param inputs - Stream options. Defined in the StreamRequest type.
20
20
  * @param options - Options for the stream.
21
21
  * @param options.timeout - The maximum time to wait for a chunk before cancelling the stream.
22
22
  * If set to `0`, the stream will not time out.
@@ -24,22 +24,26 @@ declare class WebSocket extends Client {
24
24
  * @returns An Emittery instance that emits messages from the WebSocket.
25
25
  * @returns An abort function that can be called to cancel the stream.
26
26
  */
27
- send(inputs: StreamRequest["inputs"], { timeout }?: StreamRequest["options"]): {
27
+ send({ ...inputs }: StreamRequest, { timeout }?: StreamOptions): {
28
28
  stop: {
29
29
  (reason?: any): void;
30
30
  (reason?: any): void;
31
31
  };
32
- on: <Name extends keyof emittery.OmnipresentEventData | "message">(eventName: Name | readonly Name[], listener: (eventData: ({
32
+ on: <Name extends "timestamps" | keyof emittery.OmnipresentEventData | "message">(eventName: Name | readonly Name[], listener: (eventData: ({
33
33
  message: string;
34
+ timestamps: WordTimestamps;
34
35
  } & emittery.OmnipresentEventData)[Name]) => void | Promise<void>) => emittery.UnsubscribeFunction;
35
- off: <Name_1 extends keyof emittery.OmnipresentEventData | "message">(eventName: Name_1 | readonly Name_1[], listener: (eventData: ({
36
+ off: <Name_1 extends "timestamps" | keyof emittery.OmnipresentEventData | "message">(eventName: Name_1 | readonly Name_1[], listener: (eventData: ({
36
37
  message: string;
38
+ timestamps: WordTimestamps;
37
39
  } & emittery.OmnipresentEventData)[Name_1]) => void | Promise<void>) => void;
38
- once: <Name_2 extends keyof emittery.OmnipresentEventData | "message">(eventName: Name_2 | readonly Name_2[]) => emittery.EmitteryOncePromise<({
40
+ once: <Name_2 extends "timestamps" | keyof emittery.OmnipresentEventData | "message">(eventName: Name_2 | readonly Name_2[]) => emittery.EmitteryOncePromise<({
39
41
  message: string;
42
+ timestamps: WordTimestamps;
40
43
  } & emittery.OmnipresentEventData)[Name_2]>;
41
- events: <Name_3 extends "message">(eventName: Name_3 | readonly Name_3[]) => AsyncIterableIterator<{
44
+ events: <Name_3 extends "timestamps" | "message">(eventName: Name_3 | readonly Name_3[]) => AsyncIterableIterator<{
42
45
  message: string;
46
+ timestamps: WordTimestamps;
43
47
  }[Name_3]>;
44
48
  source: Source;
45
49
  };
@@ -1,7 +1,7 @@
1
1
  import * as emittery from 'emittery';
2
2
  import { WebSocket as WebSocket$1 } from 'partysocket';
3
3
  import { Client } from '../lib/client.js';
4
- import { WebSocketOptions, StreamRequest, EmitteryCallbacks, ConnectionEventData } from '../types/index.js';
4
+ import { WebSocketOptions, StreamRequest, StreamOptions, WordTimestamps, EmitteryCallbacks, ConnectionEventData } from '../types/index.js';
5
5
  import Source from './source.js';
6
6
 
7
7
  declare class WebSocket extends Client {
@@ -12,11 +12,11 @@ declare class WebSocket extends Client {
12
12
  *
13
13
  * @param args - Arguments to pass to the Client constructor.
14
14
  */
15
- constructor({ sampleRate }: WebSocketOptions, ...args: ConstructorParameters<typeof Client>);
15
+ constructor({ sampleRate, container, encoding }: WebSocketOptions, ...args: ConstructorParameters<typeof Client>);
16
16
  /**
17
17
  * Send a message over the WebSocket to start a stream.
18
18
  *
19
- * @param inputs - Stream options.
19
+ * @param inputs - Stream options. Defined in the StreamRequest type.
20
20
  * @param options - Options for the stream.
21
21
  * @param options.timeout - The maximum time to wait for a chunk before cancelling the stream.
22
22
  * If set to `0`, the stream will not time out.
@@ -24,22 +24,26 @@ declare class WebSocket extends Client {
24
24
  * @returns An Emittery instance that emits messages from the WebSocket.
25
25
  * @returns An abort function that can be called to cancel the stream.
26
26
  */
27
- send(inputs: StreamRequest["inputs"], { timeout }?: StreamRequest["options"]): {
27
+ send({ ...inputs }: StreamRequest, { timeout }?: StreamOptions): {
28
28
  stop: {
29
29
  (reason?: any): void;
30
30
  (reason?: any): void;
31
31
  };
32
- on: <Name extends keyof emittery.OmnipresentEventData | "message">(eventName: Name | readonly Name[], listener: (eventData: ({
32
+ on: <Name extends "timestamps" | keyof emittery.OmnipresentEventData | "message">(eventName: Name | readonly Name[], listener: (eventData: ({
33
33
  message: string;
34
+ timestamps: WordTimestamps;
34
35
  } & emittery.OmnipresentEventData)[Name]) => void | Promise<void>) => emittery.UnsubscribeFunction;
35
- off: <Name_1 extends keyof emittery.OmnipresentEventData | "message">(eventName: Name_1 | readonly Name_1[], listener: (eventData: ({
36
+ off: <Name_1 extends "timestamps" | keyof emittery.OmnipresentEventData | "message">(eventName: Name_1 | readonly Name_1[], listener: (eventData: ({
36
37
  message: string;
38
+ timestamps: WordTimestamps;
37
39
  } & emittery.OmnipresentEventData)[Name_1]) => void | Promise<void>) => void;
38
- once: <Name_2 extends keyof emittery.OmnipresentEventData | "message">(eventName: Name_2 | readonly Name_2[]) => emittery.EmitteryOncePromise<({
40
+ once: <Name_2 extends "timestamps" | keyof emittery.OmnipresentEventData | "message">(eventName: Name_2 | readonly Name_2[]) => emittery.EmitteryOncePromise<({
39
41
  message: string;
42
+ timestamps: WordTimestamps;
40
43
  } & emittery.OmnipresentEventData)[Name_2]>;
41
- events: <Name_3 extends "message">(eventName: Name_3 | readonly Name_3[]) => AsyncIterableIterator<{
44
+ events: <Name_3 extends "timestamps" | "message">(eventName: Name_3 | readonly Name_3[]) => AsyncIterableIterator<{
42
45
  message: string;
46
+ timestamps: WordTimestamps;
43
47
  }[Name_3]>;
44
48
  source: Source;
45
49
  };
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  WebSocket
3
- } from "../chunk-FN7BK4PS.js";
4
- import "../chunk-PQ6CIPFW.js";
5
- import "../chunk-PQ5EVEEH.js";
3
+ } from "../chunk-IZBPLCGW.js";
4
+ import "../chunk-PISCPZK4.js";
6
5
  import "../chunk-2BFEKY3F.js";
7
- import "../chunk-RO7TY474.js";
8
- import "../chunk-WIFMLPT5.js";
6
+ import "../chunk-BHY7MNGT.js";
7
+ import "../chunk-6YQ6KDIQ.js";
8
+ import "../chunk-GHY2WEOK.js";
9
9
  export {
10
10
  WebSocket as default
11
11
  };