@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
package/dist/index.cjs CHANGED
@@ -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 });
@@ -90,7 +102,9 @@ var __async = (__this, __arguments, generator) => {
90
102
  var src_exports = {};
91
103
  __export(src_exports, {
92
104
  Cartesia: () => Cartesia,
105
+ Source: () => Source,
93
106
  WebPlayer: () => Player,
107
+ WebSocket: () => WebSocket,
94
108
  default: () => Cartesia
95
109
  });
96
110
  module.exports = __toCommonJS(src_exports);
@@ -112,20 +126,25 @@ var constructApiUrl = (baseUrl, path, { websocket = false } = {}) => {
112
126
  // src/lib/client.ts
113
127
  var Client = class {
114
128
  constructor(options = {}) {
115
- if (!(options.apiKey || process.env.CARTESIA_API_KEY)) {
129
+ const apiKey = options.apiKey || process.env.CARTESIA_API_KEY;
130
+ if (!apiKey) {
116
131
  throw new Error("Missing Cartesia API key.");
117
132
  }
118
- this.apiKey = options.apiKey || process.env.CARTESIA_API_KEY;
133
+ this.apiKey = typeof apiKey === "function" ? apiKey : () => __async(this, null, function* () {
134
+ return apiKey;
135
+ });
119
136
  this.baseUrl = options.baseUrl || BASE_URL;
120
137
  }
121
- fetch(path, options = {}) {
122
- const url = constructApiUrl(this.baseUrl, path);
123
- return (0, import_cross_fetch.default)(url.toString(), __spreadProps(__spreadValues({}, options), {
124
- headers: __spreadValues({
125
- "X-API-Key": this.apiKey,
126
- "Cartesia-Version": CARTESIA_VERSION
127
- }, options.headers)
128
- }));
138
+ _fetch(_0) {
139
+ return __async(this, arguments, function* (path, options = {}) {
140
+ const url = constructApiUrl(this.baseUrl, path);
141
+ const headers = new Headers(options.headers);
142
+ headers.set("X-API-Key", yield this.apiKey());
143
+ headers.set("Cartesia-Version", CARTESIA_VERSION);
144
+ return (0, import_cross_fetch.default)(url.toString(), __spreadProps(__spreadValues({}, options), {
145
+ headers
146
+ }));
147
+ });
129
148
  }
130
149
  };
131
150
 
@@ -136,7 +155,13 @@ var import_partysocket = require("partysocket");
136
155
 
137
156
  // src/tts/source.ts
138
157
  var import_emittery = __toESM(require("emittery"), 1);
139
- var _emitter, _buffer, _readIndex, _writeIndex, _closed, _sampleRate;
158
+ var ENCODING_MAP = {
159
+ pcm_f32le: { arrayType: Float32Array, bytesPerElement: 4 },
160
+ pcm_s16le: { arrayType: Int16Array, bytesPerElement: 2 },
161
+ pcm_alaw: { arrayType: Uint8Array, bytesPerElement: 1 },
162
+ pcm_mulaw: { arrayType: Uint8Array, bytesPerElement: 1 }
163
+ };
164
+ var _emitter, _buffer, _readIndex, _writeIndex, _closed, _sampleRate, _encoding, _container, _createBuffer, createBuffer_fn;
140
165
  var Source = class {
141
166
  /**
142
167
  * Create a new Source.
@@ -144,23 +169,44 @@ var Source = class {
144
169
  * @param options - Options for the Source.
145
170
  * @param options.sampleRate - The sample rate of the audio.
146
171
  */
147
- constructor({ sampleRate }) {
172
+ constructor({
173
+ sampleRate,
174
+ encoding,
175
+ container
176
+ }) {
177
+ /**
178
+ * Create a new buffer for the source.
179
+ *
180
+ * @param size - The size of the buffer to create.
181
+ * @returns The new buffer as a TypedArray based on the encoding.
182
+ */
183
+ __privateAdd(this, _createBuffer);
148
184
  __privateAdd(this, _emitter, new import_emittery.default());
149
185
  __privateAdd(this, _buffer, void 0);
150
186
  __privateAdd(this, _readIndex, 0);
151
187
  __privateAdd(this, _writeIndex, 0);
152
188
  __privateAdd(this, _closed, false);
153
189
  __privateAdd(this, _sampleRate, void 0);
190
+ __privateAdd(this, _encoding, void 0);
191
+ __privateAdd(this, _container, void 0);
154
192
  this.on = __privateGet(this, _emitter).on.bind(__privateGet(this, _emitter));
155
193
  this.once = __privateGet(this, _emitter).once.bind(__privateGet(this, _emitter));
156
194
  this.events = __privateGet(this, _emitter).events.bind(__privateGet(this, _emitter));
157
195
  this.off = __privateGet(this, _emitter).off.bind(__privateGet(this, _emitter));
158
196
  __privateSet(this, _sampleRate, sampleRate);
159
- __privateSet(this, _buffer, new Float32Array(1024));
197
+ __privateSet(this, _encoding, encoding);
198
+ __privateSet(this, _container, container);
199
+ __privateSet(this, _buffer, __privateMethod(this, _createBuffer, createBuffer_fn).call(this, 1024));
160
200
  }
161
201
  get sampleRate() {
162
202
  return __privateGet(this, _sampleRate);
163
203
  }
204
+ get encoding() {
205
+ return __privateGet(this, _encoding);
206
+ }
207
+ get container() {
208
+ return __privateGet(this, _container);
209
+ }
164
210
  /**
165
211
  * Append audio to the buffer.
166
212
  *
@@ -174,7 +220,7 @@ var Source = class {
174
220
  while (newCapacity < requiredCapacity) {
175
221
  newCapacity *= 2;
176
222
  }
177
- const newBuffer = new Float32Array(newCapacity);
223
+ const newBuffer = __privateMethod(this, _createBuffer, createBuffer_fn).call(this, newCapacity);
178
224
  newBuffer.set(__privateGet(this, _buffer));
179
225
  __privateSet(this, _buffer, newBuffer);
180
226
  }
@@ -222,6 +268,9 @@ var Source = class {
222
268
  get readIndex() {
223
269
  return __privateGet(this, _readIndex);
224
270
  }
271
+ get writeIndex() {
272
+ return __privateGet(this, _writeIndex);
273
+ }
225
274
  /**
226
275
  * Close the source. This signals that no more audio will be enqueued.
227
276
  *
@@ -243,19 +292,27 @@ _readIndex = new WeakMap();
243
292
  _writeIndex = new WeakMap();
244
293
  _closed = new WeakMap();
245
294
  _sampleRate = new WeakMap();
295
+ _encoding = new WeakMap();
296
+ _container = new WeakMap();
297
+ _createBuffer = new WeakSet();
298
+ createBuffer_fn = function(size) {
299
+ const { arrayType: ArrayType } = ENCODING_MAP[__privateGet(this, _encoding)];
300
+ return new ArrayType(size);
301
+ };
246
302
 
247
303
  // src/tts/utils.ts
248
304
  var import_base64_js = __toESM(require("base64-js"), 1);
249
- function base64ToArray(b64) {
305
+ function base64ToArray(b64, encoding) {
250
306
  const byteArrays = filterSentinel(b64).map((b) => import_base64_js.default.toByteArray(b));
307
+ const { arrayType: ArrayType, bytesPerElement } = ENCODING_MAP[encoding];
251
308
  const totalLength = byteArrays.reduce(
252
- (acc, arr) => acc + arr.length / Float32Array.BYTES_PER_ELEMENT,
309
+ (acc, arr) => acc + arr.length / bytesPerElement,
253
310
  0
254
311
  );
255
- const result = new Float32Array(totalLength);
312
+ const result = new ArrayType(totalLength);
256
313
  let offset = 0;
257
314
  for (const arr of byteArrays) {
258
- const floats = new Float32Array(arr.buffer);
315
+ const floats = new ArrayType(arr.buffer);
259
316
  result.set(floats, offset);
260
317
  offset += floats.length;
261
318
  }
@@ -286,10 +343,10 @@ function createMessageHandlerForContextId(contextId, handler) {
286
343
  let chunk;
287
344
  if (message.done) {
288
345
  chunk = getSentinel();
289
- } else {
346
+ } else if (message.type === "chunk") {
290
347
  chunk = message.data;
291
348
  }
292
- handler({ chunk, message: event.data });
349
+ handler({ chunk, message: event.data, data: message });
293
350
  };
294
351
  }
295
352
  function getSentinel() {
@@ -313,14 +370,14 @@ function getEmitteryCallbacks(emitter) {
313
370
  }
314
371
 
315
372
  // src/tts/websocket.ts
316
- var _isConnected, _sampleRate2, _generateId, generateId_fn;
373
+ var _isConnected, _sampleRate2, _container2, _encoding2, _generateId, generateId_fn;
317
374
  var WebSocket = class extends Client {
318
375
  /**
319
376
  * Create a new WebSocket client.
320
377
  *
321
378
  * @param args - Arguments to pass to the Client constructor.
322
379
  */
323
- constructor({ sampleRate }, ...args) {
380
+ constructor({ sampleRate, container, encoding }, ...args) {
324
381
  super(...args);
325
382
  /**
326
383
  * Generate a unique ID suitable for a streaming context.
@@ -333,12 +390,16 @@ var WebSocket = class extends Client {
333
390
  __privateAdd(this, _generateId);
334
391
  __privateAdd(this, _isConnected, false);
335
392
  __privateAdd(this, _sampleRate2, void 0);
393
+ __privateAdd(this, _container2, void 0);
394
+ __privateAdd(this, _encoding2, void 0);
336
395
  __privateSet(this, _sampleRate2, sampleRate);
396
+ __privateSet(this, _container2, container != null ? container : "raw");
397
+ __privateSet(this, _encoding2, encoding != null ? encoding : "pcm_f32le");
337
398
  }
338
399
  /**
339
400
  * Send a message over the WebSocket to start a stream.
340
401
  *
341
- * @param inputs - Stream options.
402
+ * @param inputs - Stream options. Defined in the StreamRequest type.
342
403
  * @param options - Options for the stream.
343
404
  * @param options.timeout - The maximum time to wait for a chunk before cancelling the stream.
344
405
  * If set to `0`, the stream will not time out.
@@ -346,26 +407,30 @@ var WebSocket = class extends Client {
346
407
  * @returns An Emittery instance that emits messages from the WebSocket.
347
408
  * @returns An abort function that can be called to cancel the stream.
348
409
  */
349
- send(inputs, { timeout = 0 } = {}) {
350
- var _a, _b, _c, _d;
410
+ send(_a, { timeout = 0 } = {}) {
411
+ var inputs = __objRest(_a, []);
412
+ var _a2, _b, _c, _d;
351
413
  if (!__privateGet(this, _isConnected)) {
352
414
  throw new Error("Not connected to WebSocket. Call .connect() first.");
353
415
  }
354
- const contextId = __privateMethod(this, _generateId, generateId_fn).call(this);
355
- (_a = this.socket) == null ? void 0 : _a.send(
356
- JSON.stringify(__spreadProps(__spreadValues({
357
- context_id: contextId
358
- }, inputs), {
359
- output_format: {
360
- container: "raw",
361
- encoding: "pcm_f32le",
362
- sample_rate: __privateGet(this, _sampleRate2)
363
- }
364
- }))
416
+ if (!inputs.context_id) {
417
+ inputs.context_id = __privateMethod(this, _generateId, generateId_fn).call(this);
418
+ }
419
+ if (!inputs.output_format) {
420
+ inputs.output_format = {
421
+ container: __privateGet(this, _container2),
422
+ encoding: __privateGet(this, _encoding2),
423
+ sample_rate: __privateGet(this, _sampleRate2)
424
+ };
425
+ }
426
+ (_a2 = this.socket) == null ? void 0 : _a2.send(
427
+ JSON.stringify(__spreadValues({}, inputs))
365
428
  );
366
429
  const emitter = new import_emittery2.default();
367
430
  const source = new Source({
368
- sampleRate: __privateGet(this, _sampleRate2)
431
+ sampleRate: __privateGet(this, _sampleRate2),
432
+ encoding: __privateGet(this, _encoding2),
433
+ container: __privateGet(this, _container2)
369
434
  });
370
435
  const streamCompleteController = new AbortController();
371
436
  let timeoutId = null;
@@ -373,19 +438,26 @@ var WebSocket = class extends Client {
373
438
  timeoutId = setTimeout(streamCompleteController.abort, timeout);
374
439
  }
375
440
  const handleMessage = createMessageHandlerForContextId(
376
- contextId,
377
- (_0) => __async(this, [_0], function* ({ chunk, message }) {
441
+ inputs.context_id,
442
+ (_0) => __async(this, [_0], function* ({ chunk, message, data }) {
378
443
  emitter.emit("message", message);
444
+ if (data.type === "timestamps") {
445
+ emitter.emit("timestamps", data.word_timestamps);
446
+ return;
447
+ }
379
448
  if (isSentinel(chunk)) {
380
449
  yield source.close();
381
450
  streamCompleteController.abort();
382
451
  return;
383
452
  }
384
- yield source.enqueue(base64ToArray([chunk]));
385
453
  if (timeoutId) {
386
454
  clearTimeout(timeoutId);
387
455
  timeoutId = setTimeout(streamCompleteController.abort, timeout);
388
456
  }
457
+ if (!chunk) {
458
+ return;
459
+ }
460
+ yield source.enqueue(base64ToArray([chunk], __privateGet(this, _encoding2)));
389
461
  })
390
462
  );
391
463
  (_b = this.socket) == null ? void 0 : _b.addEventListener("message", handleMessage, {
@@ -428,56 +500,60 @@ var WebSocket = class extends Client {
428
500
  * @throws {Error} If the WebSocket fails to connect.
429
501
  */
430
502
  connect() {
431
- const url = constructApiUrl(this.baseUrl, "/tts/websocket", {
432
- websocket: true
503
+ return __async(this, null, function* () {
504
+ const emitter = new import_emittery2.default();
505
+ this.socket = new import_partysocket.WebSocket(() => __async(this, null, function* () {
506
+ const url = constructApiUrl(this.baseUrl, "/tts/websocket", {
507
+ websocket: true
508
+ });
509
+ url.searchParams.set("api_key", yield this.apiKey());
510
+ url.searchParams.set("cartesia_version", CARTESIA_VERSION);
511
+ return url.toString();
512
+ }));
513
+ this.socket.onopen = () => {
514
+ __privateSet(this, _isConnected, true);
515
+ emitter.emit("open");
516
+ };
517
+ this.socket.onclose = () => {
518
+ __privateSet(this, _isConnected, false);
519
+ emitter.emit("close");
520
+ };
521
+ return new Promise(
522
+ (resolve, reject) => {
523
+ var _a, _b, _c;
524
+ (_a = this.socket) == null ? void 0 : _a.addEventListener(
525
+ "open",
526
+ () => {
527
+ resolve(getEmitteryCallbacks(emitter));
528
+ },
529
+ {
530
+ once: true
531
+ }
532
+ );
533
+ const aborter = new AbortController();
534
+ (_b = this.socket) == null ? void 0 : _b.addEventListener(
535
+ "error",
536
+ () => {
537
+ aborter.abort();
538
+ reject(new Error("WebSocket failed to connect."));
539
+ },
540
+ {
541
+ signal: aborter.signal
542
+ }
543
+ );
544
+ (_c = this.socket) == null ? void 0 : _c.addEventListener(
545
+ "close",
546
+ () => {
547
+ aborter.abort();
548
+ reject(new Error("WebSocket closed before it could connect."));
549
+ },
550
+ {
551
+ signal: aborter.signal
552
+ }
553
+ );
554
+ }
555
+ );
433
556
  });
434
- url.searchParams.set("api_key", this.apiKey);
435
- url.searchParams.set("cartesia_version", CARTESIA_VERSION);
436
- const emitter = new import_emittery2.default();
437
- this.socket = new import_partysocket.WebSocket(url.toString());
438
- this.socket.onopen = () => {
439
- __privateSet(this, _isConnected, true);
440
- emitter.emit("open");
441
- };
442
- this.socket.onclose = () => {
443
- __privateSet(this, _isConnected, false);
444
- emitter.emit("close");
445
- };
446
- return new Promise(
447
- (resolve, reject) => {
448
- var _a, _b, _c;
449
- (_a = this.socket) == null ? void 0 : _a.addEventListener(
450
- "open",
451
- () => {
452
- resolve(getEmitteryCallbacks(emitter));
453
- },
454
- {
455
- once: true
456
- }
457
- );
458
- const aborter = new AbortController();
459
- (_b = this.socket) == null ? void 0 : _b.addEventListener(
460
- "error",
461
- () => {
462
- aborter.abort();
463
- reject(new Error("WebSocket failed to connect."));
464
- },
465
- {
466
- signal: aborter.signal
467
- }
468
- );
469
- (_c = this.socket) == null ? void 0 : _c.addEventListener(
470
- "close",
471
- () => {
472
- aborter.abort();
473
- reject(new Error("WebSocket closed before it could connect."));
474
- },
475
- {
476
- signal: aborter.signal
477
- }
478
- );
479
- }
480
- );
481
557
  }
482
558
  /**
483
559
  * Disconnect from the Cartesia streaming WebSocket.
@@ -489,6 +565,8 @@ var WebSocket = class extends Client {
489
565
  };
490
566
  _isConnected = new WeakMap();
491
567
  _sampleRate2 = new WeakMap();
568
+ _container2 = new WeakMap();
569
+ _encoding2 = new WeakMap();
492
570
  _generateId = new WeakSet();
493
571
  generateId_fn = function() {
494
572
  return (0, import_human_id.humanId)({
@@ -516,40 +594,43 @@ var TTS = class extends Client {
516
594
  var Voices = class extends Client {
517
595
  list() {
518
596
  return __async(this, null, function* () {
519
- const response = yield this.fetch("/voices");
597
+ const response = yield this._fetch("/voices");
520
598
  return response.json();
521
599
  });
522
600
  }
523
601
  get(voiceId) {
524
602
  return __async(this, null, function* () {
525
- const response = yield this.fetch(`/voices/${voiceId}`);
603
+ const response = yield this._fetch(`/voices/${voiceId}`);
526
604
  return response.json();
527
605
  });
528
606
  }
529
607
  create(voice) {
530
608
  return __async(this, null, function* () {
531
- const response = yield this.fetch("/voices", {
609
+ const response = yield this._fetch("/voices", {
532
610
  method: "POST",
533
611
  body: JSON.stringify(voice)
534
612
  });
535
613
  return response.json();
536
614
  });
537
615
  }
616
+ update(id, voice) {
617
+ return __async(this, null, function* () {
618
+ const response = yield this._fetch(`/voices/${id}`, {
619
+ method: "PATCH",
620
+ body: JSON.stringify(voice)
621
+ });
622
+ return response.json();
623
+ });
624
+ }
538
625
  clone(options) {
539
626
  return __async(this, null, function* () {
540
- if (options.mode === "url") {
541
- const response = yield this.fetch(
542
- `/voices/clone/url?link=${options.link}`,
543
- {
544
- method: "POST"
545
- }
546
- );
547
- return response.json();
548
- }
549
627
  if (options.mode === "clip") {
550
628
  const formData = new FormData();
551
629
  formData.append("clip", options.clip);
552
- const response = yield this.fetch("/voices/clone/clip", {
630
+ if (options.enhance !== void 0) {
631
+ formData.append("enhance", options.enhance.toString());
632
+ }
633
+ const response = yield this._fetch("/voices/clone/clip", {
553
634
  method: "POST",
554
635
  body: formData
555
636
  });
@@ -689,5 +770,7 @@ playBuffer_fn = function(buf, sampleRate) {
689
770
  // Annotate the CommonJS export names for ESM import in node:
690
771
  0 && (module.exports = {
691
772
  Cartesia,
692
- WebPlayer
773
+ Source,
774
+ WebPlayer,
775
+ WebSocket
693
776
  });
package/dist/index.d.cts CHANGED
@@ -1,10 +1,10 @@
1
1
  export { Cartesia, Cartesia as default } from './lib/index.cjs';
2
- export { Chunk, ClientOptions, CloneOptions, CloneResponse, ConnectionEventData, CreateVoice, EmitteryCallbacks, Sentinel, SourceEventData, StreamRequest, Voice, WebSocketOptions } from './types/index.cjs';
2
+ export { Chunk, ClientOptions, CloneOptions, CloneResponse, ConnectionEventData, CreateVoice, EmitteryCallbacks, Emotion, EmotionControl, Encoding, Intensity, Sentinel, SourceEventData, StreamOptions, StreamRequest, TypedArray, UpdateVoice, Voice, VoiceOptions, VoiceSpecifier, WebSocketBaseResponse, WebSocketChunkResponse, WebSocketErrorResponse, WebSocketOptions, WebSocketResponse, WebSocketTimestampsResponse, WordTimestamps } from './types/index.cjs';
3
3
  export { default as WebPlayer } from './tts/player.cjs';
4
+ export { default as Source } from './tts/source.cjs';
5
+ export { default as WebSocket } from './tts/websocket.cjs';
4
6
  import './tts/index.cjs';
5
7
  import './lib/client.cjs';
6
- import './tts/websocket.cjs';
8
+ import './voices/index.cjs';
7
9
  import 'emittery';
8
10
  import 'partysocket';
9
- import './tts/source.cjs';
10
- import './voices/index.cjs';
package/dist/index.d.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  export { Cartesia, Cartesia as default } from './lib/index.js';
2
- export { Chunk, ClientOptions, CloneOptions, CloneResponse, ConnectionEventData, CreateVoice, EmitteryCallbacks, Sentinel, SourceEventData, StreamRequest, Voice, WebSocketOptions } from './types/index.js';
2
+ export { Chunk, ClientOptions, CloneOptions, CloneResponse, ConnectionEventData, CreateVoice, EmitteryCallbacks, Emotion, EmotionControl, Encoding, Intensity, Sentinel, SourceEventData, StreamOptions, StreamRequest, TypedArray, UpdateVoice, Voice, VoiceOptions, VoiceSpecifier, WebSocketBaseResponse, WebSocketChunkResponse, WebSocketErrorResponse, WebSocketOptions, WebSocketResponse, WebSocketTimestampsResponse, WordTimestamps } from './types/index.js';
3
3
  export { default as WebPlayer } from './tts/player.js';
4
+ export { default as Source } from './tts/source.js';
5
+ export { default as WebSocket } from './tts/websocket.js';
4
6
  import './tts/index.js';
5
7
  import './lib/client.js';
6
- import './tts/websocket.js';
8
+ import './voices/index.js';
7
9
  import 'emittery';
8
10
  import 'partysocket';
9
- import './tts/source.js';
10
- import './voices/index.js';
package/dist/index.js CHANGED
@@ -1,20 +1,26 @@
1
1
  import "./chunk-FXPGR372.js";
2
2
  import {
3
3
  Cartesia
4
- } from "./chunk-IEN4NCER.js";
5
- import "./chunk-SGXUEFII.js";
6
- import "./chunk-F4QWVJY3.js";
7
- import "./chunk-FN7BK4PS.js";
8
- import "./chunk-PQ6CIPFW.js";
9
- import "./chunk-PQ5EVEEH.js";
4
+ } from "./chunk-NVOCUUOF.js";
5
+ import "./chunk-UCYL2SOX.js";
6
+ import "./chunk-EDAAHENY.js";
7
+ import {
8
+ WebSocket
9
+ } from "./chunk-IZBPLCGW.js";
10
+ import "./chunk-PISCPZK4.js";
10
11
  import "./chunk-2BFEKY3F.js";
11
12
  import {
12
13
  Player
13
- } from "./chunk-JYLAM6VU.js";
14
- import "./chunk-RO7TY474.js";
15
- import "./chunk-WIFMLPT5.js";
14
+ } from "./chunk-LZO6K34D.js";
15
+ import "./chunk-BHY7MNGT.js";
16
+ import {
17
+ Source
18
+ } from "./chunk-6YQ6KDIQ.js";
19
+ import "./chunk-GHY2WEOK.js";
16
20
  export {
17
21
  Cartesia,
22
+ Source,
18
23
  Player as WebPlayer,
24
+ WebSocket,
19
25
  Cartesia as default
20
26
  };
@@ -43,6 +43,26 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
43
43
  mod
44
44
  ));
45
45
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
+ var __async = (__this, __arguments, generator) => {
47
+ return new Promise((resolve, reject) => {
48
+ var fulfilled = (value) => {
49
+ try {
50
+ step(generator.next(value));
51
+ } catch (e) {
52
+ reject(e);
53
+ }
54
+ };
55
+ var rejected = (value) => {
56
+ try {
57
+ step(generator.throw(value));
58
+ } catch (e) {
59
+ reject(e);
60
+ }
61
+ };
62
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
63
+ step((generator = generator.apply(__this, __arguments)).next());
64
+ });
65
+ };
46
66
 
47
67
  // src/lib/client.ts
48
68
  var client_exports = {};
@@ -66,20 +86,25 @@ var constructApiUrl = (baseUrl, path, { websocket = false } = {}) => {
66
86
  // src/lib/client.ts
67
87
  var Client = class {
68
88
  constructor(options = {}) {
69
- if (!(options.apiKey || process.env.CARTESIA_API_KEY)) {
89
+ const apiKey = options.apiKey || process.env.CARTESIA_API_KEY;
90
+ if (!apiKey) {
70
91
  throw new Error("Missing Cartesia API key.");
71
92
  }
72
- this.apiKey = options.apiKey || process.env.CARTESIA_API_KEY;
93
+ this.apiKey = typeof apiKey === "function" ? apiKey : () => __async(this, null, function* () {
94
+ return apiKey;
95
+ });
73
96
  this.baseUrl = options.baseUrl || BASE_URL;
74
97
  }
75
- fetch(path, options = {}) {
76
- const url = constructApiUrl(this.baseUrl, path);
77
- return (0, import_cross_fetch.default)(url.toString(), __spreadProps(__spreadValues({}, options), {
78
- headers: __spreadValues({
79
- "X-API-Key": this.apiKey,
80
- "Cartesia-Version": CARTESIA_VERSION
81
- }, options.headers)
82
- }));
98
+ _fetch(_0) {
99
+ return __async(this, arguments, function* (path, options = {}) {
100
+ const url = constructApiUrl(this.baseUrl, path);
101
+ const headers = new Headers(options.headers);
102
+ headers.set("X-API-Key", yield this.apiKey());
103
+ headers.set("Cartesia-Version", CARTESIA_VERSION);
104
+ return (0, import_cross_fetch.default)(url.toString(), __spreadProps(__spreadValues({}, options), {
105
+ headers
106
+ }));
107
+ });
83
108
  }
84
109
  };
85
110
  // Annotate the CommonJS export names for ESM import in node:
@@ -2,10 +2,10 @@ import { ClientOptions } from '../types/index.cjs';
2
2
  import 'emittery';
3
3
 
4
4
  declare class Client {
5
- apiKey: string;
5
+ apiKey: () => Promise<string>;
6
6
  baseUrl: string;
7
7
  constructor(options?: ClientOptions);
8
- fetch(path: string, options?: RequestInit): Promise<Response>;
8
+ protected _fetch(path: string, options?: RequestInit): Promise<Response>;
9
9
  }
10
10
 
11
11
  export { Client };
@@ -2,10 +2,10 @@ import { ClientOptions } from '../types/index.js';
2
2
  import 'emittery';
3
3
 
4
4
  declare class Client {
5
- apiKey: string;
5
+ apiKey: () => Promise<string>;
6
6
  baseUrl: string;
7
7
  constructor(options?: ClientOptions);
8
- fetch(path: string, options?: RequestInit): Promise<Response>;
8
+ protected _fetch(path: string, options?: RequestInit): Promise<Response>;
9
9
  }
10
10
 
11
11
  export { Client };
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  Client
3
- } from "../chunk-PQ5EVEEH.js";
3
+ } from "../chunk-PISCPZK4.js";
4
4
  import "../chunk-2BFEKY3F.js";
5
- import "../chunk-WIFMLPT5.js";
5
+ import "../chunk-GHY2WEOK.js";
6
6
  export {
7
7
  Client
8
8
  };
@@ -3,7 +3,7 @@ import {
3
3
  CARTESIA_VERSION,
4
4
  constructApiUrl
5
5
  } from "../chunk-2BFEKY3F.js";
6
- import "../chunk-WIFMLPT5.js";
6
+ import "../chunk-GHY2WEOK.js";
7
7
  export {
8
8
  BASE_URL,
9
9
  CARTESIA_VERSION,