@cartesia/cartesia-js 3.0.0-b4 → 3.0.0-b5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 3.0.0-b5 (2026-01-07)
4
+
5
+ Full Changelog: [v3.0.0-b4...v3.0.0-b5](https://github.com/cartesia-ai/cartesia-js-internal/compare/v3.0.0-b4...v3.0.0-b5)
6
+
7
+ ### Features
8
+
9
+ * **api:** fix readme ([91bd83c](https://github.com/cartesia-ai/cartesia-js-internal/commit/91bd83cb75d8b92778928cf7aebab908f7723b79))
10
+
3
11
  ## 3.0.0-b4 (2026-01-07)
4
12
 
5
13
  Full Changelog: [v3.0.0-b3...v3.0.0-b4](https://github.com/cartesia-ai/cartesia-js-internal/compare/v3.0.0-b3...v3.0.0-b4)
package/README.md CHANGED
@@ -23,12 +23,13 @@ The full API of this library can be found in [api.md](api.md).
23
23
  import Cartesia from '@cartesia/cartesia-js';
24
24
 
25
25
  const client = new Cartesia({
26
- token: 'My Token',
26
+ apiKey: 'My API Key',
27
27
  });
28
28
 
29
- const response = await client.getStatus();
29
+ const page = await client.voices.list();
30
+ const voice = page.data[0];
30
31
 
31
- console.log(response.ok);
32
+ console.log(voice.id);
32
33
  ```
33
34
 
34
35
  ### Request & Response types
@@ -40,10 +41,10 @@ This library includes TypeScript definitions for all request params and response
40
41
  import Cartesia from '@cartesia/cartesia-js';
41
42
 
42
43
  const client = new Cartesia({
43
- token: 'My Token',
44
+ apiKey: 'My API Key',
44
45
  });
45
46
 
46
- const response: Cartesia.GetStatusResponse = await client.getStatus();
47
+ const [voice]: [Cartesia.Voice] = await client.voices.list();
47
48
  ```
48
49
 
49
50
  Documentation for each method, request param, and response field are available in docstrings and will appear on hover in most modern editors.
@@ -85,7 +86,7 @@ a subclass of `APIError` will be thrown:
85
86
 
86
87
  <!-- prettier-ignore -->
87
88
  ```ts
88
- const response = await client.getStatus().catch(async (err) => {
89
+ const page = await client.voices.list().catch(async (err) => {
89
90
  if (err instanceof Cartesia.APIError) {
90
91
  console.log(err.status); // 400
91
92
  console.log(err.name); // BadRequestError
@@ -125,7 +126,7 @@ const client = new Cartesia({
125
126
  });
126
127
 
127
128
  // Or, configure per-request:
128
- await client.getStatus({
129
+ await client.voices.list({
129
130
  maxRetries: 5,
130
131
  });
131
132
  ```
@@ -142,7 +143,7 @@ const client = new Cartesia({
142
143
  });
143
144
 
144
145
  // Override per-request:
145
- await client.getStatus({
146
+ await client.voices.list({
146
147
  timeout: 5 * 1000,
147
148
  });
148
149
  ```
@@ -157,22 +158,22 @@ List methods in the Cartesia API are paginated.
157
158
  You can use the `for await … of` syntax to iterate through items across all pages:
158
159
 
159
160
  ```ts
160
- async function fetchAllAgentCalls(params) {
161
- const allAgentCalls = [];
161
+ async function fetchAllVoices(params) {
162
+ const allVoices = [];
162
163
  // Automatically fetches more pages as needed.
163
- for await (const agentCall of client.agents.calls.list({ agent_id: 'agent_id' })) {
164
- allAgentCalls.push(agentCall);
164
+ for await (const voice of client.voices.list()) {
165
+ allVoices.push(voice);
165
166
  }
166
- return allAgentCalls;
167
+ return allVoices;
167
168
  }
168
169
  ```
169
170
 
170
171
  Alternatively, you can request a single page at a time:
171
172
 
172
173
  ```ts
173
- let page = await client.agents.calls.list({ agent_id: 'agent_id' });
174
- for (const agentCall of page.data) {
175
- console.log(agentCall);
174
+ let page = await client.voices.list();
175
+ for (const voice of page.data) {
176
+ console.log(voice);
176
177
  }
177
178
 
178
179
  // Convenience methods are provided for manually paginating:
@@ -193,7 +194,8 @@ import Cartesia from '@cartesia/cartesia-js';
193
194
 
194
195
  const client = new Cartesia();
195
196
 
196
- const response = await client.getStatus({ headers: { 'cartesia-version': 'My-Custom-Value' } });
197
+ const page = await client.voices.list({ headers: { 'cartesia-version': 'My-Custom-Value' } });
198
+ const voice = page.data[0];
197
199
  ```
198
200
 
199
201
  ## Advanced Usage
@@ -210,13 +212,15 @@ Unlike `.asResponse()` this method consumes the body, returning once it is parse
210
212
  ```ts
211
213
  const client = new Cartesia();
212
214
 
213
- const response = await client.getStatus().asResponse();
215
+ const response = await client.voices.list().asResponse();
214
216
  console.log(response.headers.get('X-My-Header'));
215
217
  console.log(response.statusText); // access the underlying Response object
216
218
 
217
- const { data: response, response: raw } = await client.getStatus().withResponse();
219
+ const { data: page, response: raw } = await client.voices.list().withResponse();
218
220
  console.log(raw.headers.get('X-My-Header'));
219
- console.log(response.ok);
221
+ for await (const voice of page) {
222
+ console.log(voice.id);
223
+ }
220
224
  ```
221
225
 
222
226
  ### Logging
@@ -296,7 +300,7 @@ parameter. This library doesn't validate at runtime that the request matches the
296
300
  send will be sent as-is.
297
301
 
298
302
  ```ts
299
- client.getStatus({
303
+ client.voices.list({
300
304
  // ...
301
305
  // @ts-expect-error baz is not yet public
302
306
  baz: 'undocumented option',
@@ -0,0 +1,36 @@
1
+ import { Cartesia } from "../client.mjs";
2
+ declare class AudioSource {
3
+ private buffers;
4
+ private waiter;
5
+ isDone: boolean;
6
+ push(data: Buffer): void;
7
+ markDone(): void;
8
+ read(outBuffer: Float32Array): Promise<number>;
9
+ }
10
+ declare class WebSocketWrapper {
11
+ private client;
12
+ private config;
13
+ private socket;
14
+ private sources;
15
+ private defaultSource;
16
+ constructor(client: Cartesia, config: any);
17
+ connect(): Promise<void>;
18
+ private handleMessage;
19
+ send(request: any): Promise<{
20
+ source: AudioSource;
21
+ }>;
22
+ disconnect(): void;
23
+ }
24
+ declare class TTSWrapper {
25
+ private client;
26
+ constructor(client: Cartesia);
27
+ websocket(config: any): WebSocketWrapper;
28
+ bytes(request: any, requestOptions?: any): Promise<any>;
29
+ }
30
+ export declare class CartesiaClient {
31
+ private client;
32
+ tts: TTSWrapper;
33
+ constructor(options: any);
34
+ }
35
+ export {};
36
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/backcompat/index.ts"],"names":[],"mappings":"OACO,EAAE,QAAQ,EAAE;AAEnB,cAAM,WAAW;IAChB,OAAO,CAAC,OAAO,CAAgB;IAC/B,OAAO,CAAC,MAAM,CAAsC;IAC7C,MAAM,UAAS;IAEtB,IAAI,CAAC,IAAI,EAAE,MAAM;IAQjB,QAAQ;IAQF,IAAI,CAAC,SAAS,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,CAAC;CAkDpD;AAED,cAAM,gBAAgB;IACrB,OAAO,CAAC,MAAM,CAAW;IACzB,OAAO,CAAC,MAAM,CAAM;IACpB,OAAO,CAAC,MAAM,CAA0B;IACxC,OAAO,CAAC,OAAO,CAAuC;IAItD,OAAO,CAAC,aAAa,CAA4B;gBAErC,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG;IAKnC,OAAO;IAiDb,OAAO,CAAC,aAAa;IA2Bf,IAAI,CAAC,OAAO,EAAE,GAAG;;;IA4DvB,UAAU;CAKV;AAED,cAAM,UAAU;IACf,OAAO,CAAC,MAAM,CAAW;gBAEb,MAAM,EAAE,QAAQ;IAI5B,SAAS,CAAC,MAAM,EAAE,GAAG;IAIf,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,cAAc,CAAC,EAAE,GAAG;CAiC9C;AAMD,qBAAa,cAAc;IAC1B,OAAO,CAAC,MAAM,CAAW;IAClB,GAAG,EAAE,UAAU,CAAC;gBAEX,OAAO,EAAE,GAAG;CAIxB"}
@@ -0,0 +1,36 @@
1
+ import { Cartesia } from "../client.js";
2
+ declare class AudioSource {
3
+ private buffers;
4
+ private waiter;
5
+ isDone: boolean;
6
+ push(data: Buffer): void;
7
+ markDone(): void;
8
+ read(outBuffer: Float32Array): Promise<number>;
9
+ }
10
+ declare class WebSocketWrapper {
11
+ private client;
12
+ private config;
13
+ private socket;
14
+ private sources;
15
+ private defaultSource;
16
+ constructor(client: Cartesia, config: any);
17
+ connect(): Promise<void>;
18
+ private handleMessage;
19
+ send(request: any): Promise<{
20
+ source: AudioSource;
21
+ }>;
22
+ disconnect(): void;
23
+ }
24
+ declare class TTSWrapper {
25
+ private client;
26
+ constructor(client: Cartesia);
27
+ websocket(config: any): WebSocketWrapper;
28
+ bytes(request: any, requestOptions?: any): Promise<any>;
29
+ }
30
+ export declare class CartesiaClient {
31
+ private client;
32
+ tts: TTSWrapper;
33
+ constructor(options: any);
34
+ }
35
+ export {};
36
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/backcompat/index.ts"],"names":[],"mappings":"OACO,EAAE,QAAQ,EAAE;AAEnB,cAAM,WAAW;IAChB,OAAO,CAAC,OAAO,CAAgB;IAC/B,OAAO,CAAC,MAAM,CAAsC;IAC7C,MAAM,UAAS;IAEtB,IAAI,CAAC,IAAI,EAAE,MAAM;IAQjB,QAAQ;IAQF,IAAI,CAAC,SAAS,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,CAAC;CAkDpD;AAED,cAAM,gBAAgB;IACrB,OAAO,CAAC,MAAM,CAAW;IACzB,OAAO,CAAC,MAAM,CAAM;IACpB,OAAO,CAAC,MAAM,CAA0B;IACxC,OAAO,CAAC,OAAO,CAAuC;IAItD,OAAO,CAAC,aAAa,CAA4B;gBAErC,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG;IAKnC,OAAO;IAiDb,OAAO,CAAC,aAAa;IA2Bf,IAAI,CAAC,OAAO,EAAE,GAAG;;;IA4DvB,UAAU;CAKV;AAED,cAAM,UAAU;IACf,OAAO,CAAC,MAAM,CAAW;gBAEb,MAAM,EAAE,QAAQ;IAI5B,SAAS,CAAC,MAAM,EAAE,GAAG;IAIf,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,cAAc,CAAC,EAAE,GAAG;CAiC9C;AAMD,qBAAa,cAAc;IAC1B,OAAO,CAAC,MAAM,CAAW;IAClB,GAAG,EAAE,UAAU,CAAC;gBAEX,OAAO,EAAE,GAAG;CAIxB"}
@@ -0,0 +1,266 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CartesiaClient = void 0;
4
+ const tslib_1 = require("../internal/tslib.js");
5
+ const ws_1 = tslib_1.__importDefault(require("ws"));
6
+ const client_1 = require("../client.js");
7
+ class AudioSource {
8
+ constructor() {
9
+ this.buffers = [];
10
+ this.waiter = null;
11
+ this.isDone = false;
12
+ }
13
+ push(data) {
14
+ this.buffers.push(data);
15
+ if (this.waiter) {
16
+ this.waiter();
17
+ this.waiter = null;
18
+ }
19
+ }
20
+ markDone() {
21
+ this.isDone = true;
22
+ if (this.waiter) {
23
+ this.waiter();
24
+ this.waiter = null;
25
+ }
26
+ }
27
+ async read(outBuffer) {
28
+ if (this.buffers.length === 0 && !this.isDone) {
29
+ await new Promise((resolve) => { this.waiter = resolve; });
30
+ }
31
+ if (this.buffers.length === 0 && this.isDone) {
32
+ return 0;
33
+ }
34
+ let totalFloatsRead = 0;
35
+ let outOffset = 0;
36
+ const maxFloats = outBuffer.length;
37
+ while (this.buffers.length > 0 && totalFloatsRead < maxFloats) {
38
+ const buf = this.buffers[0]; // ts not smart enough to check loop condition
39
+ const floatsInBuf = buf.length / 4;
40
+ const floatsNeeded = maxFloats - totalFloatsRead;
41
+ const floatsToCopy = Math.min(floatsInBuf, floatsNeeded);
42
+ const bytesToCopy = floatsToCopy * 4;
43
+ // Copy to outBuffer.
44
+ // Create a view on the buffer to read floats.
45
+ // We need to ensure byteOffset is a multiple of 4.
46
+ // If not, we must copy the buffer to a new one.
47
+ let srcFloats;
48
+ if (buf.byteOffset % 4 === 0) {
49
+ srcFloats = new Float32Array(buf.buffer, buf.byteOffset, floatsInBuf);
50
+ }
51
+ else {
52
+ const alignedBuf = new Uint8Array(buf);
53
+ srcFloats = new Float32Array(alignedBuf.buffer, alignedBuf.byteOffset, floatsInBuf);
54
+ }
55
+ outBuffer.set(srcFloats.subarray(0, floatsToCopy), outOffset);
56
+ totalFloatsRead += floatsToCopy;
57
+ outOffset += floatsToCopy;
58
+ if (floatsToCopy < floatsInBuf) {
59
+ // We didn't use the whole buffer. Update it.
60
+ this.buffers[0] = buf.subarray(bytesToCopy);
61
+ }
62
+ else {
63
+ // We used the whole buffer. Remove it.
64
+ this.buffers.shift();
65
+ }
66
+ }
67
+ return totalFloatsRead;
68
+ }
69
+ }
70
+ class WebSocketWrapper {
71
+ constructor(client, config) {
72
+ this.socket = null;
73
+ this.sources = new Map();
74
+ // Fallback source for messages without context_id or if we just want to capture everything (legacy behavior?)
75
+ // The original test didn't use context_id explicitly in send() but expected a response source.
76
+ // We'll map context_id to source.
77
+ this.defaultSource = null;
78
+ this.client = client;
79
+ this.config = config;
80
+ }
81
+ async connect() {
82
+ const baseURL = this.client.baseURL;
83
+ // Construct WebSocket URL
84
+ // baseURL is like https://api.cartesia.ai
85
+ let urlStr = baseURL.replace(/^http/, "ws");
86
+ if (!urlStr.includes("/tts/websocket")) {
87
+ if (urlStr.endsWith("/")) {
88
+ urlStr += "tts/websocket";
89
+ }
90
+ else {
91
+ urlStr += "/tts/websocket";
92
+ }
93
+ }
94
+ const url = new URL(urlStr);
95
+ const headers = {
96
+ "cartesia-version": "2025-04-16",
97
+ };
98
+ if (this.client.apiKey) {
99
+ headers["Authorization"] = `Bearer ${this.client.apiKey}`;
100
+ }
101
+ this.socket = new ws_1.default(url.toString(), {
102
+ headers: headers,
103
+ });
104
+ return new Promise((resolve, reject) => {
105
+ this.socket.on("open", () => {
106
+ console.log("WebSocket connected.");
107
+ resolve();
108
+ });
109
+ this.socket.on("error", (err) => {
110
+ console.error("WebSocket error:", err);
111
+ reject(err);
112
+ });
113
+ this.socket.on("message", (data) => {
114
+ this.handleMessage(data);
115
+ });
116
+ this.socket.on("close", () => {
117
+ console.log("WebSocket closed.");
118
+ this.sources.forEach((s) => { s.markDone(); });
119
+ if (this.defaultSource)
120
+ this.defaultSource.markDone();
121
+ });
122
+ });
123
+ }
124
+ handleMessage(data) {
125
+ try {
126
+ const str = data.toString();
127
+ const msg = JSON.parse(str);
128
+ const contextId = msg.context_id;
129
+ let source = contextId ? this.sources.get(contextId) : this.defaultSource;
130
+ // If we received a message for a context we don't know about, and we have a default source, use it
131
+ if (!source && this.defaultSource) {
132
+ source = this.defaultSource;
133
+ }
134
+ if (msg.type === "chunk" && msg.data) {
135
+ const audioData = Buffer.from(msg.data, "base64");
136
+ if (source)
137
+ source.push(audioData);
138
+ }
139
+ else if (msg.type === "done") {
140
+ if (source)
141
+ source.markDone();
142
+ }
143
+ else if (msg.type === "error") {
144
+ console.error("Server error:", msg);
145
+ if (source)
146
+ source.markDone(); // Fail the stream?
147
+ }
148
+ }
149
+ catch (e) {
150
+ console.error("Error parsing message:", e);
151
+ }
152
+ }
153
+ async send(request) {
154
+ if (!this.socket) {
155
+ throw new Error("WebSocket not connected");
156
+ }
157
+ // Ensure request has a context_id so we can route the response
158
+ if (!request.context_id) {
159
+ request.context_id = uuidv4();
160
+ }
161
+ const source = new AudioSource();
162
+ this.sources.set(request.context_id, source);
163
+ // Also set as default source if none exists, for compatibility with simple tests
164
+ if (!this.defaultSource) {
165
+ this.defaultSource = source;
166
+ }
167
+ // Add output format from config if not present
168
+ if (!request.output_format && this.config) {
169
+ request.output_format = {
170
+ container: this.config.container,
171
+ encoding: this.config.encoding,
172
+ sample_rate: this.config.sampleRate,
173
+ };
174
+ }
175
+ // Fix camelCase to snake_case for output_format if needed
176
+ // The new API expects snake_case keys in JSON usually, but let's check.
177
+ // The GenerationRequest interface has `output_format`.
178
+ // The config passed to .websocket() uses `sampleRate`.
179
+ // We might need to map it.
180
+ if (request.output_format) {
181
+ // Ensure sample_rate is set (mapping from sampleRate)
182
+ if (request.output_format.sampleRate && !request.output_format.sample_rate) {
183
+ request.output_format.sample_rate = request.output_format.sampleRate;
184
+ delete request.output_format.sampleRate;
185
+ }
186
+ }
187
+ // Map camelCase request fields to snake_case if necessary?
188
+ // The old test uses `modelId`, `generationConfig`.
189
+ // The new API expects `model_id`, `generation_config`.
190
+ const payload = {
191
+ ...request,
192
+ model_id: request.modelId || request.model_id,
193
+ generation_config: request.generationConfig || request.generation_config,
194
+ context_id: request.context_id,
195
+ };
196
+ // Remove camelCase keys if they persist?
197
+ // JSON.stringify handles it, but we should clean up if we want to be strict.
198
+ // Also `voice` object. Old test: `voice: { mode: 'id', id: ... }`. New API: same.
199
+ this.socket.send(JSON.stringify(payload));
200
+ return {
201
+ source: source
202
+ };
203
+ }
204
+ disconnect() {
205
+ if (this.socket) {
206
+ this.socket.close();
207
+ }
208
+ }
209
+ }
210
+ class TTSWrapper {
211
+ constructor(client) {
212
+ this.client = client;
213
+ }
214
+ websocket(config) {
215
+ return new WebSocketWrapper(this.client, config);
216
+ }
217
+ async bytes(request, requestOptions) {
218
+ const params = {
219
+ model_id: request.modelId,
220
+ transcript: request.transcript,
221
+ voice: request.voice,
222
+ generation_config: request.generationConfig,
223
+ context_id: request.contextId,
224
+ };
225
+ if (request.outputFormat) {
226
+ params.output_format = {
227
+ ...request.outputFormat,
228
+ sample_rate: request.outputFormat.sampleRate,
229
+ bit_rate: request.outputFormat.bitRate,
230
+ };
231
+ // Remove camelCase keys
232
+ delete params.output_format.sampleRate;
233
+ delete params.output_format.bitRate;
234
+ }
235
+ const options = {};
236
+ if (requestOptions) {
237
+ if (requestOptions.timeoutInSeconds) {
238
+ options.timeout = requestOptions.timeoutInSeconds * 1000;
239
+ }
240
+ options.maxRetries = requestOptions.maxRetries;
241
+ options.headers = requestOptions.headers;
242
+ options.signal = requestOptions.abortSignal;
243
+ }
244
+ // @ts-ignore
245
+ return this.client.tts.synthesizeBytes(params, options);
246
+ }
247
+ }
248
+ /*
249
+ * CartesiaClient - deprecated backcompat class.
250
+ * New code should use Cartesia class directly instead.
251
+ */
252
+ class CartesiaClient {
253
+ constructor(options) {
254
+ this.client = new client_1.Cartesia(options);
255
+ this.tts = new TTSWrapper(this.client);
256
+ }
257
+ }
258
+ exports.CartesiaClient = CartesiaClient;
259
+ // Helper for generating UUIDs. Not cryptographically secure.
260
+ function uuidv4() {
261
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
262
+ var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
263
+ return v.toString(16);
264
+ });
265
+ }
266
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/backcompat/index.ts"],"names":[],"mappings":";;;;AAAA,oDAA2B;AAC3B,yCAAqC;AAErC,MAAM,WAAW;IAAjB;QACS,YAAO,GAAa,EAAE,CAAC;QACvB,WAAM,GAAiC,IAAI,CAAC;QAC7C,WAAM,GAAG,KAAK,CAAC;IAoEvB,CAAC;IAlEA,IAAI,CAAC,IAAY;QAChB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACxB,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,IAAI,CAAC,MAAM,EAAE,CAAC;YACd,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACpB,CAAC;IACF,CAAC;IAED,QAAQ;QACP,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACnB,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,IAAI,CAAC,MAAM,EAAE,CAAC;YACd,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACpB,CAAC;IACF,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,SAAuB;QACjC,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YAC/C,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,GAAG,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;QAClE,CAAC;QAED,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,CAAC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 this.waiter = null;
7
+ this.isDone = false;
8
+ }
9
+ push(data) {
10
+ this.buffers.push(data);
11
+ if (this.waiter) {
12
+ this.waiter();
13
+ this.waiter = null;
14
+ }
15
+ }
16
+ markDone() {
17
+ this.isDone = true;
18
+ if (this.waiter) {
19
+ this.waiter();
20
+ this.waiter = null;
21
+ }
22
+ }
23
+ async read(outBuffer) {
24
+ if (this.buffers.length === 0 && !this.isDone) {
25
+ await new Promise((resolve) => { this.waiter = resolve; });
26
+ }
27
+ if (this.buffers.length === 0 && this.isDone) {
28
+ return 0;
29
+ }
30
+ let totalFloatsRead = 0;
31
+ let outOffset = 0;
32
+ const maxFloats = outBuffer.length;
33
+ while (this.buffers.length > 0 && totalFloatsRead < maxFloats) {
34
+ const buf = this.buffers[0]; // ts not smart enough to check loop condition
35
+ const floatsInBuf = buf.length / 4;
36
+ const floatsNeeded = maxFloats - totalFloatsRead;
37
+ const floatsToCopy = Math.min(floatsInBuf, floatsNeeded);
38
+ const bytesToCopy = floatsToCopy * 4;
39
+ // Copy to outBuffer.
40
+ // Create a view on the buffer to read floats.
41
+ // We need to ensure byteOffset is a multiple of 4.
42
+ // If not, we must copy the buffer to a new one.
43
+ let srcFloats;
44
+ if (buf.byteOffset % 4 === 0) {
45
+ srcFloats = new Float32Array(buf.buffer, buf.byteOffset, floatsInBuf);
46
+ }
47
+ else {
48
+ const alignedBuf = new Uint8Array(buf);
49
+ srcFloats = new Float32Array(alignedBuf.buffer, alignedBuf.byteOffset, floatsInBuf);
50
+ }
51
+ outBuffer.set(srcFloats.subarray(0, floatsToCopy), outOffset);
52
+ totalFloatsRead += floatsToCopy;
53
+ outOffset += floatsToCopy;
54
+ if (floatsToCopy < floatsInBuf) {
55
+ // We didn't use the whole buffer. Update it.
56
+ this.buffers[0] = buf.subarray(bytesToCopy);
57
+ }
58
+ else {
59
+ // We used the whole buffer. Remove it.
60
+ this.buffers.shift();
61
+ }
62
+ }
63
+ return totalFloatsRead;
64
+ }
65
+ }
66
+ class WebSocketWrapper {
67
+ constructor(client, config) {
68
+ this.socket = null;
69
+ this.sources = new Map();
70
+ // Fallback source for messages without context_id or if we just want to capture everything (legacy behavior?)
71
+ // The original test didn't use context_id explicitly in send() but expected a response source.
72
+ // We'll map context_id to source.
73
+ this.defaultSource = null;
74
+ this.client = client;
75
+ this.config = config;
76
+ }
77
+ async connect() {
78
+ const baseURL = this.client.baseURL;
79
+ // Construct WebSocket URL
80
+ // baseURL is like https://api.cartesia.ai
81
+ let urlStr = baseURL.replace(/^http/, "ws");
82
+ if (!urlStr.includes("/tts/websocket")) {
83
+ if (urlStr.endsWith("/")) {
84
+ urlStr += "tts/websocket";
85
+ }
86
+ else {
87
+ urlStr += "/tts/websocket";
88
+ }
89
+ }
90
+ const url = new URL(urlStr);
91
+ const headers = {
92
+ "cartesia-version": "2025-04-16",
93
+ };
94
+ if (this.client.apiKey) {
95
+ headers["Authorization"] = `Bearer ${this.client.apiKey}`;
96
+ }
97
+ this.socket = new WebSocket(url.toString(), {
98
+ headers: headers,
99
+ });
100
+ return new Promise((resolve, reject) => {
101
+ this.socket.on("open", () => {
102
+ console.log("WebSocket connected.");
103
+ resolve();
104
+ });
105
+ this.socket.on("error", (err) => {
106
+ console.error("WebSocket error:", err);
107
+ reject(err);
108
+ });
109
+ this.socket.on("message", (data) => {
110
+ this.handleMessage(data);
111
+ });
112
+ this.socket.on("close", () => {
113
+ console.log("WebSocket closed.");
114
+ this.sources.forEach((s) => { s.markDone(); });
115
+ if (this.defaultSource)
116
+ this.defaultSource.markDone();
117
+ });
118
+ });
119
+ }
120
+ handleMessage(data) {
121
+ try {
122
+ const str = data.toString();
123
+ const msg = JSON.parse(str);
124
+ const contextId = msg.context_id;
125
+ let source = contextId ? this.sources.get(contextId) : this.defaultSource;
126
+ // If we received a message for a context we don't know about, and we have a default source, use it
127
+ if (!source && this.defaultSource) {
128
+ source = this.defaultSource;
129
+ }
130
+ if (msg.type === "chunk" && msg.data) {
131
+ const audioData = Buffer.from(msg.data, "base64");
132
+ if (source)
133
+ source.push(audioData);
134
+ }
135
+ else if (msg.type === "done") {
136
+ if (source)
137
+ source.markDone();
138
+ }
139
+ else if (msg.type === "error") {
140
+ console.error("Server error:", msg);
141
+ if (source)
142
+ source.markDone(); // Fail the stream?
143
+ }
144
+ }
145
+ catch (e) {
146
+ console.error("Error parsing message:", e);
147
+ }
148
+ }
149
+ async send(request) {
150
+ if (!this.socket) {
151
+ throw new Error("WebSocket not connected");
152
+ }
153
+ // Ensure request has a context_id so we can route the response
154
+ if (!request.context_id) {
155
+ request.context_id = uuidv4();
156
+ }
157
+ const source = new AudioSource();
158
+ this.sources.set(request.context_id, source);
159
+ // Also set as default source if none exists, for compatibility with simple tests
160
+ if (!this.defaultSource) {
161
+ this.defaultSource = source;
162
+ }
163
+ // Add output format from config if not present
164
+ if (!request.output_format && this.config) {
165
+ request.output_format = {
166
+ container: this.config.container,
167
+ encoding: this.config.encoding,
168
+ sample_rate: this.config.sampleRate,
169
+ };
170
+ }
171
+ // Fix camelCase to snake_case for output_format if needed
172
+ // The new API expects snake_case keys in JSON usually, but let's check.
173
+ // The GenerationRequest interface has `output_format`.
174
+ // The config passed to .websocket() uses `sampleRate`.
175
+ // We might need to map it.
176
+ if (request.output_format) {
177
+ // Ensure sample_rate is set (mapping from sampleRate)
178
+ if (request.output_format.sampleRate && !request.output_format.sample_rate) {
179
+ request.output_format.sample_rate = request.output_format.sampleRate;
180
+ delete request.output_format.sampleRate;
181
+ }
182
+ }
183
+ // Map camelCase request fields to snake_case if necessary?
184
+ // The old test uses `modelId`, `generationConfig`.
185
+ // The new API expects `model_id`, `generation_config`.
186
+ const payload = {
187
+ ...request,
188
+ model_id: request.modelId || request.model_id,
189
+ generation_config: request.generationConfig || request.generation_config,
190
+ context_id: request.context_id,
191
+ };
192
+ // Remove camelCase keys if they persist?
193
+ // JSON.stringify handles it, but we should clean up if we want to be strict.
194
+ // Also `voice` object. Old test: `voice: { mode: 'id', id: ... }`. New API: same.
195
+ this.socket.send(JSON.stringify(payload));
196
+ return {
197
+ source: source
198
+ };
199
+ }
200
+ disconnect() {
201
+ if (this.socket) {
202
+ this.socket.close();
203
+ }
204
+ }
205
+ }
206
+ class TTSWrapper {
207
+ constructor(client) {
208
+ this.client = client;
209
+ }
210
+ websocket(config) {
211
+ return new WebSocketWrapper(this.client, config);
212
+ }
213
+ async bytes(request, requestOptions) {
214
+ const params = {
215
+ model_id: request.modelId,
216
+ transcript: request.transcript,
217
+ voice: request.voice,
218
+ generation_config: request.generationConfig,
219
+ context_id: request.contextId,
220
+ };
221
+ if (request.outputFormat) {
222
+ params.output_format = {
223
+ ...request.outputFormat,
224
+ sample_rate: request.outputFormat.sampleRate,
225
+ bit_rate: request.outputFormat.bitRate,
226
+ };
227
+ // Remove camelCase keys
228
+ delete params.output_format.sampleRate;
229
+ delete params.output_format.bitRate;
230
+ }
231
+ const options = {};
232
+ if (requestOptions) {
233
+ if (requestOptions.timeoutInSeconds) {
234
+ options.timeout = requestOptions.timeoutInSeconds * 1000;
235
+ }
236
+ options.maxRetries = requestOptions.maxRetries;
237
+ options.headers = requestOptions.headers;
238
+ options.signal = requestOptions.abortSignal;
239
+ }
240
+ // @ts-ignore
241
+ return this.client.tts.synthesizeBytes(params, options);
242
+ }
243
+ }
244
+ /*
245
+ * CartesiaClient - deprecated backcompat class.
246
+ * New code should use Cartesia class directly instead.
247
+ */
248
+ export class CartesiaClient {
249
+ constructor(options) {
250
+ this.client = new Cartesia(options);
251
+ this.tts = new TTSWrapper(this.client);
252
+ }
253
+ }
254
+ // Helper for generating UUIDs. Not cryptographically secure.
255
+ function uuidv4() {
256
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
257
+ var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
258
+ return v.toString(16);
259
+ });
260
+ }
261
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs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cAAc,CAAC,UAAU,CAAC;YAC/C,OAAO,CAAC,OAAO,GAAG,cAAc,CAAC,OAAO,CAAC;YACzC,OAAO,CAAC,MAAM,GAAG,cAAc,CAAC,WAAW,CAAC;QAC7C,CAAC;QAED,aAAa;QACb,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,eAAe,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACzD,CAAC;CACD;AAED;;;GAGG;AACH,MAAM,OAAO,cAAc;IAI1B,YAAY,OAAY;QACvB,IAAI,CAAC,MAAM,GAAG,IAAI,QAAQ,CAAC,OAAO,CAAC,CAAC;QACpC,IAAI,CAAC,GAAG,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACxC,CAAC;CACD;AAGD,6DAA6D;AAC7D,SAAS,MAAM;IACd,OAAO,sCAAsC,CAAC,OAAO,CAAC,OAAO,EAAE,UAAS,CAAC;QACxE,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;QACnE,OAAO,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;AACJ,CAAC"}
package/index.d.mts CHANGED
@@ -2,6 +2,7 @@ export { Cartesia as default } from "./client.mjs";
2
2
  export { type Uploadable, toFile } from "./core/uploads.mjs";
3
3
  export { APIPromise } from "./core/api-promise.mjs";
4
4
  export { Cartesia, type ClientOptions } from "./client.mjs";
5
+ export { CartesiaClient } from "./backcompat/index.mjs";
5
6
  export { PagePromise } from "./core/pagination.mjs";
6
7
  export { CartesiaError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "./core/error.mjs";
7
8
  //# sourceMappingURL=index.d.mts.map
package/index.d.mts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"OAEO,EAAE,QAAQ,IAAI,OAAO,EAAE;OAEvB,EAAE,KAAK,UAAU,EAAE,MAAM,EAAE;OAC3B,EAAE,UAAU,EAAE;OACd,EAAE,QAAQ,EAAE,KAAK,aAAa,EAAE;OAChC,EAAE,WAAW,EAAE;OACf,EACL,aAAa,EACb,QAAQ,EACR,kBAAkB,EAClB,yBAAyB,EACzB,iBAAiB,EACjB,aAAa,EACb,aAAa,EACb,cAAc,EACd,eAAe,EACf,mBAAmB,EACnB,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,GACzB"}
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"OAEO,EAAE,QAAQ,IAAI,OAAO,EAAE;OAEvB,EAAE,KAAK,UAAU,EAAE,MAAM,EAAE;OAC3B,EAAE,UAAU,EAAE;OACd,EAAE,QAAQ,EAAE,KAAK,aAAa,EAAE;OAChC,EAAE,cAAc,EAAE;OAClB,EAAE,WAAW,EAAE;OACf,EACL,aAAa,EACb,QAAQ,EACR,kBAAkB,EAClB,yBAAyB,EACzB,iBAAiB,EACjB,aAAa,EACb,aAAa,EACb,cAAc,EACd,eAAe,EACf,mBAAmB,EACnB,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,GACzB"}
package/index.d.ts CHANGED
@@ -2,6 +2,7 @@ export { Cartesia as default } from "./client.js";
2
2
  export { type Uploadable, toFile } from "./core/uploads.js";
3
3
  export { APIPromise } from "./core/api-promise.js";
4
4
  export { Cartesia, type ClientOptions } from "./client.js";
5
+ export { CartesiaClient } from "./backcompat/index.js";
5
6
  export { PagePromise } from "./core/pagination.js";
6
7
  export { CartesiaError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "./core/error.js";
7
8
  //# sourceMappingURL=index.d.ts.map
package/index.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"OAEO,EAAE,QAAQ,IAAI,OAAO,EAAE;OAEvB,EAAE,KAAK,UAAU,EAAE,MAAM,EAAE;OAC3B,EAAE,UAAU,EAAE;OACd,EAAE,QAAQ,EAAE,KAAK,aAAa,EAAE;OAChC,EAAE,WAAW,EAAE;OACf,EACL,aAAa,EACb,QAAQ,EACR,kBAAkB,EAClB,yBAAyB,EACzB,iBAAiB,EACjB,aAAa,EACb,aAAa,EACb,cAAc,EACd,eAAe,EACf,mBAAmB,EACnB,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,GACzB"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"OAEO,EAAE,QAAQ,IAAI,OAAO,EAAE;OAEvB,EAAE,KAAK,UAAU,EAAE,MAAM,EAAE;OAC3B,EAAE,UAAU,EAAE;OACd,EAAE,QAAQ,EAAE,KAAK,aAAa,EAAE;OAChC,EAAE,cAAc,EAAE;OAClB,EAAE,WAAW,EAAE;OACf,EACL,aAAa,EACb,QAAQ,EACR,kBAAkB,EAClB,yBAAyB,EACzB,iBAAiB,EACjB,aAAa,EACb,aAAa,EACb,cAAc,EACd,eAAe,EACf,mBAAmB,EACnB,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,GACzB"}
package/index.js CHANGED
@@ -4,7 +4,7 @@ exports = module.exports = function (...args) {
4
4
  return new exports.default(...args)
5
5
  }
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.UnprocessableEntityError = exports.PermissionDeniedError = exports.InternalServerError = exports.AuthenticationError = exports.BadRequestError = exports.RateLimitError = exports.ConflictError = exports.NotFoundError = exports.APIUserAbortError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIError = exports.CartesiaError = exports.PagePromise = exports.Cartesia = exports.APIPromise = exports.toFile = exports.default = void 0;
7
+ exports.UnprocessableEntityError = exports.PermissionDeniedError = exports.InternalServerError = exports.AuthenticationError = exports.BadRequestError = exports.RateLimitError = exports.ConflictError = exports.NotFoundError = exports.APIUserAbortError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIError = exports.CartesiaError = exports.PagePromise = exports.CartesiaClient = exports.Cartesia = exports.APIPromise = exports.toFile = exports.default = void 0;
8
8
  var client_1 = require("./client.js");
9
9
  Object.defineProperty(exports, "default", { enumerable: true, get: function () { return client_1.Cartesia; } });
10
10
  var uploads_1 = require("./core/uploads.js");
@@ -13,6 +13,8 @@ var api_promise_1 = require("./core/api-promise.js");
13
13
  Object.defineProperty(exports, "APIPromise", { enumerable: true, get: function () { return api_promise_1.APIPromise; } });
14
14
  var client_2 = require("./client.js");
15
15
  Object.defineProperty(exports, "Cartesia", { enumerable: true, get: function () { return client_2.Cartesia; } });
16
+ var backcompat_1 = require("./backcompat/index.js");
17
+ Object.defineProperty(exports, "CartesiaClient", { enumerable: true, get: function () { return backcompat_1.CartesiaClient; } });
16
18
  var pagination_1 = require("./core/pagination.js");
17
19
  Object.defineProperty(exports, "PagePromise", { enumerable: true, get: function () { return pagination_1.PagePromise; } });
18
20
  var error_1 = require("./core/error.js");
package/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,sCAA+C;AAAtC,iGAAA,QAAQ,OAAW;AAE5B,6CAAyD;AAA/B,iGAAA,MAAM,OAAA;AAChC,qDAAgD;AAAvC,yGAAA,UAAU,OAAA;AACnB,sCAAwD;AAA/C,kGAAA,QAAQ,OAAA;AACjB,mDAAgD;AAAvC,yGAAA,WAAW,OAAA;AACpB,yCAcsB;AAbpB,sGAAA,aAAa,OAAA;AACb,iGAAA,QAAQ,OAAA;AACR,2GAAA,kBAAkB,OAAA;AAClB,kHAAA,yBAAyB,OAAA;AACzB,0GAAA,iBAAiB,OAAA;AACjB,sGAAA,aAAa,OAAA;AACb,sGAAA,aAAa,OAAA;AACb,uGAAA,cAAc,OAAA;AACd,wGAAA,eAAe,OAAA;AACf,4GAAA,mBAAmB,OAAA;AACnB,4GAAA,mBAAmB,OAAA;AACnB,8GAAA,qBAAqB,OAAA;AACrB,iHAAA,wBAAwB,OAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,sCAA+C;AAAtC,iGAAA,QAAQ,OAAW;AAE5B,6CAAyD;AAA/B,iGAAA,MAAM,OAAA;AAChC,qDAAgD;AAAvC,yGAAA,UAAU,OAAA;AACnB,sCAAwD;AAA/C,kGAAA,QAAQ,OAAA;AACjB,oDAA8C;AAArC,4GAAA,cAAc,OAAA;AACvB,mDAAgD;AAAvC,yGAAA,WAAW,OAAA;AACpB,yCAcsB;AAbpB,sGAAA,aAAa,OAAA;AACb,iGAAA,QAAQ,OAAA;AACR,2GAAA,kBAAkB,OAAA;AAClB,kHAAA,yBAAyB,OAAA;AACzB,0GAAA,iBAAiB,OAAA;AACjB,sGAAA,aAAa,OAAA;AACb,sGAAA,aAAa,OAAA;AACb,uGAAA,cAAc,OAAA;AACd,wGAAA,eAAe,OAAA;AACf,4GAAA,mBAAmB,OAAA;AACnB,4GAAA,mBAAmB,OAAA;AACnB,8GAAA,qBAAqB,OAAA;AACrB,iHAAA,wBAAwB,OAAA"}
package/index.mjs CHANGED
@@ -3,6 +3,7 @@ export { Cartesia as default } from "./client.mjs";
3
3
  export { toFile } from "./core/uploads.mjs";
4
4
  export { APIPromise } from "./core/api-promise.mjs";
5
5
  export { Cartesia } from "./client.mjs";
6
+ export { CartesiaClient } from "./backcompat/index.mjs";
6
7
  export { PagePromise } from "./core/pagination.mjs";
7
8
  export { CartesiaError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "./core/error.mjs";
8
9
  //# sourceMappingURL=index.mjs.map
package/index.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,QAAQ,IAAI,OAAO,EAAE;OAEvB,EAAmB,MAAM,EAAE;OAC3B,EAAE,UAAU,EAAE;OACd,EAAE,QAAQ,EAAsB;OAChC,EAAE,WAAW,EAAE;OACf,EACL,aAAa,EACb,QAAQ,EACR,kBAAkB,EAClB,yBAAyB,EACzB,iBAAiB,EACjB,aAAa,EACb,aAAa,EACb,cAAc,EACd,eAAe,EACf,mBAAmB,EACnB,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,GACzB"}
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,QAAQ,IAAI,OAAO,EAAE;OAEvB,EAAmB,MAAM,EAAE;OAC3B,EAAE,UAAU,EAAE;OACd,EAAE,QAAQ,EAAsB;OAChC,EAAE,cAAc,EAAE;OAClB,EAAE,WAAW,EAAE;OACf,EACL,aAAa,EACb,QAAQ,EACR,kBAAkB,EAClB,yBAAyB,EACzB,iBAAiB,EACjB,aAAa,EACb,aAAa,EACb,cAAc,EACd,eAAe,EACf,mBAAmB,EACnB,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,GACzB"}
package/internal/tslib.js CHANGED
@@ -5,6 +5,7 @@ exports.__classPrivateFieldSet = __classPrivateFieldSet;
5
5
  exports.__classPrivateFieldGet = __classPrivateFieldGet;
6
6
  exports.__importStar = __importStar;
7
7
  exports.__exportStar = __exportStar;
8
+ exports.__importDefault = __importDefault;
8
9
  function __classPrivateFieldSet(receiver, state, value, kind, f) {
9
10
  if (kind === "m")
10
11
  throw new TypeError("Private method is not writable");
@@ -79,3 +80,6 @@ function __exportStar(m, o) {
79
80
  if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
80
81
  __createBinding(o, m, p);
81
82
  }
83
+ function __importDefault(mod) {
84
+ return mod && mod.__esModule ? mod : { default: mod };
85
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cartesia/cartesia-js",
3
- "version": "3.0.0-b4",
3
+ "version": "3.0.0-b5",
4
4
  "description": "The official TypeScript library for the Cartesia API",
5
5
  "author": "Cartesia <>",
6
6
  "types": "./index.d.ts",
@@ -52,6 +52,16 @@
52
52
  "./api-promise.mjs": {
53
53
  "default": "./api-promise.mjs"
54
54
  },
55
+ "./backcompat/*.mjs": {
56
+ "default": "./backcompat/*.mjs"
57
+ },
58
+ "./backcompat/*.js": {
59
+ "default": "./backcompat/*.js"
60
+ },
61
+ "./backcompat/*": {
62
+ "import": "./backcompat/*.mjs",
63
+ "require": "./backcompat/*.js"
64
+ },
55
65
  "./client": {
56
66
  "import": "./client.mjs",
57
67
  "require": "./client.js"
@@ -0,0 +1,302 @@
1
+ import WebSocket from "ws";
2
+ import { Cartesia } from "../client";
3
+
4
+ class AudioSource {
5
+ private buffers: Buffer[] = [];
6
+ private waiter: ((val?: any) => void) | null = null;
7
+ public isDone = false;
8
+
9
+ push(data: Buffer) {
10
+ this.buffers.push(data);
11
+ if (this.waiter) {
12
+ this.waiter();
13
+ this.waiter = null;
14
+ }
15
+ }
16
+
17
+ markDone() {
18
+ this.isDone = true;
19
+ if (this.waiter) {
20
+ this.waiter();
21
+ this.waiter = null;
22
+ }
23
+ }
24
+
25
+ async read(outBuffer: Float32Array): Promise<number> {
26
+ if (this.buffers.length === 0 && !this.isDone) {
27
+ await new Promise<void>((resolve) => { this.waiter = resolve; });
28
+ }
29
+
30
+ if (this.buffers.length === 0 && this.isDone) {
31
+ return 0;
32
+ }
33
+
34
+ let totalFloatsRead = 0;
35
+ let outOffset = 0;
36
+ const maxFloats = outBuffer.length;
37
+
38
+ while (this.buffers.length > 0 && totalFloatsRead < maxFloats) {
39
+ const buf = this.buffers[0] as Buffer; // ts not smart enough to check loop condition
40
+ const floatsInBuf = buf.length / 4;
41
+ const floatsNeeded = maxFloats - totalFloatsRead;
42
+
43
+ const floatsToCopy = Math.min(floatsInBuf, floatsNeeded);
44
+ const bytesToCopy = floatsToCopy * 4;
45
+
46
+ // Copy to outBuffer.
47
+ // Create a view on the buffer to read floats.
48
+
49
+ // We need to ensure byteOffset is a multiple of 4.
50
+ // If not, we must copy the buffer to a new one.
51
+ let srcFloats: Float32Array;
52
+ if (buf.byteOffset % 4 === 0) {
53
+ srcFloats = new Float32Array(buf.buffer, buf.byteOffset, floatsInBuf);
54
+ } else {
55
+ const alignedBuf = new Uint8Array(buf);
56
+ srcFloats = new Float32Array(alignedBuf.buffer, alignedBuf.byteOffset, floatsInBuf);
57
+ }
58
+
59
+ outBuffer.set(srcFloats.subarray(0, floatsToCopy), outOffset);
60
+
61
+ totalFloatsRead += floatsToCopy;
62
+ outOffset += floatsToCopy;
63
+
64
+ if (floatsToCopy < floatsInBuf) {
65
+ // We didn't use the whole buffer. Update it.
66
+ this.buffers[0] = buf.subarray(bytesToCopy);
67
+ } else {
68
+ // We used the whole buffer. Remove it.
69
+ this.buffers.shift();
70
+ }
71
+ }
72
+
73
+ return totalFloatsRead;
74
+ }
75
+ }
76
+
77
+ class WebSocketWrapper {
78
+ private client: Cartesia;
79
+ private config: any;
80
+ private socket: WebSocket | null = null;
81
+ private sources: Map<string, AudioSource> = new Map();
82
+ // Fallback source for messages without context_id or if we just want to capture everything (legacy behavior?)
83
+ // The original test didn't use context_id explicitly in send() but expected a response source.
84
+ // We'll map context_id to source.
85
+ private defaultSource: AudioSource | null = null;
86
+
87
+ constructor(client: Cartesia, config: any) {
88
+ this.client = client;
89
+ this.config = config;
90
+ }
91
+
92
+ async connect() {
93
+ const baseURL = this.client.baseURL;
94
+ // Construct WebSocket URL
95
+ // baseURL is like https://api.cartesia.ai
96
+ let urlStr = baseURL.replace(/^http/, "ws");
97
+ if (!urlStr.includes("/tts/websocket")) {
98
+ if (urlStr.endsWith("/")) {
99
+ urlStr += "tts/websocket";
100
+ } else {
101
+ urlStr += "/tts/websocket";
102
+ }
103
+ }
104
+
105
+ const url = new URL(urlStr);
106
+
107
+ const headers: any = {
108
+ "cartesia-version": "2025-04-16",
109
+ };
110
+ if (this.client.apiKey) {
111
+ headers["Authorization"] = `Bearer ${this.client.apiKey}`;
112
+ }
113
+
114
+ this.socket = new WebSocket(url.toString(), {
115
+ headers: headers,
116
+ });
117
+
118
+ return new Promise<void>((resolve, reject) => {
119
+ this.socket!.on("open", () => {
120
+ console.log("WebSocket connected.");
121
+ resolve();
122
+ });
123
+
124
+ this.socket!.on("error", (err) => {
125
+ console.error("WebSocket error:", err);
126
+ reject(err);
127
+ });
128
+
129
+ this.socket!.on("message", (data) => {
130
+ this.handleMessage(data);
131
+ });
132
+
133
+ this.socket!.on("close", () => {
134
+ console.log("WebSocket closed.");
135
+ this.sources.forEach((s) => { s.markDone(); });
136
+ if (this.defaultSource) this.defaultSource.markDone();
137
+ });
138
+ });
139
+ }
140
+
141
+ private handleMessage(data: WebSocket.Data) {
142
+ try {
143
+ const str = data.toString();
144
+ const msg = JSON.parse(str);
145
+
146
+ const contextId = msg.context_id;
147
+ let source = contextId ? this.sources.get(contextId) : this.defaultSource;
148
+
149
+ // If we received a message for a context we don't know about, and we have a default source, use it
150
+ if (!source && this.defaultSource) {
151
+ source = this.defaultSource;
152
+ }
153
+
154
+ if (msg.type === "chunk" && msg.data) {
155
+ const audioData = Buffer.from(msg.data, "base64");
156
+ if (source) source.push(audioData);
157
+ } else if (msg.type === "done") {
158
+ if (source) source.markDone();
159
+ } else if (msg.type === "error") {
160
+ console.error("Server error:", msg);
161
+ if (source) source.markDone(); // Fail the stream?
162
+ }
163
+ } catch (e) {
164
+ console.error("Error parsing message:", e);
165
+ }
166
+ }
167
+
168
+ async send(request: any) {
169
+ if (!this.socket) {
170
+ throw new Error("WebSocket not connected");
171
+ }
172
+
173
+ // Ensure request has a context_id so we can route the response
174
+ if (!request.context_id) {
175
+ request.context_id = uuidv4();
176
+ }
177
+
178
+ const source = new AudioSource();
179
+ this.sources.set(request.context_id, source);
180
+ // Also set as default source if none exists, for compatibility with simple tests
181
+ if (!this.defaultSource) {
182
+ this.defaultSource = source;
183
+ }
184
+
185
+ // Add output format from config if not present
186
+ if (!request.output_format && this.config) {
187
+ request.output_format = {
188
+ container: this.config.container,
189
+ encoding: this.config.encoding,
190
+ sample_rate: this.config.sampleRate,
191
+ };
192
+ }
193
+ // Fix camelCase to snake_case for output_format if needed
194
+ // The new API expects snake_case keys in JSON usually, but let's check.
195
+ // The GenerationRequest interface has `output_format`.
196
+ // The config passed to .websocket() uses `sampleRate`.
197
+ // We might need to map it.
198
+
199
+ if (request.output_format) {
200
+ // Ensure sample_rate is set (mapping from sampleRate)
201
+ if (request.output_format.sampleRate && !request.output_format.sample_rate) {
202
+ request.output_format.sample_rate = request.output_format.sampleRate;
203
+ delete request.output_format.sampleRate;
204
+ }
205
+ }
206
+
207
+ // Map camelCase request fields to snake_case if necessary?
208
+ // The old test uses `modelId`, `generationConfig`.
209
+ // The new API expects `model_id`, `generation_config`.
210
+ const payload = {
211
+ ...request,
212
+ model_id: request.modelId || request.model_id,
213
+ generation_config: request.generationConfig || request.generation_config,
214
+ context_id: request.context_id,
215
+ };
216
+ // Remove camelCase keys if they persist?
217
+ // JSON.stringify handles it, but we should clean up if we want to be strict.
218
+
219
+ // Also `voice` object. Old test: `voice: { mode: 'id', id: ... }`. New API: same.
220
+
221
+ this.socket.send(JSON.stringify(payload));
222
+
223
+ return {
224
+ source: source
225
+ };
226
+ }
227
+
228
+ disconnect() {
229
+ if (this.socket) {
230
+ this.socket.close();
231
+ }
232
+ }
233
+ }
234
+
235
+ class TTSWrapper {
236
+ private client: Cartesia;
237
+
238
+ constructor(client: Cartesia) {
239
+ this.client = client;
240
+ }
241
+
242
+ websocket(config: any) {
243
+ return new WebSocketWrapper(this.client, config);
244
+ }
245
+
246
+ async bytes(request: any, requestOptions?: any) {
247
+ const params: any = {
248
+ model_id: request.modelId,
249
+ transcript: request.transcript,
250
+ voice: request.voice,
251
+ generation_config: request.generationConfig,
252
+ context_id: request.contextId,
253
+ };
254
+
255
+ if (request.outputFormat) {
256
+ params.output_format = {
257
+ ...request.outputFormat,
258
+ sample_rate: request.outputFormat.sampleRate,
259
+ bit_rate: request.outputFormat.bitRate,
260
+ };
261
+ // Remove camelCase keys
262
+ delete params.output_format.sampleRate;
263
+ delete params.output_format.bitRate;
264
+ }
265
+
266
+ const options: any = {};
267
+ if (requestOptions) {
268
+ if (requestOptions.timeoutInSeconds) {
269
+ options.timeout = requestOptions.timeoutInSeconds * 1000;
270
+ }
271
+ options.maxRetries = requestOptions.maxRetries;
272
+ options.headers = requestOptions.headers;
273
+ options.signal = requestOptions.abortSignal;
274
+ }
275
+
276
+ // @ts-ignore
277
+ return this.client.tts.synthesizeBytes(params, options);
278
+ }
279
+ }
280
+
281
+ /*
282
+ * CartesiaClient - deprecated backcompat class.
283
+ * New code should use Cartesia class directly instead.
284
+ */
285
+ export class CartesiaClient {
286
+ private client: Cartesia;
287
+ public tts: TTSWrapper;
288
+
289
+ constructor(options: any) {
290
+ this.client = new Cartesia(options);
291
+ this.tts = new TTSWrapper(this.client);
292
+ }
293
+ }
294
+
295
+
296
+ // Helper for generating UUIDs. Not cryptographically secure.
297
+ function uuidv4() {
298
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
299
+ var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
300
+ return v.toString(16);
301
+ });
302
+ }
package/src/index.ts CHANGED
@@ -5,6 +5,7 @@ export { Cartesia as default } from './client';
5
5
  export { type Uploadable, toFile } from './core/uploads';
6
6
  export { APIPromise } from './core/api-promise';
7
7
  export { Cartesia, type ClientOptions } from './client';
8
+ export { CartesiaClient } from './backcompat';
8
9
  export { PagePromise } from './core/pagination';
9
10
  export {
10
11
  CartesiaError,
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const VERSION = '3.0.0-b4'; // x-release-please-version
1
+ export const VERSION = '3.0.0-b5'; // x-release-please-version
package/version.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "3.0.0-b4";
1
+ export declare const VERSION = "3.0.0-b5";
2
2
  //# sourceMappingURL=version.d.mts.map
package/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "3.0.0-b4";
1
+ export declare const VERSION = "3.0.0-b5";
2
2
  //# sourceMappingURL=version.d.ts.map
package/version.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VERSION = void 0;
4
- exports.VERSION = '3.0.0-b4'; // x-release-please-version
4
+ exports.VERSION = '3.0.0-b5'; // x-release-please-version
5
5
  //# sourceMappingURL=version.js.map
package/version.mjs CHANGED
@@ -1,2 +1,2 @@
1
- export const VERSION = '3.0.0-b4'; // x-release-please-version
1
+ export const VERSION = '3.0.0-b5'; // x-release-please-version
2
2
  //# sourceMappingURL=version.mjs.map