@apextelemed/partner-core 0.15.0 → 0.16.0-dev.44

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.
Files changed (42) hide show
  1. package/dist/api/index.d.ts +1 -1
  2. package/dist/api/index.js +3 -3
  3. package/dist/api/index.jsx +5 -3
  4. package/dist/chunk/{JOPX73FC.jsx → 2RWPQQ4A.jsx} +5 -5
  5. package/dist/chunk/{WDB3G3X3.js → 46MIDHRD.js} +3 -3
  6. package/dist/chunk/{WDB3G3X3.js.map → 46MIDHRD.js.map} +1 -1
  7. package/dist/chunk/{DLP3Q3AT.js → AM5HSKWG.js} +6 -6
  8. package/dist/chunk/{DLP3Q3AT.js.map → AM5HSKWG.js.map} +1 -1
  9. package/dist/chunk/{OLSTMCLZ.jsx → AO3N6VTS.jsx} +24 -1
  10. package/dist/chunk/{YYWHDAAF.js → CXMAV5SC.js} +3 -3
  11. package/dist/chunk/{YYWHDAAF.js.map → CXMAV5SC.js.map} +1 -1
  12. package/dist/chunk/{CWPXPAUD.js → E6KLEFN3.js} +586 -6
  13. package/dist/chunk/E6KLEFN3.js.map +1 -0
  14. package/dist/chunk/{5ZJ7NC4S.jsx → HYN2BVTH.jsx} +2225 -1352
  15. package/dist/chunk/{CCRVBJ6A.jsx → KK36ZETG.jsx} +2 -2
  16. package/dist/chunk/{NCK4UJHA.jsx → MMPKHKIU.jsx} +2 -2
  17. package/dist/chunk/{NSWRAFQE.js → MPW4IVPB.js} +2533 -1132
  18. package/dist/chunk/MPW4IVPB.js.map +1 -0
  19. package/dist/chunk/{ZYHXLSJA.js → NEV5KNPS.js} +25 -3
  20. package/dist/chunk/NEV5KNPS.js.map +1 -0
  21. package/dist/chunk/{VECSCRAK.jsx → ONYGQYUN.jsx} +608 -5
  22. package/dist/chunk/{2LWM2YSR.jsx → RF6RWN3P.jsx} +2 -2
  23. package/dist/chunk/{IBGYHU26.js → RGFD2T3K.js} +3 -3
  24. package/dist/chunk/{IBGYHU26.js.map → RGFD2T3K.js.map} +1 -1
  25. package/dist/{client-B07yeMS8.d.ts → client-oZcZn-HB.d.ts} +178 -1
  26. package/dist/flows/index.d.ts +300 -2
  27. package/dist/flows/index.js +6 -6
  28. package/dist/flows/index.jsx +44 -6
  29. package/dist/index/index.d.ts +2 -2
  30. package/dist/index/index.js +7 -7
  31. package/dist/index/index.jsx +47 -7
  32. package/dist/pages/index.d.ts +1 -1
  33. package/dist/pages/index.js +5 -5
  34. package/dist/pages/index.jsx +5 -5
  35. package/dist/stores/index.d.ts +1 -1
  36. package/dist/stores/index.js +2 -2
  37. package/dist/stores/index.jsx +2 -2
  38. package/dist/theme/admin.css +95 -0
  39. package/package.json +1 -1
  40. package/dist/chunk/CWPXPAUD.js.map +0 -1
  41. package/dist/chunk/NSWRAFQE.js.map +0 -1
  42. package/dist/chunk/ZYHXLSJA.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/promoRef.ts","../../src/api/cart.ts"],"names":[],"mappings":";;;;AAiBA,IAAM,MAAA,GAAS,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,GAAA;AAEnC,IAAM,UAAA,GAAa,MAAM,CAAA,EAAG,SAAA,GAAY,aAAa,CAAA,WAAA,CAAA;AAQ9C,SAAS,iBAAiB,IAAA,EAAoB;AACnD,EAAA,IAAI,OAAO,iBAAiB,WAAA,EAAa;AACzC,EAAA,MAAM,OAAA,GAAU,KAAK,IAAA,EAAK;AAC1B,EAAA,IAAI,CAAC,OAAA,EAAS;AACd,EAAA,IAAI;AACF,IAAA,MAAM,QAAqB,EAAE,IAAA,EAAM,SAAS,EAAA,EAAI,IAAA,CAAK,KAAI,EAAE;AAC3D,IAAA,YAAA,CAAa,QAAQ,UAAA,EAAW,EAAG,IAAA,CAAK,SAAA,CAAU,KAAK,CAAC,CAAA;AAAA,EAC1D,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;AASO,SAAS,aAAA,GAA+B;AAC7C,EA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AAM,CAAA,EAAG;AACnC,IAAA,GAAA,CAAI,YAAA,CAAa,OAAO,MAAM,CAAA;AAC9B,IAAA,MAAA,CAAO,QAAQ,YAAA,CAAa,IAAI,EAAA,EAAI,GAAA,CAAI,UAAU,CAAA;AAAA,EACpD,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"IBGYHU26.js","sourcesContent":["// ── First-party promo-code capture from a `?promo=` landing ──────────\n//\n// A campaign link can carry its own code (`/?promo=TRUE10`) so the member does\n// not have to type it. Stashed in the storefront's own localStorage and read\n// back when the intake reaches the promo field.\n//\n// Mirrors `affiliateRef` deliberately — same storage shape, same 30-day window —\n// but is a SEPARATE concern: an affiliate ref attributes a sale to a partner and\n// is validated server-side at checkout, while this only pre-fills an input the\n// member still has to submit.\n\nimport { getConfig } from '../config';\n\n// Matches the affiliate-ref window. A stash that outlives the promo it carries\n// is not a correctness problem — the code is re-validated before it is used,\n// and silently dropped if it has expired — but there is no reason to keep one\n// around longer than a campaign plausibly runs.\nconst TTL_MS = 30 * 24 * 60 * 60 * 1000;\n\nconst storageKey = () => `${getConfig().storagePrefix}-promo-code`;\n\ninterface StoredPromo {\n code: string;\n ts: number;\n}\n\n/** Persist a promo code from a `?promo=` landing. No-op for empty input. */\nexport function capturePromoCode(code: string): void {\n if (typeof localStorage === 'undefined') return;\n const trimmed = code.trim();\n if (!trimmed) return;\n try {\n const entry: StoredPromo = { code: trimmed, ts: Date.now() };\n localStorage.setItem(storageKey(), JSON.stringify(entry));\n } catch {\n // storage unavailable (private mode / quota) — non-fatal\n }\n}\n\n/**\n * Read the stored promo code, or null if absent or past the storage window.\n *\n * Being within the window says nothing about whether the CODE is still valid —\n * a campaign can end while the stash is fresh. The caller re-validates against\n * the server before showing it to anyone.\n */\nexport function readPromoCode(): string | null {\n if (typeof localStorage === 'undefined') return null;\n try {\n const raw = localStorage.getItem(storageKey());\n if (!raw) return null;\n const parsed = JSON.parse(raw) as Partial<StoredPromo>;\n if (!parsed.code || typeof parsed.ts !== 'number') return null;\n if (Date.now() - parsed.ts > TTL_MS) {\n localStorage.removeItem(storageKey());\n return null;\n }\n return parsed.code;\n } catch {\n return null;\n }\n}\n\n/** Drop the stored promo code. */\nexport function clearPromoCode(): void {\n if (typeof localStorage === 'undefined') return;\n try {\n localStorage.removeItem(storageKey());\n } catch {\n // non-fatal\n }\n}\n","import { getConfig } from '../config';\nimport { captureAuthHeader, peekFunnelSessionId } from './funnel';\n\n// ── Abandoned-cart transport ────────────────────────────────────────────────\n//\n// Thin client for the-backend's cart-capture endpoints:\n// GET /config/cart → whether this tenant mirrors carts at all\n// POST /cart/snapshot → server-side mirror of the browser's cart\n// GET /cart/resume → trade an emailed token for the saved cart\n//\n// Sibling of ./funnel, and the same posture: fire-and-forget, fail-silent.\n// Cart capture is marketing instrumentation and must never break, block or\n// slow down shopping.\n\nexport interface CartCaptureConfig {\n /** Tenant opted in (features.cartRecovery); false = never send anything. */\n snapshot: boolean;\n}\n\nconst DISABLED: CartCaptureConfig = { snapshot: false };\n\nlet configPromise: Promise<CartCaptureConfig> | null = null;\n\n/**\n * The tenant's cart-capture posture, fetched once per page load and cached.\n * Fails closed: any error reads as \"off\".\n */\nexport function fetchCartConfig(): Promise<CartCaptureConfig> {\n if (!configPromise) {\n configPromise = (async () => {\n try {\n const cfg = getConfig();\n const res = await fetch(`${cfg.apiBase}/config/cart`, {\n headers: { 'X-Tenant-Key': cfg.tenantKey },\n });\n if (!res.ok) return DISABLED;\n const body = (await res.json()) as Partial<CartCaptureConfig>;\n return { snapshot: body.snapshot === true };\n } catch {\n return DISABLED;\n }\n })();\n }\n return configPromise;\n}\n\n/** Test seam: forget the cached config so the next fetch re-resolves. */\nexport function resetCartConfigCache(): void {\n configPromise = null;\n}\n\nconst cartIdKey = () => `${getConfig().storagePrefix}-cart-id`;\n\n/**\n * Stable id for this shopper's cart, minted on first use and kept in\n * localStorage — NOT sessionStorage like the survey session.\n *\n * A cart outlives the tab it was filled in: someone adds items, closes the\n * browser, comes back tomorrow and finds the cart still there (the cart store\n * itself persists the same way). The id has to survive with it, or every visit\n * would look like a brand-new abandoned cart and one shopper would accumulate\n * a row — and a reminder track — per session.\n */\nexport function cartId(): string {\n let id: string | null = null;\n try {\n id = localStorage.getItem(cartIdKey());\n } catch {\n /* storage unavailable (private mode) — fall through to an ephemeral id */\n }\n if (!id) {\n id =\n typeof crypto !== 'undefined' && 'randomUUID' in crypto\n ? crypto.randomUUID()\n : `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n try {\n localStorage.setItem(cartIdKey(), id);\n } catch {\n /* ephemeral it is */\n }\n }\n return id;\n}\n\n/**\n * Continue the cart a recovery email points at, instead of the one this browser\n * happens to hold. Adopting the emailed id keeps the reminder history, the\n * email address and the eventual conversion on ONE row.\n */\nexport function adoptCartId(id: string): void {\n if (!id) return;\n try {\n localStorage.setItem(cartIdKey(), id);\n } catch {\n /* storage unavailable — the adoption is ephemeral */\n }\n}\n\n/**\n * Start a fresh cart id. Called after a purchase: the old id is stamped\n * converted server-side and must never be written to again, or a new cart\n * would inherit a bought cart's row (and its silence — converted rows are\n * never nudged).\n */\nexport function resetCartId(): void {\n try {\n localStorage.removeItem(cartIdKey());\n } catch {\n /* nothing to clear */\n }\n}\n\nexport interface CartSnapshotLine {\n productId: string;\n dosage?: string;\n quantity: number;\n}\n\n/**\n * Mirror the cart server-side. Identity only — the backend re-prices from the\n * catalog and ignores anything else we send, so there is no point shipping\n * names or prices.\n *\n * `keepalive` lets the request survive the page unload that so often IS the\n * abandonment.\n *\n * The bearer token, when there is one, is how a signed-in shopper's cart gets\n * their user id: the endpoint takes identity from the token and never from the\n * body (`optionalAuth`), so omitting it left every logged-in cart anonymous —\n * joinable only by whatever email happened to be attached.\n */\nexport function postCartSnapshot(params: {\n items: CartSnapshotLine[];\n promoCode?: string | null;\n email?: string | null;\n}): void {\n try {\n const cfg = getConfig();\n void fetch(`${cfg.apiBase}/cart/snapshot`, {\n method: 'POST',\n keepalive: true,\n headers: {\n 'Content-Type': 'application/json',\n 'X-Tenant-Key': cfg.tenantKey,\n ...captureAuthHeader(),\n },\n body: JSON.stringify({\n cartId: cartId(),\n items: params.items,\n promoCode: params.promoCode ?? null,\n ...(params.email ? { email: params.email } : {}),\n // Only when a survey session already exists: it lets the backend reuse\n // the address the pre-survey email gate collected, which is often the\n // only handle we have on an anonymous shopper.\n ...(peekFunnelSessionId() ? { sessionId: peekFunnelSessionId() } : {}),\n }),\n }).catch(() => {});\n } catch {\n /* not configured yet — drop */\n }\n}\n\n/** A resumed cart line, already re-priced against today's catalog. */\nexport interface ResumedCartLine {\n productId: string;\n dosage?: string;\n quantity: number;\n name: string;\n priceCents: number;\n salePriceCents: number | null;\n thumbnailUrl: string | null;\n isSubscription: boolean;\n apexDrugId: string | null;\n categories: string[];\n hideDoseLabel: boolean;\n}\n\nexport interface ResumedCart {\n cartId: string;\n items: ResumedCartLine[];\n /** Lines whose product has since been discontinued or deactivated. */\n unavailable: Array<{ productId: string; dosage?: string; quantity: number }>;\n promoCode: string | null;\n subtotalCents: number;\n}\n\n/**\n * Exchange an emailed recovery token for the saved cart.\n *\n * The token is the ONLY thing authorizing this read — the-backend verifies its\n * HMAC before returning anything. A 404 (expired, already bought, tampered, or\n * every product gone) resolves to null so the caller simply keeps whatever cart\n * this browser already had.\n */\nexport async function fetchResumedCart(token: string): Promise<ResumedCart | null> {\n try {\n const cfg = getConfig();\n const res = await fetch(`${cfg.apiBase}/cart/resume?token=${encodeURIComponent(token)}`, {\n headers: { 'X-Tenant-Key': cfg.tenantKey },\n });\n if (!res.ok) return null;\n const body = (await res.json()) as Partial<ResumedCart>;\n if (!body.cartId || !Array.isArray(body.items) || body.items.length === 0) return null;\n return {\n cartId: body.cartId,\n items: body.items,\n unavailable: Array.isArray(body.unavailable) ? body.unavailable : [],\n promoCode: body.promoCode ?? null,\n subtotalCents: typeof body.subtotalCents === 'number' ? body.subtotalCents : 0,\n };\n } catch {\n return null;\n }\n}\n\n/** Read the `?cart=` token from the current URL. */\nexport function readCartToken(): string | null {\n try {\n const token = new URLSearchParams(window.location.search).get('cart');\n return token && token.length > 0 ? token : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Drop `?cart=` from the address bar once it's been redeemed, so a refresh (or\n * a shared URL) doesn't re-run the restore over a cart the shopper has since\n * edited. History is replaced, not pushed — the token was never a page.\n */\nexport function stripCartToken(): void {\n try {\n const url = new URL(window.location.href);\n if (!url.searchParams.has('cart')) return;\n url.searchParams.delete('cart');\n window.history.replaceState({}, '', url.toString());\n } catch {\n /* no history API — leaving the param is harmless */\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/api/promoRef.ts","../../src/api/cart.ts"],"names":[],"mappings":";;;;AAiBA,IAAM,MAAA,GAAS,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,GAAA;AAEnC,IAAM,UAAA,GAAa,MAAM,CAAA,EAAG,SAAA,GAAY,aAAa,CAAA,WAAA,CAAA;AAQ9C,SAAS,iBAAiB,IAAA,EAAoB;AACnD,EAAA,IAAI,OAAO,iBAAiB,WAAA,EAAa;AACzC,EAAA,MAAM,OAAA,GAAU,KAAK,IAAA,EAAK;AAC1B,EAAA,IAAI,CAAC,OAAA,EAAS;AACd,EAAA,IAAI;AACF,IAAA,MAAM,QAAqB,EAAE,IAAA,EAAM,SAAS,EAAA,EAAI,IAAA,CAAK,KAAI,EAAE;AAC3D,IAAA,YAAA,CAAa,QAAQ,UAAA,EAAW,EAAG,IAAA,CAAK,SAAA,CAAU,KAAK,CAAC,CAAA;AAAA,EAC1D,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;AASO,SAAS,aAAA,GAA+B;AAC7C,EAAA,IAAI,OAAO,YAAA,KAAiB,WAAA,EAAa,OAAO,IAAA;AAChD,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,YAAA,CAAa,OAAA,CAAQ,UAAA,EAAY,CAAA;AAC7C,IAAA,IAAI,CAAC,KAAK,OAAO,IAAA;AACjB,IAAA,MAAM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","file":"RGFD2T3K.js","sourcesContent":["// ── First-party promo-code capture from a `?promo=` landing ──────────\n//\n// A campaign link can carry its own code (`/?promo=TRUE10`) so the member does\n// not have to type it. Stashed in the storefront's own localStorage and read\n// back when the intake reaches the promo field.\n//\n// Mirrors `affiliateRef` deliberately — same storage shape, same 30-day window —\n// but is a SEPARATE concern: an affiliate ref attributes a sale to a partner and\n// is validated server-side at checkout, while this only pre-fills an input the\n// member still has to submit.\n\nimport { getConfig } from '../config';\n\n// Matches the affiliate-ref window. A stash that outlives the promo it carries\n// is not a correctness problem — the code is re-validated before it is used,\n// and silently dropped if it has expired — but there is no reason to keep one\n// around longer than a campaign plausibly runs.\nconst TTL_MS = 30 * 24 * 60 * 60 * 1000;\n\nconst storageKey = () => `${getConfig().storagePrefix}-promo-code`;\n\ninterface StoredPromo {\n code: string;\n ts: number;\n}\n\n/** Persist a promo code from a `?promo=` landing. No-op for empty input. */\nexport function capturePromoCode(code: string): void {\n if (typeof localStorage === 'undefined') return;\n const trimmed = code.trim();\n if (!trimmed) return;\n try {\n const entry: StoredPromo = { code: trimmed, ts: Date.now() };\n localStorage.setItem(storageKey(), JSON.stringify(entry));\n } catch {\n // storage unavailable (private mode / quota) — non-fatal\n }\n}\n\n/**\n * Read the stored promo code, or null if absent or past the storage window.\n *\n * Being within the window says nothing about whether the CODE is still valid —\n * a campaign can end while the stash is fresh. The caller re-validates against\n * the server before showing it to anyone.\n */\nexport function readPromoCode(): string | null {\n if (typeof localStorage === 'undefined') return null;\n try {\n const raw = localStorage.getItem(storageKey());\n if (!raw) return null;\n const parsed = JSON.parse(raw) as Partial<StoredPromo>;\n if (!parsed.code || typeof parsed.ts !== 'number') return null;\n if (Date.now() - parsed.ts > TTL_MS) {\n localStorage.removeItem(storageKey());\n return null;\n }\n return parsed.code;\n } catch {\n return null;\n }\n}\n\n/** Drop the stored promo code. */\nexport function clearPromoCode(): void {\n if (typeof localStorage === 'undefined') return;\n try {\n localStorage.removeItem(storageKey());\n } catch {\n // non-fatal\n }\n}\n","import { getConfig } from '../config';\nimport { captureAuthHeader, peekFunnelSessionId } from './funnel';\n\n// ── Abandoned-cart transport ────────────────────────────────────────────────\n//\n// Thin client for the-backend's cart-capture endpoints:\n// GET /config/cart → whether this tenant mirrors carts at all\n// POST /cart/snapshot → server-side mirror of the browser's cart\n// GET /cart/resume → trade an emailed token for the saved cart\n//\n// Sibling of ./funnel, and the same posture: fire-and-forget, fail-silent.\n// Cart capture is marketing instrumentation and must never break, block or\n// slow down shopping.\n\nexport interface CartCaptureConfig {\n /** Tenant opted in (features.cartRecovery); false = never send anything. */\n snapshot: boolean;\n}\n\nconst DISABLED: CartCaptureConfig = { snapshot: false };\n\nlet configPromise: Promise<CartCaptureConfig> | null = null;\n\n/**\n * The tenant's cart-capture posture, fetched once per page load and cached.\n * Fails closed: any error reads as \"off\".\n */\nexport function fetchCartConfig(): Promise<CartCaptureConfig> {\n if (!configPromise) {\n configPromise = (async () => {\n try {\n const cfg = getConfig();\n const res = await fetch(`${cfg.apiBase}/config/cart`, {\n headers: { 'X-Tenant-Key': cfg.tenantKey },\n });\n if (!res.ok) return DISABLED;\n const body = (await res.json()) as Partial<CartCaptureConfig>;\n return { snapshot: body.snapshot === true };\n } catch {\n return DISABLED;\n }\n })();\n }\n return configPromise;\n}\n\n/** Test seam: forget the cached config so the next fetch re-resolves. */\nexport function resetCartConfigCache(): void {\n configPromise = null;\n}\n\nconst cartIdKey = () => `${getConfig().storagePrefix}-cart-id`;\n\n/**\n * Stable id for this shopper's cart, minted on first use and kept in\n * localStorage — NOT sessionStorage like the survey session.\n *\n * A cart outlives the tab it was filled in: someone adds items, closes the\n * browser, comes back tomorrow and finds the cart still there (the cart store\n * itself persists the same way). The id has to survive with it, or every visit\n * would look like a brand-new abandoned cart and one shopper would accumulate\n * a row — and a reminder track — per session.\n */\nexport function cartId(): string {\n let id: string | null = null;\n try {\n id = localStorage.getItem(cartIdKey());\n } catch {\n /* storage unavailable (private mode) — fall through to an ephemeral id */\n }\n if (!id) {\n id =\n typeof crypto !== 'undefined' && 'randomUUID' in crypto\n ? crypto.randomUUID()\n : `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n try {\n localStorage.setItem(cartIdKey(), id);\n } catch {\n /* ephemeral it is */\n }\n }\n return id;\n}\n\n/**\n * Continue the cart a recovery email points at, instead of the one this browser\n * happens to hold. Adopting the emailed id keeps the reminder history, the\n * email address and the eventual conversion on ONE row.\n */\nexport function adoptCartId(id: string): void {\n if (!id) return;\n try {\n localStorage.setItem(cartIdKey(), id);\n } catch {\n /* storage unavailable — the adoption is ephemeral */\n }\n}\n\n/**\n * Start a fresh cart id. Called after a purchase: the old id is stamped\n * converted server-side and must never be written to again, or a new cart\n * would inherit a bought cart's row (and its silence — converted rows are\n * never nudged).\n */\nexport function resetCartId(): void {\n try {\n localStorage.removeItem(cartIdKey());\n } catch {\n /* nothing to clear */\n }\n}\n\nexport interface CartSnapshotLine {\n productId: string;\n dosage?: string;\n quantity: number;\n}\n\n/**\n * Mirror the cart server-side. Identity only — the backend re-prices from the\n * catalog and ignores anything else we send, so there is no point shipping\n * names or prices.\n *\n * `keepalive` lets the request survive the page unload that so often IS the\n * abandonment.\n *\n * The bearer token, when there is one, is how a signed-in shopper's cart gets\n * their user id: the endpoint takes identity from the token and never from the\n * body (`optionalAuth`), so omitting it left every logged-in cart anonymous —\n * joinable only by whatever email happened to be attached.\n */\nexport function postCartSnapshot(params: {\n items: CartSnapshotLine[];\n promoCode?: string | null;\n email?: string | null;\n}): void {\n try {\n const cfg = getConfig();\n void fetch(`${cfg.apiBase}/cart/snapshot`, {\n method: 'POST',\n keepalive: true,\n headers: {\n 'Content-Type': 'application/json',\n 'X-Tenant-Key': cfg.tenantKey,\n ...captureAuthHeader(),\n },\n body: JSON.stringify({\n cartId: cartId(),\n items: params.items,\n promoCode: params.promoCode ?? null,\n ...(params.email ? { email: params.email } : {}),\n // Only when a survey session already exists: it lets the backend reuse\n // the address the pre-survey email gate collected, which is often the\n // only handle we have on an anonymous shopper.\n ...(peekFunnelSessionId() ? { sessionId: peekFunnelSessionId() } : {}),\n }),\n }).catch(() => {});\n } catch {\n /* not configured yet — drop */\n }\n}\n\n/** A resumed cart line, already re-priced against today's catalog. */\nexport interface ResumedCartLine {\n productId: string;\n dosage?: string;\n quantity: number;\n name: string;\n priceCents: number;\n salePriceCents: number | null;\n thumbnailUrl: string | null;\n isSubscription: boolean;\n apexDrugId: string | null;\n categories: string[];\n hideDoseLabel: boolean;\n}\n\nexport interface ResumedCart {\n cartId: string;\n items: ResumedCartLine[];\n /** Lines whose product has since been discontinued or deactivated. */\n unavailable: Array<{ productId: string; dosage?: string; quantity: number }>;\n promoCode: string | null;\n subtotalCents: number;\n}\n\n/**\n * Exchange an emailed recovery token for the saved cart.\n *\n * The token is the ONLY thing authorizing this read — the-backend verifies its\n * HMAC before returning anything. A 404 (expired, already bought, tampered, or\n * every product gone) resolves to null so the caller simply keeps whatever cart\n * this browser already had.\n */\nexport async function fetchResumedCart(token: string): Promise<ResumedCart | null> {\n try {\n const cfg = getConfig();\n const res = await fetch(`${cfg.apiBase}/cart/resume?token=${encodeURIComponent(token)}`, {\n headers: { 'X-Tenant-Key': cfg.tenantKey },\n });\n if (!res.ok) return null;\n const body = (await res.json()) as Partial<ResumedCart>;\n if (!body.cartId || !Array.isArray(body.items) || body.items.length === 0) return null;\n return {\n cartId: body.cartId,\n items: body.items,\n unavailable: Array.isArray(body.unavailable) ? body.unavailable : [],\n promoCode: body.promoCode ?? null,\n subtotalCents: typeof body.subtotalCents === 'number' ? body.subtotalCents : 0,\n };\n } catch {\n return null;\n }\n}\n\n/** Read the `?cart=` token from the current URL. */\nexport function readCartToken(): string | null {\n try {\n const token = new URLSearchParams(window.location.search).get('cart');\n return token && token.length > 0 ? token : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Drop `?cart=` from the address bar once it's been redeemed, so a refresh (or\n * a shared URL) doesn't re-run the restore over a cart the shopper has since\n * edited. History is replaced, not pushed — the token was never a page.\n */\nexport function stripCartToken(): void {\n try {\n const url = new URL(window.location.href);\n if (!url.searchParams.has('cart')) return;\n url.searchParams.delete('cart');\n window.history.replaceState({}, '', url.toString());\n } catch {\n /* no history API — leaving the param is harmless */\n }\n}\n"]}
