import {z} from 'zod' export type GetApiTemplatesArgs = {engine?: ('gva' | 'motion') | undefined}; export type GetApiTemplatesOptions = {baseUrl?: string | undefined, MotionApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiTemplatesResponse = z.object({engine: z.string().optional(), templates: z.array(z.object({template: z.string().optional(), engine: z.string().optional(), name: z.string().optional(), description: z.string().nullable().optional(), duration_seconds: z.number().optional(), preview_url: z.string().nullable().optional(), thumbnail_url: z.string().nullable().optional(), width: z.number().optional(), height: z.number().optional()})).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 }; /** * List templates available to your account for an engine * * GET /templates */ export const getApiTemplates = async (args: GetApiTemplatesArgs, options?: GetApiTemplatesOptions) => { const {baseUrl = "https://api.motion.so/api/motion", fetch: fetchFn = fetch, MotionApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.engine != null) query.append("engine", String(args.engine)) if (MotionApiKey !== undefined) headers.set('authorization', `Bearer ${MotionApiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/templates${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(getApiTemplatesResponse, await res.json()) };