import {z} from 'zod' export type GetApiApiV1CcaaStatsArgs = {'If-None-Match'?: string | undefined}; export type GetApiApiV1CcaaStatsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const ccaaStatsRow = z.object({award_procedures_count: z.number().int().gte(0), award_procedures_count_status: z.enum(["public_projection_v3", "projection_unavailable"]), contracts_count: z.number().int().gte(0), contracts_count_status: z.literal("award_procedures_per_corporate_supplier_not_unique_contracts"), contracts_total_eur: z.unknown(), contracts_total_eur_status: z.literal("withheld_no_typed_rollup"), name: z.string(), total: z.number().int().gte(0), active: z.number().int().gte(0), extinct: z.number().int().gte(0), concurso: z.number().int().gte(0), total_capital_eur: z.number().int().gte(0), provinces: z.array(z.string())}); export const ccaaStatsResponse = z.object({count: z.number().int().gte(0), ccaa: z.array(ccaaStatsRow), source: z.string(), updated: z.string().nullable()}); 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 CCAA aggregates through the suffix-less legacy alias * * GET /api/v1/ccaa/stats */ export const getApiApiV1CcaaStats = async (args: GetApiApiV1CcaaStatsArgs, options?: GetApiApiV1CcaaStatsOptions) => { const {baseUrl = "https://openmercantil.es", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['If-None-Match'] != null) headers.set("If-None-Match", String(args['If-None-Match'])) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/ccaa/stats${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(ccaaStatsResponse, await res.json()) };