namu-ai 0.0.0-stage → 0.1.0

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 ADDED
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (unreleased)
4
+
5
+ First version: `Namu` with `speech`, `transcribe`, `translate`, `converse`, `usage`, `voices` and `models`; types for
6
+ every response; one error class per status; retries for network errors, `rate_limited` and 502/503/504; timeouts; the
7
+ `NAMU_API_KEY` and `NAMU_BASE_URL` environment variables. No runtime dependencies; Node 18+, Deno, Bun, Workers.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,109 @@
1
- # Temporary Holding Version
1
+ # Namu API for JavaScript and TypeScript
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Speech recognition, speech synthesis, translation and a voice agent for **Hausa, Zarma and French**. No dependencies;
4
+ runs on Node 18+, Deno, Bun and Cloudflare Workers.
5
+
6
+ ```bash
7
+ npm install namu-ai
8
+ ```
9
+
10
+ ```typescript
11
+ import { writeFile, readFile } from "node:fs/promises";
12
+ import { Namu } from "namu-ai";
13
+
14
+ const namu = new Namu(); // reads NAMU_API_KEY
15
+
16
+ const audio = await namu.speech("Sannu da zuwa! Muna farin cikin jin muryarku.", { voice: "nadia", format: "mp3" });
17
+ await writeFile("welcome.mp3", Buffer.from(audio));
18
+
19
+ const { text } = await namu.transcribe(await readFile("welcome.mp3"), { language: "ha" });
20
+ ```
21
+
22
+ Get a key at [namuai-lab.com/account/keys](https://www.namuai-lab.com/account/keys). **Server-side only**: never import
23
+ this package in browser or React Native code, where the key would travel with it. During the beta every account gets 30
24
+ minutes of audio a month, free.
25
+
26
+ ## Usage
27
+
28
+ ```typescript
29
+ // Text to speech: nadia (Hausa), mouhamad (Zarma and Hausa), fr (French); wav, mp3 or opus
30
+ const opus = await namu.speech("Fofo! Mate ni go?", { voice: "mouhamad", language: "dje", format: "opus" });
31
+
32
+ // Speech to text: a Blob, ArrayBuffer, Uint8Array or Buffer; ha, dje or fr (not detected: say which)
33
+ const result = await namu.transcribe(await readFile("voice-note.ogg"), { language: "ha" });
34
+
35
+ // Translation, Hausa ⇄ French, from text or speech, optionally spoken back (base64 WAV)
36
+ const fr = await namu.translate({ text: "Ina kwana? Yau za a yi zafi sosai." }, { source: "ha", target: "fr" });
37
+ const spoken = await namu.translate({ audio: await readFile("question.ogg") }, { source: "ha", includeAudio: true });
38
+
39
+ // Voice agent (research preview; the key needs the converse scope)
40
+ const turn = await namu.converse(await readFile("hello.ogg"), { sessionId: "demo-42" });
41
+
42
+ // Account and catalogue
43
+ await namu.usage(); // { month_audio_seconds_used, month_audio_seconds_limit }
44
+ await namu.voices(); // no key needed
45
+ await namu.models();
46
+ ```
47
+
48
+ Every response is typed: `Transcription`, `Translation`, `ConverseTurn`, `Usage`, `VoiceInfo`, `Model`.
49
+
50
+ ## Errors
51
+
52
+ ```typescript
53
+ import { NamuError, QuotaExceededError, BadRequestError } from "namu-ai";
54
+
55
+ try {
56
+ await namu.speech(text);
57
+ } catch (err) {
58
+ if (err instanceof QuotaExceededError) { /* this month's allowance is used */ }
59
+ else if (err instanceof BadRequestError) console.error(err.type, err.message);
60
+ else if (err instanceof NamuError) console.error(err.status, err.type, err.requestId);
61
+ else throw err;
62
+ }
63
+ ```
64
+
65
+ | Class | Status | `type` |
66
+ | --- | --- | --- |
67
+ | `BadRequestError` | 400 | `invalid_request`, `invalid_json`, `missing_text`, `missing_file`, `empty_audio`, `unknown_voice`, `unsupported_language`, `unsupported_pair`, `unknown_persona` |
68
+ | `AuthenticationError` | 401 | `missing_api_key`, `invalid_api_key`, `key_revoked` |
69
+ | `PermissionDeniedError` | 403 | `insufficient_scope`, `account_paused` |
70
+ | `PayloadTooLargeError` | 413 | `payload_too_large`, `audio_too_long`, `text_too_long` |
71
+ | `UnsupportedAudioError` | 415 | `unsupported_audio` |
72
+ | `NothingHeardError` | 422 | `nothing_heard` |
73
+ | `RateLimitError` / `QuotaExceededError` | 429 | `rate_limited` / `quota_exceeded` |
74
+ | `InternalServerError` | 5xx | `internal_error`, `upstream_error`, `upstream_timeout`, ... |
75
+ | `APIConnectionError` / `APITimeoutError` | none | the API could not be reached, or did not answer in time |
76
+
77
+ ## Retries and timeouts
78
+
79
+ Network errors, `429 rate_limited` and `502`/`503`/`504` are retried up to 3 times, after `Retry-After` or 1, 2, 4
80
+ seconds (with jitter); `quota_exceeded` and other 4xx never are. The default timeout is 5 minutes: the first request
81
+ after a quiet spell can take a minute while a model wakes up.
82
+
83
+ ```typescript
84
+ const namu = new Namu({ timeoutMs: 120_000, maxRetries: 5 });
85
+ ```
86
+
87
+ | Option | Environment | Default |
88
+ | --- | --- | --- |
89
+ | `apiKey` | `NAMU_API_KEY` | none |
90
+ | `baseUrl` | `NAMU_BASE_URL` | `https://api.namuai-lab.com` |
91
+ | `timeoutMs` | | 300000 |
92
+ | `maxRetries` | | 3 |
93
+ | `fetch` | | `globalThis.fetch` |
94
+
95
+ ## Data
96
+
97
+ Speech to text and text to speech run on Namu's own models. Translation and the voice agent's replies are written by
98
+ Google Gemini through OpenRouter, which receives the text they work on. Namu keeps usage records, not your audio or
99
+ text.
100
+
101
+ ## Development
102
+
103
+ ```bash
104
+ npm install
105
+ npm test # builds, then runs the mocked tests
106
+ npm run test:live # the free endpoints of the real API
107
+ ```
108
+
109
+ Licensed under Apache 2.0.
@@ -0,0 +1,60 @@
1
+ import type { AudioInput, ConverseTurn, Language, Model, SpeechFormat, Transcription, Translation, Usage, Voice, VoiceInfo } from "./types.ts";
2
+ export declare const DEFAULT_BASE_URL = "https://api.namuai-lab.com";
3
+ export interface ClientOptions {
4
+ /** Your secret key (`namu_sk_...`). Defaults to the `NAMU_API_KEY` environment variable. */
5
+ apiKey?: string;
6
+ /** Defaults to `NAMU_BASE_URL`, then https://api.namuai-lab.com. */
7
+ baseUrl?: string;
8
+ /** Milliseconds to wait for an answer. Generous by default (5 minutes): a model waking up can take a minute. */
9
+ timeoutMs?: number;
10
+ /** Retries for network errors, 429 rate_limited and 502/503/504 (never quota_exceeded or other 4xx). Default 3. */
11
+ maxRetries?: number;
12
+ /** A fetch implementation, for runtimes without a global fetch or for tests. */
13
+ fetch?: typeof fetch;
14
+ }
15
+ /**
16
+ * A client for the Namu API: speech recognition, speech synthesis, translation and a voice agent for Hausa, Zarma
17
+ * and French. Server-side only: the key must never reach a browser or a mobile app.
18
+ *
19
+ * import { Namu } from "namu-ai";
20
+ * const namu = new Namu(); // reads NAMU_API_KEY
21
+ * const audio = await namu.speech("Sannu da zuwa!", { voice: "nadia", format: "mp3" });
22
+ */
23
+ export declare class Namu {
24
+ #private;
25
+ readonly baseUrl: string;
26
+ readonly timeoutMs: number;
27
+ readonly maxRetries: number;
28
+ constructor(options?: ClientOptions);
29
+ /** Speak `text` (up to 2,000 characters). Returns the audio: WAV (24 kHz mono, default), MP3 or Ogg Opus. */
30
+ speech(text: string, opts?: {
31
+ voice?: Voice;
32
+ language?: Language;
33
+ format?: SpeechFormat;
34
+ }): Promise<ArrayBuffer>;
35
+ /** Write down what was said. `language` (default `ha`) is not detected: send the one you expect. */
36
+ transcribe(audio: AudioInput, opts?: {
37
+ language?: Language;
38
+ }): Promise<Transcription>;
39
+ /** Translate Hausa ⇄ French, from text or from audio. `source` defaults to the other language from `target`. */
40
+ translate(input: {
41
+ text: string;
42
+ } | {
43
+ audio: AudioInput;
44
+ }, opts?: {
45
+ target?: "ha" | "fr";
46
+ source?: "ha" | "fr";
47
+ includeAudio?: boolean;
48
+ }): Promise<Translation>;
49
+ /** One turn with the voice agent, in Hausa (research preview; the key needs the converse scope). */
50
+ converse(audio: AudioInput, opts?: {
51
+ sessionId?: string;
52
+ persona?: string;
53
+ }): Promise<ConverseTurn>;
54
+ /** Audio seconds used this calendar month (UTC) and the allowance. Free: counts nothing. */
55
+ usage(): Promise<Usage>;
56
+ /** The voices `speech` can use. No key needed. */
57
+ voices(): Promise<VoiceInfo[]>;
58
+ /** The models, their endpoints, languages and status. No key needed. */
59
+ models(): Promise<Model[]>;
60
+ }
package/dist/client.js ADDED
@@ -0,0 +1,132 @@
1
+ import { APIConnectionError, APITimeoutError, AuthenticationError, NamuError, errorFor } from "./errors.js";
2
+ import { VERSION } from "./version.js";
3
+ export const DEFAULT_BASE_URL = "https://api.namuai-lab.com";
4
+ const RETRY = new Set([429, 502, 503, 504]);
5
+ const env = (name) => globalThis.process?.env?.[name];
6
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
7
+ /**
8
+ * A client for the Namu API: speech recognition, speech synthesis, translation and a voice agent for Hausa, Zarma
9
+ * and French. Server-side only: the key must never reach a browser or a mobile app.
10
+ *
11
+ * import { Namu } from "namu-ai";
12
+ * const namu = new Namu(); // reads NAMU_API_KEY
13
+ * const audio = await namu.speech("Sannu da zuwa!", { voice: "nadia", format: "mp3" });
14
+ */
15
+ export class Namu {
16
+ baseUrl;
17
+ timeoutMs;
18
+ maxRetries;
19
+ #apiKey;
20
+ #fetch;
21
+ constructor(options = {}) {
22
+ this.#apiKey = options.apiKey ?? env("NAMU_API_KEY");
23
+ this.baseUrl = (options.baseUrl ?? env("NAMU_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
24
+ this.timeoutMs = options.timeoutMs ?? 300_000;
25
+ this.maxRetries = Math.max(0, options.maxRetries ?? 3);
26
+ const f = options.fetch ?? globalThis.fetch;
27
+ if (!f)
28
+ throw new NamuError("No fetch available: use Node 18+ or pass { fetch }.");
29
+ this.#fetch = f.bind(globalThis);
30
+ }
31
+ /** Speak `text` (up to 2,000 characters). Returns the audio: WAV (24 kHz mono, default), MP3 or Ogg Opus. */
32
+ async speech(text, opts = {}) {
33
+ const json = { text, voice: opts.voice ?? "nadia", format: opts.format ?? "wav" };
34
+ if (opts.language)
35
+ json.language = opts.language;
36
+ return (await this.#request("POST", "/v1/speech", { json })).arrayBuffer();
37
+ }
38
+ /** Write down what was said. `language` (default `ha`) is not detected: send the one you expect. */
39
+ async transcribe(audio, opts = {}) {
40
+ return (await this.#request("POST", "/v1/transcribe", { form: { file: audio, language: opts.language ?? "ha" } })).json();
41
+ }
42
+ /** Translate Hausa ⇄ French, from text or from audio. `source` defaults to the other language from `target`. */
43
+ async translate(input, opts = {}) {
44
+ const target = opts.target ?? "fr";
45
+ if ("text" in input) {
46
+ return (await this.#request("POST", "/v1/translate", { json: { text: input.text, target, include_audio: Boolean(opts.includeAudio), ...(opts.source ? { source: opts.source } : {}) } })).json();
47
+ }
48
+ return (await this.#request("POST", "/v1/translate", { form: { file: input.audio, target, source: opts.source, include_audio: opts.includeAudio ? "true" : undefined } })).json();
49
+ }
50
+ /** One turn with the voice agent, in Hausa (research preview; the key needs the converse scope). */
51
+ async converse(audio, opts = {}) {
52
+ return (await this.#request("POST", "/v1/converse", { form: { file: audio, persona: opts.persona ?? "nadia", session_id: opts.sessionId } })).json();
53
+ }
54
+ /** Audio seconds used this calendar month (UTC) and the allowance. Free: counts nothing. */
55
+ async usage() {
56
+ return (await this.#request("GET", "/v1/usage")).json();
57
+ }
58
+ /** The voices `speech` can use. No key needed. */
59
+ async voices() {
60
+ return (await (await this.#request("GET", "/v1/voices", {}, false)).json()).data;
61
+ }
62
+ /** The models, their endpoints, languages and status. No key needed. */
63
+ async models() {
64
+ return (await (await this.#request("GET", "/v1/models", {}, false)).json()).data;
65
+ }
66
+ async #request(method, path, body = {}, auth = true) {
67
+ const headers = { Accept: "application/json", "User-Agent": `namu-js/${VERSION}` };
68
+ if (auth) {
69
+ if (!this.#apiKey)
70
+ throw new AuthenticationError("Set NAMU_API_KEY or pass { apiKey }.", { status: 401, type: "missing_api_key" });
71
+ headers.Authorization = `Bearer ${this.#apiKey}`;
72
+ }
73
+ for (let attempt = 0;; attempt++) {
74
+ let res;
75
+ try {
76
+ res = await this.#fetch(this.baseUrl + path, { method, headers: { ...headers, ...contentType(body) }, body: encode(body), signal: AbortSignal.timeout(this.timeoutMs) });
77
+ }
78
+ catch (cause) {
79
+ const timedOut = cause?.name === "TimeoutError";
80
+ const error = timedOut
81
+ ? new APITimeoutError(`No answer within ${this.timeoutMs / 1000} s.`, { cause })
82
+ : new APIConnectionError(`Could not reach the Namu API: ${cause?.name ?? "error"}.`, { cause });
83
+ if (attempt >= this.maxRetries)
84
+ throw error;
85
+ await sleep(delay(attempt, null));
86
+ continue;
87
+ }
88
+ if (res.ok)
89
+ return res;
90
+ const error = await apiError(res);
91
+ if (!RETRY.has(res.status) || error.type === "quota_exceeded" || attempt >= this.maxRetries)
92
+ throw error;
93
+ await sleep(delay(attempt, res.headers.get("Retry-After")));
94
+ }
95
+ }
96
+ }
97
+ function contentType(body) {
98
+ return body.json !== undefined ? { "Content-Type": "application/json" } : {};
99
+ }
100
+ function encode(body) {
101
+ if (body.json !== undefined)
102
+ return JSON.stringify(body.json);
103
+ if (!body.form)
104
+ return undefined;
105
+ const form = new FormData();
106
+ for (const [key, value] of Object.entries(body.form)) {
107
+ if (value === undefined)
108
+ continue;
109
+ if (typeof value === "string")
110
+ form.append(key, value);
111
+ else
112
+ form.append(key, value instanceof Blob ? value : new Blob([value]), "audio");
113
+ }
114
+ return form;
115
+ }
116
+ function delay(attempt, retryAfter) {
117
+ const seconds = retryAfter === null ? NaN : Number(retryAfter);
118
+ if (Number.isFinite(seconds))
119
+ return Math.min(Math.max(seconds, 0), 60) * 1000;
120
+ return Math.min(2 ** attempt, 16) * 1000 * (0.75 + Math.random() / 2); // 1, 2, 4 … seconds, with jitter
121
+ }
122
+ async function apiError(res) {
123
+ const requestId = res.headers.get("X-Request-Id") ?? undefined;
124
+ const text = await res.text().catch(() => "");
125
+ try {
126
+ const { error } = JSON.parse(text);
127
+ return errorFor(res.status, error.type || "http_error", error.message ?? "", error.request_id || requestId);
128
+ }
129
+ catch {
130
+ return errorFor(res.status, "http_error", text.slice(0, 200), requestId);
131
+ }
132
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Errors thrown by the Namu client. Every error is a `NamuError`; errors the API answered carry its stable `type`
3
+ * (branch on it), the HTTP `status`, a `message` for developers and the `requestId` to send Namu.
4
+ *
5
+ * NamuError
6
+ * ├── APIConnectionError the request did not reach the API, or no answer came back
7
+ * │ └── APITimeoutError no answer within the client's timeout
8
+ * └── APIStatusError the API answered with an error status
9
+ * ├── BadRequestError 400
10
+ * ├── AuthenticationError 401
11
+ * ├── PermissionDeniedError 403
12
+ * ├── NotFoundError 404
13
+ * ├── PayloadTooLargeError 413
14
+ * ├── UnsupportedAudioError 415
15
+ * ├── NothingHeardError 422
16
+ * ├── RateLimitError 429 rate_limited
17
+ * │ └── QuotaExceededError 429 quota_exceeded (never retried)
18
+ * └── InternalServerError 5xx
19
+ */
20
+ export declare class NamuError extends Error {
21
+ readonly status?: number;
22
+ readonly type?: string;
23
+ readonly requestId?: string;
24
+ constructor(message: string, opts?: {
25
+ status?: number;
26
+ type?: string;
27
+ requestId?: string;
28
+ cause?: unknown;
29
+ });
30
+ }
31
+ export declare class APIConnectionError extends NamuError {
32
+ }
33
+ export declare class APITimeoutError extends APIConnectionError {
34
+ }
35
+ export declare class APIStatusError extends NamuError {
36
+ readonly status: number;
37
+ readonly type: string;
38
+ }
39
+ export declare class BadRequestError extends APIStatusError {
40
+ }
41
+ export declare class AuthenticationError extends APIStatusError {
42
+ }
43
+ export declare class PermissionDeniedError extends APIStatusError {
44
+ }
45
+ export declare class NotFoundError extends APIStatusError {
46
+ }
47
+ export declare class PayloadTooLargeError extends APIStatusError {
48
+ }
49
+ export declare class UnsupportedAudioError extends APIStatusError {
50
+ }
51
+ export declare class NothingHeardError extends APIStatusError {
52
+ }
53
+ export declare class RateLimitError extends APIStatusError {
54
+ }
55
+ export declare class QuotaExceededError extends RateLimitError {
56
+ }
57
+ export declare class InternalServerError extends APIStatusError {
58
+ }
59
+ /** The most specific error class for an API answer. */
60
+ export declare function errorFor(status: number, type: string, message: string, requestId?: string): APIStatusError;
package/dist/errors.js ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Errors thrown by the Namu client. Every error is a `NamuError`; errors the API answered carry its stable `type`
3
+ * (branch on it), the HTTP `status`, a `message` for developers and the `requestId` to send Namu.
4
+ *
5
+ * NamuError
6
+ * ├── APIConnectionError the request did not reach the API, or no answer came back
7
+ * │ └── APITimeoutError no answer within the client's timeout
8
+ * └── APIStatusError the API answered with an error status
9
+ * ├── BadRequestError 400
10
+ * ├── AuthenticationError 401
11
+ * ├── PermissionDeniedError 403
12
+ * ├── NotFoundError 404
13
+ * ├── PayloadTooLargeError 413
14
+ * ├── UnsupportedAudioError 415
15
+ * ├── NothingHeardError 422
16
+ * ├── RateLimitError 429 rate_limited
17
+ * │ └── QuotaExceededError 429 quota_exceeded (never retried)
18
+ * └── InternalServerError 5xx
19
+ */
20
+ export class NamuError extends Error {
21
+ status;
22
+ type;
23
+ requestId;
24
+ constructor(message, opts = {}) {
25
+ const prefix = [opts.status, opts.type].filter((x) => x !== undefined).join(" ");
26
+ super(prefix ? `${prefix}: ${message}${opts.requestId ? ` (request ${opts.requestId})` : ""}` : message, opts.cause === undefined ? undefined : { cause: opts.cause });
27
+ this.name = new.target.name;
28
+ this.status = opts.status;
29
+ this.type = opts.type;
30
+ this.requestId = opts.requestId;
31
+ }
32
+ }
33
+ export class APIConnectionError extends NamuError {
34
+ }
35
+ export class APITimeoutError extends APIConnectionError {
36
+ }
37
+ export class APIStatusError extends NamuError {
38
+ }
39
+ export class BadRequestError extends APIStatusError {
40
+ }
41
+ export class AuthenticationError extends APIStatusError {
42
+ }
43
+ export class PermissionDeniedError extends APIStatusError {
44
+ }
45
+ export class NotFoundError extends APIStatusError {
46
+ }
47
+ export class PayloadTooLargeError extends APIStatusError {
48
+ }
49
+ export class UnsupportedAudioError extends APIStatusError {
50
+ }
51
+ export class NothingHeardError extends APIStatusError {
52
+ }
53
+ export class RateLimitError extends APIStatusError {
54
+ }
55
+ export class QuotaExceededError extends RateLimitError {
56
+ }
57
+ export class InternalServerError extends APIStatusError {
58
+ }
59
+ const BY_STATUS = {
60
+ 400: BadRequestError, 401: AuthenticationError, 403: PermissionDeniedError, 404: NotFoundError,
61
+ 413: PayloadTooLargeError, 415: UnsupportedAudioError, 422: NothingHeardError, 429: RateLimitError,
62
+ };
63
+ /** The most specific error class for an API answer. */
64
+ export function errorFor(status, type, message, requestId) {
65
+ const Cls = status === 429 && type === "quota_exceeded" ? QuotaExceededError
66
+ : status >= 500 ? InternalServerError
67
+ : BY_STATUS[status] ?? APIStatusError;
68
+ return new Cls(message, { status, type, requestId });
69
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The Namu API for JavaScript and TypeScript: speech recognition, speech synthesis, translation and a voice agent for
3
+ * Hausa, Zarma and French. https://www.namuai-lab.com
4
+ */
5
+ export { Namu, DEFAULT_BASE_URL } from "./client.ts";
6
+ export type { ClientOptions } from "./client.ts";
7
+ export { NamuError, APIConnectionError, APITimeoutError, APIStatusError, BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, PayloadTooLargeError, UnsupportedAudioError, NothingHeardError, RateLimitError, QuotaExceededError, InternalServerError, } from "./errors.ts";
8
+ export type * from "./types.ts";
9
+ export { VERSION } from "./version.ts";
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The Namu API for JavaScript and TypeScript: speech recognition, speech synthesis, translation and a voice agent for
3
+ * Hausa, Zarma and French. https://www.namuai-lab.com
4
+ */
5
+ export { Namu, DEFAULT_BASE_URL } from "./client.js";
6
+ export { NamuError, APIConnectionError, APITimeoutError, APIStatusError, BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, PayloadTooLargeError, UnsupportedAudioError, NothingHeardError, RateLimitError, QuotaExceededError, InternalServerError, } from "./errors.js";
7
+ export { VERSION } from "./version.js";
@@ -0,0 +1,64 @@
1
+ /** `ha` Hausa, `dje` Zarma, `fr` French. */
2
+ export type Language = "ha" | "dje" | "fr";
3
+ /** `nadia` (Hausa; `warm` is the same voice), `mouhamad` (Zarma and Hausa), `fr` (French). */
4
+ export type Voice = "nadia" | "warm" | "mouhamad" | "fr";
5
+ export type SpeechFormat = "wav" | "mp3" | "opus";
6
+ /** Audio to send: any of WAV, MP3, M4A/AAC, OGG/Opus, WebM or FLAC, up to 25 MB and 5 minutes. */
7
+ export type AudioInput = Blob | ArrayBuffer | ArrayBufferView;
8
+ export interface Transcription {
9
+ model: string;
10
+ /** What was said, in lower case, without punctuation. */
11
+ text: string;
12
+ language: string;
13
+ /** The length of the audio sent: what was counted. */
14
+ audio_seconds: number;
15
+ }
16
+ export interface Translation {
17
+ model: string;
18
+ source: "ha" | "fr";
19
+ target: "ha" | "fr";
20
+ /** The text sent, or what was heard in the audio. */
21
+ source_text: string;
22
+ /** The translation. */
23
+ text: string;
24
+ /** Text requests: the characters translated. */
25
+ characters?: number;
26
+ /** Audio requests: the length of the audio sent. */
27
+ audio_seconds?: number;
28
+ /** With includeAudio: the translation spoken, base64 WAV. */
29
+ audio?: string | null;
30
+ }
31
+ export interface ConverseTurn {
32
+ model: string;
33
+ persona: string;
34
+ session_id: string | null;
35
+ /** What the person said, as text. */
36
+ heard: string;
37
+ /** The answer, as text. */
38
+ reply: string;
39
+ /** The answer spoken, base64 WAV. */
40
+ audio: string;
41
+ sample_rate: number;
42
+ /** Audio sent plus the reply: what was counted. */
43
+ audio_seconds: number;
44
+ }
45
+ export interface Usage {
46
+ month_audio_seconds_used: number;
47
+ month_audio_seconds_limit: number;
48
+ }
49
+ export interface Model {
50
+ id: string;
51
+ task: string;
52
+ endpoint: string;
53
+ scope: string;
54
+ languages: Language[];
55
+ /** `beta` or `research`. */
56
+ status: string;
57
+ }
58
+ export interface VoiceInfo {
59
+ id: string;
60
+ languages: Language[];
61
+ /** The voice's first language. */
62
+ language: Language;
63
+ description: string;
64
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export declare const VERSION = "0.1.0";
@@ -0,0 +1 @@
1
+ export const VERSION = "0.1.0";
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "namu-ai",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The Namu API for JavaScript and TypeScript: speech recognition, speech synthesis and translation for Hausa, Zarma and French.",
5
+ "license": "Apache-2.0",
6
+ "author": "Namu AI Lab <contact@namuai.org>",
7
+ "homepage": "https://www.namuai-lab.com/api",
8
+ "keywords": ["namu", "speech", "text-to-speech", "speech-to-text", "translation", "hausa", "zarma", "french", "sahel"],
9
+ "type": "module",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "files": ["dist", "README.md", "CHANGELOG.md", "LICENSE"],
19
+ "sideEffects": false,
20
+ "engines": { "node": ">=18" },
21
+ "scripts": {
22
+ "build": "rm -rf dist && tsc -p tsconfig.json",
23
+ "typecheck": "tsc -p tsconfig.json --noEmit",
24
+ "test": "npm run build && node --test test/*.test.mjs",
25
+ "test:live": "npm run build && NAMU_LIVE=1 node --test test/live.test.mjs",
26
+ "prepublishOnly": "npm test"
27
+ },
28
+ "devDependencies": {
29
+ "typescript": "5.9.3"
30
+ }
31
+ }