@cartesia/cartesia-js 0.0.3 → 1.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/.turbo/turbo-build.log +68 -38
  2. package/CHANGELOG.md +12 -0
  3. package/README.md +123 -16
  4. package/dist/chunk-3FL2SNIR.js +17 -0
  5. package/dist/chunk-3GBZUGUD.js +17 -0
  6. package/dist/chunk-4RMSIQLG.js +25 -0
  7. package/dist/chunk-BCQ63627.js +32 -0
  8. package/dist/chunk-JOHSCOLW.js +106 -0
  9. package/dist/chunk-LYPTISWL.js +75 -0
  10. package/dist/chunk-NDNN326Q.js +207 -0
  11. package/dist/chunk-WBK6LLXX.js +58 -0
  12. package/dist/chunk-WE63M7PJ.js +119 -0
  13. package/dist/{chunk-HNLIBHEN.mjs → chunk-WIFMLPT5.js} +31 -16
  14. package/dist/chunk-X7SJMF2R.js +22 -0
  15. package/dist/index.cjs +652 -0
  16. package/dist/index.d.cts +10 -0
  17. package/dist/index.d.ts +10 -0
  18. package/dist/index.js +20 -0
  19. package/dist/lib/client.cjs +89 -0
  20. package/dist/lib/client.d.cts +11 -0
  21. package/dist/lib/client.d.ts +2 -0
  22. package/dist/lib/client.js +7 -42
  23. package/dist/lib/constants.cjs +42 -0
  24. package/dist/lib/constants.d.cts +4 -0
  25. package/dist/lib/constants.d.ts +2 -3
  26. package/dist/lib/constants.js +8 -37
  27. package/dist/lib/index.cjs +531 -0
  28. package/dist/lib/index.d.cts +16 -0
  29. package/dist/lib/index.d.ts +6 -2
  30. package/dist/lib/index.js +13 -409
  31. package/dist/react/index.cjs +846 -0
  32. package/dist/react/index.d.cts +33 -0
  33. package/dist/react/index.d.ts +20 -13
  34. package/dist/react/index.js +161 -501
  35. package/dist/react/utils.cjs +57 -0
  36. package/dist/react/utils.d.cts +7 -0
  37. package/dist/react/utils.d.ts +7 -0
  38. package/dist/react/utils.js +7 -0
  39. package/dist/tts/index.cjs +470 -0
  40. package/dist/tts/index.d.cts +17 -0
  41. package/dist/tts/index.d.ts +17 -0
  42. package/dist/tts/index.js +12 -0
  43. package/dist/tts/player.cjs +198 -0
  44. package/dist/tts/player.d.cts +43 -0
  45. package/dist/tts/player.d.ts +43 -0
  46. package/dist/tts/player.js +8 -0
  47. package/dist/tts/source.cjs +167 -0
  48. package/dist/tts/source.d.cts +53 -0
  49. package/dist/tts/source.d.ts +53 -0
  50. package/dist/tts/source.js +7 -0
  51. package/dist/{audio/utils.js → tts/utils.cjs} +13 -54
  52. package/dist/tts/utils.d.cts +67 -0
  53. package/dist/tts/utils.d.ts +67 -0
  54. package/dist/{audio/utils.mjs → tts/utils.js} +2 -6
  55. package/dist/tts/websocket.cjs +453 -0
  56. package/dist/tts/websocket.d.cts +53 -0
  57. package/dist/tts/websocket.d.ts +53 -0
  58. package/dist/tts/websocket.js +11 -0
  59. package/dist/types/index.cjs +18 -0
  60. package/dist/types/index.d.cts +55 -0
  61. package/dist/types/index.d.ts +50 -1
  62. package/dist/types/index.js +1 -18
  63. package/dist/voices/index.cjs +155 -0
  64. package/dist/voices/index.d.cts +12 -0
  65. package/dist/voices/index.d.ts +12 -0
  66. package/dist/voices/index.js +9 -0
  67. package/package.json +11 -7
  68. package/src/index.ts +4 -0
  69. package/src/lib/client.ts +14 -1
  70. package/src/lib/constants.ts +13 -3
  71. package/src/lib/index.ts +6 -3
  72. package/src/react/index.ts +167 -75
  73. package/src/react/utils.ts +11 -0
  74. package/src/tts/index.ts +17 -0
  75. package/src/tts/player.ts +109 -0
  76. package/src/tts/source.ts +98 -0
  77. package/src/{audio → tts}/utils.ts +19 -97
  78. package/src/tts/websocket.ts +210 -0
  79. package/src/types/index.ts +63 -0
  80. package/src/voices/index.ts +47 -0
  81. package/dist/audio/index.d.mts +0 -5
  82. package/dist/audio/index.d.ts +0 -5
  83. package/dist/audio/index.js +0 -396
  84. package/dist/audio/index.mjs +0 -9
  85. package/dist/audio/utils.d.mts +0 -5
  86. package/dist/audio/utils.d.ts +0 -5
  87. package/dist/chunk-3CYTAFLF.mjs +0 -262
  88. package/dist/chunk-FRIBQZPN.mjs +0 -113
  89. package/dist/chunk-XSFPHPPG.mjs +0 -18
  90. package/dist/index-DSBmfK9-.d.mts +0 -158
  91. package/dist/index-qwAyxV5I.d.ts +0 -158
  92. package/dist/lib/client.d.mts +0 -9
  93. package/dist/lib/client.mjs +0 -7
  94. package/dist/lib/constants.d.mts +0 -5
  95. package/dist/lib/constants.mjs +0 -10
  96. package/dist/lib/index.d.mts +0 -12
  97. package/dist/lib/index.mjs +0 -19
  98. package/dist/react/index.d.mts +0 -26
  99. package/dist/react/index.mjs +0 -130
  100. package/dist/types/index.d.mts +0 -6
  101. package/index.ts +0 -3
  102. package/src/audio/index.ts +0 -282
  103. /package/dist/{types/index.mjs → chunk-FXPGR372.js} +0 -0
