import {z} from 'zod' export type STTEncoding = 'pcm_s16le' | 'pcm_s32le' | 'pcm_f16le' | 'pcm_f32le' | 'pcm_mulaw' | 'pcm_alaw'; export type CreateApiSttArgs = {'Cartesia-Version': '2026-03-01', encoding?: STTEncoding | undefined, sample_rate?: (number | null) | undefined, body: BodyInit}; export type CreateApiSttOptions = {baseUrl?: string | undefined, APIKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const transcriptionWord = z.object({word: z.string(), start: z.number(), end: z.number()}); export const transcriptionResponse = z.object({type: z.literal("transcript"), request_id: z.string().optional(), text: z.string(), is_final: z.boolean().optional(), language: z.string().optional(), duration: z.number().optional(), words: z.array(transcriptionWord).optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Batch Speech-to-Text * * POST /stt * * Also accepts auth: AccessTokenAuth */ export const createApiStt = async (args: CreateApiSttArgs, options?: CreateApiSttOptions) => { const {baseUrl = "https://api.cartesia.ai", fetch: fetchFn = fetch, APIKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['Cartesia-Version'] != null) headers.set("Cartesia-Version", String(args['Cartesia-Version'])) if (args.encoding != null) query.append("encoding", String(args.encoding)) if (args.sample_rate != null) query.append("sample_rate", String(args.sample_rate)) if (APIKeyAuth !== undefined) headers.set('authorization', `Bearer ${APIKeyAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/stt${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: args.body}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(transcriptionResponse, await res.json()) };