import {z} from 'zod' export type GetApiApiCrawlIdArgs = {id: string, page?: number | undefined, batchSize?: number | undefined}; export type GetApiApiCrawlIdOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const jobStatus = z.enum(["pending", "running", "completed", "failed", "stopped"]); export const crawledPage = z.object({url: z.string(), status: z.enum(["completed", "failed"]), error: z.string().nullable().optional(), metadata: z.record(z.string(), z.union([z.string(), z.array(z.string())])).optional(), markdown: z.string().optional(), html: z.string().optional(), links: z.array(z.string()).optional(), screenshot: z.string().optional()}); export const getApiApiCrawlIdResponse = z.object({jobId: z.string(), status: jobStatus, error: z.string().nullable().optional(), totalCrawledPages: z.number().int().gte(0).optional(), totalPageBatches: z.number().int().gte(0).optional(), currentPageBatch: z.number().int().gte(0).optional(), batchSize: z.number().int().gte(1).optional(), data: z.array(crawledPage).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 }; /** * Get crawl job status and results * * GET /api/crawl/{id} */ export const getApiApiCrawlId = async (args: GetApiApiCrawlIdArgs, options?: GetApiApiCrawlIdOptions) => { const {baseUrl = "https://api.hyperbrowser.ai", fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.page != null) query.append("page", String(args.page)) if (args.batchSize != null) query.append("batchSize", String(args.batchSize)) if (ApiKeyAuth !== undefined) headers.set("x-api-key", ApiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/api/crawl/${encodeURIComponent(String(args.id))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiApiCrawlIdResponse, await res.json()) };