import {z} from 'zod' export type GetApiApiV1SearchArgs = {q: string, limit?: number | undefined, offset?: number | undefined, 'If-None-Match'?: string | undefined}; export type GetApiApiV1SearchOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const jsonValue: z.ZodType = z.union([z.string(), z.number(), z.boolean(), z.array(z.lazy(() => jsonValue)), z.record(z.string(), z.lazy(() => jsonValue))]).nullable(); export const companySearchItem = z.object({slug: z.string(), name: z.string(), cif: z.string(), acts_count: z.number().int(), last_seen: z.string().nullable().optional(), province: z.string().nullable().optional(), cnae_code: z.string().nullable().optional(), cnae_section: z.string().nullable().optional(), capital_cents: z.number().int().gte(0).nullable().optional(), first_seen: z.string().nullable().optional(), matched_alias: z.string().optional(), aliases: z.array(z.string()).optional()}).and(z.record(z.string(), jsonValue)); export const searchResponse = z.object({query: z.string(), count: z.number().int(), offset: z.number().int().optional(), items: z.array(companySearchItem)}); 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 }; /** * Search published Spanish legal entities * * GET /api/v1/search * * Also accepts auth: bearerAuth */ export const getApiApiV1Search = async (args: GetApiApiV1SearchArgs, options?: GetApiApiV1SearchOptions) => { const {baseUrl = "https://openmercantil.es", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.q != null) query.append("q", String(args.q)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.offset != null) query.append("offset", String(args.offset)) if (args['If-None-Match'] != null) headers.set("If-None-Match", String(args['If-None-Match'])) if (apiKey !== undefined) headers.set("X-API-Key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/search${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(searchResponse, await res.json()) };