import {z} from 'zod' export type Evaluate = {service: string, law: string, parameters?: {[key: string]: unknown} | undefined, effectiveDate?: string | undefined, referenceDate?: string | undefined, input?: {[key: string]: unknown} | undefined, output?: string | undefined, approved?: boolean | undefined}; export type CreateApiEvaluateArgs = {body: {data: Evaluate}}; export type CreateApiEvaluateOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const pathNode: z.ZodType = z.object({type: z.string(), name: z.string(), result: z.unknown(), resolveType: z.string().optional(), required: z.boolean().optional(), details: z.record(z.string(), z.unknown()).optional(), children: z.array(z.lazy(() => pathNode)).optional()}); export const responseEvaluateSchema = z.object({output: z.record(z.string(), z.unknown()), input: z.record(z.string(), z.unknown()), requirementsMet: z.boolean(), rulespecId: z.string(), missingRequired: z.boolean(), path: pathNode}); export const createApiEvaluateResponse = z.object({data: responseEvaluateSchema}); 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 }; /** * Evaluate the law * * POST /evaluate */ export const createApiEvaluate = async (args: CreateApiEvaluateArgs, options?: CreateApiEvaluateOptions) => { const {baseUrl = "https://rvig-engine.bzlg.apps.digilab.network/v0", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/evaluate${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(createApiEvaluateResponse, await res.json()) };