@neosapience/typecast-js 0.1.3

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/LICENSE ADDED
@@ -0,0 +1,191 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 Neosapience Inc.
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
191
+
package/README.md ADDED
@@ -0,0 +1,293 @@
1
+ # Typecast Node.js SDK
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@neosapience/typecast-js.svg)](https://www.npmjs.com/package/@neosapience/typecast-js)
4
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.7-blue.svg)](https://www.typescriptlang.org/)
6
+ [![Node.js](https://img.shields.io/badge/Node.js-%3E%3D16.0.0-green.svg)](https://nodejs.org/)
7
+
8
+ The official Node.js library for the [Typecast API](https://typecast.ai). Convert text to lifelike speech using AI-powered voices.
9
+
10
+ Works with both JavaScript and TypeScript. TypeScript types included.
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ npm install @neosapience/typecast-js
16
+ ```
17
+
18
+ ## Quick Start
19
+
20
+ ### TypeScript (ESM)
21
+
22
+ ```typescript
23
+ import { TypecastClient } from '@neosapience/typecast-js';
24
+ import fs from 'fs';
25
+
26
+ // Initialize client with API key
27
+ const client = new TypecastClient({
28
+ apiKey: 'YOUR_API_KEY'
29
+ });
30
+
31
+ // Convert text to speech
32
+ const audio = await client.textToSpeech({
33
+ text: "Hello there! I'm your friendly text-to-speech agent.",
34
+ model: "ssfm-v21",
35
+ voice_id: "tc_62a8975e695ad26f7fb514d1"
36
+ });
37
+
38
+ // Save audio file
39
+ await fs.promises.writeFile('output.wav', Buffer.from(audio.audioData));
40
+ console.log(`Audio saved! Duration: ${audio.duration}s, Format: ${audio.format}`);
41
+ ```
42
+
43
+ ### JavaScript (CommonJS)
44
+
45
+ ```javascript
46
+ const { TypecastClient } = require('@neosapience/typecast-js');
47
+ const fs = require('fs');
48
+
49
+ async function main() {
50
+ const client = new TypecastClient({
51
+ apiKey: 'YOUR_API_KEY'
52
+ });
53
+
54
+ const audio = await client.textToSpeech({
55
+ text: "Hello there! I'm your friendly text-to-speech agent.",
56
+ model: "ssfm-v21",
57
+ voice_id: "tc_62a8975e695ad26f7fb514d1"
58
+ });
59
+
60
+ await fs.promises.writeFile('output.wav', Buffer.from(audio.audioData));
61
+ console.log(`Audio saved! Duration: ${audio.duration}s, Format: ${audio.format}`);
62
+ }
63
+
64
+ main();
65
+ ```
66
+
67
+ ## Configuration
68
+
69
+ The client can be configured using environment variables or constructor options:
70
+
71
+ ```typescript
72
+ // Using environment variables
73
+ // TYPECAST_API_KEY=your_api_key
74
+ // TYPECAST_API_HOST=https://api.typecast.ai (optional)
75
+ const client = new TypecastClient();
76
+
77
+ // Using constructor options
78
+ const client = new TypecastClient({
79
+ apiKey: 'your_api_key',
80
+ baseHost: 'https://api.typecast.ai' // optional
81
+ });
82
+ ```
83
+
84
+ ## API Reference
85
+
86
+ ### Text-to-Speech
87
+
88
+ Generate speech from text using a specified voice model.
89
+
90
+ ```typescript
91
+ const response = await client.textToSpeech({
92
+ text: "Hello. How are you?",
93
+ voice_id: "tc_62a8975e695ad26f7fb514d1",
94
+ model: "ssfm-v21",
95
+ language: "eng", // optional, auto-detected if not provided
96
+ prompt: {
97
+ emotion_preset: "happy",
98
+ emotion_intensity: 1.5
99
+ },
100
+ output: {
101
+ audio_format: "mp3",
102
+ volume: 100,
103
+ audio_pitch: 0,
104
+ audio_tempo: 1.0
105
+ },
106
+ seed: 42 // for reproducible results
107
+ });
108
+ ```
109
+
110
+ #### Parameters
111
+
112
+ - **text** (required): Text to convert to speech (max 5000 characters)
113
+ - **voice_id** (required): Voice ID (format: `tc_*` for Typecast voices, `uc_*` for user-created voices)
114
+ - **model** (required): Voice model (`ssfm-v21`)
115
+ - **language** (optional): Language code (see supported languages below)
116
+ - **prompt** (optional): Emotion and style settings
117
+ - `emotion_preset`: `'happy' | 'sad' | 'normal' | 'angry'` (default: `'normal'`)
118
+ - `emotion_intensity`: 0.0 - 2.0 (default: 1.0)
119
+ - `speed`: 0.5 - 2.0 (default: 1.0)
120
+ - `intonation`: -2 - 2 (default: 0)
121
+ - **output** (optional): Audio output settings
122
+ - `audio_format`: `'wav' | 'mp3'` (default: `'wav'`)
123
+ - `volume`: 0 - 200 (default: 100)
124
+ - `audio_pitch`: -12 - 12 semitones (default: 0)
125
+ - `audio_tempo`: 0.5 - 2.0 (default: 1.0)
126
+ - **seed** (optional): Random seed for reproducible results
127
+
128
+ ### Get Voices
129
+
130
+ List all available voices, optionally filtered by model.
131
+
132
+ ```typescript
133
+ // Get all voices
134
+ const voices = await client.getVoices();
135
+
136
+ // Get voices for specific model
137
+ const voices = await client.getVoices("ssfm-v21");
138
+
139
+ voices.forEach(voice => {
140
+ console.log(`${voice.voice_name} (${voice.voice_id})`);
141
+ console.log(`Emotions: ${voice.emotions.join(', ')}`);
142
+ });
143
+ ```
144
+
145
+ ### Get Voice by ID
146
+
147
+ Get information about a specific voice.
148
+
149
+ ```typescript
150
+ const voiceInfo = await client.getVoiceById("tc_62a8975e695ad26f7fb514d1");
151
+ console.log(voiceInfo);
152
+ ```
153
+
154
+ ## Supported Languages
155
+
156
+ The SDK supports 27 languages with automatic language detection:
157
+
158
+ | Code | Language | Code | Language | Code | Language |
159
+ |------|------------|------|------------|------|------------|
160
+ | eng | English | jpn | Japanese | ukr | Ukrainian |
161
+ | kor | Korean | ell | Greek | ind | Indonesian |
162
+ | spa | Spanish | tam | Tamil | dan | Danish |
163
+ | deu | German | tgl | Tagalog | swe | Swedish |
164
+ | fra | French | fin | Finnish | msa | Malay |
165
+ | ita | Italian | zho | Chinese | ces | Czech |
166
+ | pol | Polish | slk | Slovak | por | Portuguese |
167
+ | nld | Dutch | ara | Arabic | bul | Bulgarian |
168
+ | rus | Russian | hrv | Croatian | ron | Romanian |
169
+
170
+ If not specified, the language will be automatically detected from the input text.
171
+
172
+ ## Advanced Examples
173
+
174
+ ### Emotion Control
175
+
176
+ ```typescript
177
+ // Happy and energetic voice
178
+ const happyAudio = await client.textToSpeech({
179
+ text: "Great to see you!",
180
+ voice_id: "tc_62a8975e695ad26f7fb514d1",
181
+ model: "ssfm-v21",
182
+ prompt: {
183
+ emotion_preset: "happy",
184
+ emotion_intensity: 1.8,
185
+ speed: 1.2
186
+ }
187
+ });
188
+
189
+ // Calm and professional voice
190
+ const calmAudio = await client.textToSpeech({
191
+ text: "Welcome to our presentation.",
192
+ voice_id: "tc_62a8975e695ad26f7fb514d1",
193
+ model: "ssfm-v21",
194
+ prompt: {
195
+ emotion_preset: "normal",
196
+ emotion_intensity: 0.8,
197
+ speed: 0.9
198
+ }
199
+ });
200
+ ```
201
+
202
+ ### Audio Customization
203
+
204
+ ```typescript
205
+ // Generate louder audio with higher pitch
206
+ const customAudio = await client.textToSpeech({
207
+ text: "This is a test with custom settings.",
208
+ voice_id: "tc_62a8975e695ad26f7fb514d1",
209
+ model: "ssfm-v21",
210
+ output: {
211
+ volume: 150,
212
+ audio_pitch: 3,
213
+ audio_tempo: 1.1,
214
+ audio_format: "mp3"
215
+ }
216
+ });
217
+ ```
218
+
219
+ ### Multilingual Content
220
+
221
+ ```typescript
222
+ // Korean text
223
+ const koreanAudio = await client.textToSpeech({
224
+ text: "안녕하세요. 반갑습니다.",
225
+ voice_id: "tc_62a8975e695ad26f7fb514d1",
226
+ model: "ssfm-v21",
227
+ language: "kor"
228
+ });
229
+
230
+ // Japanese text
231
+ const japaneseAudio = await client.textToSpeech({
232
+ text: "こんにちは。お元気ですか。",
233
+ voice_id: "tc_62a8975e695ad26f7fb514d1",
234
+ model: "ssfm-v21",
235
+ language: "jpn"
236
+ });
237
+ ```
238
+
239
+ ### Error Handling
240
+
241
+ ```typescript
242
+ import { TypecastClient, TypecastAPIError } from '@neosapience/typecast-js';
243
+
244
+ try {
245
+ const audio = await client.textToSpeech({
246
+ text: "Hello world",
247
+ voice_id: "tc_62a8975e695ad26f7fb514d1",
248
+ model: "ssfm-v21"
249
+ });
250
+ } catch (error) {
251
+ if (error instanceof TypecastAPIError) {
252
+ switch (error.statusCode) {
253
+ case 401:
254
+ console.error('Invalid API key');
255
+ break;
256
+ case 402:
257
+ console.error('Insufficient credits');
258
+ break;
259
+ case 422:
260
+ console.error('Validation error:', error.response);
261
+ break;
262
+ default:
263
+ console.error(`API error (${error.statusCode}):`, error.message);
264
+ }
265
+ } else {
266
+ console.error('Unexpected error:', error);
267
+ }
268
+ }
269
+ ```
270
+
271
+ ## TypeScript Support
272
+
273
+ This SDK is written in TypeScript and provides full type definitions:
274
+
275
+ ```typescript
276
+ import type {
277
+ TTSRequest,
278
+ TTSResponse,
279
+ LanguageCode,
280
+ Prompt,
281
+ Output
282
+ } from '@neosapience/typecast-js';
283
+ ```
284
+
285
+ ## Documentation
286
+
287
+ - [Typecast API Documentation](https://typecast.ai/docs)
288
+ - [API Reference](https://typecast.ai/docs/api-reference)
289
+ - [Quickstart Guide](https://typecast.ai/docs/quickstart)
290
+
291
+ ## License
292
+
293
+ Apache-2.0 License
package/lib/index.cjs ADDED
@@ -0,0 +1,115 @@
1
+ 'use strict';
2
+
3
+ var axios = require('axios');
4
+
5
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
6
+
7
+ var axios__default = /*#__PURE__*/_interopDefault(axios);
8
+
9
+ // src/client.ts
10
+
11
+ // src/errors.ts
12
+ var TypecastAPIError = class _TypecastAPIError extends Error {
13
+ constructor(message, statusCode, response) {
14
+ super(message);
15
+ this.name = "TypecastAPIError";
16
+ this.statusCode = statusCode;
17
+ this.response = response;
18
+ if (Error.captureStackTrace) {
19
+ Error.captureStackTrace(this, _TypecastAPIError);
20
+ }
21
+ }
22
+ static fromResponse(statusCode, statusText, data) {
23
+ let message;
24
+ switch (statusCode) {
25
+ case 400:
26
+ message = "Bad Request - The request was invalid or cannot be served";
27
+ break;
28
+ case 401:
29
+ message = "Unauthorized - Invalid or missing API key";
30
+ break;
31
+ case 402:
32
+ message = "Payment Required - Insufficient credits to complete the request";
33
+ break;
34
+ case 404:
35
+ message = "Not Found - The requested resource does not exist";
36
+ break;
37
+ case 422:
38
+ message = "Validation Error - The request data failed validation";
39
+ break;
40
+ case 500:
41
+ message = "Internal Server Error - Something went wrong on the server";
42
+ break;
43
+ default:
44
+ message = `API request failed with status ${statusCode}: ${statusText}`;
45
+ }
46
+ if (data?.detail) {
47
+ const detailStr = typeof data.detail === "string" ? data.detail : JSON.stringify(data.detail);
48
+ message += ` - ${detailStr}`;
49
+ }
50
+ return new _TypecastAPIError(message, statusCode, data);
51
+ }
52
+ };
53
+
54
+ // src/client.ts
55
+ var TypecastClient = class {
56
+ constructor(config = {}) {
57
+ this.config = {
58
+ baseHost: process.env.TYPECAST_API_HOST || "https://api.typecast.ai",
59
+ apiKey: process.env.TYPECAST_API_KEY || "",
60
+ ...config
61
+ };
62
+ this.client = axios__default.default.create({
63
+ baseURL: this.config.baseHost,
64
+ headers: {
65
+ "X-API-KEY": this.config.apiKey,
66
+ "Content-Type": "application/json"
67
+ }
68
+ });
69
+ this.client.interceptors.response.use(
70
+ (response) => response,
71
+ (error) => {
72
+ if (error.response) {
73
+ throw TypecastAPIError.fromResponse(
74
+ error.response.status,
75
+ error.response.statusText,
76
+ error.response.data
77
+ );
78
+ }
79
+ throw error;
80
+ }
81
+ );
82
+ }
83
+ async textToSpeech(request) {
84
+ const response = await this.client.post("/v1/text-to-speech", request, {
85
+ responseType: "arraybuffer"
86
+ });
87
+ const contentType = String(response.headers["content-type"] || "audio/wav");
88
+ const formatFromHeader = contentType.split("/")[1] || "wav";
89
+ const format = formatFromHeader === "mp3" ? "mp3" : "wav";
90
+ const durationHeader = response.headers["x-audio-duration"];
91
+ const duration = typeof durationHeader === "string" ? Number(durationHeader) : 0;
92
+ return {
93
+ audioData: response.data,
94
+ duration,
95
+ format
96
+ };
97
+ }
98
+ async getVoices(model) {
99
+ const response = await this.client.get("/v1/voices", {
100
+ params: model ? { model } : void 0
101
+ });
102
+ return response.data;
103
+ }
104
+ async getVoiceById(voiceId, model) {
105
+ const response = await this.client.get(`/v1/voices/${voiceId}`, {
106
+ params: model ? { model } : void 0
107
+ });
108
+ return response.data;
109
+ }
110
+ };
111
+
112
+ exports.TypecastAPIError = TypecastAPIError;
113
+ exports.TypecastClient = TypecastClient;
114
+ //# sourceMappingURL=index.cjs.map
115
+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EAAS;AAAA,MAClF,YAAA,EAAc;AAAA,KACf,CAAA;AAED,IAAA,MAAM,cAAc,MAAA,CAAO,QAAA,CAAS,OAAA,CAAQ,cAAc,KAAK,WAAW,CAAA;AAC1E,IAAA,MAAM,mBAAmB,WAAA,CAAY,KAAA,CAAM,GAAG,CAAA,CAAE,CAAC,CAAA,IAAK,KAAA;AACtD,IAAA,MAAM,MAAA,GAAwB,gBAAA,KAAqB,KAAA,GAAQ,KAAA,GAAQ,KAAA;AAEnE,IAAA,MAAM,cAAA,GAA0B,QAAA,CAAS,OAAA,CAAQ,kBAAkB,CAAA;AACnE,IAAA,MAAM,WAAW,OAAO,cAAA,KAAmB,QAAA,GAAW,MAAA,CAAO,cAAc,CAAA,GAAI,CAAA;AAE/E,IAAA,OAAO;AAAA,MACL,WAAW,QAAA,CAAS,IAAA;AAAA,MACpB,QAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AAAA,EAEA,MAAM,UAAU,KAAA,EAA2C;AACzD,IAAA,MAAM,QAAA,GAAW,MAAM,IAAA,CAAK,MAAA,CAAO,IAAsB,YAAA,EAAc;AAAA,MACrE,MAAA,EAAQ,KAAA,GAAQ,EAAE,KAAA,EAAM,GAAI;AAAA,KAC7B,CAAA;AACD,IAAA,OAAO,QAAA,CAAS,IAAA;AAAA,EAClB;AAAA,EAEA,MAAM,YAAA,CAAa,OAAA,EAAiB,KAAA,EAA2C;AAC7E,IAAA,MAAM,WAAW,MAAM,IAAA,CAAK,OAAO,GAAA,CAAsB,CAAA,WAAA,EAAc,OAAO,CAAA,CAAA,EAAI;AAAA,MAChF,MAAA,EAAQ,KAAA,GAAQ,EAAE,KAAA,EAAM,GAAI;AAAA,KAC7B,CAAA;AACD,IAAA,OAAO,QAAA,CAAS,IAAA;AAAA,EAClB;AACF","file":"index.cjs","sourcesContent":["import { ApiErrorResponse } from './types';\n\nexport class TypecastAPIError extends Error {\n public readonly statusCode: number;\n public readonly response?: ApiErrorResponse;\n\n constructor(message: string, statusCode: number, response?: ApiErrorResponse) {\n super(message);\n this.name = 'TypecastAPIError';\n this.statusCode = statusCode;\n this.response = response;\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, TypecastAPIError);\n }\n }\n\n static fromResponse(statusCode: number, statusText: string, data?: ApiErrorResponse): TypecastAPIError {\n let message: string;\n\n switch (statusCode) {\n case 400:\n message = 'Bad Request - The request was invalid or cannot be served';\n break;\n case 401:\n message = 'Unauthorized - Invalid or missing API key';\n break;\n case 402:\n message = 'Payment Required - Insufficient credits to complete the request';\n break;\n case 404:\n message = 'Not Found - The requested resource does not exist';\n break;\n case 422:\n message = 'Validation Error - The request data failed validation';\n break;\n case 500:\n message = 'Internal Server Error - Something went wrong on the server';\n break;\n default:\n message = `API request failed with status ${statusCode}: ${statusText}`;\n }\n\n if (data?.detail) {\n const detailStr = typeof data.detail === 'string' \n ? data.detail \n : JSON.stringify(data.detail);\n message += ` - ${detailStr}`;\n }\n\n return new TypecastAPIError(message, statusCode, data);\n }\n}\n\n","import axios, { AxiosInstance, AxiosError } from 'axios';\nimport { ClientConfig, TTSRequest, TTSResponse, ApiErrorResponse } from './types';\nimport { VoicesResponse } from './types/Voices';\nimport { TypecastAPIError } from './errors';\n\nexport class TypecastClient {\n private client: AxiosInstance;\n private config: ClientConfig;\n\n constructor(config: Partial<ClientConfig> = {}) {\n this.config = {\n baseHost: process.env.TYPECAST_API_HOST || 'https://api.typecast.ai',\n apiKey: process.env.TYPECAST_API_KEY || '',\n ...config,\n };\n this.client = axios.create({\n baseURL: this.config.baseHost,\n headers: {\n 'X-API-KEY': this.config.apiKey,\n 'Content-Type': 'application/json',\n },\n });\n\n // Add response interceptor for error handling\n this.client.interceptors.response.use(\n (response) => response,\n (error: AxiosError<ApiErrorResponse>) => {\n if (error.response) {\n throw TypecastAPIError.fromResponse(\n error.response.status,\n error.response.statusText,\n error.response.data\n );\n }\n throw error;\n }\n );\n }\n\n async textToSpeech(request: TTSRequest): Promise<TTSResponse> {\n const response = await this.client.post<ArrayBuffer>('/v1/text-to-speech', request, {\n responseType: 'arraybuffer',\n });\n\n const contentType = String(response.headers['content-type'] || 'audio/wav');\n const formatFromHeader = contentType.split('/')[1] || 'wav';\n const format: 'wav' | 'mp3' = formatFromHeader === 'mp3' ? 'mp3' : 'wav';\n\n const durationHeader: unknown = response.headers['x-audio-duration'];\n const duration = typeof durationHeader === 'string' ? Number(durationHeader) : 0;\n\n return {\n audioData: response.data,\n duration,\n format,\n };\n }\n\n async getVoices(model?: string): Promise<VoicesResponse[]> {\n const response = await this.client.get<VoicesResponse[]>('/v1/voices', {\n params: model ? { model } : undefined,\n });\n return response.data;\n }\n\n async getVoiceById(voiceId: string, model?: string): Promise<VoicesResponse[]> {\n const response = await this.client.get<VoicesResponse[]>(`/v1/voices/${voiceId}`, {\n params: model ? { model } : undefined,\n });\n return response.data;\n }\n}\n"]}
@@ -0,0 +1,150 @@
1
+ /**
2
+ * API error response structure
3
+ * Based on Typecast API documentation: https://typecast.ai/docs/api-reference
4
+ */
5
+ interface ApiErrorResponse {
6
+ detail?: string | string[] | Record<string, unknown>;
7
+ message?: string;
8
+ error?: string;
9
+ [key: string]: unknown;
10
+ }
11
+ /**
12
+ * Validation error detail structure (422 responses)
13
+ */
14
+ interface ValidationError {
15
+ loc: (string | number)[];
16
+ msg: string;
17
+ type: string;
18
+ }
19
+ interface ValidationErrorResponse {
20
+ detail: ValidationError[];
21
+ }
22
+
23
+ interface ClientConfig {
24
+ baseHost: string;
25
+ apiKey: string;
26
+ }
27
+
28
+ type TTSModel = 'ssfm-v21';
29
+ /**
30
+ * Language code following ISO 639-3 standard
31
+ * Supported languages for text-to-speech conversion
32
+ */
33
+ type LanguageCode = 'eng' | 'kor' | 'jpn' | 'spa' | 'deu' | 'fra' | 'ita' | 'pol' | 'nld' | 'rus' | 'ell' | 'tam' | 'tgl' | 'fin' | 'zho' | 'slk' | 'ara' | 'hrv' | 'ukr' | 'ind' | 'dan' | 'swe' | 'msa' | 'ces' | 'por' | 'bul' | 'ron';
34
+ /**
35
+ * Emotion and style settings for the generated speech
36
+ */
37
+ interface Prompt {
38
+ /** Emotion preset for the voice (default: 'normal') */
39
+ emotion_preset?: 'happy' | 'sad' | 'normal' | 'angry';
40
+ /**
41
+ * Emotion intensity
42
+ * @min 0.0
43
+ * @max 2.0
44
+ * @default 1.0
45
+ */
46
+ emotion_intensity?: number;
47
+ /**
48
+ * Speech speed
49
+ * @min 0.5
50
+ * @max 2.0
51
+ * @default 1.0
52
+ */
53
+ speed?: number;
54
+ /**
55
+ * Intonation adjustment
56
+ * @min -2
57
+ * @max 2
58
+ * @default 0
59
+ */
60
+ intonation?: number;
61
+ }
62
+ /**
63
+ * Audio output settings for controlling the final audio characteristics
64
+ */
65
+ interface Output {
66
+ /**
67
+ * Output volume
68
+ * @min 0
69
+ * @max 200
70
+ * @default 100
71
+ */
72
+ volume?: number;
73
+ /**
74
+ * Audio pitch adjustment in semitones
75
+ * @min -12
76
+ * @max 12
77
+ * @default 0
78
+ */
79
+ audio_pitch?: number;
80
+ /**
81
+ * Audio tempo (speed multiplier)
82
+ * @min 0.5
83
+ * @max 2.0
84
+ * @default 1.0
85
+ */
86
+ audio_tempo?: number;
87
+ /**
88
+ * Audio output format
89
+ * @default 'wav'
90
+ */
91
+ audio_format?: 'wav' | 'mp3';
92
+ }
93
+ /**
94
+ * Text-to-Speech request parameters
95
+ */
96
+ interface TTSRequest {
97
+ /**
98
+ * Text to convert to speech
99
+ * @maxLength 5000
100
+ */
101
+ text: string;
102
+ /** Voice ID in format 'tc_' (Typecast voice) or 'uc_' (User-created voice) followed by a unique identifier */
103
+ voice_id: string;
104
+ /** Voice model to use */
105
+ model: TTSModel;
106
+ /** Language code (ISO 639-3). If not provided, will be auto-detected based on text content */
107
+ language?: LanguageCode;
108
+ /** Emotion and style settings for the generated speech */
109
+ prompt?: Prompt;
110
+ /** Audio output settings */
111
+ output?: Output;
112
+ /** Random seed for reproducible results (same seed + same parameters = same output) */
113
+ seed?: number;
114
+ }
115
+ /**
116
+ * Text-to-Speech response
117
+ */
118
+ interface TTSResponse {
119
+ /** Generated audio data as ArrayBuffer */
120
+ audioData: ArrayBuffer;
121
+ /** Audio duration in seconds */
122
+ duration: number;
123
+ /** Audio format (wav or mp3) */
124
+ format: 'wav' | 'mp3';
125
+ }
126
+
127
+ interface VoicesResponse {
128
+ voice_id: string;
129
+ voice_name: string;
130
+ model: string;
131
+ emotions: string[];
132
+ }
133
+
134
+ declare class TypecastClient {
135
+ private client;
136
+ private config;
137
+ constructor(config?: Partial<ClientConfig>);
138
+ textToSpeech(request: TTSRequest): Promise<TTSResponse>;
139
+ getVoices(model?: string): Promise<VoicesResponse[]>;
140
+ getVoiceById(voiceId: string, model?: string): Promise<VoicesResponse[]>;
141
+ }
142
+
143
+ declare class TypecastAPIError extends Error {
144
+ readonly statusCode: number;
145
+ readonly response?: ApiErrorResponse;
146
+ constructor(message: string, statusCode: number, response?: ApiErrorResponse);
147
+ static fromResponse(statusCode: number, statusText: string, data?: ApiErrorResponse): TypecastAPIError;
148
+ }
149
+
150
+ export { type ApiErrorResponse, type ClientConfig, type LanguageCode, type Output, type Prompt, type TTSModel, type TTSRequest, type TTSResponse, TypecastAPIError, TypecastClient, type ValidationError, type ValidationErrorResponse, type VoicesResponse };
package/lib/index.d.ts ADDED
@@ -0,0 +1,150 @@
1
+ /**
2
+ * API error response structure
3
+ * Based on Typecast API documentation: https://typecast.ai/docs/api-reference
4
+ */
5
+ interface ApiErrorResponse {
6
+ detail?: string | string[] | Record<string, unknown>;
7
+ message?: string;
8
+ error?: string;
9
+ [key: string]: unknown;
10
+ }
11
+ /**
12
+ * Validation error detail structure (422 responses)
13
+ */
14
+ interface ValidationError {
15
+ loc: (string | number)[];
16
+ msg: string;
17
+ type: string;
18
+ }
19
+ interface ValidationErrorResponse {
20
+ detail: ValidationError[];
21
+ }
22
+
23
+ interface ClientConfig {
24
+ baseHost: string;
25
+ apiKey: string;
26
+ }
27
+
28
+ type TTSModel = 'ssfm-v21';
29
+ /**
30
+ * Language code following ISO 639-3 standard
31
+ * Supported languages for text-to-speech conversion
32
+ */
33
+ type LanguageCode = 'eng' | 'kor' | 'jpn' | 'spa' | 'deu' | 'fra' | 'ita' | 'pol' | 'nld' | 'rus' | 'ell' | 'tam' | 'tgl' | 'fin' | 'zho' | 'slk' | 'ara' | 'hrv' | 'ukr' | 'ind' | 'dan' | 'swe' | 'msa' | 'ces' | 'por' | 'bul' | 'ron';
34
+ /**
35
+ * Emotion and style settings for the generated speech
36
+ */
37
+ interface Prompt {
38
+ /** Emotion preset for the voice (default: 'normal') */
39
+ emotion_preset?: 'happy' | 'sad' | 'normal' | 'angry';
40
+ /**
41
+ * Emotion intensity
42
+ * @min 0.0
43
+ * @max 2.0
44
+ * @default 1.0
45
+ */
46
+ emotion_intensity?: number;
47
+ /**
48
+ * Speech speed
49
+ * @min 0.5
50
+ * @max 2.0
51
+ * @default 1.0
52
+ */
53
+ speed?: number;
54
+ /**
55
+ * Intonation adjustment
56
+ * @min -2
57
+ * @max 2
58
+ * @default 0
59
+ */
60
+ intonation?: number;
61
+ }
62
+ /**
63
+ * Audio output settings for controlling the final audio characteristics
64
+ */
65
+ interface Output {
66
+ /**
67
+ * Output volume
68
+ * @min 0
69
+ * @max 200
70
+ * @default 100
71
+ */
72
+ volume?: number;
73
+ /**
74
+ * Audio pitch adjustment in semitones
75
+ * @min -12
76
+ * @max 12
77
+ * @default 0
78
+ */
79
+ audio_pitch?: number;
80
+ /**
81
+ * Audio tempo (speed multiplier)
82
+ * @min 0.5
83
+ * @max 2.0
84
+ * @default 1.0
85
+ */
86
+ audio_tempo?: number;
87
+ /**
88
+ * Audio output format
89
+ * @default 'wav'
90
+ */
91
+ audio_format?: 'wav' | 'mp3';
92
+ }
93
+ /**
94
+ * Text-to-Speech request parameters
95
+ */
96
+ interface TTSRequest {
97
+ /**
98
+ * Text to convert to speech
99
+ * @maxLength 5000
100
+ */
101
+ text: string;
102
+ /** Voice ID in format 'tc_' (Typecast voice) or 'uc_' (User-created voice) followed by a unique identifier */
103
+ voice_id: string;
104
+ /** Voice model to use */
105
+ model: TTSModel;
106
+ /** Language code (ISO 639-3). If not provided, will be auto-detected based on text content */
107
+ language?: LanguageCode;
108
+ /** Emotion and style settings for the generated speech */
109
+ prompt?: Prompt;
110
+ /** Audio output settings */
111
+ output?: Output;
112
+ /** Random seed for reproducible results (same seed + same parameters = same output) */
113
+ seed?: number;
114
+ }
115
+ /**
116
+ * Text-to-Speech response
117
+ */
118
+ interface TTSResponse {
119
+ /** Generated audio data as ArrayBuffer */
120
+ audioData: ArrayBuffer;
121
+ /** Audio duration in seconds */
122
+ duration: number;
123
+ /** Audio format (wav or mp3) */
124
+ format: 'wav' | 'mp3';
125
+ }
126
+
127
+ interface VoicesResponse {
128
+ voice_id: string;
129
+ voice_name: string;
130
+ model: string;
131
+ emotions: string[];
132
+ }
133
+
134
+ declare class TypecastClient {
135
+ private client;
136
+ private config;
137
+ constructor(config?: Partial<ClientConfig>);
138
+ textToSpeech(request: TTSRequest): Promise<TTSResponse>;
139
+ getVoices(model?: string): Promise<VoicesResponse[]>;
140
+ getVoiceById(voiceId: string, model?: string): Promise<VoicesResponse[]>;
141
+ }
142
+
143
+ declare class TypecastAPIError extends Error {
144
+ readonly statusCode: number;
145
+ readonly response?: ApiErrorResponse;
146
+ constructor(message: string, statusCode: number, response?: ApiErrorResponse);
147
+ static fromResponse(statusCode: number, statusText: string, data?: ApiErrorResponse): TypecastAPIError;
148
+ }
149
+
150
+ export { type ApiErrorResponse, type ClientConfig, type LanguageCode, type Output, type Prompt, type TTSModel, type TTSRequest, type TTSResponse, TypecastAPIError, TypecastClient, type ValidationError, type ValidationErrorResponse, type VoicesResponse };
package/lib/index.js ADDED
@@ -0,0 +1,108 @@
1
+ import axios from 'axios';
2
+
3
+ // src/client.ts
4
+
5
+ // src/errors.ts
6
+ var TypecastAPIError = class _TypecastAPIError extends Error {
7
+ constructor(message, statusCode, response) {
8
+ super(message);
9
+ this.name = "TypecastAPIError";
10
+ this.statusCode = statusCode;
11
+ this.response = response;
12
+ if (Error.captureStackTrace) {
13
+ Error.captureStackTrace(this, _TypecastAPIError);
14
+ }
15
+ }
16
+ static fromResponse(statusCode, statusText, data) {
17
+ let message;
18
+ switch (statusCode) {
19
+ case 400:
20
+ message = "Bad Request - The request was invalid or cannot be served";
21
+ break;
22
+ case 401:
23
+ message = "Unauthorized - Invalid or missing API key";
24
+ break;
25
+ case 402:
26
+ message = "Payment Required - Insufficient credits to complete the request";
27
+ break;
28
+ case 404:
29
+ message = "Not Found - The requested resource does not exist";
30
+ break;
31
+ case 422:
32
+ message = "Validation Error - The request data failed validation";
33
+ break;
34
+ case 500:
35
+ message = "Internal Server Error - Something went wrong on the server";
36
+ break;
37
+ default:
38
+ message = `API request failed with status ${statusCode}: ${statusText}`;
39
+ }
40
+ if (data?.detail) {
41
+ const detailStr = typeof data.detail === "string" ? data.detail : JSON.stringify(data.detail);
42
+ message += ` - ${detailStr}`;
43
+ }
44
+ return new _TypecastAPIError(message, statusCode, data);
45
+ }
46
+ };
47
+
48
+ // src/client.ts
49
+ var TypecastClient = class {
50
+ constructor(config = {}) {
51
+ this.config = {
52
+ baseHost: process.env.TYPECAST_API_HOST || "https://api.typecast.ai",
53
+ apiKey: process.env.TYPECAST_API_KEY || "",
54
+ ...config
55
+ };
56
+ this.client = axios.create({
57
+ baseURL: this.config.baseHost,
58
+ headers: {
59
+ "X-API-KEY": this.config.apiKey,
60
+ "Content-Type": "application/json"
61
+ }
62
+ });
63
+ this.client.interceptors.response.use(
64
+ (response) => response,
65
+ (error) => {
66
+ if (error.response) {
67
+ throw TypecastAPIError.fromResponse(
68
+ error.response.status,
69
+ error.response.statusText,
70
+ error.response.data
71
+ );
72
+ }
73
+ throw error;
74
+ }
75
+ );
76
+ }
77
+ async textToSpeech(request) {
78
+ const response = await this.client.post("/v1/text-to-speech", request, {
79
+ responseType: "arraybuffer"
80
+ });
81
+ const contentType = String(response.headers["content-type"] || "audio/wav");
82
+ const formatFromHeader = contentType.split("/")[1] || "wav";
83
+ const format = formatFromHeader === "mp3" ? "mp3" : "wav";
84
+ const durationHeader = response.headers["x-audio-duration"];
85
+ const duration = typeof durationHeader === "string" ? Number(durationHeader) : 0;
86
+ return {
87
+ audioData: response.data,
88
+ duration,
89
+ format
90
+ };
91
+ }
92
+ async getVoices(model) {
93
+ const response = await this.client.get("/v1/voices", {
94
+ params: model ? { model } : void 0
95
+ });
96
+ return response.data;
97
+ }
98
+ async getVoiceById(voiceId, model) {
99
+ const response = await this.client.get(`/v1/voices/${voiceId}`, {
100
+ params: model ? { model } : void 0
101
+ });
102
+ return response.data;
103
+ }
104
+ };
105
+
106
+ export { TypecastAPIError, TypecastClient };
107
+ //# sourceMappingURL=index.js.map
108
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/client.ts"],"names":[],"mappings":";;;;;AAEO,IAAM,gBAAA,GAAN,MAAM,iBAAA,SAAyB,KAAA,CAAM;AAAA,EAI1C,WAAA,CAAY,OAAA,EAAiB,UAAA,EAAoB,QAAA,EAA6B;AAC5E,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;AACZ,IAAA,IAAA,CAAK,UAAA,GAAa,UAAA;AAClB,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAGhB,IAAA,IAAI,MAAM,iBAAA,EAAmB;AAC3B,MAAA,KAAA,CAAM,iBAAA,CAAkB,MAAM,iBAAgB,CAAA;AAAA,IAChD;AAAA,EACF;AAAA,EAEA,OAAO,YAAA,CAAa,UAAA,EAAoB,UAAA,EAAoB,IAAA,EAA2C;AACrG,IAAA,IAAI,OAAA;AAEJ,IAAA,QAAQ,UAAA;AAAY,MAClB,KAAK,GAAA;AACH,QAAA,OAAA,GAAU,2DAAA;AACV,QAAA;AAAA,MACF,KAAK,GAAA;A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AE,KAAA,EAAM,GAAI;AAAA,KAC7B,CAAA;AACD,IAAA,OAAO,QAAA,CAAS,IAAA;AAAA,EAClB;AAAA,EAEA,MAAM,YAAA,CAAa,OAAA,EAAiB,KAAA,EAA2C;AAC7E,IAAA,MAAM,WAAW,MAAM,IAAA,CAAK,OAAO,GAAA,CAAsB,CAAA,WAAA,EAAc,OAAO,CAAA,CAAA,EAAI;AAAA,MAChF,MAAA,EAAQ,KAAA,GAAQ,EAAE,KAAA,EAAM,GAAI;AAAA,KAC7B,CAAA;AACD,IAAA,OAAO,QAAA,CAAS,IAAA;AAAA,EAClB;AACF","file":"index.js","sourcesContent":["import { ApiErrorResponse } from './types';\n\nexport class TypecastAPIError extends Error {\n public readonly statusCode: number;\n public readonly response?: ApiErrorResponse;\n\n constructor(message: string, statusCode: number, response?: ApiErrorResponse) {\n super(message);\n this.name = 'TypecastAPIError';\n this.statusCode = statusCode;\n this.response = response;\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, TypecastAPIError);\n }\n }\n\n static fromResponse(statusCode: number, statusText: string, data?: ApiErrorResponse): TypecastAPIError {\n let message: string;\n\n switch (statusCode) {\n case 400:\n message = 'Bad Request - The request was invalid or cannot be served';\n break;\n case 401:\n message = 'Unauthorized - Invalid or missing API key';\n break;\n case 402:\n message = 'Payment Required - Insufficient credits to complete the request';\n break;\n case 404:\n message = 'Not Found - The requested resource does not exist';\n break;\n case 422:\n message = 'Validation Error - The request data failed validation';\n break;\n case 500:\n message = 'Internal Server Error - Something went wrong on the server';\n break;\n default:\n message = `API request failed with status ${statusCode}: ${statusText}`;\n }\n\n if (data?.detail) {\n const detailStr = typeof data.detail === 'string' \n ? data.detail \n : JSON.stringify(data.detail);\n message += ` - ${detailStr}`;\n }\n\n return new TypecastAPIError(message, statusCode, data);\n }\n}\n\n","import axios, { AxiosInstance, AxiosError } from 'axios';\nimport { ClientConfig, TTSRequest, TTSResponse, ApiErrorResponse } from './types';\nimport { VoicesResponse } from './types/Voices';\nimport { TypecastAPIError } from './errors';\n\nexport class TypecastClient {\n private client: AxiosInstance;\n private config: ClientConfig;\n\n constructor(config: Partial<ClientConfig> = {}) {\n this.config = {\n baseHost: process.env.TYPECAST_API_HOST || 'https://api.typecast.ai',\n apiKey: process.env.TYPECAST_API_KEY || '',\n ...config,\n };\n this.client = axios.create({\n baseURL: this.config.baseHost,\n headers: {\n 'X-API-KEY': this.config.apiKey,\n 'Content-Type': 'application/json',\n },\n });\n\n // Add response interceptor for error handling\n this.client.interceptors.response.use(\n (response) => response,\n (error: AxiosError<ApiErrorResponse>) => {\n if (error.response) {\n throw TypecastAPIError.fromResponse(\n error.response.status,\n error.response.statusText,\n error.response.data\n );\n }\n throw error;\n }\n );\n }\n\n async textToSpeech(request: TTSRequest): Promise<TTSResponse> {\n const response = await this.client.post<ArrayBuffer>('/v1/text-to-speech', request, {\n responseType: 'arraybuffer',\n });\n\n const contentType = String(response.headers['content-type'] || 'audio/wav');\n const formatFromHeader = contentType.split('/')[1] || 'wav';\n const format: 'wav' | 'mp3' = formatFromHeader === 'mp3' ? 'mp3' : 'wav';\n\n const durationHeader: unknown = response.headers['x-audio-duration'];\n const duration = typeof durationHeader === 'string' ? Number(durationHeader) : 0;\n\n return {\n audioData: response.data,\n duration,\n format,\n };\n }\n\n async getVoices(model?: string): Promise<VoicesResponse[]> {\n const response = await this.client.get<VoicesResponse[]>('/v1/voices', {\n params: model ? { model } : undefined,\n });\n return response.data;\n }\n\n async getVoiceById(voiceId: string, model?: string): Promise<VoicesResponse[]> {\n const response = await this.client.get<VoicesResponse[]>(`/v1/voices/${voiceId}`, {\n params: model ? { model } : undefined,\n });\n return response.data;\n }\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,78 @@
1
+ {
2
+ "name": "@neosapience/typecast-js",
3
+ "version": "0.1.3",
4
+ "type": "module",
5
+ "main": "./lib/index.cjs",
6
+ "module": "./lib/index.js",
7
+ "types": "./lib/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./lib/index.d.ts",
11
+ "import": "./lib/index.js",
12
+ "require": "./lib/index.cjs"
13
+ }
14
+ },
15
+ "files": [
16
+ "lib",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "scripts": {
21
+ "build": "tsup",
22
+ "test": "vitest",
23
+ "test:coverage": "vitest run --coverage",
24
+ "test:package": "bash scripts/test-package.sh",
25
+ "prepare": "npm run build",
26
+ "prepublishOnly": "npm run lint && vitest run && npm run build",
27
+ "link:dev": "npm link",
28
+ "clean": "rm -rf lib",
29
+ "lint": "eslint src --ext .ts",
30
+ "lint:fix": "eslint src --ext .ts --fix",
31
+ "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
32
+ "format:check": "prettier --check \"src/**/*.ts\" \"test/**/*.ts\""
33
+ },
34
+ "keywords": [
35
+ "typecast",
36
+ "tts",
37
+ "text-to-speech",
38
+ "ai",
39
+ "voice",
40
+ "speech-synthesis",
41
+ "typescript",
42
+ "nodejs",
43
+ "javascript",
44
+ "sdk"
45
+ ],
46
+ "author": "Neosapience <help@typecast.ai>",
47
+ "license": "Apache-2.0",
48
+ "description": "The official Node.js library for the Typecast API. Text-to-Speech with AI voices. TypeScript support included.",
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/neosapience/typecast-js.git"
52
+ },
53
+ "homepage": "https://typecast.ai",
54
+ "bugs": {
55
+ "url": "https://github.com/neosapience/typecast-js/issues"
56
+ },
57
+ "publishConfig": {
58
+ "registry": "https://registry.npmjs.org/",
59
+ "access": "public"
60
+ },
61
+ "engines": {
62
+ "node": ">=16.0.0"
63
+ },
64
+ "devDependencies": {
65
+ "@types/node": "^22.13.5",
66
+ "@typescript-eslint/eslint-plugin": "^7.3.1",
67
+ "@typescript-eslint/parser": "^7.3.1",
68
+ "dotenv": "^16.4.7",
69
+ "eslint": "^8.57.0",
70
+ "prettier": "^3.2.5",
71
+ "tsup": "^8.4.0",
72
+ "typescript": "^5.7.3",
73
+ "vitest": "^3.0.9"
74
+ },
75
+ "dependencies": {
76
+ "axios": "^1.7.9"
77
+ }
78
+ }