import {z} from 'zod' export type LanguageV1 = {code: string}; export type TranslationProfileRequestV1 = {uid: string}; export type MtSettingSimplifiedV1 = {profile?: TranslationProfileRequestV1 | undefined}; export type TextTranslationsRequestV1 = {sourceLang?: LanguageV1 | undefined, sourceText: string, targetLang: LanguageV1, mtSettings?: MtSettingSimplifiedV1 | undefined}; export type CreateApiV1TextTranslationsArgs = {body: TextTranslationsRequestV1}; export type CreateApiV1TextTranslationsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const languageV1 = z.object({code: z.string()}); export const textTranslationsResponseV1 = z.object({translatedText: z.string(), sourceLang: languageV1, targetLang: languageV1}); 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 }; /** * Text translations * * POST /v1/textTranslations */ export const createApiV1TextTranslations = async (args: CreateApiV1TextTranslationsArgs, options?: CreateApiV1TextTranslationsOptions) => { const {baseUrl = "https://eu.phrase.com/control-hub", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/v1/textTranslations${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(textTranslationsResponseV1, await res.json()) };