cope-sdk 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +74 -1
- package/README.md +94 -41
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +55 -10
- package/dist/index.d.ts +55 -10
- package/dist/index.global.js +1 -2
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/mcp/node.cjs +59 -20
- package/dist/mcp/node.cjs.map +1 -1
- package/dist/mcp/node.js +59 -20
- package/dist/mcp/node.js.map +1 -1
- package/dist/mcp.cjs +59 -20
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.js +59 -20
- package/dist/mcp.js.map +1 -1
- package/package.json +2 -1
package/dist/mcp.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp/cart-ref.ts","../src/mcp/rate-limit.ts","../src/types.ts","../src/cope-cart.ts","../src/mcp/results.ts","../src/mcp/tools.ts","../src/mcp/handler.ts"],"names":["cartRef","window","isRecord","lineId","z","productId","createMcpHandler","server","McpServer","hostHeaderValidationResponse","originValidationResponse"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,IAAM,MAAA,GAAS,KAAA;AACf,IAAM,QAAA,GAAW,EAAA;AACjB,IAAM,SAAA,GAAY,EAAA;AAEX,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC7C,WAAA,GAAc;AACZ,IAAA,KAAA,CAAM,qCAAqC,CAAA;AAC3C,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF,CAAA;AAgBO,SAAS,iBAAiB,IAAA,EAAoD;AACnF,EAAA,IAAI,KAAK,MAAA,KAAW,CAAA,EAAG,MAAM,IAAI,MAAM,oCAAoC,CAAA;AAC3E,EAAA,OAAO,IAAA,CAAK,GAAA,C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,GAAA;AAAA,YACR,SAAS,EAAE,cAAA,EAAgB,oBAAoB,aAAA,EAAe,MAAA,CAAO,UAAU,CAAA;AAAE,WAClF,CAAA;AAAA,QACH;AAAA,MACF;AACA,MAAA,OAAO,GAAA,CAAI,MAAM,OAAO,CAAA;AAAA,IAC1B;AAAA,GACF;AACF","file":"mcp.cjs","sourcesContent":["/**\n * The cart handle an agent carries between tool calls.\n *\n * MCP's 2026-07-28 protocol is stateless, so nothing ties one tool call to the\n * next except what the agent sends back. The handle therefore holds the cart's\n * id and bearer secret — encrypted, so the agent (and the model behind it) never\n * sees the secret, and authenticated, so a forged or edited handle is refused\n * rather than pointed at another buyer's cart.\n *\n * Format: `cr1.<iv>.<ciphertext>`, base64url, AES-256-GCM. The merchant's\n * publishable key is the additional data, so a handle minted for one merchant\n * never opens under another's configuration even if both reused a key. Keys are\n * a list: the first encrypts, every one decrypts, which is how a key rotates\n * without breaking handles already in agents' hands.\n */\n\nconst PREFIX = 'cr1'\nconst IV_BYTES = 12\nconst KEY_BYTES = 32\n\nexport class InvalidCartRefError extends Error {\n constructor() {\n super('cartRef is not valid for this store')\n this.name = 'InvalidCartRefError'\n }\n}\n\nexport interface CartCredentials {\n readonly id: string\n readonly secret: string\n}\n\nexport interface CartRefCodec {\n encode(cart: CartCredentials): Promise<string>\n decode(cartRef: string): Promise<CartCredentials>\n}\n\n/**\n * Decodes and checks the configured keys. Synchronous, so a handler can refuse a\n * bad configuration when it is created rather than on its first request.\n */\nexport function parseCartRefKeys(keys: readonly string[]): Uint8Array<ArrayBuffer>[] {\n if (keys.length === 0) throw new Error('cartRefKeys needs at least one key')\n return keys.map((encoded) => {\n let raw: Uint8Array<ArrayBuffer>\n try {\n raw = fromBase64Url(encoded)\n } catch {\n throw new Error('cartRefKeys entries must be base64 or base64url')\n }\n if (raw.length !== KEY_BYTES) throw new Error(`cartRefKeys entries must decode to ${KEY_BYTES} bytes`)\n return raw\n })\n}\n\nexport async function createCartRefCodec(keys: readonly string[], publishableKey: string): Promise<CartRefCodec> {\n const cryptoKeys = await Promise.all(parseCartRefKeys(keys).map((raw) =>\n crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['encrypt', 'decrypt'])))\n const additionalData = new TextEncoder().encode(publishableKey)\n\n return {\n async encode(cart) {\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES))\n const plaintext = new TextEncoder().encode(JSON.stringify({ c: cart.id, s: cart.secret }))\n const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData }, cryptoKeys[0], plaintext)\n return `${PREFIX}.${toBase64Url(iv)}.${toBase64Url(new Uint8Array(ciphertext))}`\n },\n\n async decode(cartRef) {\n const parts = cartRef.split('.')\n if (parts.length !== 3 || parts[0] !== PREFIX) throw new InvalidCartRefError()\n let iv: Uint8Array<ArrayBuffer>\n let ciphertext: Uint8Array<ArrayBuffer>\n try {\n iv = fromBase64Url(parts[1])\n ciphertext = fromBase64Url(parts[2])\n } catch {\n throw new InvalidCartRefError()\n }\n if (iv.length !== IV_BYTES) throw new InvalidCartRefError()\n\n for (const key of cryptoKeys) {\n let plaintext: ArrayBuffer\n try {\n plaintext = await crypto.subtle.decrypt({ name: 'AES-GCM', iv, additionalData }, key, ciphertext)\n } catch {\n continue // not this key, or tampered — try the next\n }\n const parsed: unknown = JSON.parse(new TextDecoder().decode(plaintext))\n if (isRecord(parsed) && typeof parsed.c === 'string' && typeof parsed.s === 'string') {\n return { id: parsed.c, secret: parsed.s }\n }\n throw new InvalidCartRefError()\n }\n throw new InvalidCartRefError()\n },\n }\n}\n\n/** A fresh key in the format `cartRefKeys` takes: 32 random bytes, base64url. */\nexport function generateCartRefKey(): string {\n return toBase64Url(crypto.getRandomValues(new Uint8Array(KEY_BYTES)))\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n let binary = ''\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n// Accepts base64url and standard base64, padded or not.\nfunction fromBase64Url(value: string): Uint8Array<ArrayBuffer> {\n if (!/^[A-Za-z0-9_\\-+/]*={0,2}$/.test(value)) throw new Error('not base64')\n const base64 = value.replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, '')\n const binary = atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4))\n return Uint8Array.from(binary, (char) => char.charCodeAt(0))\n}\n","/**\n * A fixed-window request limit per key, in memory.\n *\n * Every tool call reaches cope-edge with the store's publishable key and from\n * the store's own server, so edge cannot tell one buyer's agent from another.\n * The handler keeps two of these: one per identifiable client, so one runaway\n * agent is stopped without affecting the rest, and one for the whole store, a\n * higher ceiling that protects the store's edge quota when clients cannot be\n * told apart. It is per process: a store running several instances should put a\n * shared limiter in front.\n */\n\nexport interface RateLimiter {\n /** Counts one request for `key`; returns null if allowed, or seconds to wait. */\n take(key: string): number | null\n}\n\nconst WINDOW_MS = 60_000\n// Bounds memory under a flood of distinct keys.\nconst MAX_KEYS = 10_000\n\nexport function createRateLimiter(perMinute: number, now: () => number = Date.now): RateLimiter {\n if (!Number.isInteger(perMinute) || perMinute < 1) throw new Error('rate limits must be positive integers')\n // Insertion order is window-start order: a key is deleted and re-inserted\n // whenever its window restarts, so the oldest windows are always at the front\n // and eviction never scans.\n const windows = new Map<string, { start: number; count: number }>()\n\n return {\n take(key) {\n const at = now()\n const current = windows.get(key)\n if (current && at - current.start < WINDOW_MS) {\n if (current.count >= perMinute) return Math.ceil((current.start + WINDOW_MS - at) / 1000)\n current.count += 1\n return null\n }\n windows.delete(key)\n for (const [oldest, window] of windows) {\n if (windows.size < MAX_KEYS && at - window.start < WINDOW_MS) break\n windows.delete(oldest)\n }\n windows.set(key, { start: at, count: 1 })\n return null\n },\n }\n}\n","// ---------------------------------------------------------------------------\n// Error classes\n// ---------------------------------------------------------------------------\n\nexport class CopeError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'CopeError'\n }\n}\n\nexport class CopeApiError extends CopeError {\n readonly code: ApiErrorCode\n readonly status: number\n readonly field?: string\n readonly requestId: string | null\n /** Seconds the server asked the caller to wait (`Retry-After`), or null. */\n readonly retryAfter: number | null\n readonly errors: ReadonlyArray<{ readonly code: string; readonly message: string; readonly field?: string }>\n\n constructor(\n status: number,\n errors: Array<{ code: string; message: string; field?: string }>,\n requestId?: string | null,\n retryAfter?: number | null,\n ) {\n const first = errors[0]\n super(first?.message ?? `API error ${status}`)\n this.name = 'CopeApiError'\n this.status = status\n this.code = (first?.code ?? 'unknown') as ApiErrorCode\n this.field = first?.field\n this.requestId = requestId ?? null\n this.retryAfter = retryAfter ?? null\n this.errors = errors\n }\n}\n\nexport class CopeNetworkError extends CopeError {\n constructor(message: string) {\n super(message)\n this.name = 'CopeNetworkError'\n }\n}\n\nexport class CopeCartExpiredError extends CopeError {\n readonly state: CartState\n\n constructor(state: CartState) {\n super(`Cart is ${state} and cannot be used`)\n this.name = 'CopeCartExpiredError'\n this.state = state\n }\n}\n\n// ---------------------------------------------------------------------------\n// Error codes — known codes + string escape hatch\n// ---------------------------------------------------------------------------\n\nexport type ApiErrorCode =\n | 'rate_limited'\n | 'cart_not_active'\n | 'duplicate_line'\n | 'not_saleable'\n | 'empty_cart'\n | 'incomplete_buyer_identity'\n | 'incomplete_shipping_address'\n | 'missing_consent'\n | 'below_minimum_charge'\n | 'invalid_redirect_url'\n | 'checkout_expired'\n | 'checkout_not_open'\n | 'checkout_not_cancellable'\n // A refused promo code (422), PromoCodes::Validate's reasons. `not_found` here\n // means no such code; it shares the name of the 404 code below.\n | 'inactive'\n | 'not_started'\n | 'expired'\n | 'exhausted'\n | 'no_applicable_items'\n | 'currency_not_supported'\n | 'promo_not_supported_for_recurring'\n | 'missing_code'\n | 'missing_tax_location'\n | 'tax_service_unavailable'\n | 'payment_provider_error'\n | 'unauthorized'\n | 'not_found'\n | 'validation_error'\n | 'cart_id_mismatch'\n // Answered by cope-edge itself, in its `{error, request_id}` envelope.\n | 'payload_too_large'\n | 'upstream_unavailable'\n | 'gateway_timeout'\n | (string & {}) // escape hatch for unknown codes\n\n// ---------------------------------------------------------------------------\n// Cart\n// ---------------------------------------------------------------------------\n\nexport type CartState =\n | 'active'\n | 'checkout_in_progress'\n | 'ordered'\n | 'expired'\n | 'abandoned'\n | 'merged'\n\nexport interface OneClickChargeConsentApplicability {\n readonly applicable: boolean\n readonly terms_version: string | null\n}\n\nexport interface Cart {\n readonly id: string\n readonly state: CartState\n readonly version: number\n readonly currency: string\n readonly charge_currency: string\n /** Present only in the `createCart()` response. The SDK persists it to localStorage automatically. */\n readonly cart_secret?: string\n readonly lines: readonly CartLine[]\n /**\n * Absent where cope-core does not report it — the reprice and promo-code\n * responses — which is not the same as `null` (no buyer recorded yet).\n */\n readonly buyer_identity?: BuyerIdentity | null\n readonly totals: CartTotals | null\n readonly locale: string\n readonly applied_promo_code: AppliedPromoCode | null\n /** Backend-owned OTO candidate; absent while older backends roll forward. */\n readonly one_click_charge_consent?: OneClickChargeConsentApplicability | null\n}\n\n// ---------------------------------------------------------------------------\n// Cart Line\n// ---------------------------------------------------------------------------\n\nexport interface CartLine {\n readonly id: string\n readonly cart_id: string\n readonly product_id: number\n readonly plan_id: number | null\n readonly quantity: number\n readonly price_snapshot: PriceSnapshot | null\n /** The product's name, present before the line is repriced (`price_snapshot` is null until then). */\n readonly product_name?: string | null\n readonly product_uuid: string\n readonly stale?: boolean\n readonly requires_shipping?: boolean\n readonly trial_days?: number\n readonly payment_methods: readonly string[]\n readonly plan_type: string | null\n}\n\nexport interface PriceSnapshot {\n readonly unit_price_minor_units: number\n readonly currency: string\n readonly charge_currency: string\n readonly product_name: string\n readonly plan_name: string | null\n readonly captured_at: string\n}\n\n// ---------------------------------------------------------------------------\n// Buyer Identity\n// ---------------------------------------------------------------------------\n\nexport interface Address {\n readonly line1: string\n readonly line2: string | null\n readonly city: string\n readonly region?: string | null\n readonly postal_code: string\n readonly country: string\n}\n\n/** The promo code on the cart and what it takes off (apps/cope-core CartBlueprint `applied_promo_code`). */\nexport interface AppliedPromoCode {\n readonly id: number\n readonly code: string\n readonly discount_total_minor_units: number\n /** True when the discount was trimmed to keep the order above the minimum charge. */\n readonly capped_to_minimum_charge: boolean\n}\n\nexport interface BuyerIdentity {\n readonly email: string\n readonly country: string\n readonly postal_code: string | null\n readonly company: string | null\n readonly buyer_type: 'b2b' | 'b2c' | null\n readonly billing_address: Address | null\n readonly shipping_address: Address | null\n readonly consents: readonly Consent[]\n}\n\nexport interface Consent {\n readonly type: string\n readonly granted_at: string\n readonly ip: string\n}\n\n// ---------------------------------------------------------------------------\n// Totals\n// ---------------------------------------------------------------------------\n\nexport type TotalsFinality = 'estimate' | 'final'\n\nexport interface CartTotals {\n readonly subtotal_minor_units: number\n readonly tax_minor_units: number\n readonly shipping_minor_units: number\n readonly discount_minor_units: number\n readonly total_minor_units: number\n /** Currency the *_minor_units are denominated in. Always equals `charge_currency`. */\n readonly currency: string\n /** Currency that will be billed (Stripe PaymentIntent.currency). */\n readonly charge_currency: string\n readonly finality: TotalsFinality\n /** Buyer's selected presentment currency, when different from `charge_currency`.\n * Paired with `presentment_exchange_rate`; both present or both absent.\n * To display amounts in presentment, multiply each `*_minor_units` by `presentment_exchange_rate`. */\n readonly presentment_currency?: string\n readonly presentment_exchange_rate?: number\n}\n\n// ---------------------------------------------------------------------------\n// Product (read-only, for getProduct)\n// ---------------------------------------------------------------------------\n\nexport interface SdkProduct {\n readonly uuid: string\n readonly name: string\n readonly headline: string | null\n readonly product_type: string\n readonly currency: string\n readonly payment_methods: readonly string[]\n readonly images: readonly SdkProductImage[]\n readonly payment_plans: readonly SdkPaymentPlan[]\n}\n\nexport interface SdkProductImage {\n readonly id: number\n readonly image_url: string\n}\n\nexport interface SdkPaymentPlan {\n readonly id: number\n readonly plan_type: 'one_time' | 'subscription' | 'installment'\n readonly position: number\n readonly currency: string\n readonly display_name: string | null\n /** Price as a decimal string, e.g. \"24.99\" (dollars, not cents despite the field name) */\n readonly first_payment_amount_cents: string\n readonly next_payments_amount_cents: string | null\n readonly next_payments_count: number | null\n readonly shipping_price_cents: string\n readonly charge_shipping_once: boolean\n readonly shipping_depend_on_quantity: boolean\n readonly interval: 'day' | 'week' | 'month' | 'year' | null\n readonly interval_count: number | null\n readonly second_payment_in: number | null\n readonly vanity_prices: readonly SdkVanityPrice[]\n}\n\nexport interface SdkVanityPrice {\n readonly id: number\n readonly currency: string\n readonly first_payment_amount_cents: string\n readonly next_payments_amount_cents: string | null\n}\n\n// ---------------------------------------------------------------------------\n// Checkout\n// ---------------------------------------------------------------------------\n\nexport type CheckoutStatus = 'open' | 'completed' | 'expired' | 'cancelled'\n\nexport interface CheckoutCreateEmbedPolicy {\n readonly allowed: true\n readonly parent_origin: string\n}\n\nexport interface CheckoutCreateResponse {\n readonly checkout_id: string\n readonly checkout_url: string\n readonly embed?: CheckoutCreateEmbedPolicy\n readonly status: CheckoutStatus\n readonly expires_at: string\n readonly totals: CartTotals\n readonly cart_version: number\n}\n\n// ---------------------------------------------------------------------------\n// SDK Options & Payloads\n// ---------------------------------------------------------------------------\n\nexport interface CopeCartOptions {\n readonly publishableKey: string\n readonly baseUrl?: string\n readonly checkoutBaseUrl?: string\n /**\n * Where the active cart's id and secret are kept between page loads.\n * `'localStorage'` (default) is right for one buyer in one browser. Use `'none'`\n * on a server, where one process serves many buyers: a process-wide store would\n * hand one buyer's cart secret to the next client. A client also holds its cart\n * secret in memory and sends it on every request, so a server needs one client\n * per buyer (or per request with `cart`), never one shared client.\n */\n readonly persistence?: 'localStorage' | 'none'\n /**\n * Act on an existing cart whose credentials the caller already holds. Implies\n * `persistence: 'none'`: such a client never reads, writes or clears stored carts.\n */\n readonly cart?: { readonly id: string; readonly secret: string }\n}\n\nexport interface CheckoutOptions {\n /**\n * Sent as the Idempotency-Key. The cart API replays its stored answer to a\n * repeated key and identical body, so a caller that may re-send the same\n * checkout (an agent retrying a tool call) gets the same checkout back instead\n * of `cart_not_active` from a cart the first call already locked. While the first\n * call is still being processed, a repeat gets 409 `idempotency_conflict`; wait\n * briefly and repeat again.\n */\n readonly idempotencyKey?: string\n}\n\nexport interface CreateCartPayload {\n readonly currency: string\n readonly locale?: string\n readonly attribution?: CartAttribution\n readonly metadata?: CartMetadata\n}\n\nexport interface CartAttribution {\n readonly affiliate_id?: string\n readonly promo_code?: string\n readonly utm_source?: string\n readonly utm_medium?: string\n readonly utm_campaign?: string\n readonly utm_content?: string\n readonly utm_term?: string\n readonly landing_url?: string\n readonly referrer?: string\n readonly captured_at?: string\n}\n\nexport type CartMetadataValue =\n | string\n | number\n | boolean\n | null\n | readonly CartMetadataValue[]\n | { readonly [key: string]: CartMetadataValue }\n\nexport interface CartMetadata {\n readonly [key: string]: CartMetadataValue\n}\n\nexport interface AddLinePayload {\n /** Product UUID string — resolved to integer FK in API response (CartLine.product_id) */\n readonly product_id: string\n /** Optional payment plan ID. Omit it to let the API select the product's default plan. */\n readonly plan_id?: number\n readonly quantity?: number\n}\n\nexport interface UpdateLinePayload {\n readonly quantity?: number\n readonly plan_id?: number\n}\n\nexport interface UpdateBuyerIdentityPayload {\n readonly email?: string\n readonly first_name?: string\n readonly last_name?: string\n readonly country?: string\n readonly postal_code?: string\n readonly company?: string\n readonly buyer_type?: 'b2b' | 'b2c'\n readonly vat_id?: string\n readonly billing_address?: Partial<Address>\n readonly shipping_address?: Partial<Address>\n readonly consents?: ReadonlyArray<{ readonly type: string }>\n}\n\nexport interface CheckoutPayload {\n readonly success_url?: string\n readonly cancel_url?: string\n readonly embed_origin?: string\n readonly consents: ReadonlyArray<{ readonly type: string; readonly version?: string }>\n}\n\n/**\n * The minimum a checkout has to expose to be mounted in an iframe.\n *\n * `mountCheckout` reads exactly three things: `embedCheckoutUrl` (the frame's\n * src, and the source of the handshake token), `embedOrigin` (checked against\n * the hosting page), and `checkoutUrl` — the last only for `fallback:\n * 'redirect'`, which refuses to run without it rather than deriving one. It\n * never reads `checkoutId`, `totals`, `status` or `expiresAt`.\n *\n * Asking for a whole `CheckoutResult` therefore asked for four fields it does\n * not use, which shut out the caller that has no CheckoutResult to give: an\n * offer is created server-side and its API answers with `embed_url` +\n * `embed_origin`, no cart and no totals in sight. Integrators were left\n * inventing a `checkoutId` to satisfy a type, or hand-rolling the postMessage\n * handshake the SDK exists to own.\n *\n * `mountCheckout` accepts `CheckoutResult | MountableCheckout` rather than this\n * type alone, and the union is load-bearing: TypeScript excess-property-checks\n * an object LITERAL against its parameter type, so narrowing the parameter to\n * this interface would have rejected the seven-field literal integrators write\n * inline today — a compile break dressed up as a widening. Keeping\n * `CheckoutResult` in the union gives that literal an arm to match.\n */\nexport interface MountableCheckout {\n readonly embedCheckoutUrl: string\n /** Required: `mountCheckout` refuses to mount without it. */\n readonly embedOrigin: string\n /** Required only by `fallback: 'redirect'`; for an offer, pass `public_url`. */\n readonly checkoutUrl?: string\n}\n\nexport interface CheckoutResult {\n readonly checkoutId: string\n readonly checkoutUrl: string\n readonly embedCheckoutUrl: string\n readonly embedOrigin?: string\n readonly status: CheckoutStatus\n readonly expiresAt: string\n readonly totals: CartTotals\n}\n\nexport interface PrefilledCheckoutLineInput {\n readonly productId: string\n /** Optional payment plan ID. Omit it to let the API select the product's default plan. */\n readonly planId?: number\n readonly quantity?: number\n}\n\ninterface PrefilledCheckoutBaseInput {\n /**\n * Stable caller-side reference, e.g. an event sales session ID. The SDK uses\n * it for the backend Idempotency-Key and stores it as cart metadata. Distinct\n * references always get distinct keys: up to 120 characters of\n * `[A-Za-z0-9._:-]` are used as is, anything else is SHA-256'd whole. A replay\n * returns the stored handoff only for the cart API's 24-hour idempotency TTL;\n * after that the same reference creates a new cart and checkout.\n */\n readonly externalReference: string\n readonly currency: string\n readonly locale?: string\n readonly attribution?: CartAttribution\n /**\n * Non-sensitive reconciliation metadata. `external_reference` and\n * `intended_payment_method` are reserved metadata keys populated from the\n * matching top-level SDK fields.\n */\n readonly metadata?: CartMetadata\n readonly intendedPaymentMethod?: string\n readonly buyerIdentity: UpdateBuyerIdentityPayload\n readonly checkout: CheckoutPayload\n}\n\nexport type PrefilledCheckoutInput = PrefilledCheckoutBaseInput & (\n | {\n readonly line: PrefilledCheckoutLineInput\n readonly lines?: never\n }\n | {\n readonly line?: never\n readonly lines: readonly [PrefilledCheckoutLineInput, ...PrefilledCheckoutLineInput[]]\n }\n)\n\nexport interface PrefilledCheckoutResult {\n /**\n * Cart ID for logging and reconciliation only. The prefilled handoff response\n * intentionally excludes `cart_secret`, so this SDK instance cannot use this\n * cart ID for follow-up mutations such as `addLine`, `reprice`, or `checkout`.\n */\n readonly cartId: string\n readonly cartVersion: number\n readonly checkoutId: string\n readonly checkoutToken: string\n readonly checkoutUrl: string\n readonly embedCheckoutUrl: string\n readonly embedOrigin?: string\n readonly status: CheckoutStatus\n readonly expiresAt: string\n readonly totals: CartTotals\n readonly intendedPaymentMethod?: string\n}\n\n// ---------------------------------------------------------------------------\n// Checkout embed postMessage protocol — consumer half of a two-package contract\n// ---------------------------------------------------------------------------\n//\n// The producer is the hosted checkout embed bridge\n// (`apps/frontend/lib/checkout/embed-protocol.ts` +\n// `apps/frontend/app/checkout/embed/[token]/HostedCheckoutEmbedBridge.tsx`).\n// A status the bridge emits but this list omits is silently dropped by\n// `parseCheckoutEmbedEvent` — the parent frame then sees nothing at all, not\n// even an error. The two lists are asserted equal by\n// `tests/checkout-embed-protocol-contract.test.ts` (and by its mirror in the\n// frontend suite, so either package's CI lane catches a divergence).\n//\n// Do not add a value here without adding a producer on the bridge side, and do\n// not add one there without adding it here.\n\nexport const CHECKOUT_EMBED_ERROR_CODES = [\n 'not_found',\n 'load_failed',\n 'embed_not_allowed',\n 'confirm_failed',\n] as const\n\nexport type CheckoutEmbedErrorCode = (typeof CHECKOUT_EMBED_ERROR_CODES)[number]\nexport type CheckoutEmbedFallbackMode = 'redirect' | 'error'\n\n/**\n * Terminal states the mounted checkout can report.\n *\n * - `completed` — the order was placed in this session (live payment success).\n * - `already_completed` — the token resolved to a checkout that was paid\n * *before* this iframe mounted (refresh after success, bookmark, re-opened\n * offer link). The parent must not re-run fulfilment, so it does NOT fire\n * `onSuccess`.\n * - `processing` — an asynchronous rail (Klarna/iDEAL/BNPL/SEPA) accepted the\n * payment but Cart's authoritative order state is still `processing`. Not a\n * success: the parent should wait for its own server-side signal.\n * - `expired` / `cancelled` — the checkout or its offer is no longer payable.\n */\nexport const CHECKOUT_EMBED_TERMINAL_STATUSES = [\n 'expired',\n 'completed',\n 'already_completed',\n 'cancelled',\n 'processing',\n] as const\n\nexport type CheckoutEmbedTerminalStatus = (typeof CHECKOUT_EMBED_TERMINAL_STATUSES)[number]\n\nexport interface CheckoutEmbedErrorPayload {\n readonly code: CheckoutEmbedErrorCode\n readonly retryable: boolean\n}\n\nexport interface CheckoutEmbedTerminalPayload {\n readonly status: CheckoutEmbedTerminalStatus\n}\n\nexport interface CheckoutEmbedResizePayload {\n readonly height: number\n}\n\nexport interface CheckoutEmbedEventMetadata {\n readonly messageId?: string\n readonly timestamp?: string\n}\n\n// ---------------------------------------------------------------------------\n// Post-Purchase Offer (OTO) — native post-purchase upsell/downsell flow\n// ---------------------------------------------------------------------------\n//\n// These types mirror the backend post-purchase offer/decision contract for\n// typed consumption by SDK integrators. The SDK never fetches OTO state\n// directly — it only relays sanitized lifecycle events emitted by the\n// mounted checkout iframe (see `post_purchase_offer` / `post_purchase_decision`\n// / `post_purchase_terminal` in CheckoutEmbedEvent below). `offerRef` is an\n// opaque reference — no product/plan identifiers, checkout tokens, cart\n// secrets, payment client secrets, or buyer PII are ever included. The 3DS\n// step-up authentication for an accepted offer happens entirely inside the\n// COPE-owned iframe; the parent only ever learns `requires_action` as a status.\n\nexport type PostPurchaseOfferStepKind = 'upsell' | 'downsell'\n\n/**\n * Buyer's response to a presented offer. `requires_action` means a 3DS\n * step-up is in progress inside the COPE iframe — the payment client secret\n * never leaves that surface.\n */\nexport type PostPurchaseDecisionStatus = 'accepted' | 'declined' | 'failed_not_charged' | 'requires_action'\n\n/** Payment outcome for an accepted offer, tracked separately from the buyer-facing decision status. */\nexport type PostPurchaseChargeStatus = 'not_charged' | 'charged' | 'requires_action' | 'failed'\n\n/** Final state of the overall post-purchase offer flow. */\nexport type PostPurchaseTerminalStatus = 'completed' | 'declined' | 'expired' | 'unavailable'\n\n/** Sanitized offer display fields — no product/plan IDs, only an opaque `offerRef`. */\nexport interface PostPurchaseOffer {\n readonly offerRef: string\n readonly stepKind: PostPurchaseOfferStepKind\n readonly title: string\n readonly priceGrossMinorUnits: number\n readonly currency: string\n}\n\n/** Sanitized decision outcome for a single offer. */\nexport interface PostPurchaseOutcome {\n readonly offerRef: string\n readonly status: PostPurchaseDecisionStatus\n readonly chargeStatus: PostPurchaseChargeStatus\n}\n\nexport type PostPurchaseOfferPayload = PostPurchaseOffer\nexport type PostPurchaseDecisionPayload = PostPurchaseOutcome\n\nexport interface PostPurchaseTerminalPayload {\n readonly status: PostPurchaseTerminalStatus\n}\n\nexport type CheckoutEmbedEvent =\n | ({ readonly type: 'ready' } & CheckoutEmbedEventMetadata)\n | ({ readonly type: 'error'; readonly payload: CheckoutEmbedErrorPayload } & CheckoutEmbedEventMetadata)\n | ({ readonly type: 'terminal'; readonly payload: CheckoutEmbedTerminalPayload } & CheckoutEmbedEventMetadata)\n | ({ readonly type: 'resize'; readonly payload: CheckoutEmbedResizePayload } & CheckoutEmbedEventMetadata)\n | ({ readonly type: 'post_purchase_offer'; readonly payload: PostPurchaseOfferPayload } & CheckoutEmbedEventMetadata)\n | ({ readonly type: 'post_purchase_decision'; readonly payload: PostPurchaseDecisionPayload } & CheckoutEmbedEventMetadata)\n | ({ readonly type: 'post_purchase_terminal'; readonly payload: PostPurchaseTerminalPayload } & CheckoutEmbedEventMetadata)\n\nexport interface CheckoutMountMessage {\n readonly type: 'copecart.checkout.mount'\n readonly version: 1\n readonly token: string\n}\n\nexport interface MountCheckoutOptions {\n readonly target: HTMLElement | string\n readonly title?: string\n readonly className?: string\n /**\n * What to do when the iframe never completes the trusted ready handshake.\n * Defaults to `error`; set `redirect` for a buyer-safe hosted checkout fallback.\n */\n readonly fallback?: CheckoutEmbedFallbackMode\n readonly readyTimeoutMs?: number\n /**\n * Called after a trusted `cope.checkout` ready message from the mounted checkout iframe.\n * `mountCheckout()` intentionally does not expose checkout tokens, cart secrets,\n * payment client secrets, or buyer PII through any callback payload.\n */\n readonly onReady?: () => void\n readonly onResize?: (payload: CheckoutEmbedResizePayload) => void\n readonly onError?: (payload: CheckoutEmbedErrorPayload) => void\n readonly onTerminal?: (payload: CheckoutEmbedTerminalPayload) => void\n readonly onSuccess?: () => void\n readonly onCancel?: () => void\n readonly onFallbackRedirect?: () => void\n /**\n * Called when the mounted checkout iframe presents a post-purchase offer\n * (native OTO upsell/downsell). The payload is sanitized: display fields\n * and an opaque `offerRef` only — never a product/plan ID, checkout token,\n * cart secret, payment client secret, or buyer PII.\n */\n readonly onPostPurchaseOffer?: (payload: PostPurchaseOfferPayload) => void\n /**\n * Called when the buyer decides on a post-purchase offer. `requires_action`\n * means a 3DS step-up is happening inside the COPE iframe — the payment\n * client secret is never forwarded here.\n */\n readonly onPostPurchaseDecision?: (payload: PostPurchaseDecisionPayload) => void\n /** Called when the overall post-purchase offer flow reaches a final state. */\n readonly onPostPurchaseTerminal?: (payload: PostPurchaseTerminalPayload) => void\n readonly onMessage?: (event: CheckoutEmbedEvent) => void\n}\n\nexport type MountCheckoutCallbacks = Omit<MountCheckoutOptions, 'target'>\n\nexport interface MountedCheckout {\n /**\n * Hosted checkout iframe. The SDK sets `allow=\"payment *\"` and\n * `referrerPolicy=\"no-referrer\"`.\n *\n * The SDK intentionally omits a `sandbox` attribute: no sandbox token set has\n * been proven compatible with all required wallet, redirect, and payment\n * provider flows yet. Embedding is instead constrained by the registered\n * `embed_origin` contract plus strict postMessage origin/source checks.\n */\n readonly iframe: HTMLIFrameElement\n destroy(): void\n}\n","import type {\n AddLinePayload,\n Cart,\n CheckoutCreateResponse,\n CheckoutEmbedErrorCode,\n CheckoutEmbedEvent,\n CheckoutEmbedTerminalPayload,\n CheckoutMountMessage,\n CheckoutPayload,\n CheckoutOptions,\n CheckoutResult,\n CopeCartOptions,\n CreateCartPayload,\n MountedCheckout,\n MountCheckoutCallbacks,\n MountCheckoutOptions,\n MountableCheckout,\n OneClickChargeConsentApplicability,\n PostPurchaseChargeStatus,\n PostPurchaseDecisionStatus,\n PostPurchaseOfferStepKind,\n PostPurchaseTerminalStatus,\n PrefilledCheckoutInput,\n PrefilledCheckoutLineInput,\n PrefilledCheckoutResult,\n SdkProduct,\n UpdateBuyerIdentityPayload,\n UpdateLinePayload,\n} from './types.js'\nimport {\n CHECKOUT_EMBED_ERROR_CODES,\n CHECKOUT_EMBED_TERMINAL_STATUSES,\n CopeApiError,\n CopeCartExpiredError,\n CopeError,\n CopeNetworkError,\n} from './types.js'\nimport type { CartState } from './types.js'\n\nconst TERMINAL_STATES: ReadonlySet<CartState> = new Set(['ordered', 'expired', 'abandoned', 'merged'])\n// The app host: requests go to `${baseUrl}/api/cart/v1/...`, which cope-edge's\n// checkout block serves there, and the hosted checkout's origin (derived from\n// this URL when checkoutBaseUrl is unset) is the same host.\nconst DEFAULT_BASE_URL = 'https://app.cope.com'\nconst STORAGE_KEY = 'cope_sdk_cart'\nconst REQUEST_TIMEOUT_MS = 8_000\nconst RETRY_INITIAL_DELAY_MS = 500\nconst RETRY_MAX_DELAY_MS = 5_000\nconst CHECKOUT_MESSAGE_SOURCE = 'cope.checkout'\nconst CHECKOUT_MESSAGE_VERSION = 1\nconst CHECKOUT_MOUNT_MESSAGE_TYPE = 'copecart.checkout.mount'\nconst CHECKOUT_MOUNT_MESSAGE_VERSION = 1\nconst CHECKOUT_MOUNT_RETRY_INTERVAL_MS = 250\nconst CHECKOUT_MOUNT_MAX_ATTEMPTS = 20\nconst CHECKOUT_READY_TIMEOUT_MS = 8_000\nconst SUPPORTED_ONE_CLICK_CHARGE_TERMS_VERSIONS: ReadonlySet<string> = new Set(['oto-v1'])\n\ntype HttpMethod = 'GET' | 'POST' | 'PATCH' | 'DELETE'\ntype MountCleanup = () => void\ntype RequestOptions = {\n readonly skipAuth?: boolean\n readonly idempotencyKey?: string\n}\ntype PrefilledCheckoutCreateResponse = CheckoutCreateResponse & {\n readonly cart_id: string\n readonly checkout_token?: string\n}\n\n// One path segment. Ids arrive from callers (and, through cope-sdk/mcp, from AI\n// agents); unencoded, `../buyer-identity` or a `?` would aim a request carrying\n// the cart secret at another route.\nfunction seg(id: string): string {\n return encodeURIComponent(id)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\ntype ApiErrorEntry = { code: string; message: string; field?: string }\n\n// The normalized origin of a URL that is nothing but an origin — no path, query,\n// fragment or credentials — or null. `https://App.Cope.com:443/` is accepted and\n// becomes `https://app.cope.com`.\nfunction originOnly(value: string): string | null {\n try {\n const url = new URL(value)\n const bare = url.pathname === '/' && !url.search && !url.hash && !url.username && !url.password\n return bare ? url.origin : null\n } catch {\n return null\n }\n}\n\nconst EDGE_ERROR_MESSAGES: Readonly<Record<string, string>> = {\n payload_too_large: 'Request body is too large',\n rate_limited: 'Too many requests',\n upstream_unavailable: 'The checkout service is unavailable',\n gateway_timeout: 'The checkout service did not answer in time',\n not_found: 'Not found',\n}\n\n// Two envelopes reach the SDK: cope-core's `{errors: [{code, message}]}`, and\n// the `{error: \"<code>\", request_id}` cope-edge answers itself on the checkout\n// block — rate limit, body cap, unreachable upstream, deadline\n// (svcs/cope-edge/docs/errors.md). Plan 30 W2-47.\nfunction parseErrorBody(body: unknown): ApiErrorEntry[] | null {\n if (!isRecord(body)) return null\n if (Array.isArray(body.errors) && body.errors.length > 0 && body.errors.every(isApiErrorEntry)) return body.errors\n if (typeof body.error === 'string' && body.error.length > 0) {\n // Edge's `error` is a snake_case code; anything else is prose some other\n // upstream put there, which must not masquerade as a code callers switch on.\n return /^[a-z][a-z0-9_]*$/.test(body.error)\n ? [{ code: body.error, message: EDGE_ERROR_MESSAGES[body.error] ?? body.error }]\n : [{ code: 'unknown', message: body.error }]\n }\n return null\n}\n\nfunction isApiErrorEntry(value: unknown): value is ApiErrorEntry {\n return isRecord(value) && typeof value.code === 'string' && typeof value.message === 'string'\n}\n\n// `Retry-After` is either delta-seconds or an HTTP-date (RFC 9110 §10.2.3).\nfunction parseRetryAfter(value: string | null): number | null {\n if (value === null || value.trim() === '') return null\n if (/^\\d+$/.test(value.trim())) return Number(value.trim())\n const at = Date.parse(value)\n return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - Date.now()) / 1000))\n}\n\nfunction bodyRequestId(body: unknown): string | null {\n return isRecord(body) && typeof body.request_id === 'string' ? body.request_id : null\n}\n\nfunction normalizeOneClickChargeConsent(value: unknown): OneClickChargeConsentApplicability {\n if (!isRecord(value)) {\n return { applicable: false, terms_version: null }\n }\n\n const termsVersion = value.terms_version\n if (\n value.applicable !== true\n || typeof termsVersion !== 'string'\n || !SUPPORTED_ONE_CLICK_CHARGE_TERMS_VERSIONS.has(termsVersion)\n ) {\n return { applicable: false, terms_version: null }\n }\n\n return { applicable: true, terms_version: termsVersion }\n}\n\nfunction normalizeCart(cart: Cart): Cart {\n return {\n ...cart,\n one_click_charge_consent: normalizeOneClickChargeConsent(cart.one_click_charge_consent),\n }\n}\n\n// Both guards read the exported protocol lists rather than repeating the\n// union: a second hand-maintained copy is exactly how `already_completed`\n// came to be emitted by the bridge and dropped here.\nconst CHECKOUT_EMBED_ERROR_CODE_SET: ReadonlySet<string> = new Set(CHECKOUT_EMBED_ERROR_CODES)\nconst CHECKOUT_EMBED_TERMINAL_STATUS_SET: ReadonlySet<string> = new Set(CHECKOUT_EMBED_TERMINAL_STATUSES)\n\nfunction isCheckoutEmbedErrorCode(value: string): value is CheckoutEmbedErrorCode {\n return CHECKOUT_EMBED_ERROR_CODE_SET.has(value)\n}\n\nfunction isCheckoutEmbedTerminalStatus(value: string): value is CheckoutEmbedTerminalPayload['status'] {\n return CHECKOUT_EMBED_TERMINAL_STATUS_SET.has(value)\n}\n\nfunction isPostPurchaseOfferStepKind(value: string): value is PostPurchaseOfferStepKind {\n return value === 'upsell' || value === 'downsell'\n}\n\nfunction isPostPurchaseDecisionStatus(value: string): value is PostPurchaseDecisionStatus {\n return (\n value === 'accepted'\n || value === 'declined'\n || value === 'failed_not_charged'\n || value === 'requires_action'\n )\n}\n\nfunction isPostPurchaseChargeStatus(value: string): value is PostPurchaseChargeStatus {\n return (\n value === 'not_charged'\n || value === 'charged'\n || value === 'requires_action'\n || value === 'failed'\n )\n}\n\nfunction isPostPurchaseTerminalStatus(value: string): value is PostPurchaseTerminalStatus {\n return (\n value === 'completed'\n || value === 'declined'\n || value === 'expired'\n || value === 'unavailable'\n )\n}\n\nfunction currentWindowOrigin(): string {\n const location = window.location\n if (location.origin) return location.origin\n\n const host = location.host || [location.hostname, location.port].filter(Boolean).join(':')\n return new URL(`${location.protocol}//${host}`).origin\n}\n\nfunction normalizeCheckoutUrls(absoluteUrl: string): { checkoutUrl: string; embedCheckoutUrl: string } {\n const checkoutUrl = new URL(absoluteUrl)\n const embedCheckoutUrl = new URL(absoluteUrl)\n const embedMatch = checkoutUrl.pathname.match(/^\\/checkout\\/embed\\/([^/]+)$/)\n const checkoutMatch = checkoutUrl.pathname.match(/^\\/checkout\\/([^/]+)$/)\n\n if (embedMatch) {\n checkoutUrl.pathname = `/checkout/${embedMatch[1]}`\n embedCheckoutUrl.pathname = `/checkout/embed/${embedMatch[1]}`\n return {\n checkoutUrl: checkoutUrl.toString(),\n embedCheckoutUrl: embedCheckoutUrl.toString(),\n }\n }\n\n if (checkoutMatch) {\n checkoutUrl.pathname = `/checkout/${checkoutMatch[1]}`\n embedCheckoutUrl.pathname = `/checkout/embed/${checkoutMatch[1]}`\n return {\n checkoutUrl: checkoutUrl.toString(),\n embedCheckoutUrl: embedCheckoutUrl.toString(),\n }\n }\n\n throw new CopeError('Checkout URL path cannot be mapped to COPE checkout routes')\n}\n\nfunction checkoutEmbedToken(embedCheckoutUrl: string): string {\n const url = new URL(embedCheckoutUrl)\n const match = url.pathname.match(/^\\/checkout\\/embed\\/([^/]+)$/)\n if (!match) {\n throw new CopeError('Checkout embed URL path cannot be mapped to COPE checkout embed route')\n }\n\n return decodeURIComponent(match[1])\n}\n\nfunction checkoutEmbedOrigin(raw: CheckoutCreateResponse): string | undefined {\n const embed = raw.embed\n if (!isRecord(embed)) return undefined\n if (embed.allowed !== true) return undefined\n if (typeof embed.parent_origin !== 'string') return undefined\n\n try {\n const origin = new URL(embed.parent_origin).origin\n return origin === embed.parent_origin ? embed.parent_origin : undefined\n } catch {\n return undefined\n }\n}\n\nfunction parseCheckoutEmbedEvent(data: unknown): CheckoutEmbedEvent | null {\n if (!isRecord(data)) return null\n if (data.source !== CHECKOUT_MESSAGE_SOURCE) return null\n if (data.version !== CHECKOUT_MESSAGE_VERSION) return null\n\n const metadata = {\n ...(typeof data.messageId === 'string' ? { messageId: data.messageId } : {}),\n ...(typeof data.timestamp === 'string' ? { timestamp: data.timestamp } : {}),\n }\n\n if (data.type === 'ready') {\n return { type: 'ready', ...metadata }\n }\n\n if (data.type === 'resize') {\n if (!isRecord(data.payload)) return null\n const { height } = data.payload\n if (typeof height !== 'number' || !Number.isFinite(height) || height <= 0) return null\n return {\n type: 'resize',\n payload: { height: Math.ceil(height) },\n ...metadata,\n }\n }\n\n if (data.type === 'error') {\n if (!isRecord(data.payload)) return null\n const { code, retryable } = data.payload\n if (typeof code !== 'string' || !isCheckoutEmbedErrorCode(code)) return null\n if (typeof retryable !== 'boolean') return null\n return {\n type: 'error',\n payload: { code, retryable },\n ...metadata,\n }\n }\n\n if (data.type === 'terminal') {\n if (!isRecord(data.payload)) return null\n const { status } = data.payload\n if (typeof status !== 'string' || !isCheckoutEmbedTerminalStatus(status)) return null\n return {\n type: 'terminal',\n payload: { status },\n ...metadata,\n }\n }\n\n // Only recognized fields are ever read off `data.payload` below — this is what\n // keeps the sanitization guarantee: any extra keys the iframe message might\n // carry (token, cart_secret, client_secret, email, ...) are never copied into\n // the object handed to callbacks.\n if (data.type === 'post_purchase_offer') {\n if (!isRecord(data.payload)) return null\n const { offerRef, stepKind, title, priceGrossMinorUnits, currency } = data.payload\n if (typeof offerRef !== 'string' || !offerRef) return null\n if (typeof stepKind !== 'string' || !isPostPurchaseOfferStepKind(stepKind)) return null\n if (typeof title !== 'string' || !title) return null\n if (typeof priceGrossMinorUnits !== 'number' || !Number.isFinite(priceGrossMinorUnits) || priceGrossMinorUnits < 0) return null\n if (typeof currency !== 'string' || !currency) return null\n return {\n type: 'post_purchase_offer',\n payload: { offerRef, stepKind, title, priceGrossMinorUnits, currency },\n ...metadata,\n }\n }\n\n if (data.type === 'post_purchase_decision') {\n if (!isRecord(data.payload)) return null\n const { offerRef, status, chargeStatus } = data.payload\n if (typeof offerRef !== 'string' || !offerRef) return null\n if (typeof status !== 'string' || !isPostPurchaseDecisionStatus(status)) return null\n if (typeof chargeStatus !== 'string' || !isPostPurchaseChargeStatus(chargeStatus)) return null\n return {\n type: 'post_purchase_decision',\n payload: { offerRef, status, chargeStatus },\n ...metadata,\n }\n }\n\n if (data.type === 'post_purchase_terminal') {\n if (!isRecord(data.payload)) return null\n const { status } = data.payload\n if (typeof status !== 'string' || !isPostPurchaseTerminalStatus(status)) return null\n return {\n type: 'post_purchase_terminal',\n payload: { status },\n ...metadata,\n }\n }\n\n return null\n}\n\n/**\n * COPE SDK — browser client for the checkout API cope-edge serves under `/api/cart/v1`.\n *\n * Usage:\n * ```ts\n * const cope = new CopeCart({ publishableKey: 'cope_pk_...' })\n * const cart = await cope.createCart({ currency: 'EUR' })\n * await cope.addLine(cart.id, { product_id: 'uuid-123' })\n * await cope.reprice(cart.id)\n * const checkout = await cope.checkout(cart.id, { success_url: '...', cancel_url: '...', consents: [{ type: 'buyer_tos' }] })\n * cope.redirectToCheckout(checkout)\n * ```\n */\nexport class CopeCart {\n private readonly publishableKey: string\n private readonly baseUrl: string\n private readonly checkoutBaseUrl: string\n private readonly persistence: 'localStorage' | 'none'\n private readonly abortController: AbortController\n private readonly mountCleanups = new Set<MountCleanup>()\n private cachedSecret: string | null = null\n private cachedCartId: string | null = null\n\n /** The active cart ID from localStorage, or null if no cart exists. */\n get currentCartId(): string | null {\n return this.cachedCartId\n }\n\n constructor(options: CopeCartOptions) {\n if (!options.publishableKey?.startsWith('cope_pk_')) {\n throw new CopeError('Invalid publishableKey. Must start with \"cope_pk_\".')\n }\n\n if (typeof window !== 'undefined' && window.location?.protocol === 'http:' && window.location.hostname !== 'localhost') {\n throw new CopeError('CopeCart SDK requires HTTPS. Refusing to operate on an insecure page.')\n }\n\n this.publishableKey = options.publishableKey\n // An origin only. @copecart/sdk's docs told integrators to pass\n // `.../gateway/cart_api`; carried over, it would 404 on every call rather\n // than fail here where the cause is visible.\n const baseOrigin = originOnly(options.baseUrl ?? DEFAULT_BASE_URL)\n if (baseOrigin === null) {\n throw new CopeError('Invalid baseUrl. Pass an origin such as \"https://app.cope.com\"; the SDK adds /api/cart/v1 itself.')\n }\n this.baseUrl = baseOrigin\n this.checkoutBaseUrl = options.checkoutBaseUrl\n ? options.checkoutBaseUrl.replace(/\\/+$/, '')\n : new URL(this.baseUrl).origin\n this.abortController = new AbortController()\n // A client handed a cart acts on that cart only: it must not read, overwrite or\n // clear the page's stored cart, which belongs to whichever client created it.\n this.persistence = options.cart ? 'none' : (options.persistence ?? 'localStorage')\n\n if (options.cart) {\n this.cachedCartId = options.cart.id\n this.cachedSecret = options.cart.secret\n } else {\n this.hydrateFromStorage()\n }\n }\n\n // ---------------------------------------------------------------------------\n // Public API\n // ---------------------------------------------------------------------------\n\n async createCart(payload: CreateCartPayload): Promise<Cart> {\n return this.createCartRequest(payload, { skipAuth: true })\n }\n\n async getProduct(productUuid: string): Promise<SdkProduct> {\n return this.get<SdkProduct>(`/products/${seg(productUuid)}`, { skipAuth: true })\n }\n\n async getCart(cartId: string): Promise<Cart> {\n const cart = normalizeCart(await this.get<Cart>(`/carts/${seg(cartId)}`))\n if (TERMINAL_STATES.has(cart.state)) {\n this.clearStorage()\n throw new CopeCartExpiredError(cart.state)\n }\n return cart\n }\n\n async addLine(cartId: string, payload: AddLinePayload): Promise<Cart> {\n return normalizeCart(await this.post<Cart>(`/carts/${seg(cartId)}/lines`, payload))\n }\n\n async updateLine(cartId: string, lineId: string, payload: UpdateLinePayload): Promise<Cart> {\n return normalizeCart(await this.patch<Cart>(`/carts/${seg(cartId)}/lines/${seg(lineId)}`, payload))\n }\n\n async removeLine(cartId: string, lineId: string): Promise<Cart> {\n return normalizeCart(await this.del<Cart>(`/carts/${seg(cartId)}/lines/${seg(lineId)}`))\n }\n\n async setBuyerIdentity(cartId: string, payload: UpdateBuyerIdentityPayload): Promise<Cart> {\n return normalizeCart(await this.patch<Cart>(`/carts/${seg(cartId)}/buyer-identity`, payload))\n }\n\n async reprice(cartId: string): Promise<Cart> {\n return normalizeCart(await this.post<Cart>(`/carts/${seg(cartId)}/reprice`, {}))\n }\n\n async applyPromoCode(cartId: string, code: string): Promise<Cart> {\n return normalizeCart(await this.post<Cart>(`/carts/${seg(cartId)}/promo_code`, { code }))\n }\n\n async removePromoCode(cartId: string): Promise<Cart> {\n return normalizeCart(await this.del<Cart>(`/carts/${seg(cartId)}/promo_code`))\n }\n\n async checkout(cartId: string, payload: CheckoutPayload, options: CheckoutOptions = {}): Promise<CheckoutResult> {\n return this.createCheckoutResult(cartId, payload,\n options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : undefined)\n }\n\n async createPrefilledCheckout(input: PrefilledCheckoutInput): Promise<PrefilledCheckoutResult> {\n const lines = this.normalizePrefilledLines(input)\n const raw = await this.post<PrefilledCheckoutCreateResponse>('/prefilled-checkouts', {\n external_reference: input.externalReference,\n currency: input.currency,\n ...(input.locale != null ? { locale: input.locale } : {}),\n ...(input.attribution ? { attribution: input.attribution } : {}),\n ...(input.intendedPaymentMethod != null ? { intended_payment_method: input.intendedPaymentMethod } : {}),\n ...(input.metadata ? { metadata: input.metadata } : {}),\n lines: lines.map((line) => ({\n product_id: line.productId,\n ...(line.planId !== undefined ? { plan_id: line.planId } : {}),\n ...(line.quantity !== undefined ? { quantity: line.quantity } : {}),\n })),\n buyer_identity: input.buyerIdentity,\n checkout: input.checkout,\n }, {\n skipAuth: true,\n idempotencyKey: await this.prefilledIdempotencyKey(input.externalReference),\n })\n const checkout = this.normalizeCheckoutResult(raw)\n\n return {\n cartId: raw.cart_id,\n cartVersion: raw.cart_version,\n checkoutId: checkout.checkoutId,\n checkoutToken: raw.checkout_token ?? checkoutEmbedToken(checkout.embedCheckoutUrl),\n checkoutUrl: checkout.checkoutUrl,\n embedCheckoutUrl: checkout.embedCheckoutUrl,\n ...(checkout.embedOrigin ? { embedOrigin: checkout.embedOrigin } : {}),\n status: checkout.status,\n expiresAt: checkout.expiresAt,\n totals: checkout.totals,\n ...(input.intendedPaymentMethod != null ? { intendedPaymentMethod: input.intendedPaymentMethod } : {}),\n }\n }\n\n async cancelCheckout(checkoutId: string): Promise<void> {\n await this.requestVoid('POST', `/checkouts/${seg(checkoutId)}/cancel`)\n }\n\n redirectToCheckout(checkout: CheckoutResult): void {\n if (this.abortController.signal.aborted) return\n if (typeof window !== 'undefined') {\n window.location.href = checkout.checkoutUrl\n }\n }\n\n mountCheckout(checkout: CheckoutResult | MountableCheckout, options: MountCheckoutOptions): MountedCheckout\n mountCheckout(target: HTMLElement | string, checkout: CheckoutResult | MountableCheckout, options?: MountCheckoutCallbacks): MountedCheckout\n mountCheckout(\n checkoutOrTarget: CheckoutResult | MountableCheckout | HTMLElement | string,\n optionsOrCheckout: MountCheckoutOptions | CheckoutResult | MountableCheckout,\n maybeOptions: MountCheckoutCallbacks = {},\n ): MountedCheckout {\n if (this.abortController.signal.aborted) {\n throw new CopeError('SDK destroyed')\n }\n\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n throw new CopeError('mountCheckout requires a browser environment')\n }\n\n const { checkout, options } = this.normalizeMountCheckoutArgs(\n checkoutOrTarget,\n optionsOrCheckout,\n maybeOptions,\n )\n // Validation first: every check below reads caller-supplied input, and until\n // this method accepted a bare embed URL that input was origin-proven by\n // construction — it could only have come from normalizeCheckoutResult, which\n // refuses a foreign origin. Accepting `embed_url` straight out of an API\n // response removes that proof, so the two URLs are re-checked here before any\n // DOM is touched or any token is parsed.\n const allowedOrigin = this.checkoutOrigin()\n this.assertCopeOrigin(checkout.embedCheckoutUrl, allowedOrigin, 'Checkout embed URL')\n\n if (!checkout.embedOrigin) {\n throw new CopeError(\n 'mountCheckout requires checkout.embedOrigin — send embed_origin on checkout() or on '\n + 'create-offer, and register the origin in dashboard Settings',\n )\n }\n\n // The `checkoutUrl` sink is strictly worse than the frame's: `fallback:\n // 'redirect'` navigates the buyer's TOP window, so an unvalidated value would\n // hand the whole page to another origin mid-checkout.\n //\n // It is also deliberately NOT derived from the embed URL. For an offer the\n // recovery page is `public_url` (/offers/:uuid), which renders the offer's\n // state; the hosted checkout route would refuse in exactly the cases the\n // fallback exists for, and it carries the payment-capable access token into the\n // address bar and browser history. Refuse at mount rather than at the buyer's\n // eight-second timeout, so this is an integration error, never a runtime one.\n let fallbackUrl: string | undefined\n if (options.fallback === 'redirect') {\n if (!checkout.checkoutUrl) {\n throw new CopeError(\n \"mountCheckout with fallback: 'redirect' requires checkout.checkoutUrl — for an offer, \"\n + 'pass its public_url',\n )\n }\n this.assertCopeOrigin(checkout.checkoutUrl, allowedOrigin, 'Checkout URL')\n fallbackUrl = checkout.checkoutUrl\n }\n\n const target = this.resolveMountTarget(options.target)\n const iframe = document.createElement('iframe')\n const checkoutOrigin = new URL(checkout.embedCheckoutUrl).origin\n const mountMessage: CheckoutMountMessage = {\n type: CHECKOUT_MOUNT_MESSAGE_TYPE,\n version: CHECKOUT_MOUNT_MESSAGE_VERSION,\n token: checkoutEmbedToken(checkout.embedCheckoutUrl),\n }\n const parentOrigin = currentWindowOrigin()\n let destroyed = false\n let ready = false\n let mountAttempts = 0\n // The DOM timer id. Not ReturnType<typeof window.setInterval>: that picks\n // the last overload, which is Node's Timeout once @types/node is loaded.\n let mountRetry: number | undefined\n let readyTimeout: number | undefined\n\n if (checkout.embedOrigin !== parentOrigin) {\n throw new CopeError(`Checkout embed origin ${checkout.embedOrigin} does not match current origin ${parentOrigin}`)\n }\n\n iframe.src = checkout.embedCheckoutUrl\n iframe.title = options.title ?? 'COPE checkout'\n iframe.setAttribute('allow', 'payment *')\n iframe.referrerPolicy = 'no-referrer'\n iframe.style.border = '0'\n iframe.style.width = '100%'\n iframe.style.minHeight = '720px'\n if (options.className) {\n iframe.className = options.className\n }\n\n const clearMountRetry = () => {\n if (mountRetry !== undefined) {\n window.clearInterval(mountRetry)\n mountRetry = undefined\n }\n }\n\n const clearReadyTimeout = () => {\n if (readyTimeout !== undefined) {\n window.clearTimeout(readyTimeout)\n readyTimeout = undefined\n }\n }\n\n const cleanup = () => {\n if (destroyed) return\n destroyed = true\n clearMountRetry()\n clearReadyTimeout()\n window.removeEventListener('message', handleMessage)\n iframe.removeEventListener('load', handleIframeLoad)\n iframe.remove()\n this.mountCleanups.delete(cleanup)\n }\n\n const postMountMessage = () => {\n if (destroyed || ready) return\n if (mountAttempts >= CHECKOUT_MOUNT_MAX_ATTEMPTS) {\n clearMountRetry()\n return\n }\n\n mountAttempts += 1\n iframe.contentWindow?.postMessage(mountMessage, checkoutOrigin)\n }\n\n const startMountHandshake = () => {\n if (destroyed) return\n mountAttempts = 0\n clearMountRetry()\n postMountMessage()\n mountRetry = window.setInterval(postMountMessage, CHECKOUT_MOUNT_RETRY_INTERVAL_MS)\n }\n\n /**\n * Re-arm the handshake on every completed navigation inside the frame.\n *\n * A redirect payment method (Klarna / iDEAL / other BNPL) navigates the\n * iframe away to the provider and back to `/checkout/embed/<token>`. The\n * returning document is a brand-new bridge sitting in `awaiting-mount`, and\n * it will not proceed until the parent proves it knows the token again.\n * Without this the embed hangs forever after any redirect payment.\n *\n * `load` fires on the parent for cross-origin navigations too, so this also\n * runs while the frame is on the provider's page. That is safe: the mount\n * message is posted with `targetOrigin = checkoutOrigin`, so the browser\n * drops it rather than leaking the checkout token to the provider.\n *\n * The ready timeout is deliberately NOT re-armed. It is a one-shot\n * \"the embed never loaded\" guard for the initial mount. Re-arming it would\n * fire `onError({ code: 'load_failed' })` — or, under\n * `fallback: 'redirect'`, navigate the vendor's top window away — eight\n * seconds after the buyer lands on the provider's page, mid-payment. The\n * parent cannot tell those two loads apart: a cross-origin frame exposes\n * neither its location nor whether a `postMessage` was delivered.\n *\n * So the returning document owns reporting its own failure instead: the\n * bridge posts `error` even when it blocks before it has a validated\n * policy, which is why the parent can drop the timer here without going\n * silent after a redirect payment. The one case neither side covers is a\n * return the browser refuses to render at all (the embed origin was\n * disabled while the buyer was at the provider, so the response carries\n * `frame-ancestors 'none'`): no document runs, and nothing can report.\n */\n const handleIframeLoad = () => {\n if (destroyed) return\n ready = false\n startMountHandshake()\n }\n\n const handleMessage = (event: MessageEvent<unknown>) => {\n if (destroyed) return\n if (event.origin !== checkoutOrigin) return\n if (event.source !== iframe.contentWindow) return\n\n const message = parseCheckoutEmbedEvent(event.data)\n if (!message) return\n\n options.onMessage?.(message)\n if (message.type === 'ready') {\n ready = true\n clearMountRetry()\n clearReadyTimeout()\n options.onReady?.()\n } else if (message.type === 'resize') {\n iframe.style.height = `${message.payload.height}px`\n options.onResize?.(message.payload)\n } else if (message.type === 'error') {\n // A bridge that reports an error has already accepted the handshake, so\n // there is nothing left to retry and no missing load to time out. Both\n // timers must stop here or the ready timeout still fires eight seconds\n // later with a bogus `load_failed` (or a top-window fallback redirect).\n clearMountRetry()\n clearReadyTimeout()\n options.onError?.(message.payload)\n } else if (message.type === 'terminal') {\n clearMountRetry()\n clearReadyTimeout()\n options.onTerminal?.(message.payload)\n // Only a live `completed` is a success. `already_completed` means the\n // buyer paid before this mount, so re-running vendor fulfilment would\n // double-grant; `processing` is an asynchronous rail that has not\n // settled yet.\n if (message.payload.status === 'completed') {\n options.onSuccess?.()\n } else if (message.payload.status === 'cancelled') {\n options.onCancel?.()\n }\n } else if (message.type === 'post_purchase_offer') {\n options.onPostPurchaseOffer?.(message.payload)\n } else if (message.type === 'post_purchase_decision') {\n options.onPostPurchaseDecision?.(message.payload)\n } else if (message.type === 'post_purchase_terminal') {\n options.onPostPurchaseTerminal?.(message.payload)\n }\n }\n\n window.addEventListener('message', handleMessage)\n iframe.addEventListener('load', handleIframeLoad)\n this.mountCleanups.add(cleanup)\n\n try {\n target.appendChild(iframe)\n startMountHandshake()\n readyTimeout = window.setTimeout(() => {\n if (destroyed || ready) return\n if (options.fallback === 'redirect') {\n options.onFallbackRedirect?.()\n window.location.href = fallbackUrl as string\n return\n }\n\n options.onError?.({ code: 'load_failed', retryable: true })\n }, options.readyTimeoutMs ?? CHECKOUT_READY_TIMEOUT_MS)\n } catch (error) {\n cleanup()\n throw error\n }\n\n return { iframe, destroy: cleanup }\n }\n\n destroy(): void {\n for (const cleanup of Array.from(this.mountCleanups)) {\n cleanup()\n }\n this.abortController.abort()\n this.clearStorage()\n }\n\n // ---------------------------------------------------------------------------\n // HTTP methods\n // ---------------------------------------------------------------------------\n\n private async createCartRequest(payload: CreateCartPayload, opts?: RequestOptions): Promise<Cart> {\n // POST /carts renders the cart without `lines` or `buyer_identity`\n // (apps/cope-core carts_controller.rb `create`: CartBlueprint's default view,\n // unmasked). A new cart has neither, and the payload cannot supply them.\n const created = await this.post<Cart>('/carts', payload, opts)\n const cart = normalizeCart({ ...created, lines: created.lines ?? [], buyer_identity: created.buyer_identity ?? null })\n if (cart.cart_secret) {\n this.cachedCartId = cart.id\n this.cachedSecret = cart.cart_secret\n this.persistToStorage()\n }\n return cart\n }\n\n private async createCheckoutResult(cartId: string, payload: CheckoutPayload, opts?: RequestOptions): Promise<CheckoutResult> {\n const raw = await this.post<CheckoutCreateResponse>(`/carts/${seg(cartId)}/checkout`, payload, opts)\n return this.normalizeCheckoutResult(raw)\n }\n\n private normalizeCheckoutResult(raw: CheckoutCreateResponse): CheckoutResult {\n const absoluteUrl = raw.checkout_url.startsWith('http')\n ? raw.checkout_url\n : `${this.checkoutBaseUrl}${raw.checkout_url}`\n\n // Validate redirect URL belongs to expected origin\n this.assertCopeOrigin(absoluteUrl, this.checkoutOrigin(), 'Checkout URL')\n\n const urls = normalizeCheckoutUrls(absoluteUrl)\n\n return {\n checkoutId: raw.checkout_id,\n checkoutUrl: urls.checkoutUrl,\n embedCheckoutUrl: urls.embedCheckoutUrl,\n embedOrigin: checkoutEmbedOrigin(raw),\n status: raw.status,\n expiresAt: raw.expires_at,\n totals: raw.totals,\n }\n }\n\n private async requestVoid(method: HttpMethod, path: string, body?: unknown): Promise<void> {\n await this.request<unknown>(method, path, body)\n }\n\n private async get<T>(path: string, opts?: RequestOptions): Promise<T> {\n return this.request<T>('GET', path, undefined, opts)\n }\n\n private async post<T>(path: string, body: unknown, opts?: RequestOptions): Promise<T> {\n return this.request<T>('POST', path, body, opts)\n }\n\n private async patch<T>(path: string, body: unknown): Promise<T> {\n return this.request<T>('PATCH', path, body)\n }\n\n private async del<T>(path: string): Promise<T> {\n return this.request<T>('DELETE', path)\n }\n\n private async request<T>(\n method: HttpMethod,\n path: string,\n body?: unknown,\n opts?: RequestOptions,\n ): Promise<T> {\n if (this.abortController.signal.aborted) {\n throw new CopeError('SDK destroyed')\n }\n\n const url = `${this.baseUrl}/api/cart/v1${path}`\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'X-Cope-Key': this.publishableKey,\n }\n\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json'\n }\n\n if (!opts?.skipAuth && this.cachedSecret) {\n headers['Authorization'] = `CartSecret ${this.cachedSecret}`\n }\n\n // Idempotency key for POST — same key across retries\n const idempotencyKey = method === 'POST' ? (opts?.idempotencyKey ?? crypto.randomUUID()) : undefined\n if (idempotencyKey) {\n headers['Idempotency-Key'] = idempotencyKey\n }\n\n const maxAttempts = (method === 'GET' || (method === 'POST' && this.isRetryablePath(path))) ? 2 : 1\n // A retry after an ambiguous failure (5xx, timeout, network) may re-run a write the\n // server already committed; only a GET, or a POST cope-core deduplicates by\n // Idempotency-Key, survives that. A 429 is refused before processing, so it is safe.\n const replaySafe = this.isReplaySafe(method, path)\n let lastError: unknown\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n if (attempt > 0) {\n const delay = this.calculateRetryDelay(attempt - 1)\n await this.sleep(delay)\n }\n\n const timeoutController = new AbortController()\n const timeout = setTimeout(() => timeoutController.abort(), REQUEST_TIMEOUT_MS)\n const signal = AbortSignal.any([this.abortController.signal, timeoutController.signal])\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body: body !== undefined ? JSON.stringify(body) : undefined,\n signal,\n })\n\n if (response.ok) {\n if (response.status === 204) return undefined as T\n return (await response.json()) as T\n }\n\n // Parse error body\n const errorBody: unknown = await response.json().catch(() => null)\n const errors = parseErrorBody(errorBody) ?? [{ code: 'unknown', message: response.statusText }]\n const requestId = response.headers.get('X-Request-Id') ?? bodyRequestId(errorBody)\n const retryAfter = parseRetryAfter(response.headers.get('Retry-After'))\n\n // Retry on 5xx / 429\n if (this.shouldRetry(response.status) && attempt < maxAttempts - 1 && (replaySafe || response.status === 429)) {\n lastError = new CopeApiError(response.status, errors, requestId, retryAfter)\n continue\n }\n\n throw new CopeApiError(response.status, errors, requestId, retryAfter)\n } catch (error) {\n if (error instanceof CopeApiError) throw error\n if (error instanceof CopeCartExpiredError) throw error\n\n // AbortError from SDK destroy\n if (this.abortController.signal.aborted) {\n throw new CopeError('SDK destroyed')\n }\n\n // Network or timeout error — retry only where a replay cannot duplicate a write\n if (attempt < maxAttempts - 1 && replaySafe) {\n lastError = error\n continue\n }\n\n const msg = error instanceof Error ? error.message : 'Network error'\n throw new CopeNetworkError(msg)\n } finally {\n clearTimeout(timeout)\n }\n }\n\n // Should not reach here, but just in case\n throw lastError instanceof Error ? lastError : new CopeNetworkError('Request failed')\n }\n\n private shouldRetry(status: number): boolean {\n return status === 429 || status >= 500\n }\n\n private isRetryablePath(path: string): boolean {\n return !path.includes('/checkout')\n }\n\n // The SDK POSTs cope-core's IdempotencyMiddleware deduplicates\n // (CART_POST_ROUTES, apps/cope-core/app/middleware/idempotency_middleware.rb).\n // Checkout creation is deduplicated too, but isRetryablePath keeps it single-shot.\n private isReplaySafe(method: string, path: string): boolean {\n return method === 'GET' || (method === 'POST' && path === '/prefilled-checkouts')\n }\n\n private calculateRetryDelay(attempt: number): number {\n const exponential = RETRY_INITIAL_DELAY_MS * Math.pow(2, attempt)\n const capped = Math.min(exponential, RETRY_MAX_DELAY_MS)\n return capped * (0.5 + Math.random() * 0.5)\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n }\n\n private normalizePrefilledLines(input: PrefilledCheckoutInput): readonly PrefilledCheckoutLineInput[] {\n if (!isRecord(input)) {\n throw new CopeError('createPrefilledCheckout requires an input object')\n }\n\n if (!input.externalReference) {\n throw new CopeError('createPrefilledCheckout requires externalReference for backend idempotency')\n }\n\n if (input.line != null && input.lines != null) {\n throw new CopeError('Use either line or lines for createPrefilledCheckout, not both')\n }\n\n if (input.line != null) {\n return [input.line]\n }\n\n if (input.lines == null || input.lines.length === 0) {\n throw new CopeError('createPrefilledCheckout requires at least one line')\n }\n\n return input.lines\n }\n\n // Injective in the reference: two different references never share a key.\n // A reference that is already header-safe and short keeps the readable\n // `prefilled:<reference>:cart`; any other is SHA-256'd whole, under a `#`\n // prefix no readable key can contain, instead of being rewritten or cut —\n // `INV/2026/1` and `INV-2026-1` used to share a key, and the second checkout\n // got 422 idempotency_body_mismatch for the replay TTL.\n private async prefilledIdempotencyKey(externalReference: string): Promise<string> {\n if (/^[A-Za-z0-9._:-]{1,120}$/.test(externalReference)) return `prefilled:${externalReference}:cart`\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(externalReference))\n const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')\n return `prefilled#${hex}:cart`\n }\n\n // One definition of \"an origin this SDK is configured to talk to\", used by the\n // mount guards and by normalizeCheckoutResult, so the two cannot drift.\n private checkoutOrigin(): string {\n return new URL(this.checkoutBaseUrl).origin\n }\n\n private assertCopeOrigin(url: string, allowedOrigin: string, label: string): void {\n const origin = new URL(url).origin\n if (origin !== allowedOrigin) {\n throw new CopeError(`${label} origin ${origin} does not match expected ${allowedOrigin}`)\n }\n }\n\n private resolveMountTarget(target: HTMLElement | string): HTMLElement {\n // The IIFE bundle ships to untyped JS, where the checkout-first form can be\n // called with the callbacks object alone. Without this the mount got as far as\n // `undefined.appendChild` and surfaced a raw DOM TypeError instead of saying\n // what was missing.\n if (target == null) {\n throw new CopeError('mountCheckout requires options.target')\n }\n if (typeof target !== 'string') return target\n\n const element = document.querySelector(target)\n if (element instanceof HTMLElement) return element\n\n throw new CopeError(`mountCheckout target \"${target}\" was not found`)\n }\n\n private normalizeMountCheckoutArgs(\n checkoutOrTarget: CheckoutResult | MountableCheckout | HTMLElement | string,\n optionsOrCheckout: MountCheckoutOptions | CheckoutResult | MountableCheckout,\n maybeOptions: MountCheckoutCallbacks,\n ): { checkout: CheckoutResult | MountableCheckout; options: MountCheckoutOptions } {\n if (this.isMountableCheckout(checkoutOrTarget)) {\n return {\n checkout: checkoutOrTarget,\n options: optionsOrCheckout as MountCheckoutOptions,\n }\n }\n\n if (!this.isMountableCheckout(optionsOrCheckout)) {\n throw new CopeError('mountCheckout requires a checkout with embedCheckoutUrl')\n }\n\n return {\n checkout: optionsOrCheckout,\n options: { ...maybeOptions, target: checkoutOrTarget },\n }\n }\n\n // Also the overload discriminator: the target-first form passes an element or\n // a selector string, neither of which carries an embedCheckoutUrl.\n private isMountableCheckout(value: unknown): value is CheckoutResult | MountableCheckout {\n if (!isRecord(value)) return false\n return typeof value.embedCheckoutUrl === 'string'\n }\n\n // ---------------------------------------------------------------------------\n // localStorage persistence\n // ---------------------------------------------------------------------------\n\n private get storageEnabled(): boolean {\n return this.persistence === 'localStorage' && typeof localStorage !== 'undefined'\n }\n\n private hydrateFromStorage(): void {\n if (!this.storageEnabled) return\n try {\n const raw = localStorage.getItem(STORAGE_KEY)\n if (raw) {\n const parsed = JSON.parse(raw) as { cartId?: string; secret?: string }\n this.cachedCartId = parsed.cartId ?? null\n this.cachedSecret = parsed.secret ?? null\n }\n } catch {\n // Corrupted or unavailable storage — ignore\n }\n }\n\n private persistToStorage(): void {\n if (!this.storageEnabled) return\n try {\n localStorage.setItem(\n STORAGE_KEY,\n JSON.stringify({ cartId: this.cachedCartId, secret: this.cachedSecret }),\n )\n } catch {\n // Storage full or unavailable — SDK still works via in-memory cache\n }\n }\n\n private clearStorage(): void {\n this.cachedCartId = null\n this.cachedSecret = null\n if (!this.storageEnabled) return\n try {\n localStorage.removeItem(STORAGE_KEY)\n } catch {\n // Ignore\n }\n }\n}\n","import { CopeApiError, CopeCartExpiredError, CopeNetworkError } from '../types.js'\nimport type { Cart, CartLine, CheckoutResult, SdkProduct } from '../types.js'\nimport { InvalidCartRefError } from './cart-ref.js'\n\n/**\n * What an agent may see.\n *\n * Every tool result is built here from an explicit allowlist of fields, never by\n * passing an SDK object through. The cart API hands the SDK credentials an agent\n * must not hold: `cart_secret` on cart creation, and the checkout token inside\n * the embed URL and the payment-status URL. The one credential a tool returns on\n * purpose is `checkoutUrl`, which the buyer needs to pay.\n */\n\nexport interface ToolResult {\n [key: string]: unknown\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError?: boolean\n}\n\nexport function ok(payload: Record<string, unknown>): ToolResult {\n return { content: [{ type: 'text', text: JSON.stringify(payload) }], structuredContent: payload }\n}\n\n// The product's plan amounts are display strings in major units despite their\n// `_cents` names: apps/cope-core PaymentPlanBlueprint writes\n// format('%.2f', cents / 100.0) (CentsConvertible), so display * 100 inverts it\n// exactly, whatever the currency. Read as-is, a 999.00 USD plan was quoted as\n// 999 minor units, 9.99 USD, while the cart charged 99900.\nfunction minorUnits(display: string): number {\n return Math.round(Number(display) * 100)\n}\n\nexport function projectProduct(product: SdkProduct): Record<string, unknown> {\n return {\n productId: product.uuid,\n name: product.name,\n headline: product.headline,\n productType: product.product_type,\n currency: product.currency,\n paymentMethods: product.payment_methods,\n plans: product.payment_plans.map((plan) => ({\n planId: plan.id,\n planType: plan.plan_type,\n name: plan.display_name,\n currency: plan.currency,\n firstPaymentMinorUnits: minorUnits(plan.first_payment_amount_cents),\n nextPaymentsMinorUnits: plan.next_payments_amount_cents === null ? null : minorUnits(plan.next_payments_amount_cents),\n nextPaymentsCount: plan.next_payments_count,\n interval: plan.interval,\n intervalCount: plan.interval_count,\n })),\n }\n}\n\nexport function projectCart(cart: Cart): Record<string, unknown> {\n return {\n state: cart.state,\n currency: cart.currency,\n promoCode: cart.applied_promo_code?.code ?? null,\n lines: cart.lines.map(projectLine),\n // Left out where the response does not report the buyer (reprice, promo code):\n // null would tell the agent no buyer is recorded.\n ...(cart.buyer_identity === undefined ? {} : {\n buyer: cart.buyer_identity === null ? null : {\n email: cart.buyer_identity.email ?? null,\n country: cart.buyer_identity.country ?? null,\n },\n }),\n totals: cart.totals === null ? null : {\n subtotalMinorUnits: cart.totals.subtotal_minor_units,\n discountMinorUnits: cart.totals.discount_minor_units,\n taxMinorUnits: cart.totals.tax_minor_units,\n shippingMinorUnits: cart.totals.shipping_minor_units,\n totalMinorUnits: cart.totals.total_minor_units,\n currency: cart.totals.currency,\n final: cart.totals.finality === 'final',\n },\n }\n}\n\nfunction projectLine(line: CartLine): Record<string, unknown> {\n return {\n lineId: line.id,\n productId: line.product_uuid,\n planId: line.plan_id,\n quantity: line.quantity,\n productName: line.price_snapshot?.product_name ?? line.product_name ?? null,\n planName: line.price_snapshot?.plan_name ?? null,\n unitPriceMinorUnits: line.price_snapshot?.unit_price_minor_units ?? null,\n }\n}\n\nexport function projectCheckout(checkout: CheckoutResult): Record<string, unknown> {\n return {\n checkoutUrl: checkout.checkoutUrl,\n status: checkout.status,\n expiresAt: checkout.expiresAt,\n totalMinorUnits: checkout.totals.total_minor_units,\n currency: checkout.totals.currency,\n }\n}\n\n// What an agent can do about each error the cart API or cope-edge returns.\nconst GUIDANCE: Readonly<Record<string, string>> = {\n invalid_cart_ref: 'The cartRef is not valid here. Start again with create_cart.',\n cart_expired: 'This cart is finished: ordered (the buyer has paid), expired or abandoned. For a new purchase, start again with create_cart.',\n cart_not_active: 'The cart can no longer be changed, usually because checkout has started. Use the checkout URL already returned, or start again with create_cart.',\n cart_id_mismatch: 'The cartRef does not match this cart. Start again with create_cart.',\n not_saleable: 'That product or plan cannot be bought right now. Choose another with get_product.',\n price_changed: 'The price changed. Call get_cart to see current totals before continuing.',\n empty_cart: 'Add a line with add_line before starting checkout.',\n promo_code_not_accepted: 'That promo code cannot be used on this cart (reason says why). Continue without it, or ask the buyer for another.',\n promo_locked_during_payment: 'The promo code cannot change while a payment is in progress.',\n offer_sourced_no_promo: 'This cart comes from a negotiated offer; promo codes do not apply.',\n checkout_expired: 'The checkout expired. Call start_checkout again.',\n tax_address_invalid: 'The buyer address is incomplete or invalid for tax. Ask the buyer and call set_buyer_identity.',\n tax_service_unavailable: 'Tax could not be calculated right now. Retry shortly.',\n business_checkout_hold: 'This store cannot take orders right now. Tell the buyer to try later.',\n rate_limited: 'Too many requests. Wait retryAfter seconds, then retry.',\n idempotency_conflict: 'The same checkout is still being created. Wait a second and call start_checkout again.',\n upstream_unavailable: 'The checkout service is unavailable. Retry shortly.',\n gateway_timeout: 'The checkout service did not answer in time; the change may have been applied. Call get_cart before retrying.',\n network_error: 'The store could not reach the checkout service; the change may have been applied. Call get_cart before retrying.',\n invalid_sdk_key: 'This store is misconfigured. Tell the buyer to contact the store.',\n checkout_not_recoverable: 'The last checkout expired and the cart is being released. Wait a few minutes, then call start_checkout again.',\n line_not_in_cart: 'No line with that id is in the cart. Call get_cart for the current lines and their lineIds.',\n checkout_attempts_exhausted: 'This cart has had too many checkouts. Start again with create_cart.',\n}\n\n/**\n * A promo code the cart API refused. It answers 422 with the validator's own\n * reason (apps/cope-core PromoCodes::Validate: not_found, expired, exhausted,\n * ...), and `not_found` there means \"no such code\", not a missing cart or route,\n * so the refusal gets one code of its own and keeps the API's as `reason`.\n */\nexport function promoRefused(error: CopeApiError): ToolResult {\n return fail(new CopeApiError(error.status, [{ code: 'promo_code_not_accepted', message: error.message }], error.requestId),\n { reason: error.code })\n}\n\nexport function fail(error: unknown, extra: Record<string, unknown> = {}): ToolResult {\n const described = describe(error)\n const payload = {\n error: {\n ...described,\n ...extra,\n guidance: GUIDANCE[described.code] ?? 'The request failed. Do not retry the same input unchanged.',\n },\n }\n return { content: [{ type: 'text', text: JSON.stringify(payload) }], isError: true }\n}\n\nfunction describe(error: unknown): { code: string; message: string; field?: string; retryAfter?: number } {\n if (error instanceof InvalidCartRefError) return { code: 'invalid_cart_ref', message: error.message }\n if (error instanceof CopeCartExpiredError) return { code: 'cart_expired', message: error.message }\n if (error instanceof CopeApiError) {\n return {\n code: error.code,\n message: error.message,\n ...(error.field ? { field: error.field } : {}),\n ...(error.retryAfter !== null ? { retryAfter: error.retryAfter } : {}),\n }\n }\n if (error instanceof CopeNetworkError) return { code: 'network_error', message: error.message }\n // Anything else is ours, not the agent's to act on; do not leak its message.\n return { code: 'internal_error', message: 'The store could not complete this request.' }\n}\n","import * as z from 'zod'\nimport type { McpServer } from '@modelcontextprotocol/server'\nimport { CopeCart } from '../cope-cart.js'\nimport { CopeApiError } from '../types.js'\nimport type { CheckoutPayload, CheckoutResult, CopeCartOptions } from '../types.js'\nimport type { CartCredentials, CartRefCodec } from './cart-ref.js'\nimport { fail, ok, projectCart, projectCheckout, projectProduct, promoRefused } from './results.js'\nimport type { ToolResult } from './results.js'\n\nexport interface ToolContext {\n readonly clientOptions: Pick<CopeCartOptions, 'publishableKey' | 'baseUrl' | 'checkoutBaseUrl'>\n readonly codec: CartRefCodec\n readonly checkout: { readonly successUrl: string; readonly cancelUrl: string }\n}\n\n// Enough to step past checkouts the buyer cancelled or let expire on one cart\n// within the cart API's 24-hour idempotency window.\nconst MAX_CHECKOUT_KEYS = 10\nconst CONFLICT_WAITS_MS = [500, 1000, 2000]\n\nconst cartRef = z.string().min(1).max(2048).describe('The cartRef returned by create_cart. Pass it back unchanged.')\n// Ids go into cart-API paths; anything outside this shape is refused before a request is made.\nconst ID = /^[A-Za-z0-9_-]{1,100}$/\nconst productId = z.string().regex(ID).describe('The product id, e.g. from the store page')\nconst lineId = z.string().regex(ID).describe('A lineId from the cart')\nconst address = z.object({\n line1: z.string(),\n line2: z.string().optional(),\n city: z.string(),\n region: z.string().optional(),\n postalCode: z.string(),\n country: z.string().length(2).describe('ISO 3166-1 alpha-2'),\n})\n\n/**\n * Registers the buyer-facing checkout tools.\n *\n * Deliberately absent from every schema: consents (the buyer accepts terms on\n * the hosted checkout page, not an agent on their behalf), redirect URLs and the\n * embed origin (the merchant configures those), payment (the buyer pays on the\n * checkout page), and a cart id (it comes only from the authenticated cartRef).\n */\nexport function registerCheckoutTools(server: McpServer, ctx: ToolContext): void {\n const run = async (\n work: () => Promise<Record<string, unknown>>,\n refusal: (error: unknown) => ToolResult | null = () => null,\n ): Promise<ToolResult> => {\n try {\n return ok(await work())\n } catch (error) {\n return refusal(error) ?? fail(error)\n }\n }\n const newClient = () => new CopeCart({ ...ctx.clientOptions, persistence: 'none' })\n const openCart = async (ref: string) => {\n const creds = await ctx.codec.decode(ref)\n return { creds, cope: new CopeCart({ ...ctx.clientOptions, cart: creds }) }\n }\n\n server.registerTool('get_product', {\n description: 'Look up a product the store sells: name, plans and prices. Prices are in minor units (cents).',\n inputSchema: z.object({ productId }),\n annotations: { readOnlyHint: true, openWorldHint: false },\n }, ({ productId }) => run(async () => projectProduct(await newClient().getProduct(productId))))\n\n server.registerTool('create_cart', {\n description: 'Start a new cart. Returns a cartRef that every other cart tool needs; keep it for this buyer and reuse it instead of creating another cart.',\n inputSchema: z.object({\n currency: z.string().length(3).describe('ISO 4217 code, e.g. EUR'),\n locale: z.string().optional().describe('Buyer language, e.g. de-DE'),\n }),\n }, ({ currency, locale }) => run(async () => {\n const cart = await newClient().createCart({ currency: currency.toUpperCase(), ...(locale ? { locale } : {}) })\n if (!cart.cart_secret) throw new Error('cart API returned no cart secret')\n return { cartRef: await ctx.codec.encode({ id: cart.id, secret: cart.cart_secret }), cart: projectCart(cart) }\n }))\n\n server.registerTool('get_cart', {\n description: 'Recalculate and return the cart: lines, discounts, tax, shipping and total. Call after changes before quoting a price to the buyer.',\n inputSchema: z.object({ cartRef }),\n annotations: { idempotentHint: true },\n }, ({ cartRef: ref }) => run(async () => {\n const { creds, cope } = await openCart(ref)\n try {\n return { cart: projectCart(await cope.reprice(creds.id)) }\n } catch (error) {\n // A finished cart (ordered, expired, abandoned) cannot be repriced; getCart\n // raises the error that tells the agent it is finished.\n if (!hasCode(error, 'cart_not_repriceable')) throw error\n return { cart: projectCart(await cope.getCart(creds.id)) }\n }\n }))\n\n server.registerTool('add_line', {\n description: 'Add a product (and plan) to the cart. Adding a product already in the cart leaves it unchanged; use update_line to change quantity.',\n inputSchema: z.object({\n cartRef,\n productId,\n planId: z.number().int().optional().describe('From get_product; omit for the default plan'),\n quantity: z.number().int().min(1).optional(),\n }),\n annotations: { idempotentHint: true },\n }, ({ cartRef: ref, productId, planId, quantity }) => run(async () => {\n const { creds, cope } = await openCart(ref)\n try {\n const cart = await cope.addLine(creds.id, {\n product_id: productId,\n ...(planId !== undefined ? { plan_id: planId } : {}),\n ...(quantity !== undefined ? { quantity } : {}),\n })\n return { cart: projectCart(cart) }\n } catch (error) {\n // A repeated add (an agent retrying a call that already landed) is not a failure.\n if (!hasCode(error, 'duplicate_line')) throw error\n return { cart: projectCart(await cope.getCart(creds.id)), alreadyPresent: true }\n }\n }))\n\n server.registerTool('update_line', {\n description: 'Set the quantity (or plan) of a line in the cart.',\n inputSchema: z.object({\n cartRef,\n lineId,\n quantity: z.number().int().min(1).optional(),\n planId: z.number().int().optional(),\n }),\n annotations: { idempotentHint: true },\n }, ({ cartRef: ref, lineId, quantity, planId }) => run(async () => {\n const { creds, cope } = await openCart(ref)\n const cart = await cope.updateLine(creds.id, lineId, {\n ...(quantity !== undefined ? { quantity } : {}),\n ...(planId !== undefined ? { plan_id: planId } : {}),\n })\n return { cart: projectCart(cart) }\n }))\n\n server.registerTool('remove_line', {\n description: 'Remove a line from the cart.',\n inputSchema: z.object({ cartRef, lineId }),\n annotations: { destructiveHint: true },\n }, ({ cartRef: ref, lineId: id }) => run(async () => {\n const { creds, cope } = await openCart(ref)\n try {\n return { cart: projectCart(await cope.removeLine(creds.id, id)) }\n } catch (error) {\n // A 404 cannot tell a repeated remove from an id that was never a line, so\n // it is reported as what it is — not in the cart — and never as a removal.\n if (!hasCode(error, 'not_found')) throw error\n throw new CopeApiError(404, [{ code: 'line_not_in_cart', message: `No line ${id} in this cart` }])\n }\n }))\n\n server.registerTool('apply_promo_code', {\n description: 'Apply a promo code the buyer gave. Then call get_cart to see the discount.',\n inputSchema: z.object({ cartRef, code: z.string().min(1) }),\n annotations: { idempotentHint: true },\n }, ({ cartRef: ref, code }) => run(async () => {\n const { creds, cope } = await openCart(ref)\n return { cart: projectCart(await cope.applyPromoCode(creds.id, code)) }\n }, (error) => (error instanceof CopeApiError && error.status === 422 ? promoRefused(error) : null)))\n\n server.registerTool('remove_promo_code', {\n description: 'Remove the promo code from the cart.',\n inputSchema: z.object({ cartRef }),\n annotations: { idempotentHint: true },\n }, ({ cartRef: ref }) => run(async () => {\n const { creds, cope } = await openCart(ref)\n return { cart: projectCart(await cope.removePromoCode(creds.id)) }\n }))\n\n server.registerTool('set_buyer_identity', {\n description: 'Record who is buying and where, as the buyer stated it. Country and postal code drive tax. The buyer accepts terms on the checkout page, not here.',\n inputSchema: z.object({\n cartRef,\n email: z.string().email().optional(),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n country: z.string().length(2).optional().describe('ISO 3166-1 alpha-2'),\n postalCode: z.string().optional(),\n company: z.string().optional(),\n buyerType: z.enum(['b2b', 'b2c']).optional(),\n vatId: z.string().optional(),\n billingAddress: address.optional(),\n shippingAddress: address.optional(),\n }),\n annotations: { idempotentHint: true },\n }, (args) => run(async () => {\n const { creds, cope } = await openCart(args.cartRef)\n const toAddress = (a: z.infer<typeof address>) => ({\n line1: a.line1, line2: a.line2 ?? null, city: a.city, region: a.region ?? null,\n postal_code: a.postalCode, country: a.country.toUpperCase(),\n })\n const cart = await cope.setBuyerIdentity(creds.id, {\n ...(args.email !== undefined ? { email: args.email } : {}),\n ...(args.firstName !== undefined ? { first_name: args.firstName } : {}),\n ...(args.lastName !== undefined ? { last_name: args.lastName } : {}),\n ...(args.country !== undefined ? { country: args.country.toUpperCase() } : {}),\n ...(args.postalCode !== undefined ? { postal_code: args.postalCode } : {}),\n ...(args.company !== undefined ? { company: args.company } : {}),\n ...(args.buyerType !== undefined ? { buyer_type: args.buyerType } : {}),\n ...(args.vatId !== undefined ? { vat_id: args.vatId } : {}),\n ...(args.billingAddress ? { billing_address: toAddress(args.billingAddress) } : {}),\n ...(args.shippingAddress ? { shipping_address: toAddress(args.shippingAddress) } : {}),\n })\n return { cart: projectCart(cart) }\n }))\n\n server.registerTool('start_checkout', {\n description: 'Create the checkout and return the URL where the buyer reviews, accepts the terms and pays. Calling it again returns the same checkout while it is open.',\n inputSchema: z.object({ cartRef }),\n annotations: { idempotentHint: true },\n }, ({ cartRef: ref }) => run(async () => {\n const { creds, cope } = await openCart(ref)\n const payload: CheckoutPayload = { success_url: ctx.checkout.successUrl, cancel_url: ctx.checkout.cancelUrl, consents: [] }\n return projectCheckout(await startCheckout(cope, creds, payload))\n }))\n}\n\n/**\n * Create the cart's checkout, or return the one already open, without keeping\n * any state between calls.\n *\n * Each attempt n uses the key `mcp-checkout:<cartId>:<n>` with an identical\n * body, and the cart API replays its stored answer for a key it has seen (24 h).\n * - An active cart walks the keys until a call actually opens a checkout: the\n * cart leaves `active`. A replay of a cancelled or expired checkout leaves it\n * active, so the walk moves on.\n * - A cart already in checkout scans every key and returns the newest replayed\n * checkout that has not expired. Keys are used in order, so the newest is the\n * highest-numbered one; expiry alone cannot tell, because a checkout the buyer\n * cancelled keeps its future expiry. The whole range is scanned because a\n * key used more than 24 h ago is re-run (refused, cart_not_active) rather than\n * replayed, so a refusal does not mark the end of the sequence.\n * - A key the API still holds as in flight (409, including one left behind by a\n * crashed request, which cope-core does not recover on this route) is skipped\n * once its waits run out, instead of blocking the cart.\n */\nasync function startCheckout(cope: CopeCart, creds: CartCredentials, payload: CheckoutPayload): Promise<CheckoutResult> {\n const inCheckout = (await cope.getCart(creds.id)).state === 'checkout_in_progress'\n let open: CheckoutResult | null = null\n\n for (let n = 0; n < MAX_CHECKOUT_KEYS; n++) {\n let result: CheckoutResult | null\n try {\n result = await checkoutOnce(cope, creds.id, payload, `mcp-checkout:${creds.id}:${n}`)\n } catch (error) {\n if (hasCode(error, 'idempotency_body_mismatch')) continue // key used with other settings\n if (inCheckout && hasCode(error, 'cart_not_active')) continue // unused, or re-run after 24 h\n throw error\n }\n if (result === null) continue // held in flight past our waits\n if (inCheckout) {\n if (Date.parse(result.expiresAt) > Date.now()) open = result\n continue\n }\n if ((await cope.getCart(creds.id)).state !== 'active') return result // it opened a checkout\n }\n if (open) return open\n if (inCheckout) {\n throw new CopeApiError(409, [{ code: 'checkout_not_recoverable', message: 'The open checkout expired or cannot be recovered' }])\n }\n throw new CopeApiError(409, [{ code: 'checkout_attempts_exhausted', message: 'Too many checkouts for this cart; start a new cart' }])\n}\n\n/** One checkout attempt; null when the key stays in flight past every wait. */\nasync function checkoutOnce(cope: CopeCart, cartId: string, payload: CheckoutPayload, key: string): Promise<CheckoutResult | null> {\n for (const wait of [...CONFLICT_WAITS_MS, null]) {\n try {\n return await cope.checkout(cartId, payload, { idempotencyKey: key })\n } catch (error) {\n if (!hasCode(error, 'idempotency_conflict')) throw error\n if (wait === null) return null\n await new Promise((resolve) => setTimeout(resolve, wait))\n }\n }\n return null\n}\n\nfunction hasCode(error: unknown, code: string): boolean {\n return error instanceof CopeApiError && error.code === code\n}\n","import {\n McpServer,\n createMcpHandler,\n hostHeaderValidationResponse,\n originValidationResponse,\n} from '@modelcontextprotocol/server'\nimport { createCartRefCodec, parseCartRefKeys } from './cart-ref.js'\nimport type { CartRefCodec } from './cart-ref.js'\nimport { createRateLimiter } from './rate-limit.js'\nimport { registerCheckoutTools } from './tools.js'\n\nexport interface CopeMcpOptions {\n /** The store's publishable key (`cope_pk_...`), as for the browser SDK. */\n readonly publishableKey: string\n /**\n * Keys that encrypt the cartRef handed to agents: 32 random bytes each,\n * base64 or base64url (`generateCartRefKey()` makes one). Keep them secret.\n * The first encrypts; all decrypt, so add a new key first and retire an old\n * one later to rotate without breaking carts agents are holding.\n */\n readonly cartRefKeys: readonly string[]\n /** Where the checkout page sends the buyer. Must be on the store's registered redirect URLs. */\n readonly checkout: { readonly successUrl: string; readonly cancelUrl: string }\n /**\n * Host names this endpoint answers to (the `Host` header), e.g.\n * `['shop.example.com']`. Required: a server that answers any Host is open to\n * DNS rebinding from a buyer's browser.\n */\n readonly allowedHosts: readonly string[]\n /**\n * Browser origins allowed to call this endpoint, by host name. Agents calling\n * server-to-server send no Origin and are not affected. Default: none.\n */\n readonly allowedOrigins?: readonly string[]\n /**\n * Request limits, in memory and per process, or `false` to rely on your own.\n * `perClientPerMinute` (default 120) applies to each client that can be told\n * apart (see `clientKey`); `perStorePerMinute` (default 1200) caps the whole\n * endpoint, protecting the store's cart-API quota when clients cannot be.\n */\n readonly rateLimit?: false | { readonly perClientPerMinute?: number; readonly perStorePerMinute?: number }\n /**\n * How to tell clients apart for the per-client limit, e.g. from a trusted\n * proxy's header. A fetch-style Request carries no trustworthy client address,\n * so without this only the store-wide limit applies. The Node handler\n * (`cope-sdk/mcp/node`) uses the socket address by default.\n */\n readonly clientKey?: (request: Request) => string\n readonly baseUrl?: string\n readonly checkoutBaseUrl?: string\n /** Called with errors the handler swallowed (malformed requests, internal failures). */\n readonly onError?: (error: Error) => void\n}\n\nexport interface CopeMcpHandler {\n /** Serve one HTTP request: Bun, Deno, Cloudflare Workers, Next.js route handlers, Hono. */\n fetch(request: Request, clientKey?: string): Promise<Response>\n}\n\nconst SERVER_INFO = { name: 'cope-checkout', version: '0.1.0' }\n\nexport function createCopeMcpHandler(options: CopeMcpOptions): CopeMcpHandler {\n if (options.allowedHosts.length === 0) throw new Error('allowedHosts must name at least one host')\n // Refuse a bad key now, at startup, not on the first agent's request.\n parseCartRefKeys(options.cartRefKeys)\n let codec: Promise<CartRefCodec> | null = null\n const getCodec = () => (codec ??= createCartRefCodec(options.cartRefKeys, options.publishableKey))\n const limits = options.rateLimit === false ? null : {\n client: createRateLimiter(options.rateLimit?.perClientPerMinute ?? 120),\n store: createRateLimiter(options.rateLimit?.perStorePerMinute ?? 1200),\n }\n\n const mcp = createMcpHandler(async () => {\n const server = new McpServer(SERVER_INFO)\n registerCheckoutTools(server, {\n clientOptions: {\n publishableKey: options.publishableKey,\n ...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),\n ...(options.checkoutBaseUrl ? { checkoutBaseUrl: options.checkoutBaseUrl } : {}),\n },\n codec: await getCodec(),\n checkout: options.checkout,\n })\n return server\n }, { legacy: 'stateless', ...(options.onError ? { onerror: options.onError } : {}) })\n\n return {\n async fetch(request, clientKey) {\n const refused = hostHeaderValidationResponse(request, [...options.allowedHosts])\n ?? (request.headers.has('origin') ? originValidationResponse(request, [...(options.allowedOrigins ?? [])]) : undefined)\n if (refused) return refused\n\n if (limits) {\n const client = clientKey ?? options.clientKey?.(request)\n const retryAfter = (client === undefined ? null : limits.client.take(client)) ?? limits.store.take('store')\n if (retryAfter !== null) {\n return new Response(JSON.stringify({ error: 'rate_limited' }), {\n status: 429,\n headers: { 'Content-Type': 'application/json', 'Retry-After': String(retryAfter) },\n })\n }\n }\n return mcp.fetch(request)\n },\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/mcp/cart-ref.ts","../src/mcp/rate-limit.ts","../src/types.ts","../src/cope-cart.ts","../src/mcp/results.ts","../src/mcp/tools.ts","../package.json","../src/mcp/handler.ts"],"names":["cartRef","window","isRecord","lineId","z","productId","createMcpHandler","server","McpServer","hostHeaderValidationResponse","originValidationResponse"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,IAAM,MAAA,GAAS,KAAA;AACf,IAAM,QAAA,GAAW,EAAA;AACjB,IAAM,SAAA,GAAY,EAAA;AAEX,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC7C,WAAA,GAAc;AACZ,IAAA,KAAA,CAAM,qCAAqC,CAAA;AAC3C,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF,CAAA;AAgBO,SAAS,iBAAiB,IAAA,EAAoD;AACnF,EAAA,IAAI,KAAK,MAAA,KAAW,CAAA,EAAG,MAAM,IAAI,MAAM,oCAAoC,CAAA;AAC3E,EAAA,OAAO,IAAA,CAAK,GAAA,CAAI,CAAC,OAAA,KAAY;AAC3B,IAAA,IAAI,GAAA;AACJ,IAAA,IAAI;AACF,MAAA,GAAA,GAAM,cAAc,OAAO,CAAA;AAAA,IAC7B,CAAA,CAAA,MAAQ;AACN,MAAA,MAAM,IAAI,MAAM,iDAAiD,CAAA;AAAA,IACnE;AACA,IAAA,IAAI,GAAA,CAAI,WAAW,SAAA,EAAW,MAAM,IAAI,KAAA,CAAM,CAAA,mCAAA,EAAsC,SAAS,CAAA,MAAA,CAAQ,CAAA;AACrG,IAAA,OAAO,GAAA;AAAA,EACT,CAAC,CAAA;AACH;AAEA,eAAsB,kBAAA,CAAmB,MAAyB,cAAA,EAA+C;AAC/G,EAAA,MAAM,UAAA,GAAa,MAAM,OAAA,CAAQ,GAAA,CAAI,iBAAiB,IAAI,CAAA,CAAE,GAAA,CAAI,CAAC,GAAA,KAC/D,MAAA,CAAO,OAAO,SAAA,CAAU,KAAA,EAAO,KAAK,SAAA,EAAW,KAAA,EAAO,CAAC,SAAA,EAAW,SAAS,CAAC,CAAC,CAAC,CAAA;AAChF,EAAA,MAAM,cAAA,GAAiB,IAAI,WAAA,EAAY,C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Q,IAAI,QAAQ,CAAA,GAAIC,+BAAA,CAAyB,OAAA,EAAS,CAAC,GAAI,QAAQ,cAAA,IAAkB,EAAG,CAAC,CAAA,GAAI,MAAA,CAAA;AAC/G,MAAA,IAAI,SAAS,OAAO,OAAA;AAEpB,MAAA,IAAI,MAAA,EAAQ;AACV,QAAA,MAAM,MAAA,GAAS,SAAA,IAAa,OAAA,CAAQ,SAAA,GAAY,OAAO,CAAA;AACvD,QAAA,MAAM,UAAA,GAAA,CAAc,MAAA,KAAW,MAAA,GAAY,IAAA,GAAO,MAAA,CAAO,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA,KAAM,MAAA,CAAO,KAAA,CAAM,IAAA,CAAK,OAAO,CAAA;AAC1G,QAAA,IAAI,eAAe,IAAA,EAAM;AACvB,UAAA,OAAO,IAAI,SAAS,IAAA,CAAK,SAAA,CAAU,EAAE,KAAA,EAAO,cAAA,EAAgB,CAAA,EAAG;AAAA,YAC7D,MAAA,EAAQ,GAAA;AAAA,YACR,SAAS,EAAE,cAAA,EAAgB,oBAAoB,aAAA,EAAe,MAAA,CAAO,UAAU,CAAA;AAAE,WAClF,CAAA;AAAA,QACH;AAAA,MACF;AACA,MAAA,OAAO,GAAA,CAAI,MAAM,OAAO,CAAA;AAAA,IAC1B;AAAA,GACF;AACF","file":"mcp.cjs","sourcesContent":["/**\n * The cart handle an agent carries between tool calls.\n *\n * MCP's 2026-07-28 protocol is stateless, so nothing ties one tool call to the\n * next except what the agent sends back. The handle therefore holds the cart's\n * id and bearer secret — encrypted, so the agent (and the model behind it) never\n * sees the secret, and authenticated, so a forged or edited handle is refused\n * rather than pointed at another buyer's cart.\n *\n * Format: `cr1.<iv>.<ciphertext>`, base64url, AES-256-GCM. The merchant's\n * publishable key is the additional data, so a handle minted for one merchant\n * never opens under another's configuration even if both reused a key. Keys are\n * a list: the first encrypts, every one decrypts, which is how a key rotates\n * without breaking handles already in agents' hands.\n */\n\nconst PREFIX = 'cr1'\nconst IV_BYTES = 12\nconst KEY_BYTES = 32\n\nexport class InvalidCartRefError extends Error {\n constructor() {\n super('cartRef is not valid for this store')\n this.name = 'InvalidCartRefError'\n }\n}\n\nexport interface CartCredentials {\n readonly id: string\n readonly secret: string\n}\n\nexport interface CartRefCodec {\n encode(cart: CartCredentials): Promise<string>\n decode(cartRef: string): Promise<CartCredentials>\n}\n\n/**\n * Decodes and checks the configured keys. Synchronous, so a handler can refuse a\n * bad configuration when it is created rather than on its first request.\n */\nexport function parseCartRefKeys(keys: readonly string[]): Uint8Array<ArrayBuffer>[] {\n if (keys.length === 0) throw new Error('cartRefKeys needs at least one key')\n return keys.map((encoded) => {\n let raw: Uint8Array<ArrayBuffer>\n try {\n raw = fromBase64Url(encoded)\n } catch {\n throw new Error('cartRefKeys entries must be base64 or base64url')\n }\n if (raw.length !== KEY_BYTES) throw new Error(`cartRefKeys entries must decode to ${KEY_BYTES} bytes`)\n return raw\n })\n}\n\nexport async function createCartRefCodec(keys: readonly string[], publishableKey: string): Promise<CartRefCodec> {\n const cryptoKeys = await Promise.all(parseCartRefKeys(keys).map((raw) =>\n crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['encrypt', 'decrypt'])))\n const additionalData = new TextEncoder().encode(publishableKey)\n\n return {\n async encode(cart) {\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES))\n const plaintext = new TextEncoder().encode(JSON.stringify({ c: cart.id, s: cart.secret }))\n const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData }, cryptoKeys[0], plaintext)\n return `${PREFIX}.${toBase64Url(iv)}.${toBase64Url(new Uint8Array(ciphertext))}`\n },\n\n async decode(cartRef) {\n const parts = cartRef.split('.')\n if (parts.length !== 3 || parts[0] !== PREFIX) throw new InvalidCartRefError()\n let iv: Uint8Array<ArrayBuffer>\n let ciphertext: Uint8Array<ArrayBuffer>\n try {\n iv = fromBase64Url(parts[1])\n ciphertext = fromBase64Url(parts[2])\n } catch {\n throw new InvalidCartRefError()\n }\n if (iv.length !== IV_BYTES) throw new InvalidCartRefError()\n\n for (const key of cryptoKeys) {\n let plaintext: ArrayBuffer\n try {\n plaintext = await crypto.subtle.decrypt({ name: 'AES-GCM', iv, additionalData }, key, ciphertext)\n } catch {\n continue // not this key, or tampered — try the next\n }\n const parsed: unknown = JSON.parse(new TextDecoder().decode(plaintext))\n if (isRecord(parsed) && typeof parsed.c === 'string' && typeof parsed.s === 'string') {\n return { id: parsed.c, secret: parsed.s }\n }\n throw new InvalidCartRefError()\n }\n throw new InvalidCartRefError()\n },\n }\n}\n\n/** A fresh key in the format `cartRefKeys` takes: 32 random bytes, base64url. */\nexport function generateCartRefKey(): string {\n return toBase64Url(crypto.getRandomValues(new Uint8Array(KEY_BYTES)))\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n let binary = ''\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n// Accepts base64url and standard base64, padded or not.\nfunction fromBase64Url(value: string): Uint8Array<ArrayBuffer> {\n if (!/^[A-Za-z0-9_\\-+/]*={0,2}$/.test(value)) throw new Error('not base64')\n const base64 = value.replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, '')\n const binary = atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4))\n return Uint8Array.from(binary, (char) => char.charCodeAt(0))\n}\n","/**\n * A fixed-window request limit per key, in memory.\n *\n * Every tool call reaches cope-edge with the store's publishable key and from\n * the store's own server, so edge cannot tell one buyer's agent from another.\n * The handler keeps two of these: one per identifiable client, so one runaway\n * agent is stopped without affecting the rest, and one for the whole store, a\n * higher ceiling that protects the store's edge quota when clients cannot be\n * told apart. It is per process: a store running several instances should put a\n * shared limiter in front.\n */\n\nexport interface RateLimiter {\n /** Counts one request for `key`; returns null if allowed, or seconds to wait. */\n take(key: string): number | null\n}\n\nconst WINDOW_MS = 60_000\n// Bounds memory under a flood of distinct keys.\nconst MAX_KEYS = 10_000\n\nexport function createRateLimiter(perMinute: number, now: () => number = Date.now): RateLimiter {\n if (!Number.isInteger(perMinute) || perMinute < 1) throw new Error('rate limits must be positive integers')\n // Insertion order is window-start order: a key is deleted and re-inserted\n // whenever its window restarts, so the oldest windows are always at the front\n // and eviction never scans.\n const windows = new Map<string, { start: number; count: number }>()\n\n return {\n take(key) {\n const at = now()\n const current = windows.get(key)\n if (current && at - current.start < WINDOW_MS) {\n if (current.count >= perMinute) return Math.ceil((current.start + WINDOW_MS - at) / 1000)\n current.count += 1\n return null\n }\n windows.delete(key)\n for (const [oldest, window] of windows) {\n if (windows.size < MAX_KEYS && at - window.start < WINDOW_MS) break\n windows.delete(oldest)\n }\n windows.set(key, { start: at, count: 1 })\n return null\n },\n }\n}\n","// ---------------------------------------------------------------------------\n// Error classes\n// ---------------------------------------------------------------------------\n\nexport class CopeError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'CopeError'\n }\n}\n\nexport class CopeApiError extends CopeError {\n readonly code: ApiErrorCode\n readonly status: number\n readonly field?: string\n readonly requestId: string | null\n /** Seconds the server asked the caller to wait (`Retry-After`), or null. */\n readonly retryAfter: number | null\n readonly errors: ReadonlyArray<{ readonly code: string; readonly message: string; readonly field?: string }>\n\n constructor(\n status: number,\n errors: Array<{ code: string; message: string; field?: string }>,\n requestId?: string | null,\n retryAfter?: number | null,\n ) {\n const first = errors[0]\n super(first?.message ?? `API error ${status}`)\n this.name = 'CopeApiError'\n this.status = status\n this.code = (first?.code ?? 'unknown') as ApiErrorCode\n this.field = first?.field\n this.requestId = requestId ?? null\n this.retryAfter = retryAfter ?? null\n this.errors = errors\n }\n}\n\nexport class CopeNetworkError extends CopeError {\n constructor(message: string) {\n super(message)\n this.name = 'CopeNetworkError'\n }\n}\n\nexport class CopeCartExpiredError extends CopeError {\n readonly state: CartState\n\n constructor(state: CartState) {\n super(`Cart is ${state} and cannot be used`)\n this.name = 'CopeCartExpiredError'\n this.state = state\n }\n}\n\n// ---------------------------------------------------------------------------\n// Error codes — known codes + string escape hatch\n// ---------------------------------------------------------------------------\n\nexport type ApiErrorCode =\n // The codes the cart-API endpoints this SDK calls can answer.\n // tests/error-codes-agreement.test.ts holds this list to the literal codes in a\n // listed set of cope-core sources, in both directions; a code built at runtime\n // or emitted outside that set is not seen.\n | 'unauthorized'\n | 'invalid_sdk_key'\n | 'cart_id_mismatch'\n | 'not_found'\n | 'validation_error'\n | 'forbidden_field'\n | 'business_checkout_hold'\n | 'cart_not_active'\n | 'unsupported_currency'\n | 'unsupported_checkout_locale'\n | 'checkout_locale_not_allowed'\n | 'duplicate_line'\n | 'not_saleable'\n | 'product_unavailable'\n | 'insufficient_stock'\n | 'mixed_seller_cart'\n | 'mixed_vat_mode_cart'\n | 'empty_cart'\n | 'below_minimum_charge'\n | 'above_maximum_charge'\n | 'missing_tax_location'\n | 'cart_not_repriceable'\n | 'tax_address_invalid'\n | 'tax_request_rejected'\n | 'tax_service_unavailable'\n | 'invalid_redirect_url'\n | 'embed_origin_not_allowed'\n | 'price_changed'\n | 'checkout_expired'\n | 'checkout_not_cancellable'\n | 'checkout_payment_in_flight'\n | 'idempotency_conflict'\n | 'idempotency_body_mismatch'\n // A refused promo code (422), PromoCodes::Validate's reasons. `not_found` here\n // means no such code; it shares the name of the 404 code above.\n | 'inactive'\n | 'not_started'\n | 'expired'\n | 'exhausted'\n | 'no_applicable_items'\n | 'currency_not_supported'\n | 'promo_not_supported_for_recurring'\n | 'offer_sourced_no_promo'\n | 'promo_locked_during_payment'\n // Answered by cope-edge itself, in its `{error, request_id}` envelope.\n | 'payload_too_large'\n | 'rate_limited'\n | 'upstream_unavailable'\n | 'gateway_timeout'\n // Answered when the buyer's payment session is created on COPE's hosted\n // checkout page — an endpoint this SDK does not call. Kept for code that\n // switches on them; no SDK method returns them.\n | 'incomplete_buyer_identity'\n | 'incomplete_shipping_address'\n | 'missing_consent'\n | 'missing_withdrawal_waiver'\n | 'checkout_not_open'\n | 'payment_provider_error'\n | (string & {}) // escape hatch for unknown codes\n\n// ---------------------------------------------------------------------------\n// Cart\n// ---------------------------------------------------------------------------\n\nexport type CartState =\n | 'active'\n | 'checkout_in_progress'\n | 'ordered'\n | 'expired'\n | 'abandoned'\n | 'merged'\n\nexport interface OneClickChargeConsentApplicability {\n readonly applicable: boolean\n readonly terms_version: string | null\n}\n\nexport interface Cart {\n readonly id: string\n readonly state: CartState\n readonly version: number\n readonly currency: string\n readonly charge_currency: string\n /** Present only in the `createCart()` response. The SDK persists it to localStorage automatically. */\n readonly cart_secret?: string\n readonly lines: readonly CartLine[]\n /** Present only on a `setBuyerIdentity()` response that dropped a field, e.g. a malformed phone. */\n readonly field_errors?: readonly FieldError[]\n /**\n * `getCart()` masks the email (`j***n@example.com`); the `setBuyerIdentity()`\n * response carries it as saved.\n *\n * Absent where cope-core does not report it — the reprice and promo-code\n * responses — which is not the same as `null` (no buyer recorded yet).\n */\n readonly buyer_identity?: BuyerIdentity | null\n readonly totals: CartTotals | null\n readonly locale: string\n readonly applied_promo_code: AppliedPromoCode | null\n /** Backend-owned OTO candidate; absent while older backends roll forward. */\n readonly one_click_charge_consent?: OneClickChargeConsentApplicability | null\n}\n\n// ---------------------------------------------------------------------------\n// Cart Line\n// ---------------------------------------------------------------------------\n\nexport interface CartLine {\n /** The line's id: an integer (the cart API renders `cart_lines.id`, a bigint). */\n readonly id: number\n readonly cart_id: string\n readonly product_id: number\n readonly plan_id: number | null\n readonly quantity: number\n readonly price_snapshot: PriceSnapshot | null\n /** The product's name, present before the line is repriced (`price_snapshot` is null until then). */\n readonly product_name?: string | null\n readonly product_uuid: string\n readonly stale?: boolean\n readonly requires_shipping?: boolean\n readonly trial_days?: number\n readonly payment_methods: readonly string[]\n readonly plan_type: string | null\n}\n\nexport interface PriceSnapshot {\n readonly unit_price_minor_units: number\n readonly currency: string\n readonly charge_currency: string\n readonly product_name: string\n readonly plan_name: string | null\n readonly captured_at: string\n}\n\n// ---------------------------------------------------------------------------\n// Buyer Identity\n// ---------------------------------------------------------------------------\n\nexport interface Address {\n readonly line1: string\n readonly line2: string | null\n readonly city: string\n readonly region?: string | null\n readonly postal_code: string\n readonly country: string\n}\n\n/** The promo code on the cart and what it takes off (apps/cope-core CartBlueprint `applied_promo_code`). */\nexport interface AppliedPromoCode {\n readonly id: number\n readonly code: string\n readonly discount_total_minor_units: number\n /** True when the discount was trimmed to keep the order above the minimum charge. */\n readonly capped_to_minimum_charge: boolean\n}\n\nexport interface BuyerIdentity {\n readonly email: string\n readonly country: string\n readonly postal_code: string | null\n readonly company: string | null\n readonly buyer_type: 'b2b' | 'b2c' | null\n readonly billing_address: Address | null\n readonly shipping_address: Address | null\n readonly consents: readonly Consent[]\n}\n\nexport interface Consent {\n readonly type: string\n readonly granted_at: string\n readonly ip: string\n}\n\n// ---------------------------------------------------------------------------\n// Totals\n// ---------------------------------------------------------------------------\n\nexport type TotalsFinality = 'estimate' | 'final'\n\nexport interface CartTotals {\n readonly subtotal_minor_units: number\n readonly tax_minor_units: number\n readonly shipping_minor_units: number\n readonly discount_minor_units: number\n readonly total_minor_units: number\n /** Currency the *_minor_units are denominated in. Always equals `charge_currency`. */\n readonly currency: string\n /** Currency that will be billed (Stripe PaymentIntent.currency). */\n readonly charge_currency: string\n readonly finality: TotalsFinality\n /** Buyer's selected presentment currency, when different from `charge_currency`.\n * Paired with `presentment_exchange_rate`; both present or both absent.\n * To display amounts in presentment, multiply each `*_minor_units` by `presentment_exchange_rate`. */\n readonly presentment_currency?: string\n readonly presentment_exchange_rate?: number\n}\n\n// ---------------------------------------------------------------------------\n// Product (read-only, for getProduct)\n// ---------------------------------------------------------------------------\n\nexport interface SdkProduct {\n readonly uuid: string\n readonly name: string\n readonly headline: string | null\n readonly product_type: string\n readonly currency: string\n readonly payment_methods: readonly string[]\n readonly images: readonly SdkProductImage[]\n readonly payment_plans: readonly SdkPaymentPlan[]\n}\n\nexport interface SdkProductImage {\n readonly id: number\n readonly image_url: string\n}\n\nexport interface SdkPaymentPlan {\n readonly id: number\n readonly plan_type: 'one_time' | 'subscription' | 'installment'\n readonly position: number\n readonly currency: string\n readonly display_name: string | null\n /** Price as a decimal string, e.g. \"24.99\" (dollars, not cents despite the field name) */\n readonly first_payment_amount_cents: string\n readonly next_payments_amount_cents: string | null\n readonly next_payments_count: number | null\n readonly shipping_price_cents: string\n readonly charge_shipping_once: boolean\n readonly shipping_depend_on_quantity: boolean\n readonly interval: 'day' | 'week' | 'month' | 'year' | null\n readonly interval_count: number | null\n readonly second_payment_in: number | null\n readonly vanity_prices: readonly SdkVanityPrice[]\n}\n\nexport interface SdkVanityPrice {\n readonly id: number\n readonly currency: string\n readonly first_payment_amount_cents: string\n readonly next_payments_amount_cents: string | null\n}\n\n// ---------------------------------------------------------------------------\n// Checkout\n// ---------------------------------------------------------------------------\n\nexport type CheckoutStatus = 'open' | 'completed' | 'expired' | 'cancelled'\n\nexport interface CheckoutCreateEmbedPolicy {\n readonly allowed: true\n readonly parent_origin: string\n}\n\nexport interface CheckoutCreateResponse {\n readonly checkout_id: string\n readonly checkout_url: string\n readonly embed?: CheckoutCreateEmbedPolicy\n readonly status: CheckoutStatus\n readonly expires_at: string\n readonly totals: CartTotals\n readonly cart_version: number\n}\n\n// ---------------------------------------------------------------------------\n// SDK Options & Payloads\n// ---------------------------------------------------------------------------\n\nexport interface CopeOptions {\n readonly publishableKey: string\n readonly baseUrl?: string\n readonly checkoutBaseUrl?: string\n /**\n * Where the active cart's id and secret are kept between page loads.\n * `'localStorage'` (default) is right for one buyer in one browser. Use `'none'`\n * on a server, where one process serves many buyers: a process-wide store would\n * hand one buyer's cart secret to the next client. A client also holds its cart\n * secret in memory and sends it on every request, so a server needs one client\n * per buyer (or per request with `cart`), never one shared client.\n */\n readonly persistence?: 'localStorage' | 'none'\n /**\n * Act on an existing cart whose credentials the caller already holds. Implies\n * `persistence: 'none'`: such a client never reads, writes or clears stored carts.\n */\n readonly cart?: { readonly id: string; readonly secret: string }\n}\n\n/** @deprecated Use `CopeOptions`. */\nexport type CopeCartOptions = CopeOptions\n\nexport interface CheckoutOptions {\n /**\n * Sent as the Idempotency-Key. The cart API replays its stored answer to a\n * repeated key and identical body, so a caller that may re-send the same\n * checkout (an agent retrying a tool call) gets the same checkout back instead\n * of `cart_not_active` from a cart the first call already locked. While the first\n * call is still being processed, a repeat gets 409 `idempotency_conflict`; wait\n * briefly and repeat again.\n */\n readonly idempotencyKey?: string\n}\n\nexport interface CreateCartPayload {\n readonly currency: string\n readonly locale?: string\n readonly attribution?: CartAttribution\n readonly metadata?: CartMetadata\n}\n\nexport interface CartAttribution {\n readonly affiliate_id?: string\n readonly promo_code?: string\n readonly utm_source?: string\n readonly utm_medium?: string\n readonly utm_campaign?: string\n readonly utm_content?: string\n readonly utm_term?: string\n readonly landing_url?: string\n readonly referrer?: string\n readonly captured_at?: string\n}\n\nexport type CartMetadataValue =\n | string\n | number\n | boolean\n | null\n | readonly CartMetadataValue[]\n | { readonly [key: string]: CartMetadataValue }\n\nexport interface CartMetadata {\n readonly [key: string]: CartMetadataValue\n}\n\nexport interface AddLinePayload {\n /** Product UUID string — resolved to integer FK in API response (CartLine.product_id) */\n readonly product_id: string\n /** Optional payment plan ID. Omit it to let the API select the product's default plan. */\n readonly plan_id?: number\n readonly quantity?: number\n}\n\nexport interface UpdateLinePayload {\n readonly quantity?: number\n readonly plan_id?: number\n}\n\nexport interface UpdateBuyerIdentityPayload {\n readonly email?: string\n readonly first_name?: string\n readonly last_name?: string\n readonly country?: string\n readonly postal_code?: string\n readonly company?: string\n readonly buyer_type?: 'b2b' | 'b2c'\n readonly vat_id?: string\n readonly billing_address?: Partial<Address>\n readonly shipping_address?: Partial<Address>\n /**\n * Not blocking: a malformed phone is dropped and the rest of the identity is\n * saved, and the response says so in `field_errors`.\n */\n readonly phone?: string\n /** The buyer's checkout language; a locale the business has not enabled is ignored. */\n readonly locale?: string\n readonly consents?: ReadonlyArray<{ readonly type: string }>\n}\n\nexport interface CheckoutPayload {\n readonly success_url?: string\n readonly cancel_url?: string\n readonly embed_origin?: string\n /**\n * Recorded on the checkout when sent; not required to create it. When the\n * buyer's payment session is created, `buyer_tos` is required, and so is\n * `withdrawal_waiver` for a cart holding a product that does not ship (a digital\n * product). The hosted checkout page asks the buyer for both; send them here\n * only when the buyer has already given them on your page.\n */\n readonly consents?: ReadonlyArray<{ readonly type: string; readonly version?: string }>\n}\n\n/**\n * The minimum a checkout has to expose to be mounted in an iframe.\n *\n * `mountCheckout` reads exactly three things: `embedCheckoutUrl` (the frame's\n * src, and the source of the handshake token), `embedOrigin` (checked against\n * the hosting page), and `checkoutUrl` — the last only for `fallback:\n * 'redirect'`, which refuses to run without it rather than deriving one. It\n * never reads `checkoutId`, `totals`, `status` or `expiresAt`.\n *\n * Asking for a whole `CheckoutResult` therefore asked for four fields it does\n * not use, which shut out the caller that has no CheckoutResult to give: an\n * offer is created server-side and its API answers with `embed_url` +\n * `embed_origin`, no cart and no totals in sight. Integrators were left\n * inventing a `checkoutId` to satisfy a type, or hand-rolling the postMessage\n * handshake the SDK exists to own.\n *\n * `mountCheckout` accepts `CheckoutResult | MountableCheckout` rather than this\n * type alone, and the union is load-bearing: TypeScript excess-property-checks\n * an object LITERAL against its parameter type, so narrowing the parameter to\n * this interface would have rejected the seven-field literal integrators write\n * inline today — a compile break dressed up as a widening. Keeping\n * `CheckoutResult` in the union gives that literal an arm to match.\n */\nexport interface MountableCheckout {\n readonly embedCheckoutUrl: string\n /** Required: `mountCheckout` refuses to mount without it. */\n readonly embedOrigin: string\n /** Required only by `fallback: 'redirect'`; for an offer, pass `public_url`. */\n readonly checkoutUrl?: string\n}\n\nexport interface CheckoutResult {\n readonly checkoutId: string\n readonly checkoutUrl: string\n readonly embedCheckoutUrl: string\n readonly embedOrigin?: string\n readonly status: CheckoutStatus\n readonly expiresAt: string\n readonly totals: CartTotals\n}\n\nexport interface PrefilledCheckoutLineInput {\n readonly productId: string\n /** Optional payment plan ID. Omit it to let the API select the product's default plan. */\n readonly planId?: number\n readonly quantity?: number\n}\n\ninterface PrefilledCheckoutBaseInput {\n /**\n * Stable caller-side reference, e.g. an event sales session ID. The SDK uses\n * it for the backend Idempotency-Key and stores it as cart metadata. Distinct\n * references always get distinct keys: up to 120 characters of\n * `[A-Za-z0-9._:-]` are used as is, anything else is SHA-256'd whole. A replay\n * returns the stored handoff only for the cart API's 24-hour idempotency TTL;\n * after that the same reference creates a new cart and checkout.\n */\n readonly externalReference: string\n readonly currency: string\n readonly locale?: string\n readonly attribution?: CartAttribution\n /**\n * Non-sensitive reconciliation metadata. `external_reference` and\n * `intended_payment_method` are reserved metadata keys populated from the\n * matching top-level SDK fields.\n */\n readonly metadata?: CartMetadata\n readonly intendedPaymentMethod?: string\n /**\n * Let the hosted checkout page collect the buyer's email, country and postal\n * code instead of requiring them in `buyerIdentity`. Only with\n * `intendedPaymentMethod: 'hosted'`; the API refuses it otherwise.\n */\n readonly collectBuyerIdentityAtCheckout?: boolean\n readonly buyerIdentity: UpdateBuyerIdentityPayload\n readonly checkout: CheckoutPayload\n}\n\nexport type PrefilledCheckoutInput = PrefilledCheckoutBaseInput & (\n | {\n readonly line: PrefilledCheckoutLineInput\n readonly lines?: never\n }\n | {\n readonly line?: never\n readonly lines: readonly [PrefilledCheckoutLineInput, ...PrefilledCheckoutLineInput[]]\n }\n)\n\nexport interface PrefilledCheckoutResult {\n /**\n * Cart ID for logging and reconciliation only. The prefilled handoff response\n * intentionally excludes `cart_secret`, so this SDK instance cannot use this\n * cart ID for follow-up mutations such as `addLine`, `reprice`, or `checkout`.\n */\n readonly cartId: string\n readonly cartVersion: number\n readonly checkoutId: string\n readonly checkoutToken: string\n readonly checkoutUrl: string\n readonly embedCheckoutUrl: string\n readonly embedOrigin?: string\n readonly status: CheckoutStatus\n readonly expiresAt: string\n readonly totals: CartTotals\n readonly intendedPaymentMethod?: string\n /** Non-blocking notices, e.g. a malformed phone that was dropped. Absent when there are none. */\n readonly fieldErrors?: readonly FieldError[]\n}\n\n/** A non-blocking notice the API attaches to a successful response. */\nexport interface FieldError {\n readonly code: string\n readonly message: string\n readonly field: string\n}\n\n// ---------------------------------------------------------------------------\n// Checkout embed postMessage protocol — consumer half of a two-package contract\n// ---------------------------------------------------------------------------\n//\n// The producer is the hosted checkout embed bridge\n// (`apps/cope-frontend/lib/checkout/embed-protocol.ts` +\n// `apps/cope-frontend/app/checkout/embed/[token]/HostedCheckoutEmbedBridge.tsx`).\n// A status the bridge emits but this list omits is silently dropped by\n// `parseCheckoutEmbedEvent` — the parent frame then sees nothing at all, not\n// even an error. The two lists are asserted equal by\n// `tests/checkout-embed-protocol-contract.test.ts` (and by its mirror in the\n// frontend suite, so either package's CI lane catches a divergence).\n//\n// Do not add a value here without adding a producer on the bridge side, and do\n// not add one there without adding it here.\n\nexport const CHECKOUT_EMBED_ERROR_CODES = [\n 'not_found',\n 'load_failed',\n 'embed_not_allowed',\n 'confirm_failed',\n] as const\n\nexport type CheckoutEmbedErrorCode = (typeof CHECKOUT_EMBED_ERROR_CODES)[number]\nexport type CheckoutEmbedFallbackMode = 'redirect' | 'error'\n\n/**\n * Terminal states the mounted checkout can report.\n *\n * - `completed` — the order was placed in this session (live payment success).\n * - `already_completed` — the token resolved to a checkout that was paid\n * *before* this iframe mounted (refresh after success, bookmark, re-opened\n * offer link). The parent must not re-run fulfilment, so it does NOT fire\n * `onSuccess`.\n * - `processing` — an asynchronous rail (Klarna/iDEAL/BNPL/SEPA) accepted the\n * payment but Cart's authoritative order state is still `processing`. Not a\n * success: the parent should wait for its own server-side signal.\n * - `expired` / `cancelled` — the checkout or its offer is no longer payable.\n */\nexport const CHECKOUT_EMBED_TERMINAL_STATUSES = [\n 'expired',\n 'completed',\n 'already_completed',\n 'cancelled',\n 'processing',\n] as const\n\nexport type CheckoutEmbedTerminalStatus = (typeof CHECKOUT_EMBED_TERMINAL_STATUSES)[number]\n\nexport interface CheckoutEmbedErrorPayload {\n readonly code: CheckoutEmbedErrorCode\n readonly retryable: boolean\n}\n\nexport interface CheckoutEmbedTerminalPayload {\n readonly status: CheckoutEmbedTerminalStatus\n}\n\nexport interface CheckoutEmbedResizePayload {\n readonly height: number\n}\n\nexport interface CheckoutEmbedEventMetadata {\n readonly messageId?: string\n readonly timestamp?: string\n}\n\n// ---------------------------------------------------------------------------\n// Post-Purchase Offer (OTO) — native post-purchase upsell/downsell flow\n// ---------------------------------------------------------------------------\n//\n// These types mirror the backend post-purchase offer/decision contract for\n// typed consumption by SDK integrators. The SDK never fetches OTO state\n// directly — it only relays sanitized lifecycle events emitted by the\n// mounted checkout iframe (see `post_purchase_offer` / `post_purchase_decision`\n// / `post_purchase_terminal` in CheckoutEmbedEvent below). `offerRef` is an\n// opaque reference — no product/plan identifiers, checkout tokens, cart\n// secrets, payment client secrets, or buyer PII are ever included. The 3DS\n// step-up authentication for an accepted offer happens entirely inside the\n// COPE-owned iframe; the parent only ever learns `requires_action` as a status.\n\nexport type PostPurchaseOfferStepKind = 'upsell' | 'downsell'\n\n/**\n * Buyer's response to a presented offer. `requires_action` means a 3DS\n * step-up is in progress inside the COPE iframe — the payment client secret\n * never leaves that surface.\n */\nexport type PostPurchaseDecisionStatus = 'accepted' | 'declined' | 'failed_not_charged' | 'requires_action'\n\n/** Payment outcome for an accepted offer, tracked separately from the buyer-facing decision status. */\nexport type PostPurchaseChargeStatus = 'not_charged' | 'charged' | 'requires_action' | 'failed'\n\n/** Final state of the overall post-purchase offer flow. */\nexport type PostPurchaseTerminalStatus = 'completed' | 'declined' | 'expired' | 'unavailable'\n\n/** Sanitized offer display fields — no product/plan IDs, only an opaque `offerRef`. */\nexport interface PostPurchaseOffer {\n readonly offerRef: string\n readonly stepKind: PostPurchaseOfferStepKind\n readonly title: string\n readonly priceGrossMinorUnits: number\n readonly currency: string\n}\n\n/** Sanitized decision outcome for a single offer. */\nexport interface PostPurchaseOutcome {\n readonly offerRef: string\n readonly status: PostPurchaseDecisionStatus\n readonly chargeStatus: PostPurchaseChargeStatus\n}\n\nexport type PostPurchaseOfferPayload = PostPurchaseOffer\nexport type PostPurchaseDecisionPayload = PostPurchaseOutcome\n\nexport interface PostPurchaseTerminalPayload {\n readonly status: PostPurchaseTerminalStatus\n}\n\nexport type CheckoutEmbedEvent =\n | ({ readonly type: 'ready' } & CheckoutEmbedEventMetadata)\n | ({ readonly type: 'error'; readonly payload: CheckoutEmbedErrorPayload } & CheckoutEmbedEventMetadata)\n | ({ readonly type: 'terminal'; readonly payload: CheckoutEmbedTerminalPayload } & CheckoutEmbedEventMetadata)\n | ({ readonly type: 'resize'; readonly payload: CheckoutEmbedResizePayload } & CheckoutEmbedEventMetadata)\n | ({ readonly type: 'post_purchase_offer'; readonly payload: PostPurchaseOfferPayload } & CheckoutEmbedEventMetadata)\n | ({ readonly type: 'post_purchase_decision'; readonly payload: PostPurchaseDecisionPayload } & CheckoutEmbedEventMetadata)\n | ({ readonly type: 'post_purchase_terminal'; readonly payload: PostPurchaseTerminalPayload } & CheckoutEmbedEventMetadata)\n\nexport interface CheckoutMountMessage {\n readonly type: 'copecart.checkout.mount'\n readonly version: 1\n readonly token: string\n}\n\nexport interface MountCheckoutOptions {\n readonly target: HTMLElement | string\n readonly title?: string\n readonly className?: string\n /**\n * What to do when the iframe never completes the trusted ready handshake.\n * Defaults to `error`; set `redirect` for a buyer-safe hosted checkout fallback.\n */\n readonly fallback?: CheckoutEmbedFallbackMode\n readonly readyTimeoutMs?: number\n /**\n * Called after a trusted `cope.checkout` ready message from the mounted checkout iframe.\n * `mountCheckout()` intentionally does not expose checkout tokens, cart secrets,\n * payment client secrets, or buyer PII through any callback payload.\n */\n readonly onReady?: () => void\n readonly onResize?: (payload: CheckoutEmbedResizePayload) => void\n readonly onError?: (payload: CheckoutEmbedErrorPayload) => void\n readonly onTerminal?: (payload: CheckoutEmbedTerminalPayload) => void\n readonly onSuccess?: () => void\n readonly onCancel?: () => void\n readonly onFallbackRedirect?: () => void\n /**\n * Called when the mounted checkout iframe presents a post-purchase offer\n * (native OTO upsell/downsell). The payload is sanitized: display fields\n * and an opaque `offerRef` only — never a product/plan ID, checkout token,\n * cart secret, payment client secret, or buyer PII.\n */\n readonly onPostPurchaseOffer?: (payload: PostPurchaseOfferPayload) => void\n /**\n * Called when the buyer decides on a post-purchase offer. `requires_action`\n * means a 3DS step-up is happening inside the COPE iframe — the payment\n * client secret is never forwarded here.\n */\n readonly onPostPurchaseDecision?: (payload: PostPurchaseDecisionPayload) => void\n /** Called when the overall post-purchase offer flow reaches a final state. */\n readonly onPostPurchaseTerminal?: (payload: PostPurchaseTerminalPayload) => void\n readonly onMessage?: (event: CheckoutEmbedEvent) => void\n}\n\nexport type MountCheckoutCallbacks = Omit<MountCheckoutOptions, 'target'>\n\nexport interface MountedCheckout {\n /**\n * Hosted checkout iframe. The SDK sets `allow=\"payment *\"` and\n * `referrerPolicy=\"no-referrer\"`.\n *\n * The SDK intentionally omits a `sandbox` attribute: no sandbox token set has\n * been proven compatible with all required wallet, redirect, and payment\n * provider flows yet. Embedding is instead constrained by the registered\n * `embed_origin` contract plus strict postMessage origin/source checks.\n */\n readonly iframe: HTMLIFrameElement\n destroy(): void\n}\n","import type {\n AddLinePayload,\n Cart,\n CheckoutCreateResponse,\n CheckoutEmbedErrorCode,\n CheckoutEmbedEvent,\n CheckoutEmbedTerminalPayload,\n CheckoutMountMessage,\n CheckoutPayload,\n CheckoutOptions,\n CheckoutResult,\n CopeOptions,\n CreateCartPayload,\n FieldError,\n MountedCheckout,\n MountCheckoutCallbacks,\n MountCheckoutOptions,\n MountableCheckout,\n OneClickChargeConsentApplicability,\n PostPurchaseChargeStatus,\n PostPurchaseDecisionStatus,\n PostPurchaseOfferStepKind,\n PostPurchaseTerminalStatus,\n PrefilledCheckoutInput,\n PrefilledCheckoutLineInput,\n PrefilledCheckoutResult,\n SdkProduct,\n UpdateBuyerIdentityPayload,\n UpdateLinePayload,\n} from './types.js'\nimport {\n CHECKOUT_EMBED_ERROR_CODES,\n CHECKOUT_EMBED_TERMINAL_STATUSES,\n CopeApiError,\n CopeCartExpiredError,\n CopeError,\n CopeNetworkError,\n} from './types.js'\nimport type { CartState } from './types.js'\n\nconst TERMINAL_STATES: ReadonlySet<CartState> = new Set(['ordered', 'expired', 'abandoned', 'merged'])\n// The app host: requests go to `${baseUrl}/api/cart/v1/...`, which cope-edge's\n// checkout block serves there, and the hosted checkout's origin (derived from\n// this URL when checkoutBaseUrl is unset) is the same host.\nconst DEFAULT_BASE_URL = 'https://app.cope.com'\nconst STORAGE_KEY = 'cope_sdk_cart'\nconst REQUEST_TIMEOUT_MS = 8_000\nconst RETRY_INITIAL_DELAY_MS = 500\nconst RETRY_MAX_DELAY_MS = 5_000\nconst CHECKOUT_MESSAGE_SOURCE = 'cope.checkout'\nconst CHECKOUT_MESSAGE_VERSION = 1\nconst CHECKOUT_MOUNT_MESSAGE_TYPE = 'copecart.checkout.mount'\nconst CHECKOUT_MOUNT_MESSAGE_VERSION = 1\nconst CHECKOUT_MOUNT_RETRY_INTERVAL_MS = 250\nconst CHECKOUT_MOUNT_MAX_ATTEMPTS = 20\nconst CHECKOUT_READY_TIMEOUT_MS = 8_000\nconst SUPPORTED_ONE_CLICK_CHARGE_TERMS_VERSIONS: ReadonlySet<string> = new Set(['oto-v1'])\n\ntype HttpMethod = 'GET' | 'POST' | 'PATCH' | 'DELETE'\ntype MountCleanup = () => void\ntype RequestOptions = {\n readonly skipAuth?: boolean\n readonly idempotencyKey?: string\n}\ntype PrefilledCheckoutCreateResponse = CheckoutCreateResponse & {\n readonly cart_id: string\n readonly checkout_token?: string\n readonly field_errors?: readonly FieldError[]\n}\n\n// One path segment. Ids arrive from callers (and, through cope-sdk/mcp, from AI\n// agents); unencoded, `../buyer-identity` or a `?` would aim a request carrying\n// the cart secret at another route.\nfunction seg(id: string | number): string {\n return encodeURIComponent(String(id))\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\ntype ApiErrorEntry = { code: string; message: string; field?: string }\n\n// The normalized origin of a URL that is nothing but an origin — no path, query,\n// fragment or credentials — or null. `https://App.Cope.com:443/` is accepted and\n// becomes `https://app.cope.com`.\nfunction originOnly(value: string): string | null {\n try {\n const url = new URL(value)\n const bare = url.pathname === '/' && !url.search && !url.hash && !url.username && !url.password\n return bare ? url.origin : null\n } catch {\n return null\n }\n}\n\nconst EDGE_ERROR_MESSAGES: Readonly<Record<string, string>> = {\n payload_too_large: 'Request body is too large',\n rate_limited: 'Too many requests',\n upstream_unavailable: 'The checkout service is unavailable',\n gateway_timeout: 'The checkout service did not answer in time',\n not_found: 'Not found',\n}\n\n// Two envelopes reach the SDK: cope-core's `{errors: [{code, message}]}`, and\n// the `{error: \"<code>\", request_id}` cope-edge answers itself on the checkout\n// block — rate limit, body cap, unreachable upstream, deadline\n// (svcs/cope-edge/docs/errors.md). Plan 30 W2-47.\nfunction parseErrorBody(body: unknown): ApiErrorEntry[] | null {\n if (!isRecord(body)) return null\n if (Array.isArray(body.errors) && body.errors.length > 0 && body.errors.every(isApiErrorEntry)) return body.errors\n if (typeof body.error === 'string' && body.error.length > 0) {\n // Edge's `error` is a snake_case code; anything else is prose some other\n // upstream put there, which must not masquerade as a code callers switch on.\n return /^[a-z][a-z0-9_]*$/.test(body.error)\n ? [{ code: body.error, message: EDGE_ERROR_MESSAGES[body.error] ?? body.error }]\n : [{ code: 'unknown', message: body.error }]\n }\n return null\n}\n\nfunction isApiErrorEntry(value: unknown): value is ApiErrorEntry {\n return isRecord(value) && typeof value.code === 'string' && typeof value.message === 'string'\n}\n\nconst MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n// asctime, the one HTTP-date form that names no zone: `Sun Nov 6 08:49:37 1994`.\nconst ASCTIME = /^[A-Z][a-z]{2} ([A-Z][a-z]{2}) ([ \\d]\\d) (\\d{2}):(\\d{2}):(\\d{2}) (\\d{4})$/\n\n// NaN for a date that does not exist: Date.UTC rolls an unknown month (-1), day 39\n// or hour 99 over into a real instant, so the fields must survive a round trip.\nfunction asctimeToUtc([, monthName, day, hh, mm, ss, year]: RegExpExecArray): number {\n const fields = [Number(year), MONTHS.indexOf(monthName ?? ''), Number((day ?? '').trim()), Number(hh), Number(mm), Number(ss)]\n const at = Date.UTC(fields[0], fields[1], fields[2], fields[3], fields[4], fields[5])\n const back = new Date(at)\n const roundTrip = [back.getUTCFullYear(), back.getUTCMonth(), back.getUTCDate(), back.getUTCHours(),\n back.getUTCMinutes(), back.getUTCSeconds()]\n return roundTrip.every((value, i) => value === fields[i]) ? at : Number.NaN\n}\n\n// `Retry-After` is either delta-seconds or an HTTP-date (RFC 9110 §10.2.3), and\n// every HTTP-date is GMT. `Date.parse` reads the asctime form in the HOST's zone,\n// so that form is read by hand; the other two say `GMT`, which Date.parse honours.\n// Anything else is ignored rather than guessed at.\nfunction parseRetryAfter(value: string | null): number | null {\n if (value === null) return null\n const trimmed = value.trim()\n if (/^\\d+$/.test(trimmed)) return Number(trimmed)\n const asctime = ASCTIME.exec(trimmed)\n const at = asctime ? asctimeToUtc(asctime) : / GMT$/.test(trimmed) ? Date.parse(trimmed) : Number.NaN\n return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - Date.now()) / 1000))\n}\n\nfunction bodyRequestId(body: unknown): string | null {\n return isRecord(body) && typeof body.request_id === 'string' ? body.request_id : null\n}\n\nfunction normalizeOneClickChargeConsent(value: unknown): OneClickChargeConsentApplicability {\n if (!isRecord(value)) {\n return { applicable: false, terms_version: null }\n }\n\n const termsVersion = value.terms_version\n if (\n value.applicable !== true\n || typeof termsVersion !== 'string'\n || !SUPPORTED_ONE_CLICK_CHARGE_TERMS_VERSIONS.has(termsVersion)\n ) {\n return { applicable: false, terms_version: null }\n }\n\n return { applicable: true, terms_version: termsVersion }\n}\n\nfunction normalizeCart(cart: Cart): Cart {\n return {\n ...cart,\n one_click_charge_consent: normalizeOneClickChargeConsent(cart.one_click_charge_consent),\n }\n}\n\n// Both guards read the exported protocol lists rather than repeating the\n// union: a second hand-maintained copy is exactly how `already_completed`\n// came to be emitted by the bridge and dropped here.\nconst CHECKOUT_EMBED_ERROR_CODE_SET: ReadonlySet<string> = new Set(CHECKOUT_EMBED_ERROR_CODES)\nconst CHECKOUT_EMBED_TERMINAL_STATUS_SET: ReadonlySet<string> = new Set(CHECKOUT_EMBED_TERMINAL_STATUSES)\n\nfunction isCheckoutEmbedErrorCode(value: string): value is CheckoutEmbedErrorCode {\n return CHECKOUT_EMBED_ERROR_CODE_SET.has(value)\n}\n\nfunction isCheckoutEmbedTerminalStatus(value: string): value is CheckoutEmbedTerminalPayload['status'] {\n return CHECKOUT_EMBED_TERMINAL_STATUS_SET.has(value)\n}\n\nfunction isPostPurchaseOfferStepKind(value: string): value is PostPurchaseOfferStepKind {\n return value === 'upsell' || value === 'downsell'\n}\n\nfunction isPostPurchaseDecisionStatus(value: string): value is PostPurchaseDecisionStatus {\n return (\n value === 'accepted'\n || value === 'declined'\n || value === 'failed_not_charged'\n || value === 'requires_action'\n )\n}\n\nfunction isPostPurchaseChargeStatus(value: string): value is PostPurchaseChargeStatus {\n return (\n value === 'not_charged'\n || value === 'charged'\n || value === 'requires_action'\n || value === 'failed'\n )\n}\n\nfunction isPostPurchaseTerminalStatus(value: string): value is PostPurchaseTerminalStatus {\n return (\n value === 'completed'\n || value === 'declined'\n || value === 'expired'\n || value === 'unavailable'\n )\n}\n\nfunction currentWindowOrigin(): string {\n const location = window.location\n if (location.origin) return location.origin\n\n const host = location.host || [location.hostname, location.port].filter(Boolean).join(':')\n return new URL(`${location.protocol}//${host}`).origin\n}\n\nfunction normalizeCheckoutUrls(absoluteUrl: string): { checkoutUrl: string; embedCheckoutUrl: string } {\n const checkoutUrl = new URL(absoluteUrl)\n const embedCheckoutUrl = new URL(absoluteUrl)\n const embedMatch = checkoutUrl.pathname.match(/^\\/checkout\\/embed\\/([^/]+)$/)\n const checkoutMatch = checkoutUrl.pathname.match(/^\\/checkout\\/([^/]+)$/)\n\n if (embedMatch) {\n checkoutUrl.pathname = `/checkout/${embedMatch[1]}`\n embedCheckoutUrl.pathname = `/checkout/embed/${embedMatch[1]}`\n return {\n checkoutUrl: checkoutUrl.toString(),\n embedCheckoutUrl: embedCheckoutUrl.toString(),\n }\n }\n\n if (checkoutMatch) {\n checkoutUrl.pathname = `/checkout/${checkoutMatch[1]}`\n embedCheckoutUrl.pathname = `/checkout/embed/${checkoutMatch[1]}`\n return {\n checkoutUrl: checkoutUrl.toString(),\n embedCheckoutUrl: embedCheckoutUrl.toString(),\n }\n }\n\n throw new CopeError('Checkout URL path cannot be mapped to COPE checkout routes')\n}\n\nfunction checkoutEmbedToken(embedCheckoutUrl: string): string {\n const url = new URL(embedCheckoutUrl)\n const match = url.pathname.match(/^\\/checkout\\/embed\\/([^/]+)$/)\n if (!match) {\n throw new CopeError('Checkout embed URL path cannot be mapped to COPE checkout embed route')\n }\n\n return decodeURIComponent(match[1])\n}\n\nfunction checkoutEmbedOrigin(raw: CheckoutCreateResponse): string | undefined {\n const embed = raw.embed\n if (!isRecord(embed)) return undefined\n if (embed.allowed !== true) return undefined\n if (typeof embed.parent_origin !== 'string') return undefined\n\n try {\n const origin = new URL(embed.parent_origin).origin\n return origin === embed.parent_origin ? embed.parent_origin : undefined\n } catch {\n return undefined\n }\n}\n\nfunction parseCheckoutEmbedEvent(data: unknown): CheckoutEmbedEvent | null {\n if (!isRecord(data)) return null\n if (data.source !== CHECKOUT_MESSAGE_SOURCE) return null\n if (data.version !== CHECKOUT_MESSAGE_VERSION) return null\n\n const metadata = {\n ...(typeof data.messageId === 'string' ? { messageId: data.messageId } : {}),\n ...(typeof data.timestamp === 'string' ? { timestamp: data.timestamp } : {}),\n }\n\n if (data.type === 'ready') {\n return { type: 'ready', ...metadata }\n }\n\n if (data.type === 'resize') {\n if (!isRecord(data.payload)) return null\n const { height } = data.payload\n if (typeof height !== 'number' || !Number.isFinite(height) || height <= 0) return null\n return {\n type: 'resize',\n payload: { height: Math.ceil(height) },\n ...metadata,\n }\n }\n\n if (data.type === 'error') {\n if (!isRecord(data.payload)) return null\n const { code, retryable } = data.payload\n if (typeof code !== 'string' || !isCheckoutEmbedErrorCode(code)) return null\n if (typeof retryable !== 'boolean') return null\n return {\n type: 'error',\n payload: { code, retryable },\n ...metadata,\n }\n }\n\n if (data.type === 'terminal') {\n if (!isRecord(data.payload)) return null\n const { status } = data.payload\n if (typeof status !== 'string' || !isCheckoutEmbedTerminalStatus(status)) return null\n return {\n type: 'terminal',\n payload: { status },\n ...metadata,\n }\n }\n\n // Only recognized fields are ever read off `data.payload` below — this is what\n // keeps the sanitization guarantee: any extra keys the iframe message might\n // carry (token, cart_secret, client_secret, email, ...) are never copied into\n // the object handed to callbacks.\n if (data.type === 'post_purchase_offer') {\n if (!isRecord(data.payload)) return null\n const { offerRef, stepKind, title, priceGrossMinorUnits, currency } = data.payload\n if (typeof offerRef !== 'string' || !offerRef) return null\n if (typeof stepKind !== 'string' || !isPostPurchaseOfferStepKind(stepKind)) return null\n if (typeof title !== 'string' || !title) return null\n if (typeof priceGrossMinorUnits !== 'number' || !Number.isFinite(priceGrossMinorUnits) || priceGrossMinorUnits < 0) return null\n if (typeof currency !== 'string' || !currency) return null\n return {\n type: 'post_purchase_offer',\n payload: { offerRef, stepKind, title, priceGrossMinorUnits, currency },\n ...metadata,\n }\n }\n\n if (data.type === 'post_purchase_decision') {\n if (!isRecord(data.payload)) return null\n const { offerRef, status, chargeStatus } = data.payload\n if (typeof offerRef !== 'string' || !offerRef) return null\n if (typeof status !== 'string' || !isPostPurchaseDecisionStatus(status)) return null\n if (typeof chargeStatus !== 'string' || !isPostPurchaseChargeStatus(chargeStatus)) return null\n return {\n type: 'post_purchase_decision',\n payload: { offerRef, status, chargeStatus },\n ...metadata,\n }\n }\n\n if (data.type === 'post_purchase_terminal') {\n if (!isRecord(data.payload)) return null\n const { status } = data.payload\n if (typeof status !== 'string' || !isPostPurchaseTerminalStatus(status)) return null\n return {\n type: 'post_purchase_terminal',\n payload: { status },\n ...metadata,\n }\n }\n\n return null\n}\n\n/**\n * COPE SDK — browser client for the checkout API cope-edge serves under `/api/cart/v1`.\n *\n * Usage:\n * ```ts\n * const cope = new Cope({ publishableKey: 'cope_pk_...' })\n * const cart = await cope.createCart({ currency: 'EUR' })\n * await cope.addLine(cart.id, { product_id: 'uuid-123' })\n * await cope.reprice(cart.id)\n * const checkout = await cope.checkout(cart.id, { success_url: '...', cancel_url: '...', consents: [{ type: 'buyer_tos' }] })\n * cope.redirectToCheckout(checkout)\n * ```\n */\nexport class Cope {\n private readonly publishableKey: string\n private readonly baseUrl: string\n private readonly checkoutBaseUrl: string\n private readonly persistence: 'localStorage' | 'none'\n private readonly abortController: AbortController\n private readonly mountCleanups = new Set<MountCleanup>()\n private cachedSecret: string | null = null\n private cachedCartId: string | null = null\n\n /** The active cart ID from localStorage, or null if no cart exists. */\n get currentCartId(): string | null {\n return this.cachedCartId\n }\n\n constructor(options: CopeOptions) {\n if (!options.publishableKey?.startsWith('cope_pk_')) {\n throw new CopeError('Invalid publishableKey. Must start with \"cope_pk_\".')\n }\n\n if (typeof window !== 'undefined' && window.location?.protocol === 'http:' && window.location.hostname !== 'localhost') {\n throw new CopeError('COPE SDK requires HTTPS. Refusing to operate on an insecure page.')\n }\n\n this.publishableKey = options.publishableKey\n // An origin only. @copecart/sdk's docs told integrators to pass\n // `.../gateway/cart_api`; carried over, it would 404 on every call rather\n // than fail here where the cause is visible.\n const baseOrigin = originOnly(options.baseUrl ?? DEFAULT_BASE_URL)\n if (baseOrigin === null) {\n throw new CopeError('Invalid baseUrl. Pass an origin such as \"https://app.cope.com\"; the SDK adds /api/cart/v1 itself.')\n }\n this.baseUrl = baseOrigin\n this.checkoutBaseUrl = options.checkoutBaseUrl\n ? options.checkoutBaseUrl.replace(/\\/+$/, '')\n : new URL(this.baseUrl).origin\n this.abortController = new AbortController()\n // A client handed a cart acts on that cart only: it must not read, overwrite or\n // clear the page's stored cart, which belongs to whichever client created it.\n this.persistence = options.cart ? 'none' : (options.persistence ?? 'localStorage')\n\n if (options.cart) {\n this.cachedCartId = options.cart.id\n this.cachedSecret = options.cart.secret\n } else {\n this.hydrateFromStorage()\n }\n }\n\n // ---------------------------------------------------------------------------\n // Public API\n // ---------------------------------------------------------------------------\n\n async createCart(payload: CreateCartPayload): Promise<Cart> {\n return this.createCartRequest(payload, { skipAuth: true })\n }\n\n async getProduct(productUuid: string): Promise<SdkProduct> {\n return this.get<SdkProduct>(`/products/${seg(productUuid)}`, { skipAuth: true })\n }\n\n async getCart(cartId: string): Promise<Cart> {\n const cart = normalizeCart(await this.get<Cart>(`/carts/${seg(cartId)}`))\n if (TERMINAL_STATES.has(cart.state)) {\n this.clearStorage()\n throw new CopeCartExpiredError(cart.state)\n }\n return cart\n }\n\n async addLine(cartId: string, payload: AddLinePayload): Promise<Cart> {\n return normalizeCart(await this.post<Cart>(`/carts/${seg(cartId)}/lines`, payload))\n }\n\n /** `lineId` is the line's `id`, an integer; a string of its digits is accepted too. */\n async updateLine(cartId: string, lineId: number | string, payload: UpdateLinePayload): Promise<Cart> {\n return normalizeCart(await this.patch<Cart>(`/carts/${seg(cartId)}/lines/${seg(lineId)}`, payload))\n }\n\n /** `lineId` is the line's `id`, an integer; a string of its digits is accepted too. */\n async removeLine(cartId: string, lineId: number | string): Promise<Cart> {\n return normalizeCart(await this.del<Cart>(`/carts/${seg(cartId)}/lines/${seg(lineId)}`))\n }\n\n async setBuyerIdentity(cartId: string, payload: UpdateBuyerIdentityPayload): Promise<Cart> {\n return normalizeCart(await this.patch<Cart>(`/carts/${seg(cartId)}/buyer-identity`, payload))\n }\n\n async reprice(cartId: string): Promise<Cart> {\n return normalizeCart(await this.post<Cart>(`/carts/${seg(cartId)}/reprice`, {}))\n }\n\n async applyPromoCode(cartId: string, code: string): Promise<Cart> {\n return normalizeCart(await this.post<Cart>(`/carts/${seg(cartId)}/promo_code`, { code }))\n }\n\n async removePromoCode(cartId: string): Promise<Cart> {\n return normalizeCart(await this.del<Cart>(`/carts/${seg(cartId)}/promo_code`))\n }\n\n async checkout(cartId: string, payload: CheckoutPayload, options: CheckoutOptions = {}): Promise<CheckoutResult> {\n return this.createCheckoutResult(cartId, payload,\n options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : undefined)\n }\n\n async createPrefilledCheckout(input: PrefilledCheckoutInput): Promise<PrefilledCheckoutResult> {\n const lines = this.normalizePrefilledLines(input)\n const raw = await this.post<PrefilledCheckoutCreateResponse>('/prefilled-checkouts', {\n external_reference: input.externalReference,\n currency: input.currency,\n ...(input.locale != null ? { locale: input.locale } : {}),\n ...(input.attribution ? { attribution: input.attribution } : {}),\n ...(input.intendedPaymentMethod != null ? { intended_payment_method: input.intendedPaymentMethod } : {}),\n ...(input.metadata ? { metadata: input.metadata } : {}),\n ...(input.collectBuyerIdentityAtCheckout != null\n ? { collect_buyer_identity_at_checkout: input.collectBuyerIdentityAtCheckout }\n : {}),\n lines: lines.map((line) => ({\n product_id: line.productId,\n ...(line.planId !== undefined ? { plan_id: line.planId } : {}),\n ...(line.quantity !== undefined ? { quantity: line.quantity } : {}),\n })),\n buyer_identity: input.buyerIdentity,\n checkout: input.checkout,\n }, {\n skipAuth: true,\n idempotencyKey: await this.prefilledIdempotencyKey(input.externalReference),\n })\n const checkout = this.normalizeCheckoutResult(raw)\n\n return {\n cartId: raw.cart_id,\n cartVersion: raw.cart_version,\n checkoutId: checkout.checkoutId,\n checkoutToken: raw.checkout_token ?? checkoutEmbedToken(checkout.embedCheckoutUrl),\n checkoutUrl: checkout.checkoutUrl,\n embedCheckoutUrl: checkout.embedCheckoutUrl,\n ...(checkout.embedOrigin ? { embedOrigin: checkout.embedOrigin } : {}),\n status: checkout.status,\n expiresAt: checkout.expiresAt,\n totals: checkout.totals,\n ...(input.intendedPaymentMethod != null ? { intendedPaymentMethod: input.intendedPaymentMethod } : {}),\n ...(raw.field_errors?.length ? { fieldErrors: raw.field_errors } : {}),\n }\n }\n\n async cancelCheckout(checkoutId: string): Promise<void> {\n await this.requestVoid('POST', `/checkouts/${seg(checkoutId)}/cancel`)\n }\n\n redirectToCheckout(checkout: CheckoutResult): void {\n if (this.abortController.signal.aborted) return\n if (typeof window !== 'undefined') {\n window.location.href = checkout.checkoutUrl\n }\n }\n\n mountCheckout(checkout: CheckoutResult | MountableCheckout, options: MountCheckoutOptions): MountedCheckout\n mountCheckout(target: HTMLElement | string, checkout: CheckoutResult | MountableCheckout, options?: MountCheckoutCallbacks): MountedCheckout\n mountCheckout(\n checkoutOrTarget: CheckoutResult | MountableCheckout | HTMLElement | string,\n optionsOrCheckout: MountCheckoutOptions | CheckoutResult | MountableCheckout,\n maybeOptions: MountCheckoutCallbacks = {},\n ): MountedCheckout {\n if (this.abortController.signal.aborted) {\n throw new CopeError('SDK destroyed')\n }\n\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n throw new CopeError('mountCheckout requires a browser environment')\n }\n\n const { checkout, options } = this.normalizeMountCheckoutArgs(\n checkoutOrTarget,\n optionsOrCheckout,\n maybeOptions,\n )\n // Validation first: every check below reads caller-supplied input, and until\n // this method accepted a bare embed URL that input was origin-proven by\n // construction — it could only have come from normalizeCheckoutResult, which\n // refuses a foreign origin. Accepting `embed_url` straight out of an API\n // response removes that proof, so the two URLs are re-checked here before any\n // DOM is touched or any token is parsed.\n const allowedOrigin = this.checkoutOrigin()\n this.assertCopeOrigin(checkout.embedCheckoutUrl, allowedOrigin, 'Checkout embed URL')\n\n if (!checkout.embedOrigin) {\n throw new CopeError(\n 'mountCheckout requires checkout.embedOrigin — send embed_origin on checkout() or on '\n + 'create-offer, and register the origin in dashboard Settings',\n )\n }\n\n // The `checkoutUrl` sink is strictly worse than the frame's: `fallback:\n // 'redirect'` navigates the buyer's TOP window, so an unvalidated value would\n // hand the whole page to another origin mid-checkout.\n //\n // It is also deliberately NOT derived from the embed URL. For an offer the\n // recovery page is `public_url` (/offers/:uuid), which renders the offer's\n // state; the hosted checkout route would refuse in exactly the cases the\n // fallback exists for, and it carries the payment-capable access token into the\n // address bar and browser history. Refuse at mount rather than at the buyer's\n // eight-second timeout, so this is an integration error, never a runtime one.\n let fallbackUrl: string | undefined\n if (options.fallback === 'redirect') {\n if (!checkout.checkoutUrl) {\n throw new CopeError(\n \"mountCheckout with fallback: 'redirect' requires checkout.checkoutUrl — for an offer, \"\n + 'pass its public_url',\n )\n }\n this.assertCopeOrigin(checkout.checkoutUrl, allowedOrigin, 'Checkout URL')\n fallbackUrl = checkout.checkoutUrl\n }\n\n const target = this.resolveMountTarget(options.target)\n const iframe = document.createElement('iframe')\n const checkoutOrigin = new URL(checkout.embedCheckoutUrl).origin\n const mountMessage: CheckoutMountMessage = {\n type: CHECKOUT_MOUNT_MESSAGE_TYPE,\n version: CHECKOUT_MOUNT_MESSAGE_VERSION,\n token: checkoutEmbedToken(checkout.embedCheckoutUrl),\n }\n const parentOrigin = currentWindowOrigin()\n let destroyed = false\n let ready = false\n let mountAttempts = 0\n // The DOM timer id. Not ReturnType<typeof window.setInterval>: that picks\n // the last overload, which is Node's Timeout once @types/node is loaded.\n let mountRetry: number | undefined\n let readyTimeout: number | undefined\n\n if (checkout.embedOrigin !== parentOrigin) {\n throw new CopeError(`Checkout embed origin ${checkout.embedOrigin} does not match current origin ${parentOrigin}`)\n }\n\n iframe.src = checkout.embedCheckoutUrl\n iframe.title = options.title ?? 'COPE checkout'\n iframe.setAttribute('allow', 'payment *')\n iframe.referrerPolicy = 'no-referrer'\n iframe.style.border = '0'\n iframe.style.width = '100%'\n iframe.style.minHeight = '720px'\n if (options.className) {\n iframe.className = options.className\n }\n\n const clearMountRetry = () => {\n if (mountRetry !== undefined) {\n window.clearInterval(mountRetry)\n mountRetry = undefined\n }\n }\n\n const clearReadyTimeout = () => {\n if (readyTimeout !== undefined) {\n window.clearTimeout(readyTimeout)\n readyTimeout = undefined\n }\n }\n\n const cleanup = () => {\n if (destroyed) return\n destroyed = true\n clearMountRetry()\n clearReadyTimeout()\n window.removeEventListener('message', handleMessage)\n iframe.removeEventListener('load', handleIframeLoad)\n iframe.remove()\n this.mountCleanups.delete(cleanup)\n }\n\n const postMountMessage = () => {\n if (destroyed || ready) return\n if (mountAttempts >= CHECKOUT_MOUNT_MAX_ATTEMPTS) {\n clearMountRetry()\n return\n }\n\n mountAttempts += 1\n iframe.contentWindow?.postMessage(mountMessage, checkoutOrigin)\n }\n\n const startMountHandshake = () => {\n if (destroyed) return\n mountAttempts = 0\n clearMountRetry()\n postMountMessage()\n mountRetry = window.setInterval(postMountMessage, CHECKOUT_MOUNT_RETRY_INTERVAL_MS)\n }\n\n /**\n * Re-arm the handshake on every completed navigation inside the frame.\n *\n * A redirect payment method (Klarna / iDEAL / other BNPL) navigates the\n * iframe away to the provider and back to `/checkout/embed/<token>`. The\n * returning document is a brand-new bridge sitting in `awaiting-mount`, and\n * it will not proceed until the parent proves it knows the token again.\n * Without this the embed hangs forever after any redirect payment.\n *\n * `load` fires on the parent for cross-origin navigations too, so this also\n * runs while the frame is on the provider's page. That is safe: the mount\n * message is posted with `targetOrigin = checkoutOrigin`, so the browser\n * drops it rather than leaking the checkout token to the provider.\n *\n * The ready timeout is deliberately NOT re-armed. It is a one-shot\n * \"the embed never loaded\" guard for the initial mount. Re-arming it would\n * fire `onError({ code: 'load_failed' })` — or, under\n * `fallback: 'redirect'`, navigate the vendor's top window away — eight\n * seconds after the buyer lands on the provider's page, mid-payment. The\n * parent cannot tell those two loads apart: a cross-origin frame exposes\n * neither its location nor whether a `postMessage` was delivered.\n *\n * So the returning document owns reporting its own failure instead: the\n * bridge posts `error` even when it blocks before it has a validated\n * policy, which is why the parent can drop the timer here without going\n * silent after a redirect payment. The one case neither side covers is a\n * return the browser refuses to render at all (the embed origin was\n * disabled while the buyer was at the provider, so the response carries\n * `frame-ancestors 'none'`): no document runs, and nothing can report.\n */\n const handleIframeLoad = () => {\n if (destroyed) return\n ready = false\n startMountHandshake()\n }\n\n const handleMessage = (event: MessageEvent<unknown>) => {\n if (destroyed) return\n if (event.origin !== checkoutOrigin) return\n if (event.source !== iframe.contentWindow) return\n\n const message = parseCheckoutEmbedEvent(event.data)\n if (!message) return\n\n options.onMessage?.(message)\n if (message.type === 'ready') {\n ready = true\n clearMountRetry()\n clearReadyTimeout()\n options.onReady?.()\n } else if (message.type === 'resize') {\n iframe.style.height = `${message.payload.height}px`\n options.onResize?.(message.payload)\n } else if (message.type === 'error') {\n // A bridge that reports an error has already accepted the handshake, so\n // there is nothing left to retry and no missing load to time out. Both\n // timers must stop here or the ready timeout still fires eight seconds\n // later with a bogus `load_failed` (or a top-window fallback redirect).\n clearMountRetry()\n clearReadyTimeout()\n options.onError?.(message.payload)\n } else if (message.type === 'terminal') {\n clearMountRetry()\n clearReadyTimeout()\n options.onTerminal?.(message.payload)\n // Only a live `completed` is a success. `already_completed` means the\n // buyer paid before this mount, so re-running vendor fulfilment would\n // double-grant; `processing` is an asynchronous rail that has not\n // settled yet.\n if (message.payload.status === 'completed') {\n options.onSuccess?.()\n } else if (message.payload.status === 'cancelled') {\n options.onCancel?.()\n }\n } else if (message.type === 'post_purchase_offer') {\n options.onPostPurchaseOffer?.(message.payload)\n } else if (message.type === 'post_purchase_decision') {\n options.onPostPurchaseDecision?.(message.payload)\n } else if (message.type === 'post_purchase_terminal') {\n options.onPostPurchaseTerminal?.(message.payload)\n }\n }\n\n window.addEventListener('message', handleMessage)\n iframe.addEventListener('load', handleIframeLoad)\n this.mountCleanups.add(cleanup)\n\n try {\n target.appendChild(iframe)\n startMountHandshake()\n readyTimeout = window.setTimeout(() => {\n if (destroyed || ready) return\n if (options.fallback === 'redirect') {\n options.onFallbackRedirect?.()\n window.location.href = fallbackUrl as string\n return\n }\n\n options.onError?.({ code: 'load_failed', retryable: true })\n }, options.readyTimeoutMs ?? CHECKOUT_READY_TIMEOUT_MS)\n } catch (error) {\n cleanup()\n throw error\n }\n\n return { iframe, destroy: cleanup }\n }\n\n destroy(): void {\n for (const cleanup of Array.from(this.mountCleanups)) {\n cleanup()\n }\n this.abortController.abort()\n this.clearStorage()\n }\n\n // ---------------------------------------------------------------------------\n // HTTP methods\n // ---------------------------------------------------------------------------\n\n private async createCartRequest(payload: CreateCartPayload, opts?: RequestOptions): Promise<Cart> {\n // POST /carts renders the cart without `lines` or `buyer_identity`\n // (apps/cope-core carts_controller.rb `create`: CartBlueprint's default view,\n // unmasked). A new cart has neither, and the payload cannot supply them.\n const created = await this.post<Cart>('/carts', payload, opts)\n const cart = normalizeCart({ ...created, lines: created.lines ?? [], buyer_identity: created.buyer_identity ?? null })\n if (cart.cart_secret) {\n this.cachedCartId = cart.id\n this.cachedSecret = cart.cart_secret\n this.persistToStorage()\n }\n return cart\n }\n\n private async createCheckoutResult(cartId: string, payload: CheckoutPayload, opts?: RequestOptions): Promise<CheckoutResult> {\n const raw = await this.post<CheckoutCreateResponse>(`/carts/${seg(cartId)}/checkout`, payload, opts)\n return this.normalizeCheckoutResult(raw)\n }\n\n private normalizeCheckoutResult(raw: CheckoutCreateResponse): CheckoutResult {\n const absoluteUrl = raw.checkout_url.startsWith('http')\n ? raw.checkout_url\n : `${this.checkoutBaseUrl}${raw.checkout_url}`\n\n // Validate redirect URL belongs to expected origin\n this.assertCopeOrigin(absoluteUrl, this.checkoutOrigin(), 'Checkout URL')\n\n const urls = normalizeCheckoutUrls(absoluteUrl)\n\n return {\n checkoutId: raw.checkout_id,\n checkoutUrl: urls.checkoutUrl,\n embedCheckoutUrl: urls.embedCheckoutUrl,\n embedOrigin: checkoutEmbedOrigin(raw),\n status: raw.status,\n expiresAt: raw.expires_at,\n totals: raw.totals,\n }\n }\n\n private async requestVoid(method: HttpMethod, path: string, body?: unknown): Promise<void> {\n await this.request<unknown>(method, path, body)\n }\n\n private async get<T>(path: string, opts?: RequestOptions): Promise<T> {\n return this.request<T>('GET', path, undefined, opts)\n }\n\n private async post<T>(path: string, body: unknown, opts?: RequestOptions): Promise<T> {\n return this.request<T>('POST', path, body, opts)\n }\n\n private async patch<T>(path: string, body: unknown): Promise<T> {\n return this.request<T>('PATCH', path, body)\n }\n\n private async del<T>(path: string): Promise<T> {\n return this.request<T>('DELETE', path)\n }\n\n private async request<T>(\n method: HttpMethod,\n path: string,\n body?: unknown,\n opts?: RequestOptions,\n ): Promise<T> {\n if (this.abortController.signal.aborted) {\n throw new CopeError('SDK destroyed')\n }\n\n const url = `${this.baseUrl}/api/cart/v1${path}`\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'X-Cope-Key': this.publishableKey,\n }\n\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json'\n }\n\n if (!opts?.skipAuth && this.cachedSecret) {\n headers['Authorization'] = `CartSecret ${this.cachedSecret}`\n }\n\n // Idempotency key for POST — same key across retries\n const idempotencyKey = method === 'POST' ? (opts?.idempotencyKey ?? crypto.randomUUID()) : undefined\n if (idempotencyKey) {\n headers['Idempotency-Key'] = idempotencyKey\n }\n\n const maxAttempts = (method === 'GET' || (method === 'POST' && this.isRetryablePath(path))) ? 2 : 1\n // A retry after an ambiguous failure (5xx, timeout, network) may re-run a write the\n // server already committed; only a GET, or a POST cope-core deduplicates by\n // Idempotency-Key, survives that. A 429 is refused before processing, so it is safe.\n const replaySafe = this.isReplaySafe(method, path)\n let lastError: unknown\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n if (attempt > 0) {\n const delay = this.calculateRetryDelay(attempt - 1)\n await this.sleep(delay)\n }\n\n const timeoutController = new AbortController()\n const timeout = setTimeout(() => timeoutController.abort(), REQUEST_TIMEOUT_MS)\n const signal = AbortSignal.any([this.abortController.signal, timeoutController.signal])\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body: body !== undefined ? JSON.stringify(body) : undefined,\n signal,\n })\n\n if (response.ok) {\n if (response.status === 204) return undefined as T\n return (await response.json()) as T\n }\n\n // Parse error body\n const errorBody: unknown = await response.json().catch(() => null)\n const errors = parseErrorBody(errorBody) ?? [{ code: 'unknown', message: response.statusText }]\n const requestId = response.headers.get('X-Request-Id') ?? bodyRequestId(errorBody)\n const retryAfter = parseRetryAfter(response.headers.get('Retry-After'))\n\n // Retry on 5xx / 429\n if (this.shouldRetry(response.status) && attempt < maxAttempts - 1 && (replaySafe || response.status === 429)) {\n lastError = new CopeApiError(response.status, errors, requestId, retryAfter)\n continue\n }\n\n throw new CopeApiError(response.status, errors, requestId, retryAfter)\n } catch (error) {\n if (error instanceof CopeApiError) throw error\n if (error instanceof CopeCartExpiredError) throw error\n\n // AbortError from SDK destroy\n if (this.abortController.signal.aborted) {\n throw new CopeError('SDK destroyed')\n }\n\n // Network or timeout error — retry only where a replay cannot duplicate a write\n if (attempt < maxAttempts - 1 && replaySafe) {\n lastError = error\n continue\n }\n\n const msg = error instanceof Error ? error.message : 'Network error'\n throw new CopeNetworkError(msg)\n } finally {\n clearTimeout(timeout)\n }\n }\n\n // Should not reach here, but just in case\n throw lastError instanceof Error ? lastError : new CopeNetworkError('Request failed')\n }\n\n private shouldRetry(status: number): boolean {\n return status === 429 || status >= 500\n }\n\n private isRetryablePath(path: string): boolean {\n return !path.includes('/checkout')\n }\n\n // The SDK POSTs cope-core's IdempotencyMiddleware deduplicates\n // (CART_POST_ROUTES, apps/cope-core/app/middleware/idempotency_middleware.rb).\n // Checkout creation is deduplicated too, but isRetryablePath keeps it single-shot.\n private isReplaySafe(method: string, path: string): boolean {\n return method === 'GET' || (method === 'POST' && path === '/prefilled-checkouts')\n }\n\n private calculateRetryDelay(attempt: number): number {\n const exponential = RETRY_INITIAL_DELAY_MS * Math.pow(2, attempt)\n const capped = Math.min(exponential, RETRY_MAX_DELAY_MS)\n return capped * (0.5 + Math.random() * 0.5)\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n }\n\n private normalizePrefilledLines(input: PrefilledCheckoutInput): readonly PrefilledCheckoutLineInput[] {\n if (!isRecord(input)) {\n throw new CopeError('createPrefilledCheckout requires an input object')\n }\n\n if (!input.externalReference) {\n throw new CopeError('createPrefilledCheckout requires externalReference for backend idempotency')\n }\n\n if (input.line != null && input.lines != null) {\n throw new CopeError('Use either line or lines for createPrefilledCheckout, not both')\n }\n\n if (input.line != null) {\n return [input.line]\n }\n\n if (input.lines == null || input.lines.length === 0) {\n throw new CopeError('createPrefilledCheckout requires at least one line')\n }\n\n return input.lines\n }\n\n // Injective in the reference: two different references never share a key.\n // A reference that is already header-safe and short keeps the readable\n // `prefilled:<reference>:cart`; any other is SHA-256'd whole, under a `#`\n // prefix no readable key can contain, instead of being rewritten or cut —\n // `INV/2026/1` and `INV-2026-1` used to share a key, and the second checkout\n // got 422 idempotency_body_mismatch for the replay TTL.\n private async prefilledIdempotencyKey(externalReference: string): Promise<string> {\n if (/^[A-Za-z0-9._:-]{1,120}$/.test(externalReference)) return `prefilled:${externalReference}:cart`\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(externalReference))\n const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')\n return `prefilled#${hex}:cart`\n }\n\n // One definition of \"an origin this SDK is configured to talk to\", used by the\n // mount guards and by normalizeCheckoutResult, so the two cannot drift.\n private checkoutOrigin(): string {\n return new URL(this.checkoutBaseUrl).origin\n }\n\n private assertCopeOrigin(url: string, allowedOrigin: string, label: string): void {\n const origin = new URL(url).origin\n if (origin !== allowedOrigin) {\n throw new CopeError(`${label} origin ${origin} does not match expected ${allowedOrigin}`)\n }\n }\n\n private resolveMountTarget(target: HTMLElement | string): HTMLElement {\n // The IIFE bundle ships to untyped JS, where the checkout-first form can be\n // called with the callbacks object alone. Without this the mount got as far as\n // `undefined.appendChild` and surfaced a raw DOM TypeError instead of saying\n // what was missing.\n if (target == null) {\n throw new CopeError('mountCheckout requires options.target')\n }\n if (typeof target !== 'string') return target\n\n const element = document.querySelector(target)\n if (element instanceof HTMLElement) return element\n\n throw new CopeError(`mountCheckout target \"${target}\" was not found`)\n }\n\n private normalizeMountCheckoutArgs(\n checkoutOrTarget: CheckoutResult | MountableCheckout | HTMLElement | string,\n optionsOrCheckout: MountCheckoutOptions | CheckoutResult | MountableCheckout,\n maybeOptions: MountCheckoutCallbacks,\n ): { checkout: CheckoutResult | MountableCheckout; options: MountCheckoutOptions } {\n if (this.isMountableCheckout(checkoutOrTarget)) {\n return {\n checkout: checkoutOrTarget,\n options: optionsOrCheckout as MountCheckoutOptions,\n }\n }\n\n if (!this.isMountableCheckout(optionsOrCheckout)) {\n throw new CopeError('mountCheckout requires a checkout with embedCheckoutUrl')\n }\n\n return {\n checkout: optionsOrCheckout,\n options: { ...maybeOptions, target: checkoutOrTarget },\n }\n }\n\n // Also the overload discriminator: the target-first form passes an element or\n // a selector string, neither of which carries an embedCheckoutUrl.\n private isMountableCheckout(value: unknown): value is CheckoutResult | MountableCheckout {\n if (!isRecord(value)) return false\n return typeof value.embedCheckoutUrl === 'string'\n }\n\n // ---------------------------------------------------------------------------\n // localStorage persistence\n // ---------------------------------------------------------------------------\n\n private get storageEnabled(): boolean {\n return this.persistence === 'localStorage' && typeof localStorage !== 'undefined'\n }\n\n private hydrateFromStorage(): void {\n if (!this.storageEnabled) return\n try {\n const raw = localStorage.getItem(STORAGE_KEY)\n if (raw) {\n const parsed = JSON.parse(raw) as { cartId?: string; secret?: string }\n this.cachedCartId = parsed.cartId ?? null\n this.cachedSecret = parsed.secret ?? null\n }\n } catch {\n // Corrupted or unavailable storage — ignore\n }\n }\n\n private persistToStorage(): void {\n if (!this.storageEnabled) return\n try {\n localStorage.setItem(\n STORAGE_KEY,\n JSON.stringify({ cartId: this.cachedCartId, secret: this.cachedSecret }),\n )\n } catch {\n // Storage full or unavailable — SDK still works via in-memory cache\n }\n }\n\n private clearStorage(): void {\n this.cachedCartId = null\n this.cachedSecret = null\n if (!this.storageEnabled) return\n try {\n localStorage.removeItem(STORAGE_KEY)\n } catch {\n // Ignore\n }\n }\n}\n\n/**\n * The 0.1.0 name of {@link Cope}: the same class, so `instanceof` agrees across both names.\n * @deprecated Use `Cope`. `CopeCart` stays exported for code written against 0.1.0.\n */\nexport const CopeCart = Cope\n/** @deprecated Use `Cope`. */\nexport type CopeCart = Cope\n","import { CopeApiError, CopeCartExpiredError, CopeNetworkError } from '../types.js'\nimport type { Cart, CartLine, CheckoutResult, SdkProduct } from '../types.js'\nimport { InvalidCartRefError } from './cart-ref.js'\n\n/**\n * What an agent may see.\n *\n * Every tool result is built here from an explicit allowlist of fields, never by\n * passing an SDK object through. The cart API hands the SDK credentials an agent\n * must not hold: `cart_secret` on cart creation, and the checkout token inside\n * the embed URL and the payment-status URL. The one credential a tool returns on\n * purpose is `checkoutUrl`, which the buyer needs to pay.\n */\n\nexport interface ToolResult {\n [key: string]: unknown\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError?: boolean\n}\n\nexport function ok(payload: Record<string, unknown>): ToolResult {\n return { content: [{ type: 'text', text: JSON.stringify(payload) }], structuredContent: payload }\n}\n\n// The product's plan amounts are display strings in major units despite their\n// `_cents` names: apps/cope-core PaymentPlanBlueprint writes\n// format('%.2f', cents / 100.0) (CentsConvertible), so display * 100 inverts it\n// exactly, whatever the currency. Read as-is, a 999.00 USD plan was quoted as\n// 999 minor units, 9.99 USD, while the cart charged 99900.\nfunction minorUnits(display: string): number {\n return Math.round(Number(display) * 100)\n}\n\nexport function projectProduct(product: SdkProduct): Record<string, unknown> {\n return {\n productId: product.uuid,\n name: product.name,\n headline: product.headline,\n productType: product.product_type,\n currency: product.currency,\n paymentMethods: product.payment_methods,\n plans: product.payment_plans.map((plan) => ({\n planId: plan.id,\n planType: plan.plan_type,\n name: plan.display_name,\n currency: plan.currency,\n firstPaymentMinorUnits: minorUnits(plan.first_payment_amount_cents),\n nextPaymentsMinorUnits: plan.next_payments_amount_cents === null ? null : minorUnits(plan.next_payments_amount_cents),\n nextPaymentsCount: plan.next_payments_count,\n interval: plan.interval,\n intervalCount: plan.interval_count,\n })),\n }\n}\n\nexport function projectCart(cart: Cart): Record<string, unknown> {\n return {\n state: cart.state,\n currency: cart.currency,\n promoCode: cart.applied_promo_code?.code ?? null,\n lines: cart.lines.map(projectLine),\n // Left out where the response does not report the buyer (reprice, promo code):\n // null would tell the agent no buyer is recorded.\n ...(cart.buyer_identity === undefined ? {} : {\n buyer: cart.buyer_identity === null ? null : {\n email: cart.buyer_identity.email ?? null,\n country: cart.buyer_identity.country ?? null,\n },\n }),\n totals: cart.totals === null ? null : {\n subtotalMinorUnits: cart.totals.subtotal_minor_units,\n discountMinorUnits: cart.totals.discount_minor_units,\n taxMinorUnits: cart.totals.tax_minor_units,\n shippingMinorUnits: cart.totals.shipping_minor_units,\n totalMinorUnits: cart.totals.total_minor_units,\n currency: cart.totals.currency,\n final: cart.totals.finality === 'final',\n },\n }\n}\n\nfunction projectLine(line: CartLine): Record<string, unknown> {\n return {\n lineId: line.id,\n productId: line.product_uuid,\n planId: line.plan_id,\n quantity: line.quantity,\n productName: line.price_snapshot?.product_name ?? line.product_name ?? null,\n planName: line.price_snapshot?.plan_name ?? null,\n unitPriceMinorUnits: line.price_snapshot?.unit_price_minor_units ?? null,\n }\n}\n\nexport function projectCheckout(checkout: CheckoutResult, lines: readonly CartLine[]): Record<string, unknown> {\n return {\n checkoutUrl: checkout.checkoutUrl,\n status: checkout.status,\n expiresAt: checkout.expiresAt,\n totalMinorUnits: checkout.totals.total_minor_units,\n currency: checkout.totals.currency,\n buyerNext: buyerNextFor(lines),\n }\n}\n\n/**\n * What the buyer does on the checkout page. Consents are the buyer's own act (plan\n * 63): an agent sends none. The page asks for the terms always, and for the waiver\n * of the right of withdrawal when a line's product does not ship — the same rule\n * the payment session enforces (cope-core Checkouts::ConsentValidator#digital_cart?).\n */\nexport function buyerNextFor(lines: readonly CartLine[]): string {\n const waiver = lines.some((line) => line.requires_shipping === false)\n ? ', waive their right of withdrawal (a product in this cart does not ship)'\n : lines.some((line) => line.requires_shipping === undefined)\n ? ', waive their right of withdrawal if a product in the cart does not ship'\n : ''\n return `Send the buyer to checkoutUrl. There they accept the terms${waiver}, and pay. You cannot do any of these for them.`\n}\n\n// What an agent can do about each error the cart API or cope-edge returns.\nconst GUIDANCE: Readonly<Record<string, string>> = {\n invalid_cart_ref: 'The cartRef is not valid here. Start again with create_cart.',\n cart_expired: 'This cart is finished: ordered (the buyer has paid), expired or abandoned. For a new purchase, start again with create_cart.',\n cart_not_active: 'The cart can no longer be changed, usually because checkout has started. Use the checkout URL already returned, or start again with create_cart.',\n cart_id_mismatch: 'The cartRef does not match this cart. Start again with create_cart.',\n not_saleable: 'That product or plan cannot be bought right now. Choose another with get_product.',\n price_changed: 'The price changed. Call get_cart to see current totals before continuing.',\n empty_cart: 'Add a line with add_line before starting checkout.',\n promo_code_not_accepted: 'That promo code cannot be used on this cart (reason says why). Continue without it, or ask the buyer for another.',\n promo_locked_during_payment: 'The promo code cannot change while a payment is in progress.',\n offer_sourced_no_promo: 'This cart comes from a negotiated offer; promo codes do not apply.',\n checkout_expired: 'The checkout expired. Call start_checkout again.',\n tax_address_invalid: 'The buyer address is incomplete or invalid for tax. Ask the buyer and call set_buyer_identity.',\n missing_tax_location: 'Totals need the buyer\\'s country and postal code. Ask the buyer and call set_buyer_identity, then get_cart.',\n tax_service_unavailable: 'Tax could not be calculated right now. Retry shortly.',\n business_checkout_hold: 'This store cannot take orders right now. Tell the buyer to try later.',\n rate_limited: 'Too many requests. Wait retryAfter seconds, then retry.',\n idempotency_conflict: 'The same checkout is still being created. Wait a second and call start_checkout again.',\n upstream_unavailable: 'The checkout service is unavailable. Retry shortly.',\n gateway_timeout: 'The checkout service did not answer in time; the change may have been applied. Call get_cart before retrying.',\n network_error: 'The store could not reach the checkout service; the change may have been applied. Call get_cart before retrying.',\n invalid_sdk_key: 'This store is misconfigured. Tell the buyer to contact the store.',\n checkout_not_recoverable: 'The last checkout expired and the cart is being released. Wait a few minutes, then call start_checkout again.',\n line_not_in_cart: 'No line with that id is in the cart. Call get_cart for the current lines and their lineIds.',\n checkout_attempts_exhausted: 'This cart has had too many checkouts. Start again with create_cart.',\n}\n\n/**\n * A promo code the cart API refused. It answers 422 with the validator's own\n * reason (apps/cope-core PromoCodes::Validate: not_found, expired, exhausted,\n * ...), and `not_found` there means \"no such code\", not a missing cart or route,\n * so the refusal gets one code of its own and keeps the API's as `reason`.\n */\nexport function promoRefused(error: CopeApiError): ToolResult {\n return fail(new CopeApiError(error.status, [{ code: 'promo_code_not_accepted', message: error.message }], error.requestId),\n { reason: error.code })\n}\n\nexport function fail(error: unknown, extra: Record<string, unknown> = {}): ToolResult {\n const described = describe(error)\n const payload = {\n error: {\n ...described,\n ...extra,\n guidance: GUIDANCE[described.code] ?? 'The request failed. Do not retry the same input unchanged.',\n },\n }\n return { content: [{ type: 'text', text: JSON.stringify(payload) }], isError: true }\n}\n\nfunction describe(error: unknown): { code: string; message: string; field?: string; retryAfter?: number } {\n if (error instanceof InvalidCartRefError) return { code: 'invalid_cart_ref', message: error.message }\n if (error instanceof CopeCartExpiredError) return { code: 'cart_expired', message: error.message }\n if (error instanceof CopeApiError) {\n return {\n code: error.code,\n message: error.message,\n ...(error.field ? { field: error.field } : {}),\n ...(error.retryAfter !== null ? { retryAfter: error.retryAfter } : {}),\n }\n }\n if (error instanceof CopeNetworkError) return { code: 'network_error', message: error.message }\n // Anything else is ours, not the agent's to act on; do not leak its message.\n return { code: 'internal_error', message: 'The store could not complete this request.' }\n}\n","import * as z from 'zod'\nimport type { McpServer } from '@modelcontextprotocol/server'\nimport { Cope } from '../cope-cart.js'\nimport { CopeApiError } from '../types.js'\nimport type { Cart, CheckoutPayload, CheckoutResult, CopeOptions } from '../types.js'\nimport type { CartCredentials, CartRefCodec } from './cart-ref.js'\nimport { fail, ok, projectCart, projectCheckout, projectProduct, promoRefused } from './results.js'\nimport type { ToolResult } from './results.js'\n\nexport interface ToolContext {\n readonly clientOptions: Pick<CopeOptions, 'publishableKey' | 'baseUrl' | 'checkoutBaseUrl'>\n readonly codec: CartRefCodec\n readonly checkout: { readonly successUrl: string; readonly cancelUrl: string }\n}\n\n// Enough to step past checkouts the buyer cancelled or let expire on one cart\n// within the cart API's 24-hour idempotency window.\nconst MAX_CHECKOUT_KEYS = 10\nconst CONFLICT_WAITS_MS = [500, 1000, 2000]\n\nconst cartRef = z.string().min(1).max(2048).describe('The cartRef returned by create_cart. Pass it back unchanged.')\n// Ids go into cart-API paths; anything outside this shape is refused before a request is made.\nconst ID = /^[A-Za-z0-9_-]{1,100}$/\nconst productId = z.string().regex(ID).describe('The product id, e.g. from the store page')\n// A cart line's id is an integer on the wire (cart_lines.id) and is handed back as one.\n// A string of its digits is accepted too: it was the declared type, and agents quote numbers.\nconst lineId = z.union([z.number().int().positive(), z.string().regex(/^\\d{1,19}$/)])\n .describe('A lineId from the cart, as get_cart returned it')\nconst address = z.object({\n line1: z.string(),\n line2: z.string().optional(),\n city: z.string(),\n region: z.string().optional(),\n postalCode: z.string(),\n country: z.string().length(2).describe('ISO 3166-1 alpha-2'),\n})\n\n/**\n * Registers the buyer-facing checkout tools.\n *\n * Deliberately absent from every schema: consents (the buyer accepts terms on\n * the hosted checkout page, not an agent on their behalf), redirect URLs and the\n * embed origin (the merchant configures those), payment (the buyer pays on the\n * checkout page), and a cart id (it comes only from the authenticated cartRef).\n */\nexport function registerCheckoutTools(server: McpServer, ctx: ToolContext): void {\n const run = async (\n work: () => Promise<Record<string, unknown>>,\n refusal: (error: unknown) => ToolResult | null = () => null,\n ): Promise<ToolResult> => {\n try {\n return ok(await work())\n } catch (error) {\n return refusal(error) ?? fail(error)\n }\n }\n const newClient = () => new Cope({ ...ctx.clientOptions, persistence: 'none' })\n const openCart = async (ref: string) => {\n const creds = await ctx.codec.decode(ref)\n return { creds, cope: new Cope({ ...ctx.clientOptions, cart: creds }) }\n }\n\n server.registerTool('get_product', {\n description: 'Look up a product the store sells: name, plans and prices. Prices are in minor units (cents).',\n inputSchema: z.object({ productId }),\n annotations: { readOnlyHint: true, openWorldHint: false },\n }, ({ productId }) => run(async () => projectProduct(await newClient().getProduct(productId))))\n\n server.registerTool('create_cart', {\n description: 'Start a new cart. Returns a cartRef that every other cart tool needs; keep it for this buyer and reuse it instead of creating another cart.',\n inputSchema: z.object({\n currency: z.string().length(3).describe('ISO 4217 code, e.g. EUR'),\n locale: z.string().optional().describe('Buyer language, e.g. de-DE'),\n }),\n }, ({ currency, locale }) => run(async () => {\n const cart = await newClient().createCart({ currency: currency.toUpperCase(), ...(locale ? { locale } : {}) })\n if (!cart.cart_secret) throw new Error('cart API returned no cart secret')\n return { cartRef: await ctx.codec.encode({ id: cart.id, secret: cart.cart_secret }), cart: projectCart(cart) }\n }))\n\n server.registerTool('get_cart', {\n description: 'Recalculate and return the cart: lines, discounts, tax, shipping and total. Call after changes before quoting a price to the buyer.',\n inputSchema: z.object({ cartRef }),\n annotations: { idempotentHint: true },\n }, ({ cartRef: ref }) => run(async () => {\n const { creds, cope } = await openCart(ref)\n try {\n return { cart: projectCart(await cope.reprice(creds.id)) }\n } catch (error) {\n // A finished cart (ordered, expired, abandoned) cannot be repriced; getCart\n // raises the error that tells the agent it is finished.\n if (hasCode(error, 'cart_not_repriceable')) return { cart: projectCart(await cope.getCart(creds.id)) }\n // No location to tax yet. The lines are still worth showing; totals wait\n // for the buyer's country and postal code rather than being demanded first.\n if (hasCode(error, 'missing_tax_location')) {\n return {\n cart: projectCart(await cope.getCart(creds.id)),\n totalsPending: 'Totals need the buyer\\'s country and postal code. Call set_buyer_identity when the buyer gives them.',\n }\n }\n throw error\n }\n }))\n\n server.registerTool('add_line', {\n description: 'Add a product (and plan) to the cart. Adding a product already in the cart leaves it unchanged; use update_line to change quantity.',\n inputSchema: z.object({\n cartRef,\n productId,\n planId: z.number().int().optional().describe('From get_product; omit for the default plan'),\n quantity: z.number().int().min(1).optional(),\n }),\n annotations: { idempotentHint: true },\n }, ({ cartRef: ref, productId, planId, quantity }) => run(async () => {\n const { creds, cope } = await openCart(ref)\n try {\n const cart = await cope.addLine(creds.id, {\n product_id: productId,\n ...(planId !== undefined ? { plan_id: planId } : {}),\n ...(quantity !== undefined ? { quantity } : {}),\n })\n return { cart: projectCart(cart) }\n } catch (error) {\n // A repeated add (an agent retrying a call that already landed) is not a failure.\n if (!hasCode(error, 'duplicate_line')) throw error\n return { cart: projectCart(await cope.getCart(creds.id)), alreadyPresent: true }\n }\n }))\n\n server.registerTool('update_line', {\n description: 'Set the quantity (or plan) of a line in the cart.',\n inputSchema: z.object({\n cartRef,\n lineId,\n quantity: z.number().int().min(1).optional(),\n planId: z.number().int().optional(),\n }),\n annotations: { idempotentHint: true },\n }, ({ cartRef: ref, lineId, quantity, planId }) => run(async () => {\n const { creds, cope } = await openCart(ref)\n const cart = await cope.updateLine(creds.id, lineId, {\n ...(quantity !== undefined ? { quantity } : {}),\n ...(planId !== undefined ? { plan_id: planId } : {}),\n })\n return { cart: projectCart(cart) }\n }))\n\n server.registerTool('remove_line', {\n description: 'Remove a line from the cart.',\n inputSchema: z.object({ cartRef, lineId }),\n annotations: { destructiveHint: true },\n }, ({ cartRef: ref, lineId: id }) => run(async () => {\n const { creds, cope } = await openCart(ref)\n try {\n return { cart: projectCart(await cope.removeLine(creds.id, id)) }\n } catch (error) {\n // A 404 cannot tell a repeated remove from an id that was never a line, so\n // it is reported as what it is — not in the cart — and never as a removal.\n if (!hasCode(error, 'not_found')) throw error\n throw new CopeApiError(404, [{ code: 'line_not_in_cart', message: `No line ${id} in this cart` }])\n }\n }))\n\n server.registerTool('apply_promo_code', {\n description: 'Apply a promo code the buyer gave. Then call get_cart to see the discount.',\n inputSchema: z.object({ cartRef, code: z.string().min(1) }),\n annotations: { idempotentHint: true },\n }, ({ cartRef: ref, code }) => run(async () => {\n const { creds, cope } = await openCart(ref)\n return { cart: projectCart(await cope.applyPromoCode(creds.id, code)) }\n }, (error) => (error instanceof CopeApiError && error.status === 422 ? promoRefused(error) : null)))\n\n server.registerTool('remove_promo_code', {\n description: 'Remove the promo code from the cart.',\n inputSchema: z.object({ cartRef }),\n annotations: { idempotentHint: true },\n }, ({ cartRef: ref }) => run(async () => {\n const { creds, cope } = await openCart(ref)\n return { cart: projectCart(await cope.removePromoCode(creds.id)) }\n }))\n\n server.registerTool('set_buyer_identity', {\n description: 'Record who is buying and where, as the buyer stated it. Country and postal code drive tax. The buyer accepts terms on the checkout page, not here.',\n inputSchema: z.object({\n cartRef,\n email: z.string().email().optional(),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n country: z.string().length(2).optional().describe('ISO 3166-1 alpha-2'),\n postalCode: z.string().optional(),\n company: z.string().optional(),\n buyerType: z.enum(['b2b', 'b2c']).optional(),\n vatId: z.string().optional(),\n billingAddress: address.optional(),\n shippingAddress: address.optional(),\n }),\n annotations: { idempotentHint: true },\n }, (args) => run(async () => {\n const { creds, cope } = await openCart(args.cartRef)\n const toAddress = (a: z.infer<typeof address>) => ({\n line1: a.line1, line2: a.line2 ?? null, city: a.city, region: a.region ?? null,\n postal_code: a.postalCode, country: a.country.toUpperCase(),\n })\n const cart = await cope.setBuyerIdentity(creds.id, {\n ...(args.email !== undefined ? { email: args.email } : {}),\n ...(args.firstName !== undefined ? { first_name: args.firstName } : {}),\n ...(args.lastName !== undefined ? { last_name: args.lastName } : {}),\n ...(args.country !== undefined ? { country: args.country.toUpperCase() } : {}),\n ...(args.postalCode !== undefined ? { postal_code: args.postalCode } : {}),\n ...(args.company !== undefined ? { company: args.company } : {}),\n ...(args.buyerType !== undefined ? { buyer_type: args.buyerType } : {}),\n ...(args.vatId !== undefined ? { vat_id: args.vatId } : {}),\n ...(args.billingAddress ? { billing_address: toAddress(args.billingAddress) } : {}),\n ...(args.shippingAddress ? { shipping_address: toAddress(args.shippingAddress) } : {}),\n })\n return { cart: projectCart(cart) }\n }))\n\n server.registerTool('start_checkout', {\n description: 'Create the checkout and return the URL where the buyer reviews, gives the consents the cart needs and pays; buyerNext in the result says which. Calling it again returns the same checkout while it is open.',\n inputSchema: z.object({ cartRef }),\n annotations: { idempotentHint: true },\n }, ({ cartRef: ref }) => run(async () => {\n const { creds, cope } = await openCart(ref)\n const payload: CheckoutPayload = { success_url: ctx.checkout.successUrl, cancel_url: ctx.checkout.cancelUrl, consents: [] }\n const { checkout, cart } = await startCheckout(cope, creds, payload)\n return projectCheckout(checkout, cart.lines)\n }))\n}\n\n/**\n * Create the cart's checkout, or return the one already open, without keeping\n * any state between calls.\n *\n * Each attempt n uses the key `mcp-checkout:<cartId>:<n>` with an identical\n * body, and the cart API replays its stored answer for a key it has seen (24 h).\n * - An active cart walks the keys until a call actually opens a checkout: the\n * cart leaves `active`. A replay of a cancelled or expired checkout leaves it\n * active, so the walk moves on.\n * - A cart already in checkout scans every key and returns the newest replayed\n * checkout that has not expired. Keys are used in order, so the newest is the\n * highest-numbered one; expiry alone cannot tell, because a checkout the buyer\n * cancelled keeps its future expiry. The whole range is scanned because a\n * key used more than 24 h ago is re-run (refused, cart_not_active) rather than\n * replayed, so a refusal does not mark the end of the sequence.\n * - A key the API still holds as in flight (409, including one left behind by a\n * crashed request, which cope-core does not recover on this route) is skipped\n * once its waits run out, instead of blocking the cart.\n */\nasync function startCheckout(\n cope: Cope,\n creds: CartCredentials,\n payload: CheckoutPayload,\n): Promise<{ checkout: CheckoutResult; cart: Cart }> {\n const cart = await cope.getCart(creds.id)\n const inCheckout = cart.state === 'checkout_in_progress'\n let open: CheckoutResult | null = null\n\n for (let n = 0; n < MAX_CHECKOUT_KEYS; n++) {\n let result: CheckoutResult | null\n try {\n result = await checkoutOnce(cope, creds.id, payload, `mcp-checkout:${creds.id}:${n}`)\n } catch (error) {\n if (hasCode(error, 'idempotency_body_mismatch')) continue // key used with other settings\n if (inCheckout && hasCode(error, 'cart_not_active')) continue // unused, or re-run after 24 h\n throw error\n }\n if (result === null) continue // held in flight past our waits\n if (inCheckout) {\n if (Date.parse(result.expiresAt) > Date.now()) open = result\n continue\n }\n if ((await cope.getCart(creds.id)).state !== 'active') return { checkout: result, cart } // it opened a checkout\n }\n if (open) return { checkout: open, cart }\n if (inCheckout) {\n throw new CopeApiError(409, [{ code: 'checkout_not_recoverable', message: 'The open checkout expired or cannot be recovered' }])\n }\n throw new CopeApiError(409, [{ code: 'checkout_attempts_exhausted', message: 'Too many checkouts for this cart; start a new cart' }])\n}\n\n/** One checkout attempt; null when the key stays in flight past every wait. */\nasync function checkoutOnce(cope: Cope, cartId: string, payload: CheckoutPayload, key: string): Promise<CheckoutResult | null> {\n for (const wait of [...CONFLICT_WAITS_MS, null]) {\n try {\n return await cope.checkout(cartId, payload, { idempotencyKey: key })\n } catch (error) {\n if (!hasCode(error, 'idempotency_conflict')) throw error\n if (wait === null) return null\n await new Promise((resolve) => setTimeout(resolve, wait))\n }\n }\n return null\n}\n\nfunction hasCode(error: unknown, code: string): boolean {\n return error instanceof CopeApiError && error.code === code\n}\n","{\n \"name\": \"cope-sdk\",\n \"version\": \"0.1.1\",\n \"description\": \"Browser SDK for the COPE checkout API\",\n \"homepage\": \"https://docs.cope.com/checkout-sdk/overview\",\n \"type\": \"module\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"unpkg\": \"./dist/index.global.js\",\n \"jsdelivr\": \"./dist/index.global.js\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./mcp\": {\n \"types\": \"./dist/mcp.d.ts\",\n \"import\": \"./dist/mcp.js\",\n \"require\": \"./dist/mcp.cjs\"\n },\n \"./mcp/node\": {\n \"types\": \"./dist/mcp/node.d.ts\",\n \"import\": \"./dist/mcp/node.js\",\n \"require\": \"./dist/mcp/node.cjs\"\n }\n },\n \"sideEffects\": false,\n \"files\": [\n \"dist\",\n \"CHANGELOG.md\"\n ],\n \"scripts\": {\n \"build\": \"rm -rf dist && tsup && cp dist/index.global.js examples/cope-sdk.js\",\n \"dev\": \"tsup --watch\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc --noEmit --typeRoots ./node_modules/@types\",\n \"prepublishOnly\": \"npm run build\",\n \"size\": \"rm -rf dist && tsup && gzip -c dist/index.global.js | wc -c\"\n },\n \"devDependencies\": {\n \"@modelcontextprotocol/client\": \"2.1.0\",\n \"@modelcontextprotocol/node\": \"2.1.0\",\n \"@modelcontextprotocol/server\": \"2.1.0\",\n \"@types/node\": \"^22\",\n \"jsdom\": \"^30.0.1\",\n \"tsup\": \"^8.4.0\",\n \"typescript\": \"^5.9.0\",\n \"vitest\": \"^5.0.0\",\n \"zod\": \"^4.2.0\"\n },\n \"peerDependencies\": {\n \"@modelcontextprotocol/node\": \"^2.1.0\",\n \"@modelcontextprotocol/server\": \"^2.1.0\",\n \"zod\": \"^4.2.0\"\n },\n \"peerDependenciesMeta\": {\n \"@modelcontextprotocol/node\": {\n \"optional\": true\n },\n \"@modelcontextprotocol/server\": {\n \"optional\": true\n },\n \"zod\": {\n \"optional\": true\n }\n },\n \"engines\": {\n \"node\": \">=20\"\n },\n \"license\": \"MIT\"\n}\n","import {\n McpServer,\n createMcpHandler,\n hostHeaderValidationResponse,\n originValidationResponse,\n} from '@modelcontextprotocol/server'\nimport { createCartRefCodec, parseCartRefKeys } from './cart-ref.js'\nimport type { CartRefCodec } from './cart-ref.js'\nimport { createRateLimiter } from './rate-limit.js'\nimport { registerCheckoutTools } from './tools.js'\nimport { version } from '../../package.json'\n\nexport interface CopeMcpOptions {\n /** The store's publishable key (`cope_pk_...`), as for the browser SDK. */\n readonly publishableKey: string\n /**\n * Keys that encrypt the cartRef handed to agents: 32 random bytes each,\n * base64 or base64url (`generateCartRefKey()` makes one). Keep them secret.\n * The first encrypts; all decrypt, so add a new key first and retire an old\n * one later to rotate without breaking carts agents are holding.\n */\n readonly cartRefKeys: readonly string[]\n /** Where the checkout page sends the buyer. Must be on the store's registered redirect URLs. */\n readonly checkout: { readonly successUrl: string; readonly cancelUrl: string }\n /**\n * Host names this endpoint answers to (the `Host` header), e.g.\n * `['shop.example.com']`. Required: a server that answers any Host is open to\n * DNS rebinding from a buyer's browser.\n */\n readonly allowedHosts: readonly string[]\n /**\n * Browser origins allowed to call this endpoint, by host name. Agents calling\n * server-to-server send no Origin and are not affected. Default: none.\n */\n readonly allowedOrigins?: readonly string[]\n /**\n * Request limits, in memory and per process, or `false` to rely on your own.\n * `perClientPerMinute` (default 120) applies to each client that can be told\n * apart (see `clientKey`); `perStorePerMinute` (default 1200) caps the whole\n * endpoint, protecting the store's cart-API quota when clients cannot be.\n */\n readonly rateLimit?: false | { readonly perClientPerMinute?: number; readonly perStorePerMinute?: number }\n /**\n * How to tell clients apart for the per-client limit, e.g. from a trusted\n * proxy's header. A fetch-style Request carries no trustworthy client address,\n * so without this only the store-wide limit applies. The Node handler\n * (`cope-sdk/mcp/node`) uses the socket address by default.\n */\n readonly clientKey?: (request: Request) => string\n readonly baseUrl?: string\n readonly checkoutBaseUrl?: string\n /** Called with errors the handler swallowed (malformed requests, internal failures). */\n readonly onError?: (error: Error) => void\n}\n\nexport interface CopeMcpHandler {\n /** Serve one HTTP request: Bun, Deno, Cloudflare Workers, Next.js route handlers, Hono. */\n fetch(request: Request, clientKey?: string): Promise<Response>\n}\n\n// Bundled at build time (tsup inlines the one field), so the handshake reports the published version.\nconst SERVER_INFO = { name: 'cope-checkout', version }\n\nexport function createCopeMcpHandler(options: CopeMcpOptions): CopeMcpHandler {\n if (options.allowedHosts.length === 0) throw new Error('allowedHosts must name at least one host')\n // Refuse a bad key now, at startup, not on the first agent's request.\n parseCartRefKeys(options.cartRefKeys)\n let codec: Promise<CartRefCodec> | null = null\n const getCodec = () => (codec ??= createCartRefCodec(options.cartRefKeys, options.publishableKey))\n const limits = options.rateLimit === false ? null : {\n client: createRateLimiter(options.rateLimit?.perClientPerMinute ?? 120),\n store: createRateLimiter(options.rateLimit?.perStorePerMinute ?? 1200),\n }\n\n const mcp = createMcpHandler(async () => {\n const server = new McpServer(SERVER_INFO)\n registerCheckoutTools(server, {\n clientOptions: {\n publishableKey: options.publishableKey,\n ...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),\n ...(options.checkoutBaseUrl ? { checkoutBaseUrl: options.checkoutBaseUrl } : {}),\n },\n codec: await getCodec(),\n checkout: options.checkout,\n })\n return server\n }, { legacy: 'stateless', ...(options.onError ? { onerror: options.onError } : {}) })\n\n return {\n async fetch(request, clientKey) {\n const refused = hostHeaderValidationResponse(request, [...options.allowedHosts])\n ?? (request.headers.has('origin') ? originValidationResponse(request, [...(options.allowedOrigins ?? [])]) : undefined)\n if (refused) return refused\n\n if (limits) {\n const client = clientKey ?? options.clientKey?.(request)\n const retryAfter = (client === undefined ? null : limits.client.take(client)) ?? limits.store.take('store')\n if (retryAfter !== null) {\n return new Response(JSON.stringify({ error: 'rate_limited' }), {\n status: 429,\n headers: { 'Content-Type': 'application/json', 'Retry-After': String(retryAfter) },\n })\n }\n }\n return mcp.fetch(request)\n },\n }\n}\n"]}
|