import {z} from 'zod' export type ApiResolution = '480p' | '720p' | '1080p' | '2k' | '4k'; export type ApiAspectRatio = '16:9' | '9:16' | '1:1'; export type GenerateVideoApiRequest = {prompt: string, model_id: string, resolution?: (ApiResolution | null) | undefined, aspect_ratio?: (ApiAspectRatio | null) | undefined, duration?: (number | null) | undefined, start_frame_image_id?: (string | null) | undefined, end_frame_image_id?: (string | null) | undefined, reference_image_ids?: Array | undefined, reference_video_ids?: Array | undefined, source_video_id?: (string | null) | undefined}; export type CreateApiVideoArgs = {body: GenerateVideoApiRequest}; export type CreateApiVideoOptions = {baseUrl?: string | undefined, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const createVideoJobResponse = z.object({job_id: z.string(), estimated_credits: z.number()}); 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 }; /** * Generate a video * * POST /video */ export const createApiVideo = async (args: CreateApiVideoArgs, options?: CreateApiVideoOptions) => { const {baseUrl = "https://api.wondercraft.ai/v1", fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (APIKeyHeader !== undefined) headers.set("X-API-KEY", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/video${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(createVideoJobResponse, await res.json()) };