ssml-builder-js 2.4.0 → 2.6.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
@@ -133,13 +135,45 @@ const parsed = parseSsml(ssml);
133
135
  | `parseSsml(xml)` | `<speak>` XML を `SsmlDocument` に変換 |
134
136
  | `validateSsml(xml)` | SSML の構文エラーを `{ message, position }` または `null` で返す |
135
137
  | `extractSsmlText(xml)` | タグを除いた全テキストノードを文書順に抽出 |
136
- | `mapSsmlTextNodes(xml, transform)` | タグ構造を維持したままテキストノードだけを同期・非同期変換 |
138
+ | `mapSsmlTextNodes(xml, transform, options?)` | タグ構造を維持したままテキストノードだけを同期・非同期変換。スキップタグとコンテキストフィルターに対応 |
137
139
  | `validateAzureSsml(xml, options?)` | Azure Speech 向けの意味検証結果を Diagnostic 配列で返す |
138
140
 
141
+ ### 3段階の検証モデル
142
+
143
+ SSML の検証は、構文、Azure 固有の静的な意味、実サービスのランタイム状態を分けて扱います。前段の検証に通っても、後段の検証結果までは保証しません。
144
+
145
+ | 段階 | API / 操作 | 検証する範囲 | 検証しない範囲 |
146
+ | --- | --- | --- | --- |
147
+ | XML 構文 | `validateSsml` | XML の整形式性、タグの対応、属性・エンティティの構文 | Azure の音声・属性・スタイル対応、アカウント状態、実際の合成可否 |
148
+ | 静的意味 | `validateAzureSsml` | Azure SSML の必須要素、属性値、音声と `xml:lang` の整合性、音声スタイル、文字数、`audio` URL/オリジン | Azure 側の最新音声一覧、キー・リージョン権限、サービス障害、実際の音声生成結果 |
149
+ | ランタイム | `AzureTtsClient.synthesize` / Azure Speech API | アカウント、リージョン、キー、最新の音声・スタイル提供状況、サービス側の SSML 制約、通信状態 | 静的検証の代替ではないため、入力検証や SSRF 対策を自動で補完しない |
150
+
139
151
  `voice`、`prosody`、`break`、`express-as`、`say-as`、`phoneme`、`audio`、`lang`、`mark` などの要素を型付きで表現できます。`type: "custom"` と `name` を指定すれば、未定義の XML 要素や追加属性も扱えます。`mstts:` 要素を含むドキュメントを生成すると、必要な Azure Speech 名前空間が自動的に追加されます。
140
152
 
141
153
  翻訳などで本文だけを置き換える場合は、`mapSsmlTextNodes` に変換関数を渡します。変換関数には直近の親タグと祖先タグの `path` が渡され、戻り値は `string` または `Promise<string>` を指定できます。`validateAzureSsml` は音声、属性値、音声スタイル、文字数、`audio` URL/オリジンを検証します。
142
154
 
