ssml-builder-js 2.3.0 → 2.5.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/README.md CHANGED
@@ -36,6 +36,8 @@ React エディタを使用する場合は、React と Monaco Editor のアダ
36
36
  npm install ssml-builder-js @monaco-editor/react react react-dom
37
37
  ```
38
38
 
39
+ ルートパッケージの React peer dependency は `>=18.2.0 <20` です。React 18.3.1 を使う Next.js の Pages Router / App Router アプリでは、この範囲に一致するため依存関係警告は発生しません。Monaco を使う `SsmlEditor` はクライアントコンポーネントとして配置してください。
40
+
39
41
  Web Component を使用する場合は、Monaco Editor もインストールします。
40
42
 
41
43
  ```sh
@@ -132,9 +134,36 @@ const parsed = parseSsml(ssml);
132
134
  | `buildPartialSsml(text, context?)` / `buildPartialSsml({ text, ...context })` | 言語、音声、プロソディなどのコンテキスト付きで部分テキストから最小の SSML を生成 |
133
135
  | `parseSsml(xml)` | `<speak>` XML を `SsmlDocument` に変換 |
134
136
  | `validateSsml(xml)` | SSML の構文エラーを `{ message, position }` または `null` で返す |
137
+ | `extractSsmlText(xml)` | タグを除いた全テキストノードを文書順に抽出 |
138
+ | `mapSsmlTextNodes(xml, transform, options?)` | タグ構造を維持したままテキストノードだけを同期・非同期変換。スキップタグとコンテキストフィルターに対応 |
139
+ | `validateAzureSsml(xml, options?)` | Azure Speech 向けの意味検証結果を Diagnostic 配列で返す |
135
140
 
136
141
  `voice`、`prosody`、`break`、`express-as`、`say-as`、`phoneme`、`audio`、`lang`、`mark` などの要素を型付きで表現できます。`type: "custom"` と `name` を指定すれば、未定義の XML 要素や追加属性も扱えます。`mstts:` 要素を含むドキュメントを生成すると、必要な Azure Speech 名前空間が自動的に追加されます。
137
142
 
143
+ 翻訳などで本文だけを置き換える場合は、`mapSsmlTextNodes` に変換関数を渡します。変換関数には直近の親タグと祖先タグの `path` が渡され、戻り値は `string` または `Promise<string>` を指定できます。`validateAzureSsml` は音声、属性値、音声スタイル、文字数、`audio` URL/オリジンを検証します。
144
+
145
+ `mapSsmlTextNodes` の第 3 引数で、翻訳対象外タグとコンテキストフィルターを指定できます。デフォルトでは `phoneme`、`say-as`、`sub` の本文を変換しません。`filter` には `parentTag`、`parentAttributes`、`ancestorTags`、`path` が渡されます。
146
+
147
+ ```ts
148
+ const translated = await mapSsmlTextNodes(ssml, translate, {
149
+ skipTags: ["phoneme", "say-as", "sub", "custom-no-translate"],
150
+ filter: ({ parentAttributes, ancestorTags }) =>
151
+ ancestorTags.includes("voice") && parentAttributes["xml:lang"] !== "ja-JP",
152
+ });
153
+ ```
154
+
155
+ `validateAzureSsml` は `AzureValidationOptions` で音声・スタイルの定義を追加できます。`unknownVoicePolicy` のデフォルトは `"warn"`、`validateNestedVoices` のデフォルトは `true` です。`audio` の外部 URL はデフォルトで拒否されるため、利用する場合は `allowedAudioOrigins` に許可するオリジンを列挙するか、構成を理解した上で `allowExternalAudio: true` を指定してください。
156
+
157
+ ```ts
158
+ const diagnostics = validateAzureSsml(ssml, {
159
+ customVoiceStyleMap: { "my-custom-voice": ["narration"] },
160
+ unknownVoicePolicy: "error", // "error" | "warn" | "ignore"
161
+ allowedAudioOrigins: ["https://cdn.example.com"],
162
+ });
163
+ ```
164
+
165
+ Azure Speech は `<audio>` の URL を取得するため、任意の URL をそのまま受け付けるサーバーは SSRF の踏み台になり得ます。ユーザー入力の SSML を合成する場合は、HTTPS、許可オリジン、リダイレクト先、応答サイズをサーバー側でも制限し、`allowExternalAudio` だけで無制限に許可しないでください。
166
+
138
167
  ## `ssml-editor-react` の利用方法
