import {z} from 'zod' export type ParseChunkingOptions = {strategy?: ('none' | 'page' | 'section') | undefined}; export type WorkspaceFileSource = {file_id: string, type?: 'workspace_file' | undefined, workspace_id: string}; export type ParseDiagramsOptions = {mode?: ('omit' | 'mermaid') | undefined}; export type ParseFiguresOptions = {mode?: ('omit' | 'include' | 'describe') | undefined}; export type ParseOcrOptions = {languages?: Array | undefined, mode?: ('auto' | 'force' | 'disabled') | undefined}; export type ParseOutputOptions = {formats?: (Array<'markdown' | 'text' | 'blocks'>) | undefined, include_images?: boolean | undefined, include_page_markers?: boolean | undefined, return_ocr_data?: boolean | undefined, table_format?: ('html' | 'markdown') | undefined}; export type PageRange = {end: number, start: number}; export type ParseSpreadsheetOptions = {include_formulas?: boolean | undefined, include_hidden_columns?: boolean | undefined, include_hidden_rows?: boolean | undefined, include_hidden_sheets?: boolean | undefined, sheets?: (Array | null) | undefined}; export type DocumentParseRequest = {chunking?: ParseChunkingOptions | undefined, corpus_sources?: Array | undefined, diagrams?: ParseDiagramsOptions | undefined, figures?: ParseFiguresOptions | undefined, name?: (string | null) | undefined, ocr?: ParseOcrOptions | undefined, output?: ParseOutputOptions | undefined, page_ranges?: (Array | null) | undefined, parse_mode?: ('low' | 'medium' | 'high') | undefined, parser?: ('native' | 'datalab' | 'nace_router' | null) | undefined, password?: (string | null) | undefined, project_id?: (string | null) | undefined, quality?: ('auto' | 'fast' | 'accurate') | undefined, source: Record, spreadsheet?: ParseSpreadsheetOptions | undefined}; export type CreateApiV1DocumentsParseArgs = {'Idempotency-Key'?: string | undefined, wait_seconds?: number | undefined, body: DocumentParseRequest}; export type CreateApiV1DocumentsParseOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const documentTimingBreakdown = z.object({preparation_ms: z.number().int().gte(0).nullable(), queue_ms: z.number().int().gte(0).nullable(), ndi_processing_ms: z.number().int().gte(0).nullable(), result_preparation_ms: z.number().int().gte(0).nullable(), delivery_wait_ms: z.number().int().gte(0).nullable(), document_finalization_ms: z.number().int().gte(0).nullable()}); export const documentTiming = z.object({received_at: z.string(), observed_at: z.string(), completed_at: z.string().nullable(), elapsed_ms: z.number().int().nullable(), total_ms: z.number().int().nullable(), first_response_ms: z.number().int().nullable(), breakdown: documentTimingBreakdown}); export const documentCostLine = z.object({operation: z.enum(["parse", "split", "classify", "extract", "ground"]), quantity: z.number().int().gte(0), unit: z.enum(["page", "target"]), execution: z.enum(["fresh", "reused"]), unit_price_usd: z.string(), amount_usd: z.string(), reuse_reason: z.string().nullable()}); export const documentCost = z.object({currency: z.literal("USD"), pricing_version: z.string(), total_usd: z.string(), lines: z.array(documentCostLine)}); export const documentJob = z.object({job_id: z.string(), kind: z.enum(["parse", "split", "classify", "extract", "ground"]), status: z.enum(["queued", "running", "succeeded", "failed", "cancelled"]), result: z.unknown(), credits: z.number().int().nullable().optional(), usage_final: z.boolean().optional(), timing: documentTiming.optional(), cost: documentCost.nullable().optional()}).and(z.record(z.string(), z.unknown())); 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 }; /** * Parse a document * * POST /v1/documents/parse */ export const createApiV1DocumentsParse = async (args: CreateApiV1DocumentsParseArgs, options?: CreateApiV1DocumentsParseOptions) => { const {baseUrl = "https://console.nace.ai", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (args.wait_seconds != null) query.append("wait_seconds", String(args.wait_seconds)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/documents/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(documentJob, await res.json()) };