import {z} from 'zod' export type ParseRequest = {url?: string | undefined, base64?: string | undefined, filename?: string | undefined, mode?: ('fast' | 'hires' | 'auto') | undefined, output?: ('markdown' | 'json') | undefined, wait?: boolean | undefined, imageMode?: ('embedded' | 's3') | undefined, promptType?: string | undefined, callbackUrl?: string | undefined, includeDetection?: boolean | undefined}; export type CreateApiApiParseArgs = {body: ParseRequest}; export type CreateApiApiParseOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const parseResponse = z.object({success: z.boolean().optional(), requestId: z.string().optional(), mode: z.enum(["fast", "hires"]).optional(), async: z.boolean().optional(), taskId: z.string().optional(), status: z.enum(["completed", "processing"]).optional(), document: z.object({markdown: z.string().optional(), text: z.string().optional(), pageCount: z.number().int().optional(), metadata: z.object({title: z.string().optional(), author: z.string().optional(), created_at: z.string().optional(), file_type: z.string().optional()}).optional(), images: z.array(z.object({page: z.number().int().optional(), url: z.string().optional(), caption: z.string().optional()})).optional(), detections: z.array(z.object({id: z.string().optional(), type: z.string().optional(), page: z.number().int().optional(), bbox: z.array(z.number()).optional(), content: z.string().optional()})).optional(), detectionSummary: z.object({total_count: z.number().int().optional(), by_type: z.object({}).optional()}).optional(), bidirectionalIndexing: z.object({detection_ids_count: z.number().int().optional(), ref_markers_count: z.number().int().optional(), enabled: z.boolean().optional()}).optional(), estimatedTime: z.number().int().optional()}).optional(), usage: z.object({inputPages: z.number().int().optional(), inputImages: z.number().int().optional(), outputChars: z.number().int().optional(), outputTokens: z.number().int().optional()}).optional(), cost: z.object({credits: z.number().optional(), breakdown: z.object({pages: z.number().optional(), images: z.number().optional()}).optional()}).optional(), endpoints: z.object({status: z.string().optional(), result: z.string().optional(), stream: z.string().optional()}).optional(), processingTime: z.number().int().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 }; /** * Document parsing (PDF, images, OCR) * * POST /api/parse */ export const createApiApiParse = async (args: CreateApiApiParseArgs, options?: CreateApiApiParseOptions) => { const {baseUrl = "https://prismer.cloud", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (apiKey !== undefined) headers.set('authorization', `Bearer ${apiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/parse${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(parseResponse, await res.json()) };