import {z} from 'zod' export type CreateApiKbEntriesArgs = {body: {question: string, answer?: (string | null) | undefined, comment?: (string | null) | undefined, accessLevel?: ('public' | 'private' | 'internal') | undefined}}; export type CreateApiKbEntriesOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiKbEntriesResponse = z.object({ok: z.boolean().optional(), result: z.object({id: z.string().optional(), source: z.literal("manual").optional(), subtype: z.object({raw: z.array(z.literal("Custom")).optional(), pretty: z.array(z.literal("Custom")).optional()}).optional(), content: z.string().optional(), product: z.unknown(), answer: z.string().nullable().optional(), comment: z.string().nullable().optional(), pageNumber: z.unknown(), questionNumber: z.unknown(), createdAt: z.string().optional(), modifiedAt: z.string().optional()}).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 }; /** * Create Knowledge Base Entry * * POST /kb/entries */ export const createApiKbEntries = async (args: CreateApiKbEntriesArgs, options?: CreateApiKbEntriesOptions) => { const {baseUrl = "https://app.safebase.io/api/ext/v1/rest", 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("x-sb-api-key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/kb/entries${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(createApiKbEntriesResponse, await res.json()) };