import {z} from 'zod' export type GetApiV2RolePlayGetFeedbackArgs = {Authorization: string, location: string, role: string, text: string}; export type GetApiV2RolePlayGetFeedbackOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const getApiV2RolePlayGetFeedbackResponse = z.object({code: z.number().int().optional(), data: z.object({display_score: z.string().optional(), grammar_mistakes: z.array(z.string()).optional(), improved_version: z.string().optional(), raw_msgs: z.array(z.string()).optional(), score: z.string().optional(), scoring: z.string().optional(), vocabulary_mistakes: z.array(z.string()).optional()}).optional(), message: z.string().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 }; /** * analyze user's reply * * GET /v2/role_play/get_feedback */ export const getApiV2RolePlayGetFeedback = async (args: GetApiV2RolePlayGetFeedbackArgs, options: GetApiV2RolePlayGetFeedbackOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.Authorization != null) headers.set("Authorization", String(args.Authorization)) if (args.location != null) query.append("location", String(args.location)) if (args.role != null) query.append("role", String(args.role)) if (args.text != null) query.append("text", String(args.text)) const url = `${baseUrl.replace(/\/+$/, '')}/v2/role_play/get_feedback${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiV2RolePlayGetFeedbackResponse, await res.json()) };