import {z} from 'zod' export type GetApiV1AutocompleteCompanyArgs = {query: string}; export type GetApiV1AutocompleteCompanyOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const companyRegisterType = z.enum(["HRB", "HRA", "PR", "GnR", "VR"]); export const companyLegalForm = z.enum(["ag", "eg", "ek", "ev", "ewiv", "foreign", "gbr", "ggmbh", "gmbh", "kg", "kgaa", "unknown", "llp", "municipal", "ohg", "se", "ug"]); export const companySearchAddress = z.object({street: z.string().optional(), city: z.string(), postal_code: z.string().optional(), country: z.string(), extra: z.string().optional(), formatted_value: z.string()}); export const companySearchResponseItem = z.object({company_id: z.string(), name: z.string(), country: z.string().nullable(), register_number: z.string(), register_type: companyRegisterType, register_court: z.string(), active: z.boolean(), legal_form: companyLegalForm, address: companySearchAddress.nullable(), purpose: z.string().nullable()}); export const companyAutocompleteResponse = z.object({results: z.array(companySearchResponseItem)}); 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 }; /** * Autocomplete company search * * GET /v1/autocomplete/company */ export const getApiV1AutocompleteCompany = async (args: GetApiV1AutocompleteCompanyArgs, options?: GetApiV1AutocompleteCompanyOptions) => { const {baseUrl = "https://api.openregister.de", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.query != null) query.append("query", String(args.query)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/autocomplete/company${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(companyAutocompleteResponse, await res.json()) };