import {z} from 'zod' export type GetApiCompaniesArgs = {isoCode?: string | undefined, name?: string | undefined, companyNumber?: string | undefined}; export type GetApiCompaniesOptions = {baseUrl?: string | undefined, AuthHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const cost = z.object({type: z.enum(["credit", "lite"]).optional(), value: z.number().optional()}); export const identifier = z.object({value: z.string().optional(), type: z.string().optional()}); export const searchResult = z.object({id: z.string().optional(), companyName: z.string().optional(), englishName: z.string().optional(), companyNumber: z.string().optional(), address: z.string().optional(), status: z.string().optional(), type: z.string().optional(), startDate: z.string().optional(), links: z.object({self: z.string().optional()}).optional(), registrationAuthority: z.string().optional(), otherIdentifiers: z.array(identifier).optional(), registrationType: z.string().optional(), registrationTypeDetails: z.object({originalCode: z.string().optional(), originalDescription: z.string().optional(), normalizedCode: z.string().optional(), normalizedDescription: z.string().optional()}).optional(), isPreviousName: z.boolean().optional()}); export const getApiCompaniesResponse = z.object({orderId: z.string().optional(), correlationId: z.string().optional(), customerReference: z.string().optional(), timeStamp: z.string().optional(), details: z.string().optional(), cost: cost.optional(), links: z.object({self: z.string().optional()}).optional(), data: z.array(searchResult).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 }; /** * Search for companies * * GET /companies */ export const getApiCompanies = async (args: GetApiCompaniesArgs, options?: GetApiCompaniesOptions) => { const {baseUrl = "https://api.kyckr.com/v2", fetch: fetchFn = fetch, AuthHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.isoCode != null) query.append("isoCode", String(args.isoCode)) if (args.name != null) query.append("name", String(args.name)) if (args.companyNumber != null) query.append("companyNumber", String(args.companyNumber)) if (AuthHeader !== undefined) headers.set('authorization', `Bearer ${AuthHeader}`) const url = `${baseUrl.replace(/\/+$/, '')}/companies${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(getApiCompaniesResponse, await res.json()) };