import {z} from 'zod' export type GetApiStatusIdArgs = {id: string}; export type GetApiStatusIdOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const gatewayRequestKind = z.enum(["create_account", "update_authenticator", "insert_authenticator", "remove_authenticator", "update_recovery_agent", "cancel_recovery_agent_update", "execute_recovery_agent_update", "recover_account"]); export const gatewayRequestId = z.string(); export const gatewayErrorCode = z.enum(["internal_server_error", "not_found", "bad_request", "batcher_unavailable", "authenticator_already_exists", "authenticator_does_not_exist", "mismatched_signature_nonce", "pubkey_id_in_use", "pubkey_id_out_of_bounds", "authenticator_does_not_belong_to_account", "transaction_reverted", "confirmation_error", "duplicate_request_in_flight", "rate_limit_exceeded", "request_timeout", "method_not_available"]); export const gatewayRequestState = z.union([z.object({state: z.literal("queued")}), z.object({state: z.literal("batching")}), z.object({state: z.literal("submitted"), tx_hash: z.string()}), z.object({state: z.literal("finalized"), tx_hash: z.string()}), z.object({error: z.string(), error_code: gatewayErrorCode.nullable().optional(), state: z.literal("failed")})]); export const gatewayStatusResponse = z.object({kind: gatewayRequestKind, request_id: gatewayRequestId, status: gatewayRequestState}); 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 }; /** * GET /status/{id} */ export const getApiStatusId = async (args: GetApiStatusIdArgs, options: GetApiStatusIdOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/status/${encodeURIComponent(String(args.id))}${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(gatewayStatusResponse, await res.json()) };