139
168
 
140
169
  `SsmlEditor` は `SsmlDocument` を受け取り、ツールバーと本文の表示エリアだけを表示するシンプルなコンポーネントです。ツールバーから選択範囲の速度、音量、ピッチなどの設定、元に戻す・やり直す操作ができます。音声の選択と表示はアプリ側で行います。本文の編集には Monaco Editor を使用し、変更時に SSML の構文を検証します。構文エラーはエディター上のマーカーとエラーメッセージで表示されます。XML のタグ名やパラメータへホバーすると SSML の説明を確認できます。テキストを選択すると、選択文字数と試聴を行うフローティングアクションが表示されます。`enableCodeLens`(デフォルトは `true`)が有効な場合、`prosody` と `break` タグの上に属性編集やタグ操作の CodeLens が表示されます。`showDecorations` が有効な場合、`break` と `prosody` のタグに間やピッチ変化を示すインラインバッジが表示され、Monaco のインライン装飾も有効になります。生成された SSML は `onSsmlChange` で受け取り、アプリ側で自由に表示できます。`SsmlEditorRef` を `ref` に渡すと、全体、選択範囲、または現在行の SSML を取得できます。画面表示は日本語(デフォルト)と英語に対応しています。
@@ -238,6 +267,17 @@ const audio = await client.synthesize(ssml);
238
267
  // audio は audio/mpeg の ArrayBuffer
239
268
  ```
240
269
 
270
+ 帯域幅を抑える場合は `audio-24khz-48kbitrate-mono-mp3` または `audio-16khz-32kbitrate-mono-mp3` を指定できます。
271
+
272
+ ```ts
273
+ const client = new AzureTtsClient({
274
+ subscriptionKey: process.env.AZURE_SPEECH_KEY!,
275
+ region: process.env.AZURE_SPEECH_REGION!,
276
+ outputFormat: "audio-24khz-48kbitrate-mono-mp3",
277
+ timeoutMs: 15_000,
278
+ });
279
+ ```
280
+
241
281
  低レベルの `synthesizeSpeech` 関数も利用できます。この関数では `TtsConfig` の
242
282
  `endpoint`、`subscriptionKey`、`region` を指定します。
243
283
 
@@ -252,7 +292,47 @@ const audio = await synthesizeSpeech(ssml, {
252
292
  ```
253
293
 
254
294
  内部では Microsoft Cognitive Services Speech SDK の `SpeechSynthesizer` を使用します。`AzureTtsClient` の `endpoint` を省略すると `https://{region}.tts.speech.microsoft.com/cognitiveservices/v1` が使用されます。上の Playground の例では `.env.example` に合わせて WebSocket エンドポイントを明示しています。独自エンドポイントに `{region}` を含めた場合は、設定したリージョンに置き換えられます。
295
+ `endpoint` に空文字または空白文字列を指定した場合も、リージョンの既定エンドポイントへフォールバックします。`logger` オプションには `debug`、`info`、`warn`、`error` を持つロガーを注入できます。省略時はクライアントからログを出力しません。
255
296
  `outputFormat` には Speech SDK がサポートする出力形式を指定できます。省略時は `audio-16khz-128kbitrate-mono-mp3` が使用されます。
