UNPKG

acp-handler

Version:

Vercel handler for Agentic Commerce Protocol (ACP) - Build checkout APIs that AI agents like ChatGPT can use to complete purchases

89 lines (86 loc) 2.47 kB
import { z } from "zod"; //#region src/checkout/http.ts function json(data, status = 200, headers) { return new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json", ...headers } }); } function specError(code, message, param, status = 400, type = "invalid_request_error") { return json({ error: { type, code, message, ...param ? { param } : {} } }, status); } async function parseJSON(req) { try { return { ok: true, body: await req.json() }; } catch { return { ok: false, res: specError("invalid_json", "Invalid JSON body") }; } } //#endregion //#region src/checkout/schema.ts const MoneySchema = z.object({ amount: z.number(), currency: z.string().min(3).max(3) }); const AddressSchema = z.object({ name: z.string().optional(), line1: z.string(), line2: z.string().optional(), city: z.string(), region: z.string().optional(), postal_code: z.string(), country: z.string().length(2), phone: z.string().optional(), email: z.string().email().optional() }); const CreateCheckoutSessionSchema = z.object({ items: z.array(z.object({ id: z.string(), quantity: z.number().int().positive() })).min(1), customer: z.object({ billing_address: AddressSchema.optional(), shipping_address: AddressSchema.optional() }).optional(), fulfillment: z.object({ selected_id: z.string().optional() }).optional() }); const UpdateCheckoutSessionSchema = CreateCheckoutSessionSchema.partial().refine((obj) => Object.keys(obj).length > 0, { message: "must include at least one updatable field" }); const CompleteCheckoutSessionSchema = z.object({ payment: z.object({ delegated_token: z.string().optional(), method: z.string().optional() }).refine((p) => !!p.delegated_token || !!p.method, { message: "payment method or delegated_token required" }), customer: CreateCheckoutSessionSchema.shape.customer.optional(), fulfillment: CreateCheckoutSessionSchema.shape.fulfillment.optional() }); function validateBody(schema, body) { const v = schema.safeParse(body); if (!v.success) { const i = v.error.issues[0]; return { ok: false, res: specError("validation_error", i.message, i.path.join(".")) }; } return { ok: true, data: v.data }; } //#endregion export { AddressSchema, CompleteCheckoutSessionSchema, CreateCheckoutSessionSchema, MoneySchema, UpdateCheckoutSessionSchema, json, parseJSON, specError, validateBody }; //# sourceMappingURL=schema-dfYBxw9A.js.map