import {z} from 'zod' export type ModelInterrogationFormPayloadStable = {'*'?: {[key: string]: string} | undefined}; export type ModelInterrogationFormStable = {name: 'caption' | 'interrogation' | 'nsfw' | 'GFPGAN' | 'RealESRGAN_x4plus' | 'RealESRGAN_x2plus' | 'RealESRGAN_x4plus_anime_6B' | 'NMKD_Siax' | '4x_AnimeSharp' | 'CodeFormers' | 'strip_background', payload?: ModelInterrogationFormPayloadStable | undefined}; export type ModelInterrogationInputStable = {forms?: Array | undefined, source_image?: string | undefined, slow_workers?: boolean | undefined, webhook?: string | undefined}; export type CreateApiV2InterrogateAsyncArgs = {apikey: string, 'Client-Agent'?: string | undefined, 'X-Fields'?: unknown | undefined, body: ModelInterrogationInputStable}; export type CreateApiV2InterrogateAsyncOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const requestInterrogationResponse = z.object({id: z.string().optional(), message: 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 }; /** * Initiate an Asynchronous request to interrogate an image * * POST /v2/interrogate/async */ export const createApiV2InterrogateAsync = async (args: CreateApiV2InterrogateAsyncArgs, options: CreateApiV2InterrogateAsyncOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.apikey != null) headers.set("apikey", String(args.apikey)) if (args['Client-Agent'] != null) headers.set("Client-Agent", String(args['Client-Agent'])) if (args['X-Fields'] != null) headers.set("X-Fields", String(args['X-Fields'])) const url = `${baseUrl.replace(/\/+$/, '')}/v2/interrogate/async${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(requestInterrogationResponse, await res.json()) };