297
+ `timeoutMs` は合成を打ち切る時間(ミリ秒)、`signal` はクライアント切断などによるキャンセル用の `AbortSignal` です。リトライする場合は、タイムアウトや一時的な SDK エラーだけを対象にし、同じ `AbortSignal` を渡して指数バックオフを使用してください。
298
+
299
+ Next.js Route Handler ではキーをブラウザへ渡さず、サーバー側で検証・合成します。
300
+
301
+ ```ts
302
+ // app/api/synthesize/route.ts
303
+ import { AzureTtsClient, AzureTtsError } from "@ssml-builder-js/azure-tts-client";
304
+ import { validateAzureSsml, validateSsml } from "@ssml-builder-js/ssml-core";
305
+
306
+ export const runtime = "nodejs";
307
+
308
+ export async function POST(request: Request) {
309
+ const body = (await request.json()) as { ssml?: unknown };
310
+ if (typeof body.ssml !== "string" || validateSsml(body.ssml))
311
+ return Response.json({ error: "Invalid SSML" }, { status: 400 });
312
+ if (validateAzureSsml(body.ssml).some(({ severity }) => severity === "error"))
313
+ return Response.json({ error: "Invalid Azure SSML" }, { status: 400 });
314
+
315
+ const controller = new AbortController();
316
+ const timeout = setTimeout(() => controller.abort(), 15_000);
317
+ request.signal.addEventListener("abort", () => controller.abort(), { once: true });
318
+ try {
319
+ const audio = await new AzureTtsClient({
320
+ subscriptionKey: process.env.AZURE_SPEECH_KEY!,
321
+ region: process.env.AZURE_SPEECH_REGION!,
322
+ signal: controller.signal,
323
+ outputFormat: "audio-24khz-48kbitrate-mono-mp3",
324
+ }).synthesize(body.ssml);
325
+ return new Response(new Uint8Array(audio), { headers: { "Content-Type": "audio/mpeg" } });
326
+ } catch (error) {
327
+ const status = error instanceof AzureTtsError && error.status === 0 ? 504 : 502;
328
+ return Response.json({ error: "Speech synthesis failed" }, { status });
329
+ } finally {
330
+ clearTimeout(timeout);
331
+ }
332
+ }
333
+ ```
334
+
335
+ リトライを追加する場合は、`AzureTtsSdkError` の内容をログへ出しすぎず、SSML 本文とサブスクリプションキーをログへ書かないでください。外部 `audio` を使う場合も、上記の許可オリジン検証を合成前に実施してください。
256
336
 
257
337
  Speech SDK の合成エラーでは `AzureTtsSdkError`(`AzureTtsError` のサブクラス)がスローされ、`errorDetails` から SDK のエラー詳細を確認できます。SDK が HTTP ステータスやリクエスト ID を公開しないため、SDK 経由のエラーでは `status` は `0`、`statusText` は `"Speech SDK"`、`requestId` は `null` です。Playground のサーバー側ログにもこれらの情報とリージョン、SSML の文字数が出力されます。ログに出力するエラー詳細は 4,096 文字までに制限されます。サブスクリプションキーや SSML 本文自体はログに出力されません。
258
338
 
@@ -326,6 +406,8 @@ To use the React editor, also install React and the Monaco Editor adapter:
326
406
  npm install ssml-builder-js @monaco-editor/react react react-dom
327
407
  ```
328
408
 
409
+ The root package accepts React `>=18.2.0 <20` as a peer dependency. Next.js applications using React 18.3.1 work with both the Pages Router and App Router without a peer-dependency range warning. Place the Monaco-based `SsmlEditor` in a client component.
410
+
329
411
  To use the Web Component, also install Monaco Editor:
330
412
 
331
413
  ```sh
@@ -422,9 +504,34 @@ The main `buildSsml` and `parseSsml` signatures are:
422
504
  | `buildPartialSsml(text, context?)` / `buildPartialSsml({ text, ...context })` | Builds minimal playable SSML for partial text with language, voice, and prosody context |
423
505
  | `parseSsml(xml)` | Converts a `<speak>` XML document into an `SsmlDocument` |
424
506
  | `validateSsml(xml)` | Returns `{ message, position }` for a syntax error, or `null` |
507
+ | `extractSsmlText(xml)` | Extracts all text nodes in document order |
508
+ | `mapSsmlTextNodes(xml, transform, options?)` | Transforms only text nodes while preserving the XML structure; supports sync/async transforms, skipped tags, and context filters |
509
+ | `validateAzureSsml(xml, options?)` | Returns Azure Speech semantic-validation diagnostics |
425
510
 
