import {z} from 'zod' export type StreamConfig = {table: string, many?: (boolean | null) | undefined, mode?: ('append' | 'merge') | undefined, primary_key?: (Array | null) | undefined, wait?: boolean | undefined, tags?: ({[key: string]: string} | null) | undefined, trace?: ({[key: string]: string} | null) | undefined}; export type StreamRequest = {data?: ({[key: string]: unknown} | Array<{[key: string]: unknown}> | null) | undefined, config: StreamConfig}; export type CreateApiV2StreamArgs = {body: StreamRequest}; export type CreateApiV2StreamOptions = {baseUrl: string, AsyncAPIKeyHeaderAuthenticator?: string | undefined, fetch?: typeof fetch | undefined}; export const streamResponse = z.object({success: z.boolean(), request_id: z.string(), stream_id: z.string(), table: z.string(), accepted: z.number().int(), successful_rows: z.number().int(), rejected_rows: z.number().int(), partitions: z.array(z.string()), snapshot_id: z.string().nullable().optional(), warnings: z.array(z.string()).optional(), errors: z.array(z.string()).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 }; /** * Ingest JSON/NDJSON data into Ducklake * * POST /v2/stream */ export const createApiV2Stream = async (args: CreateApiV2StreamArgs, options: CreateApiV2StreamOptions) => { const {baseUrl, fetch: fetchFn = fetch, AsyncAPIKeyHeaderAuthenticator} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (AsyncAPIKeyHeaderAuthenticator !== undefined) headers.set("Authorization", AsyncAPIKeyHeaderAuthenticator) const url = `${baseUrl.replace(/\/+$/, '')}/v2/stream${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(streamResponse, await res.json()) };