@pyai/sdk 0.7.2 → 0.9.1

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.
@@ -0,0 +1,33 @@
1
+ /** Validate only explicitly requested PCM; keep opaque container APIs unchanged. */
2
+ export async function validateSpeechResponse(
3
+ response: Response,
4
+ params: { response_format?: string; sample_rate?: number },
5
+ ): Promise<void> {
6
+ if (params.response_format !== "pcm") return;
7
+ const rate = params.sample_rate ?? 24000;
8
+ const parts = (response.headers.get("Content-Type") ?? "").split(";");
9
+ const mediaType = parts.shift()?.trim().toLowerCase();
10
+ const values = new Map<string, string[]>();
11
+ let malformed = false;
12
+ for (const part of parts) {
13
+ const match = /^\s*([^=\s]+)\s*=\s*(?:"([^"\\]*)"|([^\s";]+))\s*$/.exec(part);
14
+ if (!match) { malformed = true; continue; }
15
+ const name = match[1]!.toLowerCase();
16
+ values.set(name, [...(values.get(name) ?? []), match[2] ?? match[3]!]);
17
+ }
18
+ const rates = values.get("rate") ?? [];
19
+ const channels = values.get("channels") ?? [];
20
+ const expected = {
21
+ "X-PyAI-Audio-Encoding": "pcm_s16le",
22
+ "X-PyAI-Audio-Sample-Rate": String(rate),
23
+ "X-PyAI-Audio-Channels": "1",
24
+ };
25
+ if (malformed || !Number.isInteger(rate) || rate < 8000 || rate > 48000
26
+ || mediaType !== "audio/pcm" || rates.length !== 1 || rates[0] !== String(rate)
27
+ || (channels.length > 0 && (channels.length !== 1 || channels[0] !== "1"))
28
+ || Object.entries(expected).some(([key, value]) => response.headers.has(key) && response.headers.get(key) !== value)) {
29
+ // A response body owns the fetch connection even before any audio is read.
30
+ try { await response.body?.cancel(); } catch { /* Preserve the metadata error. */ }
31
+ throw new Error("Speak PCM response metadata must match requested mono PCM16 sample rate");
32
+ }
33
+ }
@@ -0,0 +1,71 @@
1
+ /** Explicit English speech formatting. Plain strings are never rewritten. */
2
+ export type SpeechTextPart = string
3
+ | { type: "currency"; value: string; currency: "USD" | "GBP" | "EUR" }
4
+ | { type: "date"; value: string; locale: "en-US" | "en-GB" }
5
+ | { type: "phone" | "digits"; value: string };
6
+
7
+ const small = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
8
+ "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
9
+ const tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
10
+ const ordinals = ["", "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth",
11
+ "tenth", "eleventh", "twelfth", "thirteenth", "fourteenth", "fifteenth", "sixteenth", "seventeenth", "eighteenth", "nineteenth",
12
+ "twentieth", "twenty first", "twenty second", "twenty third", "twenty fourth", "twenty fifth", "twenty sixth", "twenty seventh", "twenty eighth", "twenty ninth", "thirtieth", "thirty first"];
13
+ const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
14
+
15
+ function words(n: number): string {
16
+ if (n < 20) return small[n]!;
17
+ if (n < 100) return tens[Math.floor(n / 10)]! + (n % 10 ? " " + words(n % 10) : "");
18
+ for (const [scale, label] of [[1_000_000, "million"], [1_000, "thousand"], [100, "hundred"]] as const) {
19
+ if (n >= scale) return words(Math.floor(n / scale)) + " " + label + (n % scale ? " " + words(n % scale) : "");
20
+ }
21
+ throw new RangeError("Unsupported number");
22
+ }
23
+
24
+ function formatPart(part: SpeechTextPart): string {
25
+ if (typeof part === "string") return part;
26
+ if (!part || typeof part.value !== "string") throw new TypeError("Speech fields require a string value");
27
+ const value = part.value;
28
+ switch (part.type) {
29
+ case "digits":
30
+ if (!/^[0-9]{1,64}$/.test(value)) throw new RangeError("digits requires 1–64 decimal digits");
31
+ return [...value].map(d => small[Number(d)]!).join(" ");
32
+ case "phone": {
33
+ // Formatting separators are allowed; extensions and country codes are not inferred.
34
+ if (!/^\+?[0-9 ().-]+$/.test(value) || value.length > 64) throw new RangeError("Unsupported phone format");
35
+ const digits = value.replace(/[^0-9]/g, "");
36
+ if (digits.length < 3 || digits.length > 15) throw new RangeError("phone requires 3–15 digits");
37
+ return (value.startsWith("+") ? "plus " : "") + [...digits].map(d => small[Number(d)]!).join(" ");
38
+ }
39
+ case "currency": {
40
+ // Decimal strings avoid binary floating point rounding and ambiguous separators.
41
+ if (!/^-?(0|[1-9][0-9]{0,8})(\.[0-9]{1,2})?$/.test(value)) throw new RangeError("currency requires a decimal string with at most two fractional digits");
42
+ const units = { USD: ["US dollar", "US dollars", "cent", "cents"], GBP: ["pound", "pounds", "penny", "pence"], EUR: ["euro", "euros", "cent", "cents"] } as const;
43
+ if (!Object.hasOwn(units, part.currency)) throw new RangeError("Unsupported currency");
44
+ const [wholeText, fraction = ""] = value.replace(/^-/, "").split(".");
45
+ const whole = Number(wholeText), minor = Number(fraction.padEnd(2, "0"));
46
+ const names = units[part.currency];
47
+ return (value.startsWith("-") && (whole || minor) ? "minus " : "")
48
+ + words(whole) + " " + names[whole === 1 ? 0 : 1]
49
+ + (minor ? " and " + words(minor) + " " + names[minor === 1 ? 2 : 3] : "");
50
+ }
51
+ case "date": {
52
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) throw new RangeError("date requires YYYY-MM-DD");
53
+ if (part.locale !== "en-US" && part.locale !== "en-GB") throw new RangeError("Unsupported date locale");
54
+ const [year, month, day] = value.split("-").map(Number) as [number, number, number];
55
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
56
+ const limit = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
57
+ if (year < 1 || !limit || day < 1 || day > limit) throw new RangeError("Invalid calendar date");
58
+ return (part.locale === "en-US" ? months[month - 1] + " " + ordinals[day]
59
+ : "the " + ordinals[day] + " of " + months[month - 1]) + ", " + words(year);
60
+ }
61
+ default: throw new TypeError("Unsupported speech field type");
62
+ }
63
+ }
64
+
65
+ /** Join literal text and explicitly typed English fields for Speak input or Cast text.
66
+ * Supply spaces and punctuation in literal parts. This does not infer field types,
67
+ * validate phone reachability, or guarantee how a voice will pronounce the output.
68
+ */
69
+ export function formatSpeechText(parts: readonly SpeechTextPart[]): string {
70
+ return parts.map(formatPart).join("");
71
+ }