155
+ `mapSsmlTextNodes` の第 3 引数で、翻訳対象外タグとコンテキストフィルターを指定できます。デフォルトでは `phoneme`、`say-as`、`sub` の本文を変換しません。`filter` には `parentTag`、`parentAttributes`、`ancestorTags`、`path` が渡されます。
156
+
157
+ ```ts
158
+ const translated = await mapSsmlTextNodes(ssml, translate, {
159
+ skipTags: ["phoneme", "say-as", "sub", "custom-no-translate"],
160
+ filter: ({ parentAttributes, ancestorTags }) =>
161
+ ancestorTags.includes("voice") && parentAttributes["xml:lang"] !== "ja-JP",
162
+ });
163
+ ```
164
+
165
+ `validateAzureSsml` は `AzureValidationOptions` で音声・スタイルの定義を追加できます。Azure の音声・スタイル一覧はサービス更新やリージョン差分があるため、組み込み一覧は固定の完全な台帳ではありません。新しい音声を一覧の更新前から使う場合や既存音声のスタイルを上書きする場合は、`customVoiceStyleMap` に同じ音声名を指定すれば、その呼び出しで直ちに置き換えられます。未知音声をデフォルトの `unknownVoicePolicy: "warn"` で警告に留めるのは、一覧更新前の音声、カスタム音声、リージョン限定音声を静的検証で不必要にブロックしないためです。厳格なデプロイ前検査では `"error"`、台帳外の音声を利用する構成では `"ignore"` も選択できます。`validateNestedVoices` のデフォルトは `true` です。`audio` の外部 URL はデフォルトで拒否されるため、利用する場合は `allowedAudioOrigins` に許可するオリジンを列挙するか、構成を理解した上で `allowExternalAudio: true` を指定してください。
166
+
167
+ ```ts
168
+ const diagnostics = validateAzureSsml(ssml, {
169
+ customVoiceStyleMap: { "my-custom-voice": ["narration"] },
170
+ unknownVoicePolicy: "error", // "error" | "warn" | "ignore"
171
+ allowedAudioOrigins: ["https://cdn.example.com"],
172
+ });
173
+ ```
174
+
175
+ Azure Speech は `<audio>` の URL を取得するため、任意の URL をそのまま受け付けるサーバーは SSRF の踏み台になり得ます。ユーザー入力の SSML を合成する場合は、HTTPS、許可オリジン、リダイレクト先、応答サイズをサーバー側でも制限し、`allowExternalAudio` だけで無制限に許可しないでください。
176
+
143
177
  ## `ssml-editor-react` の利用方法
144
178
 
145
179
  `SsmlEditor` は `SsmlDocument` を受け取り、ツールバーと本文の表示エリアだけを表示するシンプルなコンポーネントです。ツールバーから選択範囲の速度、音量、ピッチなどの設定、元に戻す・やり直す操作ができます。音声の選択と表示はアプリ側で行います。本文の編集には Monaco Editor を使用し、変更時に SSML の構文を検証します。構文エラーはエディター上のマーカーとエラーメッセージで表示されます。XML のタグ名やパラメータへホバーすると SSML の説明を確認できます。テキストを選択すると、選択文字数と試聴を行うフローティングアクションが表示されます。`enableCodeLens`(デフォルトは `true`)が有効な場合、`prosody` と `break` タグの上に属性編集やタグ操作の CodeLens が表示されます。`showDecorations` が有効な場合、`break` と `prosody` のタグに間やピッチ変化を示すインラインバッジが表示され、Monaco のインライン装飾も有効になります。生成された SSML は `onSsmlChange` で受け取り、アプリ側で自由に表示できます。`SsmlEditorRef` を `ref` に渡すと、全体、選択範囲、または現在行の SSML を取得できます。画面表示は日本語(デフォルト)と英語に対応しています。
@@ -243,6 +277,17 @@ const audio = await client.synthesize(ssml);
243
277
  // audio は audio/mpeg の ArrayBuffer
244
278
  ```
245
279
 
280
+ 帯域幅を抑える場合は `audio-24khz-48kbitrate-mono-mp3` または `audio-16khz-32kbitrate-mono-mp3` を指定できます。
281
+
282
+ ```ts
283
+ const client = new AzureTtsClient({
284
+ subscriptionKey: process.env.AZURE_SPEECH_KEY!,
285
+ region: process.env.AZURE_SPEECH_REGION!,
286
+ outputFormat: "audio-24khz-48kbitrate-mono-mp3",
287
+ timeoutMs: 15_000,
288
+ });
289
+ ```
290
+
246
291
  低レベルの `synthesizeSpeech` 関数も利用できます。この関数では `TtsConfig` の
247
292
  `endpoint`、`subscriptionKey`、`region` を指定します。
248
293
 
@@ -259,6 +304,45 @@ const audio = await synthesizeSpeech(ssml, {
259
304
  内部では Microsoft Cognitive Services Speech SDK の `SpeechSynthesizer` を使用します。`AzureTtsClient` の `endpoint` を省略すると `https://{region}.tts.speech.microsoft.com/cognitiveservices/v1` が使用されます。上の Playground の例では `.env.example` に合わせて WebSocket エンドポイントを明示しています。独自エンドポイントに `{region}` を含めた場合は、設定したリージョンに置き換えられます。
