import {z} from 'zod' export type GetApiAccountsArgs = {limit?: number | undefined, page?: number | undefined, include?: Array<'billing_address'> | undefined, 'filter[name]'?: string | undefined}; export type GetApiAccountsOptions = {baseUrl?: string | undefined, Oauth2?: string | undefined, fetch?: typeof fetch | undefined}; export const hasMore = z.boolean(); export const jurisdiction = z.object({id: z.string(), name: z.string()}); export const address = z.object({address_line_1: z.string(), address_line_2: z.string().nullable().optional(), locality: z.string(), postal_code: z.string(), administrative_area: jurisdiction.optional(), country: jurisdiction.optional()}); export const account = z.object({id: z.string(), name: z.string(), website: z.string().nullable().optional(), billing_address: address.optional()}); export const getApiAccountsResponse = z.object({has_more: hasMore.optional(), data: z.array(account).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 }; /** * List Accounts * * GET /accounts */ export const getApiAccounts = async (args: GetApiAccountsArgs, options?: GetApiAccountsOptions) => { const {baseUrl = "https://www.harborcompliance.com/api/v1", fetch: fetchFn = fetch, Oauth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.limit != null) query.append("limit", String(args.limit)) if (args.page != null) query.append("page", String(args.page)) if (args.include != null) query.append("include", args.include.join(',')) if (args['filter[name]'] != null) query.append("filter[name]", String(args['filter[name]'])) if (Oauth2 !== undefined) headers.set('authorization', `Bearer ${Oauth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/accounts${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(getApiAccountsResponse, await res.json()) };