import {z} from 'zod' export type Reference = string; export type ApplicantRequest = {email: string, first_name?: string | undefined, last_name?: string | undefined}; export type BusinessLegalStructure = 'ca_private_corp' | 'ca_public_corp' | 'ca_non_profit'; export type BaseRegistrationNumber = {type: string, value: string}; export type GermanRegistrationNumber = {type: string, value: string, registry: string}; export type RegistrationNumber = BaseRegistrationNumber | GermanRegistrationNumber; export type BusinessRequest = {legal_name: string, country: unknown, legal_structure?: BusinessLegalStructure | undefined, registered_address?: ({line1: string, line2?: string | undefined, street_number: string, city: string, region?: string | undefined, postal_code: string}) | undefined, registration_number?: RegistrationNumber | undefined}; export type TimeSpan = unknown; export type ApplicationWebhooksRequest = {url: string}; export type OnboardingApplicationRequest = {type: 'onboarding' | 'change_request', reference: Reference, applicant: ApplicantRequest, business: BusinessRequest, redirect: {default: string}, expires_in?: TimeSpan | undefined, webhooks?: ApplicationWebhooksRequest | undefined}; export type AccountId = string; export type ApplicationFieldRequest = {name: 'themes', access: 'read_write'}; export type ChangeRequestApplicationRequest = {type: 'onboarding' | 'change_request', account: {id: AccountId}, reference: Reference, fields: Array, redirect?: {default: string} | undefined, theme_id?: string | undefined, expires_in?: TimeSpan | undefined, webhooks?: ApplicationWebhooksRequest | undefined}; export type CreateApplicationRequest = OnboardingApplicationRequest | ChangeRequestApplicationRequest; export type CreateApiV2ApplicationsArgs = {'Getpaid-Idempotency-Key': string, body: CreateApplicationRequest}; export type CreateApiV2ApplicationsOptions = {baseUrl?: string | undefined, OAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const applicationId = z.string().min(30).max(50); export const applicationStatus = z.enum(["initiated", "identity_verified", "submitted", "screened", "approved", "completed", "cancelled", "expired"]); export const reference = z.string().min(1).max(50); export const createdAt = z.string().min(24).max(24); export const updatedAt = z.string().min(24).max(24); export const applicationExpiresAt = z.string().min(24).max(24); export const accountId = z.string().min(30).max(50); export const dateTime = z.string().min(24).max(24); export const applicationFlow = z.object({next_step: z.object({type: z.literal("redirect"), url: z.string().max(1024), expires_at: dateTime.optional()})}); export const createApplicationResponse = z.object({id: applicationId, status: applicationStatus, reference: reference, created_at: createdAt, updated_at: updatedAt, expires_at: applicationExpiresAt, account: z.object({id: accountId}), flow: applicationFlow}); 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 }; /** * Create an application * * POST /v2/applications */ export const createApiV2Applications = async (args: CreateApiV2ApplicationsArgs, options?: CreateApiV2ApplicationsOptions) => { const {baseUrl = "https://api.getpaid.io", fetch: fetchFn = fetch, OAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['Getpaid-Idempotency-Key'] != null) headers.set("Getpaid-Idempotency-Key", String(args['Getpaid-Idempotency-Key'])) if (OAuth !== undefined) headers.set('authorization', `Bearer ${OAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/applications${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createApplicationResponse, await res.json()) };