@extenshi/pay 0.7.1 → 0.8.0

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 (86) hide show
  1. package/README.md +11 -9
  2. package/dist/api/mock.d.ts +4 -0
  3. package/dist/api/mock.d.ts.map +1 -1
  4. package/dist/api/pay-api.d.ts +10 -3
  5. package/dist/api/pay-api.d.ts.map +1 -1
  6. package/dist/api/transport.d.ts.map +1 -1
  7. package/dist/core/config.d.ts.map +1 -1
  8. package/dist/core/extenshi-pay.d.ts +21 -2
  9. package/dist/core/extenshi-pay.d.ts.map +1 -1
  10. package/dist/core/locale.d.ts +13 -0
  11. package/dist/core/locale.d.ts.map +1 -0
  12. package/dist/core.d.mts +208 -113
  13. package/dist/core.d.ts +208 -113
  14. package/dist/core.js +204 -14
  15. package/dist/core.js.map +1 -1
  16. package/dist/core.mjs +204 -15
  17. package/dist/core.mjs.map +1 -1
  18. package/dist/extenshi-pay-lite.js +204 -14
  19. package/dist/extenshi-pay-lite.js.map +1 -1
  20. package/dist/extenshi-pay-lite.min.js +3 -2
  21. package/dist/extenshi-pay-lite.min.js.map +1 -1
  22. package/dist/extenshi-pay-lite.mjs +204 -15
  23. package/dist/extenshi-pay-lite.mjs.map +1 -1
  24. package/dist/extenshi-pay.cjs.js +1234 -180
  25. package/dist/extenshi-pay.cjs.js.map +1 -1
  26. package/dist/extenshi-pay.d.ts.map +1 -1
  27. package/dist/extenshi-pay.js +1234 -180
  28. package/dist/extenshi-pay.js.map +1 -1
  29. package/dist/extenshi-pay.min.js +3 -2
  30. package/dist/extenshi-pay.min.js.map +1 -1
  31. package/dist/extenshi-pay.min.mjs +3 -2
  32. package/dist/extenshi-pay.min.mjs.map +1 -1
  33. package/dist/extenshi-pay.mjs +1231 -181
  34. package/dist/extenshi-pay.mjs.map +1 -1
  35. package/dist/index.d.mts +268 -117
  36. package/dist/index.d.ts +268 -117
  37. package/dist/lite.d.mts +176 -82
  38. package/dist/lite.d.ts +176 -82
  39. package/dist/lite.d.ts.map +1 -1
  40. package/dist/payment/checkout.d.ts.map +1 -1
  41. package/dist/payment/recovery.d.ts +2 -0
  42. package/dist/payment/recovery.d.ts.map +1 -1
  43. package/dist/payment/withdrawal-waiver.d.ts +26 -0
  44. package/dist/payment/withdrawal-waiver.d.ts.map +1 -0
  45. package/dist/paywall/billing-profile-picker.d.ts +1 -1
  46. package/dist/paywall/billing-profile-picker.d.ts.map +1 -1
  47. package/dist/paywall/i18n.d.ts +94 -0
  48. package/dist/paywall/i18n.d.ts.map +1 -0
  49. package/dist/paywall/index.d.ts +2 -1
  50. package/dist/paywall/index.d.ts.map +1 -1
  51. package/dist/paywall/license-panel.d.ts +4 -1
  52. package/dist/paywall/license-panel.d.ts.map +1 -1
  53. package/dist/paywall/renderer.d.ts +16 -2
  54. package/dist/paywall/renderer.d.ts.map +1 -1
  55. package/dist/paywall/seller-details.d.ts +2 -1
  56. package/dist/paywall/seller-details.d.ts.map +1 -1
  57. package/dist/paywall/strings.d.ts +6 -4
  58. package/dist/paywall/strings.d.ts.map +1 -1
  59. package/dist/paywall.d.mts +93 -7
  60. package/dist/paywall.d.ts +93 -7
  61. package/dist/paywall.js +992 -41
  62. package/dist/paywall.js.map +1 -1
  63. package/dist/paywall.mjs +990 -42
  64. package/dist/paywall.mjs.map +1 -1
  65. package/dist/types/config.d.ts +6 -1
  66. package/dist/types/config.d.ts.map +1 -1
  67. package/dist/types/contract.d.ts +25 -0
  68. package/dist/types/contract.d.ts.map +1 -1
  69. package/dist/types/entitlement.d.ts +22 -0
  70. package/dist/types/entitlement.d.ts.map +1 -1
  71. package/dist/types/errors.d.ts +1 -0
  72. package/dist/types/errors.d.ts.map +1 -1
  73. package/dist/types/paywall.d.ts +15 -2
  74. package/dist/types/paywall.d.ts.map +1 -1
  75. package/dist/version.d.ts +1 -1
  76. package/package.json +2 -2
  77. package/dist/core.esm.js +0 -1681
  78. package/dist/core.esm.js.map +0 -1
  79. package/dist/extenshi-pay-lite.esm.js +0 -1664
  80. package/dist/extenshi-pay-lite.esm.js.map +0 -1
  81. package/dist/extenshi-pay.esm.js +0 -2496
  82. package/dist/extenshi-pay.esm.js.map +0 -1
  83. package/dist/extenshi-pay.esm.min.js +0 -7
  84. package/dist/extenshi-pay.esm.min.js.map +0 -1
  85. package/dist/paywall.esm.js +0 -442
  86. package/dist/paywall.esm.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"extenshi-pay.min.mjs","sources":["../src/types/contract.ts","../src/types/errors.ts","../src/core/identity.ts","../src/api/mock.ts","../src/api/pay-api.ts","../src/utils/logger.ts","../src/api/transport.ts","../src/payment/checkout.ts","../src/payment/features.ts","../src/payment/signature.ts","../src/payment/entitlement.ts","../src/core/storage.ts","../src/payment/recovery.ts","../src/types/config.ts","../src/version.ts","../src/core/config.ts","../src/core/event-emitter.ts","../src/core/extenshi-pay.ts","../src/paywall/billing-profile-picker.ts","../src/paywall/seller-details.ts","../src/paywall/strings.ts","../src/paywall/license-panel.ts","../src/paywall/format.ts","../../extension_templates/paywall-templates/fullscreen/template.html","../src/paywall/templates.ts","../../extension_templates/paywall-templates/modal/template.html","../../extension_templates/paywall-templates/inline/template.html","../../extension_templates/paywall-templates/sidebar/template.html","../../extension_templates/paywall-templates/minimal/template.html","../src/paywall/renderer.ts","../src/extenshi-pay.ts"],"sourcesContent":["/**\n * Wire contract between the SDK and catalog-bff `pay.*`.\n *\n * SOURCE OF TRUTH: `shared-types/pay.ts` in the extenshi.io monorepo. The SDK\n * ships with zero runtime dependencies and must not import that workspace, so\n * the types and constants it needs are copied here under identical names.\n * `canonicalJson` is copied VERBATIM: the BFF signs its output and the SDK\n * verifies it, so both sides must produce byte-identical strings\n * (pinned by tests/unit/canonical-json.test.ts). When `shared-types/pay.ts`\n * changes, mirror the change here.\n */\n\n/** Bumped only when an older SDK could misread the response. */\nexport const PAY_CONTRACT_VERSION = 1\n\nexport const PAY_GATEWAYS = ['stripe', 'paddle', 'lemonsqueezy'] as const\nexport type PayGatewayId = (typeof PAY_GATEWAYS)[number]\n\n// ─── Publishable key ────────────────────────────────────────────────────────\n\n/**\n * The only credential an extension bundle carries. It is public by\n * construction (anyone can unzip the .crx), so it must grant nothing beyond\n * \"read this project's offer\" and \"start a checkout for this project\".\n */\nexport const PAY_PUBLISHABLE_KEY_PREFIX = 'pk_ext_'\nexport const PAY_PUBLISHABLE_KEY_HEX_LENGTH = 32\nconst PUBLISHABLE_KEY_RE = new RegExp(\n\t`^${PAY_PUBLISHABLE_KEY_PREFIX}[0-9a-f]{${PAY_PUBLISHABLE_KEY_HEX_LENGTH}}$`,\n)\n\nexport function isPayPublishableKey(value: unknown): value is string {\n\treturn typeof value === 'string' && PUBLISHABLE_KEY_RE.test(value)\n}\n\n// ─── Offers ─────────────────────────────────────────────────────────────────\n\nexport const PAY_OFFER_KINDS = ['one_time', 'subscription', 'lifetime'] as const\nexport type PayOfferKind = (typeof PAY_OFFER_KINDS)[number]\n\nexport const PAY_OFFER_INTERVALS = ['month', 'year'] as const\nexport type PayOfferInterval = (typeof PAY_OFFER_INTERVALS)[number]\n\n/** ISO-4217 lowercase, matching what every gateway returns. */\nexport const PAY_CURRENCIES = ['usd', 'eur', 'gbp'] as const\nexport type PayCurrency = (typeof PAY_CURRENCIES)[number]\n\n/** `sku` is author-chosen and stable; it is what `requireFeature()` keys on. */\nexport const PAY_SKU_RE = /^[a-z0-9][a-z0-9_-]{1,39}$/\n\n// ─── Projection ─────────────────────────────────────────────────────────────\n\n/**\n * active — paid and not expired\n * grace — subscription past_due: keep access for a short window so a card\n * hiccup does not lock a paying user out mid-session\n * expired — was active, no longer is\n * none — never had it\n */\nexport const PAY_ENTITLEMENT_STATUSES = ['active', 'grace', 'expired', 'none'] as const\nexport type PayEntitlementStatus = (typeof PAY_ENTITLEMENT_STATUSES)[number]\n\n// ─── SDK-facing DTOs (the `pay.*` tRPC contract) ────────────────────────────\n\nexport interface PayOfferDto {\n\tsku: string\n\tkind: PayOfferKind\n\tinterval: PayOfferInterval | null\n\tamountMinor: number\n\tcurrency: PayCurrency\n\ttitle: string\n\tdescription: string | null\n\tfeatures: string[]\n}\n\nexport interface PayOfferResponse {\n\t/** Optional during rolling upgrades; never infer this from the project name. */\n\tseller?: PaySellerPublic | null\n\n\tv: typeof PAY_CONTRACT_VERSION\n\tprojectName: string\n\tprovider: PayGatewayId\n\t/** False while the seller cannot take money; the SDK renders the offer read-only. */\n\tcheckoutEnabled: boolean\n\t/** Optional for older servers; show recovery only when explicitly enabled. */\n\trecoveryEnabled?: boolean\n\toffers: PayOfferDto[]\n\t/** Base64 Ed25519 public key for `SignedEntitlement.signature`; null when unsigned. */\n\tentitlementPublicKey: string | null\n}\n\nexport interface PayEntitlementItem {\n\t/** Optional for old signed caches and older servers. */\n\ttitle?: string\n\tkind?: PayOfferKind\n\tsubscriptions?: Array<{\n\t\tstatus: string\n\t\tcancelAtPeriodEnd: boolean\n\t\tcurrentPeriodEnd: string | null\n\t}>\n\n\tsku: string\n\tstatus: PayEntitlementStatus\n\t/** ISO timestamp; null for lifetime / one-time grants. */\n\texpiresAt: string | null\n\tfeatures: string[]\n}\n\nexport interface PayEntitlementPayload {\n\tv: typeof PAY_CONTRACT_VERSION\n\t/** Signed application scope; prevents moving a grant to another application. */\n\tpublishableKey: string\n\tendUserRef: string\n\tentitlements: PayEntitlementItem[]\n\t/** ISO timestamp the projection was computed at; the SDK uses it for cache age. */\n\tissuedAt: string\n}\n\nexport interface SignedEntitlement {\n\tpayload: PayEntitlementPayload\n\t/** Base64 Ed25519 signature over the canonical JSON of `payload`; null when the server has no key. */\n\tsignature: string | null\n\talg: 'ed25519' | null\n}\n\nexport type PayCheckoutClaim =\n\t| { state: 'pending' }\n\t| { state: 'complete'; entitlement: SignedEntitlement }\n\t| { state: 'expired' }\n\t| { state: 'canceled' }\n\nexport interface PayCheckoutSession {\n\turl: string\n\tsessionId: string\n\t/** ISO timestamp. */\n\texpiresAt: string\n}\n\n/**\n * The `endUserRef` an SDK mints on first run and keeps in `chrome.storage`.\n * Opaque, random, never derived from anything identifying.\n */\nexport const PAY_END_USER_REF_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n/** Typed error codes the BFF throws; dojo and the SDK match on `cause.code`. */\nexport const PAY_ERRORS = {\n\tSELLER_NOT_CONNECTED: 'PAY_SELLER_NOT_CONNECTED',\n\tSELLER_NOT_ACTIVE: 'PAY_SELLER_NOT_ACTIVE',\n\tAGREEMENT_REQUIRED: 'PAY_AGREEMENT_REQUIRED',\n\tOFFER_NOT_FOUND: 'PAY_OFFER_NOT_FOUND',\n\tOFFER_LIMIT: 'PAY_OFFER_LIMIT',\n\tPRICE_TOO_LOW: 'PAY_PRICE_TOO_LOW',\n\tGATEWAY_UNAVAILABLE: 'PAY_GATEWAY_UNAVAILABLE',\n\tRATE_LIMITED: 'PAY_RATE_LIMITED',\n\tINVALID_KEY: 'PAY_INVALID_KEY',\n} as const\nexport type PayErrorCode = (typeof PAY_ERRORS)[keyof typeof PAY_ERRORS]\n\n/**\n * Canonical JSON for signing: keys sorted recursively, no whitespace. Both\n * the BFF (sign) and the SDK (verify) must produce byte-identical output for\n * the same payload, so the rule lives in the shared contract.\n */\nexport function canonicalJson(value: unknown): string {\n\tif (value === null || typeof value !== 'object') return JSON.stringify(value)\n\tif (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(',')}]`\n\tconst entries = Object.entries(value as Record<string, unknown>)\n\t\t.filter(([, v]) => v !== undefined)\n\t\t.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n\treturn `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`\n}\n\nexport interface PayRestoreSessionResponse {\n\tsessionId: string\n\texpiresAt: string\n\turl: string\n}\nexport type PayRestoreClaimResponse =\n\t| { state: 'pending' }\n\t| { state: 'complete'; endUserRef: string; entitlement: SignedEntitlement }\n\n/** A project-scoped billing profile; provider identifiers are never exposed. */\nexport interface PayPortalAccount {\n\tid: string\n\tlabel: string\n\tcreatedAt: string\n\tsubscriptions: Array<{\n\t\ttitle: string\n\t\tstatus: string\n\t\tcancelAtPeriodEnd: boolean\n\t\tcurrentPeriodEnd: string | null\n\t}>\n}\n\nexport interface PayPortalResponse {\n\turl: string | null\n\t/** Present when the buyer must choose among multiple billing profiles. */\n\taccounts?: PayPortalAccount[]\n}\n\n/** Public author-provided contact details. Not a claim of identity verification. */\nexport interface PaySellerPublic {\n\tdisplayName: string\n\t/** HTTPS support page or plain email address. */\n\tsupportUrl: string\n\ttermsUrl: string | null\n}\n","export const ERROR_CODES = {\n\tINVALID_CONFIG: 'INVALID_CONFIG',\n\tINVALID_REQUEST: 'INVALID_REQUEST',\n\tNETWORK_ERROR: 'NETWORK_ERROR',\n\tTIMEOUT: 'TIMEOUT',\n\tVERIFICATION_UNAVAILABLE: 'VERIFICATION_UNAVAILABLE',\n\tINVALID_RESPONSE: 'INVALID_RESPONSE',\n\tRATE_LIMITED: 'RATE_LIMITED',\n\tINVALID_KEY: 'INVALID_KEY',\n\tSELLER_NOT_ACTIVE: 'SELLER_NOT_ACTIVE',\n\tOFFER_NOT_FOUND: 'OFFER_NOT_FOUND',\n\tGATEWAY_UNAVAILABLE: 'GATEWAY_UNAVAILABLE',\n\tCHECKOUT_UNAVAILABLE: 'CHECKOUT_UNAVAILABLE',\n\tPAYWALL_UNAVAILABLE: 'PAYWALL_UNAVAILABLE',\n\tUNKNOWN: 'UNKNOWN',\n} as const\n\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES]\n\nexport interface ExtenshiPayErrorOptions {\n\tretryAfterSec?: number\n\thttpStatus?: number\n\tcause?: unknown\n}\n\nexport class ExtenshiPayError extends Error {\n\treadonly code: ErrorCode\n\treadonly retryAfterSec: number | undefined\n\treadonly httpStatus: number | undefined\n\treadonly cause: unknown\n\n\tconstructor(code: ErrorCode, message: string, options: ExtenshiPayErrorOptions = {}) {\n\t\tsuper(message)\n\t\tthis.name = 'ExtenshiPayError'\n\t\tthis.code = code\n\t\tthis.retryAfterSec = options.retryAfterSec\n\t\tthis.httpStatus = options.httpStatus\n\t\tthis.cause = options.cause\n\t}\n\n\tstatic from(error: unknown, fallback: ErrorCode = ERROR_CODES.UNKNOWN): ExtenshiPayError {\n\t\tif (error instanceof ExtenshiPayError) return error\n\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\treturn new ExtenshiPayError(fallback, message, { cause: error })\n\t}\n}\n","/**\n * `endUserRef` — the only identity the SDK has.\n *\n * A random UUID minted on first run and kept in the SDK's storage namespace.\n * It is never derived from anything identifying (no fingerprint, no e-mail,\n * no extension-supplied user id) and remains the installation identifier. Explicit recovery also sends a\n * random session ID and proof; it never derives identity from an email locally.\n */\n\nimport { PAY_END_USER_REF_RE } from '../types/contract.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { StorageAdapter } from './storage.js'\n\nexport const END_USER_REF_STORAGE_KEY = 'extenshi-pay:endUserRef'\n\nexport function mintEndUserRef(): string {\n\tconst cryptoApi = (globalThis as { crypto?: Crypto }).crypto\n\tif (!cryptoApi) {\n\t\tthrow new ExtenshiPayError(ERROR_CODES.UNKNOWN, 'Web Crypto is not available in this context')\n\t}\n\tif (typeof cryptoApi.randomUUID === 'function') return cryptoApi.randomUUID()\n\tconst bytes = cryptoApi.getRandomValues(new Uint8Array(16))\n\tbytes[6] = (bytes[6] & 0x0f) | 0x40\n\tbytes[8] = (bytes[8] & 0x3f) | 0x80\n\tconst hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')\n\treturn `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`\n}\n\nexport async function getOrCreateEndUserRef(storage: StorageAdapter): Promise<string> {\n\tconst existing = await storage.get(END_USER_REF_STORAGE_KEY)\n\tif (typeof existing === 'string' && PAY_END_USER_REF_RE.test(existing)) return existing\n\tconst ref = mintEndUserRef()\n\tawait storage.set(END_USER_REF_STORAGE_KEY, ref)\n\treturn ref\n}\n","/**\n * In-memory stand-in for the BFF, used when `mock: true`. Lets an extension be\n * developed with no backend: offers and entitlements come from `mockData`, a\n * mock checkout completes after `claimAfterPolls` polls and grants the SKU.\n */\n\nimport { mintEndUserRef } from '../core/identity.js'\nimport type { MockData } from '../types/config.js'\nimport {\n\tPAY_CONTRACT_VERSION,\n\ttype PayCheckoutClaim,\n\ttype PayEntitlementItem,\n\ttype PayOfferDto,\n\ttype PayOfferResponse,\n\ttype SignedEntitlement,\n} from '../types/contract.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { ProcedureKind, Transport } from './transport.js'\n\ntype SessionState = 'open' | 'complete' | 'canceled' | 'expired'\n\ninterface MockSession {\n\tsku: string\n\tpolls: number\n\tstate: SessionState\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000\n\nexport class MockTransport implements Transport {\n\tprivate entitlements: PayEntitlementItem[]\n\tprivate readonly offers: PayOfferDto[]\n\tprivate readonly projectName: string\n\tprivate readonly checkoutEnabled: boolean\n\tprivate readonly claimAfterPolls: number\n\treadonly sessions = new Map<string, MockSession>()\n\n\tconstructor(data: MockData = {}) {\n\t\tthis.entitlements = [...(data.entitlements ?? [])]\n\t\tthis.offers = [...(data.offers ?? [])]\n\t\tthis.projectName = data.projectName ?? 'Mock project'\n\t\tthis.checkoutEnabled = data.checkoutEnabled ?? true\n\t\tthis.claimAfterPolls = data.claimAfterPolls ?? 1\n\t}\n\n\tasync call<T>(procedure: string, _kind: ProcedureKind, input: Record<string, unknown>): Promise<T> {\n\t\tswitch (procedure) {\n\t\t\tcase 'pay.getOffer':\n\t\t\t\treturn this.offerResponse() as T\n\t\t\tcase 'pay.createCheckout':\n\t\t\t\treturn this.createCheckout(String(input.sku)) as T\n\t\t\tcase 'pay.claimSession':\n\t\t\t\treturn this.claim(\n\t\t\t\t\tString(input.sessionId),\n\t\t\t\t\tString(input.endUserRef),\n\t\t\t\t\tString(input.publishableKey),\n\t\t\t\t) as T\n\t\t\tcase 'pay.getEntitlement':\n\t\t\t\treturn this.envelope(String(input.endUserRef), String(input.publishableKey)) as T\n\t\t\tcase 'pay.getPortalUrl':\n\t\t\t\treturn { url: this.entitlements.length > 0 ? 'https://mock.extenshi.io/portal' : null } as T\n\t\t\tdefault:\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, `Unknown procedure ${procedure}`)\n\t\t}\n\t}\n\n\t/** Test/dev helpers. */\n\tsetEntitlements(items: PayEntitlementItem[]): void {\n\t\tthis.entitlements = [...items]\n\t}\n\n\tcancelSession(sessionId: string): void {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (session) session.state = 'canceled'\n\t}\n\n\texpireSession(sessionId: string): void {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (session) session.state = 'expired'\n\t}\n\n\tprivate offerResponse(): PayOfferResponse {\n\t\treturn {\n\t\t\tv: PAY_CONTRACT_VERSION,\n\t\t\tprojectName: this.projectName,\n\t\t\tprovider: 'stripe',\n\t\t\tcheckoutEnabled: this.checkoutEnabled && this.offers.length > 0,\n\t\t\toffers: [...this.offers],\n\t\t\tentitlementPublicKey: null,\n\t\t}\n\t}\n\n\tprivate createCheckout(sku: string) {\n\t\tif (!this.checkoutEnabled) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.SELLER_NOT_ACTIVE, 'Mock seller cannot take payments')\n\t\t}\n\t\tif (!this.offers.some((offer) => offer.sku === sku)) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.OFFER_NOT_FOUND, `Unknown mock offer ${sku}`)\n\t\t}\n\t\tconst sessionId = mintEndUserRef()\n\t\tthis.sessions.set(sessionId, { sku, polls: 0, state: 'open' })\n\t\treturn {\n\t\t\turl: `https://mock.extenshi.io/checkout/${sessionId}`,\n\t\t\tsessionId,\n\t\t\texpiresAt: new Date(Date.now() + 30 * 60 * 1000).toISOString(),\n\t\t}\n\t}\n\n\tprivate claim(sessionId: string, endUserRef: string, publishableKey: string): PayCheckoutClaim {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) throw new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, 'Unknown checkout session')\n\t\tif (session.state === 'canceled') return { state: 'canceled' }\n\t\tif (session.state === 'expired') return { state: 'expired' }\n\t\tif (session.state === 'open') {\n\t\t\tsession.polls += 1\n\t\t\tif (session.polls <= this.claimAfterPolls) return { state: 'pending' }\n\t\t\tsession.state = 'complete'\n\t\t\tthis.grant(session.sku)\n\t\t}\n\t\treturn { state: 'complete', entitlement: this.envelope(endUserRef, publishableKey) }\n\t}\n\n\tprivate grant(sku: string): void {\n\t\tconst offer = this.offers.find((o) => o.sku === sku)\n\t\tconst expiresAt =\n\t\t\toffer?.kind === 'subscription'\n\t\t\t\t? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS).toISOString()\n\t\t\t\t: null\n\t\tthis.entitlements = [\n\t\t\t...this.entitlements.filter((item) => item.sku !== sku),\n\t\t\t{\n\t\t\t\tsku,\n\t\t\t\ttitle: offer?.title,\n\t\t\t\tkind: offer?.kind,\n\t\t\t\tstatus: 'active',\n\t\t\t\texpiresAt,\n\t\t\t\tfeatures: offer?.features ?? [],\n\t\t\t},\n\t\t]\n\t}\n\n\tprivate envelope(endUserRef: string, publishableKey: string): SignedEntitlement {\n\t\treturn {\n\t\t\tpayload: {\n\t\t\t\tv: PAY_CONTRACT_VERSION,\n\t\t\t\tpublishableKey,\n\t\t\t\tendUserRef,\n\t\t\t\tentitlements: [...this.entitlements],\n\t\t\t\tissuedAt: new Date().toISOString(),\n\t\t\t},\n\t\t\tsignature: null,\n\t\t\talg: null,\n\t\t}\n\t}\n}\n","/** Typed wrapper over the SDK-facing `pay.*` procedures. Nothing else is ever called. */\n\nimport type {\n\tPayCheckoutClaim,\n\tPayCheckoutSession,\n\tPayOfferResponse,\n\tPayPortalResponse,\n\tPayRestoreClaimResponse,\n\tPayRestoreSessionResponse,\n\tSignedEntitlement,\n} from '../types/contract.js'\nimport type { Transport } from './transport.js'\n\nexport class PayApi {\n\tconstructor(\n\t\tprivate readonly transport: Transport,\n\t\tprivate readonly publishableKey: string,\n\t) {}\n\n\tcreateRestoreSession(claimChallenge: string): Promise<PayRestoreSessionResponse> {\n\t\treturn this.transport.call('pay.createRestoreSession', 'mutation', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tclaimChallenge,\n\t\t})\n\t}\n\n\tclaimRestoreSession(sessionId: string, claimSecret: string): Promise<PayRestoreClaimResponse> {\n\t\treturn this.transport.call('pay.claimRestoreSession', 'mutation', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tsessionId,\n\t\t\tclaimSecret,\n\t\t})\n\t}\n\n\tgetOffer(locale?: string | null): Promise<PayOfferResponse> {\n\t\treturn this.transport.call('pay.getOffer', 'query', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tlocale: locale ?? undefined,\n\t\t})\n\t}\n\n\tcreateCheckout(sku: string, endUserRef: string, locale?: string | null): Promise<PayCheckoutSession> {\n\t\treturn this.transport.call('pay.createCheckout', 'mutation', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tsku,\n\t\t\tendUserRef,\n\t\t\tlocale: locale ?? undefined,\n\t\t})\n\t}\n\n\tclaimSession(sessionId: string, endUserRef: string): Promise<PayCheckoutClaim> {\n\t\treturn this.transport.call('pay.claimSession', 'query', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tsessionId,\n\t\t\tendUserRef,\n\t\t})\n\t}\n\n\tgetEntitlement(endUserRef: string): Promise<SignedEntitlement> {\n\t\treturn this.transport.call('pay.getEntitlement', 'query', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tendUserRef,\n\t\t})\n\t}\n\n\tgetPortalUrl(endUserRef: string, customerId?: string): Promise<PayPortalResponse> {\n\t\treturn this.transport.call('pay.getPortalUrl', 'mutation', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tendUserRef,\n\t\t\t...(customerId ? { customerId } : {}),\n\t\t})\n\t}\n}\n","import type { LogLevel } from '../types/config.js'\n\nconst ORDER: Record<LogLevel, number> = { silent: 0, error: 1, warn: 2, info: 3, debug: 4 }\n\nexport class Logger {\n\tprivate level: LogLevel = 'warn'\n\tprivate readonly prefix = '[ExtenshiPay]'\n\n\tconfigure(options: { logLevel?: LogLevel; debug?: boolean }): void {\n\t\tif (options.logLevel) this.level = options.logLevel\n\t\tif (options.debug) this.level = 'debug'\n\t}\n\n\terror(message: string, ...args: unknown[]): void {\n\t\tif (this.enabled('error')) console.error(this.prefix, message, ...args)\n\t}\n\n\twarn(message: string, ...args: unknown[]): void {\n\t\tif (this.enabled('warn')) console.warn(this.prefix, message, ...args)\n\t}\n\n\tinfo(message: string, ...args: unknown[]): void {\n\t\tif (this.enabled('info')) console.info(this.prefix, message, ...args)\n\t}\n\n\tdebug(message: string, ...args: unknown[]): void {\n\t\tif (this.enabled('debug')) console.debug(this.prefix, message, ...args)\n\t}\n\n\tprivate enabled(level: LogLevel): boolean {\n\t\treturn ORDER[level] <= ORDER[this.level]\n\t}\n}\n\nexport const logger = new Logger()\n","/**\n * HTTP transport for the BFF's tRPC endpoint (`/api/trpc/<procedure>`).\n *\n * Queries are header-less GETs with `?input=<json>` (a CORS \"simple request\",\n * so no preflight); mutations POST a JSON body. The only things that leave the\n * extension are payment inputs and optional recovery session/proof inputs\n * and the browser's standard headers — `credentials: 'omit'` keeps cookies out.\n * Queries are retried on network / 5xx errors; mutations never are.\n */\n\nimport { PAY_ERRORS } from '../types/contract.js'\nimport { ERROR_CODES, type ErrorCode, ExtenshiPayError } from '../types/errors.js'\nimport { logger } from '../utils/logger.js'\n\nexport type ProcedureKind = 'query' | 'mutation'\n\nexport interface Transport {\n\tcall<T>(procedure: string, kind: ProcedureKind, input: Record<string, unknown>): Promise<T>\n}\n\nexport interface HttpTransportOptions {\n\tapiUrl: string\n\t/** Per-attempt timeout (default 10 s). */\n\ttimeoutMs?: number\n\t/** Extra attempts for queries (default 1). */\n\tretries?: number\n\tfetchImpl?: typeof fetch\n}\n\nexport const TRPC_PATH = '/api/trpc'\nconst DEFAULT_TIMEOUT_MS = 10_000\nconst DEFAULT_RETRIES = 1\nconst RETRY_BASE_MS = 500\n\ninterface TrpcErrorShape {\n\tmessage?: string\n\tcode?: number\n\tdata?: {\n\t\tcode?: string\n\t\thttpStatus?: number\n\t\tcause?: { code?: string; retryAfterSec?: number }\n\t}\n}\n\ninterface TrpcEnvelope<T> {\n\tresult?: { data?: T }\n\terror?: TrpcErrorShape\n}\n\nconst RETRYABLE: ReadonlySet<ErrorCode> = new Set([\n\tERROR_CODES.NETWORK_ERROR,\n\tERROR_CODES.TIMEOUT,\n\tERROR_CODES.GATEWAY_UNAVAILABLE,\n])\n\n/** `PAY_*` cause codes, when the BFF forwards them, map 1:1. */\nconst CAUSE_TO_CODE: Record<string, ErrorCode> = {\n\t[PAY_ERRORS.RATE_LIMITED]: ERROR_CODES.RATE_LIMITED,\n\t[PAY_ERRORS.INVALID_KEY]: ERROR_CODES.INVALID_KEY,\n\t[PAY_ERRORS.SELLER_NOT_CONNECTED]: ERROR_CODES.SELLER_NOT_ACTIVE,\n\t[PAY_ERRORS.SELLER_NOT_ACTIVE]: ERROR_CODES.SELLER_NOT_ACTIVE,\n\t[PAY_ERRORS.AGREEMENT_REQUIRED]: ERROR_CODES.SELLER_NOT_ACTIVE,\n\t[PAY_ERRORS.OFFER_NOT_FOUND]: ERROR_CODES.OFFER_NOT_FOUND,\n\t[PAY_ERRORS.GATEWAY_UNAVAILABLE]: ERROR_CODES.GATEWAY_UNAVAILABLE,\n}\n\nfunction parseRetryAfter(message: string): number | undefined {\n\tconst match = /retry in (\\d+)s/i.exec(message)\n\treturn match ? Number(match[1]) : undefined\n}\n\n/**\n * The BFF's error formatter does not forward `cause` for `pay.*` errors, so the\n * tRPC code + message is the primary signal; `data.cause.code` is honoured when\n * present so a future BFF that forwards it needs no SDK change.\n */\nexport function trpcErrorToPayError(error: TrpcErrorShape, httpStatus?: number): ExtenshiPayError {\n\tconst message = error.message ?? 'Request failed'\n\tconst trpcCode = error.data?.code ?? ''\n\tconst causeCode = error.data?.cause?.code\n\tconst retryAfterSec = error.data?.cause?.retryAfterSec ?? parseRetryAfter(message)\n\tconst options = { retryAfterSec, httpStatus: error.data?.httpStatus ?? httpStatus }\n\n\tconst mapped = causeCode ? CAUSE_TO_CODE[causeCode] : undefined\n\tif (mapped) return new ExtenshiPayError(mapped, message, options)\n\n\tswitch (trpcCode) {\n\t\tcase 'TOO_MANY_REQUESTS':\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, message, options)\n\t\tcase 'NOT_FOUND':\n\t\t\tif (/publishable key/i.test(message))\n\t\t\t\treturn new ExtenshiPayError(ERROR_CODES.INVALID_KEY, message, options)\n\t\t\tif (/session/i.test(message))\n\t\t\t\treturn new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, message, options)\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.OFFER_NOT_FOUND, message, options)\n\t\tcase 'PRECONDITION_FAILED':\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.SELLER_NOT_ACTIVE, message, options)\n\t\tcase 'BAD_REQUEST':\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, message, options)\n\t\tcase 'INTERNAL_SERVER_ERROR':\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, message, options)\n\t\tdefault:\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.UNKNOWN, message, options)\n\t}\n}\n\nfunction sleep(ms: number): Promise<void> {\n\treturn new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nexport class HttpTransport implements Transport {\n\tprivate readonly apiUrl: string\n\tprivate readonly timeoutMs: number\n\tprivate readonly retries: number\n\tprivate readonly fetchImpl: typeof fetch\n\n\tconstructor(options: HttpTransportOptions) {\n\t\tthis.apiUrl = options.apiUrl.replace(/\\/+$/, '')\n\t\tthis.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n\t\tthis.retries = options.retries ?? DEFAULT_RETRIES\n\t\tthis.fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init))\n\t}\n\n\tasync call<T>(procedure: string, kind: ProcedureKind, input: Record<string, unknown>): Promise<T> {\n\t\tconst base = `${this.apiUrl}${TRPC_PATH}/${procedure}`\n\t\tconst url = kind === 'query' ? `${base}?input=${encodeURIComponent(JSON.stringify(input))}` : base\n\t\tconst attempts = kind === 'query' ? this.retries + 1 : 1\n\t\tlet lastError: ExtenshiPayError | null = null\n\t\tfor (let attempt = 0; attempt < attempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn await this.request<T>(url, kind, input)\n\t\t\t} catch (error) {\n\t\t\t\tconst err = ExtenshiPayError.from(error)\n\t\t\t\tif (!RETRYABLE.has(err.code) || attempt === attempts - 1) throw err\n\t\t\t\tlastError = err\n\t\t\t\tlogger.debug(`${procedure} failed (${err.code}), retrying`)\n\t\t\t\tawait sleep(RETRY_BASE_MS * 2 ** attempt)\n\t\t\t}\n\t\t}\n\t\tthrow lastError ?? new ExtenshiPayError(ERROR_CODES.UNKNOWN, `${procedure} failed`)\n\t}\n\n\tprivate async request<T>(url: string, kind: ProcedureKind, input: Record<string, unknown>): Promise<T> {\n\t\tconst controller = typeof AbortController === 'function' ? new AbortController() : null\n\t\tconst timer = controller ? setTimeout(() => controller.abort(), this.timeoutMs) : null\n\t\tlet response: Response\n\t\ttry {\n\t\t\tresponse = await this.fetchImpl(url, {\n\t\t\t\tmethod: kind === 'query' ? 'GET' : 'POST',\n\t\t\t\theaders: kind === 'mutation' ? { 'Content-Type': 'application/json' } : undefined,\n\t\t\t\tbody: kind === 'mutation' ? JSON.stringify(input) : undefined,\n\t\t\t\tsignal: controller?.signal,\n\t\t\t\tcredentials: 'omit',\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tif (controller?.signal.aborted) {\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${this.timeoutMs}ms`)\n\t\t\t}\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error })\n\t\t} finally {\n\t\t\tif (timer !== null) clearTimeout(timer)\n\t\t}\n\n\t\tlet body: TrpcEnvelope<T> | null = null\n\t\ttry {\n\t\t\tbody = (await response.json()) as TrpcEnvelope<T>\n\t\t} catch {\n\t\t\tbody = null\n\t\t}\n\t\tif (body?.error) throw trpcErrorToPayError(body.error, response.status)\n\t\tif (!response.ok) {\n\t\t\tconst code = response.status >= 500 ? ERROR_CODES.GATEWAY_UNAVAILABLE : ERROR_CODES.INVALID_RESPONSE\n\t\t\tthrow new ExtenshiPayError(code, `HTTP ${response.status}`, { httpStatus: response.status })\n\t\t}\n\t\tif (!body?.result || !('data' in body.result)) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Malformed response from the payment backend')\n\t\t}\n\t\treturn body.result.data as T\n\t}\n}\n","/**\n * Hosted checkout flow.\n *\n * `pay.createCheckout` returns a URL on the seller's provider; the SDK opens\n * it in a new tab (`chrome.tabs.create`, falling back to `window.open`) and\n * polls `pay.claimSession` every 2 s for up to 10 min — and immediately when\n * the extension regains focus — until the webhook has landed. A pending\n * session is persisted so a restarted service worker / reopened popup can\n * finish the claim on the next `initialize()`.\n */\n\nimport type { PayApi } from '../api/pay-api.js'\nimport type { StorageAdapter } from '../core/storage.js'\nimport type { PayCheckoutClaim, SignedEntitlement } from '../types/contract.js'\nimport type { CheckoutOptions, CheckoutResult, Entitlement } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { ExtenshiPayEvents } from '../types/events.js'\nimport { logger } from '../utils/logger.js'\n\nexport const CHECKOUT_POLL_INTERVAL_MS = 2_000\nexport const CHECKOUT_TIMEOUT_MS = 10 * 60 * 1000\nconst MAX_ERROR_BACKOFF_MS = 30_000\n/** How long after `expiresAt` a persisted session is still worth one claim (webhook lag). */\nconst PENDING_GRACE_MS = 60 * 60 * 1000\n\ninterface PendingCheckout {\n\tsessionId: string\n\tsku: string\n\texpiresAt: string\n}\n\ntype OpenUrl = (url: string) => void | Promise<void>\ntype Emit = <K extends keyof ExtenshiPayEvents>(event: K, payload: ExtenshiPayEvents[K]) => void\n\nexport interface CheckoutManagerOptions {\n\tapi: PayApi\n\tstorage: StorageAdapter\n\tpublishableKey: string\n\tlocale: string | null\n\tgetEndUserRef: () => Promise<string>\n\t/** Verifies + stores the envelope from a completed session. */\n\tonComplete: (envelope: SignedEntitlement) => Promise<Entitlement>\n\temit: Emit\n\topenUrl?: OpenUrl\n\tnow?: () => number\n}\n\ninterface TabsApi {\n\tcreate(properties: { url: string }): unknown\n}\n\ninterface FocusGlobals {\n\tchrome?: { tabs?: TabsApi; windows?: { onFocusChanged?: FocusEvent } }\n\tbrowser?: { tabs?: TabsApi }\n\topen?: (url: string, target: string, features: string) => unknown\n\taddEventListener?: (type: string, listener: () => void) => void\n\tremoveEventListener?: (type: string, listener: () => void) => void\n\tdocument?: Document\n}\n\ninterface FocusEvent {\n\taddListener(listener: (windowId: number) => void): void\n\tremoveListener(listener: (windowId: number) => void): void\n}\n\nexport async function openInNewTab(url: string): Promise<void> {\n\tconst g = globalThis as FocusGlobals\n\tconst tabs = g.chrome?.tabs ?? g.browser?.tabs\n\tif (tabs && typeof tabs.create === 'function') {\n\t\tconst result = tabs.create({ url })\n\t\tif (result && typeof (result as Promise<unknown>).then === 'function') await result\n\t\treturn\n\t}\n\tif (typeof g.open === 'function') {\n\t\tg.open(url, '_blank', 'noopener,noreferrer')\n\t\treturn\n\t}\n\tthrow new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, 'Cannot open a checkout tab from this context')\n}\n\n/** Calls `onFocus` whenever the extension window/tab regains focus; returns a disposer. */\nfunction onFocusRegained(onFocus: () => void): () => void {\n\tconst g = globalThis as FocusGlobals\n\tconst disposers: Array<() => void> = []\n\tif (typeof g.addEventListener === 'function' && typeof g.removeEventListener === 'function') {\n\t\tg.addEventListener('focus', onFocus)\n\t\tdisposers.push(() => g.removeEventListener?.('focus', onFocus))\n\t}\n\tconst doc = g.document\n\tif (doc && typeof doc.addEventListener === 'function') {\n\t\tconst onVisible = () => {\n\t\t\tif (doc.visibilityState === 'visible') onFocus()\n\t\t}\n\t\tdoc.addEventListener('visibilitychange', onVisible)\n\t\tdisposers.push(() => doc.removeEventListener('visibilitychange', onVisible))\n\t}\n\tconst windows = g.chrome?.windows?.onFocusChanged\n\tif (windows && typeof windows.addListener === 'function') {\n\t\tconst onWindow = (windowId: number) => {\n\t\t\tif (windowId !== -1) onFocus()\n\t\t}\n\t\twindows.addListener(onWindow)\n\t\tdisposers.push(() => windows.removeListener(onWindow))\n\t}\n\treturn () => {\n\t\tfor (const dispose of disposers) dispose()\n\t}\n}\n\n/** A sleep that can be cut short by `wake()`. */\nfunction interruptibleSleep() {\n\tlet wake: (() => void) | null = null\n\treturn {\n\t\tsleep(ms: number): Promise<void> {\n\t\t\treturn new Promise<void>((resolve) => {\n\t\t\t\tconst timer = setTimeout(() => {\n\t\t\t\t\twake = null\n\t\t\t\t\tresolve()\n\t\t\t\t}, ms)\n\t\t\t\twake = () => {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\twake = null\n\t\t\t\t\tresolve()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\twake(): void {\n\t\t\twake?.()\n\t\t},\n\t}\n}\n\nexport class CheckoutManager {\n\tprivate active: string | null = null\n\tprivate readonly now: () => number\n\n\tconstructor(private readonly options: CheckoutManagerOptions) {\n\t\tthis.now = options.now ?? (() => Date.now())\n\t}\n\n\tget pendingKey(): string {\n\t\treturn `extenshi-pay:${this.options.publishableKey}:pendingCheckout`\n\t}\n\n\tisActive(): boolean {\n\t\treturn this.active !== null\n\t}\n\n\tasync open(sku: string, options: CheckoutOptions = {}): Promise<CheckoutResult> {\n\t\tif (this.active) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, 'A checkout is already in progress')\n\t\t}\n\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\tconst session = await this.options.api.createCheckout(\n\t\t\tsku,\n\t\t\tendUserRef,\n\t\t\toptions.locale ?? this.options.locale,\n\t\t)\n\t\tthis.active = session.sessionId\n\t\ttry {\n\t\t\tconst pending: PendingCheckout = { sessionId: session.sessionId, sku, expiresAt: session.expiresAt }\n\t\t\tawait this.options.storage.set(this.pendingKey, pending)\n\t\t\tthis.options.emit('checkout:started', { sku, sessionId: session.sessionId, url: session.url })\n\t\t\tawait (options.openUrl ?? this.options.openUrl ?? openInNewTab)(session.url)\n\t\t\treturn await this.poll(sku, session.sessionId, endUserRef, options)\n\t\t} finally {\n\t\t\tthis.active = null\n\t\t}\n\t}\n\n\t/** Finishes a checkout that was started before a restart; null when there is nothing to resume. */\n\tasync resumePending(): Promise<CheckoutResult | null> {\n\t\tconst raw = (await this.options.storage.get(this.pendingKey)) as Partial<PendingCheckout> | undefined\n\t\tif (!raw || typeof raw.sessionId !== 'string' || typeof raw.sku !== 'string') return null\n\t\tconst expires = Date.parse(raw.expiresAt ?? '')\n\t\tif (!Number.isFinite(expires) || expires + PENDING_GRACE_MS < this.now()) {\n\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\treturn null\n\t\t}\n\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\tlet claim: PayCheckoutClaim\n\t\ttry {\n\t\t\tclaim = await this.options.api.claimSession(raw.sessionId, endUserRef)\n\t\t} catch (error) {\n\t\t\tlogger.debug('could not resume pending checkout', error)\n\t\t\treturn null\n\t\t}\n\t\treturn this.settle(claim, raw.sku, raw.sessionId)\n\t}\n\n\tprivate async poll(\n\t\tsku: string,\n\t\tsessionId: string,\n\t\tendUserRef: string,\n\t\toptions: CheckoutOptions,\n\t): Promise<CheckoutResult> {\n\t\tconst interval = options.pollIntervalMs ?? CHECKOUT_POLL_INTERVAL_MS\n\t\tconst deadline = this.now() + (options.timeoutMs ?? CHECKOUT_TIMEOUT_MS)\n\t\tconst sleeper = interruptibleSleep()\n\t\tconst stopFocus = onFocusRegained(() => sleeper.wake())\n\t\tlet delay = interval\n\t\tlet errorBackoff = 0\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tawait sleeper.sleep(delay)\n\t\t\t\tif (this.now() >= deadline) return { state: 'timeout', sku, sessionId }\n\t\t\t\tlet claim: PayCheckoutClaim\n\t\t\t\ttry {\n\t\t\t\t\tclaim = await this.options.api.claimSession(sessionId, endUserRef)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst err = ExtenshiPayError.from(error)\n\t\t\t\t\tif (err.code === ERROR_CODES.RATE_LIMITED) {\n\t\t\t\t\t\tdelay = (err.retryAfterSec ?? 5) * 1000\n\t\t\t\t\t} else if (\n\t\t\t\t\t\terr.code === ERROR_CODES.NETWORK_ERROR ||\n\t\t\t\t\t\terr.code === ERROR_CODES.TIMEOUT ||\n\t\t\t\t\t\terr.code === ERROR_CODES.GATEWAY_UNAVAILABLE\n\t\t\t\t\t) {\n\t\t\t\t\t\terrorBackoff = Math.min(errorBackoff ? errorBackoff * 2 : interval, MAX_ERROR_BACKOFF_MS)\n\t\t\t\t\t\tdelay = errorBackoff\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\t\t\tthrow err\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\terrorBackoff = 0\n\t\t\t\tdelay = interval\n\t\t\t\tconst result = await this.settle(claim, sku, sessionId)\n\t\t\t\tif (result) return result\n\t\t\t}\n\t\t} finally {\n\t\t\tstopFocus()\n\t\t}\n\t}\n\n\tprivate async settle(\n\t\tclaim: PayCheckoutClaim,\n\t\tsku: string,\n\t\tsessionId: string,\n\t): Promise<CheckoutResult | null> {\n\t\tswitch (claim.state) {\n\t\t\tcase 'pending':\n\t\t\t\treturn null\n\t\t\tcase 'complete': {\n\t\t\t\tconst entitlement = await this.options.onComplete(claim.entitlement)\n\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\tthis.options.emit('checkout:completed', { sku, sessionId, entitlement })\n\t\t\t\treturn { state: 'complete', sku, sessionId, entitlement }\n\t\t\t}\n\t\t\tcase 'canceled':\n\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\tthis.options.emit('checkout:canceled', { sku, sessionId })\n\t\t\t\treturn { state: 'canceled', sku, sessionId }\n\t\t\tcase 'expired':\n\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\tthis.options.emit('checkout:expired', { sku, sessionId })\n\t\t\t\treturn { state: 'expired', sku, sessionId }\n\t\t\tdefault:\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Unknown checkout claim state')\n\t\t}\n\t}\n}\n","/** Pure helpers over the entitlement projection. Features come from the items' `features[]`. */\n\nimport type { PayEntitlementItem } from '../types/contract.js'\nimport type { Entitlement } from '../types/entitlement.js'\n\nconst LIVE_STATUSES: ReadonlySet<string> = new Set(['active', 'grace'])\n\nexport function isLive(item: PayEntitlementItem): boolean {\n\treturn LIVE_STATUSES.has(item.status)\n}\n\n/** An item past its `expiresAt` reads as expired without a network round-trip. */\nexport function applyLocalExpiry(\n\titems: PayEntitlementItem[],\n\tnow: number = Date.now(),\n): PayEntitlementItem[] {\n\treturn items.map((item) => {\n\t\tif (!isLive(item) || !item.expiresAt) return item\n\t\tconst expires = Date.parse(item.expiresAt)\n\t\treturn Number.isFinite(expires) && expires <= now ? { ...item, status: 'expired' } : item\n\t})\n}\n\nexport function collectFeatures(items: PayEntitlementItem[]): string[] {\n\tconst features = new Set<string>()\n\tfor (const item of items) {\n\t\tif (!isLive(item)) continue\n\t\tfor (const feature of item.features) features.add(feature)\n\t}\n\treturn [...features]\n}\n\nexport function isEntitled(entitlement: Entitlement, sku?: string): boolean {\n\treturn (\n\t\t!entitlement.requiresOnlineCheck &&\n\t\tentitlement.items.some((item) => isLive(item) && (sku === undefined || item.sku === sku))\n\t)\n}\n\nexport function hasFeature(entitlement: Entitlement, feature: string): boolean {\n\treturn entitlement.features.includes(feature)\n}\n\nexport function checkFeatures(entitlement: Entitlement, features: string[]): Record<string, boolean> {\n\tconst result: Record<string, boolean> = {}\n\tfor (const feature of features) result[feature] = hasFeature(entitlement, feature)\n\treturn result\n}\n\nexport const EMPTY_ENTITLEMENT: Entitlement = Object.freeze({\n\titems: [],\n\tfeatures: [],\n\tverified: false,\n\tissuedAt: null,\n\tfetchedAt: null,\n\tsource: 'none',\n\trequiresOnlineCheck: false,\n\tofflineUntil: null,\n}) as Entitlement\n\n// Frozen empty arrays prevent consumers from changing the shared denied state.\nObject.freeze(EMPTY_ENTITLEMENT.items)\nObject.freeze(EMPTY_ENTITLEMENT.features)\n","/**\n * Ed25519 verification of the entitlement projection.\n *\n * Tamper resistance, not DRM. Trust comes from the developer's bundled key or\n * a key fetched over HTTPS, never from editable extension storage. Callers must\n * deny access for both invalid and unverified envelopes outside explicit mocks.\n */\n\nimport { canonicalJson, type SignedEntitlement } from '../types/contract.js'\n\nexport type SignatureVerdict = 'valid' | 'invalid' | 'unverified'\n\nexport function base64ToBytes(base64: string): Uint8Array<ArrayBuffer> {\n\tconst binary = atob(base64)\n\tconst bytes = new Uint8Array(binary.length)\n\tfor (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n\treturn bytes\n}\n\nexport async function verifyEntitlementSignature(\n\tenvelope: SignedEntitlement,\n\tpublicKeyBase64: string | null,\n): Promise<SignatureVerdict> {\n\tif (!envelope.signature || envelope.alg !== 'ed25519') return 'invalid'\n\tif (!publicKeyBase64) return 'unverified'\n\tconst subtle = (globalThis as { crypto?: Crypto }).crypto?.subtle\n\tif (!subtle) return 'unverified'\n\n\tlet key: CryptoKey\n\ttry {\n\t\tkey = await subtle.importKey('raw', base64ToBytes(publicKeyBase64), { name: 'Ed25519' }, false, [\n\t\t\t'verify',\n\t\t])\n\t} catch {\n\t\treturn 'unverified'\n\t}\n\n\ttry {\n\t\tconst data = new TextEncoder().encode(canonicalJson(envelope.payload))\n\t\tconst ok = await subtle.verify('Ed25519', key, base64ToBytes(envelope.signature), data)\n\t\treturn ok ? 'valid' : 'invalid'\n\t} catch {\n\t\treturn 'invalid'\n\t}\n}\n","/**\n * Entitlement cache + refresh.\n *\n * The cached envelope is a cache OF the server projection, never a second\n * source of truth: it is verified when stored and re-verified on load (once\n * the project's public key is known), served without a round-trip while the\n * TTL holds, served for up to 48 hours after signed issuance when the network is down, and expired\n * locally by `expiresAt`. Background refresh polls at most every 15 minutes\n * and backs off exponentially on errors.\n */\n\nimport type { PayApi } from '../api/pay-api.js'\nimport type { StorageAdapter } from '../core/storage.js'\nimport { canonicalJson, type SignedEntitlement } from '../types/contract.js'\nimport type { Entitlement, EntitlementSource } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { logger } from '../utils/logger.js'\nimport { applyLocalExpiry, collectFeatures, EMPTY_ENTITLEMENT } from './features.js'\nimport { verifyEntitlementSignature } from './signature.js'\n\nexport const MIN_REFRESH_INTERVAL_MS = 15 * 60 * 1000\nexport const MAX_REFRESH_BACKOFF_MS = 6 * 60 * 60 * 1000\nexport const MAX_OFFLINE_AGE_MS = 48 * 60 * 60 * 1000\n// Allow small server/client clock skew without granting more than the signed age limit.\nexport const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000\nconst CACHE_VERSION = 1\n\ninterface CacheRecord {\n\tv: typeof CACHE_VERSION\n\tenvelope: SignedEntitlement\n\tfetchedAt: number\n}\n\ninterface Held {\n\tenvelope: SignedEntitlement\n\tfetchedAt: number\n\tverified: boolean\n\tsource: EntitlementSource\n}\n\nexport interface EntitlementManagerOptions {\n\tapi: PayApi\n\tstorage: StorageAdapter\n\tpublishableKey: string\n\tcacheTtlMs: number\n\tsource?: EntitlementSource\n\tgetEndUserRef: () => Promise<string>\n\t/** Base64 raw Ed25519 public key from `getOffer`, or null when unknown/unsigned. */\n\tgetPublicKey: () => Promise<string | null>\n\tonChange?: (entitlement: Entitlement) => void\n\tonError?: (error: ExtenshiPayError) => void\n\tnow?: () => number\n}\n\nfunction isEnvelope(value: unknown): value is SignedEntitlement {\n\tif (!value || typeof value !== 'object') return false\n\tconst env = value as SignedEntitlement\n\treturn (\n\t\t!!env.payload &&\n\t\ttypeof env.payload === 'object' &&\n\t\ttypeof env.payload.endUserRef === 'string' &&\n\t\tArray.isArray(env.payload.entitlements) &&\n\t\ttypeof env.payload.issuedAt === 'string'\n\t)\n}\n\nexport class EntitlementManager {\n\tprivate held: Held | null = null\n\tprivate inflight: Promise<Entitlement> | null = null\n\tprivate timer: ReturnType<typeof setTimeout> | null = null\n\tprivate refreshGeneration = 0\n\tprivate deadlineTimer: ReturnType<typeof setTimeout> | null = null\n\tprivate refreshIntervalMs = MIN_REFRESH_INTERVAL_MS\n\tprivate backoffMs = 0\n\tprivate autoRefresh = false\n\tprivate readonly online = () => {\n\t\tvoid this.get({ force: true }).then(() => this.notifyIfChanged())\n\t}\n\t// Starts at the empty projection: a first load that finds nothing is not a\n\t// change, a first load that finds a paid entitlement is.\n\tprivate lastFingerprint: string | null = canonicalJson({ items: [], requiresOnlineCheck: false })\n\tprivate readonly now: () => number\n\tprivate readonly source: EntitlementSource\n\n\tconstructor(private readonly options: EntitlementManagerOptions) {\n\t\tthis.now = options.now ?? (() => Date.now())\n\t\tthis.source = options.source ?? 'network'\n\t}\n\n\tget storageKey(): string {\n\t\t// Keep the real cache key stable for upgrades. Simulated grants must\n\t\t// neither consume nor overwrite that cache when developers switch modes.\n\t\treturn `extenshi-pay:${this.options.publishableKey}:entitlement${this.source === 'mock' ? ':mock' : ''}`\n\t}\n\n\t/** Loads the persisted envelope (unverified until `reverify()`); no network. */\n\tasync load(): Promise<Entitlement | null> {\n\t\tconst raw = await this.options.storage.get(this.storageKey)\n\t\tconst record = raw as Partial<CacheRecord> | undefined\n\t\tif (\n\t\t\t!record ||\n\t\t\trecord.v !== CACHE_VERSION ||\n\t\t\t!isEnvelope(record.envelope) ||\n\t\t\ttypeof record.fetchedAt !== 'number' ||\n\t\t\t!Number.isFinite(record.fetchedAt)\n\t\t) {\n\t\t\treturn null\n\t\t}\n\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\tif (\n\t\t\trecord.envelope.payload.endUserRef !== endUserRef ||\n\t\t\t(this.source !== 'mock' && record.envelope.payload.publishableKey !== this.options.publishableKey)\n\t\t) {\n\t\t\tawait this.options.storage.remove(this.storageKey)\n\t\t\treturn null\n\t\t}\n\t\tthis.held = {\n\t\t\tenvelope: JSON.parse(JSON.stringify(record.envelope)),\n\t\t\tfetchedAt: record.fetchedAt,\n\t\t\tverified: false,\n\t\t\tsource: this.source === 'mock' ? 'mock' : 'cache',\n\t\t}\n\t\tthis.lastFingerprint = this.fingerprint()\n\t\treturn this.snapshot()\n\t}\n\n\t/** Re-checks the loaded envelope against the project's key; discards it when the signature is invalid. */\n\tasync reverify(): Promise<void> {\n\t\tif (!this.held) return\n\t\tif (this.source === 'mock') return\n\t\tconst held = this.held\n\t\tconst key = await this.safePublicKey()\n\t\tconst verdict = await verifyEntitlementSignature(held.envelope, key)\n\t\tif (held !== this.held) return\n\t\tif (verdict === 'invalid') {\n\t\t\tlogger.warn('cached entitlement failed signature verification; discarding')\n\t\t\tawait this.discard()\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Cached entitlement signature is invalid')\n\t\t}\n\t\theld.verified = verdict === 'valid'\n\t\tif (!held.verified) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.VERIFICATION_UNAVAILABLE,\n\t\t\t\t'Entitlement verification requires a trusted key and Ed25519 WebCrypto support',\n\t\t\t)\n\t\t}\n\t\tthis.scheduleDeadline()\n\t}\n\n\tgetCached(): Entitlement | null {\n\t\treturn this.held ? this.snapshot() : null\n\t}\n\n\tisFresh(): boolean {\n\t\treturn (\n\t\t\tthis.held !== null &&\n\t\t\t(this.source === 'mock' || (this.held.verified && !this.snapshot().requiresOnlineCheck)) &&\n\t\t\tthis.now() >= this.held.fetchedAt &&\n\t\t\tthis.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, MAX_OFFLINE_AGE_MS)\n\t\t)\n\t}\n\n\tasync get(options: { force?: boolean } = {}): Promise<Entitlement> {\n\t\tif (!options.force && this.isFresh()) return this.snapshot()\n\t\ttry {\n\t\t\treturn await this.refresh()\n\t\t} catch (error) {\n\t\t\tconst err = ExtenshiPayError.from(error)\n\t\t\tthis.options.onError?.(err)\n\t\t\tif (this.held) {\n\t\t\t\tlogger.debug('serving cached entitlement after refresh failure', err.code)\n\t\t\t\treturn this.snapshot()\n\t\t\t}\n\t\t\treturn EMPTY_ENTITLEMENT\n\t\t}\n\t}\n\n\t/** Fetches the projection from the backend, verifies and stores it. */\n\trefresh(): Promise<Entitlement> {\n\t\tif (!this.inflight) {\n\t\t\tthis.inflight = (async () => {\n\t\t\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\t\t\tconst envelope = await this.options.api.getEntitlement(endUserRef)\n\t\t\t\treturn this.accept(envelope, this.source)\n\t\t\t})().finally(() => {\n\t\t\t\tthis.inflight = null\n\t\t\t})\n\t\t}\n\t\treturn this.inflight\n\t}\n\n\t/** Verifies and stores an envelope obtained elsewhere (e.g. from `claimSession`). */\n\tasync accept(envelope: SignedEntitlement, source: EntitlementSource = this.source): Promise<Entitlement> {\n\t\tif (!isEnvelope(envelope)) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Malformed entitlement envelope')\n\t\t}\n\t\t// Detach from callers/storage: later mutation must not alter verified state.\n\t\tenvelope = JSON.parse(JSON.stringify(envelope)) as SignedEntitlement\n\t\tif (this.source !== 'mock' && envelope.payload.publishableKey !== this.options.publishableKey) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_RESPONSE,\n\t\t\t\t'Entitlement belongs to a different application or lacks a signed application scope',\n\t\t\t)\n\t\t}\n\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\tif (envelope.payload.endUserRef !== endUserRef) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_RESPONSE,\n\t\t\t\t'Entitlement issued for a different endUserRef',\n\t\t\t)\n\t\t}\n\t\tconst verdict =\n\t\t\tthis.source === 'mock'\n\t\t\t\t? 'unverified'\n\t\t\t\t: await verifyEntitlementSignature(envelope, await this.safePublicKey())\n\t\tif (verdict === 'invalid') {\n\t\t\tawait this.discard()\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement signature is invalid')\n\t\t}\n\t\tif (verdict !== 'valid' && this.source !== 'mock') {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.VERIFICATION_UNAVAILABLE,\n\t\t\t\t'Entitlement verification requires a trusted key and Ed25519 WebCrypto support',\n\t\t\t)\n\t\t}\n\t\tconst fetchedAt = this.now()\n\t\tconst issuedAt = Date.parse(envelope.payload.issuedAt)\n\t\tif (this.source !== 'mock' && (!Number.isFinite(issuedAt) || issuedAt > fetchedAt + MAX_CLOCK_SKEW_MS)) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_RESPONSE,\n\t\t\t\t'Entitlement issuedAt is invalid or in the future',\n\t\t\t)\n\t\t}\n\t\tthis.held = { envelope, fetchedAt, verified: verdict === 'valid', source }\n\t\tconst record: CacheRecord = { v: CACHE_VERSION, envelope, fetchedAt }\n\t\tawait this.options.storage.set(this.storageKey, JSON.parse(JSON.stringify(record)))\n\t\tthis.backoffMs = 0\n\t\tthis.scheduleDeadline()\n\t\tthis.notifyIfChanged()\n\t\treturn this.snapshot()\n\t}\n\n\t/** Drain an older installation refresh before changing identity. */\n\tasync settleRefresh(): Promise<void> {\n\t\tawait this.inflight?.catch(() => undefined)\n\t}\n\n\tasync clear(): Promise<void> {\n\t\tthis.held = null\n\t\tthis.scheduleDeadline()\n\t\tthis.lastFingerprint = null\n\t\tawait this.options.storage.remove(this.storageKey)\n\t}\n\n\tstartAutoRefresh(intervalMs: number = Math.max(this.options.cacheTtlMs, MIN_REFRESH_INTERVAL_MS)): void {\n\t\tthis.stopAutoRefresh()\n\t\tthis.autoRefresh = true\n\t\tglobalThis.addEventListener?.('online', this.online)\n\t\tthis.refreshIntervalMs = Math.max(intervalMs, MIN_REFRESH_INTERVAL_MS)\n\t\tthis.schedule(this.refreshIntervalMs)\n\t\tthis.scheduleDeadline()\n\t}\n\n\tstopAutoRefresh(): void {\n\t\tthis.autoRefresh = false\n\t\tglobalThis.removeEventListener?.('online', this.online)\n\t\tthis.refreshGeneration++\n\t\tif (this.deadlineTimer !== null) clearTimeout(this.deadlineTimer)\n\t\tthis.deadlineTimer = null\n\t\tif (this.timer !== null) clearTimeout(this.timer)\n\t\tthis.timer = null\n\t}\n\n\tprivate scheduleDeadline(): void {\n\t\tif (this.deadlineTimer !== null) clearTimeout(this.deadlineTimer)\n\t\tthis.deadlineTimer = null\n\t\tif (!this.autoRefresh || !this.held || !this.held.verified || this.source === 'mock') return\n\t\tconst now = this.now()\n\t\tif (now >= this.offlineDeadline()) return\n\t\tconst deadlines = [\n\t\t\tthis.offlineDeadline(),\n\t\t\t...this.held.envelope.payload.entitlements\n\t\t\t\t.filter((item) => item.status === 'active' || item.status === 'grace')\n\t\t\t\t.map((item) => (item.expiresAt ? Date.parse(item.expiresAt) : NaN)),\n\t\t]\n\t\tconst remaining = Math.min(...deadlines.filter((deadline) => deadline > now)) - now\n\t\tif (!Number.isFinite(remaining) || remaining <= 0) return\n\t\tthis.deadlineTimer = setTimeout(() => {\n\t\t\tthis.deadlineTimer = null\n\t\t\tthis.notifyIfChanged()\n\t\t\tthis.scheduleDeadline()\n\t\t}, remaining)\n\t}\n\n\tprivate schedule(delayMs: number): void {\n\t\tconst generation = this.refreshGeneration\n\t\tthis.timer = setTimeout(async () => {\n\t\t\tthis.timer = null\n\t\t\ttry {\n\t\t\t\tawait this.refresh()\n\t\t\t\tif (generation !== this.refreshGeneration) return\n\t\t\t\tthis.schedule(this.refreshIntervalMs)\n\t\t\t} catch (error) {\n\t\t\t\tif (generation !== this.refreshGeneration) return\n\t\t\t\tthis.options.onError?.(ExtenshiPayError.from(error))\n\t\t\t\tthis.backoffMs = Math.min(\n\t\t\t\t\tthis.backoffMs ? this.backoffMs * 2 : this.refreshIntervalMs,\n\t\t\t\t\tMAX_REFRESH_BACKOFF_MS,\n\t\t\t\t)\n\t\t\t\tthis.schedule(this.backoffMs)\n\t\t\t}\n\t\t}, delayMs)\n\t}\n\n\tprivate async safePublicKey(): Promise<string | null> {\n\t\ttry {\n\t\t\treturn await this.options.getPublicKey()\n\t\t} catch (error) {\n\t\t\tlogger.debug('public key unavailable; entitlement stays unverified', error)\n\t\t\treturn null\n\t\t}\n\t}\n\n\tprivate async discard(): Promise<void> {\n\t\tthis.held = null\n\t\tthis.scheduleDeadline()\n\t\tawait this.options.storage.remove(this.storageKey)\n\t\tthis.notifyIfChanged()\n\t}\n\n\tprivate fingerprint(): string {\n\t\tconst state = this.snapshot()\n\t\treturn canonicalJson({ items: state.items, requiresOnlineCheck: state.requiresOnlineCheck })\n\t}\n\n\tprivate notifyIfChanged(): void {\n\t\tconst fingerprint = this.fingerprint()\n\t\tif (fingerprint === this.lastFingerprint) return\n\t\tthis.lastFingerprint = fingerprint\n\t\tthis.options.onChange?.(this.snapshot())\n\t}\n\n\tprivate offlineDeadline(): number {\n\t\tif (!this.held) return NaN\n\t\t// fetchedAt is untrusted bookkeeping; it may shorten, never extend, a grant.\n\t\treturn Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + MAX_OFFLINE_AGE_MS\n\t}\n\n\tprivate snapshot(): Entitlement {\n\t\tif (!this.held) return EMPTY_ENTITLEMENT\n\t\tif (this.source !== 'mock' && !this.held.verified) {\n\t\t\treturn { ...EMPTY_ENTITLEMENT, requiresOnlineCheck: true, source: this.held.source }\n\t\t}\n\t\tconst items = applyLocalExpiry(\n\t\t\tJSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)),\n\t\t\tthis.now(),\n\t\t)\n\t\tconst hasPaidAccess =\n\t\t\tcollectFeatures(items).length > 0 ||\n\t\t\titems.some((item) => item.status === 'active' || item.status === 'grace')\n\t\tconst offlineUntil = this.source === 'mock' || !hasPaidAccess ? null : this.offlineDeadline()\n\t\tconst requiresOnlineCheck =\n\t\t\tofflineUntil !== null &&\n\t\t\t(!Number.isFinite(offlineUntil) ||\n\t\t\t\tthis.now() >= offlineUntil ||\n\t\t\t\tthis.now() < this.held.fetchedAt ||\n\t\t\t\tthis.now() + MAX_CLOCK_SKEW_MS < Date.parse(this.held.envelope.payload.issuedAt))\n\t\treturn {\n\t\t\titems,\n\t\t\tfeatures: requiresOnlineCheck ? [] : collectFeatures(items),\n\t\t\trequiresOnlineCheck,\n\t\t\tofflineUntil,\n\t\t\tverified: this.held.verified,\n\t\t\tissuedAt: this.held.envelope.payload.issuedAt,\n\t\t\tfetchedAt: this.held.fetchedAt,\n\t\t\tsource: this.held.source,\n\t\t}\n\t}\n}\n","/**\n * Persistent key/value storage for the SDK's own namespace.\n *\n * Preference order: `chrome.storage.local` (Chrome/Edge), `browser.storage.local`\n * (Firefox), `localStorage` (non-extension contexts such as a dev page), then\n * memory. Both promise-returning (MV3, Firefox) and callback-only (MV2) storage\n * APIs are supported.\n */\n\nexport interface StorageAdapter {\n\tget(key: string): Promise<unknown>\n\tset(key: string, value: unknown): Promise<void>\n\tremove(key: string): Promise<void>\n}\n\ntype Items = Record<string, unknown>\n\ninterface StorageArea {\n\tget(keys: string, callback?: (items: Items) => void): unknown\n\tset(items: Items, callback?: () => void): unknown\n\tremove(keys: string, callback?: () => void): unknown\n}\n\ninterface ExtensionGlobals {\n\tchrome?: { storage?: { local?: StorageArea }; runtime?: { lastError?: { message?: string } } }\n\tbrowser?: { storage?: { local?: StorageArea } }\n}\n\nfunction extensionGlobals(): ExtensionGlobals {\n\treturn globalThis as ExtensionGlobals\n}\n\nfunction isThenable<T>(value: unknown): value is Promise<T> {\n\treturn !!value && typeof (value as Promise<T>).then === 'function'\n}\n\n/** Runs a storage-area call that may either return a promise or expect a callback. */\nfunction areaCall<T>(\n\tdirect: () => unknown,\n\twithCallback: (callback: (value: T) => void) => void,\n): Promise<T> {\n\tconst result = direct()\n\tif (isThenable<T>(result)) return result\n\treturn new Promise<T>((resolve, reject) => {\n\t\twithCallback((value) => {\n\t\t\tconst lastError = extensionGlobals().chrome?.runtime?.lastError\n\t\t\tif (lastError) reject(new Error(lastError.message ?? 'storage error'))\n\t\t\telse resolve(value)\n\t\t})\n\t})\n}\n\nexport class ExtensionStorage implements StorageAdapter {\n\tconstructor(private readonly area: StorageArea) {}\n\n\tasync get(key: string): Promise<unknown> {\n\t\tconst items = await areaCall<Items>(\n\t\t\t() => this.area.get(key),\n\t\t\t(cb) => this.area.get(key, cb),\n\t\t)\n\t\treturn items?.[key]\n\t}\n\n\tasync set(key: string, value: unknown): Promise<void> {\n\t\tawait areaCall<void>(\n\t\t\t() => this.area.set({ [key]: value }),\n\t\t\t(cb) => this.area.set({ [key]: value }, cb),\n\t\t)\n\t}\n\n\tasync remove(key: string): Promise<void> {\n\t\tawait areaCall<void>(\n\t\t\t() => this.area.remove(key),\n\t\t\t(cb) => this.area.remove(key, cb),\n\t\t)\n\t}\n}\n\nexport class LocalStorageAdapter implements StorageAdapter {\n\tconstructor(private readonly store: Storage) {}\n\n\tasync get(key: string): Promise<unknown> {\n\t\tconst raw = this.store.getItem(key)\n\t\tif (raw === null) return undefined\n\t\ttry {\n\t\t\treturn JSON.parse(raw)\n\t\t} catch {\n\t\t\treturn undefined\n\t\t}\n\t}\n\n\tasync set(key: string, value: unknown): Promise<void> {\n\t\tthis.store.setItem(key, JSON.stringify(value))\n\t}\n\n\tasync remove(key: string): Promise<void> {\n\t\tthis.store.removeItem(key)\n\t}\n}\n\nexport class MemoryStorage implements StorageAdapter {\n\tprivate readonly map = new Map<string, unknown>()\n\n\tasync get(key: string): Promise<unknown> {\n\t\treturn this.map.get(key)\n\t}\n\n\tasync set(key: string, value: unknown): Promise<void> {\n\t\tthis.map.set(key, value)\n\t}\n\n\tasync remove(key: string): Promise<void> {\n\t\tthis.map.delete(key)\n\t}\n}\n\nexport function createStorage(): StorageAdapter {\n\tconst g = extensionGlobals()\n\tconst area = g.chrome?.storage?.local ?? g.browser?.storage?.local\n\tif (area) return new ExtensionStorage(area)\n\ttry {\n\t\tconst store = (globalThis as { localStorage?: Storage }).localStorage\n\t\tif (store && typeof store.getItem === 'function') return new LocalStorageAdapter(store)\n\t} catch {\n\t\t// Access to localStorage can throw in sandboxed frames.\n\t}\n\treturn new MemoryStorage()\n}\n","/** Email stays on the hosted page. Only this extension context holds the claim secret. */\nimport type { PayApi } from '../api/pay-api.js'\nimport type { StorageAdapter } from '../core/storage.js'\nimport { ExtensionStorage, MemoryStorage } from '../core/storage.js'\nimport type { SignedEntitlement } from '../types/contract.js'\nimport type { Entitlement, RestoreOptions, RestoreResult } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { openInNewTab } from './checkout.js'\n\ntype SessionArea = ConstructorParameters<typeof ExtensionStorage>[0]\n\n/** storage.local is exposed to content scripts by default. Never put a recovery proof there. */\nexport function createRecoveryStorage(): StorageAdapter {\n\tconst g = globalThis as {\n\t\tchrome?: { storage?: { session?: SessionArea }; tabs?: unknown }\n\t\tbrowser?: { storage?: { session?: SessionArea }; tabs?: unknown }\n\t}\n\tconst extension = g.chrome?.tabs ? g.chrome : g.browser?.tabs ? g.browser : null\n\treturn extension?.storage?.session ? new ExtensionStorage(extension.storage.session) : new MemoryStorage()\n}\n\ninterface PendingRestore {\n\tsessionId: string\n\tclaimSecret: string\n\texpiresAt: string\n}\nexport interface RecoveryManagerOptions {\n\tapi: PayApi\n\tstorage: StorageAdapter\n\tpublishableKey: string\n\tonComplete: (endUserRef: string, envelope: SignedEntitlement) => Promise<Entitlement>\n\topenUrl?: (url: string) => void | Promise<void>\n\tnow?: () => number\n}\n\nexport class RecoveryManager {\n\tprivate active = false\n\tprivate stopped = false\n\tprivate wake: (() => void) | null = null\n\tconstructor(private readonly options: RecoveryManagerOptions) {}\n\tget pendingKey(): string {\n\t\treturn `extenshi-pay:${this.options.publishableKey}:pendingRestore`\n\t}\n\tisActive(): boolean {\n\t\treturn this.active\n\t}\n\tstop(): void {\n\t\tthis.stopped = true\n\t\tthis.wake?.()\n\t}\n\n\tasync open(options: RestoreOptions = {}): Promise<RestoreResult> {\n\t\tif (this.active)\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Recovery is already in progress')\n\t\tthis.active = true\n\t\tthis.stopped = false\n\t\ttry {\n\t\t\t// A caller from a content script must route the action to its own background;\n\t\t\t// never return this manager's internal state through that message bridge.\n\t\t\tconst g = globalThis as {\n\t\t\t\tchrome?: { runtime?: { id?: string }; tabs?: unknown }\n\t\t\t\tbrowser?: { runtime?: { id?: string }; tabs?: unknown }\n\t\t\t}\n\t\t\tif ((g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs))\n\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t'Start recovery in an extension page or background context',\n\t\t\t\t)\n\t\t\tconst cryptoApi = globalThis.crypto\n\t\t\tif (!cryptoApi?.subtle)\n\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t'Secure recovery is unavailable in this browser',\n\t\t\t\t)\n\t\t\tconst secret = Array.from(cryptoApi.getRandomValues(new Uint8Array(32)), (b) =>\n\t\t\t\tb.toString(16).padStart(2, '0'),\n\t\t\t).join('')\n\t\t\tconst hash = await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(secret))\n\t\t\tconst challenge = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('')\n\t\t\tconst created = await this.options.api.createRestoreSession(challenge)\n\t\t\tif (!Number.isFinite(Date.parse(created.expiresAt)))\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery expiry')\n\t\t\tconst pending = { sessionId: created.sessionId, expiresAt: created.expiresAt, claimSecret: secret }\n\t\t\tawait this.options.storage.set(this.pendingKey, pending)\n\t\t\tawait (options.openUrl ?? this.options.openUrl ?? openInNewTab)(created.url)\n\t\t\treturn await this.poll(pending, options)\n\t\t} finally {\n\t\t\tthis.active = false\n\t\t}\n\t}\n\n\tasync resumePending(): Promise<RestoreResult | null> {\n\t\tif (this.active || this.stopped) return null\n\t\tconst raw = (await this.options.storage.get(this.pendingKey)) as Partial<PendingRestore> | undefined\n\t\tif (!raw || this.active || this.stopped) return null\n\t\tif (\n\t\t\ttypeof raw.sessionId !== 'string' ||\n\t\t\ttypeof raw.claimSecret !== 'string' ||\n\t\t\t!/^[a-f0-9]{64}$/.test(raw.claimSecret) ||\n\t\t\t!Number.isFinite(Date.parse(raw.expiresAt ?? ''))\n\t\t) {\n\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\treturn null\n\t\t}\n\t\tthis.active = true\n\t\tthis.stopped = false\n\t\ttry {\n\t\t\treturn await this.poll(raw as PendingRestore, {})\n\t\t} finally {\n\t\t\tthis.active = false\n\t\t}\n\t}\n\n\tprivate async poll(pending: PendingRestore, options: RestoreOptions): Promise<RestoreResult> {\n\t\tconst now = this.options.now ?? Date.now\n\t\tconst expires = Date.parse(pending.expiresAt)\n\t\tconst deadline = Math.min(expires, now() + (options.timeoutMs ?? 10 * 60 * 1000))\n\t\tlet delay = 0\n\t\twhile (!this.stopped && !options.signal?.aborted && now() < deadline) {\n\t\t\tif (delay)\n\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\tconst done = () => {\n\t\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\t\toptions.signal?.removeEventListener('abort', done)\n\t\t\t\t\t\tthis.wake = null\n\t\t\t\t\t\tresolve()\n\t\t\t\t\t}\n\t\t\t\t\tconst timer = setTimeout(done, Math.min(delay, Math.max(0, deadline - now())))\n\t\t\t\t\tthis.wake = done\n\t\t\t\t\toptions.signal?.addEventListener('abort', done, { once: true })\n\t\t\t\t})\n\t\t\tif (this.stopped || options.signal?.aborted || now() >= deadline) break\n\t\t\ttry {\n\t\t\t\tconst claim = await this.options.api.claimRestoreSession(pending.sessionId, pending.claimSecret)\n\t\t\t\tif (this.stopped || options.signal?.aborted) break\n\t\t\t\tif (claim.state === 'complete') {\n\t\t\t\t\tconst entitlement = await this.options.onComplete(claim.endUserRef, claim.entitlement)\n\t\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\t\treturn { state: 'complete', entitlement }\n\t\t\t\t}\n\t\t\t\tif (claim.state !== 'pending')\n\t\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery response')\n\t\t\t\tdelay = Math.max(100, options.pollIntervalMs ?? 2_000)\n\t\t\t} catch (error) {\n\t\t\t\tconst err = ExtenshiPayError.from(error)\n\t\t\t\tif (\n\t\t\t\t\t![\n\t\t\t\t\t\tERROR_CODES.NETWORK_ERROR,\n\t\t\t\t\t\tERROR_CODES.TIMEOUT,\n\t\t\t\t\t\tERROR_CODES.GATEWAY_UNAVAILABLE,\n\t\t\t\t\t\tERROR_CODES.RATE_LIMITED,\n\t\t\t\t\t].some((code) => code === err.code)\n\t\t\t\t)\n\t\t\t\t\tthrow err\n\t\t\t\tdelay = Math.max(2_000, (err.retryAfterSec ?? 5) * 1000)\n\t\t\t}\n\t\t}\n\t\tif (now() >= expires) await this.options.storage.remove(this.pendingKey)\n\t\treturn {\n\t\t\tstate: this.stopped || options.signal?.aborted ? 'canceled' : now() >= expires ? 'expired' : 'timeout',\n\t\t}\n\t}\n}\n","import type { PayEntitlementItem, PayOfferDto } from './contract.js'\nimport type { ExtenshiPayError } from './errors.js'\n\nexport type LogLevel = 'silent' | 'error' | 'warn' | 'info' | 'debug'\n\n/** Reserved for future routing; today every environment talks to the same BFF. */\nexport type Environment = 'production' | 'sandbox' | 'development'\n\nexport interface ThemeConfig {\n\t/** `auto` follows `prefers-color-scheme`. */\n\tmode?: 'light' | 'dark' | 'auto'\n\tprimaryColor?: string\n\tfontFamily?: string\n\tborderRadius?: string\n\t/** Appended verbatim inside the paywall's shadow root. */\n\tcustomCss?: string\n}\n\n/** Offline development data used when `mock: true`. */\nexport interface MockData {\n\tentitlements?: PayEntitlementItem[]\n\toffers?: PayOfferDto[]\n\tprojectName?: string\n\t/** Defaults to true. */\n\tcheckoutEnabled?: boolean\n\t/** How many `claimSession` polls answer `pending` before a mock checkout completes (default 1). */\n\tclaimAfterPolls?: number\n}\n\nexport interface ExtenshiPayConfig {\n\t/** `pk_ext_` + 32 hex characters, from the project's Monetization tab. */\n\tpublishableKey: string\n\t/** Defaults to `https://bff.extenshi.io`. */\n\tapiUrl?: string\n\t/** Bundled raw Ed25519 public key (base64). Enables verified cache use after an offline restart. */\n\tentitlementPublicKey?: string\n\tenvironment?: Environment\n\t/** Shorthand for `logLevel: 'debug'`. */\n\tdebug?: boolean\n\tlogLevel?: LogLevel\n\t/** How long a fetched entitlement is served without a network round-trip (default 1 hour). */\n\tcacheTtlMs?: number\n\t/** BCP-47 tag such as `en` or `de-DE`; sent to the backend for checkout/offer copy and used for price formatting. */\n\tlocale?: string\n\tmock?: boolean\n\tmockData?: MockData\n\tonReady?: () => void\n\tonError?: (error: ExtenshiPayError) => void\n\ttheme?: ThemeConfig\n}\n\nexport interface ResolvedConfig {\n\tpublishableKey: string\n\tapiUrl: string\n\tentitlementPublicKey: string | null\n\tenvironment: Environment\n\tdebug: boolean\n\tlogLevel: LogLevel\n\tcacheTtlMs: number\n\tlocale: string | null\n\tmock: boolean\n\tmockData: MockData | null\n\ttheme: ThemeConfig\n}\n\nexport const DEFAULT_API_URL = 'https://bff.extenshi.io'\nexport const DEFAULT_CACHE_TTL_MS = 60 * 60 * 1000\nexport const MAX_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000\n","/** Kept in sync with package.json by tests/unit/version.test.ts. */\nexport const VERSION = '0.7.1'\n","import {\n\tDEFAULT_API_URL,\n\tDEFAULT_CACHE_TTL_MS,\n\ttype ExtenshiPayConfig,\n\tMAX_CACHE_TTL_MS,\n\ttype ResolvedConfig,\n} from '../types/config.js'\nimport { isPayPublishableKey } from '../types/contract.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\n\nconst ENVIRONMENTS = new Set(['production', 'sandbox', 'development'])\nconst LOG_LEVELS = new Set(['silent', 'error', 'warn', 'info', 'debug'])\nconst THEME_MODES = new Set(['light', 'dark', 'auto'])\n/** Same shape the BFF accepts (`en`, `de-DE`, `zh-Hant`). */\nexport const LOCALE_RE = /^[a-z]{2}(-[A-Za-z]{2,4})?$/\n\nfunction isHttpUrl(value: string): boolean {\n\ttry {\n\t\tconst url = new URL(value)\n\t\treturn url.protocol === 'https:' || url.protocol === 'http:'\n\t} catch {\n\t\treturn false\n\t}\n}\n\nexport function resolveConfig(input: ExtenshiPayConfig): ResolvedConfig {\n\tconst errors: string[] = []\n\tif (!input || typeof input !== 'object') {\n\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_CONFIG, 'ExtenshiPay config must be an object')\n\t}\n\n\tif (!isPayPublishableKey(input.publishableKey)) {\n\t\terrors.push('publishableKey must look like pk_ext_<32 hex characters>')\n\t}\n\n\tconst apiUrl = (input.apiUrl ?? DEFAULT_API_URL).replace(/\\/+$/, '')\n\tif (!isHttpUrl(apiUrl)) errors.push('apiUrl must be an http(s) URL')\n\n\tconst entitlementPublicKey = input.entitlementPublicKey ?? null\n\tif (entitlementPublicKey !== null && !/^[A-Za-z0-9+/]{43}=$/.test(entitlementPublicKey)) {\n\t\terrors.push('entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key')\n\t}\n\n\tconst environment = input.environment ?? 'production'\n\tif (!ENVIRONMENTS.has(environment)) errors.push('environment must be production, sandbox or development')\n\n\tconst logLevel = input.logLevel ?? 'warn'\n\tif (!LOG_LEVELS.has(logLevel)) errors.push('logLevel must be silent, error, warn, info or debug')\n\n\tconst cacheTtlMs = input.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS\n\tif (!Number.isFinite(cacheTtlMs) || cacheTtlMs < 0 || cacheTtlMs > MAX_CACHE_TTL_MS) {\n\t\terrors.push(`cacheTtlMs must be between 0 and ${MAX_CACHE_TTL_MS}`)\n\t}\n\n\tconst locale = input.locale ?? null\n\tif (locale !== null && !LOCALE_RE.test(locale))\n\t\terrors.push('locale must be a BCP-47 tag such as en or de-DE')\n\n\tconst theme = input.theme ?? {}\n\tif (theme.mode !== undefined && !THEME_MODES.has(theme.mode))\n\t\terrors.push('theme.mode must be light, dark or auto')\n\n\tif (\n\t\tinput.mock &&\n\t\tinput.mockData !== undefined &&\n\t\t(typeof input.mockData !== 'object' || input.mockData === null)\n\t) {\n\t\terrors.push('mockData must be an object')\n\t}\n\n\tif (errors.length > 0) {\n\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_CONFIG, `Invalid ExtenshiPay config: ${errors.join('; ')}`)\n\t}\n\n\treturn {\n\t\tpublishableKey: input.publishableKey,\n\t\tapiUrl,\n\t\tentitlementPublicKey,\n\t\tenvironment,\n\t\tdebug: input.debug === true,\n\t\tlogLevel,\n\t\tcacheTtlMs,\n\t\tlocale,\n\t\tmock: input.mock === true,\n\t\tmockData: input.mock ? (input.mockData ?? {}) : null,\n\t\ttheme,\n\t}\n}\n","import { logger } from '../utils/logger.js'\n\nexport type Listener<T> = (payload: T) => void\ntype AnyListener = (payload: never) => void\n\nexport class EventEmitter<Events extends object> {\n\tprivate readonly listeners = new Map<keyof Events, Set<AnyListener>>()\n\n\ton<K extends keyof Events>(event: K, listener: Listener<Events[K]>): () => void {\n\t\tlet set = this.listeners.get(event)\n\t\tif (!set) {\n\t\t\tset = new Set()\n\t\t\tthis.listeners.set(event, set)\n\t\t}\n\t\tset.add(listener as AnyListener)\n\t\treturn () => this.off(event, listener)\n\t}\n\n\tonce<K extends keyof Events>(event: K, listener: Listener<Events[K]>): () => void {\n\t\tconst off = this.on(event, (payload) => {\n\t\t\toff()\n\t\t\tlistener(payload)\n\t\t})\n\t\treturn off\n\t}\n\n\toff<K extends keyof Events>(event: K, listener: Listener<Events[K]>): void {\n\t\tthis.listeners.get(event)?.delete(listener as AnyListener)\n\t}\n\n\temit<K extends keyof Events>(event: K, payload: Events[K]): void {\n\t\tconst set = this.listeners.get(event)\n\t\tif (!set) return\n\t\tfor (const listener of [...set]) {\n\t\t\tconst fn = listener as Listener<Events[K]>\n\t\t\ttry {\n\t\t\t\tfn(payload)\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(`listener for \"${String(event)}\" threw`, error)\n\t\t\t}\n\t\t}\n\t}\n\n\tremoveAll(): void {\n\t\tthis.listeners.clear()\n\t}\n}\n","/**\n * `ExtenshiPayLite` — entitlement, feature gating and hosted checkout, without\n * the paywall UI. This is what the `lite` bundle exports; the full `ExtenshiPay`\n * extends it with `getOffer()` / `showPaywall()`.\n *\n * Data that leaves the extension: `publishableKey`, `endUserRef`, `sku`,\n * `locale` and checkout session IDs. Explicit recovery also sends its session ID,\n * challenge and claim secret (POST body). Email stays on the hosted page.\n */\n\nimport { MockTransport } from '../api/mock.js'\nimport { PayApi } from '../api/pay-api.js'\nimport { HttpTransport, type Transport } from '../api/transport.js'\nimport { CheckoutManager } from '../payment/checkout.js'\nimport { EntitlementManager, MAX_CLOCK_SKEW_MS } from '../payment/entitlement.js'\nimport { checkFeatures, hasFeature, isEntitled } from '../payment/features.js'\nimport { createRecoveryStorage, RecoveryManager } from '../payment/recovery.js'\nimport { verifyEntitlementSignature } from '../payment/signature.js'\nimport type { ExtenshiPayConfig, ResolvedConfig } from '../types/config.js'\nimport type { PayOfferResponse } from '../types/contract.js'\nimport { PAY_END_USER_REF_RE } from '../types/contract.js'\nimport type {\n\tCheckoutOptions,\n\tCheckoutResult,\n\tCustomerPortalOptions,\n\tEntitlement,\n\tGetEntitlementOptions,\n\tLicenseSummary,\n\tRequireFeatureOptions,\n\tRestoreOptions,\n\tRestoreResult,\n} from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { ExtenshiPayEvents } from '../types/events.js'\nimport { logger } from '../utils/logger.js'\nimport { VERSION } from '../version.js'\nimport { resolveConfig } from './config.js'\nimport { EventEmitter, type Listener } from './event-emitter.js'\nimport { END_USER_REF_STORAGE_KEY, getOrCreateEndUserRef } from './identity.js'\nimport { createStorage, type StorageAdapter } from './storage.js'\n\n/** Server-side offer cache is 5 min; mirror it in memory. */\nconst OFFER_TTL_MS = 5 * 60 * 1000\n\n/** Injection points for tests and unusual hosts. */\nexport interface ExtenshiPayDeps {\n\tstorage?: StorageAdapter\n\t/** Trusted extension-only storage; never share this adapter with content scripts. */\n\trecoveryStorage?: StorageAdapter\n\ttransport?: Transport\n\tfetch?: typeof fetch\n\topenUrl?: (url: string) => void | Promise<void>\n\tnow?: () => number\n}\n\nexport class ExtenshiPayLite {\n\tstatic readonly version = VERSION\n\n\tprotected readonly config: ResolvedConfig\n\tprotected readonly emitter = new EventEmitter<ExtenshiPayEvents>()\n\tprotected readonly storage: StorageAdapter\n\tprotected readonly api: PayApi\n\tprotected readonly entitlements: EntitlementManager\n\tprotected readonly checkout: CheckoutManager\n\tprotected readonly recovery: RecoveryManager\n\tprivate readonly now: () => number\n\tprivate endUserRef: string | null = null\n\tprivate endUserRefPromise: Promise<string> | null = null\n\tprivate offer: { value: PayOfferResponse; fetchedAt: number } | null = null\n\tprivate offerInflight: Promise<PayOfferResponse> | null = null\n\tprivate readyPromise: Promise<void> | null = null\n\tprivate destroyed = false\n\n\tconstructor(config: ExtenshiPayConfig, deps: ExtenshiPayDeps = {}) {\n\t\tthis.config = resolveConfig(config)\n\t\tlogger.configure({ logLevel: this.config.logLevel, debug: this.config.debug })\n\t\tthis.now = deps.now ?? (() => Date.now())\n\t\tthis.storage = deps.storage ?? createStorage()\n\n\t\tconst transport =\n\t\t\tdeps.transport ??\n\t\t\t(this.config.mock\n\t\t\t\t? new MockTransport(this.config.mockData ?? {})\n\t\t\t\t: new HttpTransport({ apiUrl: this.config.apiUrl, fetchImpl: deps.fetch }))\n\t\tthis.api = new PayApi(transport, this.config.publishableKey)\n\n\t\tthis.entitlements = new EntitlementManager({\n\t\t\tapi: this.api,\n\t\t\tstorage: this.storage,\n\t\t\tpublishableKey: this.config.publishableKey,\n\t\t\tcacheTtlMs: this.config.cacheTtlMs,\n\t\t\tsource: this.config.mock ? 'mock' : 'network',\n\t\t\tgetEndUserRef: () => this.getEndUserRef(),\n\t\t\tgetPublicKey: () => this.getPublicKey(),\n\t\t\tonChange: (entitlement) => this.emitter.emit('entitlement:changed', entitlement),\n\t\t\tonError: (error) => this.reportError(error),\n\t\t\tnow: this.now,\n\t\t})\n\n\t\tthis.checkout = new CheckoutManager({\n\t\t\tapi: this.api,\n\t\t\tstorage: this.storage,\n\t\t\tpublishableKey: this.config.publishableKey,\n\t\t\tlocale: this.config.locale,\n\t\t\tgetEndUserRef: () => this.getEndUserRef(),\n\t\t\tonComplete: (envelope) => this.entitlements.accept(envelope),\n\t\t\temit: (event, payload) => this.emitter.emit(event, payload),\n\t\t\t// Mock checkouts complete on their own; never open a tab to a mock URL.\n\t\t\topenUrl:\n\t\t\t\tdeps.openUrl ??\n\t\t\t\t(this.config.mock ? (url) => logger.info('mock checkout (no tab opened)', url) : undefined),\n\t\t\tnow: this.now,\n\t\t})\n\n\t\tthis.recovery = new RecoveryManager({\n\t\t\tapi: this.api,\n\t\t\tpublishableKey: this.config.publishableKey,\n\t\t\tstorage: deps.recoveryStorage ?? createRecoveryStorage(),\n\t\t\topenUrl: deps.openUrl,\n\t\t\tnow: this.now,\n\t\t\tonComplete: async (ref, envelope) => {\n\t\t\t\tif (\n\t\t\t\t\t!PAY_END_USER_REF_RE.test(ref) ||\n\t\t\t\t\tenvelope?.payload?.endUserRef !== ref ||\n\t\t\t\t\tenvelope.payload.publishableKey !== this.config.publishableKey ||\n\t\t\t\t\t!Number.isFinite(Date.parse(envelope.payload.issuedAt)) ||\n\t\t\t\t\tDate.parse(envelope.payload.issuedAt) > this.now() + MAX_CLOCK_SKEW_MS ||\n\t\t\t\t\t(await verifyEntitlementSignature(envelope, await this.getPublicKey())) !== 'valid'\n\t\t\t\t)\n\t\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\t\tERROR_CODES.INVALID_RESPONSE,\n\t\t\t\t\t\t'Recovery requires a verified entitlement for this installation',\n\t\t\t\t\t)\n\t\t\t\tthis.entitlements.stopAutoRefresh()\n\t\t\t\ttry {\n\t\t\t\t\tawait this.entitlements.settleRefresh()\n\t\t\t\t\tif (this.destroyed) throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Recovery was stopped')\n\t\t\t\t\tawait this.storage.set(END_USER_REF_STORAGE_KEY, ref)\n\t\t\t\t\tthis.endUserRef = ref\n\t\t\t\t\tthis.endUserRefPromise = null\n\t\t\t\t\tawait this.entitlements.clear()\n\t\t\t\t\treturn await this.entitlements.accept(envelope)\n\t\t\t\t} finally {\n\t\t\t\t\tif (!this.destroyed) this.entitlements.startAutoRefresh()\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\n\t\tif (config.onError) this.emitter.on('error', config.onError)\n\t\tif (config.onReady) this.emitter.once('ready', config.onReady)\n\t}\n\n\tget version(): string {\n\t\treturn VERSION\n\t}\n\n\t/**\n\t * Mints/loads `endUserRef`, loads the cached entitlement, re-verifies it and\n\t * refreshes it when stale. Resolves once `isPaid()` can answer; network\n\t * failures fall back to the cache and are reported through `error`.\n\t */\n\tinitialize(): Promise<void> {\n\t\tif (!this.readyPromise) this.readyPromise = this.doInitialize()\n\t\treturn this.readyPromise\n\t}\n\n\tprivate async doInitialize(): Promise<void> {\n\t\tconst endUserRef = await this.getEndUserRef()\n\t\tawait this.entitlements.load()\n\t\ttry {\n\t\t\tawait this.entitlements.reverify()\n\t\t} catch (error) {\n\t\t\tthis.reportError(error)\n\t\t}\n\t\tif (!this.entitlements.isFresh()) await this.entitlements.get({ force: true })\n\t\tthis.emitter.emit('ready', { endUserRef })\n\t\tvoid this.afterReady()\n\t}\n\n\tprivate async afterReady(): Promise<void> {\n\t\tif (this.destroyed) return\n\t\ttry {\n\t\t\tawait this.checkout.resumePending()\n\t\t\tif (this.destroyed) return\n\t\t\tawait this.recovery.resumePending()\n\t\t} catch (error) {\n\t\t\tthis.reportError(error)\n\t\t}\n\t\tif (!this.destroyed) this.entitlements.startAutoRefresh()\n\t}\n\n\t/** The anonymous, random id this install is known by. */\n\tgetEndUserRef(): Promise<string> {\n\t\tif (this.endUserRef) return Promise.resolve(this.endUserRef)\n\t\tif (!this.endUserRefPromise) {\n\t\t\tthis.endUserRefPromise = getOrCreateEndUserRef(this.storage).then((ref) => {\n\t\t\t\tthis.endUserRef = ref\n\t\t\t\treturn ref\n\t\t\t})\n\t\t}\n\t\treturn this.endUserRefPromise\n\t}\n\n\tgetCachedEntitlement(): Entitlement | null {\n\t\treturn this.entitlements.getCached()\n\t}\n\n\tasync getEntitlement(options: GetEntitlementOptions = {}): Promise<Entitlement> {\n\t\tawait this.initialize()\n\t\treturn this.entitlements.get(options)\n\t}\n\n\t/** True when any active/grace entitlement exists, or the given `sku` is active/grace. */\n\tasync isPaid(sku?: string): Promise<boolean> {\n\t\treturn isEntitled(await this.getEntitlement(), sku)\n\t}\n\n\tasync hasFeature(feature: string): Promise<boolean> {\n\t\treturn hasFeature(await this.getEntitlement(), feature)\n\t}\n\n\tasync checkFeatures(features: string[]): Promise<Record<string, boolean>> {\n\t\treturn checkFeatures(await this.getEntitlement(), features)\n\t}\n\n\t/** Resolves true when the feature is (or becomes) unlocked. */\n\tasync requireFeature(feature: string, options: RequireFeatureOptions = {}): Promise<boolean> {\n\t\tif (await this.hasFeature(feature)) {\n\t\t\toptions.onUnlock?.()\n\t\t\treturn true\n\t\t}\n\t\tconst unlocked = await this.onFeatureLocked(feature, options)\n\t\tif (unlocked) options.onUnlock?.()\n\t\telse options.onCancel?.()\n\t\treturn unlocked\n\t}\n\n\t/** Lite has no UI: a locked feature stays locked. The full SDK shows the paywall here. */\n\tprotected async onFeatureLocked(_feature: string, _options: RequireFeatureOptions): Promise<boolean> {\n\t\treturn false\n\t}\n\n\t/** Opens hosted checkout for `sku` in a new tab and resolves when the session settles. */\n\tasync openCheckout(sku: string, options: CheckoutOptions = {}): Promise<CheckoutResult> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\tif (this.recovery.isActive())\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Recovery is in progress')\n\t\t\treturn await this.checkout.open(sku, options)\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/** Opens email verification on the hosted page. No email is collected inside the extension. */\n\tasync restorePurchase(options: RestoreOptions = {}): Promise<RestoreResult> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\tif (this.checkout.isActive())\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Checkout is in progress')\n\t\t\treturn await this.recovery.open(options)\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/** Read-only license view. Entitlements retain cache/signature/offline semantics. */\n\tasync getLicenseSummary(options: GetEntitlementOptions = {}): Promise<LicenseSummary> {\n\t\tawait this.initialize()\n\t\tlet offer: PayOfferResponse | null = null\n\t\ttry {\n\t\t\toffer = await this.fetchOffer(options.force)\n\t\t} catch {\n\t\t\t/* Offline: do not invent seller details. */\n\t\t}\n\t\treturn {\n\t\t\tprojectName: offer?.projectName ?? null,\n\t\t\tseller: offer?.seller ?? null,\n\t\t\tentitlement: await this.getEntitlement(options),\n\t\t\trecoveryEnabled: offer?.recoveryEnabled === true,\n\t\t}\n\t}\n\n\t/** Opens the provider's self-service portal; resolves null when the provider has none. */\n\tasync openCustomerPortal(options: CustomerPortalOptions = {}): Promise<string | null> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\tconst endUserRef = await this.getEndUserRef()\n\t\t\tlet result = await this.api.getPortalUrl(endUserRef)\n\t\t\tif (this.destroyed) return null\n\t\t\tif (result.accounts?.length) {\n\t\t\t\tif (!options.selectAccount)\n\t\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t\t'Choose a billing profile using selectAccount',\n\t\t\t\t\t)\n\t\t\t\tconst customerId = await options.selectAccount(result.accounts)\n\t\t\t\tif (customerId === null || this.destroyed) return null\n\t\t\t\tif (!result.accounts.some((a) => a.id === customerId))\n\t\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Invalid billing profile')\n\t\t\t\t// Recovery may replace this installation while the selector is open.\n\t\t\t\tif (endUserRef !== (await this.getEndUserRef()))\n\t\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t\t'Installation changed; open the portal again',\n\t\t\t\t\t)\n\t\t\t\tresult = await this.api.getPortalUrl(endUserRef, customerId)\n\t\t\t}\n\t\t\tif (this.destroyed) return null\n\t\t\tconst { url } = result\n\t\t\tif (url) await (options.openUrl ?? (await import('../payment/checkout.js')).openInNewTab)(url)\n\t\t\treturn url\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\ton<K extends keyof ExtenshiPayEvents>(event: K, listener: Listener<ExtenshiPayEvents[K]>): () => void {\n\t\treturn this.emitter.on(event, listener)\n\t}\n\n\tonce<K extends keyof ExtenshiPayEvents>(event: K, listener: Listener<ExtenshiPayEvents[K]>): () => void {\n\t\treturn this.emitter.once(event, listener)\n\t}\n\n\toff<K extends keyof ExtenshiPayEvents>(event: K, listener: Listener<ExtenshiPayEvents[K]>): void {\n\t\tthis.emitter.off(event, listener)\n\t}\n\n\tonEntitlementChange(listener: Listener<Entitlement>): () => void {\n\t\treturn this.emitter.on('entitlement:changed', listener)\n\t}\n\n\tasync clearCache(): Promise<void> {\n\t\tthis.offer = null\n\t\tawait this.entitlements.clear()\n\t}\n\n\t/** Stops background refresh and drops listeners. */\n\tdestroy(): void {\n\t\tthis.destroyed = true\n\t\tthis.recovery.stop()\n\t\tthis.entitlements.stopAutoRefresh()\n\t\tthis.emitter.removeAll()\n\t}\n\n\t/** Offer + signing key. Public in the full SDK (`getOffer`), internal here. */\n\tprotected fetchOffer(force = false): Promise<PayOfferResponse> {\n\t\tif (!force && this.offer && this.now() - this.offer.fetchedAt < OFFER_TTL_MS) {\n\t\t\treturn Promise.resolve(this.offer.value)\n\t\t}\n\t\tif (!this.offerInflight) {\n\t\t\tthis.offerInflight = this.api\n\t\t\t\t.getOffer(this.config.locale)\n\t\t\t\t.then((value) => {\n\t\t\t\t\tthis.offer = { value, fetchedAt: this.now() }\n\t\t\t\t\treturn value\n\t\t\t\t})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tthis.offerInflight = null\n\t\t\t\t})\n\t\t}\n\t\treturn this.offerInflight\n\t}\n\n\tprivate async getPublicKey(): Promise<string | null> {\n\t\treturn this.config.entitlementPublicKey ?? (await this.fetchOffer()).entitlementPublicKey\n\t}\n\n\tprotected reportError(error: unknown): ExtenshiPayError {\n\t\tconst err = ExtenshiPayError.from(error)\n\t\tlogger.warn(`${err.code}: ${err.message}`)\n\t\tthis.emitter.emit('error', err)\n\t\treturn err\n\t}\n}\n","import type { PayPortalAccount } from '../types/contract.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\n\n/** Bundled UI only. Native dialog provides modal focus containment and Escape. */\nexport class BillingProfilePicker {\n\tprivate dismiss: (() => void) | null = null\n\n\thide(): void {\n\t\tthis.dismiss?.()\n\t}\n\n\tshow(accounts: PayPortalAccount[]): Promise<string | null> {\n\t\tthis.hide()\n\t\tif (typeof document === 'undefined')\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'Provide selectAccount outside an extension page',\n\t\t\t)\n\t\tconst host = document.createElement('div')\n\t\thost.className = 'extenshi-billing-profile-host'\n\t\tconst root = host.attachShadow({ mode: 'open' })\n\t\tconst style = document.createElement('style')\n\t\tstyle.textContent = `\n\t\t\tdialog{font:15px/1.5 system-ui,sans-serif;color:#172033;background:#fff;border:1px solid #dce1e8;border-radius:16px;padding:24px;width:min(440px,calc(100vw - 64px));max-height:80vh;box-shadow:0 20px 60px #0003}\n\t\t\tdialog::backdrop{background:#10182880}h2{margin:0 0 8px;font-size:22px}p{margin:0 0 16px;color:#526078}\n\t\t\tbutton{font:inherit;cursor:pointer;border:1px solid #dce1e8;border-radius:8px;background:#fff;color:inherit;padding:12px;text-align:left;width:100%;margin-top:10px}\n\t\t\tbutton:hover{background:#f3f6fa}button:focus-visible{outline:3px solid #0ea5e9;outline-offset:2px}strong,small{display:block}small{color:#526078;margin-top:4px}\n\t\t`\n\t\tconst dialog = document.createElement('dialog')\n\t\tdialog.setAttribute('aria-labelledby', 'billing-title')\n\t\tdialog.setAttribute('aria-describedby', 'billing-description')\n\t\tconst title = document.createElement('h2')\n\t\ttitle.id = 'billing-title'\n\t\ttitle.textContent = 'Choose a billing profile'\n\t\tconst description = document.createElement('p')\n\t\tdescription.id = 'billing-description'\n\t\tdescription.textContent =\n\t\t\t'Separate purchases can have separate billing profiles. Choose one to manage its subscriptions and payment details.'\n\t\tdialog.append(title, description)\n\t\troot.append(style, dialog)\n\t\tdocument.body.append(host)\n\t\tif (typeof dialog.showModal !== 'function') {\n\t\t\thost.remove()\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'This browser needs a custom selectAccount callback',\n\t\t\t)\n\t\t}\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst finish = (id: string | null) => {\n\t\t\t\tthis.dismiss = null\n\t\t\t\tdialog.close()\n\t\t\t\thost.remove()\n\t\t\t\tresolve(id)\n\t\t\t}\n\t\t\tthis.dismiss = () => finish(null)\n\t\t\tdialog.addEventListener('cancel', (event) => {\n\t\t\t\tevent.preventDefault()\n\t\t\t\tfinish(null)\n\t\t\t})\n\t\t\tfor (const account of accounts) {\n\t\t\t\tconst button = document.createElement('button')\n\t\t\t\tbutton.type = 'button'\n\t\t\t\tconst label = document.createElement('strong')\n\t\t\t\tlabel.textContent = account.label\n\t\t\t\tconst detail = document.createElement('small')\n\t\t\t\tconst recorded = new Date(account.createdAt)\n\t\t\t\tdetail.textContent = Number.isNaN(recorded.getTime())\n\t\t\t\t\t? ''\n\t\t\t\t\t: `First recorded ${recorded.toLocaleDateString()}`\n\t\t\t\tbutton.append(label, detail)\n\t\t\t\tfor (const subscription of account.subscriptions) {\n\t\t\t\t\tconst line = document.createElement('small')\n\t\t\t\t\tconst end = subscription.currentPeriodEnd ? new Date(subscription.currentPeriodEnd) : null\n\t\t\t\t\tconst cancellation = subscription.cancelAtPeriodEnd\n\t\t\t\t\t\t? ` · Renewal canceled${end && !Number.isNaN(end.getTime()) ? ` · Period ends ${end.toLocaleDateString()}` : ''}`\n\t\t\t\t\t\t: ''\n\t\t\t\t\tline.textContent = `${subscription.title} · ${subscription.status.replace(/_/g, ' ')}${cancellation}`\n\t\t\t\t\tbutton.append(line)\n\t\t\t\t}\n\t\t\t\tbutton.addEventListener('click', () => finish(account.id))\n\t\t\t\tdialog.append(button)\n\t\t\t}\n\t\t\tconst cancel = document.createElement('button')\n\t\t\tcancel.type = 'button'\n\t\t\tcancel.textContent = 'Cancel'\n\t\t\tcancel.addEventListener('click', () => finish(null))\n\t\t\tdialog.append(cancel)\n\t\t\ttry {\n\t\t\t\tdialog.showModal()\n\t\t\t} catch (error) {\n\t\t\t\tthis.dismiss = null\n\t\t\t\thost.remove()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t}\n}\n","import type { PaySellerPublic } from '../types/contract.js'\n\n/** Treat even server-provided links as untrusted; never render executable protocols. */\nexport function publicContactUrl(value: string): string | null {\n\ttry {\n\t\tconst url = new URL(value)\n\t\tif (url.protocol === 'https:' && !url.username && !url.password) return url.href\n\t} catch {\n\t\t/* A plain email address is allowed below. */\n\t}\n\tif (/^[^\\s@?&#:]+@[^\\s@?&#:]+\\.[^\\s@?&#:]+$/.test(value)) return `mailto:${encodeURIComponent(value)}`\n\treturn null\n}\n\nexport function sellerDetails(seller: PaySellerPublic | null): HTMLElement {\n\tconst section = document.createElement('section')\n\tsection.className = 'extenshi-seller-details'\n\tconst name = document.createElement('p')\n\tname.textContent = seller\n\t\t? `License provided by ${seller.displayName}`\n\t\t: 'License provider details are unavailable.'\n\tsection.append(name)\n\tconst link = (label: string, value: string | null) => {\n\t\tconst href = value ? publicContactUrl(value) : null\n\t\tif (!href) return\n\t\tconst a = document.createElement('a')\n\t\ta.textContent = label\n\t\ta.href = href\n\t\ta.target = '_blank'\n\t\ta.rel = 'noopener noreferrer'\n\t\ta.style.marginRight = '12px'\n\t\tsection.append(a)\n\t}\n\tif (seller) {\n\t\tlink('Extension support', seller.supportUrl)\n\t\tlink('License terms', seller.termsUrl)\n\t}\n\tconst role = document.createElement('p')\n\trole.textContent =\n\t\t'The author handles extension functionality and license commitments. Extenshi provides payment and license recovery tools.'\n\tsection.append(role)\n\treturn section\n}\n","/**\n * Every string the SDK adds on top of the templates. English only for now;\n * iteration 12 T9 / 13 replaces this dictionary per locale. Do not add\n * promotional claims here without marketing/legal review (see\n * .claude/modules/paywall-templates.md).\n */\n\nimport type { PaywallStrings } from '../types/paywall.js'\n\nexport const MOCK_PAYMENT_NOTICE =\n\t'Development preview: licenses and payments are simulated. No payment will be taken.'\n\nexport const DEFAULT_STRINGS: PaywallStrings = {\n\ttitle: 'Unlock premium features',\n\tdescription: 'Upgrade to get full access to this extension.',\n\tupgrade: 'Upgrade',\n\tcancel: 'Not now',\n\tdismiss: 'Dismiss',\n\tremindLater: 'Remind me later',\n\tcontinueFree: 'Continue with the free version',\n\tcheckoutUnavailable: 'Purchases are temporarily unavailable',\n\tperiodMonth: '/month',\n\tperiodYear: '/year',\n\tperiodOnce: 'one-time',\n\tfooter: 'Secure checkout opens in a new tab.',\n\trestorePurchase: 'Restore purchase',\n}\n","import type { LicenseSummary } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { sellerDetails } from './seller-details.js'\nimport { MOCK_PAYMENT_NOTICE } from './strings.js'\n\nexport class LicensePanel {\n\tprivate dismiss: (() => void) | null = null\n\thide(): void {\n\t\tthis.dismiss?.()\n\t}\n\tshow(\n\t\tsummary: LicenseSummary,\n\t\tactions: {\n\t\t\trestore: () => Promise<LicenseSummary>\n\t\t\tmanage: () => Promise<string | null>\n\t\t},\n\t): Promise<void> {\n\t\tthis.hide()\n\t\tif (typeof document === 'undefined')\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'Use getLicenseSummary outside an extension page',\n\t\t\t)\n\t\tconst host = document.createElement('div')\n\t\thost.className = 'extenshi-license-host'\n\t\tconst root = host.attachShadow({ mode: 'open' })\n\t\tconst style = document.createElement('style')\n\t\tstyle.textContent = `dialog{font:15px/1.5 system-ui,sans-serif;color:#172033;background:#fff;border:1px solid #dce1e8;border-radius:16px;padding:24px;width:min(460px,calc(100vw - 64px));max-height:80vh}dialog::backdrop{background:#10182880}h2{margin:0}h3{font-size:16px;margin:0}article{border-block-end:1px solid #ddd;padding:16px 0}p{margin:8px 0}button{font:inherit;padding:10px 14px;margin:12px 8px 0 0;border:1px solid #cbd5e1;border-radius:8px;cursor:pointer;background:#fff;color:inherit}button:disabled{opacity:.5;cursor:wait}button:focus-visible,a:focus-visible{outline:3px solid #0ea5e9}a{color:#0369a1}.extenshi-seller-details{font-size:13px;margin-top:20px}`\n\t\tconst dialog = document.createElement('dialog')\n\t\tdialog.setAttribute('aria-label', 'Your license')\n\t\tconst title = document.createElement('h2')\n\t\ttitle.textContent = 'Your license'\n\t\tconst content = document.createElement('div')\n\t\tconst feedback = document.createElement('p')\n\t\tfeedback.setAttribute('role', 'status')\n\t\tconst render = (state: LicenseSummary) => {\n\t\t\tcontent.replaceChildren()\n\t\t\tconst note = document.createElement('p')\n\t\t\tnote.textContent = state.projectName ?? 'Extension license'\n\t\t\tcontent.append(note)\n\t\t\tif (!state.entitlement.items.length) {\n\t\t\t\tconst empty = document.createElement('p')\n\t\t\t\tempty.textContent = 'No license found on this installation.'\n\t\t\t\tcontent.append(empty)\n\t\t\t}\n\t\t\tfor (const item of state.entitlement.items) {\n\t\t\t\tconst article = document.createElement('article')\n\t\t\t\tconst heading = document.createElement('h3')\n\t\t\t\theading.textContent = item.title ?? item.sku\n\t\t\t\tconst status = document.createElement('p')\n\t\t\t\tconst kind =\n\t\t\t\t\titem.kind === 'one_time'\n\t\t\t\t\t\t? item.expiresAt\n\t\t\t\t\t\t\t? 'One-time purchase'\n\t\t\t\t\t\t\t: 'Lifetime'\n\t\t\t\t\t\t: item.kind === 'subscription'\n\t\t\t\t\t\t\t? 'Subscription'\n\t\t\t\t\t\t\t: 'License'\n\t\t\t\tstatus.textContent = `${kind} · ${item.status}`\n\t\t\t\tarticle.append(heading, status)\n\t\t\t\tif (item.expiresAt) {\n\t\t\t\t\tconst date = new Date(item.expiresAt)\n\t\t\t\t\tif (!Number.isNaN(date.getTime())) {\n\t\t\t\t\t\tconst expiry = document.createElement('p')\n\t\t\t\t\t\texpiry.textContent = `${item.status === 'expired' ? 'Access ended' : item.status === 'active' || item.status === 'grace' ? 'Access until' : 'Recorded end date'} ${date.toLocaleString()}`\n\t\t\t\t\t\tarticle.append(expiry)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (const sub of item.subscriptions ?? []) {\n\t\t\t\t\tconst row = document.createElement('p')\n\t\t\t\t\trow.textContent = `Subscription: ${sub.status.replace(/_/g, ' ')}${sub.cancelAtPeriodEnd ? ' · Renewal canceled' : ''}`\n\t\t\t\t\tarticle.append(row)\n\t\t\t\t}\n\t\t\t\tcontent.append(article)\n\t\t\t}\n\t\t\tconst freshness = document.createElement('p')\n\t\t\tfreshness.textContent = state.entitlement.requiresOnlineCheck\n\t\t\t\t? 'Connect to the internet to verify your license. Paid features are paused after 48 hours without a successful check. Your purchase has not expired.'\n\t\t\t\t: state.entitlement.source === 'mock'\n\t\t\t\t\t? MOCK_PAYMENT_NOTICE\n\t\t\t\t\t: state.entitlement.source === 'cache'\n\t\t\t\t\t\t? 'Showing saved license information.'\n\t\t\t\t\t\t: 'Subscription information reflects the latest processed payment update.'\n\t\t\tcontent.append(freshness, sellerDetails(state.seller))\n\t\t}\n\t\trender(summary)\n\t\tdialog.append(title, content, feedback)\n\t\troot.append(style, dialog)\n\t\tdocument.body.append(host)\n\t\tif (typeof dialog.showModal !== 'function') {\n\t\t\thost.remove()\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'This browser needs a custom license screen using getLicenseSummary',\n\t\t\t)\n\t\t}\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tlet closed = false\n\t\t\tconst close = () => {\n\t\t\t\tclosed = true\n\t\t\t\tthis.dismiss = null\n\t\t\t\tdialog.close()\n\t\t\t\thost.remove()\n\t\t\t\tresolve()\n\t\t\t}\n\t\t\tthis.dismiss = close\n\t\t\tdialog.addEventListener('cancel', (event) => {\n\t\t\t\tevent.preventDefault()\n\t\t\t\tclose()\n\t\t\t})\n\t\t\tconst buttons: HTMLButtonElement[] = []\n\t\t\tconst action = (label: string, run: () => Promise<void>) => {\n\t\t\t\tconst button = document.createElement('button')\n\t\t\t\tbutton.type = 'button'\n\t\t\t\tbutton.textContent = label\n\t\t\t\tbutton.addEventListener('click', async () => {\n\t\t\t\t\tbuttons.forEach((b) => {\n\t\t\t\t\t\tb.disabled = true\n\t\t\t\t\t})\n\t\t\t\t\tfeedback.textContent = ''\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait run()\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tif (!closed)\n\t\t\t\t\t\t\tfeedback.textContent =\n\t\t\t\t\t\t\t\t'Unable to complete the request. Please try again or contact extension support.'\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (!closed)\n\t\t\t\t\t\t\tbuttons.forEach((b) => {\n\t\t\t\t\t\t\t\tb.disabled = false\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tbuttons.push(button)\n\t\t\t\tdialog.append(button)\n\t\t\t}\n\t\t\tif (summary.recoveryEnabled)\n\t\t\t\taction('Restore purchase', async () => {\n\t\t\t\t\tconst updated = await actions.restore()\n\t\t\t\t\tif (!closed) render(updated)\n\t\t\t\t})\n\t\t\tif (summary.entitlement.source !== 'mock')\n\t\t\t\taction('Manage billing', async () => {\n\t\t\t\t\tconst url = await actions.manage()\n\t\t\t\t\tif (!url && !closed)\n\t\t\t\t\t\tfeedback.textContent = 'No billing portal opened. You can retry or contact extension support.'\n\t\t\t\t})\n\t\t\tconst done = document.createElement('button')\n\t\t\tdone.type = 'button'\n\t\t\tdone.textContent = 'Close'\n\t\t\tdone.addEventListener('click', close)\n\t\t\tdialog.append(done)\n\t\t\ttry {\n\t\t\t\tdialog.showModal()\n\t\t\t} catch (error) {\n\t\t\t\tthis.dismiss = null\n\t\t\t\thost.remove()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t}\n}\n","import type { PayOfferDto } from '../types/contract.js'\nimport type { PaywallStrings } from '../types/paywall.js'\n\nexport interface FormattedPrice {\n\t/** Currency symbol/code as the locale renders it (`$`, `€`, `US$`). */\n\tcurrency: string\n\t/** Numeric part (`9.99`, `9,99`). */\n\tamount: string\n\t/** The whole formatted price (`$9.99`). */\n\tfull: string\n}\n\nexport function formatPrice(amountMinor: number, currency: string, locale?: string | null): FormattedPrice {\n\tconst value = amountMinor / 100\n\tconst code = currency.toUpperCase()\n\ttry {\n\t\tconst formatter = new Intl.NumberFormat(locale ?? undefined, { style: 'currency', currency: code })\n\t\tconst parts = formatter.formatToParts(value)\n\t\treturn {\n\t\t\tcurrency: parts\n\t\t\t\t.filter((part) => part.type === 'currency')\n\t\t\t\t.map((part) => part.value)\n\t\t\t\t.join(''),\n\t\t\tamount: parts\n\t\t\t\t.filter((part) => part.type !== 'currency' && part.type !== 'literal')\n\t\t\t\t.map((part) => part.value)\n\t\t\t\t.join(''),\n\t\t\tfull: formatter.format(value),\n\t\t}\n\t} catch {\n\t\tconst amount = value.toFixed(2)\n\t\treturn { currency: code, amount, full: `${amount} ${code}` }\n\t}\n}\n\nexport function periodLabel(offer: PayOfferDto, strings: PaywallStrings): string {\n\tif (offer.kind !== 'subscription') return strings.periodOnce\n\treturn offer.interval === 'year' ? strings.periodYear : strings.periodMonth\n}\n","export const html = \"<div class=\\\"ep-fullscreen-paywall\\\" id=\\\"fullscreenPaywall\\\" role=\\\"dialog\\\" aria-labelledby=\\\"fullscreen-title\\\"><div class=\\\"ep-fullscreen-background\\\"><div class=\\\"ep-background-pattern\\\"></div></div><div class=\\\"ep-fullscreen-header\\\"><div class=\\\"ep-fullscreen-logo\\\"><svg width=\\\"40\\\" height=\\\"40\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 2L2 7l10 5 10-5-10-5z\\\"></path><path d=\\\"M2 17l10 5 10-5\\\"></path><path d=\\\"M2 12l10 5 10-5\\\"></path></svg><span class=\\\"ep-fullscreen-logo-text\\\">{{brandName}}</span></div><button class=\\\"ep-fullscreen-close\\\" aria-label=\\\"Close paywall\\\" data-ep-action=\\\"closeFullscreen\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg></button></div><div class=\\\"ep-fullscreen-content\\\"><div class=\\\"ep-fullscreen-container\\\"><div class=\\\"ep-fullscreen-hero\\\"><div class=\\\"ep-hero-icon\\\"><svg width=\\\"80\\\" height=\\\"80\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 2L2 7l10 5 10-5-10-5z\\\"></path><path d=\\\"M2 17l10 5 10-5\\\"></path><path d=\\\"M2 12l10 5 10-5\\\"></path></svg></div><h1 class=\\\"ep-heading-1\\\" id=\\\"fullscreen-title\\\">{{title}}</h1><p class=\\\"ep-hero-description\\\">{{description}}</p></div><div class=\\\"ep-fullscreen-features\\\"><div class=\\\"ep-features-grid\\\"><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 12h-4l-3 9L9 3l-3 9H2\\\"></path></svg></div><h3 class=\\\"ep-feature-card-title\\\">{{feature1Title}}</h3><p class=\\\"ep-feature-card-description\\\">{{feature1Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z\\\"></path></svg></div><h3 class=\\\"ep-feature-card-title\\\">{{feature2Title}}</h3><p class=\\\"ep-feature-card-description\\\">{{feature2Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M13 2L3 14h9l-1 8 10-12h-9l1-8z\\\"></path></svg></div><h3 class=\\\"ep-feature-card-title\\\">{{feature3Title}}</h3><p class=\\\"ep-feature-card-description\\\">{{feature3Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z\\\"></path><polyline points=\\\"7.5,4.21 12,6.81 16.5,4.21\\\"></polyline><polyline points=\\\"7.5,19.79 7.5,14.6 3,12\\\"></polyline><polyline points=\\\"21,12 16.5,14.6 16.5,19.79\\\"></polyline></svg></div><h3 class=\\\"ep-feature-card-title\\\">{{feature4Title}}</h3><p class=\\\"ep-feature-card-description\\\">{{feature4Description}}</p></div></div></div><div class=\\\"ep-fullscreen-pricing\\\"><div class=\\\"ep-pricing-header\\\"><h2 class=\\\"ep-heading-2\\\">Choose Your Plan</h2><p class=\\\"ep-pricing-subtitle\\\">{{pricingSubtitle}}</p></div><div class=\\\"ep-pricing-plans\\\"><div class=\\\"ep-pricing-plan\\\"><div class=\\\"ep-pricing-plan-header\\\"><h3 class=\\\"ep-pricing-plan-title\\\">Free</h3><div class=\\\"ep-pricing-plan-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">0</span></div><p class=\\\"ep-pricing-plan-description\\\">{{freeDescription}}</p></div><ul class=\\\"ep-pricing-plan-features\\\"><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{freeFeature1}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{freeFeature2}} </li><li class=\\\"ep-pricing-feature ep-pricing-feature-disabled\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg> {{freeFeature3}} </li></ul><button class=\\\"ep-btn ep-btn-secondary ep-btn-full\\\" data-ep-action=\\\"continueFree\\\"> {{continueButtonText}} </button></div><div class=\\\"ep-pricing-plan ep-pricing-plan-premium\\\"><div class=\\\"ep-pricing-plan-badge\\\">{{premiumBadge}}</div><div class=\\\"ep-pricing-plan-header\\\"><h3 class=\\\"ep-pricing-plan-title\\\">Premium</h3><div class=\\\"ep-pricing-plan-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">{{price}}</span><span class=\\\"ep-pricing-period\\\">{{period}}</span></div><p class=\\\"ep-pricing-plan-description\\\">{{premiumDescription}}</p></div><ul class=\\\"ep-pricing-plan-features\\\"><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature1}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature2}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature3}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature4}} </li></ul><button class=\\\"ep-btn ep-btn-primary ep-btn-lg ep-btn-full\\\" data-ep-action=\\\"upgradeNow\\\"> {{upgradeButtonText}} </button></div></div></div><div class=\\\"ep-fullscreen-trial\\\"><div class=\\\"ep-trial-card\\\"><div class=\\\"ep-trial-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 11.08V12a10 10 0 1 1-5.93-9.14\\\"></path><polyline points=\\\"22,4 12,14.01 9,11.01\\\"></polyline></svg></div><h3 class=\\\"ep-trial-title\\\">{{trialTitle}}</h3><p class=\\\"ep-trial-description\\\">{{trialDescription}}</p><button class=\\\"ep-btn ep-btn-secondary ep-btn-lg\\\" data-ep-action=\\\"startTrial\\\"> {{trialButtonText}} </button></div></div></div></div></div>\";\nexport const css = \".ep-fullscreen-paywall{position:fixed;top:0;left:0;right:0;bottom:0;background-color:var(--ep-bg-primary);z-index:var(--ep-z-modal);display:flex;flex-direction:column;animation:ep-fullscreen-in var(--ep-transition-slow);overflow-y:auto}.ep-fullscreen-paywall.ep-fullscreen-closing{animation:ep-fullscreen-out var(--ep-transition-slow)}.ep-fullscreen-background{position:absolute;top:0;left:0;right:0;bottom:0;overflow:hidden;z-index:-1}.ep-background-pattern{position:absolute;top:-50%;left:-50%;width:200%;height:200%;background:linear-gradient(45deg,transparent 30%,rgba(14,165,233,0.03) 50%,transparent 70%);background-size:60px 60px;animation:ep-background-pattern var(--ep-transition-slow) infinite linear}:host([data-theme=\\\"dark\\\"]) .ep-background-pattern{background:linear-gradient(45deg,transparent 30%,rgba(14,165,233,0.05) 50%,transparent 70%)}.ep-fullscreen-header{display:flex;justify-content:space-between;align-items:center;padding:var(--ep-space-6) var(--ep-space-8);border-bottom:1px solid var(--ep-border-primary);background-color:var(--ep-bg-secondary);backdrop-filter:blur(10px);z-index:1}.ep-fullscreen-logo{display:flex;align-items:center;gap:var(--ep-space-3);color:var(--ep-primary-600)}.ep-fullscreen-logo-text{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-fullscreen-close{background:none;border:none;color:var(--ep-text-tertiary);cursor:pointer;padding:var(--ep-space-2);border-radius:var(--ep-radius-md);transition:all var(--ep-transition-fast)}.ep-fullscreen-close:hover{color:var(--ep-text-primary);background-color:var(--ep-bg-tertiary)}.ep-fullscreen-content{flex:1;padding:var(--ep-space-8);display:flex;align-items:center;justify-content:center}.ep-fullscreen-container{max-width:1200px;width:100%;margin:0 auto}.ep-fullscreen-hero{text-align:center;margin-bottom:var(--ep-space-16)}.ep-hero-icon{width:120px;height:120px;margin:0 auto var(--ep-space-6);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-2xl);display:flex;align-items:center;justify-content:center;color:white;box-shadow:var(--ep-shadow-lg);animation:ep-hero-icon-in var(--ep-transition-slow) 0.2s both}.ep-fullscreen-hero .ep-heading-1{font-size:var(--ep-font-size-5xl);margin-bottom:var(--ep-space-6);background:linear-gradient(135deg,var(--ep-primary-600),var(--ep-primary-700));-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;animation:ep-hero-title-in var(--ep-transition-slow) 0.3s both}.ep-hero-description{font-size:var(--ep-font-size-xl);color:var(--ep-text-secondary);max-width:600px;margin:0 auto;line-height:var(--ep-line-height-relaxed);animation:ep-hero-description-in var(--ep-transition-slow) 0.4s both}.ep-fullscreen-features{margin-bottom:var(--ep-space-16)}.ep-features-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:var(--ep-space-6)}.ep-feature-card{background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-xl);padding:var(--ep-space-8);text-align:center;box-shadow:var(--ep-shadow-sm);transition:all var(--ep-transition-normal);opacity:0;transform:translateY(20px);animation:ep-feature-card-in var(--ep-transition-slow) both}.ep-feature-card:hover{transform:translateY(-4px);box-shadow:var(--ep-shadow-lg)}.ep-feature-card-icon{width:80px;height:80px;margin:0 auto var(--ep-space-4);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-xl);display:flex;align-items:center;justify-content:center;color:white}.ep-feature-card-title{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-3)}.ep-feature-card-description{color:var(--ep-text-secondary);line-height:var(--ep-line-height-relaxed);margin:0}.ep-fullscreen-pricing{margin-bottom:var(--ep-space-16)}.ep-pricing-header{text-align:center;margin-bottom:var(--ep-space-10)}.ep-pricing-header .ep-heading-2{font-size:var(--ep-font-size-4xl);margin-bottom:var(--ep-space-4)}.ep-pricing-subtitle{font-size:var(--ep-font-size-lg);color:var(--ep-text-secondary);margin:0}.ep-pricing-plans{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:var(--ep-space-8);max-width:800px;margin:0 auto}.ep-pricing-plan{position:relative;background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-xl);padding:var(--ep-space-8);box-shadow:var(--ep-shadow-md);transition:all var(--ep-transition-normal);opacity:0;transform:translateY(20px);animation:ep-pricing-plan-in var(--ep-transition-slow) both}.ep-pricing-plan:hover{transform:translateY(-4px);box-shadow:var(--ep-shadow-lg)}.ep-pricing-plan-premium{border-color:var(--ep-primary-300);box-shadow:var(--ep-shadow-xl);transform:scale(1.05)}.ep-pricing-plan-premium:hover{transform:scale(1.05) translateY(-4px)}.ep-pricing-plan-badge{position:absolute;top:-16px;left:50%;transform:translateX(-50%);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));color:white;padding:var(--ep-space-2) var(--ep-space-6);border-radius:var(--ep-radius-full);font-size:var(--ep-font-size-sm);font-weight:var(--ep-font-weight-semibold);white-space:nowrap}.ep-pricing-plan-header{text-align:center;margin-bottom:var(--ep-space-8)}.ep-pricing-plan-title{font-size:var(--ep-font-size-2xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-4)}.ep-pricing-plan-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-2);margin-bottom:var(--ep-space-3)}.ep-pricing-currency{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-pricing-amount{font-size:var(--ep-font-size-5xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-pricing-period{font-size:var(--ep-font-size-xl);color:var(--ep-text-secondary)}.ep-pricing-plan-description{color:var(--ep-text-secondary);margin:0}.ep-pricing-plan-features{list-style:none;padding:0;margin:0 0 var(--ep-space-8) 0}.ep-pricing-feature{display:flex;align-items:center;gap:var(--ep-space-3);padding:var(--ep-space-3) 0;color:var(--ep-text-primary);font-size:var(--ep-font-size-base)}.ep-pricing-feature-disabled{color:var(--ep-text-tertiary)}.ep-pricing-feature-icon{color:var(--ep-success-500);flex-shrink:0}.ep-pricing-feature-disabled .ep-pricing-feature-icon{color:var(--ep-text-tertiary)}.ep-fullscreen-trial{text-align:center}.ep-trial-card{background:linear-gradient(135deg,var(--ep-success-50),var(--ep-success-100));border:1px solid var(--ep-success-200);border-radius:var(--ep-radius-xl);padding:var(--ep-space-8);max-width:600px;margin:0 auto;box-shadow:var(--ep-shadow-md)}:host([data-theme=\\\"dark\\\"]) .ep-trial-card{background:linear-gradient(135deg,rgba(16,185,129,0.1),rgba(16,185,129,0.15));border-color:rgba(16,185,129,0.3)}.ep-trial-icon{width:80px;height:80px;margin:0 auto var(--ep-space-4);background:linear-gradient(135deg,var(--ep-success-500),var(--ep-success-600));border-radius:var(--ep-radius-xl);display:flex;align-items:center;justify-content:center;color:white}.ep-trial-title{font-size:var(--ep-font-size-2xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-success-700);margin-bottom:var(--ep-space-3)}:host([data-theme=\\\"dark\\\"]) .ep-trial-title{color:var(--ep-success-400)}.ep-trial-description{color:var(--ep-success-600);font-size:var(--ep-font-size-lg);line-height:var(--ep-line-height-relaxed);margin-bottom:var(--ep-space-6)}:host([data-theme=\\\"dark\\\"]) .ep-trial-description{color:var(--ep-success-300)}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);right:var(--ep-space-4);z-index:var(--ep-z-tooltip)}@keyframes ep-fullscreen-in{from{opacity:0;transform:scale(0.98)}to{opacity:1;transform:scale(1)}}@keyframes ep-fullscreen-out{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(0.98)}}@keyframes ep-background-pattern{from{transform:translateX(0) translateY(0)}to{transform:translateX(-60px) translateY(-60px)}}@keyframes ep-hero-icon-in{from{opacity:0;transform:scale(0.8)}to{opacity:1;transform:scale(1)}}@keyframes ep-hero-title-in{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes ep-hero-description-in{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes ep-feature-card-in{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes ep-pricing-plan-in{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@media (max-width:1024px){.ep-fullscreen-content{padding:var(--ep-space-6)}.ep-fullscreen-hero{margin-bottom:var(--ep-space-12)}.ep-fullscreen-features{margin-bottom:var(--ep-space-12)}.ep-fullscreen-pricing{margin-bottom:var(--ep-space-12)}.ep-features-grid{grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:var(--ep-space-4)}.ep-pricing-plans{gap:var(--ep-space-6)}}@media (max-width:768px){.ep-fullscreen-header{padding:var(--ep-space-4) var(--ep-space-6)}.ep-fullscreen-content{padding:var(--ep-space-4)}.ep-fullscreen-hero .ep-heading-1{font-size:var(--ep-font-size-3xl)}.ep-hero-description{font-size:var(--ep-font-size-lg)}.ep-hero-icon{width:80px;height:80px}.ep-features-grid{grid-template-columns:1fr}.ep-pricing-plans{grid-template-columns:1fr}.ep-pricing-plan-premium{transform:none}.ep-pricing-plan-premium:hover{transform:translateY(-4px)}.ep-feature-card{padding:var(--ep-space-6)}.ep-feature-card-icon{width:60px;height:60px}.ep-pricing-plan{padding:var(--ep-space-6)}.ep-pricing-amount{font-size:var(--ep-font-size-4xl)}}@media (max-width:480px){.ep-fullscreen-header{padding:var(--ep-space-3) var(--ep-space-4)}.ep-fullscreen-logo-text{font-size:var(--ep-font-size-lg)}.ep-fullscreen-content{padding:var(--ep-space-3)}.ep-fullscreen-hero .ep-heading-1{font-size:var(--ep-font-size-2xl)}.ep-hero-description{font-size:var(--ep-font-size-base)}.ep-hero-icon{width:60px;height:60px}.ep-pricing-header .ep-heading-2{font-size:var(--ep-font-size-2xl)}.ep-pricing-amount{font-size:var(--ep-font-size-3xl)}.ep-feature-card-icon{width:48px;height:48px}.ep-trial-icon{width:60px;height:60px}}@media (prefers-contrast:high){.ep-fullscreen-paywall{background-color:var(--ep-bg-primary)}.ep-feature-card{border:2px solid var(--ep-border-secondary)}.ep-pricing-plan{border:2px solid var(--ep-border-secondary)}.ep-pricing-plan-premium{border:2px solid var(--ep-primary-500)}.ep-trial-card{border:2px solid var(--ep-success-500)}}@media (prefers-reduced-motion:reduce){.ep-fullscreen-paywall{animation:none}.ep-background-pattern{animation:none}.ep-hero-icon{animation:none}.ep-fullscreen-hero .ep-heading-1{animation:none}.ep-hero-description{animation:none}.ep-feature-card{animation:none;opacity:1;transform:none}.ep-pricing-plan{animation:none;opacity:1;transform:none}.ep-pricing-plan-premium{transform:none}.ep-feature-card:hover{transform:none}.ep-pricing-plan:hover{transform:none}}\";\nexport default { html, css };","/**\n * The five templates from `@extenshi/paywall-templates`, inlined at build\n * time by build/paywall-templates-plugin.mjs. No runtime fetch, no\n * `web_accessible_resources`, no remote code.\n */\n\nimport sharedCss from 'virtual:extenshi-paywall-shared-css'\nimport * as fullscreen from '@extenshi/paywall-templates/fullscreen'\nimport * as inline from '@extenshi/paywall-templates/inline'\nimport * as minimal from '@extenshi/paywall-templates/minimal'\nimport * as modal from '@extenshi/paywall-templates/modal'\nimport * as sidebar from '@extenshi/paywall-templates/sidebar'\nimport type { PaywallMode } from '../types/paywall.js'\n\nexport interface PaywallTemplate {\n\thtml: string\n\tcss: string\n}\n\nexport const PAYWALL_SHARED_CSS: string = sharedCss\n\nexport const PAYWALL_TEMPLATES: Record<PaywallMode, PaywallTemplate> = {\n\tmodal: { html: modal.html, css: modal.css },\n\tinline: { html: inline.html, css: inline.css },\n\tsidebar: { html: sidebar.html, css: sidebar.css },\n\tfullscreen: { html: fullscreen.html, css: fullscreen.css },\n\tminimal: { html: minimal.html, css: minimal.css },\n}\n\nexport const PAYWALL_MODES = Object.keys(PAYWALL_TEMPLATES) as PaywallMode[]\n","export const html = \"<div class=\\\"ep-modal-backdrop\\\" id=\\\"paywallModal\\\" role=\\\"dialog\\\" aria-labelledby=\\\"paywall-title\\\" aria-describedby=\\\"paywall-description\\\"><div class=\\\"ep-modal-container\\\"><button class=\\\"ep-modal-close\\\" aria-label=\\\"Close paywall\\\" data-ep-action=\\\"closePaywall\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg></button><div class=\\\"ep-modal-content\\\"><div class=\\\"ep-modal-header\\\"><div class=\\\"ep-modal-icon\\\"><svg width=\\\"48\\\" height=\\\"48\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><rect x=\\\"3\\\" y=\\\"11\\\" width=\\\"18\\\" height=\\\"11\\\" rx=\\\"2\\\" ry=\\\"2\\\"></rect><path d=\\\"m7 11V7a5 5 0 0 1 10 0v4\\\"></path></svg></div><h2 class=\\\"ep-heading-2\\\" id=\\\"paywall-title\\\">{{title}}</h2><p class=\\\"ep-text-body\\\" id=\\\"paywall-description\\\">{{description}}</p></div><div class=\\\"ep-modal-features\\\"><h3 class=\\\"ep-heading-3\\\">Premium Features</h3><ul class=\\\"ep-feature-list\\\"><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature1}}</span></li><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature2}}</span></li><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature3}}</span></li></ul></div><div class=\\\"ep-modal-pricing\\\"><div class=\\\"ep-pricing-card\\\"><div class=\\\"ep-pricing-header\\\"><div class=\\\"ep-pricing-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">{{price}}</span><span class=\\\"ep-pricing-period\\\">{{period}}</span></div><p class=\\\"ep-pricing-description\\\">{{pricingDescription}}</p></div><div class=\\\"ep-trial-info\\\"><p class=\\\"ep-text-sm\\\">{{trialInfo}}</p></div></div></div><div class=\\\"ep-modal-actions\\\"><button class=\\\"ep-btn ep-btn-primary ep-btn-lg ep-btn-full\\\" data-ep-action=\\\"upgradeNow\\\"> {{upgradeButtonText}} </button><button class=\\\"ep-btn ep-btn-ghost ep-btn-sm\\\" data-ep-action=\\\"closePaywall\\\"> {{cancelButtonText}} </button></div><div class=\\\"ep-modal-footer\\\"><p class=\\\"ep-text-sm\\\">{{footerText}}</p></div></div></div></div>\";\nexport const css = \".ep-modal-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,0.75);backdrop-filter:blur(4px);z-index:var(--ep-z-modal);display:flex;align-items:center;justify-content:center;padding:var(--ep-space-4);animation:ep-modal-backdrop-in var(--ep-transition-normal)}.ep-modal-backdrop.ep-modal-closing{animation:ep-modal-backdrop-out var(--ep-transition-normal)}.ep-modal-container{position:relative;background-color:var(--ep-bg-secondary);border-radius:var(--ep-radius-xl);box-shadow:var(--ep-shadow-xl);max-width:480px;width:100%;max-height:90vh;overflow-y:auto;animation:ep-modal-container-in var(--ep-transition-normal)}.ep-modal-backdrop.ep-modal-closing .ep-modal-container{animation:ep-modal-container-out var(--ep-transition-normal)}.ep-modal-close{position:absolute;top:var(--ep-space-4);right:var(--ep-space-4);background:none;border:none;color:var(--ep-text-tertiary);cursor:pointer;padding:var(--ep-space-2);border-radius:var(--ep-radius-md);transition:all var(--ep-transition-fast);z-index:1}.ep-modal-close:hover{color:var(--ep-text-primary);background-color:var(--ep-bg-tertiary)}.ep-modal-close:focus{outline:2px solid var(--ep-primary-500);outline-offset:2px}.ep-modal-content{padding:var(--ep-space-8);padding-top:var(--ep-space-12)}.ep-modal-header{text-align:center;margin-bottom:var(--ep-space-8)}.ep-modal-icon{width:80px;height:80px;margin:0 auto var(--ep-space-4);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-2xl);display:flex;align-items:center;justify-content:center;color:white}.ep-modal-header .ep-heading-2{margin-bottom:var(--ep-space-3)}.ep-modal-header .ep-text-body{margin-bottom:0;font-size:var(--ep-font-size-lg)}.ep-modal-features{margin-bottom:var(--ep-space-8)}.ep-modal-features .ep-heading-3{margin-bottom:var(--ep-space-4);text-align:center}.ep-feature-list{list-style:none;padding:0;margin:0}.ep-feature-item{display:flex;align-items:center;gap:var(--ep-space-3);padding:var(--ep-space-3) 0;border-bottom:1px solid var(--ep-border-primary)}.ep-feature-item:last-child{border-bottom:none}.ep-feature-icon{color:var(--ep-success-500);flex-shrink:0}.ep-feature-item span{color:var(--ep-text-primary);font-weight:var(--ep-font-weight-medium)}.ep-modal-pricing{margin-bottom:var(--ep-space-8)}.ep-pricing-card{background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100));border:1px solid var(--ep-primary-200);border-radius:var(--ep-radius-lg);padding:var(--ep-space-6);text-align:center}:host([data-theme=\\\"dark\\\"]) .ep-pricing-card{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800));border-color:var(--ep-primary-700)}.ep-pricing-header{margin-bottom:var(--ep-space-4)}.ep-pricing-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-1);margin-bottom:var(--ep-space-2)}.ep-pricing-currency{font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-pricing-amount{font-size:var(--ep-font-size-4xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-pricing-period{font-size:var(--ep-font-size-lg);color:var(--ep-text-secondary)}.ep-pricing-description{color:var(--ep-text-secondary);margin:0}.ep-trial-info{background-color:var(--ep-success-50);border:1px solid var(--ep-success-200);border-radius:var(--ep-radius-md);padding:var(--ep-space-3);margin-top:var(--ep-space-4)}:host([data-theme=\\\"dark\\\"]) .ep-trial-info{background-color:rgba(16,185,129,0.1);border-color:rgba(16,185,129,0.3)}.ep-trial-info .ep-text-sm{color:var(--ep-success-700);margin:0;font-weight:var(--ep-font-weight-medium)}:host([data-theme=\\\"dark\\\"]) .ep-trial-info .ep-text-sm{color:var(--ep-success-400)}.ep-modal-actions{display:flex;flex-direction:column;gap:var(--ep-space-3);margin-bottom:var(--ep-space-6)}.ep-modal-footer{text-align:center;padding-top:var(--ep-space-6);border-top:1px solid var(--ep-border-primary)}.ep-modal-footer .ep-text-sm{margin:0}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);left:var(--ep-space-4);z-index:var(--ep-z-tooltip)}@keyframes ep-modal-backdrop-in{from{opacity:0}to{opacity:1}}@keyframes ep-modal-backdrop-out{from{opacity:1}to{opacity:0}}@keyframes ep-modal-container-in{from{opacity:0;transform:scale(0.95) translateY(-10px)}to{opacity:1;transform:scale(1) translateY(0)}}@keyframes ep-modal-container-out{from{opacity:1;transform:scale(1) translateY(0)}to{opacity:0;transform:scale(0.95) translateY(-10px)}}@media (max-width:640px){.ep-modal-backdrop{padding:var(--ep-space-2)}.ep-modal-container{max-width:100%;border-radius:var(--ep-radius-lg)}.ep-modal-content{padding:var(--ep-space-6);padding-top:var(--ep-space-10)}.ep-modal-icon{width:60px;height:60px}.ep-modal-header .ep-heading-2{font-size:var(--ep-font-size-xl)}.ep-pricing-amount{font-size:var(--ep-font-size-3xl)}}@media (max-width:480px){.ep-modal-content{padding:var(--ep-space-4);padding-top:var(--ep-space-8)}.ep-modal-close{top:var(--ep-space-3);right:var(--ep-space-3)}}@media (prefers-contrast:high){.ep-modal-backdrop{background-color:rgba(0,0,0,0.9);backdrop-filter:none}.ep-modal-container{border:2px solid var(--ep-border-secondary)}.ep-pricing-card{background:var(--ep-bg-secondary);border:2px solid var(--ep-primary-500)}}@media (prefers-reduced-motion:reduce){.ep-modal-backdrop{animation:none}.ep-modal-container{animation:none}.ep-modal-backdrop.ep-modal-closing{animation:none}.ep-modal-backdrop.ep-modal-closing .ep-modal-container{animation:none}}\";\nexport default { html, css };","export const html = \"<div class=\\\"ep-inline-paywall\\\" id=\\\"inlinePaywall\\\" role=\\\"region\\\" aria-labelledby=\\\"paywall-title\\\"><div class=\\\"ep-inline-header\\\"><div class=\\\"ep-inline-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M9 12l2 2 4-4\\\"></path><path d=\\\"M21 12c-1 0-3-1-3-3s2-3 3-3 3 1 3 3-2 3-3 3\\\"></path><path d=\\\"M3 12c1 0 3-1 3-3s-2-3-3-3-3 1-3 3 2 3 3 3\\\"></path></svg></div><div class=\\\"ep-inline-header-content\\\"><h3 class=\\\"ep-heading-3\\\" id=\\\"paywall-title\\\">{{title}}</h3><p class=\\\"ep-text-body\\\">{{description}}</p></div></div><div class=\\\"ep-inline-content\\\"><div class=\\\"ep-inline-features\\\"><div class=\\\"ep-feature-grid\\\"><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 12h-4l-3 9L9 3l-3 9H2\\\"></path></svg></div><h4 class=\\\"ep-feature-card-title\\\">{{feature1Title}}</h4><p class=\\\"ep-feature-card-description\\\">{{feature1Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z\\\"></path></svg></div><h4 class=\\\"ep-feature-card-title\\\">{{feature2Title}}</h4><p class=\\\"ep-feature-card-description\\\">{{feature2Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M13 2L3 14h9l-1 8 10-12h-9l1-8z\\\"></path></svg></div><h4 class=\\\"ep-feature-card-title\\\">{{feature3Title}}</h4><p class=\\\"ep-feature-card-description\\\">{{feature3Description}}</p></div></div></div><div class=\\\"ep-inline-pricing\\\"><div class=\\\"ep-pricing-comparison\\\"><div class=\\\"ep-pricing-plan\\\"><div class=\\\"ep-pricing-plan-header\\\"><h4 class=\\\"ep-pricing-plan-title\\\">Free</h4><div class=\\\"ep-pricing-plan-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">0</span></div></div><ul class=\\\"ep-pricing-plan-features\\\"><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{freeFeature1}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{freeFeature2}} </li><li class=\\\"ep-pricing-feature ep-pricing-feature-disabled\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg> {{freeFeature3}} </li></ul></div><div class=\\\"ep-pricing-plan ep-pricing-plan-premium\\\"><div class=\\\"ep-pricing-plan-badge\\\">Most Popular</div><div class=\\\"ep-pricing-plan-header\\\"><h4 class=\\\"ep-pricing-plan-title\\\">Premium</h4><div class=\\\"ep-pricing-plan-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">{{price}}</span><span class=\\\"ep-pricing-period\\\">{{period}}</span></div></div><ul class=\\\"ep-pricing-plan-features\\\"><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature1}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature2}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature3}} </li></ul><button class=\\\"ep-btn ep-btn-primary ep-btn-full\\\" data-ep-action=\\\"upgradeNow\\\"> {{upgradeButtonText}} </button></div></div></div><div class=\\\"ep-inline-trial\\\"><div class=\\\"ep-trial-content\\\"><p class=\\\"ep-trial-text\\\">{{trialText}}</p><div class=\\\"ep-trial-actions\\\"><button class=\\\"ep-btn ep-btn-secondary\\\" data-ep-action=\\\"startTrial\\\"> {{trialButtonText}} </button><button class=\\\"ep-btn ep-btn-ghost ep-btn-sm\\\" data-ep-action=\\\"dismissPaywall\\\"> {{dismissButtonText}} </button></div></div></div></div></div>\";\nexport const css = \".ep-inline-paywall{max-width:800px;margin:0 auto;background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-lg);box-shadow:var(--ep-shadow-md);overflow:hidden;opacity:0;transform:translateY(20px);transition:all var(--ep-transition-slow)}.ep-inline-paywall.ep-inline-visible{opacity:1;transform:translateY(0)}.ep-inline-paywall.ep-inline-dismissing{opacity:0;transform:translateY(-20px);transition:all var(--ep-transition-normal)}.ep-inline-header{display:flex;align-items:center;gap:var(--ep-space-4);padding:var(--ep-space-6);background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100));border-bottom:1px solid var(--ep-border-primary)}:host([data-theme=\\\"dark\\\"]) .ep-inline-header{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800))}.ep-inline-icon{width:64px;height:64px;background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-xl);display:flex;align-items:center;justify-content:center;color:white;flex-shrink:0}.ep-inline-header-content{flex:1;min-width:0}.ep-inline-header-content .ep-heading-3{margin-bottom:var(--ep-space-2);color:var(--ep-text-primary)}.ep-inline-header-content .ep-text-body{margin-bottom:0;color:var(--ep-text-secondary)}.ep-inline-content{padding:var(--ep-space-8)}.ep-inline-features{margin-bottom:var(--ep-space-8)}.ep-feature-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:var(--ep-space-4)}.ep-feature-card{background-color:var(--ep-bg-tertiary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-md);padding:var(--ep-space-4);text-align:center;transition:all var(--ep-transition-normal);opacity:0;transform:translateY(10px);animation:ep-feature-card-in var(--ep-transition-slow) forwards}.ep-feature-card:hover{transform:translateY(-2px);box-shadow:var(--ep-shadow-md)}.ep-feature-card-icon{width:48px;height:48px;margin:0 auto var(--ep-space-3);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-lg);display:flex;align-items:center;justify-content:center;color:white}.ep-feature-card-title{font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-2)}.ep-feature-card-description{color:var(--ep-text-secondary);font-size:var(--ep-font-size-sm);line-height:var(--ep-line-height-relaxed);margin:0}.ep-inline-pricing{margin-bottom:var(--ep-space-8)}.ep-pricing-comparison{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:var(--ep-space-4);max-width:600px;margin:0 auto}.ep-pricing-plan{position:relative;background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-lg);padding:var(--ep-space-6);transition:all var(--ep-transition-normal)}.ep-pricing-plan:hover{transform:translateY(-2px);box-shadow:var(--ep-shadow-md)}.ep-pricing-plan-premium{border-color:var(--ep-primary-300);box-shadow:var(--ep-shadow-lg)}.ep-pricing-plan-badge{position:absolute;top:-12px;left:50%;transform:translateX(-50%);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));color:white;padding:var(--ep-space-1) var(--ep-space-4);border-radius:var(--ep-radius-full);font-size:var(--ep-font-size-sm);font-weight:var(--ep-font-weight-medium);white-space:nowrap}.ep-pricing-plan-header{text-align:center;margin-bottom:var(--ep-space-6)}.ep-pricing-plan-title{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-3)}.ep-pricing-plan-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-1)}.ep-pricing-currency{font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-pricing-amount{font-size:var(--ep-font-size-3xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-pricing-period{font-size:var(--ep-font-size-lg);color:var(--ep-text-secondary)}.ep-pricing-plan-features{list-style:none;padding:0;margin:0 0 var(--ep-space-6) 0}.ep-pricing-feature{display:flex;align-items:center;gap:var(--ep-space-3);padding:var(--ep-space-2) 0;color:var(--ep-text-primary);font-size:var(--ep-font-size-sm)}.ep-pricing-feature-disabled{color:var(--ep-text-tertiary)}.ep-pricing-feature-icon{color:var(--ep-success-500);flex-shrink:0}.ep-pricing-feature-disabled .ep-pricing-feature-icon{color:var(--ep-text-tertiary)}.ep-inline-trial{background:linear-gradient(135deg,var(--ep-gray-50),var(--ep-gray-100));border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-md);padding:var(--ep-space-6);text-align:center}:host([data-theme=\\\"dark\\\"]) .ep-inline-trial{background:linear-gradient(135deg,var(--ep-gray-800),var(--ep-gray-700))}.ep-trial-content{max-width:400px;margin:0 auto}.ep-trial-text{color:var(--ep-text-primary);font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-medium);margin-bottom:var(--ep-space-6)}.ep-trial-actions{display:flex;flex-direction:column;gap:var(--ep-space-3);align-items:center}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);right:var(--ep-space-4);z-index:var(--ep-z-tooltip)}@keyframes ep-feature-card-in{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@media (max-width:768px){.ep-inline-paywall{margin:var(--ep-space-4)}.ep-inline-header{flex-direction:column;text-align:center;gap:var(--ep-space-3)}.ep-inline-content{padding:var(--ep-space-6)}.ep-feature-grid{grid-template-columns:1fr}.ep-pricing-comparison{grid-template-columns:1fr}.ep-pricing-plan{padding:var(--ep-space-4)}.ep-trial-actions{flex-direction:column;width:100%}.ep-trial-actions .ep-btn{width:100%}}@media (max-width:640px){.ep-inline-paywall{margin:var(--ep-space-2);border-radius:var(--ep-radius-md)}.ep-inline-header{padding:var(--ep-space-4)}.ep-inline-content{padding:var(--ep-space-4)}.ep-inline-icon{width:48px;height:48px}.ep-feature-card-icon{width:40px;height:40px}.ep-pricing-plan{padding:var(--ep-space-3)}.ep-pricing-amount{font-size:var(--ep-font-size-2xl)}}@media (prefers-contrast:high){.ep-inline-paywall{border:2px solid var(--ep-border-secondary)}.ep-feature-card{border:2px solid var(--ep-border-secondary)}.ep-pricing-plan{border:2px solid var(--ep-border-secondary)}.ep-pricing-plan-premium{border:2px solid var(--ep-primary-500)}}@media (prefers-reduced-motion:reduce){.ep-inline-paywall{transition:none;opacity:1;transform:none}.ep-feature-card{transition:none;animation:none;opacity:1;transform:none}.ep-feature-card:hover{transform:none}.ep-pricing-plan:hover{transform:none}}\";\nexport default { html, css };","export const html = \"<div class=\\\"ep-sidebar-backdrop\\\" id=\\\"sidebarBackdrop\\\"></div><div class=\\\"ep-sidebar-paywall\\\" id=\\\"sidebarPaywall\\\" role=\\\"dialog\\\" aria-labelledby=\\\"sidebar-title\\\" aria-describedby=\\\"sidebar-description\\\"><div class=\\\"ep-sidebar-header\\\"><button class=\\\"ep-sidebar-close\\\" aria-label=\\\"Close paywall\\\" data-ep-action=\\\"closeSidebar\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg></button><div class=\\\"ep-sidebar-logo\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 2L2 7l10 5 10-5-10-5z\\\"></path><path d=\\\"M2 17l10 5 10-5\\\"></path><path d=\\\"M2 12l10 5 10-5\\\"></path></svg><span class=\\\"ep-sidebar-logo-text\\\">{{brandName}}</span></div></div><div class=\\\"ep-sidebar-content\\\"><div class=\\\"ep-sidebar-title-section\\\"><h2 class=\\\"ep-heading-2\\\" id=\\\"sidebar-title\\\">{{title}}</h2><p class=\\\"ep-text-body\\\" id=\\\"sidebar-description\\\">{{description}}</p></div><div class=\\\"ep-sidebar-progress\\\"><div class=\\\"ep-progress-header\\\"><span class=\\\"ep-progress-label\\\">{{progressLabel}}</span><span class=\\\"ep-progress-value\\\">{{usageCount}}/{{usageLimit}}</span></div><div class=\\\"ep-progress-bar\\\"><div class=\\\"ep-progress-fill\\\" style=\\\"width: {{progressPercentage}}%\\\"></div></div><p class=\\\"ep-progress-text\\\">{{progressText}}</p></div><div class=\\\"ep-sidebar-features\\\"><h3 class=\\\"ep-heading-3\\\">Unlock Premium Features</h3><div class=\\\"ep-feature-list\\\"><div class=\\\"ep-feature-item\\\"><div class=\\\"ep-feature-icon\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 2L2 7l10 5 10-5-10-5z\\\"></path><path d=\\\"M2 17l10 5 10-5\\\"></path><path d=\\\"M2 12l10 5 10-5\\\"></path></svg></div><div class=\\\"ep-feature-content\\\"><h4 class=\\\"ep-feature-title\\\">{{feature1Title}}</h4><p class=\\\"ep-feature-description\\\">{{feature1Description}}</p></div></div><div class=\\\"ep-feature-item\\\"><div class=\\\"ep-feature-icon\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 12h-4l-3 9L9 3l-3 9H2\\\"></path></svg></div><div class=\\\"ep-feature-content\\\"><h4 class=\\\"ep-feature-title\\\">{{feature2Title}}</h4><p class=\\\"ep-feature-description\\\">{{feature2Description}}</p></div></div><div class=\\\"ep-feature-item\\\"><div class=\\\"ep-feature-icon\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z\\\"></path></svg></div><div class=\\\"ep-feature-content\\\"><h4 class=\\\"ep-feature-title\\\">{{feature3Title}}</h4><p class=\\\"ep-feature-description\\\">{{feature3Description}}</p></div></div></div></div><div class=\\\"ep-sidebar-pricing\\\"><div class=\\\"ep-pricing-card\\\"><div class=\\\"ep-pricing-header\\\"><div class=\\\"ep-pricing-badge\\\">{{pricingBadge}}</div><div class=\\\"ep-pricing-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">{{price}}</span><span class=\\\"ep-pricing-period\\\">{{period}}</span></div><p class=\\\"ep-pricing-description\\\">{{pricingDescription}}</p></div></div></div><div class=\\\"ep-sidebar-trial\\\"><div class=\\\"ep-trial-info\\\"><div class=\\\"ep-trial-icon\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 11.08V12a10 10 0 1 1-5.93-9.14\\\"></path><polyline points=\\\"22,4 12,14.01 9,11.01\\\"></polyline></svg></div><div class=\\\"ep-trial-content\\\"><h4 class=\\\"ep-trial-title\\\">{{trialTitle}}</h4><p class=\\\"ep-trial-description\\\">{{trialDescription}}</p></div></div></div></div><div class=\\\"ep-sidebar-footer\\\"><button class=\\\"ep-btn ep-btn-primary ep-btn-lg ep-btn-full\\\" data-ep-action=\\\"startUpgrade\\\"> {{upgradeButtonText}} </button><button class=\\\"ep-btn ep-btn-secondary ep-btn-full\\\" data-ep-action=\\\"startTrial\\\"> {{trialButtonText}} </button><button class=\\\"ep-btn ep-btn-ghost ep-btn-sm\\\" data-ep-action=\\\"remindLater\\\"> {{remindLaterText}} </button></div></div>\";\nexport const css = \".ep-sidebar-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,0.5);backdrop-filter:blur(2px);z-index:var(--ep-z-backdrop);opacity:0;visibility:hidden;transition:all var(--ep-transition-normal)}.ep-sidebar-backdrop.ep-sidebar-backdrop-visible{opacity:1;visibility:visible}.ep-sidebar-paywall{position:fixed;top:0;right:0;bottom:0;width:400px;max-width:90vw;background-color:var(--ep-bg-secondary);border-left:1px solid var(--ep-border-primary);box-shadow:var(--ep-shadow-xl);z-index:var(--ep-z-modal);display:flex;flex-direction:column;transform:translateX(100%);transition:transform var(--ep-transition-normal)}.ep-sidebar-paywall.ep-sidebar-visible{transform:translateX(0)}.ep-sidebar-header{display:flex;align-items:center;justify-content:space-between;padding:var(--ep-space-4) var(--ep-space-6);border-bottom:1px solid var(--ep-border-primary);background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100))}:host([data-theme=\\\"dark\\\"]) .ep-sidebar-header{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800))}.ep-sidebar-close{background:none;border:none;color:var(--ep-text-tertiary);cursor:pointer;padding:var(--ep-space-2);border-radius:var(--ep-radius-md);transition:all var(--ep-transition-fast)}.ep-sidebar-close:hover{color:var(--ep-text-primary);background-color:var(--ep-bg-tertiary)}.ep-sidebar-logo{display:flex;align-items:center;gap:var(--ep-space-2);color:var(--ep-primary-600)}.ep-sidebar-logo-text{font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary)}.ep-sidebar-content{flex:1;padding:var(--ep-space-6);overflow-y:auto;display:flex;flex-direction:column;gap:var(--ep-space-6)}.ep-sidebar-title-section{text-align:center}.ep-sidebar-title-section .ep-heading-2{margin-bottom:var(--ep-space-3);color:var(--ep-text-primary)}.ep-sidebar-title-section .ep-text-body{margin-bottom:0;color:var(--ep-text-secondary)}.ep-sidebar-progress{background-color:var(--ep-bg-tertiary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-md);padding:var(--ep-space-4)}.ep-progress-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:var(--ep-space-3)}.ep-progress-label{font-size:var(--ep-font-size-sm);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-primary)}.ep-progress-value{font-size:var(--ep-font-size-sm);font-weight:var(--ep-font-weight-semibold);color:var(--ep-primary-600)}.ep-progress-bar{height:8px;background-color:var(--ep-bg-primary);border-radius:var(--ep-radius-full);overflow:hidden;margin-bottom:var(--ep-space-2)}.ep-progress-fill{height:100%;background:linear-gradient(90deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-full);transition:width var(--ep-transition-normal)}.ep-progress-text{font-size:var(--ep-font-size-xs);color:var(--ep-text-tertiary);margin:0}.ep-sidebar-features .ep-heading-3{margin-bottom:var(--ep-space-4);text-align:center}.ep-feature-list{display:flex;flex-direction:column;gap:var(--ep-space-4)}.ep-feature-item{display:flex;align-items:flex-start;gap:var(--ep-space-3);padding:var(--ep-space-3);background-color:var(--ep-bg-tertiary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-md);opacity:0;transform:translateX(20px);transition:all var(--ep-transition-normal)}.ep-feature-item.ep-feature-item-visible{opacity:1;transform:translateX(0)}.ep-feature-icon{width:40px;height:40px;background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-lg);display:flex;align-items:center;justify-content:center;color:white;flex-shrink:0}.ep-feature-content{flex:1;min-width:0}.ep-feature-title{font-size:var(--ep-font-size-base);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-1)}.ep-feature-description{font-size:var(--ep-font-size-sm);color:var(--ep-text-secondary);line-height:var(--ep-line-height-relaxed);margin:0}.ep-sidebar-pricing{background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100));border:1px solid var(--ep-primary-200);border-radius:var(--ep-radius-lg);padding:var(--ep-space-4)}:host([data-theme=\\\"dark\\\"]) .ep-sidebar-pricing{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800));border-color:var(--ep-primary-700)}.ep-pricing-card{text-align:center}.ep-pricing-header{margin-bottom:var(--ep-space-4)}.ep-pricing-badge{background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));color:white;padding:var(--ep-space-1) var(--ep-space-3);border-radius:var(--ep-radius-full);font-size:var(--ep-font-size-xs);font-weight:var(--ep-font-weight-medium);display:inline-block;margin-bottom:var(--ep-space-3)}.ep-pricing-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-1);margin-bottom:var(--ep-space-2)}.ep-pricing-currency{font-size:var(--ep-font-size-base);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-pricing-amount{font-size:var(--ep-font-size-2xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-pricing-period{font-size:var(--ep-font-size-base);color:var(--ep-text-secondary)}.ep-pricing-description{font-size:var(--ep-font-size-sm);color:var(--ep-text-secondary);margin:0}.ep-sidebar-trial{background-color:var(--ep-success-50);border:1px solid var(--ep-success-200);border-radius:var(--ep-radius-md);padding:var(--ep-space-4)}:host([data-theme=\\\"dark\\\"]) .ep-sidebar-trial{background-color:rgba(16,185,129,0.1);border-color:rgba(16,185,129,0.3)}.ep-trial-info{display:flex;align-items:flex-start;gap:var(--ep-space-3)}.ep-trial-icon{width:32px;height:32px;background:linear-gradient(135deg,var(--ep-success-500),var(--ep-success-600));border-radius:var(--ep-radius-lg);display:flex;align-items:center;justify-content:center;color:white;flex-shrink:0}.ep-trial-content{flex:1;min-width:0}.ep-trial-title{font-size:var(--ep-font-size-base);font-weight:var(--ep-font-weight-semibold);color:var(--ep-success-700);margin-bottom:var(--ep-space-1)}:host([data-theme=\\\"dark\\\"]) .ep-trial-title{color:var(--ep-success-400)}.ep-trial-description{font-size:var(--ep-font-size-sm);color:var(--ep-success-600);line-height:var(--ep-line-height-relaxed);margin:0}:host([data-theme=\\\"dark\\\"]) .ep-trial-description{color:var(--ep-success-300)}.ep-sidebar-footer{padding:var(--ep-space-6);border-top:1px solid var(--ep-border-primary);background-color:var(--ep-bg-tertiary);display:flex;flex-direction:column;gap:var(--ep-space-3)}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);left:var(--ep-space-4);z-index:var(--ep-z-tooltip);display:flex;flex-direction:column;gap:var(--ep-space-2)}@media (max-width:768px){.ep-sidebar-paywall{width:100%;max-width:100%;border-left:none}.ep-sidebar-content{padding:var(--ep-space-4)}.ep-sidebar-footer{padding:var(--ep-space-4)}}@media (max-width:480px){.ep-sidebar-header{padding:var(--ep-space-3) var(--ep-space-4)}.ep-sidebar-content{padding:var(--ep-space-3);gap:var(--ep-space-4)}.ep-sidebar-footer{padding:var(--ep-space-3)}.ep-feature-item{padding:var(--ep-space-2)}.ep-feature-icon{width:32px;height:32px}.ep-pricing-amount{font-size:var(--ep-font-size-xl)}}@media (prefers-contrast:high){.ep-sidebar-paywall{border-left:2px solid var(--ep-border-secondary)}.ep-feature-item{border:2px solid var(--ep-border-secondary)}.ep-sidebar-pricing{border:2px solid var(--ep-primary-500)}.ep-sidebar-trial{border:2px solid var(--ep-success-500)}}@media (prefers-reduced-motion:reduce){.ep-sidebar-backdrop{transition:none}.ep-sidebar-paywall{transition:none}.ep-feature-item{transition:none;opacity:1;transform:none}.ep-progress-fill{transition:none}}\";\nexport default { html, css };","export const html = \"<div class=\\\"ep-minimal-paywall\\\" id=\\\"minimalPaywall\\\" role=\\\"dialog\\\" aria-labelledby=\\\"minimal-title\\\"><button class=\\\"ep-minimal-close\\\" aria-label=\\\"Close paywall\\\" data-ep-action=\\\"closeMinimal\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg></button><div class=\\\"ep-minimal-content\\\"><div class=\\\"ep-minimal-header\\\"><div class=\\\"ep-minimal-icon\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M9 12l2 2 4-4\\\"></path><path d=\\\"M21 12c-1 0-3-1-3-3s2-3 3-3 3 1 3 3-2 3-3 3\\\"></path><path d=\\\"M3 12c1 0 3-1 3-3s-2-3-3-3-3 1-3 3 2 3 3 3\\\"></path></svg></div><h3 class=\\\"ep-minimal-title\\\" id=\\\"minimal-title\\\">{{title}}</h3><p class=\\\"ep-minimal-description\\\">{{description}}</p></div><div class=\\\"ep-minimal-pricing\\\"><div class=\\\"ep-minimal-price\\\"><span class=\\\"ep-minimal-currency\\\">{{currency}}</span><span class=\\\"ep-minimal-amount\\\">{{price}}</span><span class=\\\"ep-minimal-period\\\">{{period}}</span></div><p class=\\\"ep-minimal-price-description\\\">{{priceDescription}}</p></div><div class=\\\"ep-minimal-features\\\"><ul class=\\\"ep-minimal-feature-list\\\"><li class=\\\"ep-minimal-feature\\\"><svg class=\\\"ep-minimal-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature1}}</span></li><li class=\\\"ep-minimal-feature\\\"><svg class=\\\"ep-minimal-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature2}}</span></li><li class=\\\"ep-minimal-feature\\\"><svg class=\\\"ep-minimal-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature3}}</span></li></ul></div><div class=\\\"ep-minimal-actions\\\"><button class=\\\"ep-btn ep-btn-primary ep-btn-full\\\" data-ep-action=\\\"upgradeNow\\\"> {{upgradeButtonText}} </button><button class=\\\"ep-btn ep-btn-ghost ep-btn-sm\\\" data-ep-action=\\\"closeMinimal\\\"> {{dismissButtonText}} </button></div><div class=\\\"ep-minimal-trial\\\"><p class=\\\"ep-minimal-trial-text\\\">{{trialText}}</p></div></div></div><div class=\\\"ep-minimal-backdrop\\\" id=\\\"minimalBackdrop\\\"></div>\";\nexport const css = \".ep-minimal-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,0.4);z-index:var(--ep-z-backdrop);opacity:0;visibility:hidden;transition:all var(--ep-transition-fast)}.ep-minimal-backdrop.ep-minimal-backdrop-visible{opacity:1;visibility:visible}.ep-minimal-paywall{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%) scale(0.95);background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-lg);box-shadow:var(--ep-shadow-xl);z-index:var(--ep-z-modal);max-width:400px;width:90vw;max-height:90vh;overflow-y:auto;opacity:0;visibility:hidden;transition:all var(--ep-transition-fast)}.ep-minimal-paywall.ep-minimal-visible{opacity:1;visibility:visible;transform:translate(-50%,-50%) scale(1)}.ep-minimal-close{position:absolute;top:var(--ep-space-3);right:var(--ep-space-3);background:none;border:none;color:var(--ep-text-tertiary);cursor:pointer;padding:var(--ep-space-2);border-radius:var(--ep-radius-sm);transition:all var(--ep-transition-fast);z-index:1}.ep-minimal-close:hover{color:var(--ep-text-primary);background-color:var(--ep-bg-tertiary)}.ep-minimal-content{padding:var(--ep-space-6);padding-top:var(--ep-space-8)}.ep-minimal-header{text-align:center;margin-bottom:var(--ep-space-6)}.ep-minimal-icon{width:48px;height:48px;margin:0 auto var(--ep-space-3);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-lg);display:flex;align-items:center;justify-content:center;color:white}.ep-minimal-title{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-2)}.ep-minimal-description{color:var(--ep-text-secondary);font-size:var(--ep-font-size-sm);line-height:var(--ep-line-height-relaxed);margin:0}.ep-minimal-pricing{text-align:center;margin-bottom:var(--ep-space-6);padding:var(--ep-space-4);background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100));border:1px solid var(--ep-primary-200);border-radius:var(--ep-radius-md)}:host([data-theme=\\\"dark\\\"]) .ep-minimal-pricing{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800));border-color:var(--ep-primary-700)}.ep-minimal-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-1);margin-bottom:var(--ep-space-2)}.ep-minimal-currency{font-size:var(--ep-font-size-base);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-minimal-amount{font-size:var(--ep-font-size-2xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-minimal-period{font-size:var(--ep-font-size-base);color:var(--ep-text-secondary)}.ep-minimal-price-description{color:var(--ep-text-secondary);font-size:var(--ep-font-size-xs);margin:0}.ep-minimal-features{margin-bottom:var(--ep-space-6)}.ep-minimal-feature-list{list-style:none;padding:0;margin:0}.ep-minimal-feature{display:flex;align-items:center;gap:var(--ep-space-2);padding:var(--ep-space-2) 0;color:var(--ep-text-primary);font-size:var(--ep-font-size-sm);border-bottom:1px solid var(--ep-border-primary)}.ep-minimal-feature:last-child{border-bottom:none}.ep-minimal-feature-icon{color:var(--ep-success-500);flex-shrink:0}.ep-minimal-feature span{font-weight:var(--ep-font-weight-medium)}.ep-minimal-actions{display:flex;flex-direction:column;gap:var(--ep-space-2);margin-bottom:var(--ep-space-4)}.ep-minimal-trial{text-align:center;padding-top:var(--ep-space-4);border-top:1px solid var(--ep-border-primary)}.ep-minimal-trial-text{color:var(--ep-text-tertiary);font-size:var(--ep-font-size-xs);margin:0}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);left:var(--ep-space-4);z-index:var(--ep-z-tooltip);display:flex;flex-direction:column;gap:var(--ep-space-2)}@media (max-width:480px){.ep-minimal-paywall{width:95vw;max-width:none}.ep-minimal-content{padding:var(--ep-space-4);padding-top:var(--ep-space-6)}.ep-minimal-close{top:var(--ep-space-2);right:var(--ep-space-2)}.ep-minimal-icon{width:40px;height:40px}.ep-minimal-title{font-size:var(--ep-font-size-lg)}.ep-minimal-amount{font-size:var(--ep-font-size-xl)}.ep-minimal-pricing{padding:var(--ep-space-3)}}@media (prefers-contrast:high){.ep-minimal-paywall{border:2px solid var(--ep-border-secondary)}.ep-minimal-pricing{border:2px solid var(--ep-primary-500)}.ep-minimal-backdrop{background-color:rgba(0,0,0,0.8)}}@media (prefers-reduced-motion:reduce){.ep-minimal-backdrop{transition:none}.ep-minimal-paywall{transition:none;transform:translate(-50%,-50%)}.ep-minimal-paywall.ep-minimal-visible{transform:translate(-50%,-50%)}}@media print{.ep-minimal-backdrop{display:none}.ep-minimal-paywall{position:static;transform:none;box-shadow:none;border:1px solid black;opacity:1;visibility:visible}.ep-minimal-close{display:none}}.ep-minimal-paywall *:focus{outline:2px solid var(--ep-primary-500);outline-offset:2px}.ep-minimal-paywall *:focus:not(:focus-visible){outline:none}.ep-minimal-paywall{animation:ep-minimal-entrance var(--ep-transition-normal) ease-out}@keyframes ep-minimal-entrance{from{opacity:0;transform:translate(-50%,-50%) scale(0.9)}to{opacity:1;transform:translate(-50%,-50%) scale(1)}}.ep-minimal-feature:hover{background-color:var(--ep-bg-tertiary);border-radius:var(--ep-radius-sm);margin:0 calc(-1 * var(--ep-space-2));padding:var(--ep-space-2)}.ep-minimal-pricing:hover{background:linear-gradient(135deg,var(--ep-primary-100),var(--ep-primary-200));border-color:var(--ep-primary-300)}:host([data-theme=\\\"dark\\\"]) .ep-minimal-pricing:hover{background:linear-gradient(135deg,var(--ep-primary-800),var(--ep-primary-700));border-color:var(--ep-primary-600)}\";\nexport default { html, css };","/**\n * The one paywall renderer.\n *\n * Renders a template from `@extenshi/paywall-templates` into a Shadow DOM\n * host so the templates' resets never leak into the extension page (and vice\n * versa). Placeholders (`{{title}}`, `{{price}}` …) are filled from the offer\n * and the strings dictionary, every value HTML-escaped; buttons are bound with\n * `addEventListener` on `data-ep-action` (no inline handlers, no scripts).\n */\n\nimport type { ThemeConfig } from '../types/config.js'\nimport type { PayOfferDto, PaySellerPublic } from '../types/contract.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { PaywallMode, PaywallStrings } from '../types/paywall.js'\nimport { formatPrice, periodLabel } from './format.js'\nimport { sellerDetails } from './seller-details.js'\nimport { DEFAULT_STRINGS, MOCK_PAYMENT_NOTICE } from './strings.js'\nimport { PAYWALL_SHARED_CSS, PAYWALL_TEMPLATES } from './templates.js'\n\nexport interface PaywallView {\n\tmode: PaywallMode\n\ttitle: string\n\tdescription: string\n\tfeatures: string[]\n\tfreeFeatures: string[]\n\tbrandName: string\n\toffer: PayOfferDto | null\n\tcheckoutEnabled: boolean\n\tmock?: boolean\n\trecoveryEnabled?: boolean\n\tseller?: PaySellerPublic | null\n\tlocale: string | null\n\ttheme: ThemeConfig\n\tstrings: Partial<PaywallStrings>\n\tcontainer?: HTMLElement\n}\n\nexport interface PaywallRendererCallbacks {\n\tonUpgrade: (sku: string) => void\n\tonClose: () => void\n\tonRestore?: () => void\n}\n\nexport const PAYWALL_HOST_CLASS = 'extenshi-paywall-host'\n\nconst UPGRADE_ACTIONS: ReadonlySet<string> = new Set(['upgradeNow', 'startUpgrade'])\nconst CLOSE_ACTIONS: ReadonlySet<string> = new Set([\n\t'closePaywall',\n\t'closeSidebar',\n\t'closeFullscreen',\n\t'closeMinimal',\n\t'dismissPaywall',\n\t'remindLater',\n\t'continueFree',\n])\n\nconst ROOT_SELECTOR: Record<PaywallMode, string> = {\n\tmodal: '.ep-modal-backdrop',\n\tinline: '.ep-inline-paywall',\n\tsidebar: '.ep-sidebar-paywall',\n\tfullscreen: '.ep-fullscreen-paywall',\n\tminimal: '.ep-minimal-paywall',\n}\n\nconst BACKDROP_SELECTOR: Partial<Record<PaywallMode, string>> = {\n\tmodal: '.ep-modal-backdrop',\n\tsidebar: '.ep-sidebar-backdrop',\n\tminimal: '.ep-minimal-backdrop',\n}\n\nconst VISIBLE_CLASSES: Partial<Record<PaywallMode, Array<[selector: string, className: string]>>> = {\n\tinline: [['.ep-inline-paywall', 'ep-inline-visible']],\n\tsidebar: [\n\t\t['.ep-sidebar-paywall', 'ep-sidebar-visible'],\n\t\t['.ep-sidebar-backdrop', 'ep-sidebar-backdrop-visible'],\n\t],\n\tminimal: [\n\t\t['.ep-minimal-paywall', 'ep-minimal-visible'],\n\t\t['.ep-minimal-backdrop', 'ep-minimal-backdrop-visible'],\n\t],\n}\n\n/** Template blocks the contract has no data for (trials, usage meters). */\nconst PRUNE_SELECTOR = '[class*=\"-trial\"], .ep-sidebar-progress'\n/**\n * Templates stagger their feature rows in with this class from their demo\n * script (sidebar, fullscreen); without it the rows sit at opacity 0.\n */\nconst FEATURE_ITEM_VISIBLE = ['.ep-feature-item', 'ep-feature-item-visible'] as const\n/** Containers of a single feature slot; dropped when the slot's placeholder is empty. */\nconst FEATURE_SLOT_SELECTOR = 'li, .ep-feature-card, .ep-feature-item, .ep-pricing-feature, .ep-feature'\nconst EMPTY_SLOT_MARK = 'data-ep-empty'\nconst FEATURE_KEY_RE = /^(feature\\d+(Title)?|premiumFeature\\d+|freeFeature\\d+)$/\n\nexport function escapeHtml(value: string): string {\n\treturn value\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;')\n\t\t.replace(/\"/g, '&quot;')\n\t\t.replace(/'/g, '&#039;')\n}\n\nexport function substitute(html: string, content: Record<string, string>): string {\n\treturn html.replace(/\\{\\{(\\w+)\\}\\}/g, (_match, key: string) => {\n\t\tconst value = content[key] ?? ''\n\t\tif (value === '' && FEATURE_KEY_RE.test(key)) return `<i ${EMPTY_SLOT_MARK}></i>`\n\t\treturn escapeHtml(value)\n\t})\n}\n\nexport function buildContent(view: PaywallView, strings: PaywallStrings): Record<string, string> {\n\tconst offer = view.offer\n\tconst price = offer ? formatPrice(offer.amountMinor, offer.currency, view.locale) : null\n\tconst content: Record<string, string> = {\n\t\ttitle: view.title,\n\t\tdescription: view.description,\n\t\tbrandName: view.brandName,\n\t\tcurrency: price?.currency ?? '',\n\t\tprice: price?.amount ?? '',\n\t\tperiod: offer ? periodLabel(offer, strings) : '',\n\t\tpricingDescription: offer?.description ?? '',\n\t\tpriceDescription: offer?.description ?? '',\n\t\tpremiumDescription: offer?.description ?? '',\n\t\tupgradeButtonText: view.checkoutEnabled && offer ? strings.upgrade : strings.checkoutUnavailable,\n\t\tcancelButtonText: strings.cancel,\n\t\tdismissButtonText: strings.dismiss,\n\t\tremindLaterText: strings.remindLater,\n\t\tcontinueButtonText: strings.continueFree,\n\t\tfooterText: strings.footer,\n\t}\n\tview.features.forEach((feature, index) => {\n\t\tconst n = index + 1\n\t\tcontent[`feature${n}`] = feature\n\t\tcontent[`feature${n}Title`] = feature\n\t\tcontent[`premiumFeature${n}`] = feature\n\t})\n\tview.freeFeatures.forEach((feature, index) => {\n\t\tcontent[`freeFeature${index + 1}`] = feature\n\t})\n\treturn content\n}\n\nconst CSS_VALUE_UNSAFE = /[;{}<>]/g\n\nexport function themeCss(theme: ThemeConfig): string {\n\tconst declarations: string[] = []\n\tconst safe = (value: string) => value.replace(CSS_VALUE_UNSAFE, '')\n\tif (theme.primaryColor) {\n\t\tconst color = safe(theme.primaryColor)\n\t\tdeclarations.push(`--ep-primary-500:${color}`, `--ep-primary-600:${color}`, `--ep-primary-700:${color}`)\n\t}\n\tif (theme.fontFamily) declarations.push(`--ep-font-family-sans:${safe(theme.fontFamily)}`)\n\tif (theme.borderRadius) {\n\t\tconst radius = safe(theme.borderRadius)\n\t\tdeclarations.push(`--ep-radius-md:${radius}`, `--ep-radius-lg:${radius}`, `--ep-radius-xl:${radius}`)\n\t}\n\tconst host = declarations.length > 0 ? `:host{${declarations.join(';')}}` : ''\n\treturn host + (theme.customCss ?? '')\n}\n\nexport function resolveThemeMode(theme: ThemeConfig): 'light' | 'dark' {\n\tconst mode = theme.mode ?? 'auto'\n\tif (mode !== 'auto') return mode\n\tconst matchMedia = (globalThis as { matchMedia?: (query: string) => { matches: boolean } }).matchMedia\n\treturn typeof matchMedia === 'function' &&\n\t\tmatchMedia.call(globalThis, '(prefers-color-scheme: dark)').matches\n\t\t? 'dark'\n\t\t: 'light'\n}\n\nexport class PaywallRenderer {\n\tprivate host: HTMLElement | null = null\n\tprivate keyHandler: ((event: KeyboardEvent) => void) | null = null\n\n\tconstructor(private readonly callbacks: PaywallRendererCallbacks) {}\n\n\tisVisible(): boolean {\n\t\treturn this.host !== null\n\t}\n\n\t/** Returns the host element; its shadow root holds the rendered template. */\n\tshow(view: PaywallView): HTMLElement {\n\t\tthis.hide()\n\t\tconst doc = (globalThis as { document?: Document }).document\n\t\tif (!doc || typeof doc.createElement !== 'function' || !doc.body) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.PAYWALL_UNAVAILABLE,\n\t\t\t\t'The paywall needs a DOM; call showPaywall() from a popup, options page or content script',\n\t\t\t)\n\t\t}\n\t\tconst template = PAYWALL_TEMPLATES[view.mode]\n\t\tif (!template)\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, `Unknown paywall mode \"${view.mode}\"`)\n\n\t\tconst strings: PaywallStrings = { ...DEFAULT_STRINGS, ...view.strings }\n\t\tif (view.mock) {\n\t\t\tstrings.upgrade = 'Simulate purchase'\n\t\t\tstrings.footer = MOCK_PAYMENT_NOTICE\n\t\t}\n\t\tconst host = doc.createElement('div')\n\t\thost.className = PAYWALL_HOST_CLASS\n\t\thost.setAttribute('data-theme', resolveThemeMode(view.theme))\n\t\tconst root: ShadowRoot | HTMLElement =\n\t\t\ttypeof host.attachShadow === 'function' ? host.attachShadow({ mode: 'open' }) : host\n\t\troot.innerHTML =\n\t\t\t`<style>${PAYWALL_SHARED_CSS}${template.css}${themeCss(view.theme)}</style>` +\n\t\t\tsubstitute(template.html, buildContent(view, strings))\n\n\t\tthis.prune(root)\n\t\tthis.bind(root, view, doc)\n\t\tconst sellerMount = root.querySelector(\n\t\t\t'[class*=\"-footer\"], .ep-minimal-actions, .ep-inline-content, .ep-fullscreen-content',\n\t\t)\n\t\tif (sellerMount) {\n\t\t\tconst details = sellerDetails(view.seller ?? null)\n\t\t\tdetails.style.cssText =\n\t\t\t\t'font-size:12px;line-height:1.5;margin-top:12px;text-align:left;white-space:normal'\n\t\t\t// In the modal, disclose the provider before the purchase action,\n\t\t\t// instead of below it in the scrollable footer.\n\t\t\tconst modalActions = root.querySelector('.ep-modal-actions')\n\t\t\tif (modalActions) modalActions.before(details)\n\t\t\telse sellerMount.append(details)\n\t\t}\n\t\tif (view.mock) {\n\t\t\tconst upgrade = root.querySelector('[data-ep-action=\"upgradeNow\"], [data-ep-action=\"startUpgrade\"]')\n\t\t\tif (upgrade) {\n\t\t\t\tconst notice = doc.createElement('p')\n\t\t\t\tnotice.className = 'extenshi-payment-preview'\n\t\t\t\tnotice.textContent = MOCK_PAYMENT_NOTICE\n\t\t\t\tnotice.style.cssText = 'font-size:13px;line-height:1.5;margin:12px 0;white-space:normal'\n\t\t\t\tupgrade.before(notice)\n\t\t\t}\n\t\t}\n\t\tif (view.recoveryEnabled && this.callbacks.onRestore) {\n\t\t\tconst footer = root.querySelector(\n\t\t\t\t'[class*=\"-footer\"], .ep-minimal-actions, .ep-inline-content, .ep-fullscreen-content',\n\t\t\t)\n\t\t\tif (footer) {\n\t\t\t\tconst button = doc.createElement('button')\n\t\t\t\tbutton.type = 'button'\n\t\t\t\tbutton.textContent = strings.restorePurchase\n\t\t\t\tbutton.style.cssText =\n\t\t\t\t\t'display:block;margin:12px auto 0;background:none;border:0;color:inherit;font:inherit;text-decoration:underline;cursor:pointer'\n\t\t\t\tbutton.addEventListener('click', () => this.callbacks.onRestore?.())\n\t\t\t\tfooter.appendChild(button)\n\t\t\t}\n\t\t}\n\t\tconst mount = view.mode === 'inline' ? (view.container ?? doc.body) : doc.body\n\t\tmount.appendChild(host)\n\t\tthis.host = host\n\t\tthis.reveal(root, view.mode)\n\t\treturn host\n\t}\n\n\thide(): void {\n\t\tif (!this.host) return\n\t\tif (this.keyHandler) {\n\t\t\tthis.host.ownerDocument.removeEventListener('keydown', this.keyHandler)\n\t\t\tthis.keyHandler = null\n\t\t}\n\t\tthis.host.remove()\n\t\tthis.host = null\n\t}\n\n\tprivate prune(root: ParentNode): void {\n\t\tfor (const element of root.querySelectorAll(PRUNE_SELECTOR)) element.remove()\n\t\tfor (const mark of root.querySelectorAll(`[${EMPTY_SLOT_MARK}]`)) {\n\t\t\tconst slot = mark.parentElement?.closest(FEATURE_SLOT_SELECTOR) ?? mark.parentElement\n\t\t\t;(slot ?? mark).remove()\n\t\t}\n\t\t// A button whose label placeholder the contract does not fill (trial\n\t\t// CTAs on sidebar/fullscreen) would render as an empty pill; icon-only\n\t\t// buttons (close) keep their SVG and stay.\n\t\tfor (const button of root.querySelectorAll('button')) {\n\t\t\tif (!button.textContent?.trim() && !button.querySelector('svg')) button.remove()\n\t\t}\n\t}\n\n\tprivate bind(root: ParentNode, view: PaywallView, doc: Document): void {\n\t\tfor (const element of root.querySelectorAll<HTMLElement>('[data-ep-action]')) {\n\t\t\tconst action = element.getAttribute('data-ep-action') ?? ''\n\t\t\tif (UPGRADE_ACTIONS.has(action)) {\n\t\t\t\tif (view.offer && view.checkoutEnabled) {\n\t\t\t\t\tconst sku = view.offer.sku\n\t\t\t\t\telement.addEventListener('click', (event) => {\n\t\t\t\t\t\tevent.preventDefault()\n\t\t\t\t\t\tthis.callbacks.onUpgrade(sku)\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\telement.setAttribute('disabled', '')\n\t\t\t\t\telement.setAttribute('aria-disabled', 'true')\n\t\t\t\t}\n\t\t\t} else if (CLOSE_ACTIONS.has(action)) {\n\t\t\t\telement.addEventListener('click', (event) => {\n\t\t\t\t\tevent.preventDefault()\n\t\t\t\t\tthis.close()\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\telement.remove()\n\t\t\t}\n\t\t}\n\t\tconst backdropSelector = BACKDROP_SELECTOR[view.mode]\n\t\tif (backdropSelector) {\n\t\t\troot.querySelector(backdropSelector)?.addEventListener('click', (event) => {\n\t\t\t\tif (event.target === event.currentTarget) this.close()\n\t\t\t})\n\t\t}\n\t\tif (view.mode !== 'inline') {\n\t\t\tthis.keyHandler = (event) => {\n\t\t\t\tif (event.key === 'Escape') this.close()\n\t\t\t}\n\t\t\tdoc.addEventListener('keydown', this.keyHandler)\n\t\t}\n\t}\n\n\tprivate reveal(root: ParentNode, mode: PaywallMode): void {\n\t\tconst rootElement = root.querySelector<HTMLElement>(ROOT_SELECTOR[mode])\n\t\tif (rootElement && (mode === 'modal' || mode === 'fullscreen')) rootElement.style.display = 'flex'\n\t\tfor (const [selector, className] of VISIBLE_CLASSES[mode] ?? []) {\n\t\t\troot.querySelector(selector)?.classList.add(className)\n\t\t}\n\t\tfor (const item of root.querySelectorAll(FEATURE_ITEM_VISIBLE[0]))\n\t\t\titem.classList.add(FEATURE_ITEM_VISIBLE[1])\n\t}\n\n\tprivate close(): void {\n\t\tthis.hide()\n\t\tthis.callbacks.onClose()\n\t}\n}\n","/** Full SDK: everything in `ExtenshiPayLite` plus the offer and the paywall UI. */\n\nimport { ExtenshiPayLite } from './core/extenshi-pay.js'\nimport { isEntitled } from './payment/features.js'\nimport { BillingProfilePicker } from './paywall/billing-profile-picker.js'\nimport { LicensePanel } from './paywall/license-panel.js'\nimport { PaywallRenderer, type PaywallView } from './paywall/renderer.js'\nimport { DEFAULT_STRINGS } from './paywall/strings.js'\nimport type { PayOfferDto, PayOfferResponse } from './types/contract.js'\nimport type { CustomerPortalOptions, RequireFeatureOptions } from './types/entitlement.js'\nimport type { PaywallOptions } from './types/paywall.js'\n\ninterface PaywallSession {\n\toptions: PaywallOptions\n\tresolve: (unlocked: boolean) => void\n}\n\nfunction pickOffer(offer: PayOfferResponse | null, sku: string | undefined): PayOfferDto | null {\n\tif (!offer) return null\n\treturn offer.offers.find((candidate) => candidate.sku === sku) ?? offer.offers[0] ?? null\n}\n\nexport class ExtenshiPay extends ExtenshiPayLite {\n\tprivate disposed = false\n\tprivate licensePanel = new LicensePanel()\n\tprivate billingProfiles = new BillingProfilePicker()\n\tprivate paywall: PaywallRenderer | null = null\n\tprivate paywallSession: PaywallSession | null = null\n\n\toverride async openCustomerPortal(options: CustomerPortalOptions = {}): Promise<string | null> {\n\t\treturn super.openCustomerPortal({\n\t\t\t...options,\n\t\t\tselectAccount: options.selectAccount ?? ((accounts) => this.billingProfiles.show(accounts)),\n\t\t})\n\t}\n\n\toverride destroy(): void {\n\t\tthis.disposed = true\n\t\tthis.licensePanel.hide()\n\t\tthis.billingProfiles.hide()\n\t\tthis.hidePaywall()\n\t\tsuper.destroy()\n\t}\n\n\tasync showLicense(): Promise<void> {\n\t\t// An explicit status check should see refunds/cancellations immediately.\n\t\t// The entitlement manager still falls back to the verified cache offline.\n\t\tconst summary = await this.getLicenseSummary({ force: !this.config.mock })\n\t\tif (this.disposed) return\n\t\treturn this.licensePanel.show(summary, {\n\t\t\trestore: async () => {\n\t\t\t\tawait this.restorePurchase()\n\t\t\t\treturn this.getLicenseSummary({ force: true })\n\t\t\t},\n\t\t\tmanage: () => this.openCustomerPortal(),\n\t\t})\n\t}\n\n\tasync getOffer(options: { force?: boolean } = {}): Promise<PayOfferResponse> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\treturn await this.fetchOffer(options.force)\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/**\n\t * Renders the paywall and resolves `true` when a checkout started from it\n\t * completes, `false` when the user closes it. The offer is fetched via\n\t * `getOffer()`; if that fails the paywall still renders with checkout disabled.\n\t */\n\tasync showPaywall(options: PaywallOptions = {}): Promise<boolean> {\n\t\tawait this.initialize()\n\t\tlet offer: PayOfferResponse | null = null\n\t\ttry {\n\t\t\toffer = await this.fetchOffer()\n\t\t} catch (error) {\n\t\t\tthis.reportError(error)\n\t\t}\n\t\tconst selected = pickOffer(offer, options.sku)\n\t\tconst view: PaywallView = {\n\t\t\tmode: options.mode ?? 'modal',\n\t\t\ttitle: options.title ?? selected?.title ?? DEFAULT_STRINGS.title,\n\t\t\tdescription: options.description ?? selected?.description ?? DEFAULT_STRINGS.description,\n\t\t\tfeatures: options.features ?? selected?.features ?? [],\n\t\t\tfreeFeatures: options.freeFeatures ?? [],\n\t\t\tbrandName: offer?.projectName ?? '',\n\t\t\toffer: selected,\n\t\t\tcheckoutEnabled: offer?.checkoutEnabled === true && selected !== null && offer.seller !== null,\n\t\t\tmock: this.config.mock,\n\t\t\trecoveryEnabled: offer?.recoveryEnabled === true,\n\t\t\tseller: offer?.seller ?? null,\n\t\t\tlocale: this.config.locale,\n\t\t\ttheme: { ...this.config.theme, ...options.theme },\n\t\t\tstrings: options.strings ?? {},\n\t\t\tcontainer: options.container,\n\t\t}\n\t\tthis.hidePaywall()\n\t\treturn new Promise<boolean>((resolve) => {\n\t\t\tthis.paywallSession = { options, resolve }\n\t\t\ttry {\n\t\t\t\tthis.renderer().show(view)\n\t\t\t} catch (error) {\n\t\t\t\tthis.paywallSession = null\n\t\t\t\tthis.reportError(error)\n\t\t\t\tresolve(false)\n\t\t\t}\n\t\t})\n\t}\n\n\thidePaywall(): void {\n\t\tthis.paywall?.hide()\n\t\tthis.settlePaywall(false)\n\t}\n\n\tisPaywallVisible(): boolean {\n\t\treturn this.paywall?.isVisible() === true\n\t}\n\n\tprotected override async onFeatureLocked(\n\t\t_feature: string,\n\t\toptions: RequireFeatureOptions,\n\t): Promise<boolean> {\n\t\tif (options.showPaywall === false) return false\n\t\tif ((await this.getEntitlement()).requiresOnlineCheck) {\n\t\t\tawait this.showLicense()\n\t\t\treturn false\n\t\t}\n\t\treturn this.showPaywall(options.paywall ?? {})\n\t}\n\n\tprivate renderer(): PaywallRenderer {\n\t\tif (!this.paywall) {\n\t\t\tthis.paywall = new PaywallRenderer({\n\t\t\t\tonUpgrade: (sku) => void this.handleUpgrade(sku),\n\t\t\t\tonClose: () => this.settlePaywall(false),\n\t\t\t\tonRestore: () => void this.handleRestore(),\n\t\t\t})\n\t\t}\n\t\treturn this.paywall\n\t}\n\n\tprivate async handleRestore(): Promise<void> {\n\t\ttry {\n\t\t\tconst result = await this.restorePurchase()\n\t\t\tif (result.state === 'complete' && isEntitled(result.entitlement)) {\n\t\t\t\tthis.paywall?.hide()\n\t\t\t\tthis.settlePaywall(true)\n\t\t\t}\n\t\t} catch {\n\t\t\t/* Reported through the error event; leave the paywall open for retry. */\n\t\t}\n\t}\n\n\tprivate async handleUpgrade(sku: string): Promise<void> {\n\t\tthis.paywallSession?.options.onUpgrade?.(sku)\n\t\ttry {\n\t\t\tconst result = await this.openCheckout(sku)\n\t\t\tif (result.state === 'complete') {\n\t\t\t\tthis.paywall?.hide()\n\t\t\t\tthis.settlePaywall(true)\n\t\t\t}\n\t\t} catch {\n\t\t\t// Reported through the `error` event by openCheckout(); the paywall stays open for a retry.\n\t\t}\n\t}\n\n\tprivate settlePaywall(unlocked: boolean): void {\n\t\tconst session = this.paywallSession\n\t\tif (!session) return\n\t\tthis.paywallSession = null\n\t\tif (!unlocked) session.options.onClose?.()\n\t\tsession.resolve(unlocked)\n\t}\n}\n"],"names":["PAY_CONTRACT_VERSION","PAY_GATEWAYS","PAY_PUBLISHABLE_KEY_PREFIX","PAY_PUBLISHABLE_KEY_HEX_LENGTH","PUBLISHABLE_KEY_RE","RegExp","isPayPublishableKey","value","test","PAY_OFFER_KINDS","PAY_OFFER_INTERVALS","PAY_CURRENCIES","PAY_SKU_RE","PAY_ENTITLEMENT_STATUSES","PAY_END_USER_REF_RE","PAY_ERRORS","SELLER_NOT_CONNECTED","SELLER_NOT_ACTIVE","AGREEMENT_REQUIRED","OFFER_NOT_FOUND","OFFER_LIMIT","PRICE_TOO_LOW","GATEWAY_UNAVAILABLE","RATE_LIMITED","INVALID_KEY","canonicalJson","JSON","stringify","Array","isArray","map","item","join","Object","entries","filter","v","undefined","sort","a","b","k","ERROR_CODES","INVALID_CONFIG","INVALID_REQUEST","NETWORK_ERROR","TIMEOUT","VERIFICATION_UNAVAILABLE","INVALID_RESPONSE","CHECKOUT_UNAVAILABLE","PAYWALL_UNAVAILABLE","UNKNOWN","ExtenshiPayError","Error","constructor","code","message","options","super","this","name","retryAfterSec","httpStatus","cause","from","error","fallback","String","END_USER_REF_STORAGE_KEY","mintEndUserRef","cryptoApi","globalThis","crypto","randomUUID","bytes","getRandomValues","Uint8Array","hex","toString","padStart","slice","async","getOrCreateEndUserRef","storage","existing","get","ref","set","MockTransport","data","sessions","Map","entitlements","offers","projectName","checkoutEnabled","claimAfterPolls","call","procedure","_kind","input","offerResponse","createCheckout","sku","claim","sessionId","endUserRef","publishableKey","envelope","url","length","setEntitlements","items","cancelSession","session","state","expireSession","provider","entitlementPublicKey","some","offer","polls","expiresAt","Date","now","toISOString","grant","entitlement","find","o","kind","interval","title","status","features","payload","issuedAt","signature","alg","PayApi","transport","createRestoreSession","claimChallenge","claimRestoreSession","claimSecret","getOffer","locale","claimSession","getEntitlement","getPortalUrl","customerId","ORDER","silent","warn","info","debug","Logger","level","prefix","configure","logLevel","args","enabled","console","logger","TRPC_PATH","RETRYABLE","Set","CAUSE_TO_CODE","trpcErrorToPayError","trpcCode","causeCode","match","exec","Number","parseRetryAfter","mapped","sleep","ms","Promise","resolve","setTimeout","HttpTransport","apiUrl","replace","timeoutMs","retries","fetchImpl","init","fetch","base","encodeURIComponent","attempts","lastError","attempt","request","err","has","controller","AbortController","timer","abort","response","method","headers","body","signal","credentials","aborted","clearTimeout","json","ok","result","CHECKOUT_POLL_INTERVAL_MS","CHECKOUT_TIMEOUT_MS","openInNewTab","g","tabs","chrome","browser","create","then","open","CheckoutManager","active","pendingKey","isActive","getEndUserRef","api","pending","emit","openUrl","poll","resumePending","raw","expires","parse","isFinite","remove","settle","pollIntervalMs","deadline","sleeper","wake","interruptibleSleep","stopFocus","onFocus","disposers","addEventListener","removeEventListener","push","doc","document","onVisible","visibilityState","windows","onFocusChanged","addListener","onWindow","windowId","removeListener","dispose","onFocusRegained","delay","errorBackoff","Math","min","onComplete","LIVE_STATUSES","isLive","applyLocalExpiry","collectFeatures","feature","add","isEntitled","requiresOnlineCheck","hasFeature","includes","checkFeatures","EMPTY_ENTITLEMENT","freeze","verified","fetchedAt","source","offlineUntil","base64ToBytes","base64","binary","atob","i","charCodeAt","verifyEntitlementSignature","publicKeyBase64","subtle","key","importKey","TextEncoder","encode","verify","MIN_REFRESH_INTERVAL_MS","MAX_REFRESH_BACKOFF_MS","MAX_OFFLINE_AGE_MS","MAX_CLOCK_SKEW_MS","isEnvelope","env","EntitlementManager","held","inflight","refreshGeneration","deadlineTimer","refreshIntervalMs","backoffMs","autoRefresh","online","force","notifyIfChanged","lastFingerprint","storageKey","load","record","fingerprint","snapshot","reverify","safePublicKey","verdict","discard","scheduleDeadline","getCached","isFresh","cacheTtlMs","refresh","onError","accept","finally","settleRefresh","catch","clear","startAutoRefresh","intervalMs","max","stopAutoRefresh","schedule","offlineDeadline","deadlines","NaN","remaining","delayMs","generation","getPublicKey","onChange","hasPaidAccess","extensionGlobals","areaCall","direct","withCallback","reject","runtime","ExtensionStorage","area","cb","LocalStorageAdapter","store","getItem","setItem","removeItem","MemoryStorage","delete","createStorage","local","localStorage","createRecoveryStorage","extension","RecoveryManager","stopped","stop","id","secret","hash","digest","challenge","created","done","once","DEFAULT_API_URL","DEFAULT_CACHE_TTL_MS","MAX_CACHE_TTL_MS","VERSION","ENVIRONMENTS","LOG_LEVELS","THEME_MODES","LOCALE_RE","resolveConfig","errors","URL","protocol","isHttpUrl","environment","theme","mode","mock","mockData","EventEmitter","listeners","on","event","listener","off","fn","removeAll","ExtenshiPayLite","config","deps","emitter","endUserRefPromise","offerInflight","readyPromise","destroyed","reportError","checkout","recovery","recoveryStorage","onReady","version","initialize","doInitialize","afterReady","getCachedEntitlement","isPaid","requireFeature","onUnlock","unlocked","onFeatureLocked","onCancel","_feature","_options","openCheckout","restorePurchase","getLicenseSummary","fetchOffer","seller","recoveryEnabled","openCustomerPortal","accounts","selectAccount","onEntitlementChange","clearCache","destroy","BillingProfilePicker","dismiss","hide","show","host","createElement","className","root","attachShadow","style","textContent","dialog","setAttribute","description","append","showModal","finish","close","preventDefault","account","button","type","label","detail","recorded","createdAt","isNaN","getTime","toLocaleDateString","subscription","subscriptions","line","end","currentPeriodEnd","cancellation","cancelAtPeriodEnd","cancel","sellerDetails","section","displayName","link","href","username","password","publicContactUrl","target","rel","marginRight","supportUrl","termsUrl","role","MOCK_PAYMENT_NOTICE","DEFAULT_STRINGS","upgrade","remindLater","continueFree","checkoutUnavailable","periodMonth","periodYear","periodOnce","footer","LicensePanel","summary","actions","content","feedback","render","replaceChildren","note","empty","article","heading","date","expiry","toLocaleString","sub","row","freshness","closed","buttons","action","run","forEach","disabled","updated","restore","manage","formatPrice","amountMinor","currency","toUpperCase","formatter","Intl","NumberFormat","parts","formatToParts","part","amount","full","format","toFixed","periodLabel","strings","PAYWALL_SHARED_CSS","PAYWALL_TEMPLATES","modal","html","css","inline","sidebar","fullscreen","minimal","PAYWALL_MODES","keys","PAYWALL_HOST_CLASS","UPGRADE_ACTIONS","CLOSE_ACTIONS","ROOT_SELECTOR","BACKDROP_SELECTOR","VISIBLE_CLASSES","FEATURE_ITEM_VISIBLE","EMPTY_SLOT_MARK","FEATURE_KEY_RE","escapeHtml","substitute","_match","buildContent","view","price","brandName","period","pricingDescription","priceDescription","premiumDescription","upgradeButtonText","cancelButtonText","dismissButtonText","remindLaterText","continueButtonText","footerText","index","n","freeFeatures","CSS_VALUE_UNSAFE","themeCss","declarations","safe","primaryColor","color","fontFamily","borderRadius","radius","customCss","resolveThemeMode","matchMedia","matches","PaywallRenderer","callbacks","keyHandler","isVisible","template","innerHTML","prune","bind","sellerMount","querySelector","details","cssText","modalActions","before","notice","onRestore","appendChild","container","reveal","ownerDocument","element","querySelectorAll","mark","parentElement","closest","trim","getAttribute","onUpgrade","backdropSelector","currentTarget","rootElement","display","selector","classList","onClose","ExtenshiPay","disposed","licensePanel","billingProfiles","paywall","paywallSession","hidePaywall","showLicense","showPaywall","selected","candidate","pickOffer","renderer","settlePaywall","isPaywallVisible","handleUpgrade","handleRestore"],"mappings":";;;;;AAaO,MAAMA,EAAuB,EAEvBC,EAAe,CAAC,SAAU,SAAU,gBAUpCC,EAA6B,UAC7BC,EAAiC,GACxCC,EAAqB,IAAIC,OAC9B,IAAIH,kBAGC,SAAUI,EAAoBC,GACnC,MAAwB,iBAAVA,GAAsBH,EAAmBI,KAAKD,EAC7D,CAIO,MAAME,EAAkB,CAAC,WAAY,eAAgB,YAG/CC,EAAsB,CAAC,QAAS,QAIhCC,EAAiB,CAAC,MAAO,MAAO,OAIhCC,EAAa,6BAWbC,EAA2B,CAAC,SAAU,QAAS,UAAW,QAmF1DC,EAAsB,kEAGtBC,EAAa,CACzBC,qBAAsB,2BACtBC,kBAAmB,wBACnBC,mBAAoB,yBACpBC,gBAAiB,sBACjBC,YAAa,kBACbC,cAAe,oBACfC,oBAAqB,0BACrBC,aAAc,mBACdC,YAAa,mBASR,SAAUC,EAAclB,GAC7B,GAAc,OAAVA,GAAmC,iBAAVA,EAAoB,OAAOmB,KAAKC,UAAUpB,GACvE,GAAIqB,MAAMC,QAAQtB,GAAQ,MAAO,IAAIA,EAAMuB,IAAKC,GAASN,EAAcM,IAAOC,KAAK,QAInF,MAAO,IAHSC,OAAOC,QAAQ3B,GAC7B4B,OAAO,EAAC,CAAGC,UAAaC,IAAND,GAClBE,KAAK,EAAEC,IAAKC,KAAQD,EAAIC,GAAI,EAAKD,EAAIC,EAAI,EAAI,GAC5BV,IAAI,EAAEW,EAAGL,KAAO,GAAGV,KAAKC,UAAUc,MAAMhB,EAAcW,MAAMJ,KAAK,OACrF,CC1KO,MAAMU,EAAc,CAC1BC,eAAgB,iBAChBC,gBAAiB,kBACjBC,cAAe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K2kB,YAAY7kB,EAAQykB,SAAW,CAAA,GAC5C,CAEQ,QAAAQ,GAQP,OAPK/kB,KAAKukB,UACTvkB,KAAKukB,QAAU,IAAIvC,GAAgB,CAClC2B,UAAY/gB,IAAa5C,KAAKklB,cAActiB,IAC5CshB,QAAS,IAAMlkB,KAAKglB,eAAc,GAClCjC,UAAW,KAAW/iB,KAAKmlB,oBAGtBnlB,KAAKukB,OACb,CAEQ,mBAAMY,GACb,IACC,MAAM1b,QAAezJ,KAAKyX,kBACL,aAAjBhO,EAAOjG,OAAwB+J,EAAW9D,EAAOrF,eACpDpE,KAAKukB,SAASjM,OACdtY,KAAKglB,eAAc,GAErB,CAAE,MAEF,CACD,CAEQ,mBAAME,CAActiB,GAC3B5C,KAAKwkB,gBAAgB1kB,QAAQ6jB,YAAY/gB,GACzC,IAEsB,oBADA5C,KAAKwX,aAAa5U,IAC5BY,QACVxD,KAAKukB,SAASjM,OACdtY,KAAKglB,eAAc,GAErB,CAAE,MAEF,CACD,CAEQ,aAAAA,CAAc7N,GACrB,MAAM5T,EAAUvD,KAAKwkB,eAChBjhB,IACLvD,KAAKwkB,eAAiB,KACjBrN,GAAU5T,EAAQzD,QAAQokB,YAC/B3gB,EAAQkE,QAAQ0P,GACjB"}
1
+ {"version":3,"file":"extenshi-pay.min.mjs","sources":["../src/types/contract.ts","../src/types/errors.ts","../src/core/identity.ts","../src/api/mock.ts","../src/api/pay-api.ts","../src/utils/logger.ts","../src/api/transport.ts","../src/payment/checkout.ts","../src/payment/features.ts","../src/payment/signature.ts","../src/payment/entitlement.ts","../src/core/storage.ts","../src/payment/recovery.ts","../src/types/config.ts","../src/version.ts","../src/core/locale.ts","../src/core/config.ts","../src/core/event-emitter.ts","../src/paywall/i18n.ts","../src/payment/withdrawal-waiver.ts","../src/core/extenshi-pay.ts","../src/paywall/seller-details.ts","../src/paywall/license-panel.ts","../src/paywall/billing-profile-picker.ts","../src/paywall/format.ts","../src/paywall/strings.ts","../../extension_templates/paywall-templates/fullscreen/template.html","../src/paywall/templates.ts","../../extension_templates/paywall-templates/modal/template.html","../../extension_templates/paywall-templates/inline/template.html","../../extension_templates/paywall-templates/sidebar/template.html","../../extension_templates/paywall-templates/minimal/template.html","../src/paywall/renderer.ts","../src/extenshi-pay.ts"],"sourcesContent":["/**\n * Wire contract between the SDK and catalog-bff `pay.*`.\n *\n * SOURCE OF TRUTH: `shared-types/pay.ts` in the extenshi.io monorepo. The SDK\n * ships with zero runtime dependencies and must not import that workspace, so\n * the types and constants it needs are copied here under identical names.\n * `canonicalJson` is copied VERBATIM: the BFF signs its output and the SDK\n * verifies it, so both sides must produce byte-identical strings\n * (pinned by tests/unit/canonical-json.test.ts). When `shared-types/pay.ts`\n * changes, mirror the change here.\n */\n\n/** Bumped only when an older SDK could misread the response. */\nexport const PAY_CONTRACT_VERSION = 1\n\nexport const PAY_GATEWAYS = ['stripe', 'paddle', 'lemonsqueezy'] as const\nexport type PayGatewayId = (typeof PAY_GATEWAYS)[number]\n\n// ─── Publishable key ────────────────────────────────────────────────────────\n\n/**\n * The only credential an extension bundle carries. It is public by\n * construction (anyone can unzip the .crx), so it must grant nothing beyond\n * \"read this project's offer\" and \"start a checkout for this project\".\n */\nexport const PAY_PUBLISHABLE_KEY_PREFIX = 'pk_ext_'\nexport const PAY_PUBLISHABLE_KEY_HEX_LENGTH = 32\nconst PUBLISHABLE_KEY_RE = new RegExp(\n\t`^${PAY_PUBLISHABLE_KEY_PREFIX}[0-9a-f]{${PAY_PUBLISHABLE_KEY_HEX_LENGTH}}$`,\n)\n\nexport function isPayPublishableKey(value: unknown): value is string {\n\treturn typeof value === 'string' && PUBLISHABLE_KEY_RE.test(value)\n}\n\n// ─── Offers ─────────────────────────────────────────────────────────────────\n\nexport const PAY_OFFER_KINDS = ['one_time', 'subscription', 'lifetime'] as const\nexport type PayOfferKind = (typeof PAY_OFFER_KINDS)[number]\n\nexport const PAY_OFFER_INTERVALS = ['month', 'year'] as const\nexport type PayOfferInterval = (typeof PAY_OFFER_INTERVALS)[number]\n\n/** ISO-4217 lowercase, matching what every gateway returns. */\nexport const PAY_CURRENCIES = ['usd', 'eur', 'gbp'] as const\nexport type PayCurrency = (typeof PAY_CURRENCIES)[number]\n\n/** `sku` is author-chosen and stable; it is what `requireFeature()` keys on. */\nexport const PAY_SKU_RE = /^[a-z0-9][a-z0-9_-]{1,39}$/\n\n// ─── Projection ─────────────────────────────────────────────────────────────\n\n/**\n * active — paid and not expired\n * grace — subscription past_due: keep access for a short window so a card\n * hiccup does not lock a paying user out mid-session\n * expired — was active, no longer is\n * none — never had it\n */\nexport const PAY_ENTITLEMENT_STATUSES = ['active', 'grace', 'expired', 'none'] as const\nexport type PayEntitlementStatus = (typeof PAY_ENTITLEMENT_STATUSES)[number]\n\n// ─── SDK-facing DTOs (the `pay.*` tRPC contract) ────────────────────────────\n\nexport interface PayOfferDto {\n\tsku: string\n\tkind: PayOfferKind\n\tinterval: PayOfferInterval | null\n\tamountMinor: number\n\tcurrency: PayCurrency\n\ttitle: string\n\tdescription: string | null\n\tfeatures: string[]\n}\n\nexport interface PayOfferResponse {\n\t/** Optional during rolling upgrades; never infer this from the project name. */\n\tseller?: PaySellerPublic | null\n\n\tv: typeof PAY_CONTRACT_VERSION\n\tprojectName: string\n\tprovider: PayGatewayId\n\t/** False while the seller cannot take money; the SDK renders the offer read-only. */\n\tcheckoutEnabled: boolean\n\t/** Optional for older servers; show recovery only when explicitly enabled. */\n\trecoveryEnabled?: boolean\n\toffers: PayOfferDto[]\n\t/** Base64 Ed25519 public key for `SignedEntitlement.signature`; null when unsigned. */\n\tentitlementPublicKey: string | null\n\t/**\n\t * The language the offers' text is in when the seller translated them\n\t * (it. 13 T10 L2); absent from older servers and for single-language offers.\n\t */\n\tlocale?: string\n\t/**\n\t * Set when the paywall must show an unticked withdrawal-waiver checkbox and\n\t * send the accepted `version` with `createCheckout`. Null when the seller\n\t * attested the extension is not distributed in the EEA/UK; absent from\n\t * older servers (the SDK then shows no checkbox).\n\t */\n\twithdrawalWaiver?: PayWithdrawalWaiver | null\n}\n\n/**\n * Version of the buyer-facing withdrawal waiver text the paywall shows (EU/EEA\n * digital content, Directive 2011/83/EU art. 16(m); UK CCR 2013 reg. 37). The\n * text itself lives in the SDK dictionary under the same version; bump both\n * together so a recorded consent always names the words the buyer saw.\n */\nexport const PAY_WITHDRAWAL_WAIVER_VERSION = '2026-10-v1'\n\nexport interface PayWithdrawalWaiver {\n\tversion: string\n}\n\nexport interface PayEntitlementItem {\n\t/** Optional for old signed caches and older servers. */\n\ttitle?: string\n\tkind?: PayOfferKind\n\tsubscriptions?: Array<{\n\t\tstatus: string\n\t\tcancelAtPeriodEnd: boolean\n\t\tcurrentPeriodEnd: string | null\n\t}>\n\n\tsku: string\n\tstatus: PayEntitlementStatus\n\t/** ISO timestamp; null for lifetime / one-time grants. */\n\texpiresAt: string | null\n\tfeatures: string[]\n}\n\nexport interface PayEntitlementPayload {\n\tv: typeof PAY_CONTRACT_VERSION\n\t/** Signed application scope; prevents moving a grant to another application. */\n\tpublishableKey: string\n\tendUserRef: string\n\tentitlements: PayEntitlementItem[]\n\t/** ISO timestamp the projection was computed at; the SDK uses it for cache age. */\n\tissuedAt: string\n}\n\nexport interface SignedEntitlement {\n\tpayload: PayEntitlementPayload\n\t/** Base64 Ed25519 signature over the canonical JSON of `payload`; null when the server has no key. */\n\tsignature: string | null\n\talg: 'ed25519' | null\n}\n\nexport type PayCheckoutClaim =\n\t| { state: 'pending' }\n\t| { state: 'complete'; entitlement: SignedEntitlement }\n\t| { state: 'expired' }\n\t| { state: 'canceled' }\n\nexport interface PayCheckoutSession {\n\turl: string\n\tsessionId: string\n\t/** ISO timestamp. */\n\texpiresAt: string\n}\n\n/**\n * The `endUserRef` an SDK mints on first run and keeps in `chrome.storage`.\n * Opaque, random, never derived from anything identifying.\n */\nexport const PAY_END_USER_REF_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n/** Typed error codes the BFF throws; dojo and the SDK match on `cause.code`. */\nexport const PAY_ERRORS = {\n\tSELLER_NOT_CONNECTED: 'PAY_SELLER_NOT_CONNECTED',\n\tSELLER_NOT_ACTIVE: 'PAY_SELLER_NOT_ACTIVE',\n\tAGREEMENT_REQUIRED: 'PAY_AGREEMENT_REQUIRED',\n\tOFFER_NOT_FOUND: 'PAY_OFFER_NOT_FOUND',\n\tOFFER_LIMIT: 'PAY_OFFER_LIMIT',\n\tPRICE_TOO_LOW: 'PAY_PRICE_TOO_LOW',\n\tGATEWAY_UNAVAILABLE: 'PAY_GATEWAY_UNAVAILABLE',\n\tRATE_LIMITED: 'PAY_RATE_LIMITED',\n\tINVALID_KEY: 'PAY_INVALID_KEY',\n\tWITHDRAWAL_WAIVER_REQUIRED: 'PAY_WITHDRAWAL_WAIVER_REQUIRED',\n} as const\nexport type PayErrorCode = (typeof PAY_ERRORS)[keyof typeof PAY_ERRORS]\n\n/**\n * Canonical JSON for signing: keys sorted recursively, no whitespace. Both\n * the BFF (sign) and the SDK (verify) must produce byte-identical output for\n * the same payload, so the rule lives in the shared contract.\n */\nexport function canonicalJson(value: unknown): string {\n\tif (value === null || typeof value !== 'object') return JSON.stringify(value)\n\tif (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(',')}]`\n\tconst entries = Object.entries(value as Record<string, unknown>)\n\t\t.filter(([, v]) => v !== undefined)\n\t\t.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n\treturn `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`\n}\n\nexport interface PayRestoreSessionResponse {\n\tsessionId: string\n\texpiresAt: string\n\turl: string\n}\nexport type PayRestoreClaimResponse =\n\t| { state: 'pending' }\n\t| { state: 'complete'; endUserRef: string; entitlement: SignedEntitlement }\n\n/** A project-scoped billing profile; provider identifiers are never exposed. */\nexport interface PayPortalAccount {\n\tid: string\n\tlabel: string\n\tcreatedAt: string\n\tsubscriptions: Array<{\n\t\ttitle: string\n\t\tstatus: string\n\t\tcancelAtPeriodEnd: boolean\n\t\tcurrentPeriodEnd: string | null\n\t}>\n}\n\nexport interface PayPortalResponse {\n\turl: string | null\n\t/** Present when the buyer must choose among multiple billing profiles. */\n\taccounts?: PayPortalAccount[]\n}\n\n/** Public author-provided contact details. Not a claim of identity verification. */\nexport interface PaySellerPublic {\n\tdisplayName: string\n\t/** HTTPS support page or plain email address. */\n\tsupportUrl: string\n\ttermsUrl: string | null\n\t/** Optional for older servers: refunds section of the license terms. */\n\trefundPolicyUrl?: string | null\n}\n","export const ERROR_CODES = {\n\tINVALID_CONFIG: 'INVALID_CONFIG',\n\tINVALID_REQUEST: 'INVALID_REQUEST',\n\tNETWORK_ERROR: 'NETWORK_ERROR',\n\tTIMEOUT: 'TIMEOUT',\n\tVERIFICATION_UNAVAILABLE: 'VERIFICATION_UNAVAILABLE',\n\tINVALID_RESPONSE: 'INVALID_RESPONSE',\n\tRATE_LIMITED: 'RATE_LIMITED',\n\tINVALID_KEY: 'INVALID_KEY',\n\tSELLER_NOT_ACTIVE: 'SELLER_NOT_ACTIVE',\n\tOFFER_NOT_FOUND: 'OFFER_NOT_FOUND',\n\tGATEWAY_UNAVAILABLE: 'GATEWAY_UNAVAILABLE',\n\tCHECKOUT_UNAVAILABLE: 'CHECKOUT_UNAVAILABLE',\n\tPAYWALL_UNAVAILABLE: 'PAYWALL_UNAVAILABLE',\n\tWITHDRAWAL_WAIVER_REQUIRED: 'WITHDRAWAL_WAIVER_REQUIRED',\n\tUNKNOWN: 'UNKNOWN',\n} as const\n\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES]\n\nexport interface ExtenshiPayErrorOptions {\n\tretryAfterSec?: number\n\thttpStatus?: number\n\tcause?: unknown\n}\n\nexport class ExtenshiPayError extends Error {\n\treadonly code: ErrorCode\n\treadonly retryAfterSec: number | undefined\n\treadonly httpStatus: number | undefined\n\treadonly cause: unknown\n\n\tconstructor(code: ErrorCode, message: string, options: ExtenshiPayErrorOptions = {}) {\n\t\tsuper(message)\n\t\tthis.name = 'ExtenshiPayError'\n\t\tthis.code = code\n\t\tthis.retryAfterSec = options.retryAfterSec\n\t\tthis.httpStatus = options.httpStatus\n\t\tthis.cause = options.cause\n\t}\n\n\tstatic from(error: unknown, fallback: ErrorCode = ERROR_CODES.UNKNOWN): ExtenshiPayError {\n\t\tif (error instanceof ExtenshiPayError) return error\n\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\treturn new ExtenshiPayError(fallback, message, { cause: error })\n\t}\n}\n","/**\n * `endUserRef` — the only identity the SDK has.\n *\n * A random UUID minted on first run and kept in the SDK's storage namespace.\n * It is never derived from anything identifying (no fingerprint, no e-mail,\n * no extension-supplied user id) and remains the installation identifier. Explicit recovery also sends a\n * random session ID and proof; it never derives identity from an email locally.\n */\n\nimport { PAY_END_USER_REF_RE } from '../types/contract.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { StorageAdapter } from './storage.js'\n\nexport const END_USER_REF_STORAGE_KEY = 'extenshi-pay:endUserRef'\n\nexport function mintEndUserRef(): string {\n\tconst cryptoApi = (globalThis as { crypto?: Crypto }).crypto\n\tif (!cryptoApi) {\n\t\tthrow new ExtenshiPayError(ERROR_CODES.UNKNOWN, 'Web Crypto is not available in this context')\n\t}\n\tif (typeof cryptoApi.randomUUID === 'function') return cryptoApi.randomUUID()\n\tconst bytes = cryptoApi.getRandomValues(new Uint8Array(16))\n\tbytes[6] = (bytes[6] & 0x0f) | 0x40\n\tbytes[8] = (bytes[8] & 0x3f) | 0x80\n\tconst hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')\n\treturn `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`\n}\n\nexport async function getOrCreateEndUserRef(storage: StorageAdapter): Promise<string> {\n\tconst existing = await storage.get(END_USER_REF_STORAGE_KEY)\n\tif (typeof existing === 'string' && PAY_END_USER_REF_RE.test(existing)) return existing\n\tconst ref = mintEndUserRef()\n\tawait storage.set(END_USER_REF_STORAGE_KEY, ref)\n\treturn ref\n}\n","/**\n * In-memory stand-in for the BFF, used when `mock: true`. Lets an extension be\n * developed with no backend: offers and entitlements come from `mockData`, a\n * mock checkout completes after `claimAfterPolls` polls and grants the SKU.\n */\n\nimport { mintEndUserRef } from '../core/identity.js'\nimport type { MockData } from '../types/config.js'\nimport {\n\tPAY_CONTRACT_VERSION,\n\tPAY_WITHDRAWAL_WAIVER_VERSION,\n\ttype PayCheckoutClaim,\n\ttype PayEntitlementItem,\n\ttype PayOfferDto,\n\ttype PayOfferResponse,\n\ttype PayWithdrawalWaiver,\n\ttype SignedEntitlement,\n} from '../types/contract.js'\nimport type { WithdrawalWaiverConsent } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { ProcedureKind, Transport } from './transport.js'\n\ntype SessionState = 'open' | 'complete' | 'canceled' | 'expired'\n\ninterface MockSession {\n\tsku: string\n\tpolls: number\n\tstate: SessionState\n\t/** What `createCheckout` received, for inspecting the consent in dev/tests. */\n\twithdrawalWaiver: WithdrawalWaiverConsent | null\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000\n\n/** Accepts the same optional `withdrawalWaiver` input as the BFF; anything else is no consent. */\nfunction mockConsent(value: unknown): WithdrawalWaiverConsent | null {\n\tconst consent = value as Partial<WithdrawalWaiverConsent> | null | undefined\n\treturn consent && typeof consent.version === 'string' && consent.accepted === true\n\t\t? { version: consent.version, accepted: true }\n\t\t: null\n}\n\nexport class MockTransport implements Transport {\n\tprivate entitlements: PayEntitlementItem[]\n\tprivate readonly offers: PayOfferDto[]\n\tprivate readonly projectName: string\n\tprivate readonly checkoutEnabled: boolean\n\tprivate readonly claimAfterPolls: number\n\tprivate readonly withdrawalWaiver: PayWithdrawalWaiver | null\n\treadonly sessions = new Map<string, MockSession>()\n\n\tconstructor(data: MockData = {}) {\n\t\tthis.entitlements = [...(data.entitlements ?? [])]\n\t\tthis.offers = [...(data.offers ?? [])]\n\t\tthis.projectName = data.projectName ?? 'Mock project'\n\t\tthis.checkoutEnabled = data.checkoutEnabled ?? true\n\t\tthis.claimAfterPolls = data.claimAfterPolls ?? 1\n\t\tthis.withdrawalWaiver =\n\t\t\tdata.withdrawalWaiver === undefined ? { version: PAY_WITHDRAWAL_WAIVER_VERSION } : data.withdrawalWaiver\n\t}\n\n\tasync call<T>(procedure: string, _kind: ProcedureKind, input: Record<string, unknown>): Promise<T> {\n\t\tswitch (procedure) {\n\t\t\tcase 'pay.getOffer':\n\t\t\t\treturn this.offerResponse() as T\n\t\t\tcase 'pay.createCheckout':\n\t\t\t\treturn this.createCheckout(String(input.sku), mockConsent(input.withdrawalWaiver)) as T\n\t\t\tcase 'pay.claimSession':\n\t\t\t\treturn this.claim(\n\t\t\t\t\tString(input.sessionId),\n\t\t\t\t\tString(input.endUserRef),\n\t\t\t\t\tString(input.publishableKey),\n\t\t\t\t) as T\n\t\t\tcase 'pay.getEntitlement':\n\t\t\t\treturn this.envelope(String(input.endUserRef), String(input.publishableKey)) as T\n\t\t\tcase 'pay.getPortalUrl':\n\t\t\t\treturn { url: this.entitlements.length > 0 ? 'https://mock.extenshi.io/portal' : null } as T\n\t\t\tdefault:\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, `Unknown procedure ${procedure}`)\n\t\t}\n\t}\n\n\t/** Test/dev helpers. */\n\tsetEntitlements(items: PayEntitlementItem[]): void {\n\t\tthis.entitlements = [...items]\n\t}\n\n\tcancelSession(sessionId: string): void {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (session) session.state = 'canceled'\n\t}\n\n\texpireSession(sessionId: string): void {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (session) session.state = 'expired'\n\t}\n\n\tprivate offerResponse(): PayOfferResponse {\n\t\treturn {\n\t\t\tv: PAY_CONTRACT_VERSION,\n\t\t\tprojectName: this.projectName,\n\t\t\tprovider: 'stripe',\n\t\t\tcheckoutEnabled: this.checkoutEnabled && this.offers.length > 0,\n\t\t\toffers: [...this.offers],\n\t\t\tentitlementPublicKey: null,\n\t\t\twithdrawalWaiver: this.withdrawalWaiver ? { ...this.withdrawalWaiver } : null,\n\t\t}\n\t}\n\n\tprivate createCheckout(sku: string, withdrawalWaiver: WithdrawalWaiverConsent | null) {\n\t\tif (!this.checkoutEnabled) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.SELLER_NOT_ACTIVE, 'Mock seller cannot take payments')\n\t\t}\n\t\tif (!this.offers.some((offer) => offer.sku === sku)) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.OFFER_NOT_FOUND, `Unknown mock offer ${sku}`)\n\t\t}\n\t\tconst sessionId = mintEndUserRef()\n\t\tthis.sessions.set(sessionId, { sku, polls: 0, state: 'open', withdrawalWaiver })\n\t\treturn {\n\t\t\turl: `https://mock.extenshi.io/checkout/${sessionId}`,\n\t\t\tsessionId,\n\t\t\texpiresAt: new Date(Date.now() + 30 * 60 * 1000).toISOString(),\n\t\t}\n\t}\n\n\tprivate claim(sessionId: string, endUserRef: string, publishableKey: string): PayCheckoutClaim {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) throw new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, 'Unknown checkout session')\n\t\tif (session.state === 'canceled') return { state: 'canceled' }\n\t\tif (session.state === 'expired') return { state: 'expired' }\n\t\tif (session.state === 'open') {\n\t\t\tsession.polls += 1\n\t\t\tif (session.polls <= this.claimAfterPolls) return { state: 'pending' }\n\t\t\tsession.state = 'complete'\n\t\t\tthis.grant(session.sku)\n\t\t}\n\t\treturn { state: 'complete', entitlement: this.envelope(endUserRef, publishableKey) }\n\t}\n\n\tprivate grant(sku: string): void {\n\t\tconst offer = this.offers.find((o) => o.sku === sku)\n\t\tconst expiresAt =\n\t\t\toffer?.kind === 'subscription'\n\t\t\t\t? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS).toISOString()\n\t\t\t\t: null\n\t\tthis.entitlements = [\n\t\t\t...this.entitlements.filter((item) => item.sku !== sku),\n\t\t\t{\n\t\t\t\tsku,\n\t\t\t\ttitle: offer?.title,\n\t\t\t\tkind: offer?.kind,\n\t\t\t\tstatus: 'active',\n\t\t\t\texpiresAt,\n\t\t\t\tfeatures: offer?.features ?? [],\n\t\t\t},\n\t\t]\n\t}\n\n\tprivate envelope(endUserRef: string, publishableKey: string): SignedEntitlement {\n\t\treturn {\n\t\t\tpayload: {\n\t\t\t\tv: PAY_CONTRACT_VERSION,\n\t\t\t\tpublishableKey,\n\t\t\t\tendUserRef,\n\t\t\t\tentitlements: [...this.entitlements],\n\t\t\t\tissuedAt: new Date().toISOString(),\n\t\t\t},\n\t\t\tsignature: null,\n\t\t\talg: null,\n\t\t}\n\t}\n}\n","/** Typed wrapper over the SDK-facing `pay.*` procedures. Nothing else is ever called. */\n\nimport type {\n\tPayCheckoutClaim,\n\tPayCheckoutSession,\n\tPayOfferResponse,\n\tPayPortalResponse,\n\tPayRestoreClaimResponse,\n\tPayRestoreSessionResponse,\n\tSignedEntitlement,\n} from '../types/contract.js'\nimport type { WithdrawalWaiverConsent } from '../types/entitlement.js'\nimport type { Transport } from './transport.js'\n\nexport class PayApi {\n\tconstructor(\n\t\tprivate readonly transport: Transport,\n\t\tprivate readonly publishableKey: string,\n\t) {}\n\n\t/** `locale` opens the hosted recovery page (and its email) in the user's language. */\n\tcreateRestoreSession(claimChallenge: string, locale?: string | null): Promise<PayRestoreSessionResponse> {\n\t\treturn this.transport.call('pay.createRestoreSession', 'mutation', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tclaimChallenge,\n\t\t\t...(locale ? { locale } : {}),\n\t\t})\n\t}\n\n\tclaimRestoreSession(sessionId: string, claimSecret: string): Promise<PayRestoreClaimResponse> {\n\t\treturn this.transport.call('pay.claimRestoreSession', 'mutation', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tsessionId,\n\t\t\tclaimSecret,\n\t\t})\n\t}\n\n\tgetOffer(locale?: string | null): Promise<PayOfferResponse> {\n\t\treturn this.transport.call('pay.getOffer', 'query', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tlocale: locale ?? undefined,\n\t\t})\n\t}\n\n\t/**\n\t * `withdrawalWaiver` is sent only when given. Older BFFs parse the input with\n\t * a non-strict zod object, which strips the unknown key, so it is safe there.\n\t * Plain-JS callers passing anything but `accepted: true` send no consent.\n\t */\n\tcreateCheckout(\n\t\tsku: string,\n\t\tendUserRef: string,\n\t\tlocale?: string | null,\n\t\twithdrawalWaiver?: WithdrawalWaiverConsent,\n\t): Promise<PayCheckoutSession> {\n\t\treturn this.transport.call('pay.createCheckout', 'mutation', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tsku,\n\t\t\tendUserRef,\n\t\t\tlocale: locale ?? undefined,\n\t\t\t...(withdrawalWaiver?.accepted === true && typeof withdrawalWaiver.version === 'string'\n\t\t\t\t? { withdrawalWaiver: { version: withdrawalWaiver.version, accepted: true } }\n\t\t\t\t: {}),\n\t\t})\n\t}\n\n\tclaimSession(sessionId: string, endUserRef: string): Promise<PayCheckoutClaim> {\n\t\treturn this.transport.call('pay.claimSession', 'query', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tsessionId,\n\t\t\tendUserRef,\n\t\t})\n\t}\n\n\tgetEntitlement(endUserRef: string): Promise<SignedEntitlement> {\n\t\treturn this.transport.call('pay.getEntitlement', 'query', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tendUserRef,\n\t\t})\n\t}\n\n\tgetPortalUrl(endUserRef: string, customerId?: string, locale?: string | null): Promise<PayPortalResponse> {\n\t\treturn this.transport.call('pay.getPortalUrl', 'mutation', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tendUserRef,\n\t\t\t...(customerId ? { customerId } : {}),\n\t\t\t...(locale ? { locale } : {}),\n\t\t})\n\t}\n}\n","import type { LogLevel } from '../types/config.js'\n\nconst ORDER: Record<LogLevel, number> = { silent: 0, error: 1, warn: 2, info: 3, debug: 4 }\n\nexport class Logger {\n\tprivate level: LogLevel = 'warn'\n\tprivate readonly prefix = '[ExtenshiPay]'\n\n\tconfigure(options: { logLevel?: LogLevel; debug?: boolean }): void {\n\t\tif (options.logLevel) this.level = options.logLevel\n\t\tif (options.debug) this.level = 'debug'\n\t}\n\n\terror(message: string, ...args: unknown[]): void {\n\t\tif (this.enabled('error')) console.error(this.prefix, message, ...args)\n\t}\n\n\twarn(message: string, ...args: unknown[]): void {\n\t\tif (this.enabled('warn')) console.warn(this.prefix, message, ...args)\n\t}\n\n\tinfo(message: string, ...args: unknown[]): void {\n\t\tif (this.enabled('info')) console.info(this.prefix, message, ...args)\n\t}\n\n\tdebug(message: string, ...args: unknown[]): void {\n\t\tif (this.enabled('debug')) console.debug(this.prefix, message, ...args)\n\t}\n\n\tprivate enabled(level: LogLevel): boolean {\n\t\treturn ORDER[level] <= ORDER[this.level]\n\t}\n}\n\nexport const logger = new Logger()\n","/**\n * HTTP transport for the BFF's tRPC endpoint (`/api/trpc/<procedure>`).\n *\n * Queries are header-less GETs with `?input=<json>` (a CORS \"simple request\",\n * so no preflight); mutations POST a JSON body. The only things that leave the\n * extension are payment inputs and optional recovery session/proof inputs\n * and the browser's standard headers — `credentials: 'omit'` keeps cookies out.\n * Queries are retried on network / 5xx errors; mutations never are.\n */\n\nimport { PAY_ERRORS } from '../types/contract.js'\nimport { ERROR_CODES, type ErrorCode, ExtenshiPayError } from '../types/errors.js'\nimport { logger } from '../utils/logger.js'\n\nexport type ProcedureKind = 'query' | 'mutation'\n\nexport interface Transport {\n\tcall<T>(procedure: string, kind: ProcedureKind, input: Record<string, unknown>): Promise<T>\n}\n\nexport interface HttpTransportOptions {\n\tapiUrl: string\n\t/** Per-attempt timeout (default 10 s). */\n\ttimeoutMs?: number\n\t/** Extra attempts for queries (default 1). */\n\tretries?: number\n\tfetchImpl?: typeof fetch\n}\n\nexport const TRPC_PATH = '/api/trpc'\nconst DEFAULT_TIMEOUT_MS = 10_000\nconst DEFAULT_RETRIES = 1\nconst RETRY_BASE_MS = 500\n\ninterface TrpcErrorShape {\n\tmessage?: string\n\tcode?: number\n\tdata?: {\n\t\tcode?: string\n\t\thttpStatus?: number\n\t\tcause?: { code?: string; retryAfterSec?: number }\n\t}\n}\n\ninterface TrpcEnvelope<T> {\n\tresult?: { data?: T }\n\terror?: TrpcErrorShape\n}\n\nconst RETRYABLE: ReadonlySet<ErrorCode> = new Set([\n\tERROR_CODES.NETWORK_ERROR,\n\tERROR_CODES.TIMEOUT,\n\tERROR_CODES.GATEWAY_UNAVAILABLE,\n])\n\n/** `PAY_*` cause codes, when the BFF forwards them, map 1:1. */\nconst CAUSE_TO_CODE: Record<string, ErrorCode> = {\n\t[PAY_ERRORS.RATE_LIMITED]: ERROR_CODES.RATE_LIMITED,\n\t[PAY_ERRORS.INVALID_KEY]: ERROR_CODES.INVALID_KEY,\n\t[PAY_ERRORS.SELLER_NOT_CONNECTED]: ERROR_CODES.SELLER_NOT_ACTIVE,\n\t[PAY_ERRORS.SELLER_NOT_ACTIVE]: ERROR_CODES.SELLER_NOT_ACTIVE,\n\t[PAY_ERRORS.AGREEMENT_REQUIRED]: ERROR_CODES.SELLER_NOT_ACTIVE,\n\t[PAY_ERRORS.OFFER_NOT_FOUND]: ERROR_CODES.OFFER_NOT_FOUND,\n\t[PAY_ERRORS.GATEWAY_UNAVAILABLE]: ERROR_CODES.GATEWAY_UNAVAILABLE,\n\t[PAY_ERRORS.WITHDRAWAL_WAIVER_REQUIRED]: ERROR_CODES.WITHDRAWAL_WAIVER_REQUIRED,\n}\n\nfunction parseRetryAfter(message: string): number | undefined {\n\tconst match = /retry in (\\d+)s/i.exec(message)\n\treturn match ? Number(match[1]) : undefined\n}\n\n/**\n * The BFF's error formatter does not forward `cause` for `pay.*` errors, so the\n * tRPC code + message is the primary signal; `data.cause.code` is honoured when\n * present so a future BFF that forwards it needs no SDK change.\n */\nexport function trpcErrorToPayError(error: TrpcErrorShape, httpStatus?: number): ExtenshiPayError {\n\tconst message = error.message ?? 'Request failed'\n\tconst trpcCode = error.data?.code ?? ''\n\tconst causeCode = error.data?.cause?.code\n\tconst retryAfterSec = error.data?.cause?.retryAfterSec ?? parseRetryAfter(message)\n\tconst options = { retryAfterSec, httpStatus: error.data?.httpStatus ?? httpStatus }\n\n\tconst mapped = causeCode ? CAUSE_TO_CODE[causeCode] : undefined\n\tif (mapped) return new ExtenshiPayError(mapped, message, options)\n\n\tswitch (trpcCode) {\n\t\tcase 'TOO_MANY_REQUESTS':\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, message, options)\n\t\tcase 'NOT_FOUND':\n\t\t\tif (/publishable key/i.test(message))\n\t\t\t\treturn new ExtenshiPayError(ERROR_CODES.INVALID_KEY, message, options)\n\t\t\tif (/session/i.test(message))\n\t\t\t\treturn new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, message, options)\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.OFFER_NOT_FOUND, message, options)\n\t\tcase 'PRECONDITION_FAILED':\n\t\t\tif (/withdrawal/i.test(message))\n\t\t\t\treturn new ExtenshiPayError(ERROR_CODES.WITHDRAWAL_WAIVER_REQUIRED, message, options)\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.SELLER_NOT_ACTIVE, message, options)\n\t\tcase 'BAD_REQUEST':\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, message, options)\n\t\tcase 'INTERNAL_SERVER_ERROR':\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, message, options)\n\t\tdefault:\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.UNKNOWN, message, options)\n\t}\n}\n\nfunction sleep(ms: number): Promise<void> {\n\treturn new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nexport class HttpTransport implements Transport {\n\tprivate readonly apiUrl: string\n\tprivate readonly timeoutMs: number\n\tprivate readonly retries: number\n\tprivate readonly fetchImpl: typeof fetch\n\n\tconstructor(options: HttpTransportOptions) {\n\t\tthis.apiUrl = options.apiUrl.replace(/\\/+$/, '')\n\t\tthis.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n\t\tthis.retries = options.retries ?? DEFAULT_RETRIES\n\t\tthis.fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init))\n\t}\n\n\tasync call<T>(procedure: string, kind: ProcedureKind, input: Record<string, unknown>): Promise<T> {\n\t\tconst base = `${this.apiUrl}${TRPC_PATH}/${procedure}`\n\t\tconst url = kind === 'query' ? `${base}?input=${encodeURIComponent(JSON.stringify(input))}` : base\n\t\tconst attempts = kind === 'query' ? this.retries + 1 : 1\n\t\tlet lastError: ExtenshiPayError | null = null\n\t\tfor (let attempt = 0; attempt < attempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn await this.request<T>(url, kind, input)\n\t\t\t} catch (error) {\n\t\t\t\tconst err = ExtenshiPayError.from(error)\n\t\t\t\tif (!RETRYABLE.has(err.code) || attempt === attempts - 1) throw err\n\t\t\t\tlastError = err\n\t\t\t\tlogger.debug(`${procedure} failed (${err.code}), retrying`)\n\t\t\t\tawait sleep(RETRY_BASE_MS * 2 ** attempt)\n\t\t\t}\n\t\t}\n\t\tthrow lastError ?? new ExtenshiPayError(ERROR_CODES.UNKNOWN, `${procedure} failed`)\n\t}\n\n\tprivate async request<T>(url: string, kind: ProcedureKind, input: Record<string, unknown>): Promise<T> {\n\t\tconst controller = typeof AbortController === 'function' ? new AbortController() : null\n\t\tconst timer = controller ? setTimeout(() => controller.abort(), this.timeoutMs) : null\n\t\tlet response: Response\n\t\ttry {\n\t\t\tresponse = await this.fetchImpl(url, {\n\t\t\t\tmethod: kind === 'query' ? 'GET' : 'POST',\n\t\t\t\theaders: kind === 'mutation' ? { 'Content-Type': 'application/json' } : undefined,\n\t\t\t\tbody: kind === 'mutation' ? JSON.stringify(input) : undefined,\n\t\t\t\tsignal: controller?.signal,\n\t\t\t\tcredentials: 'omit',\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tif (controller?.signal.aborted) {\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${this.timeoutMs}ms`)\n\t\t\t}\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error })\n\t\t} finally {\n\t\t\tif (timer !== null) clearTimeout(timer)\n\t\t}\n\n\t\tlet body: TrpcEnvelope<T> | null = null\n\t\ttry {\n\t\t\tbody = (await response.json()) as TrpcEnvelope<T>\n\t\t} catch {\n\t\t\tbody = null\n\t\t}\n\t\tif (body?.error) throw trpcErrorToPayError(body.error, response.status)\n\t\tif (!response.ok) {\n\t\t\tconst code = response.status >= 500 ? ERROR_CODES.GATEWAY_UNAVAILABLE : ERROR_CODES.INVALID_RESPONSE\n\t\t\tthrow new ExtenshiPayError(code, `HTTP ${response.status}`, { httpStatus: response.status })\n\t\t}\n\t\tif (!body?.result || !('data' in body.result)) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Malformed response from the payment backend')\n\t\t}\n\t\treturn body.result.data as T\n\t}\n}\n","/**\n * Hosted checkout flow.\n *\n * `pay.createCheckout` returns a URL on the seller's provider; the SDK opens\n * it in a new tab (`chrome.tabs.create`, falling back to `window.open`) and\n * polls `pay.claimSession` every 2 s for up to 10 min — and immediately when\n * the extension regains focus — until the webhook has landed. A pending\n * session is persisted so a restarted service worker / reopened popup can\n * finish the claim on the next `initialize()`.\n */\n\nimport type { PayApi } from '../api/pay-api.js'\nimport type { StorageAdapter } from '../core/storage.js'\nimport type { PayCheckoutClaim, SignedEntitlement } from '../types/contract.js'\nimport type { CheckoutOptions, CheckoutResult, Entitlement } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { ExtenshiPayEvents } from '../types/events.js'\nimport { logger } from '../utils/logger.js'\n\nexport const CHECKOUT_POLL_INTERVAL_MS = 2_000\nexport const CHECKOUT_TIMEOUT_MS = 10 * 60 * 1000\nconst MAX_ERROR_BACKOFF_MS = 30_000\n/** How long after `expiresAt` a persisted session is still worth one claim (webhook lag). */\nconst PENDING_GRACE_MS = 60 * 60 * 1000\n\ninterface PendingCheckout {\n\tsessionId: string\n\tsku: string\n\texpiresAt: string\n}\n\ntype OpenUrl = (url: string) => void | Promise<void>\ntype Emit = <K extends keyof ExtenshiPayEvents>(event: K, payload: ExtenshiPayEvents[K]) => void\n\nexport interface CheckoutManagerOptions {\n\tapi: PayApi\n\tstorage: StorageAdapter\n\tpublishableKey: string\n\tlocale: string | null\n\tgetEndUserRef: () => Promise<string>\n\t/** Verifies + stores the envelope from a completed session. */\n\tonComplete: (envelope: SignedEntitlement) => Promise<Entitlement>\n\temit: Emit\n\topenUrl?: OpenUrl\n\tnow?: () => number\n}\n\ninterface TabsApi {\n\tcreate(properties: { url: string }): unknown\n}\n\ninterface FocusGlobals {\n\tchrome?: { tabs?: TabsApi; windows?: { onFocusChanged?: FocusEvent } }\n\tbrowser?: { tabs?: TabsApi }\n\topen?: (url: string, target: string, features: string) => unknown\n\taddEventListener?: (type: string, listener: () => void) => void\n\tremoveEventListener?: (type: string, listener: () => void) => void\n\tdocument?: Document\n}\n\ninterface FocusEvent {\n\taddListener(listener: (windowId: number) => void): void\n\tremoveListener(listener: (windowId: number) => void): void\n}\n\nexport async function openInNewTab(url: string): Promise<void> {\n\tconst g = globalThis as FocusGlobals\n\tconst tabs = g.chrome?.tabs ?? g.browser?.tabs\n\tif (tabs && typeof tabs.create === 'function') {\n\t\tconst result = tabs.create({ url })\n\t\tif (result && typeof (result as Promise<unknown>).then === 'function') await result\n\t\treturn\n\t}\n\tif (typeof g.open === 'function') {\n\t\tg.open(url, '_blank', 'noopener,noreferrer')\n\t\treturn\n\t}\n\tthrow new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, 'Cannot open a checkout tab from this context')\n}\n\n/** Calls `onFocus` whenever the extension window/tab regains focus; returns a disposer. */\nfunction onFocusRegained(onFocus: () => void): () => void {\n\tconst g = globalThis as FocusGlobals\n\tconst disposers: Array<() => void> = []\n\tif (typeof g.addEventListener === 'function' && typeof g.removeEventListener === 'function') {\n\t\tg.addEventListener('focus', onFocus)\n\t\tdisposers.push(() => g.removeEventListener?.('focus', onFocus))\n\t}\n\tconst doc = g.document\n\tif (doc && typeof doc.addEventListener === 'function') {\n\t\tconst onVisible = () => {\n\t\t\tif (doc.visibilityState === 'visible') onFocus()\n\t\t}\n\t\tdoc.addEventListener('visibilitychange', onVisible)\n\t\tdisposers.push(() => doc.removeEventListener('visibilitychange', onVisible))\n\t}\n\tconst windows = g.chrome?.windows?.onFocusChanged\n\tif (windows && typeof windows.addListener === 'function') {\n\t\tconst onWindow = (windowId: number) => {\n\t\t\tif (windowId !== -1) onFocus()\n\t\t}\n\t\twindows.addListener(onWindow)\n\t\tdisposers.push(() => windows.removeListener(onWindow))\n\t}\n\treturn () => {\n\t\tfor (const dispose of disposers) dispose()\n\t}\n}\n\n/** A sleep that can be cut short by `wake()`. */\nfunction interruptibleSleep() {\n\tlet wake: (() => void) | null = null\n\treturn {\n\t\tsleep(ms: number): Promise<void> {\n\t\t\treturn new Promise<void>((resolve) => {\n\t\t\t\tconst timer = setTimeout(() => {\n\t\t\t\t\twake = null\n\t\t\t\t\tresolve()\n\t\t\t\t}, ms)\n\t\t\t\twake = () => {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\twake = null\n\t\t\t\t\tresolve()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\twake(): void {\n\t\t\twake?.()\n\t\t},\n\t}\n}\n\nexport class CheckoutManager {\n\tprivate active: string | null = null\n\tprivate readonly now: () => number\n\n\tconstructor(private readonly options: CheckoutManagerOptions) {\n\t\tthis.now = options.now ?? (() => Date.now())\n\t}\n\n\tget pendingKey(): string {\n\t\treturn `extenshi-pay:${this.options.publishableKey}:pendingCheckout`\n\t}\n\n\tisActive(): boolean {\n\t\treturn this.active !== null\n\t}\n\n\tasync open(sku: string, options: CheckoutOptions = {}): Promise<CheckoutResult> {\n\t\tif (this.active) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, 'A checkout is already in progress')\n\t\t}\n\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\tconst session = await this.options.api.createCheckout(\n\t\t\tsku,\n\t\t\tendUserRef,\n\t\t\toptions.locale ?? this.options.locale,\n\t\t\toptions.withdrawalWaiver,\n\t\t)\n\t\tthis.active = session.sessionId\n\t\ttry {\n\t\t\tconst pending: PendingCheckout = { sessionId: session.sessionId, sku, expiresAt: session.expiresAt }\n\t\t\tawait this.options.storage.set(this.pendingKey, pending)\n\t\t\tthis.options.emit('checkout:started', { sku, sessionId: session.sessionId, url: session.url })\n\t\t\tawait (options.openUrl ?? this.options.openUrl ?? openInNewTab)(session.url)\n\t\t\treturn await this.poll(sku, session.sessionId, endUserRef, options)\n\t\t} finally {\n\t\t\tthis.active = null\n\t\t}\n\t}\n\n\t/** Finishes a checkout that was started before a restart; null when there is nothing to resume. */\n\tasync resumePending(): Promise<CheckoutResult | null> {\n\t\tconst raw = (await this.options.storage.get(this.pendingKey)) as Partial<PendingCheckout> | undefined\n\t\tif (!raw || typeof raw.sessionId !== 'string' || typeof raw.sku !== 'string') return null\n\t\tconst expires = Date.parse(raw.expiresAt ?? '')\n\t\tif (!Number.isFinite(expires) || expires + PENDING_GRACE_MS < this.now()) {\n\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\treturn null\n\t\t}\n\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\tlet claim: PayCheckoutClaim\n\t\ttry {\n\t\t\tclaim = await this.options.api.claimSession(raw.sessionId, endUserRef)\n\t\t} catch (error) {\n\t\t\tlogger.debug('could not resume pending checkout', error)\n\t\t\treturn null\n\t\t}\n\t\treturn this.settle(claim, raw.sku, raw.sessionId)\n\t}\n\n\tprivate async poll(\n\t\tsku: string,\n\t\tsessionId: string,\n\t\tendUserRef: string,\n\t\toptions: CheckoutOptions,\n\t): Promise<CheckoutResult> {\n\t\tconst interval = options.pollIntervalMs ?? CHECKOUT_POLL_INTERVAL_MS\n\t\tconst deadline = this.now() + (options.timeoutMs ?? CHECKOUT_TIMEOUT_MS)\n\t\tconst sleeper = interruptibleSleep()\n\t\tconst stopFocus = onFocusRegained(() => sleeper.wake())\n\t\tlet delay = interval\n\t\tlet errorBackoff = 0\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tawait sleeper.sleep(delay)\n\t\t\t\tif (this.now() >= deadline) return { state: 'timeout', sku, sessionId }\n\t\t\t\tlet claim: PayCheckoutClaim\n\t\t\t\ttry {\n\t\t\t\t\tclaim = await this.options.api.claimSession(sessionId, endUserRef)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst err = ExtenshiPayError.from(error)\n\t\t\t\t\tif (err.code === ERROR_CODES.RATE_LIMITED) {\n\t\t\t\t\t\tdelay = (err.retryAfterSec ?? 5) * 1000\n\t\t\t\t\t} else if (\n\t\t\t\t\t\terr.code === ERROR_CODES.NETWORK_ERROR ||\n\t\t\t\t\t\terr.code === ERROR_CODES.TIMEOUT ||\n\t\t\t\t\t\terr.code === ERROR_CODES.GATEWAY_UNAVAILABLE\n\t\t\t\t\t) {\n\t\t\t\t\t\terrorBackoff = Math.min(errorBackoff ? errorBackoff * 2 : interval, MAX_ERROR_BACKOFF_MS)\n\t\t\t\t\t\tdelay = errorBackoff\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\t\t\tthrow err\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\terrorBackoff = 0\n\t\t\t\tdelay = interval\n\t\t\t\tconst result = await this.settle(claim, sku, sessionId)\n\t\t\t\tif (result) return result\n\t\t\t}\n\t\t} finally {\n\t\t\tstopFocus()\n\t\t}\n\t}\n\n\tprivate async settle(\n\t\tclaim: PayCheckoutClaim,\n\t\tsku: string,\n\t\tsessionId: string,\n\t): Promise<CheckoutResult | null> {\n\t\tswitch (claim.state) {\n\t\t\tcase 'pending':\n\t\t\t\treturn null\n\t\t\tcase 'complete': {\n\t\t\t\tconst entitlement = await this.options.onComplete(claim.entitlement)\n\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\tthis.options.emit('checkout:completed', { sku, sessionId, entitlement })\n\t\t\t\treturn { state: 'complete', sku, sessionId, entitlement }\n\t\t\t}\n\t\t\tcase 'canceled':\n\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\tthis.options.emit('checkout:canceled', { sku, sessionId })\n\t\t\t\treturn { state: 'canceled', sku, sessionId }\n\t\t\tcase 'expired':\n\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\tthis.options.emit('checkout:expired', { sku, sessionId })\n\t\t\t\treturn { state: 'expired', sku, sessionId }\n\t\t\tdefault:\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Unknown checkout claim state')\n\t\t}\n\t}\n}\n","/** Pure helpers over the entitlement projection. Features come from the items' `features[]`. */\n\nimport type { PayEntitlementItem } from '../types/contract.js'\nimport type { Entitlement } from '../types/entitlement.js'\n\nconst LIVE_STATUSES: ReadonlySet<string> = new Set(['active', 'grace'])\n\nexport function isLive(item: PayEntitlementItem): boolean {\n\treturn LIVE_STATUSES.has(item.status)\n}\n\n/** An item past its `expiresAt` reads as expired without a network round-trip. */\nexport function applyLocalExpiry(\n\titems: PayEntitlementItem[],\n\tnow: number = Date.now(),\n): PayEntitlementItem[] {\n\treturn items.map((item) => {\n\t\tif (!isLive(item) || !item.expiresAt) return item\n\t\tconst expires = Date.parse(item.expiresAt)\n\t\treturn Number.isFinite(expires) && expires <= now ? { ...item, status: 'expired' } : item\n\t})\n}\n\nexport function collectFeatures(items: PayEntitlementItem[]): string[] {\n\tconst features = new Set<string>()\n\tfor (const item of items) {\n\t\tif (!isLive(item)) continue\n\t\tfor (const feature of item.features) features.add(feature)\n\t}\n\treturn [...features]\n}\n\nexport function isEntitled(entitlement: Entitlement, sku?: string): boolean {\n\treturn (\n\t\t!entitlement.requiresOnlineCheck &&\n\t\tentitlement.items.some((item) => isLive(item) && (sku === undefined || item.sku === sku))\n\t)\n}\n\nexport function hasFeature(entitlement: Entitlement, feature: string): boolean {\n\treturn entitlement.features.includes(feature)\n}\n\nexport function checkFeatures(entitlement: Entitlement, features: string[]): Record<string, boolean> {\n\tconst result: Record<string, boolean> = {}\n\tfor (const feature of features) result[feature] = hasFeature(entitlement, feature)\n\treturn result\n}\n\nexport const EMPTY_ENTITLEMENT: Entitlement = Object.freeze({\n\titems: [],\n\tfeatures: [],\n\tverified: false,\n\tissuedAt: null,\n\tfetchedAt: null,\n\tsource: 'none',\n\trequiresOnlineCheck: false,\n\tofflineUntil: null,\n}) as Entitlement\n\n// Frozen empty arrays prevent consumers from changing the shared denied state.\nObject.freeze(EMPTY_ENTITLEMENT.items)\nObject.freeze(EMPTY_ENTITLEMENT.features)\n","/**\n * Ed25519 verification of the entitlement projection.\n *\n * Tamper resistance, not DRM. Trust comes from the developer's bundled key or\n * a key fetched over HTTPS, never from editable extension storage. Callers must\n * deny access for both invalid and unverified envelopes outside explicit mocks.\n */\n\nimport { canonicalJson, type SignedEntitlement } from '../types/contract.js'\n\nexport type SignatureVerdict = 'valid' | 'invalid' | 'unverified'\n\nexport function base64ToBytes(base64: string): Uint8Array<ArrayBuffer> {\n\tconst binary = atob(base64)\n\tconst bytes = new Uint8Array(binary.length)\n\tfor (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n\treturn bytes\n}\n\nexport async function verifyEntitlementSignature(\n\tenvelope: SignedEntitlement,\n\tpublicKeyBase64: string | null,\n): Promise<SignatureVerdict> {\n\tif (!envelope.signature || envelope.alg !== 'ed25519') return 'invalid'\n\tif (!publicKeyBase64) return 'unverified'\n\tconst subtle = (globalThis as { crypto?: Crypto }).crypto?.subtle\n\tif (!subtle) return 'unverified'\n\n\tlet key: CryptoKey\n\ttry {\n\t\tkey = await subtle.importKey('raw', base64ToBytes(publicKeyBase64), { name: 'Ed25519' }, false, [\n\t\t\t'verify',\n\t\t])\n\t} catch {\n\t\treturn 'unverified'\n\t}\n\n\ttry {\n\t\tconst data = new TextEncoder().encode(canonicalJson(envelope.payload))\n\t\tconst ok = await subtle.verify('Ed25519', key, base64ToBytes(envelope.signature), data)\n\t\treturn ok ? 'valid' : 'invalid'\n\t} catch {\n\t\treturn 'invalid'\n\t}\n}\n","/**\n * Entitlement cache + refresh.\n *\n * The cached envelope is a cache OF the server projection, never a second\n * source of truth: it is verified when stored and re-verified on load (once\n * the project's public key is known), served without a round-trip while the\n * TTL holds, served for up to 48 hours after signed issuance when the network is down, and expired\n * locally by `expiresAt`. Background refresh polls at most every 15 minutes\n * and backs off exponentially on errors.\n */\n\nimport type { PayApi } from '../api/pay-api.js'\nimport type { StorageAdapter } from '../core/storage.js'\nimport { canonicalJson, type SignedEntitlement } from '../types/contract.js'\nimport type { Entitlement, EntitlementSource } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { logger } from '../utils/logger.js'\nimport { applyLocalExpiry, collectFeatures, EMPTY_ENTITLEMENT } from './features.js'\nimport { verifyEntitlementSignature } from './signature.js'\n\nexport const MIN_REFRESH_INTERVAL_MS = 15 * 60 * 1000\nexport const MAX_REFRESH_BACKOFF_MS = 6 * 60 * 60 * 1000\nexport const MAX_OFFLINE_AGE_MS = 48 * 60 * 60 * 1000\n// Allow small server/client clock skew without granting more than the signed age limit.\nexport const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000\nconst CACHE_VERSION = 1\n\ninterface CacheRecord {\n\tv: typeof CACHE_VERSION\n\tenvelope: SignedEntitlement\n\tfetchedAt: number\n}\n\ninterface Held {\n\tenvelope: SignedEntitlement\n\tfetchedAt: number\n\tverified: boolean\n\tsource: EntitlementSource\n}\n\nexport interface EntitlementManagerOptions {\n\tapi: PayApi\n\tstorage: StorageAdapter\n\tpublishableKey: string\n\tcacheTtlMs: number\n\tsource?: EntitlementSource\n\tgetEndUserRef: () => Promise<string>\n\t/** Base64 raw Ed25519 public key from `getOffer`, or null when unknown/unsigned. */\n\tgetPublicKey: () => Promise<string | null>\n\tonChange?: (entitlement: Entitlement) => void\n\tonError?: (error: ExtenshiPayError) => void\n\tnow?: () => number\n}\n\nfunction isEnvelope(value: unknown): value is SignedEntitlement {\n\tif (!value || typeof value !== 'object') return false\n\tconst env = value as SignedEntitlement\n\treturn (\n\t\t!!env.payload &&\n\t\ttypeof env.payload === 'object' &&\n\t\ttypeof env.payload.endUserRef === 'string' &&\n\t\tArray.isArray(env.payload.entitlements) &&\n\t\ttypeof env.payload.issuedAt === 'string'\n\t)\n}\n\nexport class EntitlementManager {\n\tprivate held: Held | null = null\n\tprivate inflight: Promise<Entitlement> | null = null\n\tprivate timer: ReturnType<typeof setTimeout> | null = null\n\tprivate refreshGeneration = 0\n\tprivate deadlineTimer: ReturnType<typeof setTimeout> | null = null\n\tprivate refreshIntervalMs = MIN_REFRESH_INTERVAL_MS\n\tprivate backoffMs = 0\n\tprivate autoRefresh = false\n\tprivate readonly online = () => {\n\t\tvoid this.get({ force: true }).then(() => this.notifyIfChanged())\n\t}\n\t// Starts at the empty projection: a first load that finds nothing is not a\n\t// change, a first load that finds a paid entitlement is.\n\tprivate lastFingerprint: string | null = canonicalJson({ items: [], requiresOnlineCheck: false })\n\tprivate readonly now: () => number\n\tprivate readonly source: EntitlementSource\n\n\tconstructor(private readonly options: EntitlementManagerOptions) {\n\t\tthis.now = options.now ?? (() => Date.now())\n\t\tthis.source = options.source ?? 'network'\n\t}\n\n\tget storageKey(): string {\n\t\t// Keep the real cache key stable for upgrades. Simulated grants must\n\t\t// neither consume nor overwrite that cache when developers switch modes.\n\t\treturn `extenshi-pay:${this.options.publishableKey}:entitlement${this.source === 'mock' ? ':mock' : ''}`\n\t}\n\n\t/** Loads the persisted envelope (unverified until `reverify()`); no network. */\n\tasync load(): Promise<Entitlement | null> {\n\t\tconst raw = await this.options.storage.get(this.storageKey)\n\t\tconst record = raw as Partial<CacheRecord> | undefined\n\t\tif (\n\t\t\t!record ||\n\t\t\trecord.v !== CACHE_VERSION ||\n\t\t\t!isEnvelope(record.envelope) ||\n\t\t\ttypeof record.fetchedAt !== 'number' ||\n\t\t\t!Number.isFinite(record.fetchedAt)\n\t\t) {\n\t\t\treturn null\n\t\t}\n\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\tif (\n\t\t\trecord.envelope.payload.endUserRef !== endUserRef ||\n\t\t\t(this.source !== 'mock' && record.envelope.payload.publishableKey !== this.options.publishableKey)\n\t\t) {\n\t\t\tawait this.options.storage.remove(this.storageKey)\n\t\t\treturn null\n\t\t}\n\t\tthis.held = {\n\t\t\tenvelope: JSON.parse(JSON.stringify(record.envelope)),\n\t\t\tfetchedAt: record.fetchedAt,\n\t\t\tverified: false,\n\t\t\tsource: this.source === 'mock' ? 'mock' : 'cache',\n\t\t}\n\t\tthis.lastFingerprint = this.fingerprint()\n\t\treturn this.snapshot()\n\t}\n\n\t/** Re-checks the loaded envelope against the project's key; discards it when the signature is invalid. */\n\tasync reverify(): Promise<void> {\n\t\tif (!this.held) return\n\t\tif (this.source === 'mock') return\n\t\tconst held = this.held\n\t\tconst key = await this.safePublicKey()\n\t\tconst verdict = await verifyEntitlementSignature(held.envelope, key)\n\t\tif (held !== this.held) return\n\t\tif (verdict === 'invalid') {\n\t\t\tlogger.warn('cached entitlement failed signature verification; discarding')\n\t\t\tawait this.discard()\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Cached entitlement signature is invalid')\n\t\t}\n\t\theld.verified = verdict === 'valid'\n\t\tif (!held.verified) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.VERIFICATION_UNAVAILABLE,\n\t\t\t\t'Entitlement verification requires a trusted key and Ed25519 WebCrypto support',\n\t\t\t)\n\t\t}\n\t\tthis.scheduleDeadline()\n\t}\n\n\tgetCached(): Entitlement | null {\n\t\treturn this.held ? this.snapshot() : null\n\t}\n\n\tisFresh(): boolean {\n\t\treturn (\n\t\t\tthis.held !== null &&\n\t\t\t(this.source === 'mock' || (this.held.verified && !this.snapshot().requiresOnlineCheck)) &&\n\t\t\tthis.now() >= this.held.fetchedAt &&\n\t\t\tthis.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, MAX_OFFLINE_AGE_MS)\n\t\t)\n\t}\n\n\tasync get(options: { force?: boolean } = {}): Promise<Entitlement> {\n\t\tif (!options.force && this.isFresh()) return this.snapshot()\n\t\ttry {\n\t\t\treturn await this.refresh()\n\t\t} catch (error) {\n\t\t\tconst err = ExtenshiPayError.from(error)\n\t\t\tthis.options.onError?.(err)\n\t\t\tif (this.held) {\n\t\t\t\tlogger.debug('serving cached entitlement after refresh failure', err.code)\n\t\t\t\treturn this.snapshot()\n\t\t\t}\n\t\t\treturn EMPTY_ENTITLEMENT\n\t\t}\n\t}\n\n\t/** Fetches the projection from the backend, verifies and stores it. */\n\trefresh(): Promise<Entitlement> {\n\t\tif (!this.inflight) {\n\t\t\tthis.inflight = (async () => {\n\t\t\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\t\t\tconst envelope = await this.options.api.getEntitlement(endUserRef)\n\t\t\t\treturn this.accept(envelope, this.source)\n\t\t\t})().finally(() => {\n\t\t\t\tthis.inflight = null\n\t\t\t})\n\t\t}\n\t\treturn this.inflight\n\t}\n\n\t/** Verifies and stores an envelope obtained elsewhere (e.g. from `claimSession`). */\n\tasync accept(envelope: SignedEntitlement, source: EntitlementSource = this.source): Promise<Entitlement> {\n\t\tif (!isEnvelope(envelope)) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Malformed entitlement envelope')\n\t\t}\n\t\t// Detach from callers/storage: later mutation must not alter verified state.\n\t\tenvelope = JSON.parse(JSON.stringify(envelope)) as SignedEntitlement\n\t\tif (this.source !== 'mock' && envelope.payload.publishableKey !== this.options.publishableKey) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_RESPONSE,\n\t\t\t\t'Entitlement belongs to a different application or lacks a signed application scope',\n\t\t\t)\n\t\t}\n\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\tif (envelope.payload.endUserRef !== endUserRef) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_RESPONSE,\n\t\t\t\t'Entitlement issued for a different endUserRef',\n\t\t\t)\n\t\t}\n\t\tconst verdict =\n\t\t\tthis.source === 'mock'\n\t\t\t\t? 'unverified'\n\t\t\t\t: await verifyEntitlementSignature(envelope, await this.safePublicKey())\n\t\tif (verdict === 'invalid') {\n\t\t\tawait this.discard()\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement signature is invalid')\n\t\t}\n\t\tif (verdict !== 'valid' && this.source !== 'mock') {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.VERIFICATION_UNAVAILABLE,\n\t\t\t\t'Entitlement verification requires a trusted key and Ed25519 WebCrypto support',\n\t\t\t)\n\t\t}\n\t\tconst fetchedAt = this.now()\n\t\tconst issuedAt = Date.parse(envelope.payload.issuedAt)\n\t\tif (this.source !== 'mock' && (!Number.isFinite(issuedAt) || issuedAt > fetchedAt + MAX_CLOCK_SKEW_MS)) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_RESPONSE,\n\t\t\t\t'Entitlement issuedAt is invalid or in the future',\n\t\t\t)\n\t\t}\n\t\tthis.held = { envelope, fetchedAt, verified: verdict === 'valid', source }\n\t\tconst record: CacheRecord = { v: CACHE_VERSION, envelope, fetchedAt }\n\t\tawait this.options.storage.set(this.storageKey, JSON.parse(JSON.stringify(record)))\n\t\tthis.backoffMs = 0\n\t\tthis.scheduleDeadline()\n\t\tthis.notifyIfChanged()\n\t\treturn this.snapshot()\n\t}\n\n\t/** Drain an older installation refresh before changing identity. */\n\tasync settleRefresh(): Promise<void> {\n\t\tawait this.inflight?.catch(() => undefined)\n\t}\n\n\tasync clear(): Promise<void> {\n\t\tthis.held = null\n\t\tthis.scheduleDeadline()\n\t\tthis.lastFingerprint = null\n\t\tawait this.options.storage.remove(this.storageKey)\n\t}\n\n\tstartAutoRefresh(intervalMs: number = Math.max(this.options.cacheTtlMs, MIN_REFRESH_INTERVAL_MS)): void {\n\t\tthis.stopAutoRefresh()\n\t\tthis.autoRefresh = true\n\t\tglobalThis.addEventListener?.('online', this.online)\n\t\tthis.refreshIntervalMs = Math.max(intervalMs, MIN_REFRESH_INTERVAL_MS)\n\t\tthis.schedule(this.refreshIntervalMs)\n\t\tthis.scheduleDeadline()\n\t}\n\n\tstopAutoRefresh(): void {\n\t\tthis.autoRefresh = false\n\t\tglobalThis.removeEventListener?.('online', this.online)\n\t\tthis.refreshGeneration++\n\t\tif (this.deadlineTimer !== null) clearTimeout(this.deadlineTimer)\n\t\tthis.deadlineTimer = null\n\t\tif (this.timer !== null) clearTimeout(this.timer)\n\t\tthis.timer = null\n\t}\n\n\tprivate scheduleDeadline(): void {\n\t\tif (this.deadlineTimer !== null) clearTimeout(this.deadlineTimer)\n\t\tthis.deadlineTimer = null\n\t\tif (!this.autoRefresh || !this.held || !this.held.verified || this.source === 'mock') return\n\t\tconst now = this.now()\n\t\tif (now >= this.offlineDeadline()) return\n\t\tconst deadlines = [\n\t\t\tthis.offlineDeadline(),\n\t\t\t...this.held.envelope.payload.entitlements\n\t\t\t\t.filter((item) => item.status === 'active' || item.status === 'grace')\n\t\t\t\t.map((item) => (item.expiresAt ? Date.parse(item.expiresAt) : NaN)),\n\t\t]\n\t\tconst remaining = Math.min(...deadlines.filter((deadline) => deadline > now)) - now\n\t\tif (!Number.isFinite(remaining) || remaining <= 0) return\n\t\tthis.deadlineTimer = setTimeout(() => {\n\t\t\tthis.deadlineTimer = null\n\t\t\tthis.notifyIfChanged()\n\t\t\tthis.scheduleDeadline()\n\t\t}, remaining)\n\t}\n\n\tprivate schedule(delayMs: number): void {\n\t\tconst generation = this.refreshGeneration\n\t\tthis.timer = setTimeout(async () => {\n\t\t\tthis.timer = null\n\t\t\ttry {\n\t\t\t\tawait this.refresh()\n\t\t\t\tif (generation !== this.refreshGeneration) return\n\t\t\t\tthis.schedule(this.refreshIntervalMs)\n\t\t\t} catch (error) {\n\t\t\t\tif (generation !== this.refreshGeneration) return\n\t\t\t\tthis.options.onError?.(ExtenshiPayError.from(error))\n\t\t\t\tthis.backoffMs = Math.min(\n\t\t\t\t\tthis.backoffMs ? this.backoffMs * 2 : this.refreshIntervalMs,\n\t\t\t\t\tMAX_REFRESH_BACKOFF_MS,\n\t\t\t\t)\n\t\t\t\tthis.schedule(this.backoffMs)\n\t\t\t}\n\t\t}, delayMs)\n\t}\n\n\tprivate async safePublicKey(): Promise<string | null> {\n\t\ttry {\n\t\t\treturn await this.options.getPublicKey()\n\t\t} catch (error) {\n\t\t\tlogger.debug('public key unavailable; entitlement stays unverified', error)\n\t\t\treturn null\n\t\t}\n\t}\n\n\tprivate async discard(): Promise<void> {\n\t\tthis.held = null\n\t\tthis.scheduleDeadline()\n\t\tawait this.options.storage.remove(this.storageKey)\n\t\tthis.notifyIfChanged()\n\t}\n\n\tprivate fingerprint(): string {\n\t\tconst state = this.snapshot()\n\t\treturn canonicalJson({ items: state.items, requiresOnlineCheck: state.requiresOnlineCheck })\n\t}\n\n\tprivate notifyIfChanged(): void {\n\t\tconst fingerprint = this.fingerprint()\n\t\tif (fingerprint === this.lastFingerprint) return\n\t\tthis.lastFingerprint = fingerprint\n\t\tthis.options.onChange?.(this.snapshot())\n\t}\n\n\tprivate offlineDeadline(): number {\n\t\tif (!this.held) return NaN\n\t\t// fetchedAt is untrusted bookkeeping; it may shorten, never extend, a grant.\n\t\treturn Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + MAX_OFFLINE_AGE_MS\n\t}\n\n\tprivate snapshot(): Entitlement {\n\t\tif (!this.held) return EMPTY_ENTITLEMENT\n\t\tif (this.source !== 'mock' && !this.held.verified) {\n\t\t\treturn { ...EMPTY_ENTITLEMENT, requiresOnlineCheck: true, source: this.held.source }\n\t\t}\n\t\tconst items = applyLocalExpiry(\n\t\t\tJSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)),\n\t\t\tthis.now(),\n\t\t)\n\t\tconst hasPaidAccess =\n\t\t\tcollectFeatures(items).length > 0 ||\n\t\t\titems.some((item) => item.status === 'active' || item.status === 'grace')\n\t\tconst offlineUntil = this.source === 'mock' || !hasPaidAccess ? null : this.offlineDeadline()\n\t\tconst requiresOnlineCheck =\n\t\t\tofflineUntil !== null &&\n\t\t\t(!Number.isFinite(offlineUntil) ||\n\t\t\t\tthis.now() >= offlineUntil ||\n\t\t\t\tthis.now() < this.held.fetchedAt ||\n\t\t\t\tthis.now() + MAX_CLOCK_SKEW_MS < Date.parse(this.held.envelope.payload.issuedAt))\n\t\treturn {\n\t\t\titems,\n\t\t\tfeatures: requiresOnlineCheck ? [] : collectFeatures(items),\n\t\t\trequiresOnlineCheck,\n\t\t\tofflineUntil,\n\t\t\tverified: this.held.verified,\n\t\t\tissuedAt: this.held.envelope.payload.issuedAt,\n\t\t\tfetchedAt: this.held.fetchedAt,\n\t\t\tsource: this.held.source,\n\t\t}\n\t}\n}\n","/**\n * Persistent key/value storage for the SDK's own namespace.\n *\n * Preference order: `chrome.storage.local` (Chrome/Edge), `browser.storage.local`\n * (Firefox), `localStorage` (non-extension contexts such as a dev page), then\n * memory. Both promise-returning (MV3, Firefox) and callback-only (MV2) storage\n * APIs are supported.\n */\n\nexport interface StorageAdapter {\n\tget(key: string): Promise<unknown>\n\tset(key: string, value: unknown): Promise<void>\n\tremove(key: string): Promise<void>\n}\n\ntype Items = Record<string, unknown>\n\ninterface StorageArea {\n\tget(keys: string, callback?: (items: Items) => void): unknown\n\tset(items: Items, callback?: () => void): unknown\n\tremove(keys: string, callback?: () => void): unknown\n}\n\ninterface ExtensionGlobals {\n\tchrome?: { storage?: { local?: StorageArea }; runtime?: { lastError?: { message?: string } } }\n\tbrowser?: { storage?: { local?: StorageArea } }\n}\n\nfunction extensionGlobals(): ExtensionGlobals {\n\treturn globalThis as ExtensionGlobals\n}\n\nfunction isThenable<T>(value: unknown): value is Promise<T> {\n\treturn !!value && typeof (value as Promise<T>).then === 'function'\n}\n\n/** Runs a storage-area call that may either return a promise or expect a callback. */\nfunction areaCall<T>(\n\tdirect: () => unknown,\n\twithCallback: (callback: (value: T) => void) => void,\n): Promise<T> {\n\tconst result = direct()\n\tif (isThenable<T>(result)) return result\n\treturn new Promise<T>((resolve, reject) => {\n\t\twithCallback((value) => {\n\t\t\tconst lastError = extensionGlobals().chrome?.runtime?.lastError\n\t\t\tif (lastError) reject(new Error(lastError.message ?? 'storage error'))\n\t\t\telse resolve(value)\n\t\t})\n\t})\n}\n\nexport class ExtensionStorage implements StorageAdapter {\n\tconstructor(private readonly area: StorageArea) {}\n\n\tasync get(key: string): Promise<unknown> {\n\t\tconst items = await areaCall<Items>(\n\t\t\t() => this.area.get(key),\n\t\t\t(cb) => this.area.get(key, cb),\n\t\t)\n\t\treturn items?.[key]\n\t}\n\n\tasync set(key: string, value: unknown): Promise<void> {\n\t\tawait areaCall<void>(\n\t\t\t() => this.area.set({ [key]: value }),\n\t\t\t(cb) => this.area.set({ [key]: value }, cb),\n\t\t)\n\t}\n\n\tasync remove(key: string): Promise<void> {\n\t\tawait areaCall<void>(\n\t\t\t() => this.area.remove(key),\n\t\t\t(cb) => this.area.remove(key, cb),\n\t\t)\n\t}\n}\n\nexport class LocalStorageAdapter implements StorageAdapter {\n\tconstructor(private readonly store: Storage) {}\n\n\tasync get(key: string): Promise<unknown> {\n\t\tconst raw = this.store.getItem(key)\n\t\tif (raw === null) return undefined\n\t\ttry {\n\t\t\treturn JSON.parse(raw)\n\t\t} catch {\n\t\t\treturn undefined\n\t\t}\n\t}\n\n\tasync set(key: string, value: unknown): Promise<void> {\n\t\tthis.store.setItem(key, JSON.stringify(value))\n\t}\n\n\tasync remove(key: string): Promise<void> {\n\t\tthis.store.removeItem(key)\n\t}\n}\n\nexport class MemoryStorage implements StorageAdapter {\n\tprivate readonly map = new Map<string, unknown>()\n\n\tasync get(key: string): Promise<unknown> {\n\t\treturn this.map.get(key)\n\t}\n\n\tasync set(key: string, value: unknown): Promise<void> {\n\t\tthis.map.set(key, value)\n\t}\n\n\tasync remove(key: string): Promise<void> {\n\t\tthis.map.delete(key)\n\t}\n}\n\nexport function createStorage(): StorageAdapter {\n\tconst g = extensionGlobals()\n\tconst area = g.chrome?.storage?.local ?? g.browser?.storage?.local\n\tif (area) return new ExtensionStorage(area)\n\ttry {\n\t\tconst store = (globalThis as { localStorage?: Storage }).localStorage\n\t\tif (store && typeof store.getItem === 'function') return new LocalStorageAdapter(store)\n\t} catch {\n\t\t// Access to localStorage can throw in sandboxed frames.\n\t}\n\treturn new MemoryStorage()\n}\n","/** Email stays on the hosted page. Only this extension context holds the claim secret. */\nimport type { PayApi } from '../api/pay-api.js'\nimport type { StorageAdapter } from '../core/storage.js'\nimport { ExtensionStorage, MemoryStorage } from '../core/storage.js'\nimport type { SignedEntitlement } from '../types/contract.js'\nimport type { Entitlement, RestoreOptions, RestoreResult } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { openInNewTab } from './checkout.js'\n\ntype SessionArea = ConstructorParameters<typeof ExtensionStorage>[0]\n\n/** storage.local is exposed to content scripts by default. Never put a recovery proof there. */\nexport function createRecoveryStorage(): StorageAdapter {\n\tconst g = globalThis as {\n\t\tchrome?: { storage?: { session?: SessionArea }; tabs?: unknown }\n\t\tbrowser?: { storage?: { session?: SessionArea }; tabs?: unknown }\n\t}\n\tconst extension = g.chrome?.tabs ? g.chrome : g.browser?.tabs ? g.browser : null\n\treturn extension?.storage?.session ? new ExtensionStorage(extension.storage.session) : new MemoryStorage()\n}\n\ninterface PendingRestore {\n\tsessionId: string\n\tclaimSecret: string\n\texpiresAt: string\n}\nexport interface RecoveryManagerOptions {\n\tapi: PayApi\n\t/** The user's language, for the hosted recovery page and its email. */\n\tlocale?: string | null\n\tstorage: StorageAdapter\n\tpublishableKey: string\n\tonComplete: (endUserRef: string, envelope: SignedEntitlement) => Promise<Entitlement>\n\topenUrl?: (url: string) => void | Promise<void>\n\tnow?: () => number\n}\n\nexport class RecoveryManager {\n\tprivate active = false\n\tprivate stopped = false\n\tprivate wake: (() => void) | null = null\n\tconstructor(private readonly options: RecoveryManagerOptions) {}\n\tget pendingKey(): string {\n\t\treturn `extenshi-pay:${this.options.publishableKey}:pendingRestore`\n\t}\n\tisActive(): boolean {\n\t\treturn this.active\n\t}\n\tstop(): void {\n\t\tthis.stopped = true\n\t\tthis.wake?.()\n\t}\n\n\tasync open(options: RestoreOptions = {}): Promise<RestoreResult> {\n\t\tif (this.active)\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Recovery is already in progress')\n\t\tthis.active = true\n\t\tthis.stopped = false\n\t\ttry {\n\t\t\t// A caller from a content script must route the action to its own background;\n\t\t\t// never return this manager's internal state through that message bridge.\n\t\t\tconst g = globalThis as {\n\t\t\t\tchrome?: { runtime?: { id?: string }; tabs?: unknown }\n\t\t\t\tbrowser?: { runtime?: { id?: string }; tabs?: unknown }\n\t\t\t}\n\t\t\tif ((g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs))\n\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t'Start recovery in an extension page or background context',\n\t\t\t\t)\n\t\t\tconst cryptoApi = globalThis.crypto\n\t\t\tif (!cryptoApi?.subtle)\n\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t'Secure recovery is unavailable in this browser',\n\t\t\t\t)\n\t\t\tconst secret = Array.from(cryptoApi.getRandomValues(new Uint8Array(32)), (b) =>\n\t\t\t\tb.toString(16).padStart(2, '0'),\n\t\t\t).join('')\n\t\t\tconst hash = await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(secret))\n\t\t\tconst challenge = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('')\n\t\t\tconst created = await this.options.api.createRestoreSession(challenge, this.options.locale)\n\t\t\tif (!Number.isFinite(Date.parse(created.expiresAt)))\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery expiry')\n\t\t\tconst pending = { sessionId: created.sessionId, expiresAt: created.expiresAt, claimSecret: secret }\n\t\t\tawait this.options.storage.set(this.pendingKey, pending)\n\t\t\tawait (options.openUrl ?? this.options.openUrl ?? openInNewTab)(created.url)\n\t\t\treturn await this.poll(pending, options)\n\t\t} finally {\n\t\t\tthis.active = false\n\t\t}\n\t}\n\n\tasync resumePending(): Promise<RestoreResult | null> {\n\t\tif (this.active || this.stopped) return null\n\t\tconst raw = (await this.options.storage.get(this.pendingKey)) as Partial<PendingRestore> | undefined\n\t\tif (!raw || this.active || this.stopped) return null\n\t\tif (\n\t\t\ttypeof raw.sessionId !== 'string' ||\n\t\t\ttypeof raw.claimSecret !== 'string' ||\n\t\t\t!/^[a-f0-9]{64}$/.test(raw.claimSecret) ||\n\t\t\t!Number.isFinite(Date.parse(raw.expiresAt ?? ''))\n\t\t) {\n\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\treturn null\n\t\t}\n\t\tthis.active = true\n\t\tthis.stopped = false\n\t\ttry {\n\t\t\treturn await this.poll(raw as PendingRestore, {})\n\t\t} finally {\n\t\t\tthis.active = false\n\t\t}\n\t}\n\n\tprivate async poll(pending: PendingRestore, options: RestoreOptions): Promise<RestoreResult> {\n\t\tconst now = this.options.now ?? Date.now\n\t\tconst expires = Date.parse(pending.expiresAt)\n\t\tconst deadline = Math.min(expires, now() + (options.timeoutMs ?? 10 * 60 * 1000))\n\t\tlet delay = 0\n\t\twhile (!this.stopped && !options.signal?.aborted && now() < deadline) {\n\t\t\tif (delay)\n\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\tconst done = () => {\n\t\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\t\toptions.signal?.removeEventListener('abort', done)\n\t\t\t\t\t\tthis.wake = null\n\t\t\t\t\t\tresolve()\n\t\t\t\t\t}\n\t\t\t\t\tconst timer = setTimeout(done, Math.min(delay, Math.max(0, deadline - now())))\n\t\t\t\t\tthis.wake = done\n\t\t\t\t\toptions.signal?.addEventListener('abort', done, { once: true })\n\t\t\t\t})\n\t\t\tif (this.stopped || options.signal?.aborted || now() >= deadline) break\n\t\t\ttry {\n\t\t\t\tconst claim = await this.options.api.claimRestoreSession(pending.sessionId, pending.claimSecret)\n\t\t\t\tif (this.stopped || options.signal?.aborted) break\n\t\t\t\tif (claim.state === 'complete') {\n\t\t\t\t\tconst entitlement = await this.options.onComplete(claim.endUserRef, claim.entitlement)\n\t\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\t\treturn { state: 'complete', entitlement }\n\t\t\t\t}\n\t\t\t\tif (claim.state !== 'pending')\n\t\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery response')\n\t\t\t\tdelay = Math.max(100, options.pollIntervalMs ?? 2_000)\n\t\t\t} catch (error) {\n\t\t\t\tconst err = ExtenshiPayError.from(error)\n\t\t\t\tif (\n\t\t\t\t\t![\n\t\t\t\t\t\tERROR_CODES.NETWORK_ERROR,\n\t\t\t\t\t\tERROR_CODES.TIMEOUT,\n\t\t\t\t\t\tERROR_CODES.GATEWAY_UNAVAILABLE,\n\t\t\t\t\t\tERROR_CODES.RATE_LIMITED,\n\t\t\t\t\t].some((code) => code === err.code)\n\t\t\t\t)\n\t\t\t\t\tthrow err\n\t\t\t\tdelay = Math.max(2_000, (err.retryAfterSec ?? 5) * 1000)\n\t\t\t}\n\t\t}\n\t\tif (now() >= expires) await this.options.storage.remove(this.pendingKey)\n\t\treturn {\n\t\t\tstate: this.stopped || options.signal?.aborted ? 'canceled' : now() >= expires ? 'expired' : 'timeout',\n\t\t}\n\t}\n}\n","import type { PayEntitlementItem, PayOfferDto, PayWithdrawalWaiver } from './contract.js'\nimport type { ExtenshiPayError } from './errors.js'\n\nexport type LogLevel = 'silent' | 'error' | 'warn' | 'info' | 'debug'\n\n/** Reserved for future routing; today every environment talks to the same BFF. */\nexport type Environment = 'production' | 'sandbox' | 'development'\n\nexport interface ThemeConfig {\n\t/** `auto` follows `prefers-color-scheme`. */\n\tmode?: 'light' | 'dark' | 'auto'\n\tprimaryColor?: string\n\tfontFamily?: string\n\tborderRadius?: string\n\t/** Appended verbatim inside the paywall's shadow root. */\n\tcustomCss?: string\n}\n\n/** Offline development data used when `mock: true`. */\nexport interface MockData {\n\tentitlements?: PayEntitlementItem[]\n\toffers?: PayOfferDto[]\n\tprojectName?: string\n\t/** Defaults to true. */\n\tcheckoutEnabled?: boolean\n\t/** How many `claimSession` polls answer `pending` before a mock checkout completes (default 1). */\n\tclaimAfterPolls?: number\n\t/**\n\t * Offer's withdrawal waiver (default: required, current version, so the\n\t * paywall previews the checkbox). `null` previews a seller outside the EEA/UK.\n\t */\n\twithdrawalWaiver?: PayWithdrawalWaiver | null\n}\n\nexport interface ExtenshiPayConfig {\n\t/** `pk_ext_` + 32 hex characters, from the project's Monetization tab. */\n\tpublishableKey: string\n\t/** Defaults to `https://bff.extenshi.io`. */\n\tapiUrl?: string\n\t/** Bundled raw Ed25519 public key (base64). Enables verified cache use after an offline restart. */\n\tentitlementPublicKey?: string\n\tenvironment?: Environment\n\t/** Shorthand for `logLevel: 'debug'`. */\n\tdebug?: boolean\n\tlogLevel?: LogLevel\n\t/** How long a fetched entitlement is served without a network round-trip (default 1 hour). */\n\tcacheTtlMs?: number\n\t/** BCP-47 tag such as `en` or `de-DE`; sent to the backend for checkout/offer copy and used for price formatting. */\n\tlocale?: string\n\tmock?: boolean\n\tmockData?: MockData\n\tonReady?: () => void\n\tonError?: (error: ExtenshiPayError) => void\n\ttheme?: ThemeConfig\n}\n\nexport interface ResolvedConfig {\n\tpublishableKey: string\n\tapiUrl: string\n\tentitlementPublicKey: string | null\n\tenvironment: Environment\n\tdebug: boolean\n\tlogLevel: LogLevel\n\tcacheTtlMs: number\n\tlocale: string | null\n\tmock: boolean\n\tmockData: MockData | null\n\ttheme: ThemeConfig\n}\n\nexport const DEFAULT_API_URL = 'https://bff.extenshi.io'\nexport const DEFAULT_CACHE_TTL_MS = 60 * 60 * 1000\nexport const MAX_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000\n","/** Kept in sync with package.json by tests/unit/version.test.ts. */\nexport const VERSION = '0.8.0'\n","/**\n * The user's language as the SDK sends it. Kept apart from the paywall\n * dictionary (../paywall/i18n.ts) so the Lite and core bundles, which never\n * render UI, do not carry the translations.\n */\n\n/** What the backend (and older backends) accept as a locale: `de`, `pt-BR`, `zh-CN`. */\nconst WIRE_LOCALE_RE = /^[a-z]{2}(-[A-Za-z]{2,4})?$/\n\n/**\n * A browser tag as the SDK sends it: `pt_BR` → `pt-BR`, `es-419` → `es`,\n * `zh-Hant-TW` → `zh-TW`; null for anything that is not a language tag.\n */\nexport function wireLocale(raw: unknown): string | null {\n\tif (typeof raw !== 'string') return null\n\tconst parts = raw.trim().replace(/_/g, '-').split('-').filter(Boolean)\n\tconst lang = parts[0]?.toLowerCase()\n\tif (!lang || !/^[a-z]{2}$/.test(lang)) return null\n\tconst script = parts\n\t\t.slice(1)\n\t\t.find((p) => /^[A-Za-z]{4}$/.test(p))\n\t\t?.toLowerCase()\n\t// zh-Hant without a region is Traditional Chinese: keep that, never let it read as zh-CN.\n\tconst region =\n\t\tparts.slice(1).find((p) => /^[A-Za-z]{2}$/.test(p)) ??\n\t\t(lang === 'zh' && script === 'hant' ? 'TW' : undefined)\n\tconst tag = region ? `${lang}-${region.toUpperCase()}` : lang\n\treturn WIRE_LOCALE_RE.test(tag) ? tag : lang\n}\n\n/** The browser UI language (`chrome.i18n.getUILanguage()`, else `navigator.language`), or null. */\nexport function browserLocale(): string | null {\n\tconst g = globalThis as {\n\t\tchrome?: { i18n?: { getUILanguage?: () => string } }\n\t\tbrowser?: { i18n?: { getUILanguage?: () => string } }\n\t\tnavigator?: { language?: string }\n\t}\n\ttry {\n\t\tconst ui = g.chrome?.i18n?.getUILanguage?.() ?? g.browser?.i18n?.getUILanguage?.()\n\t\tif (ui) return wireLocale(ui)\n\t} catch {\n\t\t/* Not an extension context. */\n\t}\n\treturn wireLocale(g.navigator?.language)\n}\n","import {\n\tDEFAULT_API_URL,\n\tDEFAULT_CACHE_TTL_MS,\n\ttype ExtenshiPayConfig,\n\tMAX_CACHE_TTL_MS,\n\ttype ResolvedConfig,\n} from '../types/config.js'\nimport { isPayPublishableKey } from '../types/contract.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { browserLocale } from './locale.js'\n\nconst ENVIRONMENTS = new Set(['production', 'sandbox', 'development'])\nconst LOG_LEVELS = new Set(['silent', 'error', 'warn', 'info', 'debug'])\nconst THEME_MODES = new Set(['light', 'dark', 'auto'])\n/** Same shape the BFF accepts (`en`, `de-DE`, `zh-Hant`). */\nexport const LOCALE_RE = /^[a-z]{2}(-[A-Za-z]{2,4})?$/\n\nfunction isHttpUrl(value: string): boolean {\n\ttry {\n\t\tconst url = new URL(value)\n\t\treturn url.protocol === 'https:' || url.protocol === 'http:'\n\t} catch {\n\t\treturn false\n\t}\n}\n\nexport function resolveConfig(input: ExtenshiPayConfig): ResolvedConfig {\n\tconst errors: string[] = []\n\tif (!input || typeof input !== 'object') {\n\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_CONFIG, 'ExtenshiPay config must be an object')\n\t}\n\n\tif (!isPayPublishableKey(input.publishableKey)) {\n\t\terrors.push('publishableKey must look like pk_ext_<32 hex characters>')\n\t}\n\n\tconst apiUrl = (input.apiUrl ?? DEFAULT_API_URL).replace(/\\/+$/, '')\n\tif (!isHttpUrl(apiUrl)) errors.push('apiUrl must be an http(s) URL')\n\n\tconst entitlementPublicKey = input.entitlementPublicKey ?? null\n\tif (entitlementPublicKey !== null && !/^[A-Za-z0-9+/]{43}=$/.test(entitlementPublicKey)) {\n\t\terrors.push('entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key')\n\t}\n\n\tconst environment = input.environment ?? 'production'\n\tif (!ENVIRONMENTS.has(environment)) errors.push('environment must be production, sandbox or development')\n\n\tconst logLevel = input.logLevel ?? 'warn'\n\tif (!LOG_LEVELS.has(logLevel)) errors.push('logLevel must be silent, error, warn, info or debug')\n\n\tconst cacheTtlMs = input.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS\n\tif (!Number.isFinite(cacheTtlMs) || cacheTtlMs < 0 || cacheTtlMs > MAX_CACHE_TTL_MS) {\n\t\terrors.push(`cacheTtlMs must be between 0 and ${MAX_CACHE_TTL_MS}`)\n\t}\n\n\t// Default: the browser UI language, as README promises (it. 13 T10 L2).\n\t// `null` still opts out explicitly: prices then use the runtime default\n\t// and the paywall reads English.\n\tconst locale = input.locale === undefined ? browserLocale() : input.locale\n\tif (locale !== null && !LOCALE_RE.test(locale))\n\t\terrors.push('locale must be a BCP-47 tag such as en or de-DE')\n\n\tconst theme = input.theme ?? {}\n\tif (theme.mode !== undefined && !THEME_MODES.has(theme.mode))\n\t\terrors.push('theme.mode must be light, dark or auto')\n\n\tif (\n\t\tinput.mock &&\n\t\tinput.mockData !== undefined &&\n\t\t(typeof input.mockData !== 'object' || input.mockData === null)\n\t) {\n\t\terrors.push('mockData must be an object')\n\t}\n\n\tif (errors.length > 0) {\n\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_CONFIG, `Invalid ExtenshiPay config: ${errors.join('; ')}`)\n\t}\n\n\treturn {\n\t\tpublishableKey: input.publishableKey,\n\t\tapiUrl,\n\t\tentitlementPublicKey,\n\t\tenvironment,\n\t\tdebug: input.debug === true,\n\t\tlogLevel,\n\t\tcacheTtlMs,\n\t\tlocale,\n\t\tmock: input.mock === true,\n\t\tmockData: input.mock ? (input.mockData ?? {}) : null,\n\t\ttheme,\n\t}\n}\n","import { logger } from '../utils/logger.js'\n\nexport type Listener<T> = (payload: T) => void\ntype AnyListener = (payload: never) => void\n\nexport class EventEmitter<Events extends object> {\n\tprivate readonly listeners = new Map<keyof Events, Set<AnyListener>>()\n\n\ton<K extends keyof Events>(event: K, listener: Listener<Events[K]>): () => void {\n\t\tlet set = this.listeners.get(event)\n\t\tif (!set) {\n\t\t\tset = new Set()\n\t\t\tthis.listeners.set(event, set)\n\t\t}\n\t\tset.add(listener as AnyListener)\n\t\treturn () => this.off(event, listener)\n\t}\n\n\tonce<K extends keyof Events>(event: K, listener: Listener<Events[K]>): () => void {\n\t\tconst off = this.on(event, (payload) => {\n\t\t\toff()\n\t\t\tlistener(payload)\n\t\t})\n\t\treturn off\n\t}\n\n\toff<K extends keyof Events>(event: K, listener: Listener<Events[K]>): void {\n\t\tthis.listeners.get(event)?.delete(listener as AnyListener)\n\t}\n\n\temit<K extends keyof Events>(event: K, payload: Events[K]): void {\n\t\tconst set = this.listeners.get(event)\n\t\tif (!set) return\n\t\tfor (const listener of [...set]) {\n\t\t\tconst fn = listener as Listener<Events[K]>\n\t\t\ttry {\n\t\t\t\tfn(payload)\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(`listener for \"${String(event)}\" threw`, error)\n\t\t\t}\n\t\t}\n\t}\n\n\tremoveAll(): void {\n\t\tthis.listeners.clear()\n\t}\n}\n","/**\n * Every string the SDK shows to the USER of an extension — paywall, license\n * dialog, billing-profile picker, seller details — in the end-user languages\n * (ROADMAP it. 13 T10, stage L2; closes it. 12 T9). Developer-facing error\n * messages stay English.\n *\n * Self-contained on purpose: the SDK ships inside third-party extensions with\n * no runtime dependencies and no remote code, so the dictionary is compiled\n * in. Placeholders are `{name}`, `{date}`, `{status}`. A missing\n * translation falls back to English, never to an empty string. The same\n * languages as the hosted pages (shared-types END_USER_LOCALES); keep the\n * lists in sync.\n */\n\nexport { browserLocale, wireLocale } from '../core/locale.js'\n\nimport { wireLocale } from '../core/locale.js'\n\nexport const SDK_LOCALES = ['en', 'es', 'pt-BR', 'fr', 'de', 'it', 'ru', 'ja', 'ko', 'zh-CN', 'ar'] as const\nexport type SdkLocale = (typeof SDK_LOCALES)[number]\n\nexport const SDK_STRINGS_EN = {\n\ttitle: 'Unlock premium features',\n\tdescription: 'Upgrade to get full access to this extension.',\n\tupgrade: 'Upgrade',\n\tcancel: 'Not now',\n\tdismiss: 'Dismiss',\n\tremindLater: 'Remind me later',\n\tcontinueFree: 'Continue with the free version',\n\tcheckoutUnavailable: 'Purchases are temporarily unavailable',\n\tperiodMonth: '/month',\n\tperiodYear: '/year',\n\tperiodOnce: 'one-time',\n\tfooter: 'Secure checkout opens in a new tab.',\n\trestorePurchase: 'Restore purchase',\n\tfeaturesHeading: 'Premium Features',\n\tplansHeading: 'Choose Your Plan',\n\tfreePlanName: 'Free',\n\tpremiumPlanName: 'Premium',\n\tpopularBadge: 'Most Popular',\n\tunlockHeading: 'Unlock Premium Features',\n\tsimulatePurchase: 'Simulate purchase',\n\tmockNotice: 'Development preview: licenses and payments are simulated. No payment will be taken.',\n\tsellerProvidedBy: 'License provided by {name}',\n\tsellerUnavailable: 'License provider details are unavailable.',\n\tsellerSupport: 'Extension support',\n\tsellerTerms: 'License terms',\n\tsellerRefunds: 'Refund policy',\n\tsellerRole:\n\t\t'The author handles extension functionality and license commitments. Extenshi provides payment and license recovery tools.',\n\tlicenseTitle: 'Your license',\n\tlicenseFallbackName: 'Extension license',\n\tlicenseNone: 'No license found on this installation.',\n\tkindOneTime: 'One-time purchase',\n\tkindLifetime: 'Lifetime',\n\tkindSubscription: 'Subscription',\n\tkindLicense: 'License',\n\tstatusLine: 'Status: {status}',\n\tstatusActive: 'active',\n\tstatusGrace: 'grace period',\n\tstatusExpired: 'expired',\n\tstatusNone: 'no access',\n\taccessEnded: 'Access ended {date}',\n\taccessUntil: 'Access until {date}',\n\taccessRecordedEnd: 'Recorded end date {date}',\n\tsubscriptionLine: 'Subscription: {status}',\n\trenewalCanceled: 'Renewal canceled',\n\tperiodEnds: 'Period ends {date}',\n\tsubActive: 'active',\n\tsubTrialing: 'trial',\n\tsubPastDue: 'payment overdue',\n\tsubCanceled: 'canceled',\n\tsubUnpaid: 'unpaid',\n\tsubIncomplete: 'incomplete',\n\tsubIncompleteExpired: 'payment not completed',\n\tsubPaused: 'paused',\n\tlicenseOffline:\n\t\t'Connect to the internet to verify your license. Paid features are paused after 48 hours without a successful check. Your purchase has not expired.',\n\tlicenseCached: 'Showing saved license information.',\n\tlicenseFresh: 'Subscription information reflects the latest processed payment update.',\n\tactionFailed: 'Unable to complete the request. Please try again or contact extension support.',\n\tmanageBilling: 'Manage billing',\n\tnoPortal: 'No billing portal opened. You can retry or contact extension support.',\n\tclose: 'Close',\n\tpickerTitle: 'Choose a billing profile',\n\tpickerDescription:\n\t\t'Separate purchases can have separate billing profiles. Choose one to manage its subscriptions and payment details.',\n\tpickerFirstRecorded: 'First recorded {date}',\n\tpickerCancel: 'Cancel',\n}\n\nexport type SdkStringKey = keyof typeof SDK_STRINGS_EN\nexport type SdkStrings = Record<SdkStringKey, string>\n\n// BEGIN GENERATED TRANSLATIONS\nconst TRANSLATIONS: Partial<Record<Exclude<SdkLocale, 'en'>, SdkStrings>> = {\n\tes: {\n\t\ttitle: 'Desbloquea las funciones premium',\n\t\tdescription: 'Mejora tu plan para obtener acceso completo a esta extensión.',\n\t\tupgrade: 'Mejorar plan',\n\t\tcancel: 'Ahora no',\n\t\tdismiss: 'Descartar',\n\t\tremindLater: 'Recordármelo más tarde',\n\t\tcontinueFree: 'Seguir con la versión gratuita',\n\t\tcheckoutUnavailable: 'Compras no disponibles temporalmente',\n\t\tperiodMonth: '/mes',\n\t\tperiodYear: '/año',\n\t\tperiodOnce: 'pago único',\n\t\tfooter: 'El pago seguro se abre en una pestaña nueva.',\n\t\trestorePurchase: 'Restaurar compra',\n\t\tfeaturesHeading: 'Funciones premium',\n\t\tplansHeading: 'Elige tu plan',\n\t\tfreePlanName: 'Gratis',\n\t\tpremiumPlanName: 'Premium',\n\t\tpopularBadge: 'Más popular',\n\t\tunlockHeading: 'Desbloquea las funciones premium',\n\t\tsimulatePurchase: 'Simular compra',\n\t\tmockNotice:\n\t\t\t'Vista previa de desarrollo: las licencias y los pagos son simulados. No se realizará ningún cobro.',\n\t\tsellerProvidedBy: 'Licencia proporcionada por {name}',\n\t\tsellerUnavailable: 'Los datos del proveedor de la licencia no están disponibles.',\n\t\tsellerSupport: 'Asistencia de la extensión',\n\t\tsellerTerms: 'Condiciones de licencia',\n\t\tsellerRefunds: 'Política de reembolsos',\n\t\tsellerRole:\n\t\t\t'El autor se encarga de las funciones de la extensión y de los compromisos de la licencia. Extenshi proporciona las herramientas de pago y de recuperación de licencias.',\n\t\tlicenseTitle: 'Tu licencia',\n\t\tlicenseFallbackName: 'Licencia de la extensión',\n\t\tlicenseNone: 'No se ha encontrado ninguna licencia en esta instalación.',\n\t\tkindOneTime: 'Compra única',\n\t\tkindLifetime: 'Licencia vitalicia',\n\t\tkindSubscription: 'Suscripción',\n\t\tkindLicense: 'Licencia',\n\t\tstatusLine: 'Estado: {status}',\n\t\tstatusActive: 'activo',\n\t\tstatusGrace: 'período de gracia',\n\t\tstatusExpired: 'caducado',\n\t\tstatusNone: 'sin acceso',\n\t\taccessEnded: 'Acceso finalizado el {date}',\n\t\taccessUntil: 'Acceso hasta el {date}',\n\t\taccessRecordedEnd: 'Fecha de finalización registrada: {date}',\n\t\tsubscriptionLine: 'Suscripción: {status}',\n\t\trenewalCanceled: 'Renovación cancelada',\n\t\tperiodEnds: 'El período finaliza el {date}',\n\t\tsubActive: 'activa',\n\t\tsubTrialing: 'en período de prueba',\n\t\tsubPastDue: 'pago vencido',\n\t\tsubCanceled: 'cancelada',\n\t\tsubUnpaid: 'sin pagar',\n\t\tsubIncomplete: 'incompleta',\n\t\tsubIncompleteExpired: 'pago no completado',\n\t\tsubPaused: 'en pausa',\n\t\tlicenseOffline:\n\t\t\t'Conéctate a internet para verificar tu licencia. Las funciones de pago se suspenden si pasan 48 horas sin una verificación correcta. Tu compra no ha caducado.',\n\t\tlicenseCached: 'Se muestra la información de licencia guardada.',\n\t\tlicenseFresh: 'La información de la suscripción refleja la última actualización de pago procesada.',\n\t\tactionFailed:\n\t\t\t'No se pudo completar la solicitud. Inténtalo de nuevo o ponte en contacto con la asistencia de la extensión.',\n\t\tmanageBilling: 'Gestionar facturación',\n\t\tnoPortal:\n\t\t\t'No se abrió ningún portal de facturación. Puedes volver a intentarlo o ponerte en contacto con la asistencia de la extensión.',\n\t\tclose: 'Cerrar',\n\t\tpickerTitle: 'Elige un perfil de facturación',\n\t\tpickerDescription:\n\t\t\t'Las compras independientes pueden tener perfiles de facturación distintos. Elige uno para gestionar sus suscripciones y datos de pago.',\n\t\tpickerFirstRecorded: 'Registrado por primera vez el {date}',\n\t\tpickerCancel: 'Cancelar',\n\t},\n\t'pt-BR': {\n\t\ttitle: 'Desbloqueie os recursos premium',\n\t\tdescription: 'Faça o upgrade para ter acesso completo a esta extensão.',\n\t\tupgrade: 'Fazer upgrade',\n\t\tcancel: 'Agora não',\n\t\tdismiss: 'Dispensar',\n\t\tremindLater: 'Lembrar mais tarde',\n\t\tcontinueFree: 'Continuar com a versão gratuita',\n\t\tcheckoutUnavailable: 'Compras temporariamente indisponíveis',\n\t\tperiodMonth: '/mês',\n\t\tperiodYear: '/ano',\n\t\tperiodOnce: 'pagamento único',\n\t\tfooter: 'O checkout seguro abre em uma nova guia.',\n\t\trestorePurchase: 'Restaurar compra',\n\t\tfeaturesHeading: 'Recursos premium',\n\t\tplansHeading: 'Escolha seu plano',\n\t\tfreePlanName: 'Gratuito',\n\t\tpremiumPlanName: 'Premium',\n\t\tpopularBadge: 'Mais popular',\n\t\tunlockHeading: 'Desbloqueie os recursos premium',\n\t\tsimulatePurchase: 'Simular compra',\n\t\tmockNotice: 'Prévia de desenvolvimento: licenças e pagamentos são simulados. Nenhum valor será cobrado.',\n\t\tsellerProvidedBy: 'Licença fornecida por {name}',\n\t\tsellerUnavailable: 'Os dados do fornecedor da licença não estão disponíveis.',\n\t\tsellerSupport: 'Suporte da extensão',\n\t\tsellerTerms: 'Termos de licença',\n\t\tsellerRefunds: 'Política de reembolso',\n\t\tsellerRole:\n\t\t\t'O autor é responsável pelo funcionamento da extensão e pelos compromissos da licença. A Extenshi fornece as ferramentas de pagamento e de recuperação de licenças.',\n\t\tlicenseTitle: 'Sua licença',\n\t\tlicenseFallbackName: 'Licença da extensão',\n\t\tlicenseNone: 'Nenhuma licença encontrada nesta instalação.',\n\t\tkindOneTime: 'Compra única',\n\t\tkindLifetime: 'Licença vitalícia',\n\t\tkindSubscription: 'Assinatura',\n\t\tkindLicense: 'Licença',\n\t\tstatusLine: 'Status: {status}',\n\t\tstatusActive: 'ativo',\n\t\tstatusGrace: 'período de carência',\n\t\tstatusExpired: 'expirado',\n\t\tstatusNone: 'sem acesso',\n\t\taccessEnded: 'Acesso encerrado em {date}',\n\t\taccessUntil: 'Acesso até {date}',\n\t\taccessRecordedEnd: 'Data de término registrada: {date}',\n\t\tsubscriptionLine: 'Assinatura: {status}',\n\t\trenewalCanceled: 'Renovação cancelada',\n\t\tperiodEnds: 'Período termina em {date}',\n\t\tsubActive: 'ativa',\n\t\tsubTrialing: 'em período de teste',\n\t\tsubPastDue: 'pagamento em atraso',\n\t\tsubCanceled: 'cancelada',\n\t\tsubUnpaid: 'não paga',\n\t\tsubIncomplete: 'incompleta',\n\t\tsubIncompleteExpired: 'pagamento não concluído',\n\t\tsubPaused: 'pausada',\n\t\tlicenseOffline:\n\t\t\t'Conecte-se à internet para verificar sua licença. Os recursos pagos são pausados após 48 horas sem uma verificação bem-sucedida. Sua compra não expirou.',\n\t\tlicenseCached: 'Exibindo as informações de licença salvas.',\n\t\tlicenseFresh: 'As informações da assinatura refletem a atualização de pagamento processada mais recente.',\n\t\tactionFailed:\n\t\t\t'Não foi possível concluir a solicitação. Tente novamente ou entre em contato com o suporte da extensão.',\n\t\tmanageBilling: 'Gerenciar cobrança',\n\t\tnoPortal:\n\t\t\t'O portal de cobrança não foi aberto. Você pode tentar novamente ou entrar em contato com o suporte da extensão.',\n\t\tclose: 'Fechar',\n\t\tpickerTitle: 'Escolha um perfil de cobrança',\n\t\tpickerDescription:\n\t\t\t'Compras diferentes podem ter perfis de cobrança diferentes. Escolha um perfil para gerenciar as assinaturas e os dados de pagamento vinculados a ele.',\n\t\tpickerFirstRecorded: 'Registrado pela primeira vez em {date}',\n\t\tpickerCancel: 'Cancelar',\n\t},\n\tfr: {\n\t\ttitle: 'Débloquez les fonctionnalités premium',\n\t\tdescription: 'Passez à la version supérieure pour obtenir un accès complet à cette extension.',\n\t\tupgrade: 'Mettre à niveau',\n\t\tcancel: 'Pas maintenant',\n\t\tdismiss: 'Ignorer',\n\t\tremindLater: 'Me le rappeler plus tard',\n\t\tcontinueFree: 'Continuer avec la version gratuite',\n\t\tcheckoutUnavailable: 'Les achats sont temporairement indisponibles',\n\t\tperiodMonth: '/mois',\n\t\tperiodYear: '/an',\n\t\tperiodOnce: 'paiement unique',\n\t\tfooter: 'Le paiement sécurisé s’ouvre dans un nouvel onglet.',\n\t\trestorePurchase: 'Restaurer l’achat',\n\t\tfeaturesHeading: 'Fonctionnalités premium',\n\t\tplansHeading: 'Choisissez votre formule',\n\t\tfreePlanName: 'Gratuit',\n\t\tpremiumPlanName: 'Premium',\n\t\tpopularBadge: 'Le plus populaire',\n\t\tunlockHeading: 'Débloquez les fonctionnalités premium',\n\t\tsimulatePurchase: 'Simuler l’achat',\n\t\tmockNotice:\n\t\t\t'Aperçu de développement : les licences et les paiements sont simulés. Aucun paiement ne sera prélevé.',\n\t\tsellerProvidedBy: 'Licence fournie par {name}',\n\t\tsellerUnavailable: 'Les informations sur le fournisseur de la licence ne sont pas disponibles.',\n\t\tsellerSupport: 'Assistance pour l’extension',\n\t\tsellerTerms: 'Conditions de licence',\n\t\tsellerRefunds: 'Politique de remboursement',\n\t\tsellerRole:\n\t\t\t'L’auteur est responsable des fonctionnalités de l’extension et des engagements liés à la licence. Extenshi fournit les outils de paiement et de restauration des licences.',\n\t\tlicenseTitle: 'Votre licence',\n\t\tlicenseFallbackName: 'Licence de l’extension',\n\t\tlicenseNone: 'Aucune licence n’a été trouvée pour cette installation.',\n\t\tkindOneTime: 'Achat unique',\n\t\tkindLifetime: 'Licence à vie',\n\t\tkindSubscription: 'Abonnement',\n\t\tkindLicense: 'Licence',\n\t\tstatusLine: 'Statut : {status}',\n\t\tstatusActive: 'actif',\n\t\tstatusGrace: 'période de grâce',\n\t\tstatusExpired: 'expiré',\n\t\tstatusNone: 'aucun accès',\n\t\taccessEnded: 'Accès terminé le {date}',\n\t\taccessUntil: 'Accès jusqu’au {date}',\n\t\taccessRecordedEnd: 'Date de fin enregistrée : {date}',\n\t\tsubscriptionLine: 'Abonnement : {status}',\n\t\trenewalCanceled: 'Renouvellement annulé',\n\t\tperiodEnds: 'Fin de la période le {date}',\n\t\tsubActive: 'actif',\n\t\tsubTrialing: 'en période d’essai',\n\t\tsubPastDue: 'paiement en retard',\n\t\tsubCanceled: 'résilié',\n\t\tsubUnpaid: 'impayé',\n\t\tsubIncomplete: 'incomplet',\n\t\tsubIncompleteExpired: 'paiement non finalisé',\n\t\tsubPaused: 'en pause',\n\t\tlicenseOffline:\n\t\t\t'Connectez-vous à Internet pour vérifier votre licence. Les fonctionnalités payantes sont suspendues après 48 heures sans vérification réussie. Votre achat n’a pas expiré.',\n\t\tlicenseCached: 'Affichage des informations de licence enregistrées.',\n\t\tlicenseFresh: 'Les informations d’abonnement reflètent la dernière mise à jour de paiement traitée.',\n\t\tactionFailed:\n\t\t\t'Impossible de traiter la demande. Veuillez réessayer ou contacter l’assistance de l’extension.',\n\t\tmanageBilling: 'Gérer la facturation',\n\t\tnoPortal:\n\t\t\t'Le portail de facturation ne s’est pas ouvert. Vous pouvez réessayer ou contacter l’assistance de l’extension.',\n\t\tclose: 'Fermer',\n\t\tpickerTitle: 'Choisissez un profil de facturation',\n\t\tpickerDescription:\n\t\t\t'Des achats distincts peuvent avoir des profils de facturation distincts. Choisissez-en un pour gérer ses abonnements et ses informations de paiement.',\n\t\tpickerFirstRecorded: 'Enregistré pour la première fois le {date}',\n\t\tpickerCancel: 'Annuler',\n\t},\n\tde: {\n\t\ttitle: 'Premium-Funktionen freischalten',\n\t\tdescription: 'Hol dir mit einem Upgrade vollen Zugriff auf diese Erweiterung.',\n\t\tupgrade: 'Upgraden',\n\t\tcancel: 'Jetzt nicht',\n\t\tdismiss: 'Ausblenden',\n\t\tremindLater: 'Später erinnern',\n\t\tcontinueFree: 'Mit der kostenlosen Version fortfahren',\n\t\tcheckoutUnavailable: 'Käufe sind vorübergehend nicht möglich',\n\t\tperiodMonth: '/Monat',\n\t\tperiodYear: '/Jahr',\n\t\tperiodOnce: 'einmalig',\n\t\tfooter: 'Der sichere Bezahlvorgang öffnet sich in einem neuen Tab.',\n\t\trestorePurchase: 'Kauf wiederherstellen',\n\t\tfeaturesHeading: 'Premium-Funktionen',\n\t\tplansHeading: 'Wähle deinen Tarif',\n\t\tfreePlanName: 'Kostenlos',\n\t\tpremiumPlanName: 'Premium',\n\t\tpopularBadge: 'Am beliebtesten',\n\t\tunlockHeading: 'Premium-Funktionen freischalten',\n\t\tsimulatePurchase: 'Kauf simulieren',\n\t\tmockNotice:\n\t\t\t'Entwicklungsvorschau: Lizenzen und Zahlungen werden simuliert. Es wird keine Zahlung eingezogen.',\n\t\tsellerProvidedBy: 'Lizenz bereitgestellt von {name}',\n\t\tsellerUnavailable: 'Angaben zum Lizenzgeber sind nicht verfügbar.',\n\t\tsellerSupport: 'Support für die Erweiterung',\n\t\tsellerTerms: 'Lizenzbedingungen',\n\t\tsellerRefunds: 'Rückerstattungen',\n\t\tsellerRole:\n\t\t\t'Der Autor ist für die Funktionen der Erweiterung und die Lizenzzusagen verantwortlich. Extenshi stellt die Werkzeuge für Zahlung und Lizenzwiederherstellung bereit.',\n\t\tlicenseTitle: 'Deine Lizenz',\n\t\tlicenseFallbackName: 'Erweiterungslizenz',\n\t\tlicenseNone: 'Für diese Installation wurde keine Lizenz gefunden.',\n\t\tkindOneTime: 'Einmalkauf',\n\t\tkindLifetime: 'Lebenslange Lizenz',\n\t\tkindSubscription: 'Abonnement',\n\t\tkindLicense: 'Lizenz',\n\t\tstatusLine: 'Status: {status}',\n\t\tstatusActive: 'aktiv',\n\t\tstatusGrace: 'Kulanzfrist',\n\t\tstatusExpired: 'abgelaufen',\n\t\tstatusNone: 'kein Zugriff',\n\t\taccessEnded: 'Zugriff endete am {date}',\n\t\taccessUntil: 'Zugriff bis {date}',\n\t\taccessRecordedEnd: 'Erfasstes Enddatum: {date}',\n\t\tsubscriptionLine: 'Abonnement: {status}',\n\t\trenewalCanceled: 'Wird nicht verlängert',\n\t\tperiodEnds: 'Zeitraum endet am {date}',\n\t\tsubActive: 'aktiv',\n\t\tsubTrialing: 'Testphase',\n\t\tsubPastDue: 'Zahlung überfällig',\n\t\tsubCanceled: 'gekündigt',\n\t\tsubUnpaid: 'unbezahlt',\n\t\tsubIncomplete: 'unvollständig',\n\t\tsubIncompleteExpired: 'Zahlung nicht abgeschlossen',\n\t\tsubPaused: 'pausiert',\n\t\tlicenseOffline:\n\t\t\t'Stelle eine Internetverbindung her, um deine Lizenz zu prüfen. Kostenpflichtige Funktionen werden nach 48 Stunden ohne erfolgreiche Prüfung pausiert. Dein Kauf ist nicht abgelaufen.',\n\t\tlicenseCached: 'Gespeicherte Lizenzinformationen werden angezeigt.',\n\t\tlicenseFresh: 'Die Abonnementangaben entsprechen dem zuletzt verarbeiteten Zahlungsstand.',\n\t\tactionFailed:\n\t\t\t'Die Anfrage konnte nicht abgeschlossen werden. Bitte versuche es erneut oder wende dich an den Support für die Erweiterung.',\n\t\tmanageBilling: 'Abrechnung verwalten',\n\t\tnoPortal:\n\t\t\t'Das Abrechnungsportal wurde nicht geöffnet. Du kannst es erneut versuchen oder dich an den Support für die Erweiterung wenden.',\n\t\tclose: 'Schließen',\n\t\tpickerTitle: 'Abrechnungsprofil auswählen',\n\t\tpickerDescription:\n\t\t\t'Verschiedene Käufe können eigene Abrechnungsprofile haben. Wähle eines aus, um seine Abonnements und Zahlungsdaten zu verwalten.',\n\t\tpickerFirstRecorded: 'Erstmals erfasst am {date}',\n\t\tpickerCancel: 'Abbrechen',\n\t},\n\tit: {\n\t\ttitle: 'Sblocca le funzionalità premium',\n\t\tdescription: 'Effettua l’upgrade per ottenere l’accesso completo a questa estensione.',\n\t\tupgrade: 'Effettua l’upgrade',\n\t\tcancel: 'Non ora',\n\t\tdismiss: 'Ignora',\n\t\tremindLater: 'Ricordamelo più tardi',\n\t\tcontinueFree: 'Continua con la versione gratuita',\n\t\tcheckoutUnavailable: 'Gli acquisti sono temporaneamente non disponibili',\n\t\tperiodMonth: '/mese',\n\t\tperiodYear: '/anno',\n\t\tperiodOnce: 'una tantum',\n\t\tfooter: 'Il checkout sicuro si apre in una nuova scheda.',\n\t\trestorePurchase: 'Ripristina acquisto',\n\t\tfeaturesHeading: 'Funzionalità premium',\n\t\tplansHeading: 'Scegli il tuo piano',\n\t\tfreePlanName: 'Gratuito',\n\t\tpremiumPlanName: 'Premium',\n\t\tpopularBadge: 'Il più scelto',\n\t\tunlockHeading: 'Sblocca le funzionalità premium',\n\t\tsimulatePurchase: 'Simula acquisto',\n\t\tmockNotice:\n\t\t\t'Anteprima di sviluppo: licenze e pagamenti sono simulati. Non verrà addebitato alcun pagamento.',\n\t\tsellerProvidedBy: 'Licenza fornita da {name}',\n\t\tsellerUnavailable: 'I dettagli del fornitore della licenza non sono disponibili.',\n\t\tsellerSupport: 'Assistenza per l’estensione',\n\t\tsellerTerms: 'Termini di licenza',\n\t\tsellerRefunds: 'Politica di rimborso',\n\t\tsellerRole:\n\t\t\t'L’autore è responsabile delle funzionalità dell’estensione e degli impegni relativi alla licenza. Extenshi fornisce gli strumenti di pagamento e di recupero della licenza.',\n\t\tlicenseTitle: 'La tua licenza',\n\t\tlicenseFallbackName: 'Licenza dell’estensione',\n\t\tlicenseNone: 'Nessuna licenza trovata in questa installazione.',\n\t\tkindOneTime: 'Acquisto una tantum',\n\t\tkindLifetime: 'Licenza a vita',\n\t\tkindSubscription: 'Abbonamento',\n\t\tkindLicense: 'Licenza',\n\t\tstatusLine: 'Stato: {status}',\n\t\tstatusActive: 'attivo',\n\t\tstatusGrace: 'periodo di tolleranza',\n\t\tstatusExpired: 'scaduto',\n\t\tstatusNone: 'nessun accesso',\n\t\taccessEnded: 'Accesso terminato il {date}',\n\t\taccessUntil: 'Accesso fino al {date}',\n\t\taccessRecordedEnd: 'Data di fine registrata: {date}',\n\t\tsubscriptionLine: 'Abbonamento: {status}',\n\t\trenewalCanceled: 'Rinnovo annullato',\n\t\tperiodEnds: 'Il periodo termina il {date}',\n\t\tsubActive: 'attivo',\n\t\tsubTrialing: 'in prova',\n\t\tsubPastDue: 'pagamento in ritardo',\n\t\tsubCanceled: 'disdetto',\n\t\tsubUnpaid: 'non pagato',\n\t\tsubIncomplete: 'incompleto',\n\t\tsubIncompleteExpired: 'pagamento non completato',\n\t\tsubPaused: 'in pausa',\n\t\tlicenseOffline:\n\t\t\t'Connettiti a internet per verificare la tua licenza. Le funzionalità a pagamento vengono sospese dopo 48 ore senza una verifica riuscita. Il tuo acquisto non è scaduto.',\n\t\tlicenseCached: 'Vengono mostrate le informazioni salvate sulla licenza.',\n\t\tlicenseFresh:\n\t\t\t'Le informazioni sull’abbonamento riflettono l’ultimo aggiornamento di pagamento elaborato.',\n\t\tactionFailed: 'Impossibile completare la richiesta. Riprova o contatta l’assistenza per l’estensione.',\n\t\tmanageBilling: 'Gestisci fatturazione',\n\t\tnoPortal:\n\t\t\t'Il portale di fatturazione non è stato aperto. Puoi riprovare o contattare l’assistenza per l’estensione.',\n\t\tclose: 'Chiudi',\n\t\tpickerTitle: 'Scegli un profilo di fatturazione',\n\t\tpickerDescription:\n\t\t\t'Acquisti diversi possono avere profili di fatturazione diversi. Scegline uno per gestirne gli abbonamenti e i dati di pagamento.',\n\t\tpickerFirstRecorded: 'Registrato per la prima volta il {date}',\n\t\tpickerCancel: 'Annulla',\n\t},\n\tru: {\n\t\ttitle: 'Откройте доступ к премиум-функциям',\n\t\tdescription: 'Перейдите на премиум, чтобы получить полный доступ к этому расширению.',\n\t\tupgrade: 'Перейти на премиум',\n\t\tcancel: 'Не сейчас',\n\t\tdismiss: 'Скрыть',\n\t\tremindLater: 'Напомнить позже',\n\t\tcontinueFree: 'Продолжить в бесплатной версии',\n\t\tcheckoutUnavailable: 'Покупки временно недоступны',\n\t\tperiodMonth: '/мес.',\n\t\tperiodYear: '/год',\n\t\tperiodOnce: 'разово',\n\t\tfooter: 'Защищённая страница оплаты откроется в новой вкладке.',\n\t\trestorePurchase: 'Восстановить покупку',\n\t\tfeaturesHeading: 'Премиум-функции',\n\t\tplansHeading: 'Выберите тарифный план',\n\t\tfreePlanName: 'Бесплатный',\n\t\tpremiumPlanName: 'Премиум',\n\t\tpopularBadge: 'Самый популярный',\n\t\tunlockHeading: 'Откройте доступ к премиум-функциям',\n\t\tsimulatePurchase: 'Имитировать покупку',\n\t\tmockNotice: 'Режим разработки: лицензии и платежи имитируются. Деньги не будут списаны.',\n\t\tsellerProvidedBy: 'Лицензию предоставляет {name}',\n\t\tsellerUnavailable: 'Сведения о поставщике лицензии недоступны.',\n\t\tsellerSupport: 'Поддержка расширения',\n\t\tsellerTerms: 'Условия лицензии',\n\t\tsellerRefunds: 'Возврат средств',\n\t\tsellerRole:\n\t\t\t'Автор отвечает за работу расширения и обязательства по лицензии. Extenshi предоставляет инструменты для оплаты и восстановления лицензий.',\n\t\tlicenseTitle: 'Ваша лицензия',\n\t\tlicenseFallbackName: 'Лицензия на расширение',\n\t\tlicenseNone: 'Для этой установки лицензия не найдена.',\n\t\tkindOneTime: 'Разовая покупка',\n\t\tkindLifetime: 'Бессрочная лицензия',\n\t\tkindSubscription: 'Подписка',\n\t\tkindLicense: 'Лицензия',\n\t\tstatusLine: 'Статус: {status}',\n\t\tstatusActive: 'действует',\n\t\tstatusGrace: 'льготный период',\n\t\tstatusExpired: 'срок истёк',\n\t\tstatusNone: 'нет доступа',\n\t\taccessEnded: 'Доступ закончился: {date}',\n\t\taccessUntil: 'Доступ до {date}',\n\t\taccessRecordedEnd: 'Зафиксированная дата окончания: {date}',\n\t\tsubscriptionLine: 'Подписка: {status}',\n\t\trenewalCanceled: 'Продление отменено',\n\t\tperiodEnds: 'Период заканчивается: {date}',\n\t\tsubActive: 'активна',\n\t\tsubTrialing: 'пробный период',\n\t\tsubPastDue: 'платёж просрочен',\n\t\tsubCanceled: 'отменена',\n\t\tsubUnpaid: 'не оплачена',\n\t\tsubIncomplete: 'ожидает первого платежа',\n\t\tsubIncompleteExpired: 'платёж не завершён',\n\t\tsubPaused: 'приостановлена',\n\t\tlicenseOffline:\n\t\t\t'Подключитесь к интернету, чтобы проверить лицензию. Если успешной проверки не было 48 часов, платные функции приостанавливаются. Срок действия вашей покупки не истёк.',\n\t\tlicenseCached: 'Показаны сохранённые сведения о лицензии.',\n\t\tlicenseFresh: 'Сведения о подписке соответствуют последнему обработанному обновлению платежа.',\n\t\tactionFailed: 'Не удалось выполнить запрос. Попробуйте ещё раз или обратитесь в поддержку расширения.',\n\t\tmanageBilling: 'Управление оплатой',\n\t\tnoPortal: 'Портал оплаты не открылся. Можно повторить попытку или обратиться в поддержку расширения.',\n\t\tclose: 'Закрыть',\n\t\tpickerTitle: 'Выберите платёжный профиль',\n\t\tpickerDescription:\n\t\t\t'У разных покупок могут быть разные платёжные профили. Выберите профиль, чтобы управлять его подписками и платёжными данными.',\n\t\tpickerFirstRecorded: 'Впервые зафиксирован: {date}',\n\t\tpickerCancel: 'Отмена',\n\t},\n\tja: {\n\t\ttitle: 'プレミアム機能をアンロック',\n\t\tdescription: 'アップグレードすると、この拡張機能のすべての機能をご利用いただけます。',\n\t\tupgrade: 'アップグレード',\n\t\tcancel: '今はしない',\n\t\tdismiss: '非表示にする',\n\t\tremindLater: 'あとで通知する',\n\t\tcontinueFree: '無料版のまま使い続ける',\n\t\tcheckoutUnavailable: '一時的に購入できません',\n\t\tperiodMonth: '/月',\n\t\tperiodYear: '/年',\n\t\tperiodOnce: '買い切り',\n\t\tfooter: '安全なチェックアウト画面が新しいタブで開きます。',\n\t\trestorePurchase: '購入を復元',\n\t\tfeaturesHeading: 'プレミアム機能',\n\t\tplansHeading: 'プランを選択',\n\t\tfreePlanName: '無料',\n\t\tpremiumPlanName: 'プレミアム',\n\t\tpopularBadge: '一番人気',\n\t\tunlockHeading: 'プレミアム機能をアンロック',\n\t\tsimulatePurchase: '購入をシミュレート',\n\t\tmockNotice: '開発用プレビュー:ライセンスと支払いはシミュレーションです。実際の請求は発生しません。',\n\t\tsellerProvidedBy: 'ライセンス提供者:{name}',\n\t\tsellerUnavailable: 'ライセンス提供者の情報を取得できません。',\n\t\tsellerSupport: '拡張機能のサポート',\n\t\tsellerTerms: 'ライセンス条件',\n\t\tsellerRefunds: '返金ポリシー',\n\t\tsellerRole:\n\t\t\t'拡張機能の機能とライセンス上の約束については、開発者が責任を負います。Extenshiは、お支払いとライセンス復元のためのツールを提供します。',\n\t\tlicenseTitle: 'ご利用のライセンス',\n\t\tlicenseFallbackName: '拡張機能のライセンス',\n\t\tlicenseNone: 'このインストール環境ではライセンスが見つかりませんでした。',\n\t\tkindOneTime: '買い切り',\n\t\tkindLifetime: 'ライフタイムライセンス',\n\t\tkindSubscription: 'サブスクリプション',\n\t\tkindLicense: 'ライセンス',\n\t\tstatusLine: 'ステータス:{status}',\n\t\tstatusActive: '有効',\n\t\tstatusGrace: '猶予期間中',\n\t\tstatusExpired: '期限切れ',\n\t\tstatusNone: '利用不可',\n\t\taccessEnded: '利用終了日時:{date}',\n\t\taccessUntil: '利用期限:{date}',\n\t\taccessRecordedEnd: '記録上の終了日時:{date}',\n\t\tsubscriptionLine: 'サブスクリプション:{status}',\n\t\trenewalCanceled: '更新停止済み',\n\t\tperiodEnds: '期間終了日:{date}',\n\t\tsubActive: '有効',\n\t\tsubTrialing: 'トライアル中',\n\t\tsubPastDue: '支払い期限超過',\n\t\tsubCanceled: '解約済み',\n\t\tsubUnpaid: '未払い',\n\t\tsubIncomplete: '手続き未完了',\n\t\tsubIncompleteExpired: '支払い未完了',\n\t\tsubPaused: '一時停止中',\n\t\tlicenseOffline:\n\t\t\t'ライセンスを確認するには、インターネットに接続してください。確認に成功しないまま48時間が経過すると、有料機能は一時停止されます。ご購入が失効したわけではありません。',\n\t\tlicenseCached: '保存済みのライセンス情報を表示しています。',\n\t\tlicenseFresh: 'サブスクリプション情報には、処理済みの最新の支払い情報が反映されています。',\n\t\tactionFailed:\n\t\t\t'リクエストを完了できませんでした。もう一度お試しいただくか、拡張機能のサポートにお問い合わせください。',\n\t\tmanageBilling: '請求情報を管理',\n\t\tnoPortal: '請求ポータルを開けませんでした。再試行するか、拡張機能のサポートにお問い合わせください。',\n\t\tclose: '閉じる',\n\t\tpickerTitle: '請求プロファイルを選択',\n\t\tpickerDescription:\n\t\t\t'購入ごとに別々の請求プロファイルがある場合があります。サブスクリプションと支払い情報を管理するプロファイルを1つ選択してください。',\n\t\tpickerFirstRecorded: '初回記録日:{date}',\n\t\tpickerCancel: 'キャンセル',\n\t},\n\tko: {\n\t\ttitle: '프리미엄 기능 잠금 해제',\n\t\tdescription: '업그레이드하면 이 확장 프로그램의 모든 기능을 이용할 수 있습니다.',\n\t\tupgrade: '업그레이드',\n\t\tcancel: '나중에',\n\t\tdismiss: '닫기',\n\t\tremindLater: '나중에 다시 알림',\n\t\tcontinueFree: '무료 버전으로 계속하기',\n\t\tcheckoutUnavailable: '일시적으로 구매할 수 없습니다',\n\t\tperiodMonth: '/월',\n\t\tperiodYear: '/년',\n\t\tperiodOnce: '일회성',\n\t\tfooter: '안전한 결제 페이지가 새 탭에서 열립니다.',\n\t\trestorePurchase: '구매 복원',\n\t\tfeaturesHeading: '프리미엄 기능',\n\t\tplansHeading: '요금제 선택',\n\t\tfreePlanName: '무료',\n\t\tpremiumPlanName: '프리미엄',\n\t\tpopularBadge: '가장 인기',\n\t\tunlockHeading: '프리미엄 기능 잠금 해제',\n\t\tsimulatePurchase: '구매 시뮬레이션',\n\t\tmockNotice: '개발용 미리보기: 라이선스와 결제는 시뮬레이션됩니다. 실제로 결제되지 않습니다.',\n\t\tsellerProvidedBy: '라이선스 제공자: {name}',\n\t\tsellerUnavailable: '라이선스 제공자 정보를 확인할 수 없습니다.',\n\t\tsellerSupport: '확장 프로그램 지원',\n\t\tsellerTerms: '라이선스 약관',\n\t\tsellerRefunds: '환불 정책',\n\t\tsellerRole:\n\t\t\t'확장 프로그램의 기능과 라이선스 관련 약속은 개발자가 책임집니다. Extenshi는 결제 및 라이선스 복구 도구를 제공합니다.',\n\t\tlicenseTitle: '내 라이선스',\n\t\tlicenseFallbackName: '확장 프로그램 라이선스',\n\t\tlicenseNone: '이 설치 환경에서 라이선스를 찾지 못했습니다.',\n\t\tkindOneTime: '일회성 구매',\n\t\tkindLifetime: '평생 라이선스',\n\t\tkindSubscription: '구독',\n\t\tkindLicense: '라이선스',\n\t\tstatusLine: '상태: {status}',\n\t\tstatusActive: '활성',\n\t\tstatusGrace: '유예 기간 중',\n\t\tstatusExpired: '만료됨',\n\t\tstatusNone: '이용 권한 없음',\n\t\taccessEnded: '이용 종료 일시: {date}',\n\t\taccessUntil: '이용 기한: {date}',\n\t\taccessRecordedEnd: '기록된 종료 일시: {date}',\n\t\tsubscriptionLine: '구독: {status}',\n\t\trenewalCanceled: '갱신 취소됨',\n\t\tperiodEnds: '기간 종료일: {date}',\n\t\tsubActive: '활성',\n\t\tsubTrialing: '체험 중',\n\t\tsubPastDue: '결제 연체',\n\t\tsubCanceled: '해지됨',\n\t\tsubUnpaid: '미결제',\n\t\tsubIncomplete: '미완료',\n\t\tsubIncompleteExpired: '결제 미완료',\n\t\tsubPaused: '일시 중지됨',\n\t\tlicenseOffline:\n\t\t\t'라이선스를 확인하려면 인터넷에 연결해 주세요. 확인에 성공하지 못한 채 48시간이 지나면 유료 기능이 일시 중지됩니다. 구매가 만료된 것은 아닙니다.',\n\t\tlicenseCached: '저장된 라이선스 정보를 표시하고 있습니다.',\n\t\tlicenseFresh: '구독 정보에는 가장 최근에 처리된 결제 내역이 반영되어 있습니다.',\n\t\tactionFailed: '요청을 완료할 수 없습니다. 다시 시도하거나 확장 프로그램 지원 창구에 문의해 주세요.',\n\t\tmanageBilling: '결제 관리',\n\t\tnoPortal: '결제 포털이 열리지 않았습니다. 다시 시도하거나 확장 프로그램 지원 창구에 문의해 주세요.',\n\t\tclose: '닫기',\n\t\tpickerTitle: '결제 프로필 선택',\n\t\tpickerDescription:\n\t\t\t'구매마다 결제 프로필이 다를 수 있습니다. 구독과 결제 정보를 관리할 프로필을 하나 선택해 주세요.',\n\t\tpickerFirstRecorded: '최초 기록일: {date}',\n\t\tpickerCancel: '취소',\n\t},\n\t'zh-CN': {\n\t\ttitle: '解锁高级功能',\n\t\tdescription: '升级即可完整使用此扩展程序。',\n\t\tupgrade: '升级',\n\t\tcancel: '以后再说',\n\t\tdismiss: '忽略',\n\t\tremindLater: '稍后提醒我',\n\t\tcontinueFree: '继续使用免费版',\n\t\tcheckoutUnavailable: '暂时无法购买',\n\t\tperiodMonth: '/月',\n\t\tperiodYear: '/年',\n\t\tperiodOnce: '一次性',\n\t\tfooter: '安全结账页面将在新标签页中打开。',\n\t\trestorePurchase: '恢复购买',\n\t\tfeaturesHeading: '高级功能',\n\t\tplansHeading: '选择您的方案',\n\t\tfreePlanName: '免费版',\n\t\tpremiumPlanName: '高级版',\n\t\tpopularBadge: '最受欢迎',\n\t\tunlockHeading: '解锁高级功能',\n\t\tsimulatePurchase: '模拟购买',\n\t\tmockNotice: '开发预览:许可证和付款均为模拟,不会实际扣款。',\n\t\tsellerProvidedBy: '许可证由 {name} 提供',\n\t\tsellerUnavailable: '无法获取许可证提供方的详细信息。',\n\t\tsellerSupport: '扩展程序支持',\n\t\tsellerTerms: '许可条款',\n\t\tsellerRefunds: '退款政策',\n\t\tsellerRole: '作者负责扩展程序的功能及许可证相关承诺。Extenshi 提供支付及许可证恢复工具。',\n\t\tlicenseTitle: '您的许可证',\n\t\tlicenseFallbackName: '扩展程序许可证',\n\t\tlicenseNone: '此安装中未找到许可证。',\n\t\tkindOneTime: '一次性购买',\n\t\tkindLifetime: '终身许可证',\n\t\tkindSubscription: '订阅',\n\t\tkindLicense: '许可证',\n\t\tstatusLine: '状态:{status}',\n\t\tstatusActive: '有效',\n\t\tstatusGrace: '宽限期',\n\t\tstatusExpired: '已过期',\n\t\tstatusNone: '无使用权限',\n\t\taccessEnded: '使用权限已于 {date} 结束',\n\t\taccessUntil: '可使用至 {date}',\n\t\taccessRecordedEnd: '记录的结束日期:{date}',\n\t\tsubscriptionLine: '订阅:{status}',\n\t\trenewalCanceled: '已取消续订',\n\t\tperiodEnds: '当前计费周期于 {date} 结束',\n\t\tsubActive: '有效',\n\t\tsubTrialing: '试用中',\n\t\tsubPastDue: '付款逾期',\n\t\tsubCanceled: '已取消',\n\t\tsubUnpaid: '未付款',\n\t\tsubIncomplete: '未完成',\n\t\tsubIncompleteExpired: '付款未完成',\n\t\tsubPaused: '已暂停',\n\t\tlicenseOffline:\n\t\t\t'请连接互联网以验证您的许可证。如果连续48小时未能成功验证,付费功能将暂停。您的购买仍然有效。',\n\t\tlicenseCached: '正在显示已保存的许可证信息。',\n\t\tlicenseFresh: '订阅信息反映的是最近一次已处理的付款更新。',\n\t\tactionFailed: '无法完成请求。请重试或联系扩展程序支持。',\n\t\tmanageBilling: '管理账单',\n\t\tnoPortal: '未能打开账单门户。您可以重试或联系扩展程序支持。',\n\t\tclose: '关闭',\n\t\tpickerTitle: '选择账单资料',\n\t\tpickerDescription: '不同的购买可以有各自的账单资料。请选择一个,以管理其订阅和付款信息。',\n\t\tpickerFirstRecorded: '首次记录于 {date}',\n\t\tpickerCancel: '取消',\n\t},\n\tar: {\n\t\ttitle: 'احصل على الميزات المميزة',\n\t\tdescription: 'قم بالترقية للوصول الكامل إلى هذه الإضافة.',\n\t\tupgrade: 'ترقية',\n\t\tcancel: 'ليس الآن',\n\t\tdismiss: 'تجاهل',\n\t\tremindLater: 'ذكّرني لاحقًا',\n\t\tcontinueFree: 'المتابعة بالإصدار المجاني',\n\t\tcheckoutUnavailable: 'عمليات الشراء غير متاحة مؤقتًا',\n\t\tperiodMonth: '/شهر',\n\t\tperiodYear: '/سنة',\n\t\tperiodOnce: 'لمرة واحدة',\n\t\tfooter: 'تُفتح صفحة الدفع الآمن في علامة تبويب جديدة.',\n\t\trestorePurchase: 'استعادة الشراء',\n\t\tfeaturesHeading: 'الميزات المميزة',\n\t\tplansHeading: 'اختر خطتك',\n\t\tfreePlanName: 'مجاني',\n\t\tpremiumPlanName: 'مميز',\n\t\tpopularBadge: 'الأكثر رواجًا',\n\t\tunlockHeading: 'احصل على الميزات المميزة',\n\t\tsimulatePurchase: 'محاكاة الشراء',\n\t\tmockNotice: 'معاينة التطوير: تجري محاكاة التراخيص والمدفوعات، ولن يُحصَّل أي مبلغ.',\n\t\tsellerProvidedBy: 'الترخيص مقدَّم من البائع {name}',\n\t\tsellerUnavailable: 'بيانات مانح الترخيص غير متاحة.',\n\t\tsellerSupport: 'دعم الإضافة',\n\t\tsellerTerms: 'شروط الترخيص',\n\t\tsellerRefunds: 'سياسة استرداد المبالغ',\n\t\tsellerRole:\n\t\t\t'يتحمّل مطوّر الإضافة المسؤولية عن وظائفها وعن التزامات الترخيص، وتوفّر Extenshi أدوات الدفع واستعادة التراخيص.',\n\t\tlicenseTitle: 'ترخيصك',\n\t\tlicenseFallbackName: 'ترخيص الإضافة',\n\t\tlicenseNone: 'لم يُعثر على أي ترخيص في هذا التثبيت.',\n\t\tkindOneTime: 'شراء لمرة واحدة',\n\t\tkindLifetime: 'ترخيص مدى الحياة',\n\t\tkindSubscription: 'اشتراك',\n\t\tkindLicense: 'ترخيص',\n\t\tstatusLine: 'الحالة: {status}',\n\t\tstatusActive: 'نشطة',\n\t\tstatusGrace: 'في فترة السماح',\n\t\tstatusExpired: 'منتهية الصلاحية',\n\t\tstatusNone: 'بلا وصول',\n\t\taccessEnded: 'انتهى الوصول في {date}',\n\t\taccessUntil: 'الوصول متاح حتى {date}',\n\t\taccessRecordedEnd: 'تاريخ الانتهاء المسجَّل: {date}',\n\t\tsubscriptionLine: 'الاشتراك: {status}',\n\t\trenewalCanceled: 'أُلغي التجديد',\n\t\tperiodEnds: 'تنتهي الفترة الحالية في {date}',\n\t\tsubActive: 'نشط',\n\t\tsubTrialing: 'فترة تجريبية',\n\t\tsubPastDue: 'متأخر السداد',\n\t\tsubCanceled: 'ملغى',\n\t\tsubUnpaid: 'غير مدفوع',\n\t\tsubIncomplete: 'غير مكتمل',\n\t\tsubIncompleteExpired: 'لم يكتمل الدفع',\n\t\tsubPaused: 'متوقف مؤقتًا',\n\t\tlicenseOffline:\n\t\t\t'اتصل بالإنترنت للتحقق من ترخيصك. تتوقف الميزات المدفوعة مؤقتًا إذا مرّت 48 ساعة دون تحقق ناجح. لم تنتهِ صلاحية عملية الشراء.',\n\t\tlicenseCached: 'تُعرض معلومات الترخيص المحفوظة.',\n\t\tlicenseFresh: 'تعكس معلومات الاشتراك آخر تحديث للدفع تمت معالجته.',\n\t\tactionFailed: 'تعذّر إكمال الطلب. يُرجى المحاولة مرة أخرى أو التواصل مع دعم الإضافة.',\n\t\tmanageBilling: 'إدارة الفوترة',\n\t\tnoPortal: 'لم تُفتح بوابة الفوترة. يمكنك المحاولة مرة أخرى أو التواصل مع دعم الإضافة.',\n\t\tclose: 'إغلاق',\n\t\tpickerTitle: 'اختر ملف فوترة',\n\t\tpickerDescription:\n\t\t\t'يمكن أن تكون لعمليات الشراء المنفصلة ملفات فوترة منفصلة. اختر ملفًا منها لإدارة اشتراكاته وتفاصيل الدفع الخاصة به.',\n\t\tpickerFirstRecorded: 'سُجِّل لأول مرة في {date}',\n\t\tpickerCancel: 'إلغاء',\n\t},\n}\n// END GENERATED TRANSLATIONS\n\n/** Our dictionary language for a tag: exact, then pt → pt-BR, zh(-CN/SG/Hans) → zh-CN, then the bare language. */\nexport function sdkLocale(locale: string | null | undefined): SdkLocale {\n\tconst tag = wireLocale(locale)\n\tif (!tag) return 'en'\n\tconst exact = SDK_LOCALES.find((l) => l.toLowerCase() === tag.toLowerCase())\n\tif (exact) return exact\n\tconst [lang, region] = tag.split('-')\n\tif (lang === 'pt') return 'pt-BR'\n\t// Traditional-script regions read English rather than Simplified characters.\n\tif (lang === 'zh') return region && ['TW', 'HK', 'MO'].includes(region) ? 'en' : 'zh-CN'\n\treturn SDK_LOCALES.find((l) => l === lang) ?? 'en'\n}\n\nexport function sdkDir(locale: string | null | undefined): 'ltr' | 'rtl' {\n\tconst lang = wireLocale(locale)?.split('-')[0]\n\treturn lang && ['ar', 'he', 'fa', 'ur'].includes(lang) ? 'rtl' : 'ltr'\n}\n\n/** English merged with the translation for `locale`. */\nexport function sdkStrings(locale: string | null | undefined): SdkStrings {\n\tconst tag = sdkLocale(locale)\n\treturn tag === 'en' ? SDK_STRINGS_EN : { ...SDK_STRINGS_EN, ...TRANSLATIONS[tag] }\n}\n\n/** Fill `{placeholders}` once; a value containing braces is inserted literally. */\nexport function fill(message: string, values: Record<string, string>): string {\n\treturn message.replace(/\\{([a-z]+)\\}/g, (whole, key: string) => values[key] ?? whole)\n}\n\n/** The raw translation block, for completeness tests. */\nexport function sdkTranslations(locale: Exclude<SdkLocale, 'en'>): SdkStrings | undefined {\n\treturn TRANSLATIONS[locale]\n}\n","/**\n * Buyer-facing withdrawal-waiver text (EU/EEA digital content, Directive\n * 2011/83/EU art. 16(m); UK CCR 2013 reg. 37), per text version and SDK\n * language. Its own module, not part of the paywall dictionary, so Lite can\n * show it without bundling every paywall string.\n *\n * The recorded consent names the version, so a version's words never change:\n * new wording is a new version here and a new PAY_WITHDRAWAL_WAIVER_VERSION.\n *\n * MIRRORED in shared-types/pay-withdrawal-waiver.ts, which the purchase\n * confirmation email quotes; shared-types/pay-withdrawal-waiver.test.ts fails\n * unless both copies are byte-identical. Change them together.\n */\n\nimport { fill, type SdkLocale, sdkLocale } from '../paywall/i18n.js'\nimport { PAY_WITHDRAWAL_WAIVER_VERSION } from '../types/contract.js'\n\nexport const WITHDRAWAL_WAIVER_TEXTS: Readonly<Record<string, Readonly<Record<SdkLocale, string>>>> = {\n\t[PAY_WITHDRAWAL_WAIVER_VERSION]: {\n\t\ten: 'I agree that {seller} starts supplying the digital content immediately, and I acknowledge that I lose my right of withdrawal once supply has begun.',\n\t\tes: 'Acepto que {seller} comience a suministrar el contenido digital de inmediato y reconozco que pierdo mi derecho de desistimiento una vez iniciado el suministro.',\n\t\t'pt-BR':\n\t\t\t'Concordo que {seller} comece a fornecer o conteúdo digital imediatamente e reconheço que perco meu direito de arrependimento assim que o fornecimento tiver início.',\n\t\tfr: 'J’accepte que {seller} commence immédiatement la fourniture du contenu numérique et je reconnais perdre mon droit de rétractation dès le début de la fourniture.',\n\t\tde: 'Ich stimme zu, dass {seller} sofort mit der Bereitstellung der digitalen Inhalte beginnt, und ich nehme zur Kenntnis, dass ich mit Beginn der Bereitstellung mein Widerrufsrecht verliere.',\n\t\tit: 'Accetto che {seller} inizi immediatamente la fornitura del contenuto digitale e riconosco di perdere il mio diritto di recesso una volta iniziata la fornitura.',\n\t\tru: 'Я соглашаюсь с тем, что {seller} немедленно начнёт предоставление цифрового контента, и подтверждаю, что утрачиваю право на отказ от договора с момента начала предоставления.',\n\t\tja: '{seller}がデジタルコンテンツの提供を直ちに開始することに同意し、提供の開始後は撤回権を失うことを了承します。',\n\t\tko: '{seller}의 디지털 콘텐츠 제공이 즉시 시작되는 것에 동의하며, 제공이 시작되면 청약철회권을 상실한다는 점을 확인합니다.',\n\t\t'zh-CN': '我同意 {seller} 立即开始提供数字内容,并确认一旦开始提供,我将失去撤回权。',\n\t\tar: 'أوافق على أن يبدأ {seller} فورًا في تقديم المحتوى الرقمي، وأُقرّ بأنني أفقد حقي في العدول عن العقد بمجرد بدء التقديم.',\n\t},\n}\n\n/**\n * The waiver text to show for `serverVersion`, and the version to send with\n * the consent. A version this SDK does not know (a newer server) shows this\n * SDK's current text and sends its version: the consent always names the words\n * actually shown.\n */\nexport function withdrawalWaiverText(\n\tserverVersion: string,\n\tlocale: string | null | undefined,\n\tseller: string,\n): { version: string; text: string } {\n\t// Own keys only: `toString` / `__proto__` from a server are just unknown versions.\n\tconst known = Object.keys(WITHDRAWAL_WAIVER_TEXTS).includes(serverVersion)\n\tconst version = known ? serverVersion : PAY_WITHDRAWAL_WAIVER_VERSION\n\treturn { version, text: fill(WITHDRAWAL_WAIVER_TEXTS[version][sdkLocale(locale)], { seller }) }\n}\n","/**\n * `ExtenshiPayLite` — entitlement, feature gating and hosted checkout, without\n * the paywall UI. This is what the `lite` bundle exports; the full `ExtenshiPay`\n * extends it with `getOffer()` / `showPaywall()`.\n *\n * Data that leaves the extension: `publishableKey`, `endUserRef`, `sku`,\n * `locale` and checkout session IDs. Explicit recovery also sends its session ID,\n * challenge and claim secret (POST body). Email stays on the hosted page.\n */\n\nimport { MockTransport } from '../api/mock.js'\nimport { PayApi } from '../api/pay-api.js'\nimport { HttpTransport, type Transport } from '../api/transport.js'\nimport { CheckoutManager } from '../payment/checkout.js'\nimport { EntitlementManager, MAX_CLOCK_SKEW_MS } from '../payment/entitlement.js'\nimport { checkFeatures, hasFeature, isEntitled } from '../payment/features.js'\nimport { createRecoveryStorage, RecoveryManager } from '../payment/recovery.js'\nimport { verifyEntitlementSignature } from '../payment/signature.js'\nimport { withdrawalWaiverText } from '../payment/withdrawal-waiver.js'\nimport type { ExtenshiPayConfig, ResolvedConfig } from '../types/config.js'\nimport type { PayOfferResponse } from '../types/contract.js'\nimport { PAY_END_USER_REF_RE } from '../types/contract.js'\nimport type {\n\tCheckoutOptions,\n\tCheckoutResult,\n\tCustomerPortalOptions,\n\tEntitlement,\n\tGetEntitlementOptions,\n\tLicenseSummary,\n\tRequireFeatureOptions,\n\tRestoreOptions,\n\tRestoreResult,\n} from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { ExtenshiPayEvents } from '../types/events.js'\nimport { logger } from '../utils/logger.js'\nimport { VERSION } from '../version.js'\nimport { resolveConfig } from './config.js'\nimport { EventEmitter, type Listener } from './event-emitter.js'\nimport { END_USER_REF_STORAGE_KEY, getOrCreateEndUserRef } from './identity.js'\nimport { createStorage, type StorageAdapter } from './storage.js'\n\n/** Server-side offer cache is 5 min; mirror it in memory. */\nconst OFFER_TTL_MS = 5 * 60 * 1000\n\n/** Injection points for tests and unusual hosts. */\nexport interface ExtenshiPayDeps {\n\tstorage?: StorageAdapter\n\t/** Trusted extension-only storage; never share this adapter with content scripts. */\n\trecoveryStorage?: StorageAdapter\n\ttransport?: Transport\n\tfetch?: typeof fetch\n\topenUrl?: (url: string) => void | Promise<void>\n\tnow?: () => number\n}\n\nexport class ExtenshiPayLite {\n\tstatic readonly version = VERSION\n\n\tprotected readonly config: ResolvedConfig\n\tprotected readonly emitter = new EventEmitter<ExtenshiPayEvents>()\n\tprotected readonly storage: StorageAdapter\n\tprotected readonly api: PayApi\n\tprotected readonly entitlements: EntitlementManager\n\tprotected readonly checkout: CheckoutManager\n\tprotected readonly recovery: RecoveryManager\n\tprivate readonly now: () => number\n\tprivate endUserRef: string | null = null\n\tprivate endUserRefPromise: Promise<string> | null = null\n\tprivate offer: { value: PayOfferResponse; fetchedAt: number } | null = null\n\tprivate offerInflight: Promise<PayOfferResponse> | null = null\n\tprivate readyPromise: Promise<void> | null = null\n\tprivate destroyed = false\n\n\tconstructor(config: ExtenshiPayConfig, deps: ExtenshiPayDeps = {}) {\n\t\tthis.config = resolveConfig(config)\n\t\tlogger.configure({ logLevel: this.config.logLevel, debug: this.config.debug })\n\t\tthis.now = deps.now ?? (() => Date.now())\n\t\tthis.storage = deps.storage ?? createStorage()\n\n\t\tconst transport =\n\t\t\tdeps.transport ??\n\t\t\t(this.config.mock\n\t\t\t\t? new MockTransport(this.config.mockData ?? {})\n\t\t\t\t: new HttpTransport({ apiUrl: this.config.apiUrl, fetchImpl: deps.fetch }))\n\t\tthis.api = new PayApi(transport, this.config.publishableKey)\n\n\t\tthis.entitlements = new EntitlementManager({\n\t\t\tapi: this.api,\n\t\t\tstorage: this.storage,\n\t\t\tpublishableKey: this.config.publishableKey,\n\t\t\tcacheTtlMs: this.config.cacheTtlMs,\n\t\t\tsource: this.config.mock ? 'mock' : 'network',\n\t\t\tgetEndUserRef: () => this.getEndUserRef(),\n\t\t\tgetPublicKey: () => this.getPublicKey(),\n\t\t\tonChange: (entitlement) => this.emitter.emit('entitlement:changed', entitlement),\n\t\t\tonError: (error) => this.reportError(error),\n\t\t\tnow: this.now,\n\t\t})\n\n\t\tthis.checkout = new CheckoutManager({\n\t\t\tapi: this.api,\n\t\t\tstorage: this.storage,\n\t\t\tpublishableKey: this.config.publishableKey,\n\t\t\tlocale: this.config.locale,\n\t\t\tgetEndUserRef: () => this.getEndUserRef(),\n\t\t\tonComplete: (envelope) => this.entitlements.accept(envelope),\n\t\t\temit: (event, payload) => this.emitter.emit(event, payload),\n\t\t\t// Mock checkouts complete on their own; never open a tab to a mock URL.\n\t\t\topenUrl:\n\t\t\t\tdeps.openUrl ??\n\t\t\t\t(this.config.mock ? (url) => logger.info('mock checkout (no tab opened)', url) : undefined),\n\t\t\tnow: this.now,\n\t\t})\n\n\t\tthis.recovery = new RecoveryManager({\n\t\t\tapi: this.api,\n\t\t\tlocale: this.config.locale,\n\t\t\tpublishableKey: this.config.publishableKey,\n\t\t\tstorage: deps.recoveryStorage ?? createRecoveryStorage(),\n\t\t\topenUrl: deps.openUrl,\n\t\t\tnow: this.now,\n\t\t\tonComplete: async (ref, envelope) => {\n\t\t\t\tif (\n\t\t\t\t\t!PAY_END_USER_REF_RE.test(ref) ||\n\t\t\t\t\tenvelope?.payload?.endUserRef !== ref ||\n\t\t\t\t\tenvelope.payload.publishableKey !== this.config.publishableKey ||\n\t\t\t\t\t!Number.isFinite(Date.parse(envelope.payload.issuedAt)) ||\n\t\t\t\t\tDate.parse(envelope.payload.issuedAt) > this.now() + MAX_CLOCK_SKEW_MS ||\n\t\t\t\t\t(await verifyEntitlementSignature(envelope, await this.getPublicKey())) !== 'valid'\n\t\t\t\t)\n\t\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\t\tERROR_CODES.INVALID_RESPONSE,\n\t\t\t\t\t\t'Recovery requires a verified entitlement for this installation',\n\t\t\t\t\t)\n\t\t\t\tthis.entitlements.stopAutoRefresh()\n\t\t\t\ttry {\n\t\t\t\t\tawait this.entitlements.settleRefresh()\n\t\t\t\t\tif (this.destroyed) throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Recovery was stopped')\n\t\t\t\t\tawait this.storage.set(END_USER_REF_STORAGE_KEY, ref)\n\t\t\t\t\tthis.endUserRef = ref\n\t\t\t\t\tthis.endUserRefPromise = null\n\t\t\t\t\tawait this.entitlements.clear()\n\t\t\t\t\treturn await this.entitlements.accept(envelope)\n\t\t\t\t} finally {\n\t\t\t\t\tif (!this.destroyed) this.entitlements.startAutoRefresh()\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\n\t\tif (config.onError) this.emitter.on('error', config.onError)\n\t\tif (config.onReady) this.emitter.once('ready', config.onReady)\n\t}\n\n\tget version(): string {\n\t\treturn VERSION\n\t}\n\n\t/**\n\t * Mints/loads `endUserRef`, loads the cached entitlement, re-verifies it and\n\t * refreshes it when stale. Resolves once `isPaid()` can answer; network\n\t * failures fall back to the cache and are reported through `error`.\n\t */\n\tinitialize(): Promise<void> {\n\t\tif (!this.readyPromise) this.readyPromise = this.doInitialize()\n\t\treturn this.readyPromise\n\t}\n\n\tprivate async doInitialize(): Promise<void> {\n\t\tconst endUserRef = await this.getEndUserRef()\n\t\tawait this.entitlements.load()\n\t\ttry {\n\t\t\tawait this.entitlements.reverify()\n\t\t} catch (error) {\n\t\t\tthis.reportError(error)\n\t\t}\n\t\tif (!this.entitlements.isFresh()) await this.entitlements.get({ force: true })\n\t\tthis.emitter.emit('ready', { endUserRef })\n\t\tvoid this.afterReady()\n\t}\n\n\tprivate async afterReady(): Promise<void> {\n\t\tif (this.destroyed) return\n\t\ttry {\n\t\t\tawait this.checkout.resumePending()\n\t\t\tif (this.destroyed) return\n\t\t\tawait this.recovery.resumePending()\n\t\t} catch (error) {\n\t\t\tthis.reportError(error)\n\t\t}\n\t\tif (!this.destroyed) this.entitlements.startAutoRefresh()\n\t}\n\n\t/** The anonymous, random id this install is known by. */\n\tgetEndUserRef(): Promise<string> {\n\t\tif (this.endUserRef) return Promise.resolve(this.endUserRef)\n\t\tif (!this.endUserRefPromise) {\n\t\t\tthis.endUserRefPromise = getOrCreateEndUserRef(this.storage).then((ref) => {\n\t\t\t\tthis.endUserRef = ref\n\t\t\t\treturn ref\n\t\t\t})\n\t\t}\n\t\treturn this.endUserRefPromise\n\t}\n\n\tgetCachedEntitlement(): Entitlement | null {\n\t\treturn this.entitlements.getCached()\n\t}\n\n\tasync getEntitlement(options: GetEntitlementOptions = {}): Promise<Entitlement> {\n\t\tawait this.initialize()\n\t\treturn this.entitlements.get(options)\n\t}\n\n\t/** True when any active/grace entitlement exists, or the given `sku` is active/grace. */\n\tasync isPaid(sku?: string): Promise<boolean> {\n\t\treturn isEntitled(await this.getEntitlement(), sku)\n\t}\n\n\tasync hasFeature(feature: string): Promise<boolean> {\n\t\treturn hasFeature(await this.getEntitlement(), feature)\n\t}\n\n\tasync checkFeatures(features: string[]): Promise<Record<string, boolean>> {\n\t\treturn checkFeatures(await this.getEntitlement(), features)\n\t}\n\n\t/** Resolves true when the feature is (or becomes) unlocked. */\n\tasync requireFeature(feature: string, options: RequireFeatureOptions = {}): Promise<boolean> {\n\t\tif (await this.hasFeature(feature)) {\n\t\t\toptions.onUnlock?.()\n\t\t\treturn true\n\t\t}\n\t\tconst unlocked = await this.onFeatureLocked(feature, options)\n\t\tif (unlocked) options.onUnlock?.()\n\t\telse options.onCancel?.()\n\t\treturn unlocked\n\t}\n\n\t/** Lite has no UI: a locked feature stays locked. The full SDK shows the paywall here. */\n\tprotected async onFeatureLocked(_feature: string, _options: RequireFeatureOptions): Promise<boolean> {\n\t\treturn false\n\t}\n\n\t/**\n\t * The withdrawal waiver this offer asks for, with the exact text to show\n\t * next to an unticked checkbox (buyer's language, seller's name filled in),\n\t * or null when the seller attested the extension is not distributed in the\n\t * EEA/UK. For UIs that call `openCheckout()` themselves — Lite, or a custom\n\t * paywall; the full SDK's paywall does this for you.\n\t */\n\tasync getWithdrawalWaiver(): Promise<{ version: string; text: string } | null> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\tconst offer = await this.fetchOffer()\n\t\t\tif (!offer.withdrawalWaiver) return null\n\t\t\tconst seller = offer.seller?.displayName?.trim() || offer.projectName\n\t\t\treturn withdrawalWaiverText(offer.withdrawalWaiver.version, this.config.locale, seller)\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/**\n\t * Opens hosted checkout for `sku` in a new tab and resolves when the session settles.\n\t *\n\t * Called directly (not from the paywall), this does NOT collect the EU/UK\n\t * withdrawal waiver. If `getWithdrawalWaiver()` returns one, your UI must\n\t * collect the buyer's consent and pass it as `options.withdrawalWaiver`;\n\t * without it this rejects with `WITHDRAWAL_WAIVER_REQUIRED` (the server\n\t * refuses such a checkout too).\n\t */\n\tasync openCheckout(sku: string, options: CheckoutOptions = {}): Promise<CheckoutResult> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\tif (this.recovery.isActive())\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Recovery is in progress')\n\t\t\t// A cold cache is filled here; if the offer cannot be read, the server decides.\n\t\t\tconst offer = await this.fetchOffer().catch(() => null)\n\t\t\tif (offer?.withdrawalWaiver && options.withdrawalWaiver?.accepted !== true)\n\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\tERROR_CODES.WITHDRAWAL_WAIVER_REQUIRED,\n\t\t\t\t\t'This offer needs the buyer to accept the withdrawal waiver; pass options.withdrawalWaiver',\n\t\t\t\t)\n\t\t\treturn await this.checkout.open(sku, options)\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/** Opens email verification on the hosted page. No email is collected inside the extension. */\n\tasync restorePurchase(options: RestoreOptions = {}): Promise<RestoreResult> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\tif (this.checkout.isActive())\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Checkout is in progress')\n\t\t\treturn await this.recovery.open(options)\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/** Read-only license view. Entitlements retain cache/signature/offline semantics. */\n\tasync getLicenseSummary(options: GetEntitlementOptions = {}): Promise<LicenseSummary> {\n\t\tawait this.initialize()\n\t\tlet offer: PayOfferResponse | null = null\n\t\ttry {\n\t\t\toffer = await this.fetchOffer(options.force)\n\t\t} catch {\n\t\t\t/* Offline: do not invent seller details. */\n\t\t}\n\t\treturn {\n\t\t\tprojectName: offer?.projectName ?? null,\n\t\t\tseller: offer?.seller ?? null,\n\t\t\tentitlement: await this.getEntitlement(options),\n\t\t\trecoveryEnabled: offer?.recoveryEnabled === true,\n\t\t}\n\t}\n\n\t/** Opens the provider's self-service portal; resolves null when the provider has none. */\n\tasync openCustomerPortal(options: CustomerPortalOptions = {}): Promise<string | null> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\tconst endUserRef = await this.getEndUserRef()\n\t\t\tlet result = await this.api.getPortalUrl(endUserRef, undefined, this.config.locale)\n\t\t\tif (this.destroyed) return null\n\t\t\tif (result.accounts?.length) {\n\t\t\t\tif (!options.selectAccount)\n\t\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t\t'Choose a billing profile using selectAccount',\n\t\t\t\t\t)\n\t\t\t\tconst customerId = await options.selectAccount(result.accounts)\n\t\t\t\tif (customerId === null || this.destroyed) return null\n\t\t\t\tif (!result.accounts.some((a) => a.id === customerId))\n\t\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Invalid billing profile')\n\t\t\t\t// Recovery may replace this installation while the selector is open.\n\t\t\t\tif (endUserRef !== (await this.getEndUserRef()))\n\t\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t\t'Installation changed; open the portal again',\n\t\t\t\t\t)\n\t\t\t\tresult = await this.api.getPortalUrl(endUserRef, customerId, this.config.locale)\n\t\t\t}\n\t\t\tif (this.destroyed) return null\n\t\t\tconst { url } = result\n\t\t\tif (url) await (options.openUrl ?? (await import('../payment/checkout.js')).openInNewTab)(url)\n\t\t\treturn url\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\ton<K extends keyof ExtenshiPayEvents>(event: K, listener: Listener<ExtenshiPayEvents[K]>): () => void {\n\t\treturn this.emitter.on(event, listener)\n\t}\n\n\tonce<K extends keyof ExtenshiPayEvents>(event: K, listener: Listener<ExtenshiPayEvents[K]>): () => void {\n\t\treturn this.emitter.once(event, listener)\n\t}\n\n\toff<K extends keyof ExtenshiPayEvents>(event: K, listener: Listener<ExtenshiPayEvents[K]>): void {\n\t\tthis.emitter.off(event, listener)\n\t}\n\n\tonEntitlementChange(listener: Listener<Entitlement>): () => void {\n\t\treturn this.emitter.on('entitlement:changed', listener)\n\t}\n\n\tasync clearCache(): Promise<void> {\n\t\tthis.offer = null\n\t\tawait this.entitlements.clear()\n\t}\n\n\t/** Stops background refresh and drops listeners. */\n\tdestroy(): void {\n\t\tthis.destroyed = true\n\t\tthis.recovery.stop()\n\t\tthis.entitlements.stopAutoRefresh()\n\t\tthis.emitter.removeAll()\n\t}\n\n\t/** Offer + signing key. Public in the full SDK (`getOffer`), internal here. */\n\tprotected fetchOffer(force = false): Promise<PayOfferResponse> {\n\t\tif (!force && this.offer && this.now() - this.offer.fetchedAt < OFFER_TTL_MS) {\n\t\t\treturn Promise.resolve(this.offer.value)\n\t\t}\n\t\tif (!this.offerInflight) {\n\t\t\tthis.offerInflight = this.api\n\t\t\t\t.getOffer(this.config.locale)\n\t\t\t\t.then((value) => {\n\t\t\t\t\tthis.offer = { value, fetchedAt: this.now() }\n\t\t\t\t\treturn value\n\t\t\t\t})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tthis.offerInflight = null\n\t\t\t\t})\n\t\t}\n\t\treturn this.offerInflight\n\t}\n\n\tprivate async getPublicKey(): Promise<string | null> {\n\t\treturn this.config.entitlementPublicKey ?? (await this.fetchOffer()).entitlementPublicKey\n\t}\n\n\tprotected reportError(error: unknown): ExtenshiPayError {\n\t\tconst err = ExtenshiPayError.from(error)\n\t\tlogger.warn(`${err.code}: ${err.message}`)\n\t\tthis.emitter.emit('error', err)\n\t\treturn err\n\t}\n}\n","import type { PaySellerPublic } from '../types/contract.js'\nimport { fill, SDK_STRINGS_EN, type SdkStrings } from './i18n.js'\n\n/** Treat even server-provided links as untrusted; never render executable protocols. */\nexport function publicContactUrl(value: string): string | null {\n\ttry {\n\t\tconst url = new URL(value)\n\t\tif (url.protocol === 'https:' && !url.username && !url.password) return url.href\n\t} catch {\n\t\t/* A plain email address is allowed below. */\n\t}\n\tif (/^[^\\s@?&#:]+@[^\\s@?&#:]+\\.[^\\s@?&#:]+$/.test(value)) return `mailto:${encodeURIComponent(value)}`\n\treturn null\n}\n\nexport function sellerDetails(seller: PaySellerPublic | null, t: SdkStrings = SDK_STRINGS_EN): HTMLElement {\n\tconst section = document.createElement('section')\n\tsection.className = 'extenshi-seller-details'\n\tconst name = document.createElement('p')\n\tname.textContent = seller ? fill(t.sellerProvidedBy, { name: seller.displayName }) : t.sellerUnavailable\n\tsection.append(name)\n\tconst link = (label: string, value: string | null) => {\n\t\tconst href = value ? publicContactUrl(value) : null\n\t\tif (!href) return\n\t\tconst a = document.createElement('a')\n\t\ta.textContent = label\n\t\ta.href = href\n\t\ta.target = '_blank'\n\t\ta.rel = 'noopener noreferrer'\n\t\ta.style.marginRight = '12px'\n\t\tsection.append(a)\n\t}\n\tif (seller) {\n\t\tlink(t.sellerSupport, seller.supportUrl)\n\t\tlink(t.sellerTerms, seller.termsUrl)\n\t\tlink(t.sellerRefunds, seller.refundPolicyUrl ?? null)\n\t}\n\tconst role = document.createElement('p')\n\trole.textContent = t.sellerRole\n\tsection.append(role)\n\treturn section\n}\n","import type { LicenseSummary } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { fill, type SdkStrings, sdkDir, sdkLocale, sdkStrings } from './i18n.js'\nimport { sellerDetails } from './seller-details.js'\n\n/** A status label in the language, or the raw value for one we do not know. */\nfunction statusLabel(t: SdkStrings, status: string): string {\n\tconst map: Record<string, string> = {\n\t\tactive: t.statusActive,\n\t\tgrace: t.statusGrace,\n\t\texpired: t.statusExpired,\n\t\tnone: t.statusNone,\n\t}\n\treturn map[status] ?? status.replace(/_/g, ' ')\n}\n\n/** A provider subscription status (Stripe vocabulary) in the language. */\nexport function subscriptionStatusLabel(t: SdkStrings, status: string): string {\n\tconst map: Record<string, string> = {\n\t\tactive: t.subActive,\n\t\ttrialing: t.subTrialing,\n\t\tpast_due: t.subPastDue,\n\t\tcanceled: t.subCanceled,\n\t\tunpaid: t.subUnpaid,\n\t\tincomplete: t.subIncomplete,\n\t\tincomplete_expired: t.subIncompleteExpired,\n\t\tpaused: t.subPaused,\n\t}\n\treturn map[status] ?? status.replace(/_/g, ' ')\n}\n\nexport class LicensePanel {\n\tprivate dismiss: (() => void) | null = null\n\thide(): void {\n\t\tthis.dismiss?.()\n\t}\n\tshow(\n\t\tsummary: LicenseSummary,\n\t\tactions: {\n\t\t\trestore: () => Promise<LicenseSummary>\n\t\t\tmanage: () => Promise<string | null>\n\t\t},\n\t\tlocale: string | null = null,\n\t): Promise<void> {\n\t\tthis.hide()\n\t\tif (typeof document === 'undefined')\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'Use getLicenseSummary outside an extension page',\n\t\t\t)\n\t\tconst t = sdkStrings(locale)\n\t\tconst lang = sdkLocale(locale)\n\t\tconst host = document.createElement('div')\n\t\thost.className = 'extenshi-license-host'\n\t\thost.setAttribute('lang', lang)\n\t\thost.setAttribute('dir', sdkDir(lang))\n\t\tconst root = host.attachShadow({ mode: 'open' })\n\t\tconst style = document.createElement('style')\n\t\tstyle.textContent = `dialog{font:15px/1.5 system-ui,sans-serif;color:#172033;background:#fff;border:1px solid #dce1e8;border-radius:16px;padding:24px;width:min(460px,calc(100vw - 64px));max-height:80vh}dialog::backdrop{background:#10182880}h2{margin:0}h3{font-size:16px;margin:0}article{border-block-end:1px solid #ddd;padding:16px 0}p{margin:8px 0}button{font:inherit;padding:10px 14px;margin:12px 8px 0 0;border:1px solid #cbd5e1;border-radius:8px;cursor:pointer;background:#fff;color:inherit}button:disabled{opacity:.5;cursor:wait}button:focus-visible,a:focus-visible{outline:3px solid #0ea5e9}a{color:#0369a1}.extenshi-seller-details{font-size:13px;margin-top:20px}`\n\t\tconst dialog = document.createElement('dialog')\n\t\tdialog.setAttribute('aria-label', t.licenseTitle)\n\t\tconst title = document.createElement('h2')\n\t\ttitle.textContent = t.licenseTitle\n\t\tconst content = document.createElement('div')\n\t\tconst feedback = document.createElement('p')\n\t\tfeedback.setAttribute('role', 'status')\n\t\tconst render = (state: LicenseSummary) => {\n\t\t\tcontent.replaceChildren()\n\t\t\tconst note = document.createElement('p')\n\t\t\tnote.textContent = state.projectName ?? t.licenseFallbackName\n\t\t\tcontent.append(note)\n\t\t\tif (!state.entitlement.items.length) {\n\t\t\t\tconst empty = document.createElement('p')\n\t\t\t\tempty.textContent = t.licenseNone\n\t\t\t\tcontent.append(empty)\n\t\t\t}\n\t\t\tfor (const item of state.entitlement.items) {\n\t\t\t\tconst article = document.createElement('article')\n\t\t\t\tconst heading = document.createElement('h3')\n\t\t\t\theading.textContent = item.title ?? item.sku\n\t\t\t\tconst status = document.createElement('p')\n\t\t\t\tconst kind =\n\t\t\t\t\titem.kind === 'one_time'\n\t\t\t\t\t\t? item.expiresAt\n\t\t\t\t\t\t\t? t.kindOneTime\n\t\t\t\t\t\t\t: t.kindLifetime\n\t\t\t\t\t\t: item.kind === 'subscription'\n\t\t\t\t\t\t\t? t.kindSubscription\n\t\t\t\t\t\t\t: t.kindLicense\n\t\t\t\tstatus.textContent = `${kind} · ${fill(t.statusLine, { status: statusLabel(t, item.status) })}`\n\t\t\t\tarticle.append(heading, status)\n\t\t\t\tif (item.expiresAt) {\n\t\t\t\t\tconst date = new Date(item.expiresAt)\n\t\t\t\t\tif (!Number.isNaN(date.getTime())) {\n\t\t\t\t\t\tconst expiry = document.createElement('p')\n\t\t\t\t\t\tconst when = date.toLocaleString(lang)\n\t\t\t\t\t\texpiry.textContent = fill(\n\t\t\t\t\t\t\titem.status === 'expired'\n\t\t\t\t\t\t\t\t? t.accessEnded\n\t\t\t\t\t\t\t\t: item.status === 'active' || item.status === 'grace'\n\t\t\t\t\t\t\t\t\t? t.accessUntil\n\t\t\t\t\t\t\t\t\t: t.accessRecordedEnd,\n\t\t\t\t\t\t\t{ date: when },\n\t\t\t\t\t\t)\n\t\t\t\t\t\tarticle.append(expiry)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (const sub of item.subscriptions ?? []) {\n\t\t\t\t\tconst row = document.createElement('p')\n\t\t\t\t\trow.textContent = `${fill(t.subscriptionLine, { status: subscriptionStatusLabel(t, sub.status) })}${sub.cancelAtPeriodEnd ? ` · ${t.renewalCanceled}` : ''}`\n\t\t\t\t\tarticle.append(row)\n\t\t\t\t}\n\t\t\t\tcontent.append(article)\n\t\t\t}\n\t\t\tconst freshness = document.createElement('p')\n\t\t\tfreshness.textContent = state.entitlement.requiresOnlineCheck\n\t\t\t\t? t.licenseOffline\n\t\t\t\t: state.entitlement.source === 'mock'\n\t\t\t\t\t? t.mockNotice\n\t\t\t\t\t: state.entitlement.source === 'cache'\n\t\t\t\t\t\t? t.licenseCached\n\t\t\t\t\t\t: t.licenseFresh\n\t\t\tcontent.append(freshness, sellerDetails(state.seller, t))\n\t\t}\n\t\trender(summary)\n\t\tdialog.append(title, content, feedback)\n\t\troot.append(style, dialog)\n\t\tdocument.body.append(host)\n\t\tif (typeof dialog.showModal !== 'function') {\n\t\t\thost.remove()\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'This browser needs a custom license screen using getLicenseSummary',\n\t\t\t)\n\t\t}\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tlet closed = false\n\t\t\tconst close = () => {\n\t\t\t\tclosed = true\n\t\t\t\tthis.dismiss = null\n\t\t\t\tdialog.close()\n\t\t\t\thost.remove()\n\t\t\t\tresolve()\n\t\t\t}\n\t\t\tthis.dismiss = close\n\t\t\tdialog.addEventListener('cancel', (event) => {\n\t\t\t\tevent.preventDefault()\n\t\t\t\tclose()\n\t\t\t})\n\t\t\tconst buttons: HTMLButtonElement[] = []\n\t\t\tconst action = (label: string, run: () => Promise<void>) => {\n\t\t\t\tconst button = document.createElement('button')\n\t\t\t\tbutton.type = 'button'\n\t\t\t\tbutton.textContent = label\n\t\t\t\tbutton.addEventListener('click', async () => {\n\t\t\t\t\tbuttons.forEach((b) => {\n\t\t\t\t\t\tb.disabled = true\n\t\t\t\t\t})\n\t\t\t\t\tfeedback.textContent = ''\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait run()\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tif (!closed) feedback.textContent = t.actionFailed\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (!closed)\n\t\t\t\t\t\t\tbuttons.forEach((b) => {\n\t\t\t\t\t\t\t\tb.disabled = false\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tbuttons.push(button)\n\t\t\t\tdialog.append(button)\n\t\t\t}\n\t\t\tif (summary.recoveryEnabled)\n\t\t\t\taction(t.restorePurchase, async () => {\n\t\t\t\t\tconst updated = await actions.restore()\n\t\t\t\t\tif (!closed) render(updated)\n\t\t\t\t})\n\t\t\tif (summary.entitlement.source !== 'mock')\n\t\t\t\taction(t.manageBilling, async () => {\n\t\t\t\t\tconst url = await actions.manage()\n\t\t\t\t\tif (!url && !closed) feedback.textContent = t.noPortal\n\t\t\t\t})\n\t\t\tconst done = document.createElement('button')\n\t\t\tdone.type = 'button'\n\t\t\tdone.textContent = t.close\n\t\t\tdone.addEventListener('click', close)\n\t\t\tdialog.append(done)\n\t\t\ttry {\n\t\t\t\tdialog.showModal()\n\t\t\t} catch (error) {\n\t\t\t\tthis.dismiss = null\n\t\t\t\thost.remove()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t}\n}\n","import type { PayPortalAccount } from '../types/contract.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { fill, sdkDir, sdkLocale, sdkStrings } from './i18n.js'\nimport { subscriptionStatusLabel } from './license-panel.js'\n\n/** Bundled UI only. Native dialog provides modal focus containment and Escape. */\nexport class BillingProfilePicker {\n\tprivate dismiss: (() => void) | null = null\n\n\thide(): void {\n\t\tthis.dismiss?.()\n\t}\n\n\tshow(accounts: PayPortalAccount[], locale: string | null = null): Promise<string | null> {\n\t\tthis.hide()\n\t\tif (typeof document === 'undefined')\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'Provide selectAccount outside an extension page',\n\t\t\t)\n\t\tconst t = sdkStrings(locale)\n\t\tconst lang = sdkLocale(locale)\n\t\tconst host = document.createElement('div')\n\t\thost.className = 'extenshi-billing-profile-host'\n\t\thost.setAttribute('lang', lang)\n\t\thost.setAttribute('dir', sdkDir(lang))\n\t\tconst root = host.attachShadow({ mode: 'open' })\n\t\tconst style = document.createElement('style')\n\t\tstyle.textContent = `\n\t\t\tdialog{font:15px/1.5 system-ui,sans-serif;color:#172033;background:#fff;border:1px solid #dce1e8;border-radius:16px;padding:24px;width:min(440px,calc(100vw - 64px));max-height:80vh;box-shadow:0 20px 60px #0003}\n\t\t\tdialog::backdrop{background:#10182880}h2{margin:0 0 8px;font-size:22px}p{margin:0 0 16px;color:#526078}\n\t\t\tbutton{font:inherit;cursor:pointer;border:1px solid #dce1e8;border-radius:8px;background:#fff;color:inherit;padding:12px;text-align:left;width:100%;margin-top:10px}\n\t\t\tbutton:hover{background:#f3f6fa}button:focus-visible{outline:3px solid #0ea5e9;outline-offset:2px}strong,small{display:block}small{color:#526078;margin-top:4px}\n\t\t`\n\t\tconst dialog = document.createElement('dialog')\n\t\tdialog.setAttribute('aria-labelledby', 'billing-title')\n\t\tdialog.setAttribute('aria-describedby', 'billing-description')\n\t\tconst title = document.createElement('h2')\n\t\ttitle.id = 'billing-title'\n\t\ttitle.textContent = t.pickerTitle\n\t\tconst description = document.createElement('p')\n\t\tdescription.id = 'billing-description'\n\t\tdescription.textContent = t.pickerDescription\n\t\tdialog.append(title, description)\n\t\troot.append(style, dialog)\n\t\tdocument.body.append(host)\n\t\tif (typeof dialog.showModal !== 'function') {\n\t\t\thost.remove()\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'This browser needs a custom selectAccount callback',\n\t\t\t)\n\t\t}\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst finish = (id: string | null) => {\n\t\t\t\tthis.dismiss = null\n\t\t\t\tdialog.close()\n\t\t\t\thost.remove()\n\t\t\t\tresolve(id)\n\t\t\t}\n\t\t\tthis.dismiss = () => finish(null)\n\t\t\tdialog.addEventListener('cancel', (event) => {\n\t\t\t\tevent.preventDefault()\n\t\t\t\tfinish(null)\n\t\t\t})\n\t\t\tfor (const account of accounts) {\n\t\t\t\tconst button = document.createElement('button')\n\t\t\t\tbutton.type = 'button'\n\t\t\t\tconst label = document.createElement('strong')\n\t\t\t\tlabel.textContent = account.label\n\t\t\t\tconst detail = document.createElement('small')\n\t\t\t\tconst recorded = new Date(account.createdAt)\n\t\t\t\tdetail.textContent = Number.isNaN(recorded.getTime())\n\t\t\t\t\t? ''\n\t\t\t\t\t: fill(t.pickerFirstRecorded, { date: recorded.toLocaleDateString(lang) })\n\t\t\t\tbutton.append(label, detail)\n\t\t\t\tfor (const subscription of account.subscriptions) {\n\t\t\t\t\tconst line = document.createElement('small')\n\t\t\t\t\tconst end = subscription.currentPeriodEnd ? new Date(subscription.currentPeriodEnd) : null\n\t\t\t\t\tconst cancellation = subscription.cancelAtPeriodEnd\n\t\t\t\t\t\t? ` · ${t.renewalCanceled}${end && !Number.isNaN(end.getTime()) ? ` · ${fill(t.periodEnds, { date: end.toLocaleDateString(lang) })}` : ''}`\n\t\t\t\t\t\t: ''\n\t\t\t\t\tline.textContent = `${subscription.title} · ${subscriptionStatusLabel(t, subscription.status)}${cancellation}`\n\t\t\t\t\tbutton.append(line)\n\t\t\t\t}\n\t\t\t\tbutton.addEventListener('click', () => finish(account.id))\n\t\t\t\tdialog.append(button)\n\t\t\t}\n\t\t\tconst cancel = document.createElement('button')\n\t\t\tcancel.type = 'button'\n\t\t\tcancel.textContent = t.pickerCancel\n\t\t\tcancel.addEventListener('click', () => finish(null))\n\t\t\tdialog.append(cancel)\n\t\t\ttry {\n\t\t\t\tdialog.showModal()\n\t\t\t} catch (error) {\n\t\t\t\tthis.dismiss = null\n\t\t\t\thost.remove()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t}\n}\n","import type { PayOfferDto } from '../types/contract.js'\nimport type { PaywallStrings } from '../types/paywall.js'\n\nexport interface FormattedPrice {\n\t/** Currency symbol/code as the locale renders it (`$`, `€`, `US$`). */\n\tcurrency: string\n\t/** Numeric part (`9.99`, `9,99`). */\n\tamount: string\n\t/** The whole formatted price (`$9.99`). */\n\tfull: string\n}\n\nexport function formatPrice(amountMinor: number, currency: string, locale?: string | null): FormattedPrice {\n\tconst value = amountMinor / 100\n\tconst code = currency.toUpperCase()\n\ttry {\n\t\tconst formatter = new Intl.NumberFormat(locale ?? undefined, { style: 'currency', currency: code })\n\t\tconst parts = formatter.formatToParts(value)\n\t\treturn {\n\t\t\tcurrency: parts\n\t\t\t\t.filter((part) => part.type === 'currency')\n\t\t\t\t.map((part) => part.value)\n\t\t\t\t.join(''),\n\t\t\tamount: parts\n\t\t\t\t.filter((part) => part.type !== 'currency' && part.type !== 'literal')\n\t\t\t\t.map((part) => part.value)\n\t\t\t\t.join(''),\n\t\t\tfull: formatter.format(value),\n\t\t}\n\t} catch {\n\t\tconst amount = value.toFixed(2)\n\t\treturn { currency: code, amount, full: `${amount} ${code}` }\n\t}\n}\n\nexport function periodLabel(offer: PayOfferDto, strings: PaywallStrings): string {\n\tif (offer.kind !== 'subscription') return strings.periodOnce\n\treturn offer.interval === 'year' ? strings.periodYear : strings.periodMonth\n}\n","/**\n * The paywall's strings in a locale, from the SDK dictionary (./i18n.ts).\n * Do not add promotional claims without marketing/legal review (see\n * .claude/modules/paywall-templates.md).\n */\n\nimport type { PaywallStrings } from '../types/paywall.js'\nimport { SDK_STRINGS_EN, type SdkStrings, sdkStrings } from './i18n.js'\n\nfunction paywallStrings(t: SdkStrings): PaywallStrings {\n\treturn {\n\t\ttitle: t.title,\n\t\tdescription: t.description,\n\t\tupgrade: t.upgrade,\n\t\tcancel: t.cancel,\n\t\tdismiss: t.dismiss,\n\t\tremindLater: t.remindLater,\n\t\tcontinueFree: t.continueFree,\n\t\tcheckoutUnavailable: t.checkoutUnavailable,\n\t\tperiodMonth: t.periodMonth,\n\t\tperiodYear: t.periodYear,\n\t\tperiodOnce: t.periodOnce,\n\t\tfooter: t.footer,\n\t\trestorePurchase: t.restorePurchase,\n\t\tfeaturesHeading: t.featuresHeading,\n\t\tplansHeading: t.plansHeading,\n\t\tfreePlanName: t.freePlanName,\n\t\tpremiumPlanName: t.premiumPlanName,\n\t\tpopularBadge: t.popularBadge,\n\t\tunlockHeading: t.unlockHeading,\n\t}\n}\n\n/** English (the default and the fallback). */\nexport const DEFAULT_STRINGS: PaywallStrings = paywallStrings(SDK_STRINGS_EN)\n\nexport const MOCK_PAYMENT_NOTICE = SDK_STRINGS_EN.mockNotice\n\n/** The paywall strings for `locale` (English when we have no translation). */\nexport function stringsFor(locale: string | null | undefined): PaywallStrings {\n\treturn paywallStrings(sdkStrings(locale))\n}\n","export const html = \"<div class=\\\"ep-fullscreen-paywall\\\" id=\\\"fullscreenPaywall\\\" role=\\\"dialog\\\" aria-labelledby=\\\"fullscreen-title\\\"><div class=\\\"ep-fullscreen-background\\\"><div class=\\\"ep-background-pattern\\\"></div></div><div class=\\\"ep-fullscreen-header\\\"><div class=\\\"ep-fullscreen-logo\\\"><svg width=\\\"40\\\" height=\\\"40\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 2L2 7l10 5 10-5-10-5z\\\"></path><path d=\\\"M2 17l10 5 10-5\\\"></path><path d=\\\"M2 12l10 5 10-5\\\"></path></svg><span class=\\\"ep-fullscreen-logo-text\\\">{{brandName}}</span></div><button class=\\\"ep-fullscreen-close\\\" aria-label=\\\"Close paywall\\\" data-ep-action=\\\"closeFullscreen\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg></button></div><div class=\\\"ep-fullscreen-content\\\"><div class=\\\"ep-fullscreen-container\\\"><div class=\\\"ep-fullscreen-hero\\\"><div class=\\\"ep-hero-icon\\\"><svg width=\\\"80\\\" height=\\\"80\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 2L2 7l10 5 10-5-10-5z\\\"></path><path d=\\\"M2 17l10 5 10-5\\\"></path><path d=\\\"M2 12l10 5 10-5\\\"></path></svg></div><h1 class=\\\"ep-heading-1\\\" id=\\\"fullscreen-title\\\">{{title}}</h1><p class=\\\"ep-hero-description\\\">{{description}}</p></div><div class=\\\"ep-fullscreen-features\\\"><div class=\\\"ep-features-grid\\\"><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 12h-4l-3 9L9 3l-3 9H2\\\"></path></svg></div><h3 class=\\\"ep-feature-card-title\\\">{{feature1Title}}</h3><p class=\\\"ep-feature-card-description\\\">{{feature1Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z\\\"></path></svg></div><h3 class=\\\"ep-feature-card-title\\\">{{feature2Title}}</h3><p class=\\\"ep-feature-card-description\\\">{{feature2Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M13 2L3 14h9l-1 8 10-12h-9l1-8z\\\"></path></svg></div><h3 class=\\\"ep-feature-card-title\\\">{{feature3Title}}</h3><p class=\\\"ep-feature-card-description\\\">{{feature3Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z\\\"></path><polyline points=\\\"7.5,4.21 12,6.81 16.5,4.21\\\"></polyline><polyline points=\\\"7.5,19.79 7.5,14.6 3,12\\\"></polyline><polyline points=\\\"21,12 16.5,14.6 16.5,19.79\\\"></polyline></svg></div><h3 class=\\\"ep-feature-card-title\\\">{{feature4Title}}</h3><p class=\\\"ep-feature-card-description\\\">{{feature4Description}}</p></div></div></div><div class=\\\"ep-fullscreen-pricing\\\"><div class=\\\"ep-pricing-header\\\"><h2 class=\\\"ep-heading-2\\\">{{plansHeading}}</h2><p class=\\\"ep-pricing-subtitle\\\">{{pricingSubtitle}}</p></div><div class=\\\"ep-pricing-plans\\\"><div class=\\\"ep-pricing-plan\\\"><div class=\\\"ep-pricing-plan-header\\\"><h3 class=\\\"ep-pricing-plan-title\\\">{{freePlanName}}</h3><div class=\\\"ep-pricing-plan-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">0</span></div><p class=\\\"ep-pricing-plan-description\\\">{{freeDescription}}</p></div><ul class=\\\"ep-pricing-plan-features\\\"><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{freeFeature1}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{freeFeature2}} </li><li class=\\\"ep-pricing-feature ep-pricing-feature-disabled\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg> {{freeFeature3}} </li></ul><button class=\\\"ep-btn ep-btn-secondary ep-btn-full\\\" data-ep-action=\\\"continueFree\\\"> {{continueButtonText}} </button></div><div class=\\\"ep-pricing-plan ep-pricing-plan-premium\\\"><div class=\\\"ep-pricing-plan-badge\\\">{{premiumBadge}}</div><div class=\\\"ep-pricing-plan-header\\\"><h3 class=\\\"ep-pricing-plan-title\\\">{{premiumPlanName}}</h3><div class=\\\"ep-pricing-plan-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">{{price}}</span><span class=\\\"ep-pricing-period\\\">{{period}}</span></div><p class=\\\"ep-pricing-plan-description\\\">{{premiumDescription}}</p></div><ul class=\\\"ep-pricing-plan-features\\\"><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature1}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature2}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature3}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature4}} </li></ul><button class=\\\"ep-btn ep-btn-primary ep-btn-lg ep-btn-full\\\" data-ep-action=\\\"upgradeNow\\\"> {{upgradeButtonText}} </button></div></div></div><div class=\\\"ep-fullscreen-trial\\\"><div class=\\\"ep-trial-card\\\"><div class=\\\"ep-trial-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 11.08V12a10 10 0 1 1-5.93-9.14\\\"></path><polyline points=\\\"22,4 12,14.01 9,11.01\\\"></polyline></svg></div><h3 class=\\\"ep-trial-title\\\">{{trialTitle}}</h3><p class=\\\"ep-trial-description\\\">{{trialDescription}}</p><button class=\\\"ep-btn ep-btn-secondary ep-btn-lg\\\" data-ep-action=\\\"startTrial\\\"> {{trialButtonText}} </button></div></div></div></div></div>\";\nexport const css = \".ep-fullscreen-paywall{position:fixed;top:0;left:0;right:0;bottom:0;background-color:var(--ep-bg-primary);z-index:var(--ep-z-modal);display:flex;flex-direction:column;animation:ep-fullscreen-in var(--ep-transition-slow);overflow-y:auto}.ep-fullscreen-paywall.ep-fullscreen-closing{animation:ep-fullscreen-out var(--ep-transition-slow)}.ep-fullscreen-background{position:absolute;top:0;left:0;right:0;bottom:0;overflow:hidden;z-index:-1}.ep-background-pattern{position:absolute;top:-50%;left:-50%;width:200%;height:200%;background:linear-gradient(45deg,transparent 30%,rgba(14,165,233,0.03) 50%,transparent 70%);background-size:60px 60px;animation:ep-background-pattern var(--ep-transition-slow) infinite linear}:host([data-theme=\\\"dark\\\"]) .ep-background-pattern{background:linear-gradient(45deg,transparent 30%,rgba(14,165,233,0.05) 50%,transparent 70%)}.ep-fullscreen-header{display:flex;justify-content:space-between;align-items:center;padding:var(--ep-space-6) var(--ep-space-8);border-bottom:1px solid var(--ep-border-primary);background-color:var(--ep-bg-secondary);backdrop-filter:blur(10px);z-index:1}.ep-fullscreen-logo{display:flex;align-items:center;gap:var(--ep-space-3);color:var(--ep-primary-600)}.ep-fullscreen-logo-text{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-fullscreen-close{background:none;border:none;color:var(--ep-text-tertiary);cursor:pointer;padding:var(--ep-space-2);border-radius:var(--ep-radius-md);transition:all var(--ep-transition-fast)}.ep-fullscreen-close:hover{color:var(--ep-text-primary);background-color:var(--ep-bg-tertiary)}.ep-fullscreen-content{flex:1;padding:var(--ep-space-8);display:flex;align-items:center;justify-content:center}.ep-fullscreen-container{max-width:1200px;width:100%;margin:0 auto}.ep-fullscreen-hero{text-align:center;margin-bottom:var(--ep-space-16)}.ep-hero-icon{width:120px;height:120px;margin:0 auto var(--ep-space-6);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-2xl);display:flex;align-items:center;justify-content:center;color:white;box-shadow:var(--ep-shadow-lg);animation:ep-hero-icon-in var(--ep-transition-slow) 0.2s both}.ep-fullscreen-hero .ep-heading-1{font-size:var(--ep-font-size-5xl);margin-bottom:var(--ep-space-6);background:linear-gradient(135deg,var(--ep-primary-600),var(--ep-primary-700));-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;animation:ep-hero-title-in var(--ep-transition-slow) 0.3s both}.ep-hero-description{font-size:var(--ep-font-size-xl);color:var(--ep-text-secondary);max-width:600px;margin:0 auto;line-height:var(--ep-line-height-relaxed);animation:ep-hero-description-in var(--ep-transition-slow) 0.4s both}.ep-fullscreen-features{margin-bottom:var(--ep-space-16)}.ep-features-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:var(--ep-space-6)}.ep-feature-card{background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-xl);padding:var(--ep-space-8);text-align:center;box-shadow:var(--ep-shadow-sm);transition:all var(--ep-transition-normal);opacity:0;transform:translateY(20px);animation:ep-feature-card-in var(--ep-transition-slow) both}.ep-feature-card:hover{transform:translateY(-4px);box-shadow:var(--ep-shadow-lg)}.ep-feature-card-icon{width:80px;height:80px;margin:0 auto var(--ep-space-4);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-xl);display:flex;align-items:center;justify-content:center;color:white}.ep-feature-card-title{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-3)}.ep-feature-card-description{color:var(--ep-text-secondary);line-height:var(--ep-line-height-relaxed);margin:0}.ep-fullscreen-pricing{margin-bottom:var(--ep-space-16)}.ep-pricing-header{text-align:center;margin-bottom:var(--ep-space-10)}.ep-pricing-header .ep-heading-2{font-size:var(--ep-font-size-4xl);margin-bottom:var(--ep-space-4)}.ep-pricing-subtitle{font-size:var(--ep-font-size-lg);color:var(--ep-text-secondary);margin:0}.ep-pricing-plans{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:var(--ep-space-8);max-width:800px;margin:0 auto}.ep-pricing-plan{position:relative;background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-xl);padding:var(--ep-space-8);box-shadow:var(--ep-shadow-md);transition:all var(--ep-transition-normal);opacity:0;transform:translateY(20px);animation:ep-pricing-plan-in var(--ep-transition-slow) both}.ep-pricing-plan:hover{transform:translateY(-4px);box-shadow:var(--ep-shadow-lg)}.ep-pricing-plan-premium{border-color:var(--ep-primary-300);box-shadow:var(--ep-shadow-xl);transform:scale(1.05)}.ep-pricing-plan-premium:hover{transform:scale(1.05) translateY(-4px)}.ep-pricing-plan-badge{position:absolute;top:-16px;left:50%;transform:translateX(-50%);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));color:white;padding:var(--ep-space-2) var(--ep-space-6);border-radius:var(--ep-radius-full);font-size:var(--ep-font-size-sm);font-weight:var(--ep-font-weight-semibold);white-space:nowrap}.ep-pricing-plan-header{text-align:center;margin-bottom:var(--ep-space-8)}.ep-pricing-plan-title{font-size:var(--ep-font-size-2xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-4)}.ep-pricing-plan-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-2);margin-bottom:var(--ep-space-3)}.ep-pricing-currency{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-pricing-amount{font-size:var(--ep-font-size-5xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-pricing-period{font-size:var(--ep-font-size-xl);color:var(--ep-text-secondary)}.ep-pricing-plan-description{color:var(--ep-text-secondary);margin:0}.ep-pricing-plan-features{list-style:none;padding:0;margin:0 0 var(--ep-space-8) 0}.ep-pricing-feature{display:flex;align-items:center;gap:var(--ep-space-3);padding:var(--ep-space-3) 0;color:var(--ep-text-primary);font-size:var(--ep-font-size-base)}.ep-pricing-feature-disabled{color:var(--ep-text-tertiary)}.ep-pricing-feature-icon{color:var(--ep-success-500);flex-shrink:0}.ep-pricing-feature-disabled .ep-pricing-feature-icon{color:var(--ep-text-tertiary)}.ep-fullscreen-trial{text-align:center}.ep-trial-card{background:linear-gradient(135deg,var(--ep-success-50),var(--ep-success-100));border:1px solid var(--ep-success-200);border-radius:var(--ep-radius-xl);padding:var(--ep-space-8);max-width:600px;margin:0 auto;box-shadow:var(--ep-shadow-md)}:host([data-theme=\\\"dark\\\"]) .ep-trial-card{background:linear-gradient(135deg,rgba(16,185,129,0.1),rgba(16,185,129,0.15));border-color:rgba(16,185,129,0.3)}.ep-trial-icon{width:80px;height:80px;margin:0 auto var(--ep-space-4);background:linear-gradient(135deg,var(--ep-success-500),var(--ep-success-600));border-radius:var(--ep-radius-xl);display:flex;align-items:center;justify-content:center;color:white}.ep-trial-title{font-size:var(--ep-font-size-2xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-success-700);margin-bottom:var(--ep-space-3)}:host([data-theme=\\\"dark\\\"]) .ep-trial-title{color:var(--ep-success-400)}.ep-trial-description{color:var(--ep-success-600);font-size:var(--ep-font-size-lg);line-height:var(--ep-line-height-relaxed);margin-bottom:var(--ep-space-6)}:host([data-theme=\\\"dark\\\"]) .ep-trial-description{color:var(--ep-success-300)}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);right:var(--ep-space-4);z-index:var(--ep-z-tooltip)}@keyframes ep-fullscreen-in{from{opacity:0;transform:scale(0.98)}to{opacity:1;transform:scale(1)}}@keyframes ep-fullscreen-out{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(0.98)}}@keyframes ep-background-pattern{from{transform:translateX(0) translateY(0)}to{transform:translateX(-60px) translateY(-60px)}}@keyframes ep-hero-icon-in{from{opacity:0;transform:scale(0.8)}to{opacity:1;transform:scale(1)}}@keyframes ep-hero-title-in{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes ep-hero-description-in{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes ep-feature-card-in{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes ep-pricing-plan-in{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@media (max-width:1024px){.ep-fullscreen-content{padding:var(--ep-space-6)}.ep-fullscreen-hero{margin-bottom:var(--ep-space-12)}.ep-fullscreen-features{margin-bottom:var(--ep-space-12)}.ep-fullscreen-pricing{margin-bottom:var(--ep-space-12)}.ep-features-grid{grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:var(--ep-space-4)}.ep-pricing-plans{gap:var(--ep-space-6)}}@media (max-width:768px){.ep-fullscreen-header{padding:var(--ep-space-4) var(--ep-space-6)}.ep-fullscreen-content{padding:var(--ep-space-4)}.ep-fullscreen-hero .ep-heading-1{font-size:var(--ep-font-size-3xl)}.ep-hero-description{font-size:var(--ep-font-size-lg)}.ep-hero-icon{width:80px;height:80px}.ep-features-grid{grid-template-columns:1fr}.ep-pricing-plans{grid-template-columns:1fr}.ep-pricing-plan-premium{transform:none}.ep-pricing-plan-premium:hover{transform:translateY(-4px)}.ep-feature-card{padding:var(--ep-space-6)}.ep-feature-card-icon{width:60px;height:60px}.ep-pricing-plan{padding:var(--ep-space-6)}.ep-pricing-amount{font-size:var(--ep-font-size-4xl)}}@media (max-width:480px){.ep-fullscreen-header{padding:var(--ep-space-3) var(--ep-space-4)}.ep-fullscreen-logo-text{font-size:var(--ep-font-size-lg)}.ep-fullscreen-content{padding:var(--ep-space-3)}.ep-fullscreen-hero .ep-heading-1{font-size:var(--ep-font-size-2xl)}.ep-hero-description{font-size:var(--ep-font-size-base)}.ep-hero-icon{width:60px;height:60px}.ep-pricing-header .ep-heading-2{font-size:var(--ep-font-size-2xl)}.ep-pricing-amount{font-size:var(--ep-font-size-3xl)}.ep-feature-card-icon{width:48px;height:48px}.ep-trial-icon{width:60px;height:60px}}@media (prefers-contrast:high){.ep-fullscreen-paywall{background-color:var(--ep-bg-primary)}.ep-feature-card{border:2px solid var(--ep-border-secondary)}.ep-pricing-plan{border:2px solid var(--ep-border-secondary)}.ep-pricing-plan-premium{border:2px solid var(--ep-primary-500)}.ep-trial-card{border:2px solid var(--ep-success-500)}}@media (prefers-reduced-motion:reduce){.ep-fullscreen-paywall{animation:none}.ep-background-pattern{animation:none}.ep-hero-icon{animation:none}.ep-fullscreen-hero .ep-heading-1{animation:none}.ep-hero-description{animation:none}.ep-feature-card{animation:none;opacity:1;transform:none}.ep-pricing-plan{animation:none;opacity:1;transform:none}.ep-pricing-plan-premium{transform:none}.ep-feature-card:hover{transform:none}.ep-pricing-plan:hover{transform:none}}\";\nexport default { html, css };","/**\n * The five templates from `@extenshi/paywall-templates`, inlined at build\n * time by build/paywall-templates-plugin.mjs. No runtime fetch, no\n * `web_accessible_resources`, no remote code.\n */\n\nimport sharedCss from 'virtual:extenshi-paywall-shared-css'\nimport * as fullscreen from '@extenshi/paywall-templates/fullscreen'\nimport * as inline from '@extenshi/paywall-templates/inline'\nimport * as minimal from '@extenshi/paywall-templates/minimal'\nimport * as modal from '@extenshi/paywall-templates/modal'\nimport * as sidebar from '@extenshi/paywall-templates/sidebar'\nimport type { PaywallMode } from '../types/paywall.js'\n\nexport interface PaywallTemplate {\n\thtml: string\n\tcss: string\n}\n\nexport const PAYWALL_SHARED_CSS: string = sharedCss\n\nexport const PAYWALL_TEMPLATES: Record<PaywallMode, PaywallTemplate> = {\n\tmodal: { html: modal.html, css: modal.css },\n\tinline: { html: inline.html, css: inline.css },\n\tsidebar: { html: sidebar.html, css: sidebar.css },\n\tfullscreen: { html: fullscreen.html, css: fullscreen.css },\n\tminimal: { html: minimal.html, css: minimal.css },\n}\n\nexport const PAYWALL_MODES = Object.keys(PAYWALL_TEMPLATES) as PaywallMode[]\n","export const html = \"<div class=\\\"ep-modal-backdrop\\\" id=\\\"paywallModal\\\" role=\\\"dialog\\\" aria-labelledby=\\\"paywall-title\\\" aria-describedby=\\\"paywall-description\\\"><div class=\\\"ep-modal-container\\\"><button class=\\\"ep-modal-close\\\" aria-label=\\\"Close paywall\\\" data-ep-action=\\\"closePaywall\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg></button><div class=\\\"ep-modal-content\\\"><div class=\\\"ep-modal-header\\\"><div class=\\\"ep-modal-icon\\\"><svg width=\\\"48\\\" height=\\\"48\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><rect x=\\\"3\\\" y=\\\"11\\\" width=\\\"18\\\" height=\\\"11\\\" rx=\\\"2\\\" ry=\\\"2\\\"></rect><path d=\\\"m7 11V7a5 5 0 0 1 10 0v4\\\"></path></svg></div><h2 class=\\\"ep-heading-2\\\" id=\\\"paywall-title\\\">{{title}}</h2><p class=\\\"ep-text-body\\\" id=\\\"paywall-description\\\">{{description}}</p></div><div class=\\\"ep-modal-features\\\"><h3 class=\\\"ep-heading-3\\\">{{featuresHeading}}</h3><ul class=\\\"ep-feature-list\\\"><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature1}}</span></li><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature2}}</span></li><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature3}}</span></li></ul></div><div class=\\\"ep-modal-pricing\\\"><div class=\\\"ep-pricing-card\\\"><div class=\\\"ep-pricing-header\\\"><div class=\\\"ep-pricing-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">{{price}}</span><span class=\\\"ep-pricing-period\\\">{{period}}</span></div><p class=\\\"ep-pricing-description\\\">{{pricingDescription}}</p></div><div class=\\\"ep-trial-info\\\"><p class=\\\"ep-text-sm\\\">{{trialInfo}}</p></div></div></div><div class=\\\"ep-modal-actions\\\"><button class=\\\"ep-btn ep-btn-primary ep-btn-lg ep-btn-full\\\" data-ep-action=\\\"upgradeNow\\\"> {{upgradeButtonText}} </button><button class=\\\"ep-btn ep-btn-ghost ep-btn-sm\\\" data-ep-action=\\\"closePaywall\\\"> {{cancelButtonText}} </button></div><div class=\\\"ep-modal-footer\\\"><p class=\\\"ep-text-sm\\\">{{footerText}}</p></div></div></div></div>\";\nexport const css = \".ep-modal-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,0.75);backdrop-filter:blur(4px);z-index:var(--ep-z-modal);display:flex;align-items:center;justify-content:center;padding:var(--ep-space-4);animation:ep-modal-backdrop-in var(--ep-transition-normal)}.ep-modal-backdrop.ep-modal-closing{animation:ep-modal-backdrop-out var(--ep-transition-normal)}.ep-modal-container{position:relative;background-color:var(--ep-bg-secondary);border-radius:var(--ep-radius-xl);box-shadow:var(--ep-shadow-xl);max-width:480px;width:100%;max-height:90vh;overflow-y:auto;animation:ep-modal-container-in var(--ep-transition-normal)}.ep-modal-backdrop.ep-modal-closing .ep-modal-container{animation:ep-modal-container-out var(--ep-transition-normal)}.ep-modal-close{position:absolute;top:var(--ep-space-4);right:var(--ep-space-4);background:none;border:none;color:var(--ep-text-tertiary);cursor:pointer;padding:var(--ep-space-2);border-radius:var(--ep-radius-md);transition:all var(--ep-transition-fast);z-index:1}.ep-modal-close:hover{color:var(--ep-text-primary);background-color:var(--ep-bg-tertiary)}.ep-modal-close:focus{outline:2px solid var(--ep-primary-500);outline-offset:2px}.ep-modal-content{padding:var(--ep-space-8);padding-top:var(--ep-space-12)}.ep-modal-header{text-align:center;margin-bottom:var(--ep-space-8)}.ep-modal-icon{width:80px;height:80px;margin:0 auto var(--ep-space-4);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-2xl);display:flex;align-items:center;justify-content:center;color:white}.ep-modal-header .ep-heading-2{margin-bottom:var(--ep-space-3)}.ep-modal-header .ep-text-body{margin-bottom:0;font-size:var(--ep-font-size-lg)}.ep-modal-features{margin-bottom:var(--ep-space-8)}.ep-modal-features .ep-heading-3{margin-bottom:var(--ep-space-4);text-align:center}.ep-feature-list{list-style:none;padding:0;margin:0}.ep-feature-item{display:flex;align-items:center;gap:var(--ep-space-3);padding:var(--ep-space-3) 0;border-bottom:1px solid var(--ep-border-primary)}.ep-feature-item:last-child{border-bottom:none}.ep-feature-icon{color:var(--ep-success-500);flex-shrink:0}.ep-feature-item span{color:var(--ep-text-primary);font-weight:var(--ep-font-weight-medium)}.ep-modal-pricing{margin-bottom:var(--ep-space-8)}.ep-pricing-card{background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100));border:1px solid var(--ep-primary-200);border-radius:var(--ep-radius-lg);padding:var(--ep-space-6);text-align:center}:host([data-theme=\\\"dark\\\"]) .ep-pricing-card{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800));border-color:var(--ep-primary-700)}.ep-pricing-header{margin-bottom:var(--ep-space-4)}.ep-pricing-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-1);margin-bottom:var(--ep-space-2)}.ep-pricing-currency{font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-pricing-amount{font-size:var(--ep-font-size-4xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-pricing-period{font-size:var(--ep-font-size-lg);color:var(--ep-text-secondary)}.ep-pricing-description{color:var(--ep-text-secondary);margin:0}.ep-trial-info{background-color:var(--ep-success-50);border:1px solid var(--ep-success-200);border-radius:var(--ep-radius-md);padding:var(--ep-space-3);margin-top:var(--ep-space-4)}:host([data-theme=\\\"dark\\\"]) .ep-trial-info{background-color:rgba(16,185,129,0.1);border-color:rgba(16,185,129,0.3)}.ep-trial-info .ep-text-sm{color:var(--ep-success-700);margin:0;font-weight:var(--ep-font-weight-medium)}:host([data-theme=\\\"dark\\\"]) .ep-trial-info .ep-text-sm{color:var(--ep-success-400)}.ep-modal-actions{display:flex;flex-direction:column;gap:var(--ep-space-3);margin-bottom:var(--ep-space-6)}.ep-modal-footer{text-align:center;padding-top:var(--ep-space-6);border-top:1px solid var(--ep-border-primary)}.ep-modal-footer .ep-text-sm{margin:0}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);left:var(--ep-space-4);z-index:var(--ep-z-tooltip)}@keyframes ep-modal-backdrop-in{from{opacity:0}to{opacity:1}}@keyframes ep-modal-backdrop-out{from{opacity:1}to{opacity:0}}@keyframes ep-modal-container-in{from{opacity:0;transform:scale(0.95) translateY(-10px)}to{opacity:1;transform:scale(1) translateY(0)}}@keyframes ep-modal-container-out{from{opacity:1;transform:scale(1) translateY(0)}to{opacity:0;transform:scale(0.95) translateY(-10px)}}@media (max-width:640px){.ep-modal-backdrop{padding:var(--ep-space-2)}.ep-modal-container{max-width:100%;border-radius:var(--ep-radius-lg)}.ep-modal-content{padding:var(--ep-space-6);padding-top:var(--ep-space-10)}.ep-modal-icon{width:60px;height:60px}.ep-modal-header .ep-heading-2{font-size:var(--ep-font-size-xl)}.ep-pricing-amount{font-size:var(--ep-font-size-3xl)}}@media (max-width:480px){.ep-modal-content{padding:var(--ep-space-4);padding-top:var(--ep-space-8)}.ep-modal-close{top:var(--ep-space-3);right:var(--ep-space-3)}}@media (prefers-contrast:high){.ep-modal-backdrop{background-color:rgba(0,0,0,0.9);backdrop-filter:none}.ep-modal-container{border:2px solid var(--ep-border-secondary)}.ep-pricing-card{background:var(--ep-bg-secondary);border:2px solid var(--ep-primary-500)}}@media (prefers-reduced-motion:reduce){.ep-modal-backdrop{animation:none}.ep-modal-container{animation:none}.ep-modal-backdrop.ep-modal-closing{animation:none}.ep-modal-backdrop.ep-modal-closing .ep-modal-container{animation:none}}\";\nexport default { html, css };","export const html = \"<div class=\\\"ep-inline-paywall\\\" id=\\\"inlinePaywall\\\" role=\\\"region\\\" aria-labelledby=\\\"paywall-title\\\"><div class=\\\"ep-inline-header\\\"><div class=\\\"ep-inline-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M9 12l2 2 4-4\\\"></path><path d=\\\"M21 12c-1 0-3-1-3-3s2-3 3-3 3 1 3 3-2 3-3 3\\\"></path><path d=\\\"M3 12c1 0 3-1 3-3s-2-3-3-3-3 1-3 3 2 3 3 3\\\"></path></svg></div><div class=\\\"ep-inline-header-content\\\"><h3 class=\\\"ep-heading-3\\\" id=\\\"paywall-title\\\">{{title}}</h3><p class=\\\"ep-text-body\\\">{{description}}</p></div></div><div class=\\\"ep-inline-content\\\"><div class=\\\"ep-inline-features\\\"><div class=\\\"ep-feature-grid\\\"><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 12h-4l-3 9L9 3l-3 9H2\\\"></path></svg></div><h4 class=\\\"ep-feature-card-title\\\">{{feature1Title}}</h4><p class=\\\"ep-feature-card-description\\\">{{feature1Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z\\\"></path></svg></div><h4 class=\\\"ep-feature-card-title\\\">{{feature2Title}}</h4><p class=\\\"ep-feature-card-description\\\">{{feature2Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M13 2L3 14h9l-1 8 10-12h-9l1-8z\\\"></path></svg></div><h4 class=\\\"ep-feature-card-title\\\">{{feature3Title}}</h4><p class=\\\"ep-feature-card-description\\\">{{feature3Description}}</p></div></div></div><div class=\\\"ep-inline-pricing\\\"><div class=\\\"ep-pricing-comparison\\\"><div class=\\\"ep-pricing-plan\\\"><div class=\\\"ep-pricing-plan-header\\\"><h4 class=\\\"ep-pricing-plan-title\\\">{{freePlanName}}</h4><div class=\\\"ep-pricing-plan-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">0</span></div></div><ul class=\\\"ep-pricing-plan-features\\\"><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{freeFeature1}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{freeFeature2}} </li><li class=\\\"ep-pricing-feature ep-pricing-feature-disabled\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg> {{freeFeature3}} </li></ul></div><div class=\\\"ep-pricing-plan ep-pricing-plan-premium\\\"><div class=\\\"ep-pricing-plan-badge\\\">{{popularBadge}}</div><div class=\\\"ep-pricing-plan-header\\\"><h4 class=\\\"ep-pricing-plan-title\\\">{{premiumPlanName}}</h4><div class=\\\"ep-pricing-plan-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">{{price}}</span><span class=\\\"ep-pricing-period\\\">{{period}}</span></div></div><ul class=\\\"ep-pricing-plan-features\\\"><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature1}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature2}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature3}} </li></ul><button class=\\\"ep-btn ep-btn-primary ep-btn-full\\\" data-ep-action=\\\"upgradeNow\\\"> {{upgradeButtonText}} </button></div></div></div><div class=\\\"ep-inline-trial\\\"><div class=\\\"ep-trial-content\\\"><p class=\\\"ep-trial-text\\\">{{trialText}}</p><div class=\\\"ep-trial-actions\\\"><button class=\\\"ep-btn ep-btn-secondary\\\" data-ep-action=\\\"startTrial\\\"> {{trialButtonText}} </button><button class=\\\"ep-btn ep-btn-ghost ep-btn-sm\\\" data-ep-action=\\\"dismissPaywall\\\"> {{dismissButtonText}} </button></div></div></div></div></div>\";\nexport const css = \".ep-inline-paywall{max-width:800px;margin:0 auto;background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-lg);box-shadow:var(--ep-shadow-md);overflow:hidden;opacity:0;transform:translateY(20px);transition:all var(--ep-transition-slow)}.ep-inline-paywall.ep-inline-visible{opacity:1;transform:translateY(0)}.ep-inline-paywall.ep-inline-dismissing{opacity:0;transform:translateY(-20px);transition:all var(--ep-transition-normal)}.ep-inline-header{display:flex;align-items:center;gap:var(--ep-space-4);padding:var(--ep-space-6);background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100));border-bottom:1px solid var(--ep-border-primary)}:host([data-theme=\\\"dark\\\"]) .ep-inline-header{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800))}.ep-inline-icon{width:64px;height:64px;background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-xl);display:flex;align-items:center;justify-content:center;color:white;flex-shrink:0}.ep-inline-header-content{flex:1;min-width:0}.ep-inline-header-content .ep-heading-3{margin-bottom:var(--ep-space-2);color:var(--ep-text-primary)}.ep-inline-header-content .ep-text-body{margin-bottom:0;color:var(--ep-text-secondary)}.ep-inline-content{padding:var(--ep-space-8)}.ep-inline-features{margin-bottom:var(--ep-space-8)}.ep-feature-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:var(--ep-space-4)}.ep-feature-card{background-color:var(--ep-bg-tertiary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-md);padding:var(--ep-space-4);text-align:center;transition:all var(--ep-transition-normal);opacity:0;transform:translateY(10px);animation:ep-feature-card-in var(--ep-transition-slow) forwards}.ep-feature-card:hover{transform:translateY(-2px);box-shadow:var(--ep-shadow-md)}.ep-feature-card-icon{width:48px;height:48px;margin:0 auto var(--ep-space-3);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-lg);display:flex;align-items:center;justify-content:center;color:white}.ep-feature-card-title{font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-2)}.ep-feature-card-description{color:var(--ep-text-secondary);font-size:var(--ep-font-size-sm);line-height:var(--ep-line-height-relaxed);margin:0}.ep-inline-pricing{margin-bottom:var(--ep-space-8)}.ep-pricing-comparison{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:var(--ep-space-4);max-width:600px;margin:0 auto}.ep-pricing-plan{position:relative;background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-lg);padding:var(--ep-space-6);transition:all var(--ep-transition-normal)}.ep-pricing-plan:hover{transform:translateY(-2px);box-shadow:var(--ep-shadow-md)}.ep-pricing-plan-premium{border-color:var(--ep-primary-300);box-shadow:var(--ep-shadow-lg)}.ep-pricing-plan-badge{position:absolute;top:-12px;left:50%;transform:translateX(-50%);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));color:white;padding:var(--ep-space-1) var(--ep-space-4);border-radius:var(--ep-radius-full);font-size:var(--ep-font-size-sm);font-weight:var(--ep-font-weight-medium);white-space:nowrap}.ep-pricing-plan-header{text-align:center;margin-bottom:var(--ep-space-6)}.ep-pricing-plan-title{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-3)}.ep-pricing-plan-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-1)}.ep-pricing-currency{font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-pricing-amount{font-size:var(--ep-font-size-3xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-pricing-period{font-size:var(--ep-font-size-lg);color:var(--ep-text-secondary)}.ep-pricing-plan-features{list-style:none;padding:0;margin:0 0 var(--ep-space-6) 0}.ep-pricing-feature{display:flex;align-items:center;gap:var(--ep-space-3);padding:var(--ep-space-2) 0;color:var(--ep-text-primary);font-size:var(--ep-font-size-sm)}.ep-pricing-feature-disabled{color:var(--ep-text-tertiary)}.ep-pricing-feature-icon{color:var(--ep-success-500);flex-shrink:0}.ep-pricing-feature-disabled .ep-pricing-feature-icon{color:var(--ep-text-tertiary)}.ep-inline-trial{background:linear-gradient(135deg,var(--ep-gray-50),var(--ep-gray-100));border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-md);padding:var(--ep-space-6);text-align:center}:host([data-theme=\\\"dark\\\"]) .ep-inline-trial{background:linear-gradient(135deg,var(--ep-gray-800),var(--ep-gray-700))}.ep-trial-content{max-width:400px;margin:0 auto}.ep-trial-text{color:var(--ep-text-primary);font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-medium);margin-bottom:var(--ep-space-6)}.ep-trial-actions{display:flex;flex-direction:column;gap:var(--ep-space-3);align-items:center}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);right:var(--ep-space-4);z-index:var(--ep-z-tooltip)}@keyframes ep-feature-card-in{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@media (max-width:768px){.ep-inline-paywall{margin:var(--ep-space-4)}.ep-inline-header{flex-direction:column;text-align:center;gap:var(--ep-space-3)}.ep-inline-content{padding:var(--ep-space-6)}.ep-feature-grid{grid-template-columns:1fr}.ep-pricing-comparison{grid-template-columns:1fr}.ep-pricing-plan{padding:var(--ep-space-4)}.ep-trial-actions{flex-direction:column;width:100%}.ep-trial-actions .ep-btn{width:100%}}@media (max-width:640px){.ep-inline-paywall{margin:var(--ep-space-2);border-radius:var(--ep-radius-md)}.ep-inline-header{padding:var(--ep-space-4)}.ep-inline-content{padding:var(--ep-space-4)}.ep-inline-icon{width:48px;height:48px}.ep-feature-card-icon{width:40px;height:40px}.ep-pricing-plan{padding:var(--ep-space-3)}.ep-pricing-amount{font-size:var(--ep-font-size-2xl)}}@media (prefers-contrast:high){.ep-inline-paywall{border:2px solid var(--ep-border-secondary)}.ep-feature-card{border:2px solid var(--ep-border-secondary)}.ep-pricing-plan{border:2px solid var(--ep-border-secondary)}.ep-pricing-plan-premium{border:2px solid var(--ep-primary-500)}}@media (prefers-reduced-motion:reduce){.ep-inline-paywall{transition:none;opacity:1;transform:none}.ep-feature-card{transition:none;animation:none;opacity:1;transform:none}.ep-feature-card:hover{transform:none}.ep-pricing-plan:hover{transform:none}}\";\nexport default { html, css };","export const html = \"<div class=\\\"ep-sidebar-backdrop\\\" id=\\\"sidebarBackdrop\\\"></div><div class=\\\"ep-sidebar-paywall\\\" id=\\\"sidebarPaywall\\\" role=\\\"dialog\\\" aria-labelledby=\\\"sidebar-title\\\" aria-describedby=\\\"sidebar-description\\\"><div class=\\\"ep-sidebar-header\\\"><button class=\\\"ep-sidebar-close\\\" aria-label=\\\"Close paywall\\\" data-ep-action=\\\"closeSidebar\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg></button><div class=\\\"ep-sidebar-logo\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 2L2 7l10 5 10-5-10-5z\\\"></path><path d=\\\"M2 17l10 5 10-5\\\"></path><path d=\\\"M2 12l10 5 10-5\\\"></path></svg><span class=\\\"ep-sidebar-logo-text\\\">{{brandName}}</span></div></div><div class=\\\"ep-sidebar-content\\\"><div class=\\\"ep-sidebar-title-section\\\"><h2 class=\\\"ep-heading-2\\\" id=\\\"sidebar-title\\\">{{title}}</h2><p class=\\\"ep-text-body\\\" id=\\\"sidebar-description\\\">{{description}}</p></div><div class=\\\"ep-sidebar-progress\\\"><div class=\\\"ep-progress-header\\\"><span class=\\\"ep-progress-label\\\">{{progressLabel}}</span><span class=\\\"ep-progress-value\\\">{{usageCount}}/{{usageLimit}}</span></div><div class=\\\"ep-progress-bar\\\"><div class=\\\"ep-progress-fill\\\" style=\\\"width: {{progressPercentage}}%\\\"></div></div><p class=\\\"ep-progress-text\\\">{{progressText}}</p></div><div class=\\\"ep-sidebar-features\\\"><h3 class=\\\"ep-heading-3\\\">{{unlockHeading}}</h3><div class=\\\"ep-feature-list\\\"><div class=\\\"ep-feature-item\\\"><div class=\\\"ep-feature-icon\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 2L2 7l10 5 10-5-10-5z\\\"></path><path d=\\\"M2 17l10 5 10-5\\\"></path><path d=\\\"M2 12l10 5 10-5\\\"></path></svg></div><div class=\\\"ep-feature-content\\\"><h4 class=\\\"ep-feature-title\\\">{{feature1Title}}</h4><p class=\\\"ep-feature-description\\\">{{feature1Description}}</p></div></div><div class=\\\"ep-feature-item\\\"><div class=\\\"ep-feature-icon\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 12h-4l-3 9L9 3l-3 9H2\\\"></path></svg></div><div class=\\\"ep-feature-content\\\"><h4 class=\\\"ep-feature-title\\\">{{feature2Title}}</h4><p class=\\\"ep-feature-description\\\">{{feature2Description}}</p></div></div><div class=\\\"ep-feature-item\\\"><div class=\\\"ep-feature-icon\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z\\\"></path></svg></div><div class=\\\"ep-feature-content\\\"><h4 class=\\\"ep-feature-title\\\">{{feature3Title}}</h4><p class=\\\"ep-feature-description\\\">{{feature3Description}}</p></div></div></div></div><div class=\\\"ep-sidebar-pricing\\\"><div class=\\\"ep-pricing-card\\\"><div class=\\\"ep-pricing-header\\\"><div class=\\\"ep-pricing-badge\\\">{{pricingBadge}}</div><div class=\\\"ep-pricing-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">{{price}}</span><span class=\\\"ep-pricing-period\\\">{{period}}</span></div><p class=\\\"ep-pricing-description\\\">{{pricingDescription}}</p></div></div></div><div class=\\\"ep-sidebar-trial\\\"><div class=\\\"ep-trial-info\\\"><div class=\\\"ep-trial-icon\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 11.08V12a10 10 0 1 1-5.93-9.14\\\"></path><polyline points=\\\"22,4 12,14.01 9,11.01\\\"></polyline></svg></div><div class=\\\"ep-trial-content\\\"><h4 class=\\\"ep-trial-title\\\">{{trialTitle}}</h4><p class=\\\"ep-trial-description\\\">{{trialDescription}}</p></div></div></div></div><div class=\\\"ep-sidebar-footer\\\"><button class=\\\"ep-btn ep-btn-primary ep-btn-lg ep-btn-full\\\" data-ep-action=\\\"startUpgrade\\\"> {{upgradeButtonText}} </button><button class=\\\"ep-btn ep-btn-secondary ep-btn-full\\\" data-ep-action=\\\"startTrial\\\"> {{trialButtonText}} </button><button class=\\\"ep-btn ep-btn-ghost ep-btn-sm\\\" data-ep-action=\\\"remindLater\\\"> {{remindLaterText}} </button></div></div>\";\nexport const css = \".ep-sidebar-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,0.5);backdrop-filter:blur(2px);z-index:var(--ep-z-backdrop);opacity:0;visibility:hidden;transition:all var(--ep-transition-normal)}.ep-sidebar-backdrop.ep-sidebar-backdrop-visible{opacity:1;visibility:visible}.ep-sidebar-paywall{position:fixed;top:0;right:0;bottom:0;width:400px;max-width:90vw;background-color:var(--ep-bg-secondary);border-left:1px solid var(--ep-border-primary);box-shadow:var(--ep-shadow-xl);z-index:var(--ep-z-modal);display:flex;flex-direction:column;transform:translateX(100%);transition:transform var(--ep-transition-normal)}.ep-sidebar-paywall.ep-sidebar-visible{transform:translateX(0)}.ep-sidebar-header{display:flex;align-items:center;justify-content:space-between;padding:var(--ep-space-4) var(--ep-space-6);border-bottom:1px solid var(--ep-border-primary);background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100))}:host([data-theme=\\\"dark\\\"]) .ep-sidebar-header{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800))}.ep-sidebar-close{background:none;border:none;color:var(--ep-text-tertiary);cursor:pointer;padding:var(--ep-space-2);border-radius:var(--ep-radius-md);transition:all var(--ep-transition-fast)}.ep-sidebar-close:hover{color:var(--ep-text-primary);background-color:var(--ep-bg-tertiary)}.ep-sidebar-logo{display:flex;align-items:center;gap:var(--ep-space-2);color:var(--ep-primary-600)}.ep-sidebar-logo-text{font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary)}.ep-sidebar-content{flex:1;padding:var(--ep-space-6);overflow-y:auto;display:flex;flex-direction:column;gap:var(--ep-space-6)}.ep-sidebar-title-section{text-align:center}.ep-sidebar-title-section .ep-heading-2{margin-bottom:var(--ep-space-3);color:var(--ep-text-primary)}.ep-sidebar-title-section .ep-text-body{margin-bottom:0;color:var(--ep-text-secondary)}.ep-sidebar-progress{background-color:var(--ep-bg-tertiary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-md);padding:var(--ep-space-4)}.ep-progress-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:var(--ep-space-3)}.ep-progress-label{font-size:var(--ep-font-size-sm);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-primary)}.ep-progress-value{font-size:var(--ep-font-size-sm);font-weight:var(--ep-font-weight-semibold);color:var(--ep-primary-600)}.ep-progress-bar{height:8px;background-color:var(--ep-bg-primary);border-radius:var(--ep-radius-full);overflow:hidden;margin-bottom:var(--ep-space-2)}.ep-progress-fill{height:100%;background:linear-gradient(90deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-full);transition:width var(--ep-transition-normal)}.ep-progress-text{font-size:var(--ep-font-size-xs);color:var(--ep-text-tertiary);margin:0}.ep-sidebar-features .ep-heading-3{margin-bottom:var(--ep-space-4);text-align:center}.ep-feature-list{display:flex;flex-direction:column;gap:var(--ep-space-4)}.ep-feature-item{display:flex;align-items:flex-start;gap:var(--ep-space-3);padding:var(--ep-space-3);background-color:var(--ep-bg-tertiary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-md);opacity:0;transform:translateX(20px);transition:all var(--ep-transition-normal)}.ep-feature-item.ep-feature-item-visible{opacity:1;transform:translateX(0)}.ep-feature-icon{width:40px;height:40px;background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-lg);display:flex;align-items:center;justify-content:center;color:white;flex-shrink:0}.ep-feature-content{flex:1;min-width:0}.ep-feature-title{font-size:var(--ep-font-size-base);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-1)}.ep-feature-description{font-size:var(--ep-font-size-sm);color:var(--ep-text-secondary);line-height:var(--ep-line-height-relaxed);margin:0}.ep-sidebar-pricing{background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100));border:1px solid var(--ep-primary-200);border-radius:var(--ep-radius-lg);padding:var(--ep-space-4)}:host([data-theme=\\\"dark\\\"]) .ep-sidebar-pricing{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800));border-color:var(--ep-primary-700)}.ep-pricing-card{text-align:center}.ep-pricing-header{margin-bottom:var(--ep-space-4)}.ep-pricing-badge{background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));color:white;padding:var(--ep-space-1) var(--ep-space-3);border-radius:var(--ep-radius-full);font-size:var(--ep-font-size-xs);font-weight:var(--ep-font-weight-medium);display:inline-block;margin-bottom:var(--ep-space-3)}.ep-pricing-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-1);margin-bottom:var(--ep-space-2)}.ep-pricing-currency{font-size:var(--ep-font-size-base);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-pricing-amount{font-size:var(--ep-font-size-2xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-pricing-period{font-size:var(--ep-font-size-base);color:var(--ep-text-secondary)}.ep-pricing-description{font-size:var(--ep-font-size-sm);color:var(--ep-text-secondary);margin:0}.ep-sidebar-trial{background-color:var(--ep-success-50);border:1px solid var(--ep-success-200);border-radius:var(--ep-radius-md);padding:var(--ep-space-4)}:host([data-theme=\\\"dark\\\"]) .ep-sidebar-trial{background-color:rgba(16,185,129,0.1);border-color:rgba(16,185,129,0.3)}.ep-trial-info{display:flex;align-items:flex-start;gap:var(--ep-space-3)}.ep-trial-icon{width:32px;height:32px;background:linear-gradient(135deg,var(--ep-success-500),var(--ep-success-600));border-radius:var(--ep-radius-lg);display:flex;align-items:center;justify-content:center;color:white;flex-shrink:0}.ep-trial-content{flex:1;min-width:0}.ep-trial-title{font-size:var(--ep-font-size-base);font-weight:var(--ep-font-weight-semibold);color:var(--ep-success-700);margin-bottom:var(--ep-space-1)}:host([data-theme=\\\"dark\\\"]) .ep-trial-title{color:var(--ep-success-400)}.ep-trial-description{font-size:var(--ep-font-size-sm);color:var(--ep-success-600);line-height:var(--ep-line-height-relaxed);margin:0}:host([data-theme=\\\"dark\\\"]) .ep-trial-description{color:var(--ep-success-300)}.ep-sidebar-footer{padding:var(--ep-space-6);border-top:1px solid var(--ep-border-primary);background-color:var(--ep-bg-tertiary);display:flex;flex-direction:column;gap:var(--ep-space-3)}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);left:var(--ep-space-4);z-index:var(--ep-z-tooltip);display:flex;flex-direction:column;gap:var(--ep-space-2)}@media (max-width:768px){.ep-sidebar-paywall{width:100%;max-width:100%;border-left:none}.ep-sidebar-content{padding:var(--ep-space-4)}.ep-sidebar-footer{padding:var(--ep-space-4)}}@media (max-width:480px){.ep-sidebar-header{padding:var(--ep-space-3) var(--ep-space-4)}.ep-sidebar-content{padding:var(--ep-space-3);gap:var(--ep-space-4)}.ep-sidebar-footer{padding:var(--ep-space-3)}.ep-feature-item{padding:var(--ep-space-2)}.ep-feature-icon{width:32px;height:32px}.ep-pricing-amount{font-size:var(--ep-font-size-xl)}}@media (prefers-contrast:high){.ep-sidebar-paywall{border-left:2px solid var(--ep-border-secondary)}.ep-feature-item{border:2px solid var(--ep-border-secondary)}.ep-sidebar-pricing{border:2px solid var(--ep-primary-500)}.ep-sidebar-trial{border:2px solid var(--ep-success-500)}}@media (prefers-reduced-motion:reduce){.ep-sidebar-backdrop{transition:none}.ep-sidebar-paywall{transition:none}.ep-feature-item{transition:none;opacity:1;transform:none}.ep-progress-fill{transition:none}}\";\nexport default { html, css };","export const html = \"<div class=\\\"ep-minimal-paywall\\\" id=\\\"minimalPaywall\\\" role=\\\"dialog\\\" aria-labelledby=\\\"minimal-title\\\"><button class=\\\"ep-minimal-close\\\" aria-label=\\\"Close paywall\\\" data-ep-action=\\\"closeMinimal\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg></button><div class=\\\"ep-minimal-content\\\"><div class=\\\"ep-minimal-header\\\"><div class=\\\"ep-minimal-icon\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M9 12l2 2 4-4\\\"></path><path d=\\\"M21 12c-1 0-3-1-3-3s2-3 3-3 3 1 3 3-2 3-3 3\\\"></path><path d=\\\"M3 12c1 0 3-1 3-3s-2-3-3-3-3 1-3 3 2 3 3 3\\\"></path></svg></div><h3 class=\\\"ep-minimal-title\\\" id=\\\"minimal-title\\\">{{title}}</h3><p class=\\\"ep-minimal-description\\\">{{description}}</p></div><div class=\\\"ep-minimal-pricing\\\"><div class=\\\"ep-minimal-price\\\"><span class=\\\"ep-minimal-currency\\\">{{currency}}</span><span class=\\\"ep-minimal-amount\\\">{{price}}</span><span class=\\\"ep-minimal-period\\\">{{period}}</span></div><p class=\\\"ep-minimal-price-description\\\">{{priceDescription}}</p></div><div class=\\\"ep-minimal-features\\\"><ul class=\\\"ep-minimal-feature-list\\\"><li class=\\\"ep-minimal-feature\\\"><svg class=\\\"ep-minimal-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature1}}</span></li><li class=\\\"ep-minimal-feature\\\"><svg class=\\\"ep-minimal-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature2}}</span></li><li class=\\\"ep-minimal-feature\\\"><svg class=\\\"ep-minimal-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature3}}</span></li></ul></div><div class=\\\"ep-minimal-actions\\\"><button class=\\\"ep-btn ep-btn-primary ep-btn-full\\\" data-ep-action=\\\"upgradeNow\\\"> {{upgradeButtonText}} </button><button class=\\\"ep-btn ep-btn-ghost ep-btn-sm\\\" data-ep-action=\\\"closeMinimal\\\"> {{dismissButtonText}} </button></div><div class=\\\"ep-minimal-trial\\\"><p class=\\\"ep-minimal-trial-text\\\">{{trialText}}</p></div></div></div><div class=\\\"ep-minimal-backdrop\\\" id=\\\"minimalBackdrop\\\"></div>\";\nexport const css = \".ep-minimal-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,0.4);z-index:var(--ep-z-backdrop);opacity:0;visibility:hidden;transition:all var(--ep-transition-fast)}.ep-minimal-backdrop.ep-minimal-backdrop-visible{opacity:1;visibility:visible}.ep-minimal-paywall{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%) scale(0.95);background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-lg);box-shadow:var(--ep-shadow-xl);z-index:var(--ep-z-modal);max-width:400px;width:90vw;max-height:90vh;overflow-y:auto;opacity:0;visibility:hidden;transition:all var(--ep-transition-fast)}.ep-minimal-paywall.ep-minimal-visible{opacity:1;visibility:visible;transform:translate(-50%,-50%) scale(1)}.ep-minimal-close{position:absolute;top:var(--ep-space-3);right:var(--ep-space-3);background:none;border:none;color:var(--ep-text-tertiary);cursor:pointer;padding:var(--ep-space-2);border-radius:var(--ep-radius-sm);transition:all var(--ep-transition-fast);z-index:1}.ep-minimal-close:hover{color:var(--ep-text-primary);background-color:var(--ep-bg-tertiary)}.ep-minimal-content{padding:var(--ep-space-6);padding-top:var(--ep-space-8)}.ep-minimal-header{text-align:center;margin-bottom:var(--ep-space-6)}.ep-minimal-icon{width:48px;height:48px;margin:0 auto var(--ep-space-3);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-lg);display:flex;align-items:center;justify-content:center;color:white}.ep-minimal-title{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-2)}.ep-minimal-description{color:var(--ep-text-secondary);font-size:var(--ep-font-size-sm);line-height:var(--ep-line-height-relaxed);margin:0}.ep-minimal-pricing{text-align:center;margin-bottom:var(--ep-space-6);padding:var(--ep-space-4);background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100));border:1px solid var(--ep-primary-200);border-radius:var(--ep-radius-md)}:host([data-theme=\\\"dark\\\"]) .ep-minimal-pricing{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800));border-color:var(--ep-primary-700)}.ep-minimal-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-1);margin-bottom:var(--ep-space-2)}.ep-minimal-currency{font-size:var(--ep-font-size-base);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-minimal-amount{font-size:var(--ep-font-size-2xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-minimal-period{font-size:var(--ep-font-size-base);color:var(--ep-text-secondary)}.ep-minimal-price-description{color:var(--ep-text-secondary);font-size:var(--ep-font-size-xs);margin:0}.ep-minimal-features{margin-bottom:var(--ep-space-6)}.ep-minimal-feature-list{list-style:none;padding:0;margin:0}.ep-minimal-feature{display:flex;align-items:center;gap:var(--ep-space-2);padding:var(--ep-space-2) 0;color:var(--ep-text-primary);font-size:var(--ep-font-size-sm);border-bottom:1px solid var(--ep-border-primary)}.ep-minimal-feature:last-child{border-bottom:none}.ep-minimal-feature-icon{color:var(--ep-success-500);flex-shrink:0}.ep-minimal-feature span{font-weight:var(--ep-font-weight-medium)}.ep-minimal-actions{display:flex;flex-direction:column;gap:var(--ep-space-2);margin-bottom:var(--ep-space-4)}.ep-minimal-trial{text-align:center;padding-top:var(--ep-space-4);border-top:1px solid var(--ep-border-primary)}.ep-minimal-trial-text{color:var(--ep-text-tertiary);font-size:var(--ep-font-size-xs);margin:0}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);left:var(--ep-space-4);z-index:var(--ep-z-tooltip);display:flex;flex-direction:column;gap:var(--ep-space-2)}@media (max-width:480px){.ep-minimal-paywall{width:95vw;max-width:none}.ep-minimal-content{padding:var(--ep-space-4);padding-top:var(--ep-space-6)}.ep-minimal-close{top:var(--ep-space-2);right:var(--ep-space-2)}.ep-minimal-icon{width:40px;height:40px}.ep-minimal-title{font-size:var(--ep-font-size-lg)}.ep-minimal-amount{font-size:var(--ep-font-size-xl)}.ep-minimal-pricing{padding:var(--ep-space-3)}}@media (prefers-contrast:high){.ep-minimal-paywall{border:2px solid var(--ep-border-secondary)}.ep-minimal-pricing{border:2px solid var(--ep-primary-500)}.ep-minimal-backdrop{background-color:rgba(0,0,0,0.8)}}@media (prefers-reduced-motion:reduce){.ep-minimal-backdrop{transition:none}.ep-minimal-paywall{transition:none;transform:translate(-50%,-50%)}.ep-minimal-paywall.ep-minimal-visible{transform:translate(-50%,-50%)}}@media print{.ep-minimal-backdrop{display:none}.ep-minimal-paywall{position:static;transform:none;box-shadow:none;border:1px solid black;opacity:1;visibility:visible}.ep-minimal-close{display:none}}.ep-minimal-paywall *:focus{outline:2px solid var(--ep-primary-500);outline-offset:2px}.ep-minimal-paywall *:focus:not(:focus-visible){outline:none}.ep-minimal-paywall{animation:ep-minimal-entrance var(--ep-transition-normal) ease-out}@keyframes ep-minimal-entrance{from{opacity:0;transform:translate(-50%,-50%) scale(0.9)}to{opacity:1;transform:translate(-50%,-50%) scale(1)}}.ep-minimal-feature:hover{background-color:var(--ep-bg-tertiary);border-radius:var(--ep-radius-sm);margin:0 calc(-1 * var(--ep-space-2));padding:var(--ep-space-2)}.ep-minimal-pricing:hover{background:linear-gradient(135deg,var(--ep-primary-100),var(--ep-primary-200));border-color:var(--ep-primary-300)}:host([data-theme=\\\"dark\\\"]) .ep-minimal-pricing:hover{background:linear-gradient(135deg,var(--ep-primary-800),var(--ep-primary-700));border-color:var(--ep-primary-600)}\";\nexport default { html, css };","/**\n * The one paywall renderer.\n *\n * Renders a template from `@extenshi/paywall-templates` into a Shadow DOM\n * host so the templates' resets never leak into the extension page (and vice\n * versa). Placeholders (`{{title}}`, `{{price}}` …) are filled from the offer\n * and the strings dictionary, every value HTML-escaped; buttons are bound with\n * `addEventListener` on `data-ep-action` (no inline handlers, no scripts).\n */\n\nimport { withdrawalWaiverText } from '../payment/withdrawal-waiver.js'\nimport type { ThemeConfig } from '../types/config.js'\nimport type { PayOfferDto, PaySellerPublic, PayWithdrawalWaiver } from '../types/contract.js'\nimport type { UpgradeConsent } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { PaywallMode, PaywallStrings } from '../types/paywall.js'\nimport { formatPrice, periodLabel } from './format.js'\nimport { sdkDir, sdkLocale, sdkStrings } from './i18n.js'\nimport { sellerDetails } from './seller-details.js'\nimport { stringsFor } from './strings.js'\nimport { PAYWALL_SHARED_CSS, PAYWALL_TEMPLATES } from './templates.js'\n\nexport interface PaywallView {\n\tmode: PaywallMode\n\ttitle: string\n\tdescription: string\n\tfeatures: string[]\n\tfreeFeatures: string[]\n\tbrandName: string\n\toffer: PayOfferDto | null\n\tcheckoutEnabled: boolean\n\tmock?: boolean\n\trecoveryEnabled?: boolean\n\tseller?: PaySellerPublic | null\n\t/**\n\t * From `PayOfferResponse.withdrawalWaiver`: when set (and the offer is\n\t * purchasable) an unticked waiver checkbox gates every upgrade button.\n\t * The waiver text is not overridable through `strings`: it is versioned.\n\t */\n\twithdrawalWaiver?: PayWithdrawalWaiver | null\n\tlocale: string | null\n\ttheme: ThemeConfig\n\tstrings: Partial<PaywallStrings>\n\tcontainer?: HTMLElement\n}\n\nexport interface PaywallRendererCallbacks {\n\t/** `consent` is passed only when the paywall showed the withdrawal waiver (and it was ticked). */\n\tonUpgrade: (sku: string, consent?: UpgradeConsent) => void\n\tonClose: () => void\n\tonRestore?: () => void\n}\n\nexport const PAYWALL_HOST_CLASS = 'extenshi-paywall-host'\n\nconst UPGRADE_ACTIONS: ReadonlySet<string> = new Set(['upgradeNow', 'startUpgrade'])\nconst UPGRADE_SELECTOR = '[data-ep-action=\"upgradeNow\"], [data-ep-action=\"startUpgrade\"]'\nexport const WITHDRAWAL_WAIVER_CLASS = 'extenshi-withdrawal-waiver'\nconst CLOSE_ACTIONS: ReadonlySet<string> = new Set([\n\t'closePaywall',\n\t'closeSidebar',\n\t'closeFullscreen',\n\t'closeMinimal',\n\t'dismissPaywall',\n\t'remindLater',\n\t'continueFree',\n])\n\nconst ROOT_SELECTOR: Record<PaywallMode, string> = {\n\tmodal: '.ep-modal-backdrop',\n\tinline: '.ep-inline-paywall',\n\tsidebar: '.ep-sidebar-paywall',\n\tfullscreen: '.ep-fullscreen-paywall',\n\tminimal: '.ep-minimal-paywall',\n}\n\nconst BACKDROP_SELECTOR: Partial<Record<PaywallMode, string>> = {\n\tmodal: '.ep-modal-backdrop',\n\tsidebar: '.ep-sidebar-backdrop',\n\tminimal: '.ep-minimal-backdrop',\n}\n\nconst VISIBLE_CLASSES: Partial<Record<PaywallMode, Array<[selector: string, className: string]>>> = {\n\tinline: [['.ep-inline-paywall', 'ep-inline-visible']],\n\tsidebar: [\n\t\t['.ep-sidebar-paywall', 'ep-sidebar-visible'],\n\t\t['.ep-sidebar-backdrop', 'ep-sidebar-backdrop-visible'],\n\t],\n\tminimal: [\n\t\t['.ep-minimal-paywall', 'ep-minimal-visible'],\n\t\t['.ep-minimal-backdrop', 'ep-minimal-backdrop-visible'],\n\t],\n}\n\n/** Template blocks the contract has no data for (trials, usage meters). */\nconst PRUNE_SELECTOR = '[class*=\"-trial\"], .ep-sidebar-progress'\n/**\n * Templates stagger their feature rows in with this class from their demo\n * script (sidebar, fullscreen); without it the rows sit at opacity 0.\n */\nconst FEATURE_ITEM_VISIBLE = ['.ep-feature-item', 'ep-feature-item-visible'] as const\n/** Containers of a single feature slot; dropped when the slot's placeholder is empty. */\nconst FEATURE_SLOT_SELECTOR = 'li, .ep-feature-card, .ep-feature-item, .ep-pricing-feature, .ep-feature'\nconst EMPTY_SLOT_MARK = 'data-ep-empty'\nconst FEATURE_KEY_RE = /^(feature\\d+(Title)?|premiumFeature\\d+|freeFeature\\d+)$/\n\nexport function escapeHtml(value: string): string {\n\treturn value\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;')\n\t\t.replace(/\"/g, '&quot;')\n\t\t.replace(/'/g, '&#039;')\n}\n\nexport function substitute(html: string, content: Record<string, string>): string {\n\treturn html.replace(/\\{\\{(\\w+)\\}\\}/g, (_match, key: string) => {\n\t\tconst value = content[key] ?? ''\n\t\tif (value === '' && FEATURE_KEY_RE.test(key)) return `<i ${EMPTY_SLOT_MARK}></i>`\n\t\treturn escapeHtml(value)\n\t})\n}\n\nexport function buildContent(view: PaywallView, strings: PaywallStrings): Record<string, string> {\n\tconst offer = view.offer\n\tconst price = offer ? formatPrice(offer.amountMinor, offer.currency, view.locale) : null\n\tconst content: Record<string, string> = {\n\t\ttitle: view.title,\n\t\tdescription: view.description,\n\t\tbrandName: view.brandName,\n\t\tcurrency: price?.currency ?? '',\n\t\tprice: price?.amount ?? '',\n\t\tperiod: offer ? periodLabel(offer, strings) : '',\n\t\tpricingDescription: offer?.description ?? '',\n\t\tpriceDescription: offer?.description ?? '',\n\t\tpremiumDescription: offer?.description ?? '',\n\t\tupgradeButtonText: view.checkoutEnabled && offer ? strings.upgrade : strings.checkoutUnavailable,\n\t\tcancelButtonText: strings.cancel,\n\t\tdismissButtonText: strings.dismiss,\n\t\tremindLaterText: strings.remindLater,\n\t\tcontinueButtonText: strings.continueFree,\n\t\tfooterText: strings.footer,\n\t\tfeaturesHeading: strings.featuresHeading,\n\t\tplansHeading: strings.plansHeading,\n\t\tfreePlanName: strings.freePlanName,\n\t\tpremiumPlanName: strings.premiumPlanName,\n\t\tpopularBadge: strings.popularBadge,\n\t\tunlockHeading: strings.unlockHeading,\n\t}\n\tview.features.forEach((feature, index) => {\n\t\tconst n = index + 1\n\t\tcontent[`feature${n}`] = feature\n\t\tcontent[`feature${n}Title`] = feature\n\t\tcontent[`premiumFeature${n}`] = feature\n\t})\n\tview.freeFeatures.forEach((feature, index) => {\n\t\tcontent[`freeFeature${index + 1}`] = feature\n\t})\n\treturn content\n}\n\n/** Who supplies the content: the seller's public name, else the project/brand name. */\nfunction waiverSellerName(view: PaywallView): string {\n\treturn view.seller?.displayName?.trim() || view.brandName.trim() || view.title\n}\n\nconst CSS_VALUE_UNSAFE = /[;{}<>]/g\n\nexport function themeCss(theme: ThemeConfig): string {\n\tconst declarations: string[] = []\n\tconst safe = (value: string) => value.replace(CSS_VALUE_UNSAFE, '')\n\tif (theme.primaryColor) {\n\t\tconst color = safe(theme.primaryColor)\n\t\tdeclarations.push(`--ep-primary-500:${color}`, `--ep-primary-600:${color}`, `--ep-primary-700:${color}`)\n\t}\n\tif (theme.fontFamily) declarations.push(`--ep-font-family-sans:${safe(theme.fontFamily)}`)\n\tif (theme.borderRadius) {\n\t\tconst radius = safe(theme.borderRadius)\n\t\tdeclarations.push(`--ep-radius-md:${radius}`, `--ep-radius-lg:${radius}`, `--ep-radius-xl:${radius}`)\n\t}\n\tconst host = declarations.length > 0 ? `:host{${declarations.join(';')}}` : ''\n\treturn host + (theme.customCss ?? '')\n}\n\nexport function resolveThemeMode(theme: ThemeConfig): 'light' | 'dark' {\n\tconst mode = theme.mode ?? 'auto'\n\tif (mode !== 'auto') return mode\n\tconst matchMedia = (globalThis as { matchMedia?: (query: string) => { matches: boolean } }).matchMedia\n\treturn typeof matchMedia === 'function' &&\n\t\tmatchMedia.call(globalThis, '(prefers-color-scheme: dark)').matches\n\t\t? 'dark'\n\t\t: 'light'\n}\n\nexport class PaywallRenderer {\n\tprivate host: HTMLElement | null = null\n\tprivate keyHandler: ((event: KeyboardEvent) => void) | null = null\n\n\tconstructor(private readonly callbacks: PaywallRendererCallbacks) {}\n\n\tisVisible(): boolean {\n\t\treturn this.host !== null\n\t}\n\n\t/** Returns the host element; its shadow root holds the rendered template. */\n\tshow(view: PaywallView): HTMLElement {\n\t\tthis.hide()\n\t\tconst doc = (globalThis as { document?: Document }).document\n\t\tif (!doc || typeof doc.createElement !== 'function' || !doc.body) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.PAYWALL_UNAVAILABLE,\n\t\t\t\t'The paywall needs a DOM; call showPaywall() from a popup, options page or content script',\n\t\t\t)\n\t\t}\n\t\tconst template = PAYWALL_TEMPLATES[view.mode]\n\t\tif (!template)\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, `Unknown paywall mode \"${view.mode}\"`)\n\n\t\tconst t = sdkStrings(view.locale)\n\t\tconst strings: PaywallStrings = { ...stringsFor(view.locale), ...view.strings }\n\t\tif (view.mock) {\n\t\t\tstrings.upgrade = t.simulatePurchase\n\t\t\tstrings.footer = t.mockNotice\n\t\t}\n\t\tconst host = doc.createElement('div')\n\t\thost.className = PAYWALL_HOST_CLASS\n\t\thost.setAttribute('data-theme', resolveThemeMode(view.theme))\n\t\t// The shadow tree inherits the host's language: screen readers and\n\t\t// hyphenation read the strings in the language they are written in.\n\t\thost.setAttribute('lang', sdkLocale(view.locale))\n\t\thost.setAttribute('dir', sdkDir(sdkLocale(view.locale)))\n\t\tconst root: ShadowRoot | HTMLElement =\n\t\t\ttypeof host.attachShadow === 'function' ? host.attachShadow({ mode: 'open' }) : host\n\t\troot.innerHTML =\n\t\t\t`<style>${PAYWALL_SHARED_CSS}${template.css}${themeCss(view.theme)}</style>` +\n\t\t\tsubstitute(template.html, buildContent(view, strings))\n\n\t\tthis.prune(root)\n\t\tconst waiver =\n\t\t\tview.offer && view.checkoutEnabled && view.withdrawalWaiver\n\t\t\t\t? withdrawalWaiverText(view.withdrawalWaiver.version, view.locale, waiverSellerName(view))\n\t\t\t\t: null\n\t\tconst waiverBox = waiver ? doc.createElement('input') : null\n\t\t// undefined: no waiver asked → onUpgrade(sku) exactly as before; null: not ticked yet.\n\t\tconst consent = (): UpgradeConsent | null | undefined => {\n\t\t\tif (!waiver) return undefined\n\t\t\treturn waiverBox?.checked ? { withdrawalWaiver: { version: waiver.version, accepted: true } } : null\n\t\t}\n\t\tthis.bind(root, view, doc, consent)\n\t\tconst sellerMount = root.querySelector(\n\t\t\t'[class*=\"-footer\"], .ep-minimal-actions, .ep-inline-content, .ep-fullscreen-content',\n\t\t)\n\t\tif (sellerMount) {\n\t\t\tconst details = sellerDetails(view.seller ?? null, t)\n\t\t\tdetails.style.cssText =\n\t\t\t\t'font-size:12px;line-height:1.5;margin-top:12px;text-align:left;white-space:normal'\n\t\t\t// In the modal, disclose the provider before the purchase action,\n\t\t\t// instead of below it in the scrollable footer.\n\t\t\tconst modalActions = root.querySelector('.ep-modal-actions')\n\t\t\tif (modalActions) modalActions.before(details)\n\t\t\telse sellerMount.append(details)\n\t\t}\n\t\tif (view.mock) {\n\t\t\tconst upgrade = root.querySelector(UPGRADE_SELECTOR)\n\t\t\tif (upgrade) {\n\t\t\t\tconst notice = doc.createElement('p')\n\t\t\t\tnotice.className = 'extenshi-payment-preview'\n\t\t\t\tnotice.textContent = t.mockNotice\n\t\t\t\tnotice.style.cssText = 'font-size:13px;line-height:1.5;margin:12px 0;white-space:normal'\n\t\t\t\tupgrade.before(notice)\n\t\t\t}\n\t\t}\n\t\tif (waiver && waiverBox) this.mountWaiver(root, doc, waiver.text, waiverBox)\n\t\tif (view.recoveryEnabled && this.callbacks.onRestore) {\n\t\t\tconst footer = root.querySelector(\n\t\t\t\t'[class*=\"-footer\"], .ep-minimal-actions, .ep-inline-content, .ep-fullscreen-content',\n\t\t\t)\n\t\t\tif (footer) {\n\t\t\t\tconst button = doc.createElement('button')\n\t\t\t\tbutton.type = 'button'\n\t\t\t\tbutton.textContent = strings.restorePurchase\n\t\t\t\tbutton.style.cssText =\n\t\t\t\t\t'display:block;margin:12px auto 0;background:none;border:0;color:inherit;font:inherit;text-decoration:underline;cursor:pointer'\n\t\t\t\tbutton.addEventListener('click', () => this.callbacks.onRestore?.())\n\t\t\t\tfooter.appendChild(button)\n\t\t\t}\n\t\t}\n\t\tconst mount = view.mode === 'inline' ? (view.container ?? doc.body) : doc.body\n\t\tmount.appendChild(host)\n\t\tthis.host = host\n\t\tthis.reveal(root, view.mode)\n\t\treturn host\n\t}\n\n\thide(): void {\n\t\tif (!this.host) return\n\t\tif (this.keyHandler) {\n\t\t\tthis.host.ownerDocument.removeEventListener('keydown', this.keyHandler)\n\t\t\tthis.keyHandler = null\n\t\t}\n\t\tthis.host.remove()\n\t\tthis.host = null\n\t}\n\n\tprivate prune(root: ParentNode): void {\n\t\tfor (const element of root.querySelectorAll(PRUNE_SELECTOR)) element.remove()\n\t\tfor (const mark of root.querySelectorAll(`[${EMPTY_SLOT_MARK}]`)) {\n\t\t\tconst slot = mark.parentElement?.closest(FEATURE_SLOT_SELECTOR) ?? mark.parentElement\n\t\t\t;(slot ?? mark).remove()\n\t\t}\n\t\t// A button whose label placeholder the contract does not fill (trial\n\t\t// CTAs on sidebar/fullscreen) would render as an empty pill; icon-only\n\t\t// buttons (close) keep their SVG and stay.\n\t\tfor (const button of root.querySelectorAll('button')) {\n\t\t\tif (!button.textContent?.trim() && !button.querySelector('svg')) button.remove()\n\t\t}\n\t}\n\n\t/**\n\t * Inserts the unticked waiver checkbox right before the first upgrade\n\t * button and keeps every upgrade button disabled until it is ticked.\n\t */\n\tprivate mountWaiver(root: ParentNode, doc: Document, text: string, input: HTMLInputElement): void {\n\t\tconst buttons = Array.from(root.querySelectorAll<HTMLElement>(UPGRADE_SELECTOR))\n\t\tconst first = buttons[0]\n\t\tif (!first) return\n\t\tconst label = doc.createElement('label')\n\t\tlabel.className = WITHDRAWAL_WAIVER_CLASS\n\t\tlabel.style.cssText =\n\t\t\t'display:flex;align-items:flex-start;gap:8px;margin:12px 0;font-size:13px;line-height:1.5;text-align:start;white-space:normal;color:inherit;cursor:pointer'\n\t\tinput.type = 'checkbox'\n\t\tinput.checked = false\n\t\tinput.style.cssText = 'flex:none;width:16px;height:16px;margin:2px 0 0;cursor:pointer'\n\t\tconst span = doc.createElement('span')\n\t\tspan.textContent = text\n\t\tlabel.append(input, span)\n\t\tfirst.before(label)\n\t\tconst sync = () => {\n\t\t\tfor (const button of buttons) {\n\t\t\t\tif (input.checked) {\n\t\t\t\t\tbutton.removeAttribute('disabled')\n\t\t\t\t\tbutton.removeAttribute('aria-disabled')\n\t\t\t\t} else {\n\t\t\t\t\tbutton.setAttribute('disabled', '')\n\t\t\t\t\tbutton.setAttribute('aria-disabled', 'true')\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tinput.addEventListener('change', sync)\n\t\tsync()\n\t}\n\n\tprivate bind(\n\t\troot: ParentNode,\n\t\tview: PaywallView,\n\t\tdoc: Document,\n\t\tconsent: () => UpgradeConsent | null | undefined,\n\t): void {\n\t\tfor (const element of root.querySelectorAll<HTMLElement>('[data-ep-action]')) {\n\t\t\tconst action = element.getAttribute('data-ep-action') ?? ''\n\t\t\tif (UPGRADE_ACTIONS.has(action)) {\n\t\t\t\tif (view.offer && view.checkoutEnabled) {\n\t\t\t\t\tconst sku = view.offer.sku\n\t\t\t\t\telement.addEventListener('click', (event) => {\n\t\t\t\t\t\tevent.preventDefault()\n\t\t\t\t\t\tconst given = consent()\n\t\t\t\t\t\t// Waiver shown but not ticked: a disabled button cannot be\n\t\t\t\t\t\t// clicked, but never start checkout without consent anyway.\n\t\t\t\t\t\tif (given === null) return\n\t\t\t\t\t\tif (given) this.callbacks.onUpgrade(sku, given)\n\t\t\t\t\t\telse this.callbacks.onUpgrade(sku)\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\telement.setAttribute('disabled', '')\n\t\t\t\t\telement.setAttribute('aria-disabled', 'true')\n\t\t\t\t}\n\t\t\t} else if (CLOSE_ACTIONS.has(action)) {\n\t\t\t\telement.addEventListener('click', (event) => {\n\t\t\t\t\tevent.preventDefault()\n\t\t\t\t\tthis.close()\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\telement.remove()\n\t\t\t}\n\t\t}\n\t\tconst backdropSelector = BACKDROP_SELECTOR[view.mode]\n\t\tif (backdropSelector) {\n\t\t\troot.querySelector(backdropSelector)?.addEventListener('click', (event) => {\n\t\t\t\tif (event.target === event.currentTarget) this.close()\n\t\t\t})\n\t\t}\n\t\tif (view.mode !== 'inline') {\n\t\t\tthis.keyHandler = (event) => {\n\t\t\t\tif (event.key === 'Escape') this.close()\n\t\t\t}\n\t\t\tdoc.addEventListener('keydown', this.keyHandler)\n\t\t}\n\t}\n\n\tprivate reveal(root: ParentNode, mode: PaywallMode): void {\n\t\tconst rootElement = root.querySelector<HTMLElement>(ROOT_SELECTOR[mode])\n\t\tif (rootElement && (mode === 'modal' || mode === 'fullscreen')) rootElement.style.display = 'flex'\n\t\tfor (const [selector, className] of VISIBLE_CLASSES[mode] ?? []) {\n\t\t\troot.querySelector(selector)?.classList.add(className)\n\t\t}\n\t\tfor (const item of root.querySelectorAll(FEATURE_ITEM_VISIBLE[0]))\n\t\t\titem.classList.add(FEATURE_ITEM_VISIBLE[1])\n\t}\n\n\tprivate close(): void {\n\t\tthis.hide()\n\t\tthis.callbacks.onClose()\n\t}\n}\n","/** Full SDK: everything in `ExtenshiPayLite` plus the offer and the paywall UI. */\n\nimport { ExtenshiPayLite } from './core/extenshi-pay.js'\nimport { isEntitled } from './payment/features.js'\nimport { BillingProfilePicker } from './paywall/billing-profile-picker.js'\nimport { LicensePanel } from './paywall/license-panel.js'\nimport { PaywallRenderer, type PaywallView } from './paywall/renderer.js'\nimport { stringsFor } from './paywall/strings.js'\nimport type { PayOfferDto, PayOfferResponse } from './types/contract.js'\nimport type { CustomerPortalOptions, RequireFeatureOptions, UpgradeConsent } from './types/entitlement.js'\nimport type { PaywallOptions } from './types/paywall.js'\n\ninterface PaywallSession {\n\toptions: PaywallOptions\n\tresolve: (unlocked: boolean) => void\n}\n\nfunction pickOffer(offer: PayOfferResponse | null, sku: string | undefined): PayOfferDto | null {\n\tif (!offer) return null\n\treturn offer.offers.find((candidate) => candidate.sku === sku) ?? offer.offers[0] ?? null\n}\n\nexport class ExtenshiPay extends ExtenshiPayLite {\n\tprivate disposed = false\n\tprivate licensePanel = new LicensePanel()\n\tprivate billingProfiles = new BillingProfilePicker()\n\tprivate paywall: PaywallRenderer | null = null\n\tprivate paywallSession: PaywallSession | null = null\n\n\toverride async openCustomerPortal(options: CustomerPortalOptions = {}): Promise<string | null> {\n\t\treturn super.openCustomerPortal({\n\t\t\t...options,\n\t\t\tselectAccount:\n\t\t\t\toptions.selectAccount ?? ((accounts) => this.billingProfiles.show(accounts, this.config.locale)),\n\t\t})\n\t}\n\n\toverride destroy(): void {\n\t\tthis.disposed = true\n\t\tthis.licensePanel.hide()\n\t\tthis.billingProfiles.hide()\n\t\tthis.hidePaywall()\n\t\tsuper.destroy()\n\t}\n\n\tasync showLicense(): Promise<void> {\n\t\t// An explicit status check should see refunds/cancellations immediately.\n\t\t// The entitlement manager still falls back to the verified cache offline.\n\t\tconst summary = await this.getLicenseSummary({ force: !this.config.mock })\n\t\tif (this.disposed) return\n\t\treturn this.licensePanel.show(\n\t\t\tsummary,\n\t\t\t{\n\t\t\t\trestore: async () => {\n\t\t\t\t\tawait this.restorePurchase()\n\t\t\t\t\treturn this.getLicenseSummary({ force: true })\n\t\t\t\t},\n\t\t\t\tmanage: () => this.openCustomerPortal(),\n\t\t\t},\n\t\t\tthis.config.locale,\n\t\t)\n\t}\n\n\tasync getOffer(options: { force?: boolean } = {}): Promise<PayOfferResponse> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\treturn await this.fetchOffer(options.force)\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/**\n\t * Renders the paywall and resolves `true` when a checkout started from it\n\t * completes, `false` when the user closes it. The offer is fetched via\n\t * `getOffer()`; if that fails the paywall still renders with checkout disabled.\n\t */\n\tasync showPaywall(options: PaywallOptions = {}): Promise<boolean> {\n\t\tawait this.initialize()\n\t\tlet offer: PayOfferResponse | null = null\n\t\ttry {\n\t\t\toffer = await this.fetchOffer()\n\t\t} catch (error) {\n\t\t\tthis.reportError(error)\n\t\t}\n\t\tconst selected = pickOffer(offer, options.sku)\n\t\tconst defaults = stringsFor(this.config.locale)\n\t\tconst view: PaywallView = {\n\t\t\tmode: options.mode ?? 'modal',\n\t\t\ttitle: options.title ?? selected?.title ?? defaults.title,\n\t\t\tdescription: options.description ?? selected?.description ?? defaults.description,\n\t\t\tfeatures: options.features ?? selected?.features ?? [],\n\t\t\tfreeFeatures: options.freeFeatures ?? [],\n\t\t\tbrandName: offer?.projectName ?? '',\n\t\t\toffer: selected,\n\t\t\tcheckoutEnabled: offer?.checkoutEnabled === true && selected !== null && offer.seller !== null,\n\t\t\tmock: this.config.mock,\n\t\t\trecoveryEnabled: offer?.recoveryEnabled === true,\n\t\t\tseller: offer?.seller ?? null,\n\t\t\twithdrawalWaiver: offer?.withdrawalWaiver ?? null,\n\t\t\tlocale: this.config.locale,\n\t\t\ttheme: { ...this.config.theme, ...options.theme },\n\t\t\tstrings: options.strings ?? {},\n\t\t\tcontainer: options.container,\n\t\t}\n\t\tthis.hidePaywall()\n\t\treturn new Promise<boolean>((resolve) => {\n\t\t\tthis.paywallSession = { options, resolve }\n\t\t\ttry {\n\t\t\t\tthis.renderer().show(view)\n\t\t\t} catch (error) {\n\t\t\t\tthis.paywallSession = null\n\t\t\t\tthis.reportError(error)\n\t\t\t\tresolve(false)\n\t\t\t}\n\t\t})\n\t}\n\n\thidePaywall(): void {\n\t\tthis.paywall?.hide()\n\t\tthis.settlePaywall(false)\n\t}\n\n\tisPaywallVisible(): boolean {\n\t\treturn this.paywall?.isVisible() === true\n\t}\n\n\tprotected override async onFeatureLocked(\n\t\t_feature: string,\n\t\toptions: RequireFeatureOptions,\n\t): Promise<boolean> {\n\t\tif (options.showPaywall === false) return false\n\t\tif ((await this.getEntitlement()).requiresOnlineCheck) {\n\t\t\tawait this.showLicense()\n\t\t\treturn false\n\t\t}\n\t\treturn this.showPaywall(options.paywall ?? {})\n\t}\n\n\tprivate renderer(): PaywallRenderer {\n\t\tif (!this.paywall) {\n\t\t\tthis.paywall = new PaywallRenderer({\n\t\t\t\tonUpgrade: (sku, consent) => void this.handleUpgrade(sku, consent),\n\t\t\t\tonClose: () => this.settlePaywall(false),\n\t\t\t\tonRestore: () => void this.handleRestore(),\n\t\t\t})\n\t\t}\n\t\treturn this.paywall\n\t}\n\n\tprivate async handleRestore(): Promise<void> {\n\t\ttry {\n\t\t\tconst result = await this.restorePurchase()\n\t\t\tif (result.state === 'complete' && isEntitled(result.entitlement)) {\n\t\t\t\tthis.paywall?.hide()\n\t\t\t\tthis.settlePaywall(true)\n\t\t\t}\n\t\t} catch {\n\t\t\t/* Reported through the error event; leave the paywall open for retry. */\n\t\t}\n\t}\n\n\tprivate async handleUpgrade(sku: string, consent?: UpgradeConsent): Promise<void> {\n\t\tif (consent) this.paywallSession?.options.onUpgrade?.(sku, consent)\n\t\telse this.paywallSession?.options.onUpgrade?.(sku)\n\t\ttry {\n\t\t\tconst result = await this.openCheckout(\n\t\t\t\tsku,\n\t\t\t\tconsent?.withdrawalWaiver ? { withdrawalWaiver: consent.withdrawalWaiver } : {},\n\t\t\t)\n\t\t\tif (result.state === 'complete') {\n\t\t\t\tthis.paywall?.hide()\n\t\t\t\tthis.settlePaywall(true)\n\t\t\t}\n\t\t} catch {\n\t\t\t// Reported through the `error` event by openCheckout(); the paywall stays open for a retry.\n\t\t}\n\t}\n\n\tprivate settlePaywall(unlocked: boolean): void {\n\t\tconst session = this.paywallSession\n\t\tif (!session) return\n\t\tthis.paywallSession = null\n\t\tif (!unlocked) session.options.onClose?.()\n\t\tsession.resolve(unlocked)\n\t}\n}\n"],"names":["PAY_CONTRACT_VERSION","PAY_GATEWAYS","PAY_PUBLISHABLE_KEY_PREFIX","PAY_PUBLISHABLE_KEY_HEX_LENGTH","PUBLISHABLE_KEY_RE","RegExp","isPayPublishableKey","value","test","PAY_OFFER_KINDS","PAY_OFFER_INTERVALS","PAY_CURRENCIES","PAY_SKU_RE","PAY_ENTITLEMENT_STATUSES","PAY_WITHDRAWAL_WAIVER_VERSION","PAY_END_USER_REF_RE","PAY_ERRORS","SELLER_NOT_CONNECTED","SELLER_NOT_ACTIVE","AGREEMENT_REQUIRED","OFFER_NOT_FOUND","OFFER_LIMIT","PRICE_TOO_LOW","GATEWAY_UNAVAILABLE","RATE_LIMITED","INVALID_KEY","WITHDRAWAL_WAIVER_REQUIRED","canonicalJson","JSON","stringify","Array","isArray","map","item","join","Object","entries","filter","v","undefined","sort","a","b","k","ERROR_CODES","INVALID_CONFIG","INVALID_REQUEST","NETWORK_ERROR","TIMEOUT","VERIFICATION_UNAVAILABLE","INVALID_RESPONSE","CHECKOUT_UNAVAILABLE","PAYWALL_UNAVAILABLE","UNKNOWN","ExtenshiPayError","Error","constructor","code","message","options","super","this","name","retryAfterSec","httpStatus","cause","from","error","fallback","String","END_USER_REF_STORAGE_KEY","mintEndUserRef","cryptoApi","globalThis","crypto","randomUUID","bytes","getRandomValues","Uint8Array","hex","toString","padStart","slice","async","getOrCreateEndUserRef","storage","existing","get","ref","set","MockTransport","data","sessions","Map","entitlements","offers","projectName","checkoutEnabled","claimAfterPolls","withdrawalWaiver","version","call","procedure","_kind","input","offerResponse","createCheckout","sku","consent","accepted","mockConsent","claim","sessionId","endUserRef","publishableKey","envelope","url","length","setEntitlements","items","cancelSession","session","state","expireSession","provider","entitlementPublicKey","some","offer","polls","expiresAt","Date","now","toISOString","grant","entitlement","find","o","kind","interval","title","status","features","payload","issuedAt","signature","alg","PayApi","transport","createRestoreSession","claimChallenge","locale","claimRestoreSession","claimSecret","getOffer","claimSession","getEntitlement","getPortalUrl","customerId","ORDER","silent","warn","info","debug","Logger","level","prefix","configure","logLevel","args","enabled","console","logger","TRPC_PATH","RETRYABLE","Set","CAUSE_TO_CODE","trpcErrorToPayError","trpcCode","causeCode","match","exec","Number","parseRetryAfter","mapped","sleep","ms","Promise","resolve","setTimeout","HttpTransport","apiUrl","replace","timeoutMs","retries","fetchImpl","init","fetch","base","encodeURIComponent","attempts","lastError","attempt","request","err","has","controller","AbortController","timer","abort","response","method","headers","body","signal","credentials","aborted","clearTimeout","json","ok","result","CHECKOUT_POLL_INTERVAL_MS","CHECKOUT_TIMEOUT_MS","openInNewTab","g","tabs","chrome","browser","create","then","open","CheckoutManager","active","pendingKey","isActive","getEndUserRef","api","pending","emit","openUrl","poll","resumePending","raw","expires","parse","isFinite","remove","settle","pollIntervalMs","deadline","sleeper","wake","interruptibleSleep","stopFocus","onFocus","disposers","addEventListener","removeEventListener","push","doc","document","onVisible","visibilityState","windows","onFocusChanged","addListener","onWindow","windowId","removeListener","dispose","onFocusRegained","delay","errorBackoff","Math","min","onComplete","LIVE_STATUSES","isLive","applyLocalExpiry","collectFeatures","feature","add","isEntitled","requiresOnlineCheck","hasFeature","includes","checkFeatures","EMPTY_ENTITLEMENT","freeze","verified","fetchedAt","source","offlineUntil","base64ToBytes","base64","binary","atob","i","charCodeAt","verifyEntitlementSignature","publicKeyBase64","subtle","key","importKey","TextEncoder","encode","verify","MIN_REFRESH_INTERVAL_MS","MAX_REFRESH_BACKOFF_MS","MAX_OFFLINE_AGE_MS","MAX_CLOCK_SKEW_MS","isEnvelope","env","EntitlementManager","held","inflight","refreshGeneration","deadlineTimer","refreshIntervalMs","backoffMs","autoRefresh","online","force","notifyIfChanged","lastFingerprint","storageKey","load","record","fingerprint","snapshot","reverify","safePublicKey","verdict","discard","scheduleDeadline","getCached","isFresh","cacheTtlMs","refresh","onError","accept","finally","settleRefresh","catch","clear","startAutoRefresh","intervalMs","max","stopAutoRefresh","schedule","offlineDeadline","deadlines","NaN","remaining","delayMs","generation","getPublicKey","onChange","hasPaidAccess","extensionGlobals","areaCall","direct","withCallback","reject","runtime","ExtensionStorage","area","cb","LocalStorageAdapter","store","getItem","setItem","removeItem","MemoryStorage","delete","createStorage","local","localStorage","createRecoveryStorage","extension","RecoveryManager","stopped","stop","id","secret","hash","digest","challenge","created","done","once","DEFAULT_API_URL","DEFAULT_CACHE_TTL_MS","MAX_CACHE_TTL_MS","VERSION","WIRE_LOCALE_RE","wireLocale","parts","trim","split","Boolean","lang","toLowerCase","script","p","region","tag","toUpperCase","ENVIRONMENTS","LOG_LEVELS","THEME_MODES","LOCALE_RE","resolveConfig","errors","URL","protocol","isHttpUrl","environment","ui","i18n","getUILanguage","navigator","language","browserLocale","theme","mode","mock","mockData","EventEmitter","listeners","on","event","listener","off","fn","removeAll","SDK_LOCALES","SDK_STRINGS_EN","description","upgrade","cancel","dismiss","remindLater","continueFree","checkoutUnavailable","periodMonth","periodYear","periodOnce","footer","restorePurchase","featuresHeading","plansHeading","freePlanName","premiumPlanName","popularBadge","unlockHeading","simulatePurchase","mockNotice","sellerProvidedBy","sellerUnavailable","sellerSupport","sellerTerms","sellerRefunds","sellerRole","licenseTitle","licenseFallbackName","licenseNone","kindOneTime","kindLifetime","kindSubscription","kindLicense","statusLine","statusActive","statusGrace","statusExpired","statusNone","accessEnded","accessUntil","accessRecordedEnd","subscriptionLine","renewalCanceled","periodEnds","subActive","subTrialing","subPastDue","subCanceled","subUnpaid","subIncomplete","subIncompleteExpired","subPaused","licenseOffline","licenseCached","licenseFresh","actionFailed","manageBilling","noPortal","close","pickerTitle","pickerDescription","pickerFirstRecorded","pickerCancel","TRANSLATIONS","es","fr","de","it","ru","ja","ko","ar","sdkLocale","exact","l","sdkDir","sdkStrings","fill","values","whole","WITHDRAWAL_WAIVER_TEXTS","en","withdrawalWaiverText","serverVersion","seller","keys","text","ExtenshiPayLite","config","deps","emitter","endUserRefPromise","offerInflight","readyPromise","destroyed","reportError","checkout","recovery","recoveryStorage","onReady","initialize","doInitialize","afterReady","getCachedEntitlement","isPaid","requireFeature","onUnlock","unlocked","onFeatureLocked","onCancel","_feature","_options","getWithdrawalWaiver","fetchOffer","displayName","openCheckout","getLicenseSummary","recoveryEnabled","openCustomerPortal","accounts","selectAccount","onEntitlementChange","clearCache","destroy","sellerDetails","t","section","createElement","className","textContent","append","link","label","href","username","password","publicContactUrl","target","rel","style","marginRight","supportUrl","termsUrl","refundPolicyUrl","role","statusLabel","grace","expired","none","subscriptionStatusLabel","trialing","past_due","canceled","unpaid","incomplete","incomplete_expired","paused","LicensePanel","hide","show","summary","actions","host","setAttribute","root","attachShadow","dialog","content","feedback","render","replaceChildren","note","empty","article","heading","date","isNaN","getTime","expiry","when","toLocaleString","sub","subscriptions","row","cancelAtPeriodEnd","freshness","showModal","closed","preventDefault","buttons","action","run","button","type","forEach","disabled","updated","restore","manage","BillingProfilePicker","finish","account","detail","recorded","createdAt","toLocaleDateString","subscription","line","end","currentPeriodEnd","cancellation","formatPrice","amountMinor","currency","formatter","Intl","NumberFormat","formatToParts","part","amount","full","format","toFixed","periodLabel","strings","paywallStrings","DEFAULT_STRINGS","stringsFor","PAYWALL_SHARED_CSS","PAYWALL_TEMPLATES","modal","html","css","inline","sidebar","fullscreen","minimal","PAYWALL_MODES","PAYWALL_HOST_CLASS","UPGRADE_ACTIONS","UPGRADE_SELECTOR","WITHDRAWAL_WAIVER_CLASS","CLOSE_ACTIONS","ROOT_SELECTOR","BACKDROP_SELECTOR","VISIBLE_CLASSES","FEATURE_ITEM_VISIBLE","EMPTY_SLOT_MARK","FEATURE_KEY_RE","escapeHtml","substitute","_match","buildContent","view","price","brandName","period","pricingDescription","priceDescription","premiumDescription","upgradeButtonText","cancelButtonText","dismissButtonText","remindLaterText","continueButtonText","footerText","index","n","freeFeatures","CSS_VALUE_UNSAFE","themeCss","declarations","safe","primaryColor","color","fontFamily","borderRadius","radius","customCss","resolveThemeMode","matchMedia","matches","PaywallRenderer","callbacks","keyHandler","isVisible","template","innerHTML","prune","waiver","waiverSellerName","waiverBox","bind","checked","sellerMount","querySelector","details","cssText","modalActions","before","notice","mountWaiver","onRestore","appendChild","container","reveal","ownerDocument","element","querySelectorAll","mark","parentElement","closest","first","span","sync","removeAttribute","getAttribute","given","onUpgrade","backdropSelector","currentTarget","rootElement","display","selector","classList","onClose","ExtenshiPay","disposed","licensePanel","billingProfiles","paywall","paywallSession","hidePaywall","showLicense","showPaywall","selected","candidate","pickOffer","defaults","renderer","settlePaywall","isPaywallVisible","handleUpgrade","handleRestore"],"mappings":";;;;;;AAaO,MAAMA,EAAuB,EAEvBC,EAAe,CAAC,SAAU,SAAU,gBAUpCC,EAA6B,UAC7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