import {z} from 'zod' export type Method = 'GET' | 'POST' | 'DELETE' | 'PUT' | 'HEAD' | 'PATCH' | 'OPTIONS'; export type ProxiedRawHttpRequest = {path: string, method: Method, api_version?: number | undefined, headers?: {[key: string]: string} | undefined, body_base64?: (string | null) | undefined}; export type ProxyRequest = {tenant_id: string, node_id: string, request_id?: (string | null) | undefined, http: ProxiedRawHttpRequest}; export type CreateApiUserProxyCachedArgs = {body: ProxyRequest}; export type CreateApiUserProxyCachedOptions = {baseUrl: string, UserKey?: string | undefined, fetch?: typeof fetch | undefined}; export const proxiedHttpResponse = z.object({code: z.number().int(), body_json: z.record(z.string(), z.unknown()).nullable().optional()}); export const cachedProxyResponse = z.object({http: proxiedHttpResponse, request_id: z.string(), from_cache: z.boolean().optional(), cache_time: z.string().nullable().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 }; /** * Proxy Cached Endpoint * * POST /user/proxy-cached */ export const createApiUserProxyCached = async (args: CreateApiUserProxyCachedArgs, options: CreateApiUserProxyCachedOptions) => { const {baseUrl, fetch: fetchFn = fetch, UserKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (UserKey !== undefined) headers.set("X-Tenzir-UserKey", UserKey) const url = `${baseUrl.replace(/\/+$/, '')}/user/proxy-cached${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(cachedProxyResponse, await res.json()) };