import {z} from 'zod' export type CreateApiRawDownloadArgs = {sha256_original?: (string | null) | undefined, container_id?: (number | null) | undefined, entry_path?: (string | null) | undefined, expires_in?: number | undefined, body: {[key: string]: unknown} | null}; export type CreateApiRawDownloadOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const downloadSourceResponse = z.object({url: z.string(), expires_in: z.number().int().optional(), file_name: z.string().nullable().optional(), size_bytes: z.number().int().nullable().optional(), mime: z.string().nullable().optional(), already_unlocked: z.boolean().optional(), downloaded_before: z.boolean().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 }; /** * Generate a download URL for a raw file * * POST /raw/download */ export const createApiRawDownload = async (args: CreateApiRawDownloadArgs, options?: CreateApiRawDownloadOptions) => { const {baseUrl = "https://api.leakradar.io", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.sha256_original != null) query.append("sha256_original", String(args.sha256_original)) if (args.container_id != null) query.append("container_id", String(args.container_id)) if (args.entry_path != null) query.append("entry_path", String(args.entry_path)) if (args.expires_in != null) query.append("expires_in", String(args.expires_in)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/raw/download${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(downloadSourceResponse, await res.json()) };