@@ -0,0 +1,67 @@
1
+ import emittery__default from 'emittery';
2
+ import { Chunk, Sentinel, EmitteryCallbacks } from '../types/index.cjs';
3
+
4
+ /**
5
+ * Convert base64-encoded audio buffer(s) to a Float32Array.
6
+ *
7
+ * @param b64 The base64-encoded audio buffer, or an array of base64-encoded
8
+ * audio buffers.
9
+ * @returns The audio buffer(s) as a Float32Array.
10
+ */
11
+ declare function base64ToArray(b64: Chunk[]): Float32Array;
12
+ /**
13
+ * Schedule an audio buffer to play at a given time in the passed context.
14
+ *
15
+ * @param floats The audio buffer to play.
16
+ * @param context The audio context to play the buffer in.
17
+ * @param startAt The time to start playing the buffer at.
18
+ * @param sampleRate The sample rate of the audio.
19
+ * @returns A promise that resolves when the audio has finished playing.
20
+ */
21
+ declare function playAudioBuffer(floats: Float32Array, context: AudioContext, startAt: number, sampleRate: number): Promise<void>;
22
+ /**
23
+ * Unwraps a chunk of audio data from a message event and calls the
24
+ * handler with it if the context ID matches.
25
+ *
26
+ * @param contextId The context ID to listen for.
27
+ * @param handler The handler to call with the chunk of audio data.
28
+ * @returns A message event handler.
29
+ */
30
+ declare function createMessageHandlerForContextId(contextId: string, handler: ({ chunk, message, }: {
31
+ chunk: Chunk;
32
+ message: string;
33
+ }) => void): (event: MessageEvent) => void;
34
+ /**
35
+ * Get a sentinel value that indicates the end of a stream.
36
+ * @returns A sentinel value to indicate the end of a stream.
37
+ */
38
+ declare function getSentinel(): Sentinel;
39
+ /**
40
+ * Check if a chunk is a sentinel value (i.e. null).
41
+ *
42
+ * @param chunk
43
+ * @returns Whether the chunk is a sentinel value.
44
+ */
45
+ declare function isSentinel(x: unknown): x is Sentinel;
46
+ /**
47
+ * Filter out null values from a collection.
48
+ *
49
+ * @param collection The collection to filter.
50
+ * @returns The collection with null values removed.
51
+ */
52
+ declare function filterSentinel<T>(collection: T[]): Exclude<T, Sentinel>[];
53
+ /**
54
+ * Check if an array of chunks is complete by testing if the last chunk is a sentinel
55
+ * value (i.e. null).
56
+ * @param chunk
57
+ * @returns Whether the array of chunks is complete.
58
+ */
59
+ declare function isComplete(chunks: Chunk[]): boolean;
60
+ /**
61
+ * Get user-facing emitter callbacks for an Emittery instance.
62
+ * @param emitter The Emittery instance to get callbacks for.
63
+ * @returns User-facing emitter callbacks.
64
+ */
65
+ declare function getEmitteryCallbacks<T>(emitter: emittery__default<T>): EmitteryCallbacks<T>;
66
+
67
+ export { base64ToArray, createMessageHandlerForContextId, filterSentinel, getEmitteryCallbacks, getSentinel, isComplete, isSentinel, playAudioBuffer };
@@ -0,0 +1,67 @@
1
+ import emittery__default from 'emittery';
2
+ import { Chunk, Sentinel, EmitteryCallbacks } from '../types/index.js';
3
+
4
+ /**
5
+ * Convert base64-encoded audio buffer(s) to a Float32Array.
6
+ *
7
+ * @param b64 The base64-encoded audio buffer, or an array of base64-encoded
8
+ * audio buffers.
9
+ * @returns The audio buffer(s) as a Float32Array.
10
+ */
11
+ declare function base64ToArray(b64: Chunk[]): Float32Array;
12
+ /**
13
+ * Schedule an audio buffer to play at a given time in the passed context.
14
+ *
15
+ * @param floats The audio buffer to play.
16
+ * @param context The audio context to play the buffer in.
17
+ * @param startAt The time to start playing the buffer at.
18
+ * @param sampleRate The sample rate of the audio.
19
+ * @returns A promise that resolves when the audio has finished playing.
20
+ */
21
+ declare function playAudioBuffer(floats: Float32Array, context: AudioContext, startAt: number, sampleRate: number): Promise<void>;
22
+ /**
23
+ * Unwraps a chunk of audio data from a message event and calls the
24
+ * handler with it if the context ID matches.
25
+ *
26
+ * @param contextId The context ID to listen for.
27
+ * @param handler The handler to call with the chunk of audio data.
28
+ * @returns A message event handler.
29
+ */
30
+ declare function createMessageHandlerForContextId(contextId: string, handler: ({ chunk, message, }: {
31
+ chunk: Chunk;
32
+ message: string;
33
+ }) => void): (event: MessageEvent) => void;
34
+ /**
35
+ * Get a sentinel value that indicates the end of a stream.
36
+ * @returns A sentinel value to indicate the end of a stream.
37
+ */
38
+ declare function getSentinel(): Sentinel;
39
+ /**
40
+ * Check if a chunk is a sentinel value (i.e. null).
41
+ *
42
+ * @param chunk
43
+ * @returns Whether the chunk is a sentinel value.
44
+ */
45
+ declare function isSentinel(x: unknown): x is Sentinel;
46
+ /**
47
+ * Filter out null values from a collection.
48
+ *
49
+ * @param collection The collection to filter.
50
+ * @returns The collection with null values removed.
51
+ */
52
+ declare function filterSentinel<T>(collection: T[]): Exclude<T, Sentinel>[];
53
+ /**
54
+ * Check if an array of chunks is complete by testing if the last chunk is a sentinel
55
+ * value (i.e. null).
56
+ * @param chunk
57
+ * @returns Whether the array of chunks is complete.
58
+ */
59
+ declare function isComplete(chunks: Chunk[]): boolean;
60
+ /**
61
+ * Get user-facing emitter callbacks for an Emittery instance.
62
+ * @param emitter The Emittery instance to get callbacks for.
63
+ * @returns User-facing emitter callbacks.
64
+ */
65
+ declare function getEmitteryCallbacks<T>(emitter: emittery__default<T>): EmitteryCallbacks<T>;
66
+
67
+ export { base64ToArray, createMessageHandlerForContextId, filterSentinel, getEmitteryCallbacks, getSentinel, isComplete, isSentinel, playAudioBuffer };
@@ -1,22 +1,18 @@
1
1
  import {
2
2
  base64ToArray,
3
- bufferToWav,
4
3
  createMessageHandlerForContextId,
5
4
  filterSentinel,
6
- getBufferDuration,
7
5
  getEmitteryCallbacks,
8
6
  getSentinel,
9
7
  isComplete,
10
8
  isSentinel,
11
9
  playAudioBuffer
12
- } from "../chunk-FRIBQZPN.mjs";
13
- import "../chunk-HNLIBHEN.mjs";
10
+ } from "../chunk-LYPTISWL.js";
11
+ import "../chunk-WIFMLPT5.js";
14
12
  export {
15
13
  base64ToArray,
16
- bufferToWav,
17
14
  createMessageHandlerForContextId,
18
15
  filterSentinel,
19
- getBufferDuration,
20
16
  getEmitteryCallbacks,
21
17
  getSentinel,
22
18
  isComplete,
@@ -0,0 +1,453 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols)
18
+ for (var prop of __getOwnPropSymbols(b)) {
19
+ if (__propIsEnum.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ }
22
+ return a;
23
+ };
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
+ var __export = (target, all) => {
26
+ for (var name in all)
27
+ __defProp(target, name, { get: all[name], enumerable: true });
28
+ };
29
+ var __copyProps = (to, from, except, desc) => {
30
+ if (from && typeof from === "object" || typeof from === "function") {
31
+ for (let key of __getOwnPropNames(from))
32
+ if (!__hasOwnProp.call(to, key) && key !== except)
33
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
34
+ }
35
+ return to;
36
+ };
37
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
38
+ // If the importer is in node compatibility mode or this is not an ESM
39
+ // file that has been converted to a CommonJS file using a Babel-
40
+ // compatible transform (i.e. "__esModule" has not been set), then set
41
+ // "default" to the CommonJS "module.exports" for node compatibility.
42
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
43
+ mod
44
+ ));
45
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
+ var __accessCheck = (obj, member, msg) => {
47
+ if (!member.has(obj))
48
+ throw TypeError("Cannot " + msg);
49
+ };
50
+ var __privateGet = (obj, member, getter) => {
51
+ __accessCheck(obj, member, "read from private field");
52
+ return getter ? getter.call(obj) : member.get(obj);
53
+ };
54
+ var __privateAdd = (obj, member, value) => {
55
+ if (member.has(obj))
56
+ throw TypeError("Cannot add the same private member more than once");
57
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
58
+ };
59
+ var __privateSet = (obj, member, value, setter) => {
60
+ __accessCheck(obj, member, "write to private field");
61
+ setter ? setter.call(obj, value) : member.set(obj, value);
62
+ return value;
63
+ };
64
+ var __privateMethod = (obj, member, method) => {
65
+ __accessCheck(obj, member, "access private method");
66
+ return method;
67
+ };
68
+ var __async = (__this, __arguments, generator) => {
69
+ return new Promise((resolve, reject) => {
70
+ var fulfilled = (value) => {
71
+ try {
72
+ step(generator.next(value));
73
+ } catch (e) {
74
+ reject(e);
75
+ }
76
+ };
77
+ var rejected = (value) => {
78
+ try {
79
+ step(generator.throw(value));
80
+ } catch (e) {
81
+ reject(e);
82
+ }
83
+ };
84
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
85
+ step((generator = generator.apply(__this, __arguments)).next());
86
+ });
87
+ };
88
+
89
+ // src/tts/websocket.ts
90
+ var websocket_exports = {};
91
+ __export(websocket_exports, {
92
+ default: () => WebSocket
93
+ });
94
+ module.exports = __toCommonJS(websocket_exports);
95
+ var import_emittery2 = __toESM(require("emittery"), 1);
96
+ var import_human_id = require("human-id");
97
+ var import_partysocket = require("partysocket");
98
+
99
+ // src/lib/client.ts
100
+ var import_cross_fetch = __toESM(require("cross-fetch"), 1);
101
+
102
+ // src/lib/constants.ts
103
+ var BASE_URL = "https://api.cartesia.ai/v0";
104
+ var constructApiUrl = (baseUrl, path, protocol) => {
105
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
106
+ if (!protocol) {
107
+ return new URL(`${baseUrl}${normalizedPath}`);
108
+ }
109
+ if (!["http", "ws"].includes(protocol)) {
110
+ throw new Error(`Invalid protocol: ${protocol}`);
111
+ }
112
+ return new URL(`${baseUrl.replace(/^http/, protocol)}${normalizedPath}`);
113
+ };
114
+
115
+ // src/lib/client.ts
116
+ var Client = class {
117
+ constructor(options = {}) {
118
+ if (!(options.apiKey || process.env.CARTESIA_API_KEY)) {
119
+ throw new Error("Missing Cartesia API key.");
120
+ }
121
+ this.apiKey = options.apiKey || process.env.CARTESIA_API_KEY;
122
+ this.baseUrl = options.baseUrl || BASE_URL;
123
+ }
124
+ fetch(path, options = {}) {
125
+ const url = constructApiUrl(this.baseUrl, path);
126
+ return (0, import_cross_fetch.default)(url.toString(), __spreadProps(__spreadValues({}, options), {
127
+ headers: __spreadValues({
128
+ "X-API-KEY": this.apiKey
129
+ }, options.headers)
130
+ }));
131
+ }
132
+ };
133
+
134
+ // src/tts/source.ts
135
+ var import_emittery = __toESM(require("emittery"), 1);
136
+ var _emitter, _buffer, _readIndex, _closed, _sampleRate;
137
+ var Source = class {
138
+ /**
139
+ * Create a new Source.
140
+ *
141
+ * @param options - Options for the Source.
142
+ * @param options.sampleRate - The sample rate of the audio.
143
+ */
144
+ constructor({ sampleRate }) {
145
+ __privateAdd(this, _emitter, new import_emittery.default());
146
+ __privateAdd(this, _buffer, new Float32Array());
147
+ __privateAdd(this, _readIndex, 0);
148
+ __privateAdd(this, _closed, false);
149
+ __privateAdd(this, _sampleRate, void 0);
150
+ this.on = __privateGet(this, _emitter).on.bind(__privateGet(this, _emitter));
151
+ this.once = __privateGet(this, _emitter).once.bind(__privateGet(this, _emitter));
152
+ this.events = __privateGet(this, _emitter).events.bind(__privateGet(this, _emitter));
153
+ this.off = __privateGet(this, _emitter).off.bind(__privateGet(this, _emitter));
154
+ __privateSet(this, _sampleRate, sampleRate);
155
+ }
156
+ get sampleRate() {
157
+ return __privateGet(this, _sampleRate);
158
+ }
159
+ /**
160
+ * Append audio to the buffer.
161
+ *
162
+ * @param src The audio to append.
163
+ */
164
+ enqueue(src) {
165
+ return __async(this, null, function* () {
166
+ __privateSet(this, _buffer, new Float32Array([...__privateGet(this, _buffer), ...src]));
167
+ yield __privateGet(this, _emitter).emit("enqueue");
168
+ });
169
+ }
170
+ /**
171
+ * Read audio from the buffer.
172
+ *
173
+ * @param dst The buffer to read the audio into.
174
+ * @returns The number of samples read. If the source is closed, this will be
175
+ * less than the length of the provided buffer.
176
+ */
177
+ read(dst) {
178
+ return __async(this, null, function* () {
179
+ const targetReadIndex = __privateGet(this, _readIndex) + dst.length;
180
+ while (!__privateGet(this, _closed) && targetReadIndex > __privateGet(this, _buffer).length) {
181
+ yield __privateGet(this, _emitter).emit("wait");
182
+ yield Promise.race([
183
+ __privateGet(this, _emitter).once("enqueue"),
184
+ __privateGet(this, _emitter).once("close")
185
+ ]);
186
+ yield __privateGet(this, _emitter).emit("read");
187
+ }
188
+ const read = Math.min(dst.length, __privateGet(this, _buffer).length - __privateGet(this, _readIndex));
189
+ dst.set(__privateGet(this, _buffer).slice(__privateGet(this, _readIndex), __privateGet(this, _readIndex) + read));
190
+ __privateSet(this, _readIndex, __privateGet(this, _readIndex) + read);
191
+ return read;
192
+ });
193
+ }
194
+ /**
195
+ * Get the number of samples in a given duration.
196
+ *
197
+ * @param durationSecs The duration in seconds.
198
+ * @returns The number of samples.
199
+ */
200
+ durationToSampleCount(durationSecs) {
201
+ return Math.trunc(durationSecs * __privateGet(this, _sampleRate));
202
+ }
203
+ get buffer() {
204
+ return __privateGet(this, _buffer);
205
+ }
206
+ get readIndex() {
207
+ return __privateGet(this, _readIndex);
208
+ }
209
+ /**
210
+ * Close the source. This signals that no more audio will be enqueued.
211
+ *
212
+ * This will emit a "close" event.
213
+ *
214
+ * @returns A promise that resolves when the source is closed.
215
+ */
216
+ close() {
217
+ return __async(this, null, function* () {
218
+ __privateSet(this, _closed, true);
219
+ yield __privateGet(this, _emitter).emit("close");
220
+ __privateGet(this, _emitter).clearListeners();
221
+ });
222
+ }
223
+ };
224
+ _emitter = new WeakMap();
225
+ _buffer = new WeakMap();
226
+ _readIndex = new WeakMap();
227
+ _closed = new WeakMap();
228
+ _sampleRate = new WeakMap();
229
+
230
+ // src/tts/utils.ts
231
+ var import_base64_js = __toESM(require("base64-js"), 1);
232
+ function base64ToArray(b64) {
233
+ return filterSentinel(b64).reduce((acc, b) => {
234
+ const floats = new Float32Array(import_base64_js.default.toByteArray(b).buffer);
235
+ const newAcc = new Float32Array(acc.length + floats.length);
236
+ newAcc.set(acc, 0);
237
+ newAcc.set(floats, acc.length);
238
+ return newAcc;
239
+ }, new Float32Array(0));
240
+ }
241
+ function createMessageHandlerForContextId(contextId, handler) {
242
+ return (event) => {
243
+ if (typeof event.data !== "string") {
244
+ return;
245
+ }
246
+ const message = JSON.parse(event.data);
247
+ if (message.context_id !== contextId) {
248
+ return;
249
+ }
250
+ let chunk;
251
+ if (message.done) {
252
+ chunk = getSentinel();
253
+ } else {
254
+ chunk = message.data;
255
+ }
256
+ handler({ chunk, message: event.data });
257
+ };
258
+ }
259
+ function getSentinel() {
260
+ return null;
261
+ }
262
+ function isSentinel(x) {
263
+ return x === getSentinel();
264
+ }
265
+ function filterSentinel(collection) {
266
+ return collection.filter(
267
+ (x) => !isSentinel(x)
268
+ );
269
+ }
270
+ function getEmitteryCallbacks(emitter) {
271
+ return {
272
+ on: emitter.on.bind(emitter),
273
+ off: emitter.off.bind(emitter),
274
+ once: emitter.once.bind(emitter),
275
+ events: emitter.events.bind(emitter)
276
+ };
277
+ }
278
+
279
+ // src/tts/websocket.ts
280
+ var _isConnected, _sampleRate2, _generateId, generateId_fn;
281
+ var WebSocket = class extends Client {
282
+ /**
283
+ * Create a new WebSocket client.
284
+ *
285
+ * @param args - Arguments to pass to the Client constructor.
286
+ */
287
+ constructor({ sampleRate }, ...args) {
288
+ super(...args);
289
+ /**
290
+ * Generate a unique ID suitable for a streaming context.
291
+ *
292
+ * Not suitable for security purposes or as a primary key, since
293
+ * it lacks the amount of entropy required for those use cases.
294
+ *
295
+ * @returns A unique ID.
296
+ */
297
+ __privateAdd(this, _generateId);
298
+ __privateAdd(this, _isConnected, false);
299
+ __privateAdd(this, _sampleRate2, void 0);
300
+ __privateSet(this, _sampleRate2, sampleRate);
301
+ }
302
+ /**
303
+ * Send a message over the WebSocket in order to start a stream.
304
+ *
305
+ * @param inputs - Stream options.
306
+ * @param options - Options for the stream.
307
+ * @param options.timeout - The maximum time to wait for a chunk before cancelling the stream.
308
+ * If `0`, the stream will not time out.
309
+ * @returns A Source object that can be passed to a Player to play the audio.
310
+ */
311
+ send(inputs, { timeout = 0 } = {}) {
312
+ var _a, _b, _c, _d;
313
+ if (!__privateGet(this, _isConnected)) {
314
+ throw new Error("Not connected to WebSocket. Call .connect() first.");
315
+ }
316
+ const contextId = __privateMethod(this, _generateId, generateId_fn).call(this);
317
+ (_a = this.socket) == null ? void 0 : _a.send(
318
+ JSON.stringify(__spreadProps(__spreadValues({
319
+ context_id: contextId
320
+ }, inputs), {
321
+ output_format: {
322
+ container: "raw",
323
+ encoding: "pcm_f32le",
324
+ sample_rate: __privateGet(this, _sampleRate2)
325
+ }
326
+ }))
327
+ );
328
+ const emitter = new import_emittery2.default();
329
+ const source = new Source({
330
+ sampleRate: __privateGet(this, _sampleRate2)
331
+ });
332
+ const streamCompleteController = new AbortController();
333
+ let timeoutId = null;
334
+ if (timeout > 0) {
335
+ timeoutId = setTimeout(streamCompleteController.abort, timeout);
336
+ }
337
+ const handleMessage = createMessageHandlerForContextId(
338
+ contextId,
339
+ (_0) => __async(this, [_0], function* ({ chunk, message }) {
340
+ emitter.emit("message", message);
341
+ if (isSentinel(chunk)) {
342
+ yield source.close();
343
+ streamCompleteController.abort();
344
+ return;
345
+ }
346
+ yield source.enqueue(base64ToArray([chunk]));
347
+ if (timeoutId) {
348
+ clearTimeout(timeoutId);
349
+ timeoutId = setTimeout(streamCompleteController.abort, timeout);
350
+ }
351
+ })
352
+ );
353
+ (_b = this.socket) == null ? void 0 : _b.addEventListener("message", handleMessage, {
354
+ signal: streamCompleteController.signal
355
+ });
356
+ (_c = this.socket) == null ? void 0 : _c.addEventListener(
357
+ "close",
358
+ () => {
359
+ streamCompleteController.abort();
360
+ },
361
+ {
362
+ once: true
363
+ }
364
+ );
365
+ (_d = this.socket) == null ? void 0 : _d.addEventListener(
366
+ "error",
367
+ () => {
368
+ streamCompleteController.abort();
369
+ },
370
+ {
371
+ once: true
372
+ }
373
+ );
374
+ streamCompleteController.signal.addEventListener("abort", () => {
375
+ source.close();
376
+ if (timeoutId) {
377
+ clearTimeout(timeoutId);
378
+ }
379
+ });
380
+ return __spreadValues({ source }, getEmitteryCallbacks(emitter));
381
+ }
382
+ /**
383
+ * Authenticate and connect to a Cartesia streaming WebSocket.
384
+ *
385
+ * @returns A promise that resolves when the WebSocket is connected.
386
+ * @throws {Error} If the WebSocket fails to connect.
387
+ */
388
+ connect() {
389
+ const url = constructApiUrl(this.baseUrl, "/tts/websocket", "ws");
390
+ url.searchParams.set("api_key", this.apiKey);
391
+ const emitter = new import_emittery2.default();
392
+ this.socket = new import_partysocket.WebSocket(url.toString());
393
+ this.socket.onopen = () => {
394
+ __privateSet(this, _isConnected, true);
395
+ emitter.emit("open");
396
+ };
397
+ this.socket.onclose = () => {
398
+ __privateSet(this, _isConnected, false);
399
+ emitter.emit("close");
400
+ };
401
+ return new Promise(
402
+ (resolve, reject) => {
403
+ var _a, _b, _c;
404
+ (_a = this.socket) == null ? void 0 : _a.addEventListener(
405
+ "open",
406
+ () => {
407
+ resolve(getEmitteryCallbacks(emitter));
408
+ },
409
+ {
410
+ once: true
411
+ }
412
+ );
413
+ const aborter = new AbortController();
414
+ (_b = this.socket) == null ? void 0 : _b.addEventListener(
415
+ "error",
416
+ () => {
417
+ aborter.abort();
418
+ reject(new Error("WebSocket failed to connect."));
419
+ },
420
+ {
421
+ signal: aborter.signal
422
+ }
423
+ );
424
+ (_c = this.socket) == null ? void 0 : _c.addEventListener(
425
+ "close",
426
+ () => {
427
+ aborter.abort();
428
+ reject(new Error("WebSocket closed before it could connect."));
429
+ },
430
+ {
431
+ signal: aborter.signal
432
+ }
433
+ );
434
+ }
435
+ );
436
+ }
437
+ /**
438
+ * Disconnect from the Cartesia streaming WebSocket.
439
+ */
440
+ disconnect() {
441
+ var _a;
442
+ (_a = this.socket) == null ? void 0 : _a.close();
443
+ }
444
+ };
445
+ _isConnected = new WeakMap();
446
+ _sampleRate2 = new WeakMap();
447
+ _generateId = new WeakSet();
448
+ generateId_fn = function() {
449
+ return (0, import_human_id.humanId)({
450
+ separator: "-",
451
+ capitalize: false
452
+ });
453
+ };
@@ -0,0 +1,53 @@
1
+ import * as emittery from 'emittery';
2
+ import { WebSocket as WebSocket$1 } from 'partysocket';
3
+ import { Client } from '../lib/client.cjs';
4
+ import { WebSocketOptions, StreamRequest, EmitteryCallbacks, ConnectionEventData } from '../types/index.cjs';
5
+ import Source from './source.cjs';
6
+
7
+ declare class WebSocket extends Client {
8
+ #private;
9
+ socket?: WebSocket$1;
10
+ /**
11
+ * Create a new WebSocket client.
12
+ *
13
+ * @param args - Arguments to pass to the Client constructor.
14
+ */
15
+ constructor({ sampleRate }: WebSocketOptions, ...args: ConstructorParameters<typeof Client>);
16
+ /**
17
+ * Send a message over the WebSocket in order to start a stream.
18
+ *
19
+ * @param inputs - Stream options.
20
+ * @param options - Options for the stream.
21
+ * @param options.timeout - The maximum time to wait for a chunk before cancelling the stream.
22
+ * If `0`, the stream will not time out.
23
+ * @returns A Source object that can be passed to a Player to play the audio.
24
+ */
25
+ send(inputs: StreamRequest["inputs"], { timeout }?: StreamRequest["options"]): {
26
+ on: <Name extends keyof emittery.OmnipresentEventData | "message">(eventName: Name | readonly Name[], listener: (eventData: ({
27
+ message: string;
28
+ } & emittery.OmnipresentEventData)[Name]) => void | Promise<void>) => emittery.UnsubscribeFunction;
29
+ off: <Name_1 extends keyof emittery.OmnipresentEventData | "message">(eventName: Name_1 | readonly Name_1[], listener: (eventData: ({
30
+ message: string;
31
+ } & emittery.OmnipresentEventData)[Name_1]) => void | Promise<void>) => void;
32
+ once: <Name_2 extends keyof emittery.OmnipresentEventData | "message">(eventName: Name_2 | readonly Name_2[]) => emittery.EmitteryOncePromise<({
33
+ message: string;
34
+ } & emittery.OmnipresentEventData)[Name_2]>;
35
+ events: <Name_3 extends "message">(eventName: Name_3 | readonly Name_3[]) => AsyncIterableIterator<{
36
+ message: string;
37
+ }[Name_3]>;
38
+ source: Source;
39
+ };
40
+ /**
41
+ * Authenticate and connect to a Cartesia streaming WebSocket.
42
+ *
43
+ * @returns A promise that resolves when the WebSocket is connected.
44
+ * @throws {Error} If the WebSocket fails to connect.
45
+ */
46
+ connect(): Promise<EmitteryCallbacks<ConnectionEventData>>;
47
+ /**
48
+ * Disconnect from the Cartesia streaming WebSocket.
49
+ */
50
+ disconnect(): void;
51
+ }
52
+
53
+ export { WebSocket as default };