import {z} from 'zod' export type GetApiLettersArgs = {invoiceId?: string | undefined, cursor?: string | undefined, limit?: number | undefined}; export type GetApiLettersOptions = {baseUrl: string, ApiKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const letter = z.object({deliveredAt: z.string().nullable().optional(), dispatchedAt: z.string().nullable().optional(), documentType: z.string().min(1).max(100).optional(), environment: z.enum(["production", "staging"]).optional(), error: z.object({}).nullable().optional(), failedAt: z.string().nullable().optional(), id: z.string().optional(), invoiceId: z.string().nullable().optional(), invoiceSnapshot: z.object({}).optional(), invoiceStatus: z.string().nullable().optional(), recipientAddress: z.string().nullable().optional(), recipientCountry: z.string().nullable().optional(), requestedAt: z.string().nullable().optional(), status: z.enum(["sending", "processing", "dispatched", "delivered", "failed", "undeliverable", "needs_review"]).optional(), undeliverableAt: z.string().nullable().optional(), updatedAt: z.string().nullable().optional()}); export const getApiLettersResponse = z.object({data: z.object({items: z.array(letter).optional(), nextCursor: z.string().nullable().optional()}).optional(), success: z.boolean().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 postal history * * GET /letters * * Also accepts auth: FirebaseIdToken */ export const getApiLetters = async (args: GetApiLettersArgs, options: GetApiLettersOptions) => { const {baseUrl, fetch: fetchFn = fetch, ApiKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.invoiceId != null) query.append("invoiceId", String(args.invoiceId)) if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.limit != null) query.append("limit", String(args.limit)) if (ApiKeyHeader !== undefined) headers.set("X-API-Key", ApiKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/letters${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(getApiLettersResponse, await res.json()) };