260
305
  `endpoint` に空文字または空白文字列を指定した場合も、リージョンの既定エンドポイントへフォールバックします。`logger` オプションには `debug`、`info`、`warn`、`error` を持つロガーを注入できます。省略時はクライアントからログを出力しません。
261
306
  `outputFormat` には Speech SDK がサポートする出力形式を指定できます。省略時は `audio-16khz-128kbitrate-mono-mp3` が使用されます。
307
+ `timeoutMs` は合成を打ち切る時間(ミリ秒)、`signal` はクライアント切断などによるキャンセル用の `AbortSignal` です。リトライする場合は、タイムアウトや一時的な SDK エラーだけを対象にし、同じ `AbortSignal` を渡して指数バックオフを使用してください。
308
+
309
+ Next.js Route Handler ではキーをブラウザへ渡さず、サーバー側で検証・合成します。
310
+
311
+ ```ts
312
+ // app/api/synthesize/route.ts
313
+ import { AzureTtsClient, AzureTtsError } from "@ssml-builder-js/azure-tts-client";
314
+ import { validateAzureSsml, validateSsml } from "@ssml-builder-js/ssml-core";
315
+
316
+ export const runtime = "nodejs";
317
+
318
+ export async function POST(request: Request) {
319
+ const body = (await request.json()) as { ssml?: unknown };
320
+ if (typeof body.ssml !== "string" || validateSsml(body.ssml))
321
+ return Response.json({ error: "Invalid SSML" }, { status: 400 });
322
+ if (validateAzureSsml(body.ssml).some(({ severity }) => severity === "error"))
323
+ return Response.json({ error: "Invalid Azure SSML" }, { status: 400 });
324
+
325
+ const controller = new AbortController();
326
+ const timeout = setTimeout(() => controller.abort(), 15_000);
327
+ request.signal.addEventListener("abort", () => controller.abort(), { once: true });
328
+ try {
329
+ const audio = await new AzureTtsClient({
330
+ subscriptionKey: process.env.AZURE_SPEECH_KEY!,
331
+ region: process.env.AZURE_SPEECH_REGION!,
332
+ signal: controller.signal,
333
+ outputFormat: "audio-24khz-48kbitrate-mono-mp3",
334
+ }).synthesize(body.ssml);
335
+ return new Response(new Uint8Array(audio), { headers: { "Content-Type": "audio/mpeg" } });
336
+ } catch (error) {
337
+ const status = error instanceof AzureTtsError && error.status === 0 ? 504 : 502;
338
+ return Response.json({ error: "Speech synthesis failed" }, { status });
339
+ } finally {
340
+ clearTimeout(timeout);
341
+ }
342
+ }
343
+ ```
344
+
345
+ リトライを追加する場合は、`AzureTtsSdkError` の内容をログへ出しすぎず、SSML 本文とサブスクリプションキーをログへ書かないでください。外部 `audio` を使う場合も、上記の許可オリジン検証を合成前に実施してください。
262
346
 
263
347
  Speech SDK の合成エラーでは `AzureTtsSdkError`(`AzureTtsError` のサブクラス)がスローされ、`errorDetails` から SDK のエラー詳細を確認できます。SDK が HTTP ステータスやリクエスト ID を公開しないため、SDK 経由のエラーでは `status` は `0`、`statusText` は `"Speech SDK"`、`requestId` は `null` です。Playground のサーバー側ログにもこれらの情報とリージョン、SSML の文字数が出力されます。ログに出力するエラー詳細は 4,096 文字までに制限されます。サブスクリプションキーや SSML 本文自体はログに出力されません。
