import {z} from 'zod' export type GetApiProvidersCatalogArgs = {keys?: string | undefined, name?: string | undefined, channel?: string | undefined}; export type GetApiProvidersCatalogOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const paging = z.object({cursor: z.string().nullable().optional(), more: z.boolean()}); export const providerSchemaField = z.object({type: z.string(), required: z.boolean(), values: z.array(z.string()).optional()}); export const providersCatalogEntry = z.object({provider: z.string(), name: z.string(), description: z.string(), channel: z.string(), settings: z.record(z.string(), providerSchemaField)}); export const providersCatalogResponse = z.object({paging: paging, results: z.array(providersCatalogEntry)}); 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 available provider types * * GET /providers/catalog */ export const getApiProvidersCatalog = async (args: GetApiProvidersCatalogArgs, options?: GetApiProvidersCatalogOptions) => { const {baseUrl = "https://api.courier.com", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.keys != null) query.append("keys", String(args.keys)) if (args.name != null) query.append("name", String(args.name)) if (args.channel != null) query.append("channel", String(args.channel)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/providers/catalog${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(providersCatalogResponse, await res.json()) };