426
511
  Typed representations are available for elements such as `voice`, `prosody`, `break`, `express-as`, `say-as`, `phoneme`, `audio`, `lang`, and `mark`. Use `type: "custom"` and `name` to handle undefined XML elements or additional attributes. When a document contains `mstts:` elements, the required Azure Speech namespace is added automatically.
427
512
 
513
+ Use `mapSsmlTextNodes` to replace translatable content without changing tags, attributes, or nesting. The transform receives the immediate parent tag and ancestor `path`, and may return a `string` or a `Promise<string>`. The third argument supports `skipTags` and a `filter` callback; `phoneme`, `say-as`, and `sub` are skipped by default. The callback receives `parentTag`, decoded `parentAttributes`, `ancestorTags`, and `path`.
514
+
515
+ ```ts
516
+ const translated = await mapSsmlTextNodes(ssml, translate, {
517
+ skipTags: ["phoneme", "say-as", "sub", "custom-no-translate"],
518
+ filter: ({ parentAttributes, ancestorTags }) =>
519
+ ancestorTags.includes("voice") && parentAttributes["xml:lang"] !== "en-US",
520
+ });
521
+ ```
522
+
523
+ `validateAzureSsml` accepts `AzureValidationOptions` for extending the voice/style map. `unknownVoicePolicy` defaults to `"warn"` and `validateNestedVoices` defaults to `true`. External `<audio>` URLs are blocked by default; provide `allowedAudioOrigins` or explicitly set `allowExternalAudio: true` only when the deployment is configured to control those requests.
524
+
525
+ ```ts
526
+ const diagnostics = validateAzureSsml(ssml, {
527
+ customVoiceStyleMap: { "my-custom-voice": ["narration"] },
528
+ unknownVoicePolicy: "error", // "error" | "warn" | "ignore"
529
+ allowedAudioOrigins: ["https://cdn.example.com"],
530
+ });
531
+ ```
532
+
533
+ Azure Speech fetches `<audio>` URLs, so a server that accepts arbitrary user-provided SSML can become an SSRF proxy. For untrusted SSML, enforce HTTPS, an origin allowlist, redirect policy, and response-size limits on the server; do not treat `allowExternalAudio` as a substitute for those controls.
534
+
428
535
  ## Using `ssml-editor-react`
429
536
 
430
537
  `SsmlEditor` accepts an `SsmlDocument` and renders only a toolbar and text display area. The toolbar applies rate, volume, and pitch settings to the selection and provides undo and redo actions. The application is responsible for selecting and displaying the voice. Monaco Editor is used for text editing, and SSML syntax is validated whenever the text changes. Syntax errors are shown with editor markers and an error message. Hovering over XML tag names or parameters shows SSML descriptions. Selecting text displays a floating action bar with the character count and preview action. When `enableCodeLens` is enabled (the default), CodeLens quick controls for editing and unwrapping `prosody` tags and editing or deleting `break` tags are shown above those tags. When `showDecorations` is enabled, inline badges for pause and pitch changes are rendered next to `break` and `prosody` tags, and Monaco inline decorations are enabled. Generated SSML is provided through `onSsmlChange` so the application can display it wherever it needs. Pass an `SsmlEditorRef` through `ref` to retrieve full, selected, or current-line SSML, and use `onSelectionChange` to observe selection text and state. The UI supports Japanese (the default) and English.
@@ -528,6 +635,17 @@ const audio = await client.synthesize(ssml);
528
635
  // audio is an audio/mpeg ArrayBuffer