264
348
 
@@ -332,6 +416,8 @@ To use the React editor, also install React and the Monaco Editor adapter:
332
416
  npm install ssml-builder-js @monaco-editor/react react react-dom
333
417
  ```
334
418
 
419
+ 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.
420
+
335
421
  To use the Web Component, also install Monaco Editor:
336
422
 
337
423
  ```sh
@@ -429,12 +515,42 @@ The main `buildSsml` and `parseSsml` signatures are:
429
515
  | `parseSsml(xml)` | Converts a `<speak>` XML document into an `SsmlDocument` |
430
516
  | `validateSsml(xml)` | Returns `{ message, position }` for a syntax error, or `null` |
431
517
  | `extractSsmlText(xml)` | Extracts all text nodes in document order |
432
- | `mapSsmlTextNodes(xml, transform)` | Transforms only text nodes while preserving the XML structure; supports sync and async transforms |
518
+ | `mapSsmlTextNodes(xml, transform, options?)` | Transforms only text nodes while preserving the XML structure; supports sync/async transforms, skipped tags, and context filters |
433
519
  | `validateAzureSsml(xml, options?)` | Returns Azure Speech semantic-validation diagnostics |
434
520
 
521
+ ### Three-stage validation model
522
+
523
+ SSML validation separates XML syntax, Azure-specific static semantics, and runtime service state. Passing an earlier stage does not guarantee the result of a later stage.
524
+
525
+ | Stage | API / operation | What it validates | Boundary |
526
+ | --- | --- | --- | --- |
527
+ | XML syntax | `validateSsml` | Well-formed XML, matching tags, and attribute/entity syntax | Azure voice, attribute, and style support; account state; and actual synthesis availability |
528
+ | Static semantics | `validateAzureSsml` | Required Azure SSML elements, attribute values, voice/`xml:lang` alignment, voice styles, character limits, and `audio` URL/origin policy | Azure's latest voice catalog, key/region permissions, service incidents, and the actual generated audio |
529
+ | Runtime | `AzureTtsClient.synthesize` / Azure Speech API | Account, region, key, current voice/style availability, service-side SSML constraints, and network state | It does not replace input validation or automatically provide SSRF protection |
530
+
435
531
  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.
436
532
 
437
- 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>`. `validateAzureSsml` checks Azure-specific voice, attribute, style, length, and `audio` URL/origin rules.
533
+ 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`.
534
+
535
+ ```ts
536
+ const translated = await mapSsmlTextNodes(ssml, translate, {
537
+ skipTags: ["phoneme", "say-as", "sub", "custom-no-translate"],
538
+ filter: ({ parentAttributes, ancestorTags }) =>
539
+ ancestorTags.includes("voice") && parentAttributes["xml:lang"] !== "en-US",
540
+ });
541
+ ```
542
+
543
+ `validateAzureSsml` accepts `AzureValidationOptions` for extending the voice/style map. Azure's voice and style catalog changes over time and can differ by region, so the built-in map is a fixed snapshot rather than a complete live catalog. To use a newly released voice before the built-in map is updated, or to replace the styles for an existing voice, pass the same voice name through `customVoiceStyleMap`; that entry takes effect immediately for the call. Unknown voices default to `unknownVoicePolicy: "warn"` so catalog lag, custom voices, and region-limited voices do not get unnecessarily blocked by static validation. Use `"error"` for strict pre-deployment checks or `"ignore"` when the deployment intentionally operates outside the built-in catalog. `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.
544
+
545
+ ```ts
546
+ const diagnostics = validateAzureSsml(ssml, {
547
+ customVoiceStyleMap: { "my-custom-voice": ["narration"] },
548
+ unknownVoicePolicy: "error", // "error" | "warn" | "ignore"
549
+ allowedAudioOrigins: ["https://cdn.example.com"],
550
+ });
551
+ ```
552
+
553
+ 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.
438
554
 