@@ -1788,6 +1788,183 @@ declare const adminCatalogApi: {
1788
1788
  success: boolean;
1789
1789
  }>;
1790
1790
  };
1791
+ type CatalogConversionStage = 'not_started' | 'ready_to_commit' | 'active_not_committed' | 'committed_not_active' | 'converted' | 'not_convertible';
1792
+ /** One blocker / warning / note. `rows` is evidence for support, not for display. */
1793
+ interface CatalogConversionFinding {
1794
+ /** Stable machine code, e.g. `renewal_in_flight`. Branch on this, never on the prose. */
1795
+ code: string;
1796
+ check: string;
1797
+ /** The backend's explanation, in plain English. */
1798
+ message: string;
1799
+ rowCount: number;
1800
+ rows: unknown[];
1801
+ truncated: boolean;
1802
+ }
1803
+ /** The three product fields a conversion changes, and nothing else. */
1804
+ interface CatalogConversionPointers {
1805
+ apex_drug_id: string | null;
1806
+ apex_sku_id: string | null;
1807
+ dosage_prices: unknown[];
1808
+ }
1809
+ type CatalogConversionTarget = {
1810
+ kind: 'existing';
1811
+ itemId: string;
1812
+ itemName: string;
1813
+ doseModel: string | null;
1814
+ active: boolean;
1815
+ /** An earlier `prepare` of this product created it. */
1816
+ createdByConversion: boolean;
1817
+ } | {
1818
+ kind: 'create_from_drug';
1819
+ drugId: string;
1820
+ doseModel: null;
1821
+ };
1822
+ /** A stored value the conversion must decide for. */
1823
+ interface CatalogConversionSource {
1824
+ /** A price entry, the single-dose binding, or a label only subscribers hold. */
1825
+ field: 'dosage_prices' | 'apex_sku_id' | 'subscriber_dose';
1826
+ dosage: string | null;
1827
+ apexSkuId: string | null;
1828
+ price: number | null;
1829
+ savingsPrice: number | null;
1830
+ /** Open renewal cycles of this product stored on this label. */
1831
+ subscriberCount: number;
1832
+ /** A price entry bound to the same id as the single-dose binding: its match re-keys both. */
1833
+ alsoKeysApexSkuId?: boolean;
1834
+ }
1835
+ interface CatalogConversionDoseMatch {
1836
+ source: CatalogConversionSource;
1837
+ suggestedDoseId: string | null;
1838
+ /** How the suggestion was found; null when there is none. */
1839
+ how: 'source_sku' | 'exact_label' | 'already_bound' | null;
1840
+ }
1841
+ interface CatalogConversionDose {
1842
+ id: string;
1843
+ label: string;
1844
+ active: boolean;
1845
+ /** Offered right now: the only doses a match may name. */
1846
+ live: boolean;
1847
+ sourceSkuId: string | null;
1848
+ }
1849
+ interface CatalogConversionRun {
1850
+ runId: string;
1851
+ planHash: string | null;
1852
+ itemId: string;
1853
+ appliedAt: string;
1854
+ actor: string;
1855
+ activated: boolean;
1856
+ }
1857
+ interface CatalogConversionPreview {
1858
+ tenantId: string;
1859
+ productId: string;
1860
+ generatedAt: string;
1861
+ stage: CatalogConversionStage;
1862
+ /** No blockers, and a step is available. */
1863
+ eligible: boolean;
1864
+ nextStep: 'prepare' | 'commit' | 'none';
1865
+ nextStepDescription: string;
1866
+ drugListMode: {
1867
+ header: string | null;
1868
+ effective: 'mixed' | 'catalog_only';
1869
+ } | null;
1870
+ product: {
1871
+ id: string;
1872
+ name: string;
1873
+ pricingMode: string;
1874
+ current: CatalogConversionPointers;
1875
+ };
1876
+ target: CatalogConversionTarget | null;
1877
+ /** False until the target item exists (create-from-drug): suggestions are all null then. */
1878
+ dosesKnown: boolean;
1879
+ doses: CatalogConversionDose[];
1880
+ doseMatches: CatalogConversionDoseMatch[];
1881
+ plannedAfter: CatalogConversionPointers | null;
1882
+ strengthsAfter: Array<{
1883
+ dosage: string;
1884
+ apexSkuId: string | null;
1885
+ price: number | null;
1886
+ priceSource: string | null;
1887
+ needsPrice: boolean;
1888
+ }>;
1889
+ blockers: CatalogConversionFinding[];
1890
+ warnings: CatalogConversionFinding[];
1891
+ info: CatalogConversionFinding[];
1892
+ /** The conversion currently in force for this product, if any. */
1893
+ conversion: CatalogConversionRun | null;
1894
+ /** Fingerprint of everything the next step acts on; null when nothing can be planned. */
1895
+ planHash: string | null;
1896
+ /** Operator-facing text; the editor renders the structured fields instead. */
1897
+ summary: string;
1898
+ }
1899
+ interface CatalogConversionPrepareResult {
1900
+ status: 'prepared' | 'already_prepared';
1901
+ itemId: string;
1902
+ correctedActive?: boolean;
1903
+ preview: CatalogConversionPreview;
1904
+ message: string;
1905
+ }
1906
+ /** The admin's choice for one source: a live dose of the item, or `null` = not carried over. */
1907
+ interface CatalogConversionChoice {
1908
+ source: {
1909
+ dosage: string | null;
1910
+ apexSkuId: string | null;
1911
+ };
1912
+ doseId: string | null;
1913
+ }
1914
+ interface CatalogConversionCommitResult {
1915
+ status: 'converted' | 'already_converted';
1916
+ runId: string;
1917
+ itemId: string;
1918
+ before: CatalogConversionPointers;
1919
+ after: CatalogConversionPointers;
1920
+ activatedNow: boolean;
1921
+ warnings: CatalogConversionFinding[];
1922
+ preview: CatalogConversionPreview;
1923
+ message: string;
1924
+ }
1925
+ interface CatalogConversionUndoOptions {
1926
+ /** Also switch the catalog item off. The backend refuses when something else still needs it. */
1927
+ deactivateItem?: boolean;
1928
+ /** Overwrite edits made to the product's pointers since the conversion. */
1929
+ force?: boolean;
1930
+ }
1931
+ interface CatalogConversionUndoResult {
1932
+ status: 'undone';
1933
+ runId: string;
1934
+ itemId: string;
1935
+ restored: CatalogConversionPointers;
1936
+ overwrittenEdit: CatalogConversionPointers | null;
1937
+ otherProductsOnItem: string[];
1938
+ item: {
1939
+ id: string;
1940
+ deactivated: boolean;
1941
+ stillActive: boolean | null;
1942
+ deactivationRefused: string[];
1943
+ };
1944
+ requestsOnCatalogId: {
1945
+ count: number;
1946
+ rows: unknown[];
1947
+ };
1948
+ /** Plainly: what this did NOT undo. */
1949
+ notUndone: string[];
1950
+ message: string;
1951
+ }
1952
+ declare const adminCatalogConversionApi: {
1953
+ /** Where the product stands and what the next step would do. Read-only; safe to repeat. */
1954
+ preview(productId: string): Promise<CatalogConversionPreview>;
1955
+ /** Creates the catalog item INACTIVE (nothing is sold from it). Idempotent server-side. */
1956
+ prepare(productId: string, planHash: string): Promise<CatalogConversionPrepareResult>;
1957
+ /**
1958
+ * Activates the item and re-points the product. Takes about 35 seconds; never
1959
+ * retry it blindly — re-read the preview first.
1960
+ */
1961
+ commit(productId: string, body: {
1962
+ planHash: string;
1963
+ doseMatches: CatalogConversionChoice[];
1964
+ }): Promise<CatalogConversionCommitResult>;
1965
+ /** Puts a converted product back as it was. Does not undo everything — read `notUndone`. */
1966
+ undo(productId: string, options?: CatalogConversionUndoOptions): Promise<CatalogConversionUndoResult>;
1967
+ };
1791
1968
  declare const adminApi: {
1792
1969
  getDashboard(): Promise<AdminDashboardStats>;
1793
1970
  getRecurringRevenue(): Promise<AdminRecurringRevenue>;
@@ -2574,4 +2751,4 @@ declare const affiliatePortalApi: {
2574
2751
  track(refCode: string, landingPage?: string): Promise<AffiliateTrackResponse>;
2575
2752
  };
2576
2753
 
2577
- export { type AffiliateClickRecord as $, type AddressVerifyResult as A, type AdminOrphanReason as B, type AdminOrphanedDosePrice as C, type AdminPayment as D, type AdminPaymentDetail as E, type AdminProduct as F, type AdminProductOverlayField as G, type AdminProductStrength as H, type AdminPromoCode as I, type AdminPromoCodeInput as J, type AdminRecurringPricePoint as K, type AdminRecurringRevenue as L, type AdminRefundResult as M, type AdminSale as N, type AdminSaleInput as O, type AdminScheduledRefund as P, type AdminScheduledRefundProblem as Q, type AdminSubscription as R, type AdminSubscriptionDetail as S, type AdminSubscriptionPatch as T, type AdminSubscriptionWriteResult as U, type AdminSupportCustomer as V, type AdminSupportStats as W, type AdminSupportThread as X, type AdminWebhookEvent as Y, type Affiliate as Z, type AffiliateAuthTokens as _, type AdminApexDrug as a, type MemberSurveyTranscriptSection as a$, type AffiliateConversion as a0, type AffiliateDashboardLinks as a1, type AffiliateDashboardProfile as a2, type AffiliateDashboardStats as a3, type AffiliateDownlineMember as a4, type AffiliateEarningsBreakdown as a5, type AffiliatePaymentMethod as a6, type AffiliateProgram as a7, type AffiliateRegisterInput as a8, type AffiliateRegisterResponse as a9, type CatalogReadiness as aA, type CategoryMetadata as aB, type CheckoutAddress as aC, type CheckoutPayload as aD, type CheckoutResult as aE, type CommissionConfig as aF, type CommissionStatus as aG, type CompleteSurveyPayload as aH, type CreateAffiliatePayload as aI, type CreateAffiliateProgramPayload as aJ, type CreateOrderPayload as aK, type CreateRequestPayload as aL, type CreateSubscriptionPayload as aM, type CustomTemplate as aN, type CustomTemplateInput as aO, type CustomerDiscountConfig as aP, type DeliveryInfo as aQ, type DiscountType as aR, type EmailNotificationSettings as aS, type EmailTemplatesMap as aT, type LoginPayload as aU, type MemberOffer as aV, type MemberPrescriptionRequest as aW, type MemberSurveyMode as aX, type MemberSurveyResponseSummary as aY, type MemberSurveyTranscript as aZ, type MemberSurveyTranscriptItem as a_, type AffiliateSession as aa, type AffiliateStatsResponse as ab, type AffiliateStatus as ac, type AffiliateTrackResponse as ad, ApiError as ae, type ApiResponse as af, type AttributionMethod as ag, type AuthTokens as ah, type BillingReminderSettings as ai, type CatalogAvailabilityItem as aj, type CatalogAvailabilityReason as ak, type CatalogAvailabilityResult as al, type CatalogClassification as am, type CatalogDose as an, type CatalogDoseInput as ao, type CatalogDoseModel as ap, type CatalogDoseSuggestion as aq, type CatalogDoseSuggestions as ar, type CatalogEquivalentSuggestions as as, type CatalogFulfillment as at, type CatalogFulfillmentInput as au, type CatalogItem as av, type CatalogItemInput as aw, type CatalogMappableDrug as ax, type CatalogMatrixCell as ay, type CatalogProduct as az, type AdminApexItemStatus as b, onTokensCleared as b$, type MembersMeResponse as b0, type OfferGrantState as b1, type Order as b2, type OrderItemInput as b3, type PaginationParams as b4, type PaymentCallbackPayload as b5, type PaymentInitiatePayload as b6, type PaymentType as b7, type PendingRenewalSurvey as b8, type Placeholder as b9, type TenantFeature as bA, type TenantFeatureAccess as bB, type TokenTrackName as bC, type UpdateAffiliatePayload as bD, type UpdateAffiliateProgramPayload as bE, type UpdatePaymentMethodPayload as bF, type UpdateProfilePayload as bG, type User as bH, addressesApi as bI, adminAffiliatesApi as bJ, adminApi as bK, adminCatalogApi as bL, affiliateAuthStorageKey as bM, affiliatePortalApi as bN, apexApi as bO, apiFetch as bP, authApi as bQ, authStorageKey as bR, catalogApi as bS, clearAffiliateTokens as bT, clearTokens as bU, getAffiliateTokens as bV, getTokens as bW, membersApi as bX, messagesApi as bY, newIdempotencyKey as bZ, offersApi as b_, type PlaceholderKind as ba, type ProductSaleSummary as bb, type PromoValidationResponse as bc, type PublicCategory as bd, type RegisterAndSubscribePayload as be, type RegisterPayload as bf, type RenewalStatus as bg, SUPPORT_ATTACHMENT_MAX_BYTES as bh, SUPPORT_ATTACHMENT_MIME_TYPES as bi, type SelectDrugPayload as bj, type SendMessagePayload as bk, type SendToPharmacyPayload as bl, type SubscriptionPreview as bm, type SubscriptionPreviewLine as bn, type SubscriptionPreviewPayload as bo, type SupportAttachment as bp, type SupportChannel as bq, type SupportChannelSettings as br, type SupportMessage as bs, type SupportRealtimeToken as bt, type SupportThread as bu, type SupportThreadCategory as bv, type SupportThreadStatus as bw, type SurveySubmitPayload as bx, type TemplatePlaceholdersMap as by, type TemplateText as bz, type AdminBillingAttempt as c, ordersApi as c0, paymentsApi as c1, productsApi as c2, promoCodesApi as c3, setAffiliateTokens as c4, setTokens as c5, subscriptionsApi as c6, supportApi as c7, usersApi as c8, type AdminCategory as d, type AdminCategoryInput as e, type AdminCategoryUpdate as f, type AdminCustomer as g, type AdminCustomerFacts as h, type AdminCustomerFunnel as i, type AdminCustomerListParams as j, type AdminCustomerOverview as k, type AdminCustomerProfile as l, type AdminCustomerRequest as m, type AdminCustomerRow as n, type AdminCustomerSupport as o, type AdminCustomerSupportThread as p, type AdminDashboardStats as q, type AdminLifecycle as r, type AdminLifecycleBucket as s, type AdminListParams as t, type AdminOffer as u, type AdminOfferBase as v, type AdminOfferGrant as w, type AdminOfferGrantBase as x, type AdminOfferInput as y, type AdminOrderSummary as z };
2754
+ export { type AffiliateClickRecord as $, type AddressVerifyResult as A, type AdminOrphanReason as B, type AdminOrphanedDosePrice as C, type AdminPayment as D, type AdminPaymentDetail as E, type AdminProduct as F, type AdminProductOverlayField as G, type AdminProductStrength as H, type AdminPromoCode as I, type AdminPromoCodeInput as J, type AdminRecurringPricePoint as K, type AdminRecurringRevenue as L, type AdminRefundResult as M, type AdminSale as N, type AdminSaleInput as O, type AdminScheduledRefund as P, type AdminScheduledRefundProblem as Q, type AdminSubscription as R, type AdminSubscriptionDetail as S, type AdminSubscriptionPatch as T, type AdminSubscriptionWriteResult as U, type AdminSupportCustomer as V, type AdminSupportStats as W, type AdminSupportThread as X, type AdminWebhookEvent as Y, type Affiliate as Z, type AffiliateAuthTokens as _, type AdminApexDrug as a, type CustomTemplate as a$, type AffiliateConversion as a0, type AffiliateDashboardLinks as a1, type AffiliateDashboardProfile as a2, type AffiliateDashboardStats as a3, type AffiliateDownlineMember as a4, type AffiliateEarningsBreakdown as a5, type AffiliatePaymentMethod as a6, type AffiliateProgram as a7, type AffiliateRegisterInput as a8, type AffiliateRegisterResponse as a9, type CatalogConversionUndoResult as aA, type CatalogDose as aB, type CatalogDoseInput as aC, type CatalogDoseModel as aD, type CatalogDoseSuggestion as aE, type CatalogDoseSuggestions as aF, type CatalogEquivalentSuggestions as aG, type CatalogFulfillment as aH, type CatalogFulfillmentInput as aI, type CatalogItem as aJ, type CatalogItemInput as aK, type CatalogMappableDrug as aL, type CatalogMatrixCell as aM, type CatalogProduct as aN, type CatalogReadiness as aO, type CategoryMetadata as aP, type CheckoutAddress as aQ, type CheckoutPayload as aR, type CheckoutResult as aS, type CommissionConfig as aT, type CommissionStatus as aU, type CompleteSurveyPayload as aV, type CreateAffiliatePayload as aW, type CreateAffiliateProgramPayload as aX, type CreateOrderPayload as aY, type CreateRequestPayload as aZ, type CreateSubscriptionPayload as a_, type AffiliateSession as aa, type AffiliateStatsResponse as ab, type AffiliateStatus as ac, type AffiliateTrackResponse as ad, ApiError as ae, type ApiResponse as af, type AttributionMethod as ag, type AuthTokens as ah, type BillingReminderSettings as ai, type CatalogAvailabilityItem as aj, type CatalogAvailabilityReason as ak, type CatalogAvailabilityResult as al, type CatalogClassification as am, type CatalogConversionChoice as an, type CatalogConversionCommitResult as ao, type CatalogConversionDose as ap, type CatalogConversionDoseMatch as aq, type CatalogConversionFinding as ar, type CatalogConversionPointers as as, type CatalogConversionPrepareResult as at, type CatalogConversionPreview as au, type CatalogConversionRun as av, type CatalogConversionSource as aw, type CatalogConversionStage as ax, type CatalogConversionTarget as ay, type CatalogConversionUndoOptions as az, type AdminApexItemStatus as b, affiliateAuthStorageKey as b$, type CustomTemplateInput as b0, type CustomerDiscountConfig as b1, type DeliveryInfo as b2, type DiscountType as b3, type EmailNotificationSettings as b4, type EmailTemplatesMap as b5, type LoginPayload as b6, type MemberOffer as b7, type MemberPrescriptionRequest as b8, type MemberSurveyMode as b9, type SubscriptionPreview as bA, type SubscriptionPreviewLine as bB, type SubscriptionPreviewPayload as bC, type SupportAttachment as bD, type SupportChannel as bE, type SupportChannelSettings as bF, type SupportMessage as bG, type SupportRealtimeToken as bH, type SupportThread as bI, type SupportThreadCategory as bJ, type SupportThreadStatus as bK, type SurveySubmitPayload as bL, type TemplatePlaceholdersMap as bM, type TemplateText as bN, type TenantFeature as bO, type TenantFeatureAccess as bP, type TokenTrackName as bQ, type UpdateAffiliatePayload as bR, type UpdateAffiliateProgramPayload as bS, type UpdatePaymentMethodPayload as bT, type UpdateProfilePayload as bU, type User as bV, addressesApi as bW, adminAffiliatesApi as bX, adminApi as bY, adminCatalogApi as bZ, adminCatalogConversionApi as b_, type MemberSurveyResponseSummary as ba, type MemberSurveyTranscript as bb, type MemberSurveyTranscriptItem as bc, type MemberSurveyTranscriptSection as bd, type MembersMeResponse as be, type OfferGrantState as bf, type Order as bg, type OrderItemInput as bh, type PaginationParams as bi, type PaymentCallbackPayload as bj, type PaymentInitiatePayload as bk, type PaymentType as bl, type PendingRenewalSurvey as bm, type Placeholder as bn, type PlaceholderKind as bo, type ProductSaleSummary as bp, type PromoValidationResponse as bq, type PublicCategory as br, type RegisterAndSubscribePayload as bs, type RegisterPayload as bt, type RenewalStatus as bu, SUPPORT_ATTACHMENT_MAX_BYTES as bv, SUPPORT_ATTACHMENT_MIME_TYPES as bw, type SelectDrugPayload as bx, type SendMessagePayload as by, type SendToPharmacyPayload as bz, type AdminBillingAttempt as c, affiliatePortalApi as c0, apexApi as c1, apiFetch as c2, authApi as c3, authStorageKey as c4, catalogApi as c5, clearAffiliateTokens as c6, clearTokens as c7, getAffiliateTokens as c8, getTokens as c9, membersApi as ca, messagesApi as cb, newIdempotencyKey as cc, offersApi as cd, onTokensCleared as ce, ordersApi as cf, paymentsApi as cg, productsApi as ch, promoCodesApi as ci, setAffiliateTokens as cj, setTokens as ck, subscriptionsApi as cl, supportApi as cm, usersApi as cn, type AdminCategory as d, type AdminCategoryInput as e, type AdminCategoryUpdate as f, type AdminCustomer as g, type AdminCustomerFacts as h, type AdminCustomerFunnel as i, type AdminCustomerListParams as j, type AdminCustomerOverview as k, type AdminCustomerProfile as l, type AdminCustomerRequest as m, type AdminCustomerRow as n, type AdminCustomerSupport as o, type AdminCustomerSupportThread as p, type AdminDashboardStats as q, type AdminLifecycle as r, type AdminLifecycleBucket as s, type AdminListParams as t, type AdminOffer as u, type AdminOfferBase as v, type AdminOfferGrant as w, type AdminOfferGrantBase as x, type AdminOfferInput as y, type AdminOrderSummary as z };
@@ -1,5 +1,5 @@
1
1
  import { Accessor, Resource } from 'solid-js';
2
- import { A as AddressVerifyResult, aC as CheckoutAddress, al as CatalogAvailabilityResult, bH as User, aQ as DeliveryInfo, bg as RenewalStatus, b8 as PendingRenewalSurvey, s as AdminLifecycleBucket, k as AdminCustomerOverview, S as AdminSubscriptionDetail, m as AdminCustomerRequest, bv as SupportThreadCategory, bq as SupportChannel, az as CatalogProduct, a0 as AffiliateConversion, a4 as AffiliateDownlineMember, a1 as AffiliateDashboardLinks, a3 as AffiliateDashboardStats, bc as PromoValidationResponse, aV as MemberOffer, am as CatalogClassification, ap as CatalogDoseModel, C as AdminOrphanedDosePrice, F as AdminProduct, av as CatalogItem, aq as CatalogDoseSuggestion, ax as CatalogMappableDrug, as as CatalogEquivalentSuggestions, aA as CatalogReadiness } from '../client-B07yeMS8.js';
2
+ import { A as AddressVerifyResult, aQ as CheckoutAddress, al as CatalogAvailabilityResult, bV as User, b2 as DeliveryInfo, bu as RenewalStatus, bm as PendingRenewalSurvey, s as AdminLifecycleBucket, k as AdminCustomerOverview, S as AdminSubscriptionDetail, m as AdminCustomerRequest, bJ as SupportThreadCategory, bE as SupportChannel, aN as CatalogProduct, a0 as AffiliateConversion, a4 as AffiliateDownlineMember, a1 as AffiliateDashboardLinks, a3 as AffiliateDashboardStats, bq as PromoValidationResponse, b7 as MemberOffer, am as CatalogClassification, aD as CatalogDoseModel, C as AdminOrphanedDosePrice, F as AdminProduct, aJ as CatalogItem, aE as CatalogDoseSuggestion, aL as CatalogMappableDrug, aG as CatalogEquivalentSuggestions, aO as CatalogReadiness, aA as CatalogConversionUndoResult, au as CatalogConversionPreview, aq as CatalogConversionDoseMatch, aw as CatalogConversionSource, ap as CatalogConversionDose, az as CatalogConversionUndoOptions, ao as CatalogConversionCommitResult, ar as CatalogConversionFinding, an as CatalogConversionChoice } from '../client-oZcZn-HB.js';
3
3
  import { C as CartItem } from '../cart-o6DpAu5y.js';
4
4
  export { U as UseSurveyV2FlowOptions, u as useSurveyV2Flow } from '../surveyV2-BgQHK0GE.js';
5
5
  import { EmbedEvent } from '@apextelemed/survey-solid';
@@ -2093,6 +2093,304 @@ declare function addCatalogItemAsProduct(itemId: string, name: string): Promise<
2093
2093
  */
2094
2094
  declare function createCatalogProduct(input: NewCatalogProductInput): Promise<CreateCatalogProductOutcome>;
2095
2095
 
2096
+ /**
2097
+ * "Convert to catalog product": move ONE legacy prescribed product (its
2098
+ * `apexDrugId` is an individual pharmacy drug) onto a partner catalog item, and
2099
+ * back — the headless flow behind the product editor's guided panel.
2100
+ *
2101
+ * The backend owns the state machine and reports the stage the product is in on
2102
+ * every read; this flow only ever renders that stage. What the admin sees is
2103
+ * decided by the server's preview, never by what this screen remembers:
2104
+ *
2105
+ * not_started → `ready` the catalog item doesn't exist yet: PREPARE creates it
2106
+ * INACTIVE (nothing is sold from it, the product is untouched)
2107
+ * ready_to_commit → `reviewing` the item exists: match strengths, then CONVERT
2108
+ * active_not_committed → `reviewing` (`unfinished`) a conversion switched the item on and the
2109
+ * re-point didn't land; converting again re-points only
2110
+ * committed_not_active → `finish_activation` re-pointed, but the item isn't listed
2111
+ * converted → `converted` undo is available while the backend records the run
2112
+ * not_convertible / any blocker → `blocked`
2113
+ *
2114
+ * Rules this flow keeps:
2115
+ *
2116
+ * - A write is never retried blindly. After ANY failure — a refusal, a 5xx, a
2117
+ * dropped connection, a proxy timeout — the preview is re-read and the stage
2118
+ * it reports is what gets rendered. A write is offered again only from a
2119
+ * stage in which it is a fresh decision, and prepare/convert only ever with
2120
+ * the `planHash` of the preview the admin is looking at.
2121
+ * - When the answer to a convert was lost the server may STILL be working (it
2122
+ * takes about 35 seconds). That is `watching`: read-only polling for a
2123
+ * bounded time, no write offered, until the stage settles.
2124
+ * - `plan_changed` shows the fresh preview and puts the admin back in review.
2125
+ * The old matches are dropped, never resubmitted.
2126
+ * - Every source (a price entry, the single-dose binding, a label subscribers
2127
+ * hold) must end with a strength of the new item or an explicit "not carried
2128
+ * over" before Convert can be sent. A suggestion pre-selects; no suggestion
2129
+ * leaves the row undecided. The two rules the backend would refuse a `null`
2130
+ * for are mirrored here so they aren't offered.
2131
+ * - Reviewing and confirming are separate acts (`confirmReview`), and a changed
2132
+ * plan clears the confirmation.
2133
+ *
2134
+ * The decision logic (matches, blockers, the confirm summary, error sorting) is
2135
+ * exported as pure functions and tested without a component tree.
2136
+ */
2137
+
2138
+ /** A legacy prescribed product: it has an Apex pointer, and the pointer is a
2139
+ * pharmacy drug rather than a catalog item. Non-Rx and catalog products never
2140
+ * show "Convert to catalog product". */
2141
+ declare function canOfferConversion(product: Pick<AdminProduct, 'apexDrugId' | 'catalogOverlay'>): boolean;
2142
+ type ConversionFailure =
2143
+ /** The server said no, and said it before doing anything: 4xx. */
2144
+ {
2145
+ kind: 'refused';
2146
+ message: string;
2147
+ status: number;
2148
+ code?: string;
2149
+ }
2150
+ /** `plan_changed`: what the admin reviewed is no longer the plan. */
2151
+ | {
2152
+ kind: 'plan_changed';
2153
+ message: string;
2154
+ }
2155
+ /** `conversion_in_progress`: a step for this product is running on the server right now. */
2156
+ | {
2157
+ kind: 'in_progress';
2158
+ message: string;
2159
+ }
2160
+ /** The request may or may not have landed (dropped connection, proxy timeout, 5xx).
2161
+ * `serverFinished`: the backend answered with its own `code`, so its attempt is over;
2162
+ * without one the answer never reached us and the server may still be working. */
2163
+ | {
2164
+ kind: 'ambiguous';
2165
+ message: string;
2166
+ serverFinished: boolean;
2167
+ code?: string;
2168
+ };
2169
+ /**
2170
+ * Sort a thrown error into what the flow can do about it. Duck-typed on
2171
+ * `status` / `code` / `ambiguous` (what `ApiError` carries); branches on codes
2172
+ * and statuses, never on message prose.
2173
+ */
2174
+ declare function classifyConversionError(err: unknown): ConversionFailure;
2175
+ interface FindingCopy {
2176
+ /** A plain-language headline for a code we know. Null: the backend's text is all there is. */
2177
+ title: string | null;
2178
+ /** The backend's own explanation, verbatim. */
2179
+ message: string;
2180
+ }
2181
+ /** Warnings that describe the SUGGESTED matches; once the admin changes one they
2182
+ * no longer describe what will happen (the review step recomputes them). */
2183
+ declare const MATCH_DEPENDENT_WARNINGS: readonly string[];
2184
+ declare function explainFinding(finding: Pick<CatalogConversionFinding, 'code' | 'message'>): FindingCopy;
2185
+ /** A choice for one source: a dose id of the new item; `null` = not carried over;
2186
+ * absent from the record = not decided yet. */
2187
+ type MatchChoice = string | null;
2188
+ type MatchRecord = Readonly<Record<string, MatchChoice | undefined>>;
2189
+ /** The key a source goes by: the same pair the backend identifies it with. */
2190
+ declare const sourceKey: (source: Pick<CatalogConversionSource, "dosage" | "apexSkuId">) => string;
2191
+ /** What the admin knows a source as. */
2192
+ declare function sourceLabel(source: CatalogConversionSource): string;
2193
+ declare const SOURCE_FIELD_NOTE: Record<CatalogConversionSource['field'], string | null>;
2194
+ declare const MATCH_HOW_LABEL: Record<NonNullable<CatalogConversionDoseMatch['how']>, string>;
2195
+ /** The strengths a match may name: the item's LIVE doses, in the order given. */
2196
+ declare const liveDoses: (preview: Pick<CatalogConversionPreview, "doses">) => CatalogConversionDose[];
2197
+ /**
2198
+ * Whether "not carried over" is a choice the backend would accept for a source.
2199
+ * It refuses the single-dose binding (a legacy pack id on a catalog product is
2200
+ * refused at intake), and a source with no id whose label a live dose carries
2201
+ * exactly (it would keep matching by label whatever is chosen).
2202
+ */
2203
+ declare function canLeaveUnmatched(match: CatalogConversionDoseMatch, doses: readonly CatalogConversionDose[]): boolean;
2204
+ /** The pre-fill: each suggestion chosen, every other source undecided. */
2205
+ declare function initialMatches(preview: Pick<CatalogConversionPreview, 'doseMatches'>): MatchRecord;
2206
+ type MatchProblem = 'undecided' | 'not_offered' | 'cannot_be_left';
2207
+ /** What stops a source's choice being sent. Empty: it can go. */
2208
+ declare function matchProblem(match: CatalogConversionDoseMatch, choice: MatchChoice | undefined, doses: readonly CatalogConversionDose[]): MatchProblem | null;
2209
+ declare const matchesComplete: (preview: CatalogConversionPreview, matches: MatchRecord) => boolean;
2210
+ /** The body `commit` is sent, or null while any source is undecided or invalid. */
2211
+ declare function toChoices(preview: CatalogConversionPreview, matches: MatchRecord): CatalogConversionChoice[] | null;
2212
+ /** Sources with subscribers that would be left behind: flagged for review at their next renewal. */
2213
+ declare function flaggedSubscribers(preview: Pick<CatalogConversionPreview, 'doseMatches'>, matches: MatchRecord): Array<{
2214
+ source: CatalogConversionSource;
2215
+ subscribers: number;
2216
+ }>;
2217
+ interface ConversionSummary {
2218
+ itemId: string | null;
2219
+ itemName: string | null;
2220
+ carried: Array<{
2221
+ label: string;
2222
+ price: number | null;
2223
+ doseLabel: string;
2224
+ subscribers: number;
2225
+ }>;
2226
+ /** Not carried over: kept on file, never sold. `price` null for a source with no price. */
2227
+ left: Array<{
2228
+ label: string;
2229
+ price: number | null;
2230
+ subscribers: number;
2231
+ }>;
2232
+ /** Subscribers who will be flagged for review at their next renewal. */
2233
+ flaggedSubscribers: number;
2234
+ /** What the new item's strengths sell for after the switch. */
2235
+ strengthsAfter: Array<{
2236
+ label: string;
2237
+ doseId: string;
2238
+ price: number | null;
2239
+ fromBase: boolean;
2240
+ needsPrice: boolean;
2241
+ }>;
2242
+ }
2243
+ /**
2244
+ * What converting with THESE matches does, worked out the way the backend prices
2245
+ * a catalog product: a strength sells at the first priced entry matched to it,
2246
+ * else at the product's base price (a flat-fee product always charges the base
2247
+ * price); with neither it needs a price.
2248
+ */
2249
+ declare function describeConversion(preview: CatalogConversionPreview, matches: MatchRecord, basePrice: number | null): ConversionSummary;
2250
+ declare const hasBlockers: (p: CatalogConversionPreview) => boolean;
2251
+ /** A conversion in force for this product (the run an undo would reverse). */
2252
+ declare const hasConversion: (p: CatalogConversionPreview | null) => boolean;
2253
+ type ConversionNotice = {
2254
+ tone: 'info' | 'success' | 'warn' | 'danger';
2255
+ message: string;
2256
+ /** The backend's refusal code, when there was one. */
2257
+ code?: string;
2258
+ };
2259
+ type ConversionState =
2260
+ /** Not enabled: nothing has been read. */
2261
+ {
2262
+ kind: 'idle';
2263
+ }
2264
+ /** Reading the server's state (the first read, a re-read after a write, or "check again"). */
2265
+ | {
2266
+ kind: 'loading';
2267
+ reason: 'initial' | 'reconcile' | 'refresh';
2268
+ }
2269
+ /** The server's state couldn't be read, so nothing is offered but another read. */
2270
+ | {
2271
+ kind: 'unreadable';
2272
+ message: string;
2273
+ afterWrite: boolean;
2274
+ }
2275
+ /** Not convertible right now (not_convertible, or any blocker). Blockers are on the preview. */
2276
+ | {
2277
+ kind: 'blocked';
2278
+ }
2279
+ /** `not_started`: the catalog item doesn't exist yet. */
2280
+ | {
2281
+ kind: 'ready';
2282
+ } | {
2283
+ kind: 'preparing';
2284
+ }
2285
+ /** `ready_to_commit` / `active_not_committed`: match strengths, then convert. */
2286
+ | {
2287
+ kind: 'reviewing';
2288
+ unfinished: boolean;
2289
+ confirming: boolean;
2290
+ }
2291
+ /** The long one (about 35 seconds). `resume`: activation only, no re-point. */
2292
+ | {
2293
+ kind: 'committing';
2294
+ resume: 'convert' | 'activation';
2295
+ }
2296
+ /** The answer was lost and the server may still be working: read-only polling. */
2297
+ | {
2298
+ kind: 'watching';
2299
+ reason: 'dropped' | 'in_progress';
2300
+ }
2301
+ /** `committed_not_active`: re-pointed at an item Apex doesn't list. */
2302
+ | {
2303
+ kind: 'finish_activation';
2304
+ } | {
2305
+ kind: 'converted';
2306
+ origin: 'committed' | 'recovered' | 'existing';
2307
+ } | {
2308
+ kind: 'undoing';
2309
+ }
2310
+ /** The product is back on its legacy drug. `result` is null when the reply was lost. */
2311
+ | {
2312
+ kind: 'undone';
2313
+ result: CatalogConversionUndoResult | null;
2314
+ };
2315
+ interface ConversionConverted {
2316
+ productId: string;
2317
+ origin: 'committed' | 'recovered';
2318
+ warnings: CatalogConversionFinding[];
2319
+ }
2320
+ interface UseCatalogConversionOptions {
2321
+ /** The product being converted (or whose conversion is being managed). */
2322
+ product: Accessor<AdminProduct>;
2323
+ /** False: nothing is read. Default true. */
2324
+ enabled?: Accessor<boolean>;
2325
+ /** Called once when a conversion is confirmed done — this session's convert, or one found finished after a lost answer. */
2326
+ onConverted?: (info: ConversionConverted) => void;
2327
+ /** Called once when an undo is confirmed done. */
2328
+ onUndone?: (info: {
2329
+ productId: string;
2330
+ result: CatalogConversionUndoResult | null;
2331
+ }) => void;
2332
+ /** While `watching`, how often the preview is re-read. Default 5 s. */
2333
+ pollIntervalMs?: number;
2334
+ /** While `watching`, how long to wait before handing the decision back. Default 2 min. */
2335
+ watchWindowMs?: number;
2336
+ }
2337
+ interface CatalogConversion {
2338
+ state: Accessor<ConversionState>;
2339
+ /** The server's last answer. The only source of truth for the stage. */
2340
+ preview: Accessor<CatalogConversionPreview | null>;
2341
+ /** The latest thing worth telling the admin (a refusal, what a lost answer turned out to be). */
2342
+ notice: Accessor<ConversionNotice | null>;
2343
+ dismissNotice: () => void;
2344
+ /** A step is running: nothing else can be started. */
2345
+ busy: Accessor<boolean>;
2346
+ /** Re-read the preview ("check again"). Safe to repeat. */
2347
+ reload: () => Promise<void>;
2348
+ rows: Accessor<MatchRow[]>;
2349
+ /** The strengths of the new item a source can be matched to. */
2350
+ doses: Accessor<CatalogConversionDose[]>;
2351
+ setMatch: (key: string, choice: MatchChoice) => void;
2352
+ /** Mark every undecided source "not carried over" (only those that may be). */
2353
+ leaveUndecidedUnmatched: () => void;
2354
+ resetToSuggestions: () => void;
2355
+ undecidedCount: Accessor<number>;
2356
+ complete: Accessor<boolean>;
2357
+ flagged: Accessor<Array<{
2358
+ source: CatalogConversionSource;
2359
+ subscribers: number;
2360
+ }>>;
2361
+ summary: Accessor<ConversionSummary | null>;
2362
+ /** Review done: show the confirm step. Needs a complete set of matches. */
2363
+ confirmReview: () => boolean;
2364
+ /** Back from the confirm step to the strengths. */
2365
+ backToReview: () => void;
2366
+ prepare: () => Promise<void>;
2367
+ commit: () => Promise<void>;
2368
+ /** `committed_not_active` only: activation, no matches involved. */
2369
+ finishActivation: () => Promise<void>;
2370
+ /** Undo is offered while the backend records a conversion of this product. */
2371
+ canUndo: Accessor<boolean>;
2372
+ undo: (options?: CatalogConversionUndoOptions) => Promise<void>;
2373
+ /** While `watching`: read now instead of waiting for the next poll. */
2374
+ checkNow: () => Promise<void>;
2375
+ /** The convert answer, once it arrived: the warnings that stood for the matches applied. */
2376
+ lastCommit: Accessor<CatalogConversionCommitResult | null>;
2377
+ }
2378
+ interface MatchRow {
2379
+ key: string;
2380
+ match: CatalogConversionDoseMatch;
2381
+ source: CatalogConversionSource;
2382
+ label: string;
2383
+ /** undefined: not decided. null: not carried over. */
2384
+ choice: MatchChoice | undefined;
2385
+ /** Differs from what the backend suggested. */
2386
+ changed: boolean;
2387
+ canLeaveUnmatched: boolean;
2388
+ /** Subscribers who'd be flagged for review at their next renewal. */
2389
+ flagged: boolean;
2390
+ problem: MatchProblem | null;
2391
+ }
2392
+ declare function useCatalogConversion(opts: UseCatalogConversionOptions): CatalogConversion;
2393
+
2096
2394
  /**
2097
2395
  * Shared vocabulary for reading a subscription's status.
2098
2396
  *
@@ -2242,4 +2540,4 @@ declare function restoreCartFromLink(): Promise<ResumedCart | null>;
2242
2540
  */
2243
2541
  declare function startCartCapture(opts?: CartCaptureOptions): () => void;
2244
2542
 
2245
- export { type AccountSource, type AddStrengthInput, type AddStrengthOutcome, type AddressErrors, type AddressPair, type AddressValue, type AffiliateConversionsFlow, type AffiliateDownlineFlow, type AffiliateLinksFlow, type AffiliateStatsFlow, type AnswerValue, type ApexBlockCode, type AttentionAction, type AttentionActionKind, type AttentionItem, type CartCaptureOptions, type CartCheckoutFlow, type CartCheckoutOutcome, type CartCheckoutPricing, type CartDropReason, type CartReconcileState, type CartReconciliation, type CartSource, type CatalogAvailabilityDecision, type CatalogAvailabilityState, type CatalogFailure, type CatalogFlow, CatalogProduct, type CategoryColorOpts, type CheckoutFlow, type CheckoutOutcome, type Conversation, type CreateCatalogProductOutcome, DEFAULT_COLOR_PALETTE, type DashboardActivityItem, type DashboardData, type DashboardRxListItem, type DashboardRxStatus, type DashboardSubscription, type DroppedCartLine, type DrugResult, type FlatStep, type FulfillmentRow, type FulfillmentStage, type FunnelTelemetry, type JourneyState, type JourneyStep, type JourneyStepKey, LIFECYCLE_BUCKETS, LIFECYCLE_LABEL, LIFECYCLE_TONE, LIVE_SUBSCRIPTION_STATUSES, type MatrixView, type MedicationPricing, type MedicationSelectFlow, type MemberPortalData, type MemberPortalRx, type MemberPortalSubscription, type MessagesChannel, type MessagesIntent, type MessagesThread, type NewCatalogProductInput, OFFER_BEATS_PROMO_NOTICE, ORPHAN_REASON, type OfferDiscount, type PricingBreakdown, type ProductCatalogEditor, type ProductDetailFlow, type PromoPricing, READINESS_LABEL, type ReadinessStatus, type ReconcileOptions, type RefillEvent, type RefillView, type RegisterFlow, type RegisterOutcome, type RequestStatus, type ResolvedStrength, type RxRequestStatus, type Severity, type ShipmentInfo, type SignupFlow, type SignupOutcome, type StageState, type StoredDosePrice, type StrengthRow, type StructureState, type SubscribeFlow, type SubscribeOutcome, type SubscriptionIntakeFlow, type SubscriptionIntakeOutcome, type SurveyFlow, type SurveyOption, type SurveyOutcome, type SurveyQuestion, type SurveyResult, TERMINAL_SUBSCRIPTION_STATUSES, type ThreadMessage, type TimelineEvent, type TimelineKind, type Tone, type TrackerRequest, type TrackerRequestStatus, type TrackerSubscription, type TrackerSubscriptionStatus, type TrackerView, type TrackingUrlCarrier, US_STATES, US_STATE_OPTIONS, type UpdatePaymentMethodFlow, type UseAddressPairOptions, type UseCheckoutFlowOptions, type UseMedicationSelectOptions, type UseMessagesThreadOptions, type UseProductCatalogEditorOptions, type UseSignupFlowOptions, type UseSubscribeFlowOptions, type UseSubscriptionIntakeFlowOptions, type UseSurveyFlowOptions, type ValidateAddressOptions, type ValidatedResumedPromo, type VisibilityCondition, accountSource, addCatalogItemAsProduct, applyPriceDrafts, availableStateOptions, availableStates, bestOfferDiscount, buildFulfillmentRows, buildMatrixView, buildRefillView, buildStrengthRows, buildTimeline, buildTrackerView, buildTrackingUrl, captureFunnelEmail, catalogUnavailableMessage, categoryColor, classifyCatalogError, createCatalogProduct, createFunnelTelemetry, deriveAttention, deriveCatalogAvailabilityDecision, deriveJourney, emailGateAnswered, findStoredDosePrice, formatCardNumber, formatConversationTime, formatCvv, formatEventDate, formatExpiry, formatMessageTime, formatRelativeTime, formatStageDate, groupDrugsByPharmacy, hasErrors, isCatalogItemId, isCssColorValue, isLive, isQuestionVisible, isReconcilable, lifecycleReason, lowestPrice, lowestSalePrice, markEmailGateAnswered, moveInOrder, normalizeState, normalizeStates, offerBeatsPromo, offerDurationText, offerSummaryText, primarySubscription, readinessStatus, reconcileCartAgainstCatalog, reconcileCartLines, redeemResumeLink, removeStoredDosePrice, resetResumeRedemption, resolveCategoryColor, resolveStrengthPrices, restoreCartFromLink, salePriceForBase, skuBindingModeFor, startCartCapture, stateAvailabilityNote, toTrackerRequest, upsertDosePrice, useAddressPair, useAffiliateConversions, useAffiliateDownline, useAffiliateLinks, useAffiliateStats, useCartCheckoutFlow, useCartReconcile, useCatalog, useCatalogAvailability, useCheckoutFlow, useDashboardData, useMedicationSelect, useMemberPortalData, useMessagesThread, useProductCatalogEditor, useProductDetail, useRegisterFlow, useSignupFlow, useSubscribeFlow, useSubscriptionIntakeFlow, useSurveyFlow, useUpdatePaymentMethodFlow, validateAddress, validateResumedPromo };
2543
+ export { type AccountSource, type AddStrengthInput, type AddStrengthOutcome, type AddressErrors, type AddressPair, type AddressValue, type AffiliateConversionsFlow, type AffiliateDownlineFlow, type AffiliateLinksFlow, type AffiliateStatsFlow, type AnswerValue, type ApexBlockCode, type AttentionAction, type AttentionActionKind, type AttentionItem, type CartCaptureOptions, type CartCheckoutFlow, type CartCheckoutOutcome, type CartCheckoutPricing, type CartDropReason, type CartReconcileState, type CartReconciliation, type CartSource, type CatalogAvailabilityDecision, type CatalogAvailabilityState, type CatalogConversion, type CatalogFailure, type CatalogFlow, CatalogProduct, type CategoryColorOpts, type CheckoutFlow, type CheckoutOutcome, type Conversation, type ConversionConverted, type ConversionFailure, type ConversionNotice, type ConversionState, type ConversionSummary, type CreateCatalogProductOutcome, DEFAULT_COLOR_PALETTE, type DashboardActivityItem, type DashboardData, type DashboardRxListItem, type DashboardRxStatus, type DashboardSubscription, type DroppedCartLine, type DrugResult, type FindingCopy, type FlatStep, type FulfillmentRow, type FulfillmentStage, type FunnelTelemetry, type JourneyState, type JourneyStep, type JourneyStepKey, LIFECYCLE_BUCKETS, LIFECYCLE_LABEL, LIFECYCLE_TONE, LIVE_SUBSCRIPTION_STATUSES, MATCH_DEPENDENT_WARNINGS, MATCH_HOW_LABEL, type MatchChoice, type MatchProblem, type MatchRecord, type MatchRow, type MatrixView, type MedicationPricing, type MedicationSelectFlow, type MemberPortalData, type MemberPortalRx, type MemberPortalSubscription, type MessagesChannel, type MessagesIntent, type MessagesThread, type NewCatalogProductInput, OFFER_BEATS_PROMO_NOTICE, ORPHAN_REASON, type OfferDiscount, type PricingBreakdown, type ProductCatalogEditor, type ProductDetailFlow, type PromoPricing, READINESS_LABEL, type ReadinessStatus, type ReconcileOptions, type RefillEvent, type RefillView, type RegisterFlow, type RegisterOutcome, type RequestStatus, type ResolvedStrength, type RxRequestStatus, SOURCE_FIELD_NOTE, type Severity, type ShipmentInfo, type SignupFlow, type SignupOutcome, type StageState, type StoredDosePrice, type StrengthRow, type StructureState, type SubscribeFlow, type SubscribeOutcome, type SubscriptionIntakeFlow, type SubscriptionIntakeOutcome, type SurveyFlow, type SurveyOption, type SurveyOutcome, type SurveyQuestion, type SurveyResult, TERMINAL_SUBSCRIPTION_STATUSES, type ThreadMessage, type TimelineEvent, type TimelineKind, type Tone, type TrackerRequest, type TrackerRequestStatus, type TrackerSubscription, type TrackerSubscriptionStatus, type TrackerView, type TrackingUrlCarrier, US_STATES, US_STATE_OPTIONS, type UpdatePaymentMethodFlow, type UseAddressPairOptions, type UseCatalogConversionOptions, type UseCheckoutFlowOptions, type UseMedicationSelectOptions, type UseMessagesThreadOptions, type UseProductCatalogEditorOptions, type UseSignupFlowOptions, type UseSubscribeFlowOptions, type UseSubscriptionIntakeFlowOptions, type UseSurveyFlowOptions, type ValidateAddressOptions, type ValidatedResumedPromo, type VisibilityCondition, accountSource, addCatalogItemAsProduct, applyPriceDrafts, availableStateOptions, availableStates, bestOfferDiscount, buildFulfillmentRows, buildMatrixView, buildRefillView, buildStrengthRows, buildTimeline, buildTrackerView, buildTrackingUrl, canLeaveUnmatched, canOfferConversion, captureFunnelEmail, catalogUnavailableMessage, categoryColor, classifyCatalogError, classifyConversionError, createCatalogProduct, createFunnelTelemetry, deriveAttention, deriveCatalogAvailabilityDecision, deriveJourney, describeConversion, emailGateAnswered, explainFinding, findStoredDosePrice, flaggedSubscribers, formatCardNumber, formatConversationTime, formatCvv, formatEventDate, formatExpiry, formatMessageTime, formatRelativeTime, formatStageDate, groupDrugsByPharmacy, hasBlockers, hasConversion, hasErrors, initialMatches, isCatalogItemId, isCssColorValue, isLive, isQuestionVisible, isReconcilable, lifecycleReason, liveDoses, lowestPrice, lowestSalePrice, markEmailGateAnswered, matchProblem, matchesComplete, moveInOrder, normalizeState, normalizeStates, offerBeatsPromo, offerDurationText, offerSummaryText, primarySubscription, readinessStatus, reconcileCartAgainstCatalog, reconcileCartLines, redeemResumeLink, removeStoredDosePrice, resetResumeRedemption, resolveCategoryColor, resolveStrengthPrices, restoreCartFromLink, salePriceForBase, skuBindingModeFor, sourceKey, sourceLabel, startCartCapture, stateAvailabilityNote, toChoices, toTrackerRequest, upsertDosePrice, useAddressPair, useAffiliateConversions, useAffiliateDownline, useAffiliateLinks, useAffiliateStats, useCartCheckoutFlow, useCartReconcile, useCatalog, useCatalogAvailability, useCatalogConversion, useCheckoutFlow, useDashboardData, useMedicationSelect, useMemberPortalData, useMessagesThread, useProductCatalogEditor, useProductDetail, useRegisterFlow, useSignupFlow, useSubscribeFlow, useSubscriptionIntakeFlow, useSurveyFlow, useUpdatePaymentMethodFlow, validateAddress, validateResumedPromo };