import {z} from 'zod' export type GetApiOEmbedArgs = {url?: (string | null) | undefined, maxWidth?: (number | null) | undefined, maxHeight?: (number | null) | undefined, token?: (string | null) | undefined, expires?: number | undefined}; export type GetApiOEmbedOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const videoOEmbedModel = z.object({version: z.string().nullable().optional(), title: z.string().nullable().optional(), type: z.string().nullable().optional(), thumbnail_url: z.string().nullable().optional(), thumbnail_width: z.number().int().nullable().optional(), thumbnail_height: z.number().int().nullable().optional(), width: z.number().int().optional(), height: z.number().int().optional(), html: z.string().nullable().optional(), provider_name: z.string().nullable().optional(), provider_url: z.string().nullable().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 }; /** * Get oEmbed data * * GET /OEmbed */ export const getApiOEmbed = async (args: GetApiOEmbedArgs, options?: GetApiOEmbedOptions) => { const {baseUrl = "https://video.bunnycdn.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.url != null) query.append("url", String(args.url)) if (args.maxWidth != null) query.append("maxWidth", String(args.maxWidth)) if (args.maxHeight != null) query.append("maxHeight", String(args.maxHeight)) if (args.token != null) query.append("token", String(args.token)) if (args.expires != null) query.append("expires", String(args.expires)) const url = `${baseUrl.replace(/\/+$/, '')}/OEmbed${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(videoOEmbedModel, await res.json()) };