import {z} from 'zod' export type CreateApiApiOrgIdBulkArgs = {org_id: string, body: string}; export type CreateApiApiOrgIdBulkOptions = {baseUrl: string, Authorization?: string | undefined, fetch?: typeof fetch | undefined}; export const shardResponse = z.object({failed: z.number().int(), successful: z.number().int(), total: z.number().int()}); export const bulkResponseError = z.object({index: z.string(), index_uuid: z.string(), reason: z.string(), shard: z.string(), type: z.string()}); export const bulkResponseItem = z.object({_id: z.string(), _index: z.string(), _primary_term: z.number().int().nullable().optional(), _seq_no: z.number().int().nullable().optional(), _shards: shardResponse.nullable().optional(), _version: z.number().int().nullable().optional(), error: bulkResponseError.nullable().optional(), originalRecord: z.object({}).optional(), result: z.string().nullable().optional(), status: z.number().int()}); export const bulkResponse = z.object({errors: z.boolean(), items: z.array(z.record(z.string(), bulkResponseItem)), took: z.number().int().gte(0)}); 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 }; /** * Bulk ingest logs (Elasticsearch compatible) * * POST /api/{org_id}/_bulk */ export const createApiApiOrgIdBulk = async (args: CreateApiApiOrgIdBulkArgs, options: CreateApiApiOrgIdBulkOptions) => { const {baseUrl, fetch: fetchFn = fetch, Authorization} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (Authorization !== undefined) headers.set("Authorization", Authorization) const url = `${baseUrl.replace(/\/+$/, '')}/api/${encodeURIComponent(String(args.org_id))}/_bulk${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(bulkResponse, await res.json()) };