import {z} from 'zod' export type LanguageV1 = {code: string}; export type SourceTextRequestV2 = {key: string, source: string}; export type TranslationProfileRequestV1 = {uid: string}; export type MtSettingSimplifiedV1 = {profile?: TranslationProfileRequestV1 | undefined}; export type ConsumerIdV2 = string; export type TextTranslationsRequestV2 = {sourceLang?: LanguageV1 | undefined, sourceTexts: Array, targetLang: LanguageV1, mtSettings?: MtSettingSimplifiedV1 | undefined, consumerId: ConsumerIdV2}; export type CreateApiV2TextTranslationsArgs = {body: TextTranslationsRequestV2}; export type CreateApiV2TextTranslationsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const translatedTextResponseV2 = z.object({key: z.string().optional(), target: z.string().optional()}); export const languageV1 = z.object({code: z.string()}); export const consumerIdV2 = z.string().min(1).max(50); export const textTranslationsResponseV2 = z.object({translatedTexts: z.array(translatedTextResponseV2).optional(), sourceLang: languageV1, targetLang: languageV1, consumerId: consumerIdV2}); 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 v2 * * POST /v2/textTranslations */ export const createApiV2TextTranslations = async (args: CreateApiV2TextTranslationsArgs, options?: CreateApiV2TextTranslationsOptions) => { 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(/\/+$/, '')}/v2/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(textTranslationsResponseV2, await res.json()) };