> ## Documentation Index
> Fetch the complete documentation index at: https://docs.supertoneapi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK

> Supertone TypeScript SDKをインストールし、認証し、利用する方法 — PromiseベースAPI、ストリーミング、自動チャンク分割、NodeおよびBunで動作。

<Note>
  このドキュメントは英語の原文から自動翻訳されています。表現に不自然な箇所がある場合があります。正確な内容は[英語の原文](/en/docs/developer-tools/typescript)もあわせてご確認ください。
</Note>

公式のTypeScript SDKは、npmで[`@supertone/supertone`](https://www.npmjs.com/package/@supertone/supertone)として公開されています。ソース：[supertone-inc/supertone-ts](https://github.com/supertone-inc/supertone-ts)。

## 早わかり

|                 |                                                                                  |
| --------------- | -------------------------------------------------------------------------------- |
| **パッケージ**       | npmの[`@supertone/supertone`](https://www.npmjs.com/package/@supertone/supertone) |
| **リポジトリ**       | [supertone-inc/supertone-ts](https://github.com/supertone-inc/supertone-ts)      |
| **言語**          | TypeScript 5+ / Node 18+                                                         |
| **モジュール形式**     | ESM + CommonJS                                                                   |
| **認証**          | `new Supertone({ apiKey: ... })`                                                 |
| **同期API**       | n/a                                                                              |
| **非同期API**      | すべてのメソッド（Promise）                                                                |
| **ストリーミング**     | `ReadableStream`リーダー                                                             |
| **長文の自動チャンク分割** | ✅ 300文字、逐次                                                                       |
| **カスタムリトライ**    | ✅ `retryConfig`経由                                                                |
| **HTTPバックエンド**  | `fetch`                                                                          |

## インストール

<Tabs>
  <Tab title="npm">
    ```bash theme={"dark"}
    npm add @supertone/supertone
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash theme={"dark"}
    pnpm add @supertone/supertone
    ```
  </Tab>

  <Tab title="bun">
    ```bash theme={"dark"}
    bun add @supertone/supertone
    ```
  </Tab>

  <Tab title="yarn">
    Yarnの場合はピア依存を手動でインストールする必要があります。

    ```bash theme={"dark"}
    yarn add @supertone/supertone zod
    ```
  </Tab>
</Tabs>

このパッケージは**ESM**と**CommonJS**の両方のエントリポイントで公開されており、TypeScriptの型定義も同梱されています。Node 18以上が必要です（グローバルな`fetch`および`ReadableStream`のため）。BunおよびDenoでも動作します。ブラウザ向けには設計されていません（API Keyはクライアント側に置くべきではありません）。

## API Keyを設定する

```bash theme={"dark"}
export SUPERTONE_API_KEY="Kp9mZ3xQ7v..."
```

```typescript theme={"dark"}
import { Supertone } from "@supertone/supertone";

const client = new Supertone({ apiKey: process.env.SUPERTONE_API_KEY });
```

ボイスIDは環境変数ではありません。用途ごとに変わるため、コード内のプレーンな文字列として保持するか（あるいはリクエストペイロードから渡してください）。

## 音声を生成する

```typescript theme={"dark"}
import { Supertone } from "@supertone/supertone";
import * as fs from "node:fs";

const VOICE_ID = "20160a4c5ba38967330c84"; // replace with your voice ID

const client = new Supertone({ apiKey: process.env.SUPERTONE_API_KEY });

const response = await client.textToSpeech.createSpeech({
  voiceId: VOICE_ID,
  apiConvertTextToSpeechUsingCharacterRequest: {
    text: "Hello from the TypeScript SDK.",
    language: "en",
    model: "sona_speech_1",
    outputFormat: "wav",
  },
});

if (response.result instanceof Uint8Array) {
  fs.writeFileSync("speech.wav", response.result);
} else if (response.result && "getReader" in response.result) {
  const reader = (response.result as ReadableStream<Uint8Array>).getReader();
  const chunks: Uint8Array[] = [];
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    if (value) chunks.push(value);
  }
  fs.writeFileSync("speech.wav", Buffer.concat(chunks));
}
```

すべてのメソッドは非同期であり、Promiseを返します。同期版はありません。

## 音声をストリーミングする

```typescript theme={"dark"}
import { Supertone } from "@supertone/supertone";
import * as fs from "node:fs";

const VOICE_ID = "20160a4c5ba38967330c84"; // replace with your voice ID

const client = new Supertone({ apiKey: process.env.SUPERTONE_API_KEY });

const response = await client.textToSpeech.streamSpeech({
  voiceId: VOICE_ID,
  apiConvertTextToSpeechUsingCharacterRequest: {
    text: "This response is streamed chunk by chunk.",
    language: "en",
    model: "sona_speech_1",
  },
});

if (response.result && typeof response.result === "object" && "getReader" in response.result) {
  const reader = (response.result as ReadableStream<Uint8Array>).getReader();
  const chunks: Uint8Array[] = [];
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    if (value) chunks.push(value);
  }
  fs.writeFileSync("streamed.wav", Buffer.concat(chunks));
}
```

ストリーミングは現在`sona_speech_1`のみ対応しています。

## 長文の自動チャンク分割

`createSpeech`と`streamSpeech`は、いずれも300文字を超えるテキストを自動的にチャンク分割します。テキストはそのまま渡してください。SDKが分割し、セグメントごとに生成し、結果を結合（またはストリーミング）します。

```typescript theme={"dark"}
const response = await client.textToSpeech.createSpeech(
  {
    voiceId: VOICE_ID,
    apiConvertTextToSpeechUsingCharacterRequest: { text: longText, language: "en" },
  },
  {
    maxTextLength: 300, // optional override (default 300)
  },
);
```

`predictDuration`は自動チャンク分割を**行いません**。300文字制限が強制されます。

詳細は[長文](/ja/docs/text-to-speech/long-text)を参照してください。

## 一般的な操作

```typescript theme={"dark"}
// List voices with pagination
const list = await client.voices.listVoices({ pageSize: 20 });

// Search voices
const search = await client.voices.searchVoices({
  language: "ko,en",
  style: "happy",
});

// Get a single voice
const voice = await client.voices.getVoice({ voiceId: VOICE_ID });

// Predict duration (no credits deducted)
const { duration } = await client.textToSpeech.predictDuration({
  voiceId: VOICE_ID,
  predictTTSDurationRequest: {
    text: "How long will this be?",
    language: "en",
  },
});

// Get credit balance
const balance = await client.usage.getCreditBalance();
```

## 型安全なenum（任意）

型安全性を求める場合、SDKは`@supertone/supertone/models`にenum定数を公開しています。

```typescript theme={"dark"}
import * as models from "@supertone/supertone/models";

models.APIConvertTextToSpeechUsingCharacterRequestLanguage.En;     // "en"
models.APIConvertTextToSpeechUsingCharacterRequestModel.SonaSpeech1; // "sona_speech_1"
```

プレーンな文字列リテラル（`"en"`、`"sona_speech_1"`）も動作します。お好みのスタイルをお使いください。

## エラー処理

エラーは`@supertone/supertone/models/errors`に定義されており、すべて`SupertoneError`を継承しています。

```typescript theme={"dark"}
import { Supertone } from "@supertone/supertone";
import * as errors from "@supertone/supertone/models/errors";

const client = new Supertone({ apiKey: process.env.SUPERTONE_API_KEY });

try {
  const response = await client.textToSpeech.createSpeech({ /* ... */ });
} catch (err) {
  if (err instanceof errors.TooManyRequestsErrorResponse) {
    console.log("Rate limited:", err.message);
  } else if (err instanceof errors.UnauthorizedErrorResponse) {
    console.log("Auth failed:", err.message);
  } else if (err instanceof errors.PaymentRequiredErrorResponse) {
    console.log("Out of credits:", err.message);
  } else if (err instanceof errors.SupertoneError) {
    console.log(`HTTP ${err.statusCode}: ${err.message}`);
  } else {
    throw err;
  }
}
```

| エラークラス                              | HTTPステータス |
| ----------------------------------- | --------- |
| `BadRequestErrorResponse`           | 400       |
| `UnauthorizedErrorResponse`         | 401       |
| `PaymentRequiredErrorResponse`      | 402       |
| `ForbiddenErrorResponse`            | 403       |
| `NotFoundErrorResponse`             | 404       |
| `RequestTimeoutErrorResponse`       | 408       |
| `PayloadTooLargeErrorResponse`      | 413       |
| `UnsupportedMediaTypeErrorResponse` | 415       |
| `TooManyRequestsErrorResponse`      | 429       |
| `InternalServerErrorResponse`       | 500       |

ネットワーク層のエラー（`ConnectionError`、`RequestTimeoutError`、`RequestAbortedError`など）は`SupertoneError`ではなく`HTTPClientError`を継承します。

## 設定

```typescript theme={"dark"}
const client = new Supertone({
  apiKey: process.env.SUPERTONE_API_KEY,
  timeoutMs: 30_000,
  retryConfig: {
    strategy: "backoff",
    backoff: { initialInterval: 500, maxInterval: 60_000, exponent: 1.5, maxElapsedTime: 3_600_000 },
    retryConnectionErrors: true,
  },
});
```

## 関連項目

<CardGroup cols={2}>
  <Card title="Python SDK" icon="python" href="/ja/docs/developer-tools/python">
    Python向けの同等のSDK。
  </Card>

  <Card title="サンプル" icon="lightbulb" href="/ja/docs/examples/llm-streaming-tts">
    一般的なワークフローのレシピ。
  </Card>
</CardGroup>