529
636
  ```
530
637
 
638
+ For lower bandwidth, choose `audio-24khz-48kbitrate-mono-mp3` or `audio-16khz-32kbitrate-mono-mp3`.
639
+
640
+ ```ts
641
+ const client = new AzureTtsClient({
642
+ subscriptionKey: process.env.AZURE_SPEECH_KEY!,
643
+ region: process.env.AZURE_SPEECH_REGION!,
644
+ outputFormat: "audio-24khz-48kbitrate-mono-mp3",
645
+ timeoutMs: 15_000,
646
+ });
647
+ ```
648
+
531
649
  The lower-level `synthesizeSpeech` function is also available. It requires
532
650
  `endpoint`, `subscriptionKey`, and `region` in its `TtsConfig` argument.
533
651
 
@@ -542,7 +660,47 @@ const audio = await synthesizeSpeech(ssml, {
542
660
  ```
543
661
 
544
662
  Internally, the client uses the Microsoft Cognitive Services Speech SDK's `SpeechSynthesizer`. If `endpoint` is omitted from `AzureTtsClient`, `https://{region}.tts.speech.microsoft.com/cognitiveservices/v1` is used. The Playground example explicitly uses the WebSocket endpoint from `.env.example`. If a custom endpoint contains `{region}`, it is replaced with the configured region.
663
+ Empty or whitespace-only `endpoint` values also fall back to the regional endpoint. Pass a `logger` with optional `debug`, `info`, `warn`, and `error` methods to receive client diagnostics; when omitted, the client is silent.
545
664
  Set `outputFormat` to a format supported by the Speech SDK. If omitted, `audio-16khz-128kbitrate-mono-mp3` is used.
665
+ `timeoutMs` bounds a synthesis request, while `signal` supports cancellation when a client disconnects. If adding retries, retry only transient SDK failures, pass the same `AbortSignal`, and use exponential backoff.
666
+
667
+ Keep the subscription key on the server by using a Next.js Route Handler (or an equivalent Node.js endpoint):
668
+
669
+ ```ts
670
+ // app/api/synthesize/route.ts
671
+ import { AzureTtsClient, AzureTtsError } from "@ssml-builder-js/azure-tts-client";
672
+ import { validateAzureSsml, validateSsml } from "@ssml-builder-js/ssml-core";
673
+
674
+ export const runtime = "nodejs";
675
+
676
+ export async function POST(request: Request) {
677
+ const body = (await request.json()) as { ssml?: unknown };
678
+ if (typeof body.ssml !== "string" || validateSsml(body.ssml))
679
+ return Response.json({ error: "Invalid SSML" }, { status: 400 });
680
+ if (validateAzureSsml(body.ssml).some(({ severity }) => severity === "error"))
681
+ return Response.json({ error: "Invalid Azure SSML" }, { status: 400 });
682
+
683
+ const controller = new AbortController();
684
+ const timeout = setTimeout(() => controller.abort(), 15_000);
685
+ request.signal.addEventListener("abort", () => controller.abort(), { once: true });
686
+ try {
687
+ const audio = await new AzureTtsClient({
688
+ subscriptionKey: process.env.AZURE_SPEECH_KEY!,
689
+ region: process.env.AZURE_SPEECH_REGION!,
690
+ signal: controller.signal,
691
+ outputFormat: "audio-24khz-48kbitrate-mono-mp3",
692
+ }).synthesize(body.ssml);
693
+ return new Response(new Uint8Array(audio), { headers: { "Content-Type": "audio/mpeg" } });
694
+ } catch (error) {
695
+ const status = error instanceof AzureTtsError && error.status === 0 ? 504 : 502;
696
+ return Response.json({ error: "Speech synthesis failed" }, { status });
697
+ } finally {
698
+ clearTimeout(timeout);
699
+ }
700
+ }
701
+ ```
702
+
703
+ Do not log the SSML body or subscription key. If external `audio` is allowed, validate its origins before synthesis and keep the same SSRF controls in place.
546
704
 
547
705
  Speech SDK synthesis errors throw `AzureTtsSdkError` (a subclass of `AzureTtsError`); its `errorDetails` field contains the SDK error details. Because the SDK does not expose HTTP status or request IDs, SDK errors use `0` for `status`, `"Speech SDK"` for `statusText`, and `null` for `requestId`. The playground's server-side logs include these fields along with the region and SSML character count. Logged error details are limited to 4,096 characters. The subscription key and SSML content itself are not written to logs.
548
706