@extenshi/pay 0.9.0 → 0.12.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 (74) hide show
  1. package/README.md +138 -17
  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 +9 -4
  5. package/dist/api/pay-api.d.ts.map +1 -1
  6. package/dist/core/config.d.ts.map +1 -1
  7. package/dist/core/extenshi-pay.d.ts +60 -5
  8. package/dist/core/extenshi-pay.d.ts.map +1 -1
  9. package/dist/core/index.d.ts +3 -1
  10. package/dist/core/index.d.ts.map +1 -1
  11. package/dist/core/storage.d.ts +6 -0
  12. package/dist/core/storage.d.ts.map +1 -1
  13. package/dist/core.d.mts +271 -26
  14. package/dist/core.d.ts +271 -26
  15. package/dist/core.js +589 -49
  16. package/dist/core.js.map +1 -1
  17. package/dist/core.mjs +584 -50
  18. package/dist/core.mjs.map +1 -1
  19. package/dist/extenshi-pay-lite.js +577 -49
  20. package/dist/extenshi-pay-lite.js.map +1 -1
  21. package/dist/extenshi-pay-lite.min.js +3 -3
  22. package/dist/extenshi-pay-lite.min.js.map +1 -1
  23. package/dist/extenshi-pay-lite.mjs +577 -49
  24. package/dist/extenshi-pay-lite.mjs.map +1 -1
  25. package/dist/extenshi-pay.cjs.js +694 -61
  26. package/dist/extenshi-pay.cjs.js.map +1 -1
  27. package/dist/extenshi-pay.d.ts +11 -1
  28. package/dist/extenshi-pay.d.ts.map +1 -1
  29. package/dist/extenshi-pay.js +694 -61
  30. package/dist/extenshi-pay.js.map +1 -1
  31. package/dist/extenshi-pay.min.js +3 -3
  32. package/dist/extenshi-pay.min.js.map +1 -1
  33. package/dist/extenshi-pay.min.mjs +3 -3
  34. package/dist/extenshi-pay.min.mjs.map +1 -1
  35. package/dist/extenshi-pay.mjs +689 -62
  36. package/dist/extenshi-pay.mjs.map +1 -1
  37. package/dist/index.d.mts +288 -26
  38. package/dist/index.d.ts +288 -26
  39. package/dist/lite.d.mts +214 -13
  40. package/dist/lite.d.ts +214 -13
  41. package/dist/lite.d.ts.map +1 -1
  42. package/dist/payment/cloud-backup.d.ts +35 -0
  43. package/dist/payment/cloud-backup.d.ts.map +1 -0
  44. package/dist/payment/entitlement.d.ts +21 -5
  45. package/dist/payment/entitlement.d.ts.map +1 -1
  46. package/dist/payment/recovery.d.ts +4 -2
  47. package/dist/payment/recovery.d.ts.map +1 -1
  48. package/dist/payment/signature.d.ts +29 -3
  49. package/dist/payment/signature.d.ts.map +1 -1
  50. package/dist/payment/trial.d.ts +55 -0
  51. package/dist/payment/trial.d.ts.map +1 -0
  52. package/dist/paywall/i18n.d.ts +3 -0
  53. package/dist/paywall/i18n.d.ts.map +1 -1
  54. package/dist/paywall/renderer.d.ts +7 -0
  55. package/dist/paywall/renderer.d.ts.map +1 -1
  56. package/dist/paywall.d.mts +7 -0
  57. package/dist/paywall.d.ts +7 -0
  58. package/dist/paywall.js +54 -14
  59. package/dist/paywall.js.map +1 -1
  60. package/dist/paywall.mjs +54 -14
  61. package/dist/paywall.mjs.map +1 -1
  62. package/dist/types/config.d.ts +27 -1
  63. package/dist/types/config.d.ts.map +1 -1
  64. package/dist/types/contract.d.ts +36 -0
  65. package/dist/types/contract.d.ts.map +1 -1
  66. package/dist/types/entitlement.d.ts +39 -1
  67. package/dist/types/entitlement.d.ts.map +1 -1
  68. package/dist/types/events.d.ts +5 -1
  69. package/dist/types/events.d.ts.map +1 -1
  70. package/dist/types/paywall.d.ts +10 -0
  71. package/dist/types/paywall.d.ts.map +1 -1
  72. package/dist/version.d.ts +1 -1
  73. package/dist/version.d.ts.map +1 -1
  74. package/package.json +3 -2
@@ -1,8 +1,8 @@
1
1
  /*!
2
- * ExtenshiPay SDK v0.9.0
2
+ * ExtenshiPay SDK v0.12.0
3
3
  * (c) 2026 Extenshi.io
4
4
  * Released under the MIT License.
5
- * commit bd166bf9b687f60e965d03acec7a648b42226652 · built by `rollup -c`
5
+ * commit 7f4b4e98165b3c8eb11e100b3855fee1ade7aaab · built by `rollup -c`
6
6
  */