439
555
  ## Using `ssml-editor-react`
440
556
 
@@ -539,6 +655,17 @@ const audio = await client.synthesize(ssml);
539
655
  // audio is an audio/mpeg ArrayBuffer
540
656
  ```
541
657
 
658
+ For lower bandwidth, choose `audio-24khz-48kbitrate-mono-mp3` or `audio-16khz-32kbitrate-mono-mp3`.
659
+
660
+ ```ts
661
+ const client = new AzureTtsClient({
662
+ subscriptionKey: process.env.AZURE_SPEECH_KEY!,
663
+ region: process.env.AZURE_SPEECH_REGION!,
664
+ outputFormat: "audio-24khz-48kbitrate-mono-mp3",
665
+ timeoutMs: 15_000,
666
+ });
667
+ ```
668
+
542
669
  The lower-level `synthesizeSpeech` function is also available. It requires
543
670
  `endpoint`, `subscriptionKey`, and `region` in its `TtsConfig` argument.
544
671
 
@@ -555,6 +682,45 @@ const audio = await synthesizeSpeech(ssml, {
555
682
  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.
556
683
  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.
557
684
  Set `outputFormat` to a format supported by the Speech SDK. If omitted, `audio-16khz-128kbitrate-mono-mp3` is used.
685
+ `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.
686
+
687
+ Keep the subscription key on the server by using a Next.js Route Handler (or an equivalent Node.js endpoint):
688
+
689
+ ```ts
690
+ // app/api/synthesize/route.ts
691
+ import { AzureTtsClient, AzureTtsError } from "@ssml-builder-js/azure-tts-client";
692
+ import { validateAzureSsml, validateSsml } from "@ssml-builder-js/ssml-core";
693
+
694
+ export const runtime = "nodejs";
695
+
696
+ export async function POST(request: Request) {
697
+ const body = (await request.json()) as { ssml?: unknown };
698
+ if (typeof body.ssml !== "string" || validateSsml(body.ssml))
699
+ return Response.json({ error: "Invalid SSML" }, { status: 400 });
700
+ if (validateAzureSsml(body.ssml).some(({ severity }) => severity === "error"))
701
+ return Response.json({ error: "Invalid Azure SSML" }, { status: 400 });
702
+
703
+ const controller = new AbortController();
704
+ const timeout = setTimeout(() => controller.abort(), 15_000);
705
+ request.signal.addEventListener("abort", () => controller.abort(), { once: true });
706
+ try {
707
+ const audio = await new AzureTtsClient({
708
+ subscriptionKey: process.env.AZURE_SPEECH_KEY!,
709
+ region: process.env.AZURE_SPEECH_REGION!,
710
+ signal: controller.signal,
711
+ outputFormat: "audio-24khz-48kbitrate-mono-mp3",
712
+ }).synthesize(body.ssml);
713
+ return new Response(new Uint8Array(audio), { headers: { "Content-Type": "audio/mpeg" } });
714
+ } catch (error) {
715
+ const status = error instanceof AzureTtsError && error.status === 0 ? 504 : 502;
716
+ return Response.json({ error: "Speech synthesis failed" }, { status });
717
+ } finally {
718
+ clearTimeout(timeout);
719
+ }
720
+ }
721
+ ```
722
+
723
+ 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.
558
724
 
559
725
  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.
560
726
 
@@ -3510,4 +3510,4 @@ export {
3510
3510
  findSsmlHoverTarget,
3511
3511
  formatSsmlHover
3512
3512
  };
3513
- //# sourceMappingURL=chunk-I3BR2WCQ.mjs.map
3513
+ //# sourceMappingURL=chunk-GF4QZHLJ.mjs.map