import {z} from 'zod' export type SharedKeyInput = {kudos?: number | undefined, expiry?: number | undefined, name?: string | undefined, max_image_pixels?: number | undefined, max_image_steps?: number | undefined, max_text_tokens?: number | undefined}; export type UpdateApiV2SharedkeysArgs = {apikey: string, 'Client-Agent'?: string | undefined, 'X-Fields'?: unknown | undefined, body: SharedKeyInput}; export type UpdateApiV2SharedkeysOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const sharedKeyDetails = z.object({id: z.string().optional(), username: z.string().optional(), name: z.string().optional(), kudos: z.number().int().optional(), expiry: z.string().optional(), utilized: z.number().int().optional(), max_image_pixels: z.number().int().optional(), max_image_steps: z.number().int().optional(), max_text_tokens: z.number().int().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 a new SharedKey for this user * * PUT /v2/sharedkeys */ export const updateApiV2Sharedkeys = async (args: UpdateApiV2SharedkeysArgs, options: UpdateApiV2SharedkeysOptions) => { 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/sharedkeys${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "PUT", 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(sharedKeyDetails, await res.json()) };