7
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ExtenshiPayLite={})}(this,function(e){"use strict";const t=new RegExp("^pk_ext_[0-9a-f]{32}$");const i="2026-10-v1",s=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,n="PAY_SELLER_NOT_CONNECTED",r="PAY_SELLER_NOT_ACTIVE",o="PAY_AGREEMENT_REQUIRED",a="PAY_OFFER_NOT_FOUND",l="PAY_GATEWAY_UNAVAILABLE",h="PAY_RATE_LIMITED",c="PAY_INVALID_KEY",u="PAY_WITHDRAWAL_WAIVER_REQUIRED";function d(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>d(e)).join(",")}]`;return`{${Object.entries(e).filter(([,e])=>void 0!==e).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${JSON.stringify(e)}:${d(t)}`).join(",")}}`}const f={INVALID_CONFIG:"INVALID_CONFIG",INVALID_REQUEST:"INVALID_REQUEST",NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT:"TIMEOUT",VERIFICATION_UNAVAILABLE:"VERIFICATION_UNAVAILABLE",INVALID_RESPONSE:"INVALID_RESPONSE",RATE_LIMITED:"RATE_LIMITED",INVALID_KEY:"INVALID_KEY",SELLER_NOT_ACTIVE:"SELLER_NOT_ACTIVE",OFFER_NOT_FOUND:"OFFER_NOT_FOUND",GATEWAY_UNAVAILABLE:"GATEWAY_UNAVAILABLE",CHECKOUT_UNAVAILABLE:"CHECKOUT_UNAVAILABLE",PAYWALL_UNAVAILABLE:"PAYWALL_UNAVAILABLE",WITHDRAWAL_WAIVER_REQUIRED:"WITHDRAWAL_WAIVER_REQUIRED",UNKNOWN:"UNKNOWN"};class p extends Error{constructor(e,t,i={}){super(t),this.name="ExtenshiPayError",this.code=e,this.retryAfterSec=i.retryAfterSec,this.httpStatus=i.httpStatus,this.cause=i.cause}static from(e,t=f.UNKNOWN){if(e instanceof p)return e;const i=e instanceof Error?e.message:String(e);return new p(t,i,{cause:e})}}const m="extenshi-pay:endUserRef";function w(){const e=globalThis.crypto;if(!e)throw new p(f.UNKNOWN,"Web Crypto is not available in this context");if("function"==typeof e.randomUUID)return e.randomUUID();const t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;const i=Array.from(t,e=>e.toString(16).padStart(2,"0")).join("");return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}class y{constructor(e={}){this.sessions=new Map,this.entitlements=[...e.entitlements??[]],this.offers=[...e.offers??[]],this.projectName=e.projectName??"Mock project",this.checkoutEnabled=e.checkoutEnabled??!0,this.claimAfterPolls=e.claimAfterPolls??1,this.withdrawalWaiver=void 0===e.withdrawalWaiver?{version:i}:e.withdrawalWaiver}async call(e,t,i){switch(e){case"pay.getOffer":return this.offerResponse();case"pay.createCheckout":return this.createCheckout(String(i.sku),function(e){const t=e;return t&&"string"==typeof t.version&&!0===t.accepted?{version:t.version,accepted:!0}:null}(i.withdrawalWaiver));case"pay.claimSession":return this.claim(String(i.sessionId),String(i.endUserRef),String(i.publishableKey));case"pay.getEntitlement":return this.envelope(String(i.endUserRef),String(i.publishableKey));case"pay.getPortalUrl":return{url:this.entitlements.length>0?"https://mock.extenshi.io/portal":null};default:throw new p(f.INVALID_REQUEST,`Unknown procedure ${e}`)}}setEntitlements(e){this.entitlements=[...e]}cancelSession(e){const t=this.sessions.get(e);t&&(t.state="canceled")}expireSession(e){const t=this.sessions.get(e);t&&(t.state="expired")}offerResponse(){return{v:1,projectName:this.projectName,provider:"stripe",checkoutEnabled:this.checkoutEnabled&&this.offers.length>0,offers:[...this.offers],entitlementPublicKey:null,withdrawalWaiver:this.withdrawalWaiver?{...this.withdrawalWaiver}:null}}createCheckout(e,t){if(!this.checkoutEnabled)throw new p(f.SELLER_NOT_ACTIVE,"Mock seller cannot take payments");if(!this.offers.some(t=>t.sku===e))throw new p(f.OFFER_NOT_FOUND,`Unknown mock offer ${e}`);const i=w();return this.sessions.set(i,{sku:e,polls:0,state:"open",withdrawalWaiver:t}),{url:`https://mock.extenshi.io/checkout/${i}`,sessionId:i,expiresAt:new Date(Date.now()+18e5).toISOString()}}claim(e,t,i){const s=this.sessions.get(e);if(!s)throw new p(f.CHECKOUT_UNAVAILABLE,"Unknown checkout session");if("canceled"===s.state)return{state:"canceled"};if("expired"===s.state)return{state:"expired"};if("open"===s.state){if(s.polls+=1,s.polls<=this.claimAfterPolls)return{state:"pending"};s.state="complete",this.grant(s.sku)}return{state:"complete",entitlement:this.envelope(t,i)}}grant(e){const t=this.offers.find(t=>t.sku===e),i="subscription"===t?.kind?new Date(Date.now()+864e5*("year"===t.interval?365:30)).toISOString():null;this.entitlements=[...this.entitlements.filter(t=>t.sku!==e),{sku:e,title:t?.title,kind:t?.kind,status:"active",expiresAt:i,features:t?.features??[]}]}envelope(e,t){return{payload:{v:1,publishableKey:t,endUserRef:e,entitlements:[...this.entitlements],issuedAt:(new Date).toISOString()},signature:null,alg:null}}}class g{constructor(e,t){this.transport=e,this.publishableKey=t}createRestoreSession(e,t){return this.transport.call("pay.createRestoreSession","mutation",{publishableKey:this.publishableKey,claimChallenge:e,...t?{locale:t}:{}})}claimRestoreSession(e,t){return this.transport.call("pay.claimRestoreSession","mutation",{publishableKey:this.publishableKey,sessionId:e,claimSecret:t})}getOffer(e){return this.transport.call("pay.getOffer","query",{publishableKey:this.publishableKey,locale:e??void 0})}createCheckout(e,t,i,s){return this.transport.call("pay.createCheckout","mutation",{publishableKey:this.publishableKey,sku:e,endUserRef:t,locale:i??void 0,...!0===s?.accepted&&"string"==typeof s.version?{withdrawalWaiver:{version:s.version,accepted:!0}}:{}})}claimSession(e,t){return this.transport.call("pay.claimSession","query",{publishableKey:this.publishableKey,sessionId:e,endUserRef:t})}getEntitlement(e){return this.transport.call("pay.getEntitlement","query",{publishableKey:this.publishableKey,endUserRef:e})}getPortalUrl(e,t,i){return this.transport.call("pay.getPortalUrl","mutation",{publishableKey:this.publishableKey,endUserRef:e,...t?{customerId:t}:{},...i?{locale:i}:{}})}}const E={silent:0,error:1,warn:2,info:3,debug:4};const A=new class{constructor(){this.level="warn",this.prefix="[ExtenshiPay]"}configure(e){e.logLevel&&(this.level=e.logLevel),e.debug&&(this.level="debug")}error(e,...t){this.enabled("error")&&console.error(this.prefix,e,...t)}warn(e,...t){this.enabled("warn")&&console.warn(this.prefix,e,...t)}info(e,...t){this.enabled("info")&&console.info(this.prefix,e,...t)}debug(e,...t){this.enabled("debug")&&console.debug(this.prefix,e,...t)}enabled(e){return E[e]<=E[this.level]}},b=new Set([f.NETWORK_ERROR,f.TIMEOUT,f.GATEWAY_UNAVAILABLE]),I={[h]:f.RATE_LIMITED,[c]:f.INVALID_KEY,[n]:f.SELLER_NOT_ACTIVE,[r]:f.SELLER_NOT_ACTIVE,[o]:f.SELLER_NOT_ACTIVE,[a]:f.OFFER_NOT_FOUND,[l]:f.GATEWAY_UNAVAILABLE,[u]:f.WITHDRAWAL_WAIVER_REQUIRED};function v(e,t){const i=e.message??"Request failed",s=e.data?.code??"",n=e.data?.cause?.code,r=e.data?.cause?.retryAfterSec??function(e){const t=/retry in (\d+)s/i.exec(e);return t?Number(t[1]):void 0}(i),o={retryAfterSec:r,httpStatus:e.data?.httpStatus??t},a=n?I[n]:void 0;if(a)return new p(a,i,o);switch(s){case"TOO_MANY_REQUESTS":return new p(f.RATE_LIMITED,i,o);case"NOT_FOUND":return/publishable key/i.test(i)?new p(f.INVALID_KEY,i,o):/session/i.test(i)?new p(f.CHECKOUT_UNAVAILABLE,i,o):new p(f.OFFER_NOT_FOUND,i,o);case"PRECONDITION_FAILED":return/withdrawal/i.test(i)?new p(f.WITHDRAWAL_WAIVER_REQUIRED,i,o):new p(f.SELLER_NOT_ACTIVE,i,o);case"BAD_REQUEST":return new p(f.INVALID_REQUEST,i,o);case"INTERNAL_SERVER_ERROR":return new p(f.GATEWAY_UNAVAILABLE,i,o);default:return new p(f.UNKNOWN,i,o)}}function R(e){return new Promise(t=>setTimeout(t,e))}class N{constructor(e){this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??1e4,this.retries=e.retries??1,this.fetchImpl=e.fetchImpl??((e,t)=>fetch(e,t))}async call(e,t,i){const s=`${this.apiUrl}/api/trpc/${e}`,n="query"===t?`${s}?input=${encodeURIComponent(JSON.stringify(i))}`:s,r="query"===t?this.retries+1:1;let o=null;for(let s=0;s<r;s++)try{return await this.request(n,t,i)}catch(t){const i=p.from(t);if(!b.has(i.code)||s===r-1)throw i;o=i,A.debug(`${e} failed (${i.code}), retrying`),await R(500*2**s)}throw o??new p(f.UNKNOWN,`${e} failed`)}async request(e,t,i){const s="function"==typeof AbortController?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeoutMs):null;let r;try{r=await this.fetchImpl(e,{method:"query"===t?"GET":"POST",headers:"mutation"===t?{"Content-Type":"application/json"}:void 0,body:"mutation"===t?JSON.stringify(i):void 0,signal:s?.signal,credentials:"omit"})}catch(e){if(s?.signal.aborted)throw new p(f.TIMEOUT,`Request timed out after ${this.timeoutMs}ms`);throw new p(f.NETWORK_ERROR,"Network request failed",{cause:e})}finally{null!==n&&clearTimeout(n)}let o=null;try{o=await r.json()}catch{o=null}if(o?.error)throw v(o.error,r.status);if(!r.ok){const e=r.status>=500?f.GATEWAY_UNAVAILABLE:f.INVALID_RESPONSE;throw new p(e,`HTTP ${r.status}`,{httpStatus:r.status})}if(!o?.result||!("data"in o.result))throw new p(f.INVALID_RESPONSE,"Malformed response from the payment backend");return o.result.data}}const T=6e5;async function L(e){const t=globalThis,i=t.chrome?.tabs??t.browser?.tabs;if(i&&"function"==typeof i.create){const t=i.create({url:e});return void(t&&"function"==typeof t.then&&await t)}if("function"!=typeof t.open)throw new p(f.CHECKOUT_UNAVAILABLE,"Cannot open a checkout tab from this context");t.open(e,"_blank","noopener,noreferrer")}class U{constructor(e){this.options=e,this.active=null,this.now=e.now??(()=>Date.now())}get pendingKey(){return`extenshi-pay:${this.options.publishableKey}:pendingCheckout`}isActive(){return null!==this.active}async open(e,t={}){if(this.active)throw new p(f.CHECKOUT_UNAVAILABLE,"A checkout is already in progress");const i=await this.options.getEndUserRef(),s=await this.options.api.createCheckout(e,i,t.locale??this.options.locale,t.withdrawalWaiver);this.active=s.sessionId;try{const n={sessionId:s.sessionId,sku:e,expiresAt:s.expiresAt};return await this.options.storage.set(this.pendingKey,n),this.options.emit("checkout:started",{sku:e,sessionId:s.sessionId,url:s.url}),await(t.openUrl??this.options.openUrl??L)(s.url),await this.poll(e,s.sessionId,i,t)}finally{this.active=null}}async resumePending(){const e=await this.options.storage.get(this.pendingKey);if(!e||"string"!=typeof e.sessionId||"string"!=typeof e.sku)return null;const t=Date.parse(e.expiresAt??"");if(!Number.isFinite(t)||t+36e5<this.now())return await this.options.storage.remove(this.pendingKey),null;const i=await this.options.getEndUserRef();let s;try{s=await this.options.api.claimSession(e.sessionId,i)}catch(e){return A.debug("could not resume pending checkout",e),null}return this.settle(s,e.sku,e.sessionId)}async poll(e,t,i,s){const n=s.pollIntervalMs??2e3,r=this.now()+(s.timeoutMs??T),o=function(){let e=null;return{sleep:t=>new Promise(i=>{const s=setTimeout(()=>{e=null,i()},t);e=()=>{clearTimeout(s),e=null,i()}}),wake(){e?.()}}}(),a=function(e){const t=globalThis,i=[];"function"==typeof t.addEventListener&&"function"==typeof t.removeEventListener&&(t.addEventListener("focus",e),i.push(()=>t.removeEventListener?.("focus",e)));const s=t.document;if(s&&"function"==typeof s.addEventListener){const t=()=>{"visible"===s.visibilityState&&e()};s.addEventListener("visibilitychange",t),i.push(()=>s.removeEventListener("visibilitychange",t))}const n=t.chrome?.windows?.onFocusChanged;if(n&&"function"==typeof n.addListener){const t=t=>{-1!==t&&e()};n.addListener(t),i.push(()=>n.removeListener(t))}return()=>{for(const e of i)e()}}(()=>o.wake());let l=n,h=0;try{for(;;){if(await o.sleep(l),this.now()>=r)return{state:"timeout",sku:e,sessionId:t};let s;try{s=await this.options.api.claimSession(t,i)}catch(e){const t=p.from(e);if(t.code===f.RATE_LIMITED)l=1e3*(t.retryAfterSec??5);else{if(t.code!==f.NETWORK_ERROR&&t.code!==f.TIMEOUT&&t.code!==f.GATEWAY_UNAVAILABLE)throw await this.options.storage.remove(this.pendingKey),t;h=Math.min(h?2*h:n,3e4),l=h}continue}h=0,l=n;const a=await this.settle(s,e,t);if(a)return a}}finally{a()}}async settle(e,t,i){switch(e.state){case"pending":return null;case"complete":{const s=await this.options.onComplete(e.entitlement);return await this.options.storage.remove(this.pendingKey),this.options.emit("checkout:completed",{sku:t,sessionId:i,entitlement:s}),{state:"complete",sku:t,sessionId:i,entitlement:s}}case"canceled":return await this.options.storage.remove(this.pendingKey),this.options.emit("checkout:canceled",{sku:t,sessionId:i}),{state:"canceled",sku:t,sessionId:i};case"expired":return await this.options.storage.remove(this.pendingKey),this.options.emit("checkout:expired",{sku:t,sessionId:i}),{state:"expired",sku:t,sessionId:i};default:throw new p(f.INVALID_RESPONSE,"Unknown checkout claim state")}}}var _=Object.freeze({__proto__:null,CHECKOUT_POLL_INTERVAL_MS:2e3,CHECKOUT_TIMEOUT_MS:T,CheckoutManager:U,openInNewTab:L});const k=new Set(["active","grace"]);function O(e){return k.has(e.status)}function S(e){const t=new Set;for(const i of e)if(O(i))for(const e of i.features)t.add(e);return[...t]}function D(e,t){return e.features.includes(t)}const K=Object.freeze({items:[],features:[],verified:!1,issuedAt:null,fetchedAt:null,source:"none",requiresOnlineCheck:!1,offlineUntil:null});function C(e){const t=atob(e),i=new Uint8Array(t.length);for(let e=0;e<t.length;e++)i[e]=t.charCodeAt(e);return i}async function P(e,t){if(!e.signature||"ed25519"!==e.alg)return"invalid";if(!t)return"unverified";const i=globalThis.crypto?.subtle;if(!i)return"unverified";let s;try{s=await i.importKey("raw",C(t),{name:"Ed25519"},!1,["verify"])}catch{return"unverified"}try{const t=(new TextEncoder).encode(d(e.payload));return await i.verify("Ed25519",s,C(e.signature),t)?"valid":"invalid"}catch{return"invalid"}}Object.freeze(K.items),Object.freeze(K.features);const V=9e5,x=1728e5,M=3e5;function W(e){if(!e||"object"!=typeof e)return!1;const t=e;return!!t.payload&&"object"==typeof t.payload&&"string"==typeof t.payload.endUserRef&&Array.isArray(t.payload.entitlements)&&"string"==typeof t.payload.issuedAt}class F{constructor(e){this.options=e,this.held=null,this.inflight=null,this.timer=null,this.refreshGeneration=0,this.deadlineTimer=null,this.refreshIntervalMs=V,this.backoffMs=0,this.autoRefresh=!1,this.online=()=>{this.get({force:!0}).then(()=>this.notifyIfChanged())},this.lastFingerprint=d({items:[],requiresOnlineCheck:!1}),this.now=e.now??(()=>Date.now()),this.source=e.source??"network"}get storageKey(){return`extenshi-pay:${this.options.publishableKey}:entitlement${"mock"===this.source?":mock":""}`}async load(){const e=await this.options.storage.get(this.storageKey);if(!e||1!==e.v||!W(e.envelope)||"number"!=typeof e.fetchedAt||!Number.isFinite(e.fetchedAt))return null;const t=await this.options.getEndUserRef();return e.envelope.payload.endUserRef!==t||"mock"!==this.source&&e.envelope.payload.publishableKey!==this.options.publishableKey?(await this.options.storage.remove(this.storageKey),null):(this.held={envelope:JSON.parse(JSON.stringify(e.envelope)),fetchedAt:e.fetchedAt,verified:!1,source:"mock"===this.source?"mock":"cache"},this.lastFingerprint=this.fingerprint(),this.snapshot())}async reverify(){if(!this.held)return;if("mock"===this.source)return;const e=this.held,t=await this.safePublicKey(),i=await P(e.envelope,t);if(e===this.held){if("invalid"===i)throw A.warn("cached entitlement failed signature verification; discarding"),await this.discard(),new p(f.INVALID_RESPONSE,"Cached entitlement signature is invalid");if(e.verified="valid"===i,!e.verified)throw new p(f.VERIFICATION_UNAVAILABLE,"Entitlement verification requires a trusted key and Ed25519 WebCrypto support");this.scheduleDeadline()}}getCached(){return this.held?this.snapshot():null}isFresh(){return null!==this.held&&("mock"===this.source||this.held.verified&&!this.snapshot().requiresOnlineCheck)&&this.now()>=this.held.fetchedAt&&this.now()-this.held.fetchedAt<Math.min(this.options.cacheTtlMs,x)}async get(e={}){if(!e.force&&this.isFresh())return this.snapshot();try{return await this.refresh()}catch(e){const t=p.from(e);return this.options.onError?.(t),this.held?(A.debug("serving cached entitlement after refresh failure",t.code),this.snapshot()):K}}refresh(){return this.inflight||(this.inflight=(async()=>{const e=await this.options.getEndUserRef(),t=await this.options.api.getEntitlement(e);return this.accept(t,this.source)})().finally(()=>{this.inflight=null})),this.inflight}async accept(e,t=this.source){if(!W(e))throw new p(f.INVALID_RESPONSE,"Malformed entitlement envelope");if(e=JSON.parse(JSON.stringify(e)),"mock"!==this.source&&e.payload.publishableKey!==this.options.publishableKey)throw new p(f.INVALID_RESPONSE,"Entitlement belongs to a different application or lacks a signed application scope");const i=await this.options.getEndUserRef();if(e.payload.endUserRef!==i)throw new p(f.INVALID_RESPONSE,"Entitlement issued for a different endUserRef");const s="mock"===this.source?"unverified":await P(e,await this.safePublicKey());if("invalid"===s)throw await this.discard(),new p(f.INVALID_RESPONSE,"Entitlement signature is invalid");if("valid"!==s&&"mock"!==this.source)throw new p(f.VERIFICATION_UNAVAILABLE,"Entitlement verification requires a trusted key and Ed25519 WebCrypto support");const n=this.now(),r=Date.parse(e.payload.issuedAt);if("mock"!==this.source&&(!Number.isFinite(r)||r>n+M))throw new p(f.INVALID_RESPONSE,"Entitlement issuedAt is invalid or in the future");this.held={envelope:e,fetchedAt:n,verified:"valid"===s,source:t};const o={v:1,envelope:e,fetchedAt:n};return await this.options.storage.set(this.storageKey,JSON.parse(JSON.stringify(o))),this.backoffMs=0,this.scheduleDeadline(),this.notifyIfChanged(),this.snapshot()}async settleRefresh(){await(this.inflight?.catch(()=>{}))}async clear(){this.held=null,this.scheduleDeadline(),this.lastFingerprint=null,await this.options.storage.remove(this.storageKey)}startAutoRefresh(e=Math.max(this.options.cacheTtlMs,V)){this.stopAutoRefresh(),this.autoRefresh=!0,globalThis.addEventListener?.("online",this.online),this.refreshIntervalMs=Math.max(e,V),this.schedule(this.refreshIntervalMs),this.scheduleDeadline()}stopAutoRefresh(){this.autoRefresh=!1,globalThis.removeEventListener?.("online",this.online),this.refreshGeneration++,null!==this.deadlineTimer&&clearTimeout(this.deadlineTimer),this.deadlineTimer=null,null!==this.timer&&clearTimeout(this.timer),this.timer=null}scheduleDeadline(){if(null!==this.deadlineTimer&&clearTimeout(this.deadlineTimer),this.deadlineTimer=null,!this.autoRefresh||!this.held||!this.held.verified||"mock"===this.source)return;const e=this.now();if(e>=this.offlineDeadline())return;const t=[this.offlineDeadline(),...this.held.envelope.payload.entitlements.filter(e=>"active"===e.status||"grace"===e.status).map(e=>e.expiresAt?Date.parse(e.expiresAt):NaN)],i=Math.min(...t.filter(t=>t>e))-e;!Number.isFinite(i)||i<=0||(this.deadlineTimer=setTimeout(()=>{this.deadlineTimer=null,this.notifyIfChanged(),this.scheduleDeadline()},i))}schedule(e){const t=this.refreshGeneration;this.timer=setTimeout(async()=>{this.timer=null;try{if(await this.refresh(),t!==this.refreshGeneration)return;this.schedule(this.refreshIntervalMs)}catch(e){if(t!==this.refreshGeneration)return;this.options.onError?.(p.from(e)),this.backoffMs=Math.min(this.backoffMs?2*this.backoffMs:this.refreshIntervalMs,216e5),this.schedule(this.backoffMs)}},e)}async safePublicKey(){try{return await this.options.getPublicKey()}catch(e){return A.debug("public key unavailable; entitlement stays unverified",e),null}}async discard(){this.held=null,this.scheduleDeadline(),await this.options.storage.remove(this.storageKey),this.notifyIfChanged()}fingerprint(){const e=this.snapshot();return d({items:e.items,requiresOnlineCheck:e.requiresOnlineCheck})}notifyIfChanged(){const e=this.fingerprint();e!==this.lastFingerprint&&(this.lastFingerprint=e,this.options.onChange?.(this.snapshot()))}offlineDeadline(){return this.held?Math.min(this.held.fetchedAt,Date.parse(this.held.envelope.payload.issuedAt))+x:NaN}snapshot(){if(!this.held)return K;if("mock"!==this.source&&!this.held.verified)return{...K,requiresOnlineCheck:!0,source:this.held.source};const e=function(e,t=Date.now()){return e.map(e=>{if(!O(e)||!e.expiresAt)return e;const i=Date.parse(e.expiresAt);return Number.isFinite(i)&&i<=t?{...e,status:"expired"}:e})}(JSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)),this.now()),t=S(e).length>0||e.some(e=>"active"===e.status||"grace"===e.status),i="mock"!==this.source&&t?this.offlineDeadline():null,s=null!==i&&(!Number.isFinite(i)||this.now()>=i||this.now()<this.held.fetchedAt||this.now()+M<Date.parse(this.held.envelope.payload.issuedAt));return{items:e,features:s?[]:S(e),requiresOnlineCheck:s,offlineUntil:i,verified:this.held.verified,issuedAt:this.held.envelope.payload.issuedAt,fetchedAt:this.held.fetchedAt,source:this.held.source}}}function $(){return globalThis}function j(e,t){const i=e();return(s=i)&&"function"==typeof s.then?i:new Promise((e,i)=>{t(t=>{const s=$().chrome?.runtime?.lastError;s?i(new Error(s.message??"storage error")):e(t)})});var s}class z{constructor(e){this.area=e}async get(e){const t=await j(()=>this.area.get(e),t=>this.area.get(e,t));return t?.[e]}async set(e,t){await j(()=>this.area.set({[e]:t}),i=>this.area.set({[e]:t},i))}async remove(e){await j(()=>this.area.remove(e),t=>this.area.remove(e,t))}}class q{constructor(e){this.store=e}async get(e){const t=this.store.getItem(e);if(null!==t)try{return JSON.parse(t)}catch{return}}async set(e,t){this.store.setItem(e,JSON.stringify(t))}async remove(e){this.store.removeItem(e)}}class B{constructor(){this.map=new Map}async get(e){return this.map.get(e)}async set(e,t){this.map.set(e,t)}async remove(e){this.map.delete(e)}}function Y(){const e=globalThis,t=e.chrome?.tabs?e.chrome:e.browser?.tabs?e.browser:null;return t?.storage?.session?new z(t.storage.session):new B}class Q{constructor(e){this.options=e,this.active=!1,this.stopped=!1,this.wake=null}get pendingKey(){return`extenshi-pay:${this.options.publishableKey}:pendingRestore`}isActive(){return this.active}stop(){this.stopped=!0,this.wake?.()}async open(e={}){if(this.active)throw new p(f.INVALID_REQUEST,"Recovery is already in progress");this.active=!0,this.stopped=!1;try{const t=globalThis;if((t.chrome?.runtime?.id||t.browser?.runtime?.id)&&!t.chrome?.tabs&&!t.browser?.tabs)throw new p(f.INVALID_REQUEST,"Start recovery in an extension page or background context");const i=globalThis.crypto;if(!i?.subtle)throw new p(f.INVALID_REQUEST,"Secure recovery is unavailable in this browser");const s=Array.from(i.getRandomValues(new Uint8Array(32)),e=>e.toString(16).padStart(2,"0")).join(""),n=await i.subtle.digest("SHA-256",(new TextEncoder).encode(s)),r=Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,"0")).join(""),o=await this.options.api.createRestoreSession(r,this.options.locale);if(!Number.isFinite(Date.parse(o.expiresAt)))throw new p(f.INVALID_RESPONSE,"Invalid recovery expiry");const a={sessionId:o.sessionId,expiresAt:o.expiresAt,claimSecret:s};return await this.options.storage.set(this.pendingKey,a),await(e.openUrl??this.options.openUrl??L)(o.url),await this.poll(a,e)}finally{this.active=!1}}async resumePending(){if(this.active||this.stopped)return null;const e=await this.options.storage.get(this.pendingKey);if(!e||this.active||this.stopped)return null;if("string"!=typeof e.sessionId||"string"!=typeof e.claimSecret||!/^[a-f0-9]{64}$/.test(e.claimSecret)||!Number.isFinite(Date.parse(e.expiresAt??"")))return await this.options.storage.remove(this.pendingKey),null;this.active=!0,this.stopped=!1;try{return await this.poll(e,{})}finally{this.active=!1}}async poll(e,t){const i=this.options.now??Date.now,s=Date.parse(e.expiresAt),n=Math.min(s,i()+(t.timeoutMs??6e5));let r=0;for(;!this.stopped&&!t.signal?.aborted&&i()<n&&(r&&await new Promise(e=>{const s=()=>{clearTimeout(o),t.signal?.removeEventListener("abort",s),this.wake=null,e()},o=setTimeout(s,Math.min(r,Math.max(0,n-i())));this.wake=s,t.signal?.addEventListener("abort",s,{once:!0})}),!(this.stopped||t.signal?.aborted||i()>=n));)try{const i=await this.options.api.claimRestoreSession(e.sessionId,e.claimSecret);if(this.stopped||t.signal?.aborted)break;if("complete"===i.state){const e=await this.options.onComplete(i.endUserRef,i.entitlement);return await this.options.storage.remove(this.pendingKey),{state:"complete",entitlement:e}}if("pending"!==i.state)throw new p(f.INVALID_RESPONSE,"Invalid recovery response");r=Math.max(100,t.pollIntervalMs??2e3)}catch(e){const t=p.from(e);if(![f.NETWORK_ERROR,f.TIMEOUT,f.GATEWAY_UNAVAILABLE,f.RATE_LIMITED].some(e=>e===t.code))throw t;r=Math.max(2e3,1e3*(t.retryAfterSec??5))}return i()>=s&&await this.options.storage.remove(this.pendingKey),{state:this.stopped||t.signal?.aborted?"canceled":i()>=s?"expired":"timeout"}}}const G=/^[a-z]{2}(-[A-Za-z]{2,4})?$/;function H(e){if("string"!=typeof e)return null;const t=e.trim().replace(/_/g,"-").split("-").filter(Boolean),i=t[0]?.toLowerCase();if(!i||!/^[a-z]{2}$/.test(i))return null;const s=t.slice(1).find(e=>/^[A-Za-z]{4}$/.test(e))?.toLowerCase(),n=t.slice(1).find(e=>/^[A-Za-z]{2}$/.test(e))??("zh"===i&&"hant"===s?"TW":void 0),r=n?`${i}-${n.toUpperCase()}`:i;return G.test(r)?r:i}const J=["en","es","pt-BR","fr","de","it","ru","ja","ko","zh-CN","ar"];function Z(e){const t=H(e);if(!t)return"en";const i=J.find(e=>e.toLowerCase()===t.toLowerCase());if(i)return i;const[s,n]=t.split("-");return"pt"===s?"pt-BR":"zh"===s?n&&["TW","HK","MO"].includes(n)?"en":"zh-CN":J.find(e=>e===s)??"en"}const X={[i]:{en:"I agree that {seller} starts supplying the digital content immediately, and I acknowledge that I lose my right of withdrawal once supply has begun.",es:"Acepto que {seller} comience a suministrar el contenido digital de inmediato y reconozco que pierdo mi derecho de desistimiento una vez iniciado el suministro.","pt-BR":"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.",fr:"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.",de:"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.",it:"Accetto che {seller} inizi immediatamente la fornitura del contenuto digitale e riconosco di perdere il mio diritto di recesso una volta iniziata la fornitura.",ru:"Я соглашаюсь с тем, что {seller} немедленно начнёт предоставление цифрового контента, и подтверждаю, что утрачиваю право на отказ от договора с момента начала предоставления.",ja:"{seller}がデジタルコンテンツの提供を直ちに開始することに同意し、提供の開始後は撤回権を失うことを了承します。",ko:"{seller}의 디지털 콘텐츠 제공이 즉시 시작되는 것에 동의하며, 제공이 시작되면 청약철회권을 상실한다는 점을 확인합니다.","zh-CN":"我同意 {seller} 立即开始提供数字内容,并确认一旦开始提供,我将失去撤回权。",ar:"أوافق على أن يبدأ {seller} فورًا في تقديم المحتوى الرقمي، وأُقرّ بأنني أفقد حقي في العدول عن العقد بمجرد بدء التقديم."}};const ee="0.9.0",te=6048e5,ie=new Set(["production","sandbox","development"]),se=new Set(["silent","error","warn","info","debug"]),ne=new Set(["light","dark","auto"]),re=/^[a-z]{2}(-[A-Za-z]{2,4})?$/;function oe(e){const i=[];if(!e||"object"!=typeof e)throw new p(f.INVALID_CONFIG,"ExtenshiPay config must be an object");var s;"string"==typeof(s=e.publishableKey)&&t.test(s)||i.push("publishableKey must look like pk_ext_<32 hex characters>");const n=(e.apiUrl??"https://bff.extenshi.io").replace(/\/+$/,"");(function(e){try{const t=new URL(e);return"https:"===t.protocol||"http:"===t.protocol}catch{return!1}})(n)||i.push("apiUrl must be an http(s) URL");const r=e.entitlementPublicKey??null;null===r||/^[A-Za-z0-9+/]{43}=$/.test(r)||i.push("entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key");const o=e.environment??"production";ie.has(o)||i.push("environment must be production, sandbox or development");const a=e.logLevel??"warn";se.has(a)||i.push("logLevel must be silent, error, warn, info or debug");const l=e.cacheTtlMs??36e5;(!Number.isFinite(l)||l<0||l>te)&&i.push("cacheTtlMs must be between 0 and 604800000");const h=void 0===e.locale?function(){const e=globalThis;try{const t=e.chrome?.i18n?.getUILanguage?.()??e.browser?.i18n?.getUILanguage?.();if(t)return H(t)}catch{}return H(e.navigator?.language)}():e.locale;null===h||re.test(h)||i.push("locale must be a BCP-47 tag such as en or de-DE");const c=e.theme??{};if(void 0===c.mode||ne.has(c.mode)||i.push("theme.mode must be light, dark or auto"),!e.mock||void 0===e.mockData||"object"==typeof e.mockData&&null!==e.mockData||i.push("mockData must be an object"),i.length>0)throw new p(f.INVALID_CONFIG,`Invalid ExtenshiPay config: ${i.join("; ")}`);return{publishableKey:e.publishableKey,apiUrl:n,entitlementPublicKey:r,environment:o,debug:!0===e.debug,logLevel:a,cacheTtlMs:l,locale:h,mock:!0===e.mock,mockData:e.mock?e.mockData??{}:null,theme:c}}class ae{constructor(){this.listeners=new Map}on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>this.off(e,t)}once(e,t){const i=this.on(e,e=>{i(),t(e)});return i}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){const i=this.listeners.get(e);if(i)for(const s of[...i]){const i=s;try{i(t)}catch(t){A.error(`listener for "${String(e)}" threw`,t)}}}removeAll(){this.listeners.clear()}}class le{constructor(e,t={}){this.emitter=new ae,this.endUserRef=null,this.endUserRefPromise=null,this.offer=null,this.offerInflight=null,this.readyPromise=null,this.destroyed=!1,this.config=oe(e),A.configure({logLevel:this.config.logLevel,debug:this.config.debug}),this.now=t.now??(()=>Date.now()),this.storage=t.storage??function(){const e=$(),t=e.chrome?.storage?.local??e.browser?.storage?.local;if(t)return new z(t);try{const e=globalThis.localStorage;if(e&&"function"==typeof e.getItem)return new q(e)}catch{}return new B}();const i=t.transport??(this.config.mock?new y(this.config.mockData??{}):new N({apiUrl:this.config.apiUrl,fetchImpl:t.fetch}));this.api=new g(i,this.config.publishableKey),this.entitlements=new F({api:this.api,storage:this.storage,publishableKey:this.config.publishableKey,cacheTtlMs:this.config.cacheTtlMs,source:this.config.mock?"mock":"network",getEndUserRef:()=>this.getEndUserRef(),getPublicKey:()=>this.getPublicKey(),onChange:e=>this.emitter.emit("entitlement:changed",e),onError:e=>this.reportError(e),now:this.now}),this.checkout=new U({api:this.api,storage:this.storage,publishableKey:this.config.publishableKey,locale:this.config.locale,getEndUserRef:()=>this.getEndUserRef(),onComplete:e=>this.entitlements.accept(e),emit:(e,t)=>this.emitter.emit(e,t),openUrl:t.openUrl??(this.config.mock?e=>A.info("mock checkout (no tab opened)",e):void 0),now:this.now}),this.recovery=new Q({api:this.api,locale:this.config.locale,publishableKey:this.config.publishableKey,storage:t.recoveryStorage??Y(),openUrl:t.openUrl,now:this.now,onComplete:async(e,t)=>{if(!s.test(e)||t?.payload?.endUserRef!==e||t.payload.publishableKey!==this.config.publishableKey||!Number.isFinite(Date.parse(t.payload.issuedAt))||Date.parse(t.payload.issuedAt)>this.now()+M||"valid"!==await P(t,await this.getPublicKey()))throw new p(f.INVALID_RESPONSE,"Recovery requires a verified entitlement for this installation");this.entitlements.stopAutoRefresh();try{if(await this.entitlements.settleRefresh(),this.destroyed)throw new p(f.INVALID_REQUEST,"Recovery was stopped");return await this.storage.set(m,e),this.endUserRef=e,this.endUserRefPromise=null,await this.entitlements.clear(),await this.entitlements.accept(t)}finally{this.destroyed||this.entitlements.startAutoRefresh()}}}),e.onError&&this.emitter.on("error",e.onError),e.onReady&&this.emitter.once("ready",e.onReady)}get version(){return ee}initialize(){return this.readyPromise||(this.readyPromise=this.doInitialize()),this.readyPromise}async doInitialize(){const e=await this.getEndUserRef();await this.entitlements.load();try{await this.entitlements.reverify()}catch(e){this.reportError(e)}this.entitlements.isFresh()||await this.entitlements.get({force:!0}),this.emitter.emit("ready",{endUserRef:e}),this.afterReady()}async afterReady(){if(!this.destroyed){try{if(await this.checkout.resumePending(),this.destroyed)return;await this.recovery.resumePending()}catch(e){this.reportError(e)}this.destroyed||this.entitlements.startAutoRefresh()}}getEndUserRef(){return this.endUserRef?Promise.resolve(this.endUserRef):(this.endUserRefPromise||(this.endUserRefPromise=async function(e){const t=await e.get(m);if("string"==typeof t&&s.test(t))return t;const i=w();return await e.set(m,i),i}(this.storage).then(e=>(this.endUserRef=e,e))),this.endUserRefPromise)}getCachedEntitlement(){return this.entitlements.getCached()}async getEntitlement(e={}){return await this.initialize(),this.entitlements.get(e)}async isPaid(e){return function(e,t){return!e.requiresOnlineCheck&&e.items.some(e=>O(e)&&(void 0===t||e.sku===t))}(await this.getEntitlement(),e)}async hasFeature(e){return D(await this.getEntitlement(),e)}async checkFeatures(e){return function(e,t){const i={};for(const s of t)i[s]=D(e,s);return i}(await this.getEntitlement(),e)}async requireFeature(e,t={}){if(await this.hasFeature(e))return t.onUnlock?.(),!0;const i=await this.onFeatureLocked(e,t);return i?t.onUnlock?.():t.onCancel?.(),i}async onFeatureLocked(e,t){return!1}async getWithdrawalWaiver(){await this.initialize();try{const e=await this.fetchOffer();if(!e.withdrawalWaiver)return null;const t=e.seller?.displayName?.trim()||e.projectName;return function(e,t,s){const n=Object.keys(X).includes(e)?e:i;return{version:n,text:(r=X[n][Z(t)],o={seller:s},r.replace(/\{([a-z]+)\}/g,(e,t)=>o[t]??e))};var r,o}(e.withdrawalWaiver.version,this.config.locale,t)}catch(e){throw this.reportError(e)}}async openCheckout(e,t={}){await this.initialize();try{if(this.recovery.isActive())throw new p(f.INVALID_REQUEST,"Recovery is in progress");const i=await this.fetchOffer().catch(()=>null);if(i?.withdrawalWaiver&&!0!==t.withdrawalWaiver?.accepted)throw new p(f.WITHDRAWAL_WAIVER_REQUIRED,"This offer needs the buyer to accept the withdrawal waiver; pass options.withdrawalWaiver");return await this.checkout.open(e,t)}catch(e){throw this.reportError(e)}}async restorePurchase(e={}){await this.initialize();try{if(this.checkout.isActive())throw new p(f.INVALID_REQUEST,"Checkout is in progress");return await this.recovery.open(e)}catch(e){throw this.reportError(e)}}async getLicenseSummary(e={}){await this.initialize();let t=null;try{t=await this.fetchOffer(e.force)}catch{}return{projectName:t?.projectName??null,seller:t?.seller??null,entitlement:await this.getEntitlement(e),recoveryEnabled:!0===t?.recoveryEnabled}}async openCustomerPortal(e={}){await this.initialize();try{const t=await this.getEndUserRef();let i=await this.api.getPortalUrl(t,void 0,this.config.locale);if(this.destroyed)return null;if(i.accounts?.length){if(!e.selectAccount)throw new p(f.INVALID_REQUEST,"Choose a billing profile using selectAccount");const s=await e.selectAccount(i.accounts);if(null===s||this.destroyed)return null;if(!i.accounts.some(e=>e.id===s))throw new p(f.INVALID_REQUEST,"Invalid billing profile");if(t!==await this.getEndUserRef())throw new p(f.INVALID_REQUEST,"Installation changed; open the portal again");i=await this.api.getPortalUrl(t,s,this.config.locale)}if(this.destroyed)return null;const{url:s}=i;return s&&await(e.openUrl??(await Promise.resolve().then(function(){return _})).openInNewTab)(s),s}catch(e){throw this.reportError(e)}}on(e,t){return this.emitter.on(e,t)}once(e,t){return this.emitter.once(e,t)}off(e,t){this.emitter.off(e,t)}onEntitlementChange(e){return this.emitter.on("entitlement:changed",e)}async clearCache(){this.offer=null,await this.entitlements.clear()}destroy(){this.destroyed=!0,this.recovery.stop(),this.entitlements.stopAutoRefresh(),this.emitter.removeAll()}fetchOffer(e=!1){return!e&&this.offer&&this.now()-this.offer.fetchedAt<3e5?Promise.resolve(this.offer.value):(this.offerInflight||(this.offerInflight=this.api.getOffer(this.config.locale).then(e=>(this.offer={value:e,fetchedAt:this.now()},e)).finally(()=>{this.offerInflight=null})),this.offerInflight)}async getPublicKey(){return this.config.entitlementPublicKey??(await this.fetchOffer()).entitlementPublicKey}reportError(e){const t=p.from(e);return A.warn(`${t.code}: ${t.message}`),this.emitter.emit("error",t),t}}le.version=ee,e.ERROR_CODES=f,e.ExtenshiPay=le,e.ExtenshiPayError=p,e.ExtenshiPayLite=le,e.MockTransport=y,e.PAY_WITHDRAWAL_WAIVER_VERSION=i,e.VERSION=ee,e.default=le,Object.defineProperty(e,"__esModule",{value:!0})});
7
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ExtenshiPayLite={})}(this,function(e){"use strict";const t=new RegExp("^pk_ext_[0-9a-f]{32}$");const i="@regional-free",s="2026-10-v1",n=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,r="PAY_SELLER_NOT_CONNECTED",o="PAY_SELLER_NOT_ACTIVE",a="PAY_AGREEMENT_REQUIRED",l="PAY_OFFER_NOT_FOUND",h="PAY_GATEWAY_UNAVAILABLE",c="PAY_RATE_LIMITED",u="PAY_INVALID_KEY",d="PAY_WITHDRAWAL_WAIVER_REQUIRED";function f(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(e=>f(e)).join(",")}]`;return`{${Object.entries(e).filter(([,e])=>void 0!==e).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${JSON.stringify(e)}:${f(t)}`).join(",")}}`}const p=/^est_[A-Za-z0-9_-]{43}$/,m={INVALID_CONFIG:"INVALID_CONFIG",INVALID_REQUEST:"INVALID_REQUEST",NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT:"TIMEOUT",VERIFICATION_UNAVAILABLE:"VERIFICATION_UNAVAILABLE",INVALID_RESPONSE:"INVALID_RESPONSE",RATE_LIMITED:"RATE_LIMITED",INVALID_KEY:"INVALID_KEY",SELLER_NOT_ACTIVE:"SELLER_NOT_ACTIVE",OFFER_NOT_FOUND:"OFFER_NOT_FOUND",GATEWAY_UNAVAILABLE:"GATEWAY_UNAVAILABLE",CHECKOUT_UNAVAILABLE:"CHECKOUT_UNAVAILABLE",PAYWALL_UNAVAILABLE:"PAYWALL_UNAVAILABLE",WITHDRAWAL_WAIVER_REQUIRED:"WITHDRAWAL_WAIVER_REQUIRED",UNKNOWN:"UNKNOWN"};class y extends Error{constructor(e,t,i={}){super(t),this.name="ExtenshiPayError",this.code=e,this.retryAfterSec=i.retryAfterSec,this.httpStatus=i.httpStatus,this.cause=i.cause}static from(e,t=m.UNKNOWN){if(e instanceof y)return e;const i=e instanceof Error?e.message:String(e);return new y(t,i,{cause:e})}}const g="extenshi-pay:endUserRef";function w(){const e=globalThis.crypto;if(!e)throw new y(m.UNKNOWN,"Web Crypto is not available in this context");if("function"==typeof e.randomUUID)return e.randomUUID();const t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;const i=Array.from(t,e=>e.toString(16).padStart(2,"0")).join("");return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}const E=864e5;class A{constructor(e={}){this.sessions=new Map,this.entitlements=[...e.entitlements??[]],this.offers=[...e.offers??[]],this.projectName=e.projectName??"Mock project",this.checkoutEnabled=e.checkoutEnabled??!0,this.claimAfterPolls=e.claimAfterPolls??1,this.withdrawalWaiver=void 0===e.withdrawalWaiver?{version:s}:e.withdrawalWaiver,this.seller=e.seller,this.trial=null,e.trial&&this.setTrial(e.trial.days,e.trial.startedAt)}async call(e,t,i){switch(e){case"pay.getOffer":return this.offerResponse();case"pay.createCheckout":return this.createCheckout(String(i.sku),function(e){const t=e;return t&&"string"==typeof t.version&&!0===t.accepted?{version:t.version,accepted:!0}:null}(i.withdrawalWaiver));case"pay.claimSession":return this.claim(String(i.sessionId),String(i.endUserRef),String(i.publishableKey));case"pay.getEntitlement":return this.envelope(String(i.endUserRef),String(i.publishableKey));case"pay.getPortalUrl":return{url:this.entitlements.length>0?"https://mock.extenshi.io/portal":null};default:throw new y(m.INVALID_REQUEST,`Unknown procedure ${e}`)}}setEntitlements(e){this.entitlements=[...e]}setTrial(e,t=(new Date).toISOString()){const i=Date.parse(t);this.trial=null!==e&&Number.isFinite(i)?{startedAt:new Date(i).toISOString(),endsAt:new Date(i+e*E).toISOString()}:null}cancelSession(e){const t=this.sessions.get(e);t&&(t.state="canceled")}expireSession(e){const t=this.sessions.get(e);t&&(t.state="expired")}offerResponse(){return{v:1,projectName:this.projectName,provider:"stripe",checkoutEnabled:this.checkoutEnabled&&this.offers.length>0,offers:[...this.offers],entitlementPublicKey:null,withdrawalWaiver:this.withdrawalWaiver?{...this.withdrawalWaiver}:null,...void 0!==this.seller&&{seller:this.seller?{...this.seller}:null}}}createCheckout(e,t){if(!this.checkoutEnabled)throw new y(m.SELLER_NOT_ACTIVE,"Mock seller cannot take payments");if(!this.offers.some(t=>t.sku===e))throw new y(m.OFFER_NOT_FOUND,`Unknown mock offer ${e}`);const i=w();return this.sessions.set(i,{sku:e,polls:0,state:"open",withdrawalWaiver:t}),{url:`https://mock.extenshi.io/checkout/${i}`,sessionId:i,expiresAt:new Date(Date.now()+18e5).toISOString()}}claim(e,t,i){const s=this.sessions.get(e);if(!s)throw new y(m.CHECKOUT_UNAVAILABLE,"Unknown checkout session");if("canceled"===s.state)return{state:"canceled"};if("expired"===s.state)return{state:"expired"};if("open"===s.state){if(s.polls+=1,s.polls<=this.claimAfterPolls)return{state:"pending"};s.state="complete",this.grant(s.sku)}return{state:"complete",entitlement:this.envelope(t,i)}}grant(e){const t=this.offers.find(t=>t.sku===e),i="subscription"===t?.kind?new Date(Date.now()+("year"===t.interval?365:30)*E).toISOString():null;this.entitlements=[...this.entitlements.filter(t=>t.sku!==e),{sku:e,title:t?.title,kind:t?.kind,status:"active",expiresAt:i,features:t?.features??[]}]}envelope(e,t){return{payload:{v:1,publishableKey:t,endUserRef:e,entitlements:[...this.entitlements],issuedAt:(new Date).toISOString(),...this.trial?{trial:{...this.trial}}:{}},signature:null,alg:null}}}class b{constructor(e,t){this.transport=e,this.publishableKey=t}createRestoreSession(e,t,i){return this.transport.call("pay.createRestoreSession","mutation",{publishableKey:this.publishableKey,claimChallenge:e,...t?{locale:t}:{},..."storage"===i?{purpose:i}:{}})}claimRestoreSession(e,t){return this.transport.call("pay.claimRestoreSession","mutation",{publishableKey:this.publishableKey,sessionId:e,claimSecret:t})}getOffer(e){return this.transport.call("pay.getOffer","query",{publishableKey:this.publishableKey,locale:e??void 0})}createCheckout(e,t,i,s){return this.transport.call("pay.createCheckout","mutation",{publishableKey:this.publishableKey,sku:e,endUserRef:t,locale:i??void 0,...!0===s?.accepted&&"string"==typeof s.version?{withdrawalWaiver:{version:s.version,accepted:!0}}:{}})}claimSession(e,t){return this.transport.call("pay.claimSession","query",{publishableKey:this.publishableKey,sessionId:e,endUserRef:t})}getEntitlement(e,t){return this.transport.call("pay.getEntitlement","query",{publishableKey:this.publishableKey,endUserRef:e,...t?{trialStartedHint:t}:{}})}getPortalUrl(e,t,i){return this.transport.call("pay.getPortalUrl","mutation",{publishableKey:this.publishableKey,endUserRef:e,...t?{customerId:t}:{},...i?{locale:i}:{}})}}const v={silent:0,error:1,warn:2,info:3,debug:4};const I=new class{constructor(){this.level="warn",this.prefix="[ExtenshiPay]"}configure(e){e.logLevel&&(this.level=e.logLevel),e.debug&&(this.level="debug")}error(e,...t){this.enabled("error")&&console.error(this.prefix,e,...t)}warn(e,...t){this.enabled("warn")&&console.warn(this.prefix,e,...t)}info(e,...t){this.enabled("info")&&console.info(this.prefix,e,...t)}debug(e,...t){this.enabled("debug")&&console.debug(this.prefix,e,...t)}enabled(e){return v[e]<=v[this.level]}},k=new Set([m.NETWORK_ERROR,m.TIMEOUT,m.GATEWAY_UNAVAILABLE]),R={[c]:m.RATE_LIMITED,[u]:m.INVALID_KEY,[r]:m.SELLER_NOT_ACTIVE,[o]:m.SELLER_NOT_ACTIVE,[a]:m.SELLER_NOT_ACTIVE,[l]:m.OFFER_NOT_FOUND,[h]:m.GATEWAY_UNAVAILABLE,[d]:m.WITHDRAWAL_WAIVER_REQUIRED};function T(e,t){const i=e.message??"Request failed",s=e.data?.code??"",n=e.data?.cause?.code,r=e.data?.cause?.retryAfterSec??function(e){const t=/retry in (\d+)s/i.exec(e);return t?Number(t[1]):void 0}(i),o={retryAfterSec:r,httpStatus:e.data?.httpStatus??t},a=n?R[n]:void 0;if(a)return new y(a,i,o);switch(s){case"TOO_MANY_REQUESTS":return new y(m.RATE_LIMITED,i,o);case"NOT_FOUND":return/publishable key/i.test(i)?new y(m.INVALID_KEY,i,o):/session/i.test(i)?new y(m.CHECKOUT_UNAVAILABLE,i,o):new y(m.OFFER_NOT_FOUND,i,o);case"PRECONDITION_FAILED":return/withdrawal/i.test(i)?new y(m.WITHDRAWAL_WAIVER_REQUIRED,i,o):new y(m.SELLER_NOT_ACTIVE,i,o);case"BAD_REQUEST":return new y(m.INVALID_REQUEST,i,o);case"INTERNAL_SERVER_ERROR":return new y(m.GATEWAY_UNAVAILABLE,i,o);default:return new y(m.UNKNOWN,i,o)}}function S(e){return new Promise(t=>setTimeout(t,e))}class N{constructor(e){this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??1e4,this.retries=e.retries??1,this.fetchImpl=e.fetchImpl??((e,t)=>fetch(e,t))}async call(e,t,i){const s=`${this.apiUrl}/api/trpc/${e}`,n="query"===t?`${s}?input=${encodeURIComponent(JSON.stringify(i))}`:s,r="query"===t?this.retries+1:1;let o=null;for(let s=0;s<r;s++)try{return await this.request(n,t,i)}catch(t){const i=y.from(t);if(!k.has(i.code)||s===r-1)throw i;o=i,I.debug(`${e} failed (${i.code}), retrying`),await S(500*2**s)}throw o??new y(m.UNKNOWN,`${e} failed`)}async request(e,t,i){const s="function"==typeof AbortController?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeoutMs):null;let r;try{r=await this.fetchImpl(e,{method:"query"===t?"GET":"POST",headers:"mutation"===t?{"Content-Type":"application/json"}:void 0,body:"mutation"===t?JSON.stringify(i):void 0,signal:s?.signal,credentials:"omit"})}catch(e){if(s?.signal.aborted)throw new y(m.TIMEOUT,`Request timed out after ${this.timeoutMs}ms`);throw new y(m.NETWORK_ERROR,"Network request failed",{cause:e})}finally{null!==n&&clearTimeout(n)}let o=null;try{o=await r.json()}catch{o=null}if(o?.error)throw T(o.error,r.status);if(!r.ok){const e=r.status>=500?m.GATEWAY_UNAVAILABLE:m.INVALID_RESPONSE;throw new y(e,`HTTP ${r.status}`,{httpStatus:r.status})}if(!o?.result||!("data"in o.result))throw new y(m.INVALID_RESPONSE,"Malformed response from the payment backend");return o.result.data}}const U=6e5;async function L(e){const t=globalThis,i=t.chrome?.tabs??t.browser?.tabs;if(i&&"function"==typeof i.create){const t=i.create({url:e});return void(t&&"function"==typeof t.then&&await t)}if("function"!=typeof t.open)throw new y(m.CHECKOUT_UNAVAILABLE,"Cannot open a checkout tab from this context");t.open(e,"_blank","noopener,noreferrer")}class _{constructor(e){this.options=e,this.active=null,this.now=e.now??(()=>Date.now())}get pendingKey(){return`extenshi-pay:${this.options.publishableKey}:pendingCheckout`}isActive(){return null!==this.active}async open(e,t={}){if(this.active)throw new y(m.CHECKOUT_UNAVAILABLE,"A checkout is already in progress");const i=await this.options.getEndUserRef(),s=await this.options.api.createCheckout(e,i,t.locale??this.options.locale,t.withdrawalWaiver);this.active=s.sessionId;try{const n={sessionId:s.sessionId,sku:e,expiresAt:s.expiresAt};return await this.options.storage.set(this.pendingKey,n),this.options.emit("checkout:started",{sku:e,sessionId:s.sessionId,url:s.url}),await(t.openUrl??this.options.openUrl??L)(s.url),await this.poll(e,s.sessionId,i,t)}finally{this.active=null}}async resumePending(){const e=await this.options.storage.get(this.pendingKey);if(!e||"string"!=typeof e.sessionId||"string"!=typeof e.sku)return null;const t=Date.parse(e.expiresAt??"");if(!Number.isFinite(t)||t+36e5<this.now())return await this.options.storage.remove(this.pendingKey),null;const i=await this.options.getEndUserRef();let s;try{s=await this.options.api.claimSession(e.sessionId,i)}catch(e){return I.debug("could not resume pending checkout",e),null}return this.settle(s,e.sku,e.sessionId)}async poll(e,t,i,s){const n=s.pollIntervalMs??2e3,r=this.now()+(s.timeoutMs??U),o=function(){let e=null;return{sleep:t=>new Promise(i=>{const s=setTimeout(()=>{e=null,i()},t);e=()=>{clearTimeout(s),e=null,i()}}),wake(){e?.()}}}(),a=function(e){const t=globalThis,i=[];"function"==typeof t.addEventListener&&"function"==typeof t.removeEventListener&&(t.addEventListener("focus",e),i.push(()=>t.removeEventListener?.("focus",e)));const s=t.document;if(s&&"function"==typeof s.addEventListener){const t=()=>{"visible"===s.visibilityState&&e()};s.addEventListener("visibilitychange",t),i.push(()=>s.removeEventListener("visibilitychange",t))}const n=t.chrome?.windows?.onFocusChanged;if(n&&"function"==typeof n.addListener){const t=t=>{-1!==t&&e()};n.addListener(t),i.push(()=>n.removeListener(t))}return()=>{for(const e of i)e()}}(()=>o.wake());let l=n,h=0;try{for(;;){if(await o.sleep(l),this.now()>=r)return{state:"timeout",sku:e,sessionId:t};let s;try{s=await this.options.api.claimSession(t,i)}catch(e){const t=y.from(e);if(t.code===m.RATE_LIMITED)l=1e3*(t.retryAfterSec??5);else{if(t.code!==m.NETWORK_ERROR&&t.code!==m.TIMEOUT&&t.code!==m.GATEWAY_UNAVAILABLE)throw await this.options.storage.remove(this.pendingKey),t;h=Math.min(h?2*h:n,3e4),l=h}continue}h=0,l=n;const a=await this.settle(s,e,t);if(a)return a}}finally{a()}}async settle(e,t,i){switch(e.state){case"pending":return null;case"complete":{const s=await this.options.onComplete(e.entitlement);return await this.options.storage.remove(this.pendingKey),this.options.emit("checkout:completed",{sku:t,sessionId:i,entitlement:s}),{state:"complete",sku:t,sessionId:i,entitlement:s}}case"canceled":return await this.options.storage.remove(this.pendingKey),this.options.emit("checkout:canceled",{sku:t,sessionId:i}),{state:"canceled",sku:t,sessionId:i};case"expired":return await this.options.storage.remove(this.pendingKey),this.options.emit("checkout:expired",{sku:t,sessionId:i}),{state:"expired",sku:t,sessionId:i};default:throw new y(m.INVALID_RESPONSE,"Unknown checkout claim state")}}}var O=Object.freeze({__proto__:null,CHECKOUT_POLL_INTERVAL_MS:2e3,CHECKOUT_TIMEOUT_MS:U,CheckoutManager:_,openInNewTab:L});class D{constructor(e){this.options=e,this.fetchImpl=e.fetch??((e,t)=>fetch(e,t))}get storageKey(){return`extenshi-pay:${this.options.publishableKey}:storageToken`}async accept(e){if(e&&"object"==typeof e)try{if("granted"===e.state){if("string"!=typeof e.token||!p.test(e.token))return;return await this.options.storage.set(this.storageKey,e.token),"on"}if("unavailable"===e.state)return await this.options.storage.remove(this.storageKey),"LICENSE_REQUIRED"===e.reason?"license_required":"no_consent"}catch{I.warn("cloud backup state could not be saved")}}async token(){this.assertTrustedContext();const e=await this.options.storage.get(this.storageKey);return"string"==typeof e&&p.test(e)?e:null}async disable(){const e=await this.token();if(e){if(!this.options.mock){const t=await this.request("/v1/storage/grant",e);401!==t&&this.throwUnlessOk(t)}await this.options.storage.remove(this.storageKey)}}async delete(){const e=await this.token();if(!e)throw new y(m.INVALID_REQUEST,"Cloud backup is off on this installation; turn it on to delete the cloud copy");if(!this.options.mock){const t=await this.request("/v1/storage/data",e);if(401===t)throw await this.options.storage.remove(this.storageKey),new y(m.INVALID_REQUEST,"Cloud backup is off on the server; turn it on again to delete the cloud copy",{httpStatus:401});this.throwUnlessOk(t)}await this.options.storage.remove(this.storageKey)}assertTrustedContext(){if(function(){const e=globalThis;return!(!e.chrome?.runtime?.id&&!e.browser?.runtime?.id||e.chrome?.tabs||e.browser?.tabs)}())throw new y(m.INVALID_REQUEST,"Use cloud backup from an extension page or background context")}throwUnlessOk(e){if(!(e>=200&&e<300)){if(429===e)throw new y(m.RATE_LIMITED,"Too many requests",{httpStatus:e});if(e>=500)throw new y(m.GATEWAY_UNAVAILABLE,`HTTP ${e}`,{httpStatus:e});throw new y(m.INVALID_RESPONSE,`HTTP ${e}`,{httpStatus:e})}}async request(e,t){const i="function"==typeof AbortController?new AbortController:null,s=i?setTimeout(()=>i.abort(),1e4):null;try{return(await this.fetchImpl(`${this.options.apiUrl}${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`},credentials:"omit",signal:i?.signal})).status}catch(e){if(i?.signal.aborted)throw new y(m.TIMEOUT,"Request timed out after 10000ms");throw new y(m.NETWORK_ERROR,"Network request failed",{cause:e})}finally{null!==s&&clearTimeout(s)}}}const K=new Set(["active","grace"]);function C(e){return K.has(e.status)}function P(e){const t=new Set;for(const i of e)if(C(i))for(const e of i.features)t.add(e);return[...t]}function V(e,t){return e.features.includes(t)}const M=Object.freeze({items:[],features:[],verified:!1,issuedAt:null,fetchedAt:null,source:"none",requiresOnlineCheck:!1,offlineUntil:null});function x(e){const t=atob(e),i=new Uint8Array(t.length);for(let e=0;e<t.length;e++)i[e]=t.charCodeAt(e);return i}async function W(e,t){if(!e.signature||"ed25519"!==e.alg)return"invalid";if(!t)return"unverified";const i=globalThis.crypto?.subtle;if(!i)return"unverified";let s;try{s=await i.importKey("raw",x(t),{name:"Ed25519"},!1,["verify"])}catch{return"unverified"}try{const t=(new TextEncoder).encode(f(e.payload));return await i.verify("Ed25519",s,x(e.signature),t)?"valid":"invalid"}catch{return"invalid"}}Object.freeze(M.items),Object.freeze(M.features);const F=/^[A-Za-z0-9+/]{43}=$/;async function $(e,t){if(!e.signature||"ed25519"!==e.alg)return{verdict:"invalid",key:null};let i=[];try{i=await t.known()}catch{i=[]}let s,n=!1;for(const t of i){const i=await W(e,t);if("valid"===i)return{verdict:i,key:t};"invalid"===i&&(n=!0)}try{s=await t.fetchCurrent()}catch{return{verdict:"unverified",key:null}}if(s&&!i.includes(s)){const t=await W(e,s);return{verdict:t,key:"valid"===t?s:null}}return{verdict:n?"invalid":"unverified",key:null}}const q=864e5,B=q;class j{constructor(e){this.options=e,this.timer=null,this.running=!1,this.pending=Promise.resolve()}start(){this.running=!0,this.evaluate()}stop(){this.running=!1,this.clearTimer()}evaluate(){return this.pending=this.pending.then(()=>this.check()).catch(e=>I.debug("trial check",e)),this.pending}async check(){if(!this.running)return;this.clearTimer();const e=this.options.getTrial();if(!e)return;const t=this.options.now(),i=Date.parse(e.endsAt),s=i-this.options.endingDays*q,n=0===e.daysLeft?"trial:ended":e.active&&this.options.endingDays>0&&t>=s?"trial:ending":null;if(n&&!this.options.hasPaidAccess()&&await this.send(n,e),!this.running||0===e.daysLeft)return;const r=[s,i].find(e=>e>t)??i;this.timer=setTimeout(()=>{this.timer=null,this.evaluate()},Math.max(1e3,Math.min(r-t,B)))}async send(e,t){const i=`${t.startedAt}|${t.endsAt}`,s="trial:ended"===e?"ended":"ending",n=await this.options.storage.get(this.options.storageKey),r=n&&"object"==typeof n?n:{};r[s]!==i&&this.running&&(await this.options.storage.set(this.options.storageKey,{...r,[s]:i}),this.options.emit(e,t))}clearTimer(){null!==this.timer&&clearTimeout(this.timer),this.timer=null}}const z=9e5,H=3e5;function Y(e){if(!e||"object"!=typeof e)return!1;const t=e;return!!t.payload&&"object"==typeof t.payload&&"string"==typeof t.payload.endUserRef&&Array.isArray(t.payload.entitlements)&&"string"==typeof t.payload.issuedAt}class Q{constructor(e){this.options=e,this.held=null,this.inflight=null,this.clockSkew=null,this.timer=null,this.refreshGeneration=0,this.deadlineTimer=null,this.refreshIntervalMs=z,this.backoffMs=0,this.autoRefresh=!1,this.online=()=>{this.get({force:!0}).then(()=>this.notifyIfChanged())},this.lastFingerprint=f({items:[],requiresOnlineCheck:!1}),this.now=e.now??(()=>Date.now()),this.source=e.source??"network"}get storageKey(){return`extenshi-pay:${this.options.publishableKey}:entitlement${"mock"===this.source?":mock":""}`}async load(){const e=await this.options.storage.get(this.storageKey);if(!e||1!==e.v||!Y(e.envelope)||"number"!=typeof e.fetchedAt||!Number.isFinite(e.fetchedAt))return null;const t=await this.options.getEndUserRef();return e.envelope.payload.endUserRef!==t||"mock"!==this.source&&e.envelope.payload.publishableKey!==this.options.publishableKey?(await this.options.storage.remove(this.storageKey),null):(this.held={envelope:JSON.parse(JSON.stringify(e.envelope)),fetchedAt:e.fetchedAt,verified:!1,key:null,source:"mock"===this.source?"mock":"cache"},this.measureClockSkew(e.fetchedAt,Date.parse(e.envelope.payload.issuedAt)),this.lastFingerprint=this.fingerprint(),this.snapshot())}async reverify(){if(!this.held)return;if("mock"===this.source)return;const e=this.held,{verdict:t,key:i}=await $(e.envelope,this.options.keys);if(e===this.held){if("invalid"===t)throw I.warn("cached entitlement failed signature verification; discarding"),await this.discard(),new y(m.INVALID_RESPONSE,"Cached entitlement signature is invalid");if(e.verified="valid"===t,e.key=i,!e.verified)throw new y(m.VERIFICATION_UNAVAILABLE,"Entitlement verification requires a trusted key and Ed25519 WebCrypto support");this.scheduleDeadline()}}get verifiedKey(){return this.held?.verified?this.held.key:null}getCached(){return this.held?this.snapshot():null}getTrial(){const e=this.held;if(!e||"mock"!==this.source&&!e.verified)return null;const t=this.now(),i=Date.parse(e.envelope.payload.issuedAt);return function(e,t){if(!e)return null;const i=Date.parse(e.startedAt),s=Date.parse(e.endsAt);if(!Number.isFinite(i)||!Number.isFinite(s))return null;const n=s-(Number.isFinite(t.issuedAt)?Math.max(t.now,t.issuedAt):t.now);return{active:n>0&&t.checked,startedAt:e.startedAt,endsAt:e.endsAt,daysLeft:n>0?Math.ceil(n/q):0,requiresOnlineCheck:n>0&&!t.checked}}(e.envelope.payload.trial,{now:t,issuedAt:i,checked:"mock"===this.source||t>=e.fetchedAt&&t<this.offlineDeadline()&&t+H>=i})}isFresh(){return null!==this.held&&("mock"===this.source||this.held.verified&&!this.snapshot().requiresOnlineCheck)&&this.now()>=this.held.fetchedAt&&this.now()-this.held.fetchedAt<Math.min(this.options.cacheTtlMs,this.offlineAgeMs())}async get(e={}){if(!e.force&&this.isFresh())return this.snapshot();try{return await this.refresh()}catch(e){const t=y.from(e);return this.options.onError?.(t),this.held?(I.debug("serving cached entitlement after refresh failure",t.code),this.snapshot()):this.snapshot()}}refresh(){return this.inflight||(this.inflight=(async()=>{const e=await this.options.getEndUserRef(),t=this.options.getTrialStartHint?await this.options.getTrialStartHint():null,i=await this.options.api.getEntitlement(e,t);return this.accept(i,this.source)})().finally(()=>{this.inflight=null})),this.inflight}async accept(e,t=this.source){if(!Y(e))throw new y(m.INVALID_RESPONSE,"Malformed entitlement envelope");if(e=JSON.parse(JSON.stringify(e)),"mock"!==this.source&&e.payload.publishableKey!==this.options.publishableKey)throw new y(m.INVALID_RESPONSE,"Entitlement belongs to a different application or lacks a signed application scope");const i=await this.options.getEndUserRef();if(e.payload.endUserRef!==i)throw new y(m.INVALID_RESPONSE,"Entitlement issued for a different endUserRef");const{verdict:s,key:n}="mock"===this.source?{verdict:"unverified",key:null}:await $(e,this.options.keys);if("invalid"===s)throw await this.discard(),new y(m.INVALID_RESPONSE,"Entitlement signature is invalid");if("valid"!==s&&"mock"!==this.source)throw new y(m.VERIFICATION_UNAVAILABLE,"Entitlement verification requires a trusted key and Ed25519 WebCrypto support");const r=this.now(),o=Date.parse(e.payload.issuedAt);if("mock"!==this.source&&this.measureClockSkew(r,o),"mock"!==this.source&&(!Number.isFinite(o)||o>r+H))throw new y(m.INVALID_RESPONSE,"Entitlement issuedAt is invalid or in the future");this.held={envelope:e,fetchedAt:r,verified:"valid"===s,key:n,source:t};const a={v:1,envelope:e,fetchedAt:r};return await this.options.storage.set(this.storageKey,JSON.parse(JSON.stringify(a))),this.backoffMs=0,this.scheduleDeadline(),this.notifyIfChanged(),this.options.onAccepted?.(),this.snapshot()}async settleRefresh(){await(this.inflight?.catch(()=>{}))}async clear(){this.held=null,this.scheduleDeadline(),this.lastFingerprint=null,await this.options.storage.remove(this.storageKey)}startAutoRefresh(e=Math.max(this.options.cacheTtlMs,z)){this.stopAutoRefresh(),this.autoRefresh=!0,globalThis.addEventListener?.("online",this.online),this.refreshIntervalMs=Math.max(e,z),this.schedule(this.refreshIntervalMs),this.scheduleDeadline()}stopAutoRefresh(){this.autoRefresh=!1,globalThis.removeEventListener?.("online",this.online),this.refreshGeneration++,null!==this.deadlineTimer&&clearTimeout(this.deadlineTimer),this.deadlineTimer=null,null!==this.timer&&clearTimeout(this.timer),this.timer=null}scheduleDeadline(){if(null!==this.deadlineTimer&&clearTimeout(this.deadlineTimer),this.deadlineTimer=null,!this.autoRefresh||!this.held||!this.held.verified||"mock"===this.source)return;const e=this.now();if(e>=this.offlineDeadline())return;const t=[this.offlineDeadline(),...this.held.envelope.payload.entitlements.filter(e=>"active"===e.status||"grace"===e.status).map(e=>e.expiresAt?Date.parse(e.expiresAt):NaN)],i=Math.min(...t.filter(t=>t>e))-e;!Number.isFinite(i)||i<=0||(this.deadlineTimer=setTimeout(()=>{this.deadlineTimer=null,this.notifyIfChanged(),this.scheduleDeadline()},Math.min(i,2147483647)))}schedule(e){const t=this.refreshGeneration;this.timer=setTimeout(async()=>{this.timer=null;try{if(await this.refresh(),t!==this.refreshGeneration)return;this.schedule(this.refreshIntervalMs)}catch(e){if(t!==this.refreshGeneration)return;this.options.onError?.(y.from(e)),this.backoffMs=Math.min(this.backoffMs?2*this.backoffMs:this.refreshIntervalMs,216e5),this.schedule(this.backoffMs)}},e)}measureClockSkew(e,t){const i=e-t;this.clockSkew=Number.isFinite(i)&&Math.abs(i)>H?{direction:i>0?"ahead":"behind",ms:Math.abs(i)}:null}async discard(){this.held=null,this.scheduleDeadline(),await this.options.storage.remove(this.storageKey),this.notifyIfChanged()}fingerprint(){const e=this.snapshot();return f({items:e.items,requiresOnlineCheck:e.requiresOnlineCheck,...e.regionalFreeUntil?{regionalFreeUntil:e.regionalFreeUntil,features:e.features}:{}})}notifyIfChanged(){const e=this.fingerprint();e!==this.lastFingerprint&&(this.lastFingerprint=e,this.options.onChange?.(this.snapshot()))}offlineDeadline(){return this.held?Math.min(this.held.fetchedAt,Date.parse(this.held.envelope.payload.issuedAt))+this.offlineAgeMs():NaN}offlineAgeMs(){const e=this.held?.envelope.payload.offlineSeconds;return"number"!=typeof e||!Number.isFinite(e)||e<=0?1728e5:Math.min(1e3*e,316224e5)}snapshot(){if(!this.held)return this.clockSkew?{...M,clockSkew:this.clockSkew}:M;if("mock"!==this.source&&!this.held.verified)return{...M,requiresOnlineCheck:!0,clockSkew:this.clockSkew,source:this.held.source};const e=function(e,t=Date.now()){return e.map(e=>{if(!C(e)||!e.expiresAt)return e;const i=Date.parse(e.expiresAt);return Number.isFinite(i)&&i<=t?{...e,status:"expired"}:e})}(JSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)),this.now()),t=e.find(e=>e.sku===i&&"active"===e.status),s=e.filter(e=>e.sku!==i),n=e.some(e=>e.sku===i)||P(s).length>0||s.some(e=>"active"===e.status||"grace"===e.status),r="mock"!==this.source&&n?this.offlineDeadline():null,o=null!==r&&(!Number.isFinite(r)||this.now()>=r||this.now()<this.held.fetchedAt||this.now()+H<Date.parse(this.held.envelope.payload.issuedAt));return{items:s,features:o?[]:P(e),...t?.expiresAt&&!o?{regionalFreeUntil:Date.parse(t.expiresAt)}:{},requiresOnlineCheck:o,offlineUntil:r,clockSkew:this.clockSkew,verified:this.held.verified,issuedAt:this.held.envelope.payload.issuedAt,fetchedAt:this.held.fetchedAt,source:this.held.source}}}function G(){return globalThis}function J(e,t){const i=e();return(s=i)&&"function"==typeof s.then?i:new Promise((e,i)=>{t(t=>{const s=G().chrome?.runtime?.lastError;s?i(new Error(s.message??"storage error")):e(t)})});var s}class Z{constructor(e){this.area=e}async get(e){const t=await J(()=>this.area.get(e),t=>this.area.get(e,t));return t?.[e]}async set(e,t){await J(()=>this.area.set({[e]:t}),i=>this.area.set({[e]:t},i))}async remove(e){await J(()=>this.area.remove(e),t=>this.area.remove(e,t))}}class X{constructor(e){this.store=e}async get(e){const t=this.store.getItem(e);if(null!==t)try{return JSON.parse(t)}catch{return}}async set(e,t){this.store.setItem(e,JSON.stringify(t))}async remove(e){this.store.removeItem(e)}}class ee{constructor(){this.map=new Map}async get(e){return this.map.get(e)}async set(e,t){this.map.set(e,t)}async remove(e){this.map.delete(e)}}function te(){const e=globalThis,t=e.chrome?.tabs?e.chrome:e.browser?.tabs?e.browser:null;return t?.storage?.session?new Z(t.storage.session):new ee}class ie{constructor(e){this.options=e,this.active=!1,this.stopped=!1,this.wake=null}get pendingKey(){return`extenshi-pay:${this.options.publishableKey}:pendingRestore`}isActive(){return this.active}stop(){this.stopped=!0,this.wake?.()}async open(e={}){if(this.active)throw new y(m.INVALID_REQUEST,"Recovery is already in progress");this.active=!0,this.stopped=!1;try{const t=globalThis;if((t.chrome?.runtime?.id||t.browser?.runtime?.id)&&!t.chrome?.tabs&&!t.browser?.tabs)throw new y(m.INVALID_REQUEST,"Start recovery in an extension page or background context");const i=globalThis.crypto;if(!i?.subtle)throw new y(m.INVALID_REQUEST,"Secure recovery is unavailable in this browser");const s=Array.from(i.getRandomValues(new Uint8Array(32)),e=>e.toString(16).padStart(2,"0")).join(""),n=await i.subtle.digest("SHA-256",(new TextEncoder).encode(s)),r=Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,"0")).join(""),o=await this.options.api.createRestoreSession(r,this.options.locale,e.purpose);if(!Number.isFinite(Date.parse(o.expiresAt)))throw new y(m.INVALID_RESPONSE,"Invalid recovery expiry");const a={sessionId:o.sessionId,expiresAt:o.expiresAt,claimSecret:s};return await this.options.storage.set(this.pendingKey,a),await(e.openUrl??this.options.openUrl??L)(o.url),await this.poll(a,e)}finally{this.active=!1}}async resumePending(){if(this.active||this.stopped)return null;const e=await this.options.storage.get(this.pendingKey);if(!e||this.active||this.stopped)return null;if("string"!=typeof e.sessionId||"string"!=typeof e.claimSecret||!/^[a-f0-9]{64}$/.test(e.claimSecret)||!Number.isFinite(Date.parse(e.expiresAt??"")))return await this.options.storage.remove(this.pendingKey),null;this.active=!0,this.stopped=!1;try{return await this.poll(e,{})}finally{this.active=!1}}async poll(e,t){const i=this.options.now??Date.now,s=Date.parse(e.expiresAt),n=Math.min(s,i()+(t.timeoutMs??6e5));let r=0;for(;!this.stopped&&!t.signal?.aborted&&i()<n&&(r&&await new Promise(e=>{const s=()=>{clearTimeout(o),t.signal?.removeEventListener("abort",s),this.wake=null,e()},o=setTimeout(s,Math.min(r,Math.max(0,n-i())));this.wake=s,t.signal?.addEventListener("abort",s,{once:!0})}),!(this.stopped||t.signal?.aborted||i()>=n));)try{const i=await this.options.api.claimRestoreSession(e.sessionId,e.claimSecret);if(this.stopped||t.signal?.aborted)break;if("complete"===i.state){const e=await this.options.onComplete(i.endUserRef,i.entitlement),t=await(this.options.onStorageGrant?.(i.storage));return await this.options.storage.remove(this.pendingKey),{state:"complete",entitlement:e,...t?{cloudBackup:t}:{}}}if("pending"!==i.state)throw new y(m.INVALID_RESPONSE,"Invalid recovery response");r=Math.max(100,t.pollIntervalMs??2e3)}catch(e){const t=y.from(e);if(![m.NETWORK_ERROR,m.TIMEOUT,m.GATEWAY_UNAVAILABLE,m.RATE_LIMITED].some(e=>e===t.code))throw t;r=Math.max(2e3,1e3*(t.retryAfterSec??5))}return i()>=s&&await this.options.storage.remove(this.pendingKey),{state:this.stopped||t.signal?.aborted?"canceled":i()>=s?"expired":"timeout"}}}const se=/^[a-z]{2}(-[A-Za-z]{2,4})?$/;function ne(e){if("string"!=typeof e)return null;const t=e.trim().replace(/_/g,"-").split("-").filter(Boolean),i=t[0]?.toLowerCase();if(!i||!/^[a-z]{2}$/.test(i))return null;const s=t.slice(1).find(e=>/^[A-Za-z]{4}$/.test(e))?.toLowerCase(),n=t.slice(1).find(e=>/^[A-Za-z]{2}$/.test(e))??("zh"===i&&"hant"===s?"TW":void 0),r=n?`${i}-${n.toUpperCase()}`:i;return se.test(r)?r:i}const re=["en","es","pt-BR","fr","de","it","ru","ja","ko","zh-CN","ar"];function oe(e){const t=ne(e);if(!t)return"en";const i=re.find(e=>e.toLowerCase()===t.toLowerCase());if(i)return i;const[s,n]=t.split("-");return"pt"===s?"pt-BR":"zh"===s?n&&["TW","HK","MO"].includes(n)?"en":"zh-CN":re.find(e=>e===s)??"en"}const ae={[s]:{en:"I agree that {seller} starts supplying the digital content immediately, and I acknowledge that I lose my right of withdrawal once supply has begun.",es:"Acepto que {seller} comience a suministrar el contenido digital de inmediato y reconozco que pierdo mi derecho de desistimiento una vez iniciado el suministro.","pt-BR":"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.",fr:"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.",de:"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.",it:"Accetto che {seller} inizi immediatamente la fornitura del contenuto digitale e riconosco di perdere il mio diritto di recesso una volta iniziata la fornitura.",ru:"Я соглашаюсь с тем, что {seller} немедленно начнёт предоставление цифрового контента, и подтверждаю, что утрачиваю право на отказ от договора с момента начала предоставления.",ja:"{seller}がデジタルコンテンツの提供を直ちに開始することに同意し、提供の開始後は撤回権を失うことを了承します。",ko:"{seller}의 디지털 콘텐츠 제공이 즉시 시작되는 것에 동의하며, 제공이 시작되면 청약철회권을 상실한다는 점을 확인합니다.","zh-CN":"我同意 {seller} 立即开始提供数字内容,并确认一旦开始提供,我将失去撤回权。",ar:"أوافق على أن يبدأ {seller} فورًا في تقديم المحتوى الرقمي، وأُقرّ بأنني أفقد حقي في العدول عن العقد بمجرد بدء التقديم."}};const le="0.12.0",he=6048e5,ce=new Set(["production","sandbox","development"]),ue=new Set(["silent","error","warn","info","debug"]),de=new Set(["light","dark","auto"]),fe=/^[a-z]{2}(-[A-Za-z]{2,4})?$/;function pe(e){const i=[];if(!e||"object"!=typeof e)throw new y(m.INVALID_CONFIG,"ExtenshiPay config must be an object");var s;"string"==typeof(s=e.publishableKey)&&t.test(s)||i.push("publishableKey must look like pk_ext_<32 hex characters>");const n=(e.apiUrl??"https://bff.extenshi.io").replace(/\/+$/,"");(function(e){try{const t=new URL(e);return"https:"===t.protocol||"http:"===t.protocol}catch{return!1}})(n)||i.push("apiUrl must be an http(s) URL");const r=e.entitlementPublicKey??null;null===r||F.test(r)||i.push("entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key");const o=e.environment??"production";ce.has(o)||i.push("environment must be production, sandbox or development");const a=e.logLevel??"warn";ue.has(a)||i.push("logLevel must be silent, error, warn, info or debug");const l=e.cacheTtlMs??36e5;(!Number.isFinite(l)||l<0||l>he)&&i.push("cacheTtlMs must be between 0 and 604800000");const h=void 0===e.locale?function(){const e=globalThis;try{const t=e.chrome?.i18n?.getUILanguage?.()??e.browser?.i18n?.getUILanguage?.();if(t)return ne(t)}catch{}return ne(e.navigator?.language)}():e.locale;null===h||fe.test(h)||i.push("locale must be a BCP-47 tag such as en or de-DE");const c=e.theme??{};void 0===c.mode||de.has(c.mode)||i.push("theme.mode must be light, dark or auto");const u=e.trialEndingDays??2;if((!Number.isInteger(u)||u<0||u>365)&&i.push("trialEndingDays must be a whole number of days between 0 and 365"),!e.mock||void 0===e.mockData||"object"==typeof e.mockData&&null!==e.mockData||i.push("mockData must be an object"),i.length>0)throw new y(m.INVALID_CONFIG,`Invalid ExtenshiPay config: ${i.join("; ")}`);return{publishableKey:e.publishableKey,apiUrl:n,entitlementPublicKey:r,environment:o,debug:!0===e.debug,logLevel:a,cacheTtlMs:l,locale:h,mock:!0===e.mock,mockData:e.mock?e.mockData??{}:null,theme:c,trialEndingDays:u,syncTrialStart:!1!==e.syncTrialStart}}class me{constructor(){this.listeners=new Map}on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>this.off(e,t)}once(e,t){const i=this.on(e,e=>{i(),t(e)});return i}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){const i=this.listeners.get(e);if(i)for(const s of[...i]){const i=s;try{i(t)}catch(t){I.error(`listener for "${String(e)}" threw`,t)}}}removeAll(){this.listeners.clear()}}class ye{constructor(e,t={}){this.emitter=new me,this.endUserRef=null,this.endUserRefPromise=null,this.offer=null,this.offerInflight=null,this.serverKey=null,this.keys={known:async()=>{const e=this.config.entitlementPublicKey??await this.readSavedServerKey();return[...new Set([this.serverKey,e].filter(e=>!!e))]},fetchCurrent:async()=>(await this.fetchOffer(!0)).entitlementPublicKey},this.readyPromise=null,this.destroyed=!1,this.config=pe(e),I.configure({logLevel:this.config.logLevel,debug:this.config.debug}),this.now=t.now??(()=>Date.now()),this.storage=t.storage??function(){const e=G(),t=e.chrome?.storage?.local??e.browser?.storage?.local;if(t)return new Z(t);try{const e=globalThis.localStorage;if(e&&"function"==typeof e.getItem)return new X(e)}catch{}return new ee}(),this.openUrl=t.openUrl,this.syncStorage=!this.config.syncTrialStart||this.config.mock?null:void 0===t.syncStorage?function(){const e=G(),t=e.chrome?.storage?.sync??e.browser?.storage?.sync;return t?new Z(t):null}():t.syncStorage;const i=t.transport??(this.config.mock?new A(this.config.mockData??{}):new N({apiUrl:this.config.apiUrl,fetchImpl:t.fetch}));this.api=new b(i,this.config.publishableKey),this.entitlements=new Q({api:this.api,storage:this.storage,publishableKey:this.config.publishableKey,cacheTtlMs:this.config.cacheTtlMs,source:this.config.mock?"mock":"network",getEndUserRef:()=>this.getEndUserRef(),keys:this.keys,onChange:e=>this.emitter.emit("entitlement:changed",e),onAccepted:()=>{this.trial.evaluate(),this.rememberTrialStart()},getTrialStartHint:()=>this.readTrialStartHint(),onError:e=>this.reportError(e),now:this.now}),this.trial=new j({storage:this.storage,storageKey:`extenshi-pay:${this.config.publishableKey}:trial-events${this.config.mock?":mock":""}`,endingDays:this.config.trialEndingDays,getTrial:()=>this.entitlements.getTrial(),hasPaidAccess:()=>{const e=this.entitlements.getCached();return Boolean(e?.regionalFreeUntil||e?.items.some(C))},emit:(e,t)=>this.emitter.emit(e,t),now:this.now}),this.checkout=new _({api:this.api,storage:this.storage,publishableKey:this.config.publishableKey,locale:this.config.locale,getEndUserRef:()=>this.getEndUserRef(),onComplete:e=>this.entitlements.accept(e),emit:(e,t)=>this.emitter.emit(e,t),openUrl:t.openUrl??(this.config.mock?e=>I.info("mock checkout (no tab opened)",e):void 0),now:this.now}),this.backup=new D({storage:this.storage,publishableKey:this.config.publishableKey,apiUrl:this.config.apiUrl,fetch:t.fetch,mock:this.config.mock}),this.recovery=new ie({api:this.api,locale:this.config.locale,publishableKey:this.config.publishableKey,storage:t.recoveryStorage??te(),openUrl:t.openUrl,now:this.now,onComplete:async(e,t)=>{if(!n.test(e)||t?.payload?.endUserRef!==e||t.payload.publishableKey!==this.config.publishableKey||!Number.isFinite(Date.parse(t.payload.issuedAt))||Date.parse(t.payload.issuedAt)>this.now()+H||"valid"!==(await $(t,this.keys)).verdict)throw new y(m.INVALID_RESPONSE,"Recovery requires a verified entitlement for this installation");this.entitlements.stopAutoRefresh();try{if(await this.entitlements.settleRefresh(),this.destroyed)throw new y(m.INVALID_REQUEST,"Recovery was stopped");return await this.storage.set(g,e),this.endUserRef=e,this.endUserRefPromise=null,await this.entitlements.clear(),await this.entitlements.accept(t)}finally{this.destroyed||this.entitlements.startAutoRefresh()}},onStorageGrant:e=>this.backup.accept(e)}),e.onError&&this.emitter.on("error",e.onError),e.onReady&&this.emitter.once("ready",e.onReady)}get version(){return le}initialize(){return this.readyPromise||(this.readyPromise=this.doInitialize()),this.readyPromise}async doInitialize(){const e=await this.getEndUserRef();await this.entitlements.load();try{await this.entitlements.reverify()}catch(e){this.reportError(e)}this.entitlements.isFresh()||await this.entitlements.get({force:!0}),this.emitter.emit("ready",{endUserRef:e}),this.afterReady()}async afterReady(){if(!this.destroyed){try{if(await this.checkout.resumePending(),this.destroyed)return;await this.recovery.resumePending()}catch(e){this.reportError(e)}this.confirmSavedServerKey(),this.destroyed||(this.entitlements.startAutoRefresh(),this.trial.start())}}getEndUserRef(){return this.endUserRef?Promise.resolve(this.endUserRef):(this.endUserRefPromise||(this.endUserRefPromise=async function(e){const t=await e.get(g);if("string"==typeof t&&n.test(t))return t;const i=w();return await e.set(g,i),i}(this.storage).then(e=>(this.endUserRef=e,e))),this.endUserRefPromise)}getCachedEntitlement(){return this.entitlements.getCached()}async getEntitlement(e={}){return await this.initialize(),this.entitlements.get(e)}async getTrial(e={}){return await this.getEntitlement(e),this.entitlements.getTrial()}async isPaid(e){return function(e,t){return!e.requiresOnlineCheck&&e.items.some(e=>C(e)&&(void 0===t||e.sku===t))}(await this.getEntitlement(),e)}async hasFeature(e){return V(await this.getEntitlement(),e)}async checkFeatures(e){return function(e,t){const i={};for(const s of t)i[s]=V(e,s);return i}(await this.getEntitlement(),e)}async requireFeature(e,t={}){if(await this.hasFeature(e))return t.onUnlock?.(),!0;const i=await this.onFeatureLocked(e,t);return i?t.onUnlock?.():t.onCancel?.(),i}async onFeatureLocked(e,t){return!1}async getWithdrawalWaiver(){await this.initialize();try{const e=await this.fetchOffer();if(!e.withdrawalWaiver)return null;const t=e.seller?.displayName?.trim()||e.projectName;return function(e,t,i){const n=Object.keys(ae).includes(e)?e:s;return{version:n,text:(r=ae[n][oe(t)],o={seller:i},r.replace(/\{([a-z]+)\}/g,(e,t)=>o[t]??e))};var r,o}(e.withdrawalWaiver.version,this.config.locale,t)}catch(e){throw this.reportError(e)}}async openCheckout(e,t={}){await this.initialize();try{if(this.recovery.isActive())throw new y(m.INVALID_REQUEST,"Recovery is in progress");const i=await this.fetchOffer().catch(()=>null);if(i?.withdrawalWaiver&&!0!==t.withdrawalWaiver?.accepted)throw new y(m.WITHDRAWAL_WAIVER_REQUIRED,"This offer needs the buyer to accept the withdrawal waiver; pass options.withdrawalWaiver");return await this.checkout.open(e,t)}catch(e){throw this.reportError(e)}}async restorePurchase(e={}){await this.initialize();try{if(this.checkout.isActive())throw new y(m.INVALID_REQUEST,"Checkout is in progress");return await this.recovery.open(e)}catch(e){throw this.reportError(e)}}enableCloudBackup(e={}){return this.restorePurchase({...e,purpose:"storage"})}async cloudBackupToken(){return this.backup.token()}async disableCloudBackup(){try{await this.backup.disable()}catch(e){throw this.reportError(e)}}async deleteCloudBackup(){try{await this.backup.delete()}catch(e){throw this.reportError(e)}}async getLicenseSummary(e={}){await this.initialize();let t=null;try{t=await this.fetchOffer(e.force)}catch{}return{projectName:t?.projectName??null,seller:t?.seller??null,entitlement:await this.getEntitlement(e),recoveryEnabled:!0===t?.recoveryEnabled}}async openCustomerPortal(e={}){await this.initialize();try{const t=await this.getEndUserRef();let i=await this.api.getPortalUrl(t,void 0,this.config.locale);if(this.destroyed)return null;if(i.accounts?.length){if(!e.selectAccount)throw new y(m.INVALID_REQUEST,"Choose a billing profile using selectAccount");const s=await e.selectAccount(i.accounts);if(null===s||this.destroyed)return null;if(!i.accounts.some(e=>e.id===s))throw new y(m.INVALID_REQUEST,"Invalid billing profile");if(t!==await this.getEndUserRef())throw new y(m.INVALID_REQUEST,"Installation changed; open the portal again");i=await this.api.getPortalUrl(t,s,this.config.locale)}if(this.destroyed)return null;const{url:s}=i;return s&&await(e.openUrl??(await Promise.resolve().then(function(){return O})).openInNewTab)(s),s}catch(e){throw this.reportError(e)}}on(e,t){return this.emitter.on(e,t)}once(e,t){return this.emitter.once(e,t)}off(e,t){this.emitter.off(e,t)}onEntitlementChange(e){return this.emitter.on("entitlement:changed",e)}async clearCache(){this.offer=null,await this.entitlements.clear()}destroy(){this.destroyed=!0,this.recovery.stop(),this.trial.stop(),this.entitlements.stopAutoRefresh(),this.emitter.removeAll()}fetchOffer(e=!1){return!e&&this.offer&&this.now()-this.offer.fetchedAt<3e5?Promise.resolve(this.offer.value):(this.offerInflight||(this.offerInflight=this.api.getOffer(this.config.locale).then(async e=>(this.offer={value:e,fetchedAt:this.now()},await this.rememberServerKey(e.entitlementPublicKey),e)).finally(()=>{this.offerInflight=null})),this.offerInflight)}get serverKeyStorageKey(){return`extenshi-pay:${this.config.publishableKey}:entitlementPublicKey`}async readSavedServerKey(){try{const e=await this.storage.get(this.serverKeyStorageKey);return"string"==typeof e&&F.test(e)?e:null}catch{return null}}async rememberServerKey(e){if("string"==typeof e&&F.test(e)&&(this.serverKey=e,!this.config.entitlementPublicKey&&!this.config.mock))try{await this.readSavedServerKey()!==e&&await this.storage.set(this.serverKeyStorageKey,e)}catch(e){I.debug("signing key not saved",e)}}async confirmSavedServerKey(){const e=this.entitlements.verifiedKey;if(!this.destroyed&&e&&e!==this.serverKey&&e!==this.config.entitlementPublicKey){try{if((await this.fetchOffer()).entitlementPublicKey===e||this.destroyed)return}catch{return}try{await this.entitlements.refresh()}catch{await this.entitlements.reverify().catch(e=>this.reportError(e))}}}get trialStartKey(){return`extenshi-pay:${this.config.publishableKey}:trialStartedAt`}async readTrialStartHint(){if(!this.syncStorage)return null;try{const e=await this.syncStorage.get(this.trialStartKey);return"string"==typeof e&&Number.isFinite(Date.parse(e))?e:null}catch{return null}}async rememberTrialStart(){const e=this.entitlements.getTrial();if(this.syncStorage&&e)try{const t=await this.readTrialStartHint();if(t&&Date.parse(t)<=Date.parse(e.startedAt))return;await this.syncStorage.set(this.trialStartKey,e.startedAt)}catch(e){I.debug("trial start not synced",e)}}reportError(e){const t=y.from(e);return I.warn(`${t.code}: ${t.message}`),this.emitter.emit("error",t),t}}ye.version=le,e.ERROR_CODES=m,e.ExtenshiPay=ye,e.ExtenshiPayError=y,e.ExtenshiPayLite=ye,e.MockTransport=A,e.PAY_WITHDRAWAL_WAIVER_VERSION=s,e.VERSION=le,e.default=ye,Object.defineProperty(e,"__esModule",{value:!0})});
8
8
  //# sourceMappingURL=extenshi-pay-lite.min.js.map