@appfunnel-dev/sdk 2.0.0-canary.0 → 2.0.0-canary.10
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/README.md +1 -1
- package/dist/capabilities-Dq22RCr_.d.cts +180 -0
- package/dist/capabilities-Dq22RCr_.d.ts +180 -0
- package/dist/checkout-ClaO5IYV.d.ts +333 -0
- package/dist/checkout-DBp4bCpC.d.cts +333 -0
- package/dist/chunk-7JLOF6CJ.cjs +172 -0
- package/dist/chunk-7JLOF6CJ.cjs.map +1 -0
- package/dist/chunk-EMMSS5I5.cjs +37 -0
- package/dist/chunk-EMMSS5I5.cjs.map +1 -0
- package/dist/chunk-G3PMV62Z.js +33 -0
- package/dist/chunk-G3PMV62Z.js.map +1 -0
- package/dist/chunk-JAO6AA4R.js +99 -0
- package/dist/chunk-JAO6AA4R.js.map +1 -0
- package/dist/chunk-OXQBEKZ5.js +157 -0
- package/dist/chunk-OXQBEKZ5.js.map +1 -0
- package/dist/chunk-VV7TFC64.cjs +106 -0
- package/dist/chunk-VV7TFC64.cjs.map +1 -0
- package/dist/chunk-VW2HVPR4.js +446 -0
- package/dist/chunk-VW2HVPR4.js.map +1 -0
- package/dist/chunk-WYUDL4FI.cjs +8 -0
- package/dist/chunk-WYUDL4FI.cjs.map +1 -0
- package/dist/chunk-Y4YNJ2EX.cjs +476 -0
- package/dist/chunk-Y4YNJ2EX.cjs.map +1 -0
- package/dist/chunk-ZZJG4EYL.js +6 -0
- package/dist/chunk-ZZJG4EYL.js.map +1 -0
- package/dist/driver-paddle.cjs +817 -0
- package/dist/driver-paddle.cjs.map +1 -0
- package/dist/driver-paddle.d.cts +10 -0
- package/dist/driver-paddle.d.ts +10 -0
- package/dist/driver-paddle.js +814 -0
- package/dist/driver-paddle.js.map +1 -0
- package/dist/driver-stripe.cjs +2312 -0
- package/dist/driver-stripe.cjs.map +1 -0
- package/dist/driver-stripe.d.cts +24 -0
- package/dist/driver-stripe.d.ts +24 -0
- package/dist/driver-stripe.js +2305 -0
- package/dist/driver-stripe.js.map +1 -0
- package/dist/index.cjs +2654 -843
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +351 -1005
- package/dist/index.d.ts +351 -1005
- package/dist/index.js +2386 -704
- package/dist/index.js.map +1 -1
- package/dist/manifest-B3Tdab0M.d.cts +920 -0
- package/dist/manifest-B3Tdab0M.d.ts +920 -0
- package/dist/manifest-entry.cjs +408 -0
- package/dist/manifest-entry.cjs.map +1 -0
- package/dist/manifest-entry.d.cts +192 -0
- package/dist/manifest-entry.d.ts +192 -0
- package/dist/manifest-entry.js +270 -0
- package/dist/manifest-entry.js.map +1 -0
- package/dist/protocol.cjs +13 -0
- package/dist/protocol.cjs.map +1 -0
- package/dist/protocol.d.cts +182 -0
- package/dist/protocol.d.ts +182 -0
- package/dist/protocol.js +4 -0
- package/dist/protocol.js.map +1 -0
- package/package.json +49 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commerce/capabilities.ts"],"names":[],"mappings":";AAqBO,IAAM,eAAA,uBAAoD,GAAA,CAAqB;AAAA,EACpF,SAAA;AAAA,EACA,SAAA;AAAA,EACA;AACF,CAAC;AAEM,SAAS,gBAAgB,OAAA,EAAmC;AACjE,EAAA,OAAO,eAAA,CAAgB,IAAI,OAAO,CAAA;AACpC;AAyEA,IAAM,KAAwB,EAAE,QAAA,EAAU,MAAM,OAAA,EAAS,IAAA,EAAM,YAAY,UAAA,EAAW;AAEtF,IAAM,UAA6B,EAAE,QAAA,EAAU,MAAM,OAAA,EAAS,IAAA,EAAM,YAAY,aAAA,EAAc;AAE9F,IAAM,SAA4B,EAAE,QAAA,EAAU,MAAM,OAAA,EAAS,IAAA,EAAM,YAAY,aAAA,EAAc;AAY7F,IAAM,iBAAoC,EAAE,QAAA,EAAU,MAAM,OAAA,EAAS,IAAA,EAAM,YAAY,UAAA,EAAW;AAClG,IAAM,WAAA,GAA4B,CAAC,cAAA,EAAg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,KAAA,GAAuD,EAAC,EACzC;AACf,EAAA,MAAM,YAAY,KAAA,CAAM,SAAA,KAAc,aAAa,yBAAA,IAA6B,QAAA,KAAa,6BAA6B,QAAA,KAAa,kBAAA,CAAA;AACvI,EAAA,OAAO,EAAE,QAAA,EAAU,OAAA,EAAS,WAAA,EAAa,KAAA,CAAM,aAAa,SAAA,EAAU;AACxE","file":"chunk-OXQBEKZ5.js","sourcesContent":["/**\n * The provider capability matrix + checkout error taxonomy — the PURE half of the\n * checkout seam, extracted from checkout.tsx so it ships through the **manifest\n * entry** (no React): the API's publish validation, the editor, AI authoring, and\n * local dev all run the SAME checks the runtime primitives use (phase-3 §3.1b —\n * \"the SDK ships this as data\"). The React half (driver seam, `useCheckout`,\n * `<Checkout>`/`<Upsell>`) stays in ./checkout, which re-exports everything here.\n */\n\nexport type CheckoutSurface =\n | 'express' // wallet quick-buttons (Apple/Google Pay) — inline\n | 'element' // inline card form — inline\n | 'embedded' // provider-managed inline checkout — inline\n | 'sheet' // bottom-sheet popup — opens on click\n | 'popup' // provider-hosted overlay — opens on click\n | 'redirect' // provider-hosted page — opens on click\n\nexport type CheckoutProvider = 'stripe' | 'paddle' | 'whop' | 'primer' | 'solidgate'\nexport type CheckoutIntent = 'purchase' | 'upsell'\n\n/** Surfaces that render inline (vs. those that open on click). */\nexport const INLINE_SURFACES: ReadonlySet<CheckoutSurface> = new Set<CheckoutSurface>([\n 'express',\n 'element',\n 'embedded',\n])\n\nexport function isInlineSurface(surface: CheckoutSurface): boolean {\n return INLINE_SURFACES.has(surface)\n}\n\n/**\n * The kind of off-session upsell (researched against Funnelfox's changelog, which\n * ships these as distinct features). The discriminating real-world constraint is\n * **stacking a 2nd concurrent subscription** — Paddle can't, SolidGate/Stripe can.\n */\nexport type UpsellKind =\n | 'subscription' // charge a NEW, 2nd concurrent subscription off-session (stacking)\n | 'one-time' // charge a one-time add-on off-session\n | 'upgrade' // change the existing subscription's plan\n\n/** Reliability of an off-session upsell charge AFTER a purchase on a surface. */\nexport type OffSessionReliability =\n | 'reliable' // we hold the saved method (Stripe Elements / SolidGate) or the provider charges it (Paddle / Whop API)\n | 'conditional' // possible but may decline — Stripe **managed** checkout (vault charge, SCA not guaranteed) or an orchestrator's PSP-dependent routing (Primer)\n | 'none'\n\nexport interface SurfaceCapability {\n purchase: boolean\n /** Apple/Google Pay available on this surface. */\n wallets: boolean\n /** Reliability of an off-session upsell after a purchase on this surface. */\n offSession: OffSessionReliability\n /**\n * Per-surface DRIVER readiness. Absent = renderable now (the provider's driver mounts it).\n * `'planned'` = the provider genuinely ships this surface (cite it in the profile) but OUR\n * driver doesn't render it yet — publish validation FAILS CLOSED on it so we never promise a\n * surface the runtime can't produce. Mirrors the provider-level {@link ProviderProfile.status}\n * seam at surface granularity: implement the driver, drop the flag, and it flips on cleanly.\n */\n driver?: 'planned'\n}\n\n/**\n * How a provider composes a TRIAL — the scattered provider `if`s made a matrix dimension\n * (§7 item 4). Stripe trials are **composed** (a separate fee/vault step precedes the sub);\n * Paddle trials are **native** (the price itself carries the trial, MoR collects up front):\n * - `paid_composed` — Stripe: trial-fee PaymentIntent → subscription with `trial_period_days`.\n * - `free_vault` — Stripe: SetupIntent vaults the card (no charge) → trial subscription.\n * - `paid_native` — Paddle: the price carries the paid trial; one item, collected up front.\n * - `free_native` — Paddle: native free trial on the price.\n * A provider with an EMPTY `trialShapes` can't run a trial offer (planned providers → fail closed).\n */\nexport type TrialShape = 'paid_composed' | 'free_vault' | 'paid_native' | 'free_native'\n\nexport interface ProviderProfile {\n /** Merchant-of-Record (handles tax/compliance) vs. a PSP you settle through. */\n isMoR: boolean\n /** Upsell kinds this provider can charge off-session (one-click, no re-entry). */\n offSessionUpsells: UpsellKind[]\n /** Who charges the saved method off-session: you (PSP) or the provider (MoR/managed). */\n tokenModel: 'merchant' | 'provider'\n /** Routes across multiple processors (Primer; SolidGate also offers this) vs. a single acquirer. */\n orchestrator: boolean\n /**\n * Driver tier (Wave-4 decision, Simon 2026-07-02): `full` = a real driver ships\n * (Stripe, Paddle); `planned` = profile only — authoring/publish validate against\n * it, but no charge path exists yet (Whop, Primer, SolidGate). A new provider\n * becomes buildable by writing a driver; its profile already gates what authors\n * can express, so funnels written today stay valid when the driver lands.\n */\n status: 'full' | 'planned'\n /**\n * TRIAL shapes this provider can run (§7 item 4). Empty = no trial path (fail closed at\n * publish — a paid/free-trial funnel on this provider can't be produced yet).\n */\n trialShapes: TrialShape[]\n /** Supported surfaces → per-surface capabilities. **Absent = not supported.** */\n surfaces: Partial<Record<CheckoutSurface, SurfaceCapability>>\n}\n\n/** Reliable off-session after this surface (we/the provider hold a chargeable method). */\nconst ON: SurfaceCapability = { purchase: true, wallets: true, offSession: 'reliable' }\n/** Stripe-managed checkout: a purchase works, but the off-session upsell may decline. */\nconst MANAGED: SurfaceCapability = { purchase: true, wallets: true, offSession: 'conditional' }\n/** Orchestrator-routed (Primer): off-session depends on which PSP vaulted the method. */\nconst ROUTED: SurfaceCapability = { purchase: true, wallets: true, offSession: 'conditional' }\n/**\n * Paddle **Express Checkout** (Apple-Pay-first mobile variant of Paddle.js checkout, shipped\n * 2026-04-27 — https://developer.paddle.com/changelog/2026/apple-pay-express-checkout/). Paddle\n * genuinely offers it (MoR, so it's their hosted/inline frame surfaced wallet-first, NOT a raw\n * wallet element in our UI), which is why it's a distinct `express` surface here rather than only\n * the `wallets` flag already true on Paddle's embedded/popup. RENDERABLE as of 2026-07-19:\n * drivers/paddle.tsx opens the inline frame with `settings.variant: 'express'` (verified against\n * `@paddle/paddle-js@1.6.4` — `CheckoutSettings.variant: 'multi-page' | 'one-page' | 'express'` +\n * the changelog's `displayMode: 'inline'` requirement), so the `driver: 'planned'` flag is dropped\n * and publish no longer fails it closed. Off-session stays reliable (provider-token, MoR).\n */\nconst PADDLE_EXPRESS: SurfaceCapability = { purchase: true, wallets: true, offSession: 'reliable' }\nconst ALL_UPSELLS: UpsellKind[] = ['subscription', 'one-time', 'upgrade']\n\n/**\n * Provider capabilities (researched 2026-06-23 against provider docs + Funnelfox;\n * trial mechanics re-verified 2026-07-02, doc 09 §4.4).\n *\n * Three real-world corrections to the naive model:\n * 1. **Off-session upsell support is per-provider by *kind*** (`offSessionUpsells`):\n * Paddle can't stack a 2nd concurrent subscription (upgrade + one-time only);\n * Stripe/SolidGate/Whop/Primer can do all kinds.\n * 2. **Off-session *reliability* varies by the paywall surface** (`SurfaceCapability.\n * offSession`): Stripe **managed** checkout (`embedded`/`redirect`) upsells as a\n * direct charge against Stripe's vault → `conditional` (may decline); Elements\n * surfaces are `reliable`. Primer is `conditional` everywhere (PSP-dependent).\n * 3. **Surface availability is a hard constraint.** MoR/managed providers can't\n * expose a raw card field to your own UI: Paddle has no `express`/`element`/your\n * `sheet`; Whop has no raw `element`/`express`; Primer has no hosted `redirect`;\n * Stripe/SolidGate have no `popup`. A missing entry means \"not possible.\"\n */\nexport const PROVIDER_PROFILES: Record<CheckoutProvider, ProviderProfile> = {\n // PSP; you hold the PaymentMethod and fire your own off-session PaymentIntent on\n // the Elements surfaces (reliable). **Managed** Checkout (`embedded`/`redirect`)\n // upsells too, but as a direct charge against Stripe's vaulted card → conditional.\n // No provider \"popup\" surface.\n stripe: {\n isMoR: false, offSessionUpsells: ALL_UPSELLS, tokenModel: 'merchant', orchestrator: false, status: 'full',\n // Composed trials: paid = fee PaymentIntent + sub (trial_period_days); free = SetupIntent vault\n // + trial sub (services/checkout/stripe-trial.ts).\n trialShapes: ['paid_composed', 'free_vault'],\n surfaces: { express: ON, element: ON, sheet: ON, embedded: MANAGED, redirect: MANAGED },\n },\n // Merchant-of-Record; raw card entry is always Paddle's frame → no own element/sheet.\n // `express` is present AND renderable (Apple-Pay-first Express Checkout, shipped 2026-04-27 —\n // PADDLE_EXPRESS; the driver opens the inline frame with `variant: 'express'`).\n // Off-session via subscription one-time charge / collection_mode, but **no 2nd concurrent\n // subscription** (upgrade + one-time only), provider-initiated.\n paddle: {\n isMoR: true, offSessionUpsells: ['one-time', 'upgrade'], tokenModel: 'provider', orchestrator: false, status: 'full',\n // Native trials: the price itself carries the trial, Paddle collects up front / vaults\n // (services/checkout/paddle-checkout.ts — \"Paddle paid trials are NATIVE\").\n trialShapes: ['paid_native', 'free_native'],\n surfaces: { embedded: ON, popup: ON, redirect: ON, express: PADDLE_EXPRESS },\n },\n // Merchant-of-Record; iframe-only (no raw card field). Off-session works\n // (provider-initiated, async via webhooks). `sheet` = our chrome hosting their embed.\n // Trial shape not yet researched → empty (fail closed until the driver + profile land).\n whop: {\n isMoR: true, offSessionUpsells: ALL_UPSELLS, tokenModel: 'provider', orchestrator: false, status: 'planned',\n trialShapes: [],\n surfaces: { embedded: ON, redirect: ON, sheet: ON },\n },\n // Pure orchestrator (PSP-side); Headless renders express/element/sheet/embedded.\n // No hosted redirect page, no popup checkout. Off-session is PSP-conditional —\n // the vault lives with whichever processor Primer routed to (data matches this\n // comment as of 2026-07-02; it previously said conditional but coded reliable).\n primer: {\n isMoR: false, offSessionUpsells: ALL_UPSELLS, tokenModel: 'merchant', orchestrator: true, status: 'planned',\n trialShapes: [],\n surfaces: { express: ROUTED, element: ROUTED, sheet: ROUTED, embedded: ROUTED },\n },\n // PSP **and** orchestrator (own acquiring + connectors routing across Stripe/Adyen/\n // PayPal). One Payment Form (element/sheet/embedded) + hosted page + wallet button.\n // Strong native off-session (Recurring API). No popup.\n solidgate: {\n isMoR: false, offSessionUpsells: ALL_UPSELLS, tokenModel: 'merchant', orchestrator: true, status: 'planned',\n trialShapes: [],\n surfaces: { express: ON, element: ON, sheet: ON, embedded: ON, redirect: ON },\n },\n}\n\nexport interface ValidationResult {\n ok: boolean\n reason?: string\n /** Non-fatal caveat (e.g. Paddle upgrade-only). */\n note?: string\n}\n\n// ── Surface preference resolution (§7 item 3 — wallet-first is a funnel INTENT) ──\n\n/** Device class the surface resolver picks against — mobile gets the wallet-first surface. */\nexport type DeviceClass = 'mobile' | 'desktop'\n\n/**\n * What an author writes on `<Checkout surface>`: either a concrete {@link CheckoutSurface} (pinned,\n * validated as today) or `'auto'` — a declarative \"give me the best surface for this store's\n * provider and this device\". The platform resolves `'auto'` to a concrete surface via\n * {@link resolveSurface}; `'auto'` never crosses the checkout wire (the client resolves first, the\n * server re-validates the concrete surface through {@link validateCheckout}).\n */\nexport type SurfacePreference = 'auto' | CheckoutSurface\n\n/**\n * Preference order for `surface=\"auto\"` per device class. MOBILE is wallet-FIRST (express, then the\n * wallet-bearing inline frame, then a raw card field); DESKTOP prefers the inline card\n * field/embedded frame (a wallet button is a phone affordance). Both are filtered to what the\n * provider offers AND our driver can render NOW (see {@link isRenderableSurface}), so `'auto'` never\n * resolves to a surface the runtime can't produce.\n */\nconst AUTO_SURFACE_ORDER: Record<DeviceClass, readonly CheckoutSurface[]> = {\n mobile: ['express', 'embedded', 'element', 'sheet', 'popup', 'redirect'],\n desktop: ['element', 'embedded', 'express', 'sheet', 'redirect', 'popup'],\n}\n\n/** A surface the provider offers, can take a purchase on, AND our driver renders now (not `'planned'`). */\nexport function isRenderableSurface(provider: CheckoutProvider, surface: CheckoutSurface): boolean {\n const cap = PROVIDER_PROFILES[provider]?.surfaces[surface]\n return !!cap && cap.purchase && cap.driver !== 'planned'\n}\n\n/** The provider's renderable purchase surfaces (drives the `'auto'` fallbacks + the publish gate). */\nexport function renderableSurfaces(provider: CheckoutProvider): CheckoutSurface[] {\n return surfacesFor(provider).filter((s) => isRenderableSurface(provider, s))\n}\n\n/**\n * Resolve a {@link SurfacePreference} to the concrete surface the runtime will actually mount, for a\n * given provider and device class (§7 item 3). PURE — the client resolves once per mount and puts the\n * result on the wire (the wire stays surface-literal; the server re-validates via {@link\n * validateCheckout}), and the publish gate resolves it the same way. Deterministic:\n *\n * - an EXPLICIT surface resolves to ITSELF — the author's pin is never silently rewritten (an\n * unsupported pin, e.g. `express` on a provider that can't render it, is caught by\n * `validateCheckout` at publish, exactly as today);\n * - `'auto'` → mobile picks the provider's best wallet-first RENDERABLE surface (express where the\n * driver ships it, else the best inline/embedded frame); desktop picks the inline card\n * field/embedded frame. Only driver-ready surfaces are considered, so the result always renders.\n *\n * Totality guard: a provider with NO driver-ready surface (every surface `'planned'`, or unknown\n * provider) falls back to its first declared surface (unknown → a nominal default) so the function is\n * total; downstream `validateCheckout`/flow-select then fail that closed. In practice `'auto'` is only\n * authored on a funnel's ONE resolved (full-status) provider, which always has a renderable surface.\n */\nexport function resolveSurface(\n provider: CheckoutProvider,\n preference: SurfacePreference,\n deviceClass: DeviceClass,\n): CheckoutSurface {\n // Explicit pin → itself (validated elsewhere; never rewritten).\n if (preference !== 'auto') return preference\n for (const surface of AUTO_SURFACE_ORDER[deviceClass]) {\n if (isRenderableSurface(provider, surface)) return surface\n }\n // No driver-ready surface — keep total; downstream validation fails it closed.\n const declared = surfacesFor(provider)\n return declared[0] ?? (deviceClass === 'mobile' ? 'express' : 'element')\n}\n\n/** Surfaces a provider supports, for the editor/AI to steer authors. */\nexport function surfacesFor(provider: CheckoutProvider): CheckoutSurface[] {\n return Object.keys(PROVIDER_PROFILES[provider]?.surfaces ?? {}) as CheckoutSurface[]\n}\n\n/** Whether a provider is a Merchant of Record (it owns tax/compliance). */\nexport function isMerchantOfRecord(provider: CheckoutProvider): boolean {\n return PROVIDER_PROFILES[provider]?.isMoR ?? false\n}\n\n/** Whether a provider routes across multiple processors (Primer, SolidGate). */\nexport function isOrchestrator(provider: CheckoutProvider): boolean {\n return PROVIDER_PROFILES[provider]?.orchestrator ?? false\n}\n\n/**\n * Validate a (provider, surface) for a **purchase**: the surface must exist for\n * the provider and accept a payment. Surface availability is the real constraint\n * (e.g. Paddle has no `element`).\n */\nexport function validateCheckout(provider: CheckoutProvider, surface: CheckoutSurface): ValidationResult {\n const cap = PROVIDER_PROFILES[provider]?.surfaces[surface]\n if (!cap) return { ok: false, reason: `${provider} has no '${surface}' surface` }\n if (!cap.purchase) return { ok: false, reason: `'${surface}' can't take a purchase on ${provider}` }\n // The provider offers this surface but our driver can't render it yet (e.g. Paddle Express\n // Checkout) → fail closed so publish never promises a surface the runtime can't produce.\n if (cap.driver === 'planned') return { ok: false, reason: `${provider} '${surface}' checkout isn't renderable yet (the provider ships it, but our driver doesn't render it)` }\n return { ok: true }\n}\n\n/** Trial shapes a provider can compose (empty = it can't run a trial offer yet). */\nexport function trialShapesFor(provider: CheckoutProvider): TrialShape[] {\n return PROVIDER_PROFILES[provider]?.trialShapes ?? []\n}\n\n/**\n * Validate that a provider can run a TRIAL (§7 item 4). Pass a specific {@link TrialShape} to\n * check that exact shape; omit it to assert the provider supports *any* trial (the cheap gate\n * check when only the offering's TRIAL-role binding existence is known). A provider with no\n * trial shapes (every planned provider) fails closed.\n */\nexport function validateTrial(provider: CheckoutProvider, shape?: TrialShape): ValidationResult {\n const profile = PROVIDER_PROFILES[provider]\n if (!profile) return { ok: false, reason: `unknown provider '${provider}'` }\n const shapes = profile.trialShapes\n if (shapes.length === 0) return { ok: false, reason: `${provider} can't run a trial offer yet` }\n if (shape && !shapes.includes(shape)) {\n return { ok: false, reason: `${provider} doesn't support a '${shape}' trial (it supports: ${shapes.join(', ')})` }\n }\n return { ok: true }\n}\n\n/**\n * Validate an **off-session upsell** of `kind` after a purchase made on\n * `paywallSurface`. Combines provider support for the kind (Paddle can't stack a\n * 2nd subscription) with the paywall surface's off-session reliability (Stripe\n * managed checkout is `conditional` — returned as a `note`, not a hard block).\n */\nexport function validateUpsell(\n provider: CheckoutProvider,\n paywallSurface: CheckoutSurface,\n kind: UpsellKind = 'subscription',\n): ValidationResult {\n const profile = PROVIDER_PROFILES[provider]\n if (!profile) return { ok: false, reason: `unknown provider '${provider}'` }\n if (!profile.offSessionUpsells.includes(kind)) {\n const can = profile.offSessionUpsells.length ? ` (it supports: ${profile.offSessionUpsells.join(', ')})` : ''\n return { ok: false, reason: `${provider} can't charge a '${kind}' upsell off-session${can}` }\n }\n const cap = profile.surfaces[paywallSurface]\n if (!cap) return { ok: false, reason: `${provider} has no '${paywallSurface}' surface to upsell after` }\n if (cap.offSession === 'none') {\n return { ok: false, reason: `a purchase on '${paywallSurface}' retains no chargeable method for an upsell` }\n }\n if (cap.offSession === 'conditional') {\n return { ok: true, note: `off-session upsell after ${provider} '${paywallSurface}' may decline — prefer a reliable surface or wire an on-session fallback` }\n }\n return { ok: true }\n}\n\n// ── Checkout error taxonomy (pure — drivers + server both normalize into it) ──\n\n/**\n * Normalized failure category — the driver/platform maps each provider's decline\n * codes into one of these so funnels can route/recover by reason. `authentication_\n * required` (3DS/SCA) and `requires_payment_method` are the cases an **off-session**\n * upsell can't satisfy → recover on-session (re-collect a card).\n */\nexport type CheckoutErrorCategory =\n | 'card_declined'\n | 'insufficient_funds'\n | 'expired_card'\n | 'prepaid_card' // card funding is prepaid — trials/subscriptions commonly decline; route to a real-card recapture page\n | 'authentication_required' // SCA/3DS needed — off-session can't challenge\n | 'requires_payment_method' // no usable saved method\n | 'processing_error'\n | 'canceled'\n | 'unknown'\n\nexport interface CheckoutError {\n category: CheckoutErrorCategory\n message: string\n /** Raw provider decline code, if any (e.g. Stripe `card_declined`/`insufficient_funds`). */\n declineCode?: string\n /** Whether re-attempting (e.g. an on-session re-collection) may succeed. */\n retryable: boolean\n}\n\n/** Build a {@link CheckoutError} (driver/test helper). */\nexport function checkoutError(\n category: CheckoutErrorCategory,\n message: string,\n extra: { declineCode?: string; retryable?: boolean } = {},\n): CheckoutError {\n const retryable = extra.retryable ?? (category === 'authentication_required' || category === 'requires_payment_method' || category === 'processing_error')\n return { category, message, declineCode: extra.declineCode, retryable }\n}\n"]}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var chunk7JLOF6CJ_cjs = require('./chunk-7JLOF6CJ.cjs');
|
|
4
|
+
|
|
5
|
+
// src/drivers/wire.ts
|
|
6
|
+
function endpoint(ctx, path = "") {
|
|
7
|
+
const base = ctx.apiBase.replace(/\/+$/, "");
|
|
8
|
+
return `${base}/campaign/${encodeURIComponent(ctx.campaignId)}/v2/checkout${path}`;
|
|
9
|
+
}
|
|
10
|
+
async function postJson(url, body) {
|
|
11
|
+
const res = await fetch(url, {
|
|
12
|
+
method: "POST",
|
|
13
|
+
headers: { "content-type": "application/json" },
|
|
14
|
+
body: JSON.stringify(body)
|
|
15
|
+
});
|
|
16
|
+
if (!res.ok) throw chunk7JLOF6CJ_cjs.checkoutError("processing_error", `checkout request failed (HTTP ${res.status})`);
|
|
17
|
+
return await res.json();
|
|
18
|
+
}
|
|
19
|
+
function toCheckoutError(e) {
|
|
20
|
+
if (e && typeof e === "object" && "category" in e && "message" in e && "retryable" in e) {
|
|
21
|
+
return e;
|
|
22
|
+
}
|
|
23
|
+
return chunk7JLOF6CJ_cjs.checkoutError("processing_error", e instanceof Error ? e.message : "Checkout request failed");
|
|
24
|
+
}
|
|
25
|
+
function postSession(ctx, req, correlationId) {
|
|
26
|
+
const body = {
|
|
27
|
+
funnelId: ctx.funnelId,
|
|
28
|
+
mode: ctx.mode,
|
|
29
|
+
// The CHARGE identity is the catalog key (resolved from the slot by driverWithCatalog); fall back
|
|
30
|
+
// to `product` for legacy builds where the page named the catalog key directly.
|
|
31
|
+
productKey: req.catalogKey ?? req.product,
|
|
32
|
+
intent: req.intent,
|
|
33
|
+
kind: req.kind,
|
|
34
|
+
// null (not absent) = explicit off-session — the server validates surfaces
|
|
35
|
+
// against the capability matrix, so never let one default in transit.
|
|
36
|
+
surface: req.surface ?? null,
|
|
37
|
+
sessionId: ctx.sessionId ?? void 0,
|
|
38
|
+
visitorId: ctx.visitorId ?? void 0,
|
|
39
|
+
// Buyer email collected by the funnel (user.email) — Stripe Customer creation,
|
|
40
|
+
// receipts, Paddle prefill. Injected at attempt time by the FunnelProvider seam.
|
|
41
|
+
email: req.email,
|
|
42
|
+
correlationId
|
|
43
|
+
};
|
|
44
|
+
return postJson(endpoint(ctx), body);
|
|
45
|
+
}
|
|
46
|
+
function postComplete(ctx, correlationId, providerRef) {
|
|
47
|
+
const body = { providerRef };
|
|
48
|
+
return postJson(
|
|
49
|
+
endpoint(ctx, `/${encodeURIComponent(correlationId)}/complete`),
|
|
50
|
+
body
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
function settlementToResult(s) {
|
|
54
|
+
return { ok: true, amountMinor: s.amountMinor, currency: s.currency, eventId: s.eventId };
|
|
55
|
+
}
|
|
56
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
57
|
+
async function completeWithPoll(ctx, correlationId, opts = {}) {
|
|
58
|
+
const attempts = opts.attempts ?? 5;
|
|
59
|
+
const intervalMs = opts.intervalMs ?? 2e3;
|
|
60
|
+
try {
|
|
61
|
+
for (let i = 0; i < attempts; i++) {
|
|
62
|
+
const res = await postComplete(ctx, correlationId, opts.providerRef);
|
|
63
|
+
if (res.step === "settled") return settlementToResult(res.result);
|
|
64
|
+
if (res.step === "failed") return { ok: false, error: res.error };
|
|
65
|
+
if (i < attempts - 1) await sleep(intervalMs);
|
|
66
|
+
}
|
|
67
|
+
} catch (e) {
|
|
68
|
+
return { ok: false, error: toCheckoutError(e) };
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
ok: false,
|
|
72
|
+
error: chunk7JLOF6CJ_cjs.checkoutError(
|
|
73
|
+
"processing_error",
|
|
74
|
+
opts.timeoutMessage ?? "The payment has not been confirmed yet \u2014 please check back shortly.",
|
|
75
|
+
// `completion_timeout` marks "the poll ran out while the attempt was still
|
|
76
|
+
// pending" — drivers key double-charge guards on it (the attempt may still
|
|
77
|
+
// settle server-side; it was never refused).
|
|
78
|
+
{ retryable: true, declineCode: "completion_timeout" }
|
|
79
|
+
)
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function leaveForRedirect(url) {
|
|
83
|
+
return new Promise((resolve) => {
|
|
84
|
+
if (typeof window !== "undefined") {
|
|
85
|
+
const onPageshow = (event) => {
|
|
86
|
+
if (!event.persisted) return;
|
|
87
|
+
window.removeEventListener("pageshow", onPageshow);
|
|
88
|
+
resolve({
|
|
89
|
+
ok: false,
|
|
90
|
+
error: chunk7JLOF6CJ_cjs.checkoutError("canceled", "Returned from the hosted checkout without completing")
|
|
91
|
+
});
|
|
92
|
+
};
|
|
93
|
+
window.addEventListener("pageshow", onPageshow);
|
|
94
|
+
}
|
|
95
|
+
window.location.assign(url);
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
exports.completeWithPoll = completeWithPoll;
|
|
100
|
+
exports.leaveForRedirect = leaveForRedirect;
|
|
101
|
+
exports.postComplete = postComplete;
|
|
102
|
+
exports.postSession = postSession;
|
|
103
|
+
exports.settlementToResult = settlementToResult;
|
|
104
|
+
exports.toCheckoutError = toCheckoutError;
|
|
105
|
+
//# sourceMappingURL=chunk-VV7TFC64.cjs.map
|
|
106
|
+
//# sourceMappingURL=chunk-VV7TFC64.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/drivers/wire.ts"],"names":["checkoutError"],"mappings":";;;;;AAqBA,SAAS,QAAA,CAAS,GAAA,EAA4B,IAAA,GAAO,EAAA,EAAY;AAC/D,EAAA,MAAM,IAAA,GAAO,GAAA,CAAI,OAAA,CAAQ,OAAA,CAAQ,QAAQ,EAAE,CAAA;AAC3C,EAAA,OAAO,CAAA,EAAG,IAAI,CAAA,UAAA,EAAa,kBAAA,CAAmB,IAAI,UAAU,CAAC,eAAe,IAAI,CAAA,CAAA;AAClF;AAEA,eAAe,QAAA,CAAY,KAAa,IAAA,EAA2B;AACjE,EAAA,MAAM,GAAA,GAAM,MAAM,KAAA,CAAM,GAAA,EAAK;AAAA,IAC3B,MAAA,EAAQ,MAAA;AAAA,IACR,OAAA,EAAS,EAAE,cAAA,EAAgB,kBAAA,EAAmB;AAAA,IAC9C,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,IAAI;AAAA,GAC1B,CAAA;AAGD,EAAA,IAAI,CAAC,IAAI,EAAA,EAAI,MAAMA,gCAAc,kBAAA,EAAoB,CAAA,8BAAA,EAAiC,GAAA,CAAI,MAAM,C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;AAAA,MACA,KAAK,cAAA,IAAkB,0EAAA;AAAA;AAAA;AAAA;AAAA,MAIvB,EAAE,SAAA,EAAW,IAAA,EAAM,WAAA,EAAa,oBAAA;AAAqB;AACvD,GACF;AACF;AAkBO,SAAS,iBAAiB,GAAA,EAAsC;AACrE,EAAA,OAAO,IAAI,OAAA,CAAwB,CAAC,OAAA,KAAY;AAC9C,IAAA,IAAI,OAAO,WAAW,WAAA,EAAa;AACjC,MAAA,MAAM,UAAA,GAAa,CAAC,KAAA,KAA+B;AACjD,QAAA,IAAI,CAAC,MAAM,SAAA,EAAW;AACtB,QAAA,MAAA,CAAO,mBAAA,CAAoB,YAAY,UAAU,CAAA;AACjD,QAAA,OAAA,CAAQ;AAAA,UACN,EAAA,EAAI,KAAA;AAAA,UACJ,KAAA,EAAOA,+BAAA,CAAc,UAAA,EAAY,sDAAsD;AAAA,SACxF,CAAA;AAAA,MACH,CAAA;AACA,MAAA,MAAA,CAAO,gBAAA,CAAiB,YAAY,UAAU,CAAA;AAAA,IAChD;AACA,IAAA,MAAA,CAAO,QAAA,CAAS,OAAO,GAAG,CAAA;AAAA,EAC5B,CAAC,CAAA;AACH","file":"chunk-VV7TFC64.cjs","sourcesContent":["/**\n * Shared wire plumbing for the checkout drivers — the CLIENT half of the v2\n * checkout contract (commerce/checkout-api.ts). Lives under drivers/ (not\n * commerce/) on purpose: it ships only inside the `driver-*` subpath entries,\n * so the core funnel entry never bundles a checkout fetch — the core SDK talks\n * to a {@link CheckoutDriver}, never to the wire.\n *\n * Only `import type` from commerce/checkout(.tsx) here — a runtime import would\n * drag the React checkout primitives into every driver chunk. The one runtime\n * dependency is the pure error taxonomy (capabilities.ts).\n */\nimport type {\n CheckoutCompleteRequest,\n CheckoutCompleteResponse,\n CheckoutSessionRequest,\n CheckoutSessionResponse,\n CheckoutSettlement,\n} from '../commerce/checkout-api'\nimport type { CheckoutDriverContext, CheckoutRequest, CheckoutResult } from '../commerce/checkout'\nimport { checkoutError, type CheckoutError } from '../commerce/capabilities'\n\nfunction endpoint(ctx: CheckoutDriverContext, path = ''): string {\n const base = ctx.apiBase.replace(/\\/+$/, '')\n return `${base}/campaign/${encodeURIComponent(ctx.campaignId)}/v2/checkout${path}`\n}\n\nasync function postJson<T>(url: string, body: unknown): Promise<T> {\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n })\n // The contract speaks in `step` responses, not HTTP errors — a non-2xx means the\n // request never reached the checkout service properly (proxy, deploy, outage).\n if (!res.ok) throw checkoutError('processing_error', `checkout request failed (HTTP ${res.status})`)\n return (await res.json()) as T\n}\n\n/** Normalize any thrown value into the taxonomy (network drops → `processing_error`). */\nexport function toCheckoutError(e: unknown): CheckoutError {\n if (e && typeof e === 'object' && 'category' in e && 'message' in e && 'retryable' in e) {\n return e as CheckoutError\n }\n return checkoutError('processing_error', e instanceof Error ? e.message : 'Checkout request failed')\n}\n\n/**\n * Open a checkout attempt: `POST {apiBase}/campaign/{campaignId}/v2/checkout`.\n * The correlationId is client-minted per ATTEMPT (idempotency key + the id the\n * server stamps into provider metadata) — mint it once, reuse it on retries.\n */\nexport function postSession(\n ctx: CheckoutDriverContext,\n req: CheckoutRequest,\n correlationId: string,\n): Promise<CheckoutSessionResponse> {\n const body: CheckoutSessionRequest = {\n funnelId: ctx.funnelId,\n mode: ctx.mode,\n // The CHARGE identity is the catalog key (resolved from the slot by driverWithCatalog); fall back\n // to `product` for legacy builds where the page named the catalog key directly.\n productKey: req.catalogKey ?? req.product,\n intent: req.intent,\n kind: req.kind,\n // null (not absent) = explicit off-session — the server validates surfaces\n // against the capability matrix, so never let one default in transit.\n surface: req.surface ?? null,\n sessionId: ctx.sessionId ?? undefined,\n visitorId: ctx.visitorId ?? undefined,\n // Buyer email collected by the funnel (user.email) — Stripe Customer creation,\n // receipts, Paddle prefill. Injected at attempt time by the FunnelProvider seam.\n email: req.email,\n correlationId,\n }\n return postJson<CheckoutSessionResponse>(endpoint(ctx), body)\n}\n\n/** Ask the server to VERIFY with the provider and write the money facts (idempotent). */\nexport function postComplete(\n ctx: CheckoutDriverContext,\n correlationId: string,\n providerRef?: string,\n): Promise<CheckoutCompleteResponse> {\n const body: CheckoutCompleteRequest = { providerRef }\n return postJson<CheckoutCompleteResponse>(\n endpoint(ctx, `/${encodeURIComponent(correlationId)}/complete`),\n body,\n )\n}\n\n/** Server settlement → the SDK's CheckoutResult (eventId passes through for pixel dedup). */\nexport function settlementToResult(s: CheckoutSettlement): CheckoutResult {\n return { ok: true, amountMinor: s.amountMinor, currency: s.currency, eventId: s.eventId }\n}\n\nexport interface CompletePollOptions {\n providerRef?: string\n /** Total complete attempts before giving up (default 5). */\n attempts?: number\n /** Delay between attempts (default 2000ms). */\n intervalMs?: number\n /** Error message when the provider hasn't confirmed inside the window (MoR/async). */\n timeoutMessage?: string\n}\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\n\n/**\n * Complete with a bounded poll. Sync providers (Stripe) settle on the first\n * attempt — the server verifies against the provider inline. MoR/async providers\n * (Paddle) settle via webhook, so `pending` is normal: re-poll a few times, then\n * stop holding the UI hostage — the charge may still land server-side, which is\n * why the timeout error is `retryable` and the message should say the receipt\n * can still arrive (the server's money facts don't depend on this browser).\n */\nexport async function completeWithPoll(\n ctx: CheckoutDriverContext,\n correlationId: string,\n opts: CompletePollOptions = {},\n): Promise<CheckoutResult> {\n const attempts = opts.attempts ?? 5\n const intervalMs = opts.intervalMs ?? 2000\n try {\n for (let i = 0; i < attempts; i++) {\n const res = await postComplete(ctx, correlationId, opts.providerRef)\n if (res.step === 'settled') return settlementToResult(res.result)\n if (res.step === 'failed') return { ok: false, error: res.error }\n if (i < attempts - 1) await sleep(intervalMs)\n }\n } catch (e) {\n return { ok: false, error: toCheckoutError(e) }\n }\n return {\n ok: false,\n error: checkoutError(\n 'processing_error',\n opts.timeoutMessage ?? 'The payment has not been confirmed yet — please check back shortly.',\n // `completion_timeout` marks \"the poll ran out while the attempt was still\n // pending\" — drivers key double-charge guards on it (the attempt may still\n // settle server-side; it was never refused).\n { retryable: true, declineCode: 'completion_timeout' },\n ),\n }\n}\n\n/**\n * The `redirect` step hand-off: navigate to the provider-hosted page and return a\n * promise that settles ONLY if the buyer comes back to this very page. The page\n * is leaving — resolving early would fire `purchase.complete`/navigation for a\n * charge that hasn't happened, and rejecting would flash an error during the\n * (successful) hand-off — so while the navigation proceeds the promise stays\n * pending and `useCheckout` stays in `loading`, the truthful UI for a page\n * mid-navigation. The hosted page's SUCCESS return URL re-enters the funnel with\n * `af_checkout={correlationId}` (a fresh load — this promise is gone; the SDK's\n * resume leg settles the attempt).\n *\n * The one way THIS page comes back to life is a bfcache restore (browser Back\n * from the hosted page): `pageshow` with `persisted: true`. That is a buyer who\n * abandoned the hosted checkout — resolve `canceled` so the trigger re-enables\n * and inline redirect placeholders recover instead of spinning forever.\n */\nexport function leaveForRedirect(url: string): Promise<CheckoutResult> {\n return new Promise<CheckoutResult>((resolve) => {\n if (typeof window !== 'undefined') {\n const onPageshow = (event: PageTransitionEvent) => {\n if (!event.persisted) return\n window.removeEventListener('pageshow', onPageshow)\n resolve({\n ok: false,\n error: checkoutError('canceled', 'Returned from the hosted checkout without completing'),\n })\n }\n window.addEventListener('pageshow', onPageshow)\n }\n window.location.assign(url)\n })\n}\n"]}
|
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
// src/i18n/locale.ts
|
|
2
|
+
var RTL_LANGS = /* @__PURE__ */ new Set(["ar", "he", "fa", "ur", "ps", "sd", "dv", "yi"]);
|
|
3
|
+
function isRtl(locale) {
|
|
4
|
+
return RTL_LANGS.has(locale.split("-")[0]);
|
|
5
|
+
}
|
|
6
|
+
var base = (l) => l?.split("-")[0];
|
|
7
|
+
function resolveLocale(config, detected, override) {
|
|
8
|
+
const supported = config?.supported ?? (config?.default ? [config.default] : ["en"]);
|
|
9
|
+
const def = config?.default ?? supported[0] ?? "en";
|
|
10
|
+
const pick = (l) => {
|
|
11
|
+
if (!l) return void 0;
|
|
12
|
+
if (supported.includes(l)) return l;
|
|
13
|
+
return supported.find((s) => base(s) === base(l));
|
|
14
|
+
};
|
|
15
|
+
return pick(override) ?? pick(detected) ?? def;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// src/commerce/money.ts
|
|
19
|
+
var PERIOD_DAYS = {
|
|
20
|
+
day: 1,
|
|
21
|
+
week: 7,
|
|
22
|
+
month: 365 / 12,
|
|
23
|
+
year: 365,
|
|
24
|
+
one_time: 0
|
|
25
|
+
};
|
|
26
|
+
function periodDays(interval, count) {
|
|
27
|
+
return PERIOD_DAYS[interval] * count;
|
|
28
|
+
}
|
|
29
|
+
function intervalLabel(interval, count) {
|
|
30
|
+
if (interval === "one_time") return { period: "one-time", periodly: "one-time" };
|
|
31
|
+
if (interval === "month" && count === 3) return { period: "quarter", periodly: "quarterly" };
|
|
32
|
+
if (interval === "month" && count === 6) return { period: "6 months", periodly: "semiannually" };
|
|
33
|
+
if (interval === "week" && count === 2) return { period: "2 weeks", periodly: "biweekly" };
|
|
34
|
+
if (count === 1) {
|
|
35
|
+
const periodly = { day: "daily", week: "weekly", month: "monthly", year: "yearly" }[interval];
|
|
36
|
+
return { period: interval, periodly };
|
|
37
|
+
}
|
|
38
|
+
return { period: `${count} ${interval}s`, periodly: `every ${count} ${interval}s` };
|
|
39
|
+
}
|
|
40
|
+
function resolveOffering(input) {
|
|
41
|
+
const interval = input.interval ?? "one_time";
|
|
42
|
+
const count = input.intervalCount ?? 1;
|
|
43
|
+
const days = periodDays(interval, count);
|
|
44
|
+
const per = (targetDays) => days > 0 ? Math.round(input.amount * targetDays / days) : input.amount;
|
|
45
|
+
const label = intervalLabel(interval, count);
|
|
46
|
+
const trialDays = input.trialDays ?? 0;
|
|
47
|
+
const trialMinor = input.trialAmount ?? 0;
|
|
48
|
+
return {
|
|
49
|
+
id: input.id,
|
|
50
|
+
catalogKey: input.catalogKey ?? input.id,
|
|
51
|
+
name: input.name ?? input.id,
|
|
52
|
+
displayName: input.displayName ?? input.name ?? input.id,
|
|
53
|
+
provider: input.provider ?? "stripe",
|
|
54
|
+
currency: input.currency,
|
|
55
|
+
priceMinor: input.amount,
|
|
56
|
+
perDayMinor: per(1),
|
|
57
|
+
perWeekMinor: per(7),
|
|
58
|
+
perMonthMinor: per(365 / 12),
|
|
59
|
+
perYearMinor: per(365),
|
|
60
|
+
period: label.period,
|
|
61
|
+
periodly: label.periodly,
|
|
62
|
+
hasTrial: trialDays > 0 || trialMinor > 0,
|
|
63
|
+
trialDays,
|
|
64
|
+
trialMinor
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
function buildCatalog(inputs) {
|
|
68
|
+
return new Map(inputs.map((i) => [i.id, resolveOffering(i)]));
|
|
69
|
+
}
|
|
70
|
+
var EXPONENT_CACHE = /* @__PURE__ */ new Map();
|
|
71
|
+
function currencyExponent(currency) {
|
|
72
|
+
const code = currency.toUpperCase();
|
|
73
|
+
const hit = EXPONENT_CACHE.get(code);
|
|
74
|
+
if (hit !== void 0) return hit;
|
|
75
|
+
let exp = 2;
|
|
76
|
+
try {
|
|
77
|
+
exp = new Intl.NumberFormat("en", { style: "currency", currency: code }).resolvedOptions().maximumFractionDigits ?? 2;
|
|
78
|
+
} catch {
|
|
79
|
+
exp = 2;
|
|
80
|
+
}
|
|
81
|
+
EXPONENT_CACHE.set(code, exp);
|
|
82
|
+
return exp;
|
|
83
|
+
}
|
|
84
|
+
function formatMoney(minor, currency, locale) {
|
|
85
|
+
const code = currency.toUpperCase();
|
|
86
|
+
const exp = currencyExponent(code);
|
|
87
|
+
const amount = minor / 10 ** exp;
|
|
88
|
+
let formatted;
|
|
89
|
+
try {
|
|
90
|
+
formatted = new Intl.NumberFormat(locale, { style: "currency", currency: code }).format(amount);
|
|
91
|
+
} catch {
|
|
92
|
+
formatted = `${code} ${amount.toFixed(exp)}`;
|
|
93
|
+
}
|
|
94
|
+
return { amount, minor, currency: code, formatted };
|
|
95
|
+
}
|
|
96
|
+
function formatOffering(r, locale) {
|
|
97
|
+
const m = (minor) => formatMoney(minor, r.currency, locale);
|
|
98
|
+
return {
|
|
99
|
+
id: r.id,
|
|
100
|
+
catalogKey: r.catalogKey,
|
|
101
|
+
name: r.name,
|
|
102
|
+
displayName: r.displayName,
|
|
103
|
+
provider: r.provider,
|
|
104
|
+
price: m(r.priceMinor),
|
|
105
|
+
period: r.period,
|
|
106
|
+
periodly: r.periodly,
|
|
107
|
+
perDay: m(r.perDayMinor),
|
|
108
|
+
perWeek: m(r.perWeekMinor),
|
|
109
|
+
perMonth: m(r.perMonthMinor),
|
|
110
|
+
perYear: m(r.perYearMinor),
|
|
111
|
+
hasTrial: r.hasTrial,
|
|
112
|
+
trialDays: r.trialDays,
|
|
113
|
+
trialPrice: r.hasTrial ? m(r.trialMinor) : null
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// src/flow/spine.ts
|
|
118
|
+
function readField(s, field) {
|
|
119
|
+
let cur = s;
|
|
120
|
+
for (const part of field.split(".")) {
|
|
121
|
+
if (cur == null) return void 0;
|
|
122
|
+
cur = cur[part];
|
|
123
|
+
}
|
|
124
|
+
return cur;
|
|
125
|
+
}
|
|
126
|
+
function evaluateCondition(cond, s) {
|
|
127
|
+
const val = readField(s, cond.field);
|
|
128
|
+
const { op, value } = cond;
|
|
129
|
+
switch (op) {
|
|
130
|
+
case "eq":
|
|
131
|
+
return val === value;
|
|
132
|
+
case "neq":
|
|
133
|
+
return val !== value;
|
|
134
|
+
case "in":
|
|
135
|
+
return Array.isArray(value) && value.includes(val);
|
|
136
|
+
case "gt":
|
|
137
|
+
return typeof val === "number" && typeof value === "number" && val > value;
|
|
138
|
+
case "gte":
|
|
139
|
+
return typeof val === "number" && typeof value === "number" && val >= value;
|
|
140
|
+
case "lt":
|
|
141
|
+
return typeof val === "number" && typeof value === "number" && val < value;
|
|
142
|
+
case "lte":
|
|
143
|
+
return typeof val === "number" && typeof value === "number" && val <= value;
|
|
144
|
+
case "contains":
|
|
145
|
+
if (typeof val === "string") return val.includes(String(value));
|
|
146
|
+
if (Array.isArray(val))
|
|
147
|
+
return val.includes(value);
|
|
148
|
+
return false;
|
|
149
|
+
case "exists":
|
|
150
|
+
return val !== void 0 && val !== null && val !== "";
|
|
151
|
+
case "empty":
|
|
152
|
+
return val === void 0 || val === null || val === "" || Array.isArray(val) && val.length === 0;
|
|
153
|
+
default:
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
function evaluateGate(gate, s) {
|
|
158
|
+
return typeof gate === "function" ? gate(s) : evaluateCondition(gate, s);
|
|
159
|
+
}
|
|
160
|
+
function resolveRoute(routes, s) {
|
|
161
|
+
if (!routes) return void 0;
|
|
162
|
+
for (const route of routes) {
|
|
163
|
+
if (!route.when || evaluateGate(route.when, s)) return route.to;
|
|
164
|
+
}
|
|
165
|
+
return void 0;
|
|
166
|
+
}
|
|
167
|
+
function pageMeta(meta) {
|
|
168
|
+
return meta;
|
|
169
|
+
}
|
|
170
|
+
var TYPE_GUARDS = {
|
|
171
|
+
paywall: { field: "user.email", op: "exists" },
|
|
172
|
+
upsell: { field: "user.email", op: "exists" }
|
|
173
|
+
};
|
|
174
|
+
function entryGuard(meta) {
|
|
175
|
+
return meta?.guard ?? (meta?.type ? TYPE_GUARDS[meta.type] : void 0);
|
|
176
|
+
}
|
|
177
|
+
function definePage(component) {
|
|
178
|
+
return component;
|
|
179
|
+
}
|
|
180
|
+
function nextPage(pages, currentKey, s) {
|
|
181
|
+
const idx = pages.findIndex((p) => p.key === currentKey);
|
|
182
|
+
if (idx === -1) return void 0;
|
|
183
|
+
const routed = resolveRoute(pages[idx].meta?.next, s);
|
|
184
|
+
if (routed) return routed;
|
|
185
|
+
return pages[idx + 1]?.key;
|
|
186
|
+
}
|
|
187
|
+
function outgoingKeys(pages, currentKey) {
|
|
188
|
+
const idx = pages.findIndex((p) => p.key === currentKey);
|
|
189
|
+
if (idx === -1) return [];
|
|
190
|
+
const out = /* @__PURE__ */ new Set();
|
|
191
|
+
for (const route of pages[idx].meta?.next ?? []) out.add(route.to);
|
|
192
|
+
const linear = pages[idx + 1]?.key;
|
|
193
|
+
if (linear) out.add(linear);
|
|
194
|
+
return [...out];
|
|
195
|
+
}
|
|
196
|
+
function expectedPathLength(pages, startKey, s) {
|
|
197
|
+
const seen = /* @__PURE__ */ new Set();
|
|
198
|
+
let key = startKey;
|
|
199
|
+
let count = 0;
|
|
200
|
+
while (key && !seen.has(key)) {
|
|
201
|
+
seen.add(key);
|
|
202
|
+
count++;
|
|
203
|
+
if (pages.find((p) => p.key === key)?.meta?.type === "finish") break;
|
|
204
|
+
key = nextPage(pages, key, s);
|
|
205
|
+
}
|
|
206
|
+
return count;
|
|
207
|
+
}
|
|
208
|
+
function defineFunnel(def) {
|
|
209
|
+
return def;
|
|
210
|
+
}
|
|
211
|
+
function normalizeOfferings(offerings) {
|
|
212
|
+
if (!offerings) return [];
|
|
213
|
+
if (Array.isArray(offerings))
|
|
214
|
+
return offerings.map((k) => ({ slot: k, catalogKey: k }));
|
|
215
|
+
return Object.entries(offerings).map(([slot, catalogKey]) => ({
|
|
216
|
+
slot,
|
|
217
|
+
catalogKey: catalogKey ?? null
|
|
218
|
+
}));
|
|
219
|
+
}
|
|
220
|
+
function funnelCatalogKeys(offerings) {
|
|
221
|
+
return [
|
|
222
|
+
...new Set(
|
|
223
|
+
normalizeOfferings(offerings).map((s) => s.catalogKey).filter((k) => !!k)
|
|
224
|
+
)
|
|
225
|
+
];
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// src/flow/experiments.ts
|
|
229
|
+
function fnv1a(input) {
|
|
230
|
+
let h = 2166136261;
|
|
231
|
+
for (let i = 0; i < input.length; i++) {
|
|
232
|
+
h ^= input.charCodeAt(i);
|
|
233
|
+
h = h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24)) >>> 0;
|
|
234
|
+
}
|
|
235
|
+
return h >>> 0;
|
|
236
|
+
}
|
|
237
|
+
function hashToUnit(seed) {
|
|
238
|
+
return fnv1a(seed) / 4294967296;
|
|
239
|
+
}
|
|
240
|
+
function pickByWeight(weights, u) {
|
|
241
|
+
const entries = Object.entries(weights).filter(([, w]) => w > 0);
|
|
242
|
+
if (entries.length === 0) return Object.keys(weights)[0] ?? "";
|
|
243
|
+
const total = entries.reduce((sum, [, w]) => sum + w, 0);
|
|
244
|
+
const target = u * total;
|
|
245
|
+
let acc = 0;
|
|
246
|
+
for (const [key, w] of entries) {
|
|
247
|
+
acc += w;
|
|
248
|
+
if (target < acc) return key;
|
|
249
|
+
}
|
|
250
|
+
return entries[entries.length - 1][0];
|
|
251
|
+
}
|
|
252
|
+
function assignVariant(experimentId, seed, weights) {
|
|
253
|
+
return pickByWeight(weights, hashToUnit(`${experimentId}:${seed}`));
|
|
254
|
+
}
|
|
255
|
+
function bucketingSeed(context) {
|
|
256
|
+
return context.identity.visitorId ?? context.identity.customerId ?? null;
|
|
257
|
+
}
|
|
258
|
+
function parseSlotKey(key) {
|
|
259
|
+
const at = key.indexOf("@");
|
|
260
|
+
return at === -1 ? { slot: key } : { slot: key.slice(0, at), variant: key.slice(at + 1) };
|
|
261
|
+
}
|
|
262
|
+
function isVariantKey(key) {
|
|
263
|
+
return parseSlotKey(key).variant !== void 0;
|
|
264
|
+
}
|
|
265
|
+
function weightsOf(variants) {
|
|
266
|
+
const out = {};
|
|
267
|
+
for (const [label, v] of Object.entries(variants)) out[label] = v.weight;
|
|
268
|
+
return out;
|
|
269
|
+
}
|
|
270
|
+
function resolveExperiments(pages, experiments, seed) {
|
|
271
|
+
const assignments = {};
|
|
272
|
+
const render = {};
|
|
273
|
+
const experimentOf = {};
|
|
274
|
+
const versionOf = {};
|
|
275
|
+
if (seed) {
|
|
276
|
+
for (const exp of experiments) {
|
|
277
|
+
const label = assignVariant(exp.id, seed, weightsOf(exp.variants));
|
|
278
|
+
const arm = exp.variants[label];
|
|
279
|
+
if (!arm) continue;
|
|
280
|
+
assignments[exp.id] = label;
|
|
281
|
+
experimentOf[exp.slot] = exp.id;
|
|
282
|
+
if (exp.version !== void 0) versionOf[exp.id] = exp.version;
|
|
283
|
+
if (arm.page !== exp.slot) render[exp.slot] = arm.page;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
const slotOf = {};
|
|
287
|
+
const activeKeys = [];
|
|
288
|
+
for (const p of pages) {
|
|
289
|
+
const { slot, variant } = parseSlotKey(p.key);
|
|
290
|
+
if (variant !== void 0) slotOf[p.key] = slot;
|
|
291
|
+
else activeKeys.push(p.key);
|
|
292
|
+
}
|
|
293
|
+
return { assignments, activeKeys, render, slotOf, experimentOf, versionOf };
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// src/manifest/manifest.ts
|
|
297
|
+
function isVariantNode(page) {
|
|
298
|
+
return isVariantKey(page.key);
|
|
299
|
+
}
|
|
300
|
+
function serializeGate(when) {
|
|
301
|
+
if (!when) return void 0;
|
|
302
|
+
if (typeof when === "function") return { kind: "predicate" };
|
|
303
|
+
return { kind: "declarative", condition: when };
|
|
304
|
+
}
|
|
305
|
+
function compileManifest(input) {
|
|
306
|
+
const { funnel, pages } = input;
|
|
307
|
+
const keys = new Set(pages.map((p) => p.key));
|
|
308
|
+
const manifestPages = pages.map((p, index) => ({
|
|
309
|
+
id: p.key,
|
|
310
|
+
key: p.key,
|
|
311
|
+
type: p.meta?.type ?? "default",
|
|
312
|
+
slug: p.meta?.slug ?? p.key,
|
|
313
|
+
index,
|
|
314
|
+
variantOf: isVariantKey(p.key) ? parseSlotKey(p.key).slot : void 0,
|
|
315
|
+
// The effective entry guard (explicit meta.guard, else the page-type default), serialized so
|
|
316
|
+
// the renderer can evaluate a DECLARATIVE guard server-side (Option B, FIX 1). Predicate guards
|
|
317
|
+
// serialize to an opaque marker → the renderer falls back to live SSR for that deep-link.
|
|
318
|
+
entryGuard: serializeGate(entryGuard(p.meta)),
|
|
319
|
+
// Prerender opt-out: `dynamic: true` OR `prerender: false` (a page whose STRUCTURE depends on
|
|
320
|
+
// sessionValues — Option B, FIX 2). Undefined stays undefined (prerendered, the default).
|
|
321
|
+
dynamic: p.meta?.dynamic === true || p.meta?.prerender === false ? true : void 0
|
|
322
|
+
}));
|
|
323
|
+
const edges = [];
|
|
324
|
+
const badTargets = [];
|
|
325
|
+
const nextAnchor = (from) => {
|
|
326
|
+
for (let j = from + 1; j < pages.length; j++) {
|
|
327
|
+
if (!isVariantNode(pages[j])) return pages[j];
|
|
328
|
+
}
|
|
329
|
+
return void 0;
|
|
330
|
+
};
|
|
331
|
+
pages.forEach((p, i) => {
|
|
332
|
+
if (isVariantNode(p)) {
|
|
333
|
+
for (const route of p.meta?.next ?? []) {
|
|
334
|
+
if (!keys.has(route.to)) {
|
|
335
|
+
badTargets.push({ from: p.key, to: route.to });
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
edges.push({ from: p.key, to: route.to, kind: "branch", variant: true, condition: serializeGate(route.when) });
|
|
339
|
+
}
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
const routes = p.meta?.next ?? [];
|
|
343
|
+
let hasUnconditional = false;
|
|
344
|
+
for (const route of routes) {
|
|
345
|
+
if (!keys.has(route.to)) {
|
|
346
|
+
badTargets.push({ from: p.key, to: route.to });
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
edges.push({ from: p.key, to: route.to, kind: "branch", condition: serializeGate(route.when) });
|
|
350
|
+
if (!route.when) hasUnconditional = true;
|
|
351
|
+
}
|
|
352
|
+
const next = nextAnchor(i);
|
|
353
|
+
if (!hasUnconditional && next && p.meta?.type !== "finish") {
|
|
354
|
+
edges.push({ from: p.key, to: next.key, kind: "linear" });
|
|
355
|
+
}
|
|
356
|
+
});
|
|
357
|
+
const startPage = pages.find((p) => !isVariantNode(p));
|
|
358
|
+
const start = startPage?.key ?? null;
|
|
359
|
+
const variantKeys = new Set(pages.filter(isVariantNode).map((p) => p.key));
|
|
360
|
+
const offeringSlots = normalizeOfferings(funnel.offerings);
|
|
361
|
+
const validation = validate(manifestPages, edges, badTargets, start, variantKeys, offeringSlots, input.offeringRefs);
|
|
362
|
+
return {
|
|
363
|
+
id: funnel.id,
|
|
364
|
+
pages: manifestPages,
|
|
365
|
+
flow: { start, nodes: manifestPages.map((p) => p.id), edges },
|
|
366
|
+
offerings: funnelCatalogKeys(funnel.offerings),
|
|
367
|
+
offeringSlots,
|
|
368
|
+
offeringRefs: input.offeringRefs,
|
|
369
|
+
// Carry the funnel.ts `checkout:` bundle + the scanned checkout-surface usage for the publish
|
|
370
|
+
// capability gate. Both are provider-agnostic here (the SDK can't resolve offering→provider);
|
|
371
|
+
// the API gate combines them with the DB-resolved provider to run the (provider × surface) matrix.
|
|
372
|
+
checkout: funnel.checkout,
|
|
373
|
+
checkoutRefs: input.checkoutRefs,
|
|
374
|
+
locales: funnel.locales,
|
|
375
|
+
validation
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
function validate(pages, edges, badTargets, start, variantKeys, slots, offeringRefs) {
|
|
379
|
+
const outgoing = /* @__PURE__ */ new Map();
|
|
380
|
+
for (const e of edges) outgoing.set(e.from, (outgoing.get(e.from) ?? 0) + 1);
|
|
381
|
+
const deadEnds = pages.filter((p) => p.type !== "finish" && !variantKeys.has(p.id) && !(outgoing.get(p.id) > 0)).map((p) => p.id);
|
|
382
|
+
const reachable = /* @__PURE__ */ new Set();
|
|
383
|
+
if (start) {
|
|
384
|
+
const adj = /* @__PURE__ */ new Map();
|
|
385
|
+
for (const e of edges) {
|
|
386
|
+
const list = adj.get(e.from);
|
|
387
|
+
if (list) list.push(e.to);
|
|
388
|
+
else adj.set(e.from, [e.to]);
|
|
389
|
+
}
|
|
390
|
+
for (const p of pages) {
|
|
391
|
+
if (p.variantOf === void 0) continue;
|
|
392
|
+
const list = adj.get(p.variantOf);
|
|
393
|
+
if (list) list.push(p.id);
|
|
394
|
+
else adj.set(p.variantOf, [p.id]);
|
|
395
|
+
}
|
|
396
|
+
const stack = [start];
|
|
397
|
+
while (stack.length) {
|
|
398
|
+
const id = stack.pop();
|
|
399
|
+
if (reachable.has(id)) continue;
|
|
400
|
+
reachable.add(id);
|
|
401
|
+
for (const to of adj.get(id) ?? []) stack.push(to);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
const unreachable = pages.filter((p) => !variantKeys.has(p.id) && !reachable.has(p.id)).map((p) => p.id);
|
|
405
|
+
const missingEmailCapture = !pages.some((p) => p.type === "email-capture");
|
|
406
|
+
const seen = /* @__PURE__ */ new Set();
|
|
407
|
+
const duplicateKeys = [];
|
|
408
|
+
for (const p of pages) {
|
|
409
|
+
if (seen.has(p.key) && !duplicateKeys.includes(p.key)) duplicateKeys.push(p.key);
|
|
410
|
+
seen.add(p.key);
|
|
411
|
+
}
|
|
412
|
+
const bySlug = /* @__PURE__ */ new Map();
|
|
413
|
+
for (const p of pages) {
|
|
414
|
+
if (variantKeys.has(p.id)) continue;
|
|
415
|
+
const list = bySlug.get(p.slug);
|
|
416
|
+
if (list) list.push(p.id);
|
|
417
|
+
else bySlug.set(p.slug, [p.id]);
|
|
418
|
+
}
|
|
419
|
+
const slugCollisions = [...bySlug.entries()].filter(([, ids]) => ids.length > 1).map(([slug, ids]) => ({ slug, pages: ids }));
|
|
420
|
+
const flowKeys = new Set(pages.filter((p) => !variantKeys.has(p.id)).map((p) => p.key));
|
|
421
|
+
const orphanVariants = pages.filter((p) => p.variantOf !== void 0 && !flowKeys.has(p.variantOf)).map((p) => p.id);
|
|
422
|
+
const noReachableFinish = start !== null && !pages.some((p) => p.type === "finish" && reachable.has(p.id));
|
|
423
|
+
const declaredSlots = new Set(slots.map((s) => s.slot));
|
|
424
|
+
const assignedSlots = new Set(slots.filter((s) => s.catalogKey).map((s) => s.slot));
|
|
425
|
+
const refs = offeringRefs ?? [];
|
|
426
|
+
const unknownOfferingRefs = [...new Set(refs.filter((r) => !declaredSlots.has(r)))];
|
|
427
|
+
const unassignedSlots = [...new Set(refs.filter((r) => declaredSlots.has(r) && !assignedSlots.has(r)))];
|
|
428
|
+
return {
|
|
429
|
+
// Original hard errors AND the structural ones; slug collisions stay a warning.
|
|
430
|
+
ok: deadEnds.length === 0 && unreachable.length === 0 && badTargets.length === 0 && !missingEmailCapture && duplicateKeys.length === 0 && orphanVariants.length === 0 && !noReachableFinish && unknownOfferingRefs.length === 0 && unassignedSlots.length === 0,
|
|
431
|
+
deadEnds,
|
|
432
|
+
unreachable,
|
|
433
|
+
badTargets,
|
|
434
|
+
missingEmailCapture,
|
|
435
|
+
duplicateKeys,
|
|
436
|
+
slugCollisions,
|
|
437
|
+
orphanVariants,
|
|
438
|
+
noReachableFinish,
|
|
439
|
+
unknownOfferingRefs,
|
|
440
|
+
unassignedSlots
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
export { assignVariant, bucketingSeed, buildCatalog, compileManifest, currencyExponent, defineFunnel, definePage, entryGuard, evaluateCondition, evaluateGate, expectedPathLength, fnv1a, formatMoney, formatOffering, funnelCatalogKeys, hashToUnit, isRtl, isVariantKey, nextPage, normalizeOfferings, outgoingKeys, pageMeta, parseSlotKey, pickByWeight, resolveExperiments, resolveLocale, resolveOffering, resolveRoute, weightsOf };
|
|
445
|
+
//# sourceMappingURL=chunk-VW2HVPR4.js.map
|
|
446
|
+
//# sourceMappingURL=chunk-VW2HVPR4.js.map
|