@revenuecat/purchases-js 1.17.1 → 1.18.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.
- package/dist/Purchases.es.d.ts +49 -0
- package/dist/Purchases.es.js +7 -10
- package/dist/Purchases.umd.js +2 -2
- package/package.json +1 -1
package/dist/Purchases.es.d.ts
CHANGED
|
@@ -593,6 +593,49 @@ export declare interface PresentedOfferingContext {
|
|
|
593
593
|
readonly placementIdentifier: string | null;
|
|
594
594
|
}
|
|
595
595
|
|
|
596
|
+
/**
|
|
597
|
+
* Parameters for the {@link Purchases.presentPaywall} method.
|
|
598
|
+
* @public
|
|
599
|
+
*/
|
|
600
|
+
export declare interface PresentPaywallParams {
|
|
601
|
+
/**
|
|
602
|
+
* The identifier of the offering to fetch the paywall for.
|
|
603
|
+
* Can be a string identifier or one of the predefined keywords.
|
|
604
|
+
*/
|
|
605
|
+
readonly offering?: Offering;
|
|
606
|
+
/**
|
|
607
|
+
* The target element where the paywall will be rendered.
|
|
608
|
+
* The paywall will create a full-screen overlay if null.
|
|
609
|
+
*/
|
|
610
|
+
readonly htmlTarget?: HTMLElement;
|
|
611
|
+
/**
|
|
612
|
+
* The target element where the checkout flow will be rendered.
|
|
613
|
+
* The checkout flow will create a full-screen overlay if null.
|
|
614
|
+
*/
|
|
615
|
+
readonly purchaseHtmlTarget?: HTMLElement;
|
|
616
|
+
/**
|
|
617
|
+
* The email of the customer starting the purchase.
|
|
618
|
+
* If passed the checkout flow will not ask for it to the customer.
|
|
619
|
+
*/
|
|
620
|
+
readonly customerEmail?: string;
|
|
621
|
+
/**
|
|
622
|
+
* Callback to be called when the paywall tries to navigate to an external URL.
|
|
623
|
+
*/
|
|
624
|
+
readonly onNavigateToUrl?: (url: string) => void;
|
|
625
|
+
/**
|
|
626
|
+
* Callback to be called when the paywall tries to navigate back.
|
|
627
|
+
*/
|
|
628
|
+
readonly onBack?: () => void;
|
|
629
|
+
/**
|
|
630
|
+
* Callback to be called when the paywall tries to visit the customer center.
|
|
631
|
+
*/
|
|
632
|
+
readonly onVisitCustomerCenter?: () => void;
|
|
633
|
+
/**
|
|
634
|
+
* The locale to use for the paywall and the checkout flow.
|
|
635
|
+
*/
|
|
636
|
+
readonly selectedLocale?: string;
|
|
637
|
+
}
|
|
638
|
+
|
|
596
639
|
/**
|
|
597
640
|
* Price information for a product.
|
|
598
641
|
* @public
|
|
@@ -925,6 +968,12 @@ export declare class Purchases {
|
|
|
925
968
|
* up the first call to {@link Purchases.purchase}.
|
|
926
969
|
*/
|
|
927
970
|
preload(): Promise<void>;
|
|
971
|
+
/**
|
|
972
|
+
* Renders an RC Paywall and allows the user to purchase from it using Web Billing.
|
|
973
|
+
* @param paywallParams - The parameters object to customise the paywall render. Check {@link PresentPaywallParams}
|
|
974
|
+
* @returns Promise<PurchaseResult>
|
|
975
|
+
*/
|
|
976
|
+
presentPaywall(paywallParams: PresentPaywallParams): Promise<PurchaseResult>;
|
|
928
977
|
/**
|
|
929
978
|
* Fetch the configured offerings for this user. You can configure these
|
|
930
979
|
* in the RevenueCat dashboard.
|
package/dist/Purchases.es.js
CHANGED
|
@@ -12837,7 +12837,7 @@ function Th(e) {
|
|
|
12837
12837
|
}
|
|
12838
12838
|
return r;
|
|
12839
12839
|
}
|
|
12840
|
-
const tl = "1.
|
|
12840
|
+
const tl = "1.18.0", Ih = "https://api.revenuecat.com", qh = "https://e.revenue.cat";
|
|
12841
12841
|
var an;
|
|
12842
12842
|
(function(e) {
|
|
12843
12843
|
e[e.CONTINUE = 100] = "CONTINUE", e[e.SWITCHING_PROTOCOLS = 101] = "SWITCHING_PROTOCOLS", e[e.PROCESSING = 102] = "PROCESSING", e[e.EARLY_HINTS = 103] = "EARLY_HINTS", e[e.OK = 200] = "OK", e[e.CREATED = 201] = "CREATED", e[e.ACCEPTED = 202] = "ACCEPTED", e[e.NON_AUTHORITATIVE_INFORMATION = 203] = "NON_AUTHORITATIVE_INFORMATION", e[e.NO_CONTENT = 204] = "NO_CONTENT", e[e.RESET_CONTENT = 205] = "RESET_CONTENT", e[e.PARTIAL_CONTENT = 206] = "PARTIAL_CONTENT", e[e.MULTI_STATUS = 207] = "MULTI_STATUS", e[e.MULTIPLE_CHOICES = 300] = "MULTIPLE_CHOICES", e[e.MOVED_PERMANENTLY = 301] = "MOVED_PERMANENTLY", e[e.MOVED_TEMPORARILY = 302] = "MOVED_TEMPORARILY", e[e.SEE_OTHER = 303] = "SEE_OTHER", e[e.NOT_MODIFIED = 304] = "NOT_MODIFIED", e[e.USE_PROXY = 305] = "USE_PROXY", e[e.TEMPORARY_REDIRECT = 307] = "TEMPORARY_REDIRECT", e[e.PERMANENT_REDIRECT = 308] = "PERMANENT_REDIRECT", e[e.BAD_REQUEST = 400] = "BAD_REQUEST", e[e.UNAUTHORIZED = 401] = "UNAUTHORIZED", e[e.PAYMENT_REQUIRED = 402] = "PAYMENT_REQUIRED", e[e.FORBIDDEN = 403] = "FORBIDDEN", e[e.NOT_FOUND = 404] = "NOT_FOUND", e[e.METHOD_NOT_ALLOWED = 405] = "METHOD_NOT_ALLOWED", e[e.NOT_ACCEPTABLE = 406] = "NOT_ACCEPTABLE", e[e.PROXY_AUTHENTICATION_REQUIRED = 407] = "PROXY_AUTHENTICATION_REQUIRED", e[e.REQUEST_TIMEOUT = 408] = "REQUEST_TIMEOUT", e[e.CONFLICT = 409] = "CONFLICT", e[e.GONE = 410] = "GONE", e[e.LENGTH_REQUIRED = 411] = "LENGTH_REQUIRED", e[e.PRECONDITION_FAILED = 412] = "PRECONDITION_FAILED", e[e.REQUEST_TOO_LONG = 413] = "REQUEST_TOO_LONG", e[e.REQUEST_URI_TOO_LONG = 414] = "REQUEST_URI_TOO_LONG", e[e.UNSUPPORTED_MEDIA_TYPE = 415] = "UNSUPPORTED_MEDIA_TYPE", e[e.REQUESTED_RANGE_NOT_SATISFIABLE = 416] = "REQUESTED_RANGE_NOT_SATISFIABLE", e[e.EXPECTATION_FAILED = 417] = "EXPECTATION_FAILED", e[e.IM_A_TEAPOT = 418] = "IM_A_TEAPOT", e[e.INSUFFICIENT_SPACE_ON_RESOURCE = 419] = "INSUFFICIENT_SPACE_ON_RESOURCE", e[e.METHOD_FAILURE = 420] = "METHOD_FAILURE", e[e.MISDIRECTED_REQUEST = 421] = "MISDIRECTED_REQUEST", e[e.UNPROCESSABLE_ENTITY = 422] = "UNPROCESSABLE_ENTITY", e[e.LOCKED = 423] = "LOCKED", e[e.FAILED_DEPENDENCY = 424] = "FAILED_DEPENDENCY", e[e.UPGRADE_REQUIRED = 426] = "UPGRADE_REQUIRED", e[e.PRECONDITION_REQUIRED = 428] = "PRECONDITION_REQUIRED", e[e.TOO_MANY_REQUESTS = 429] = "TOO_MANY_REQUESTS", e[e.REQUEST_HEADER_FIELDS_TOO_LARGE = 431] = "REQUEST_HEADER_FIELDS_TOO_LARGE", e[e.UNAVAILABLE_FOR_LEGAL_REASONS = 451] = "UNAVAILABLE_FOR_LEGAL_REASONS", e[e.INTERNAL_SERVER_ERROR = 500] = "INTERNAL_SERVER_ERROR", e[e.NOT_IMPLEMENTED = 501] = "NOT_IMPLEMENTED", e[e.BAD_GATEWAY = 502] = "BAD_GATEWAY", e[e.SERVICE_UNAVAILABLE = 503] = "SERVICE_UNAVAILABLE", e[e.GATEWAY_TIMEOUT = 504] = "GATEWAY_TIMEOUT", e[e.HTTP_VERSION_NOT_SUPPORTED = 505] = "HTTP_VERSION_NOT_SUPPORTED", e[e.INSUFFICIENT_STORAGE = 507] = "INSUFFICIENT_STORAGE", e[e.NETWORK_AUTHENTICATION_REQUIRED = 511] = "NETWORK_AUTHENTICATION_REQUIRED";
|
|
@@ -14362,15 +14362,10 @@ const We = class We {
|
|
|
14362
14362
|
}
|
|
14363
14363
|
/**
|
|
14364
14364
|
* Renders an RC Paywall and allows the user to purchase from it using Web Billing.
|
|
14365
|
-
* @
|
|
14366
|
-
* @internal
|
|
14367
|
-
* @param paywallParams - The parameters object to customise the paywall render. Check {@link RenderPaywallParams}
|
|
14365
|
+
* @param paywallParams - The parameters object to customise the paywall render. Check {@link PresentPaywallParams}
|
|
14368
14366
|
* @returns Promise<PurchaseResult>
|
|
14369
14367
|
*/
|
|
14370
|
-
async
|
|
14371
|
-
console.warn(
|
|
14372
|
-
"This method is @experimental, Paywalls are not generally available but they will come soon!"
|
|
14373
|
-
);
|
|
14368
|
+
async presentPaywall(r) {
|
|
14374
14369
|
let a = r.htmlTarget ?? document.getElementById("rcb-ui-pw-root");
|
|
14375
14370
|
if (a === null) {
|
|
14376
14371
|
const f = document.createElement("div");
|
|
@@ -14382,9 +14377,11 @@ const We = class We {
|
|
|
14382
14377
|
);
|
|
14383
14378
|
const n = a;
|
|
14384
14379
|
n.innerHTML = "";
|
|
14385
|
-
const i = r.offering;
|
|
14380
|
+
const i = r.offering ? r.offering : (await this.getOfferings()).current;
|
|
14381
|
+
if (!i)
|
|
14382
|
+
throw new Error("No offering found.");
|
|
14386
14383
|
if (!i.paywallComponents)
|
|
14387
|
-
throw new Error("
|
|
14384
|
+
throw new Error("This offering doesn't have a paywall attached.");
|
|
14388
14385
|
if (!i.uiConfig)
|
|
14389
14386
|
throw new Error(
|
|
14390
14387
|
"No ui_config found for this offering, please contact support!"
|
package/dist/Purchases.umd.js
CHANGED
|
@@ -335,12 +335,12 @@
|
|
|
335
335
|
}
|
|
336
336
|
|
|
337
337
|
@container layout-query-container (width >= 768px) {.rcb-close-wrapper.svelte-11zapuq {display:none;}.rcb-back-wrapper.svelte-11zapuq {position:absolute;left:-48px;margin-left:0;}
|
|
338
|
-
}`};function ph(e,r){G(r,!0),Q(e,uh);const t=w=>w==null||w==null||w==""?null:w,a=g(()=>{var w;return t((w=r.brandingInfo)==null?void 0:w.app_icon)}),n=g(()=>{var w;return t((w=r.brandingInfo)==null?void 0:w.app_icon_webp)}),i=g(()=>{var w;return t((w=r.brandingInfo)==null?void 0:w.app_wordmark)}),s=g(()=>{var w;return t((w=r.brandingInfo)==null?void 0:w.app_wordmark_webp)}),l=g(()=>o(a)?Ra(o(a)):null),c=g(()=>o(n)?Ra(o(n)):null),d=g(()=>o(i)?Ra(o(i)):null),u=g(()=>o(s)?Ra(o(s)):null),p=()=>{r.onClose&&r.onClose()};var _=dh(),m=E(_);{var f=w=>{var T=lh(),I=E(T);ah(I,{$$events:{click:p}}),v(w,T)};B(m,w=>{r.showCloseButton&&w(f)})}var h=M(m,2),b=E(h),y=E(b);{var P=w=>{sh(w,{get src(){return o(d)},get srcWebp(){return o(u)}})},x=w=>{var T=ce(),I=ee(T);{var k=D=>{eh(D,{get src(){return o(l)},get srcWebp(){return o(c)}})};B(I,D=>{o(l)!==null&&o(c)!==null&&D(k)},!0)}v(w,T)};B(y,w=>{o(d)!==null?w(P):w(x,!1)})}var z=M(y,2);{var S=w=>{de(w,{size:"body-base",children:(T,I)=>{var k=Se();C(()=>{var D;return le(k,(D=r.brandingInfo)==null?void 0:D.app_name)}),v(T,k)},$$slots:{default:!0}})};B(z,w=>{o(d)===null&&w(S)})}var q=M(h,2);{var O=w=>{var T=ch(),I=E(T);nl(I,{$$events:{click:p}}),v(w,T)};B(q,w=>{r.showCloseButton&&w(O)})}C(()=>Et(_,"rcb-with-close-button",r.showCloseButton)),v(e,_),X()}var _h=A("<!> <!> <!> <!>",1);function gh(e,r){G(r,!0);const t=V(r,"onClose",3,void 0),a=Zs(r.productDetails,r.purchaseOptionToUse);let n=J($(r.defaultPriceBreakdown??{currency:a.currency,totalAmountInMicros:a.amountMicros,totalExcludingTaxInMicros:a.amountMicros,taxCalculationStatus:"unavailable",taxAmountInMicros:null,taxBreakdown:null}));const i=s=>{F(n,$(s))};Xf(e,{get brandingInfo(){return r.brandingInfo},get isInElement(){return r.isInElement},get isSandbox(){return r.isSandbox},get onClose(){return t()},navbarHeaderContent:d=>{var u=g(()=>!r.isInElement&&!!t());ph(d,{get brandingInfo(){return r.brandingInfo},get onClose(){return t()},get showCloseButton(){return o(u)}})},navbarBodyContent:d=>{var u=g(()=>{var p,_;return((_=(p=r.brandingInfo)==null?void 0:p.appearance)==null?void 0:_.show_product_description)??!1});gf(d,{get productDetails(){return r.productDetails},get purchaseOption(){return r.purchaseOptionToUse},get showProductDescription(){return o(u)},get priceBreakdown(){return o(n)}})},mainContent:d=>{var u=_h(),p=ee(u);{var _=x=>{Bm(x)};B(p,x=>{r.currentPage==="payment-entry-loading"&&x(_)})}var m=M(p,2);{var f=x=>{om(x,{get productDetails(){return r.productDetails},get purchaseOption(){return r.purchaseOptionToUse},get brandingInfo(){return r.brandingInfo},get purchaseOperationHelper(){return r.purchaseOperationHelper},get gatewayParams(){return r.gatewayParams},get managementUrl(){return r.managementUrl},get customerEmail(){return r.customerEmail},get defaultPriceBreakdown(){return r.defaultPriceBreakdown},get onContinue(){return r.onContinue},get onError(){return r.onError},onPriceBreakdownUpdated:i})};B(m,x=>{r.currentPage==="payment-entry"&&x(f)})}var h=M(m,2);{var b=x=>{var z=g(()=>{var q;return((q=r.brandingInfo)==null?void 0:q.support_email)??null}),S=g(()=>{var q;return((q=r.brandingInfo)==null?void 0:q.app_name)??null});Om(x,{get lastError(){return r.lastError},get productDetails(){return r.productDetails},get supportEmail(){return o(z)},get onDismiss(){return r.closeWithError},get appName(){return o(S)}})};B(h,x=>{r.currentPage==="error"&&x(b)})}var y=M(h,2);{var P=x=>{Lm(x,{get onContinue(){return r.onContinue}})};B(y,x=>{r.currentPage==="success"&&x(P)})}v(d,u)},$$slots:{navbarHeaderContent:!0,navbarBodyContent:!0,mainContent:!0}}),X()}function mh(e){return e.trim()===""?"You need to provide your email address to continue.":e.match(/^[^@]+@[^@]+\.[^@]+$/)?null:"Email is not valid. Please provide a valid email address."}function fh(e){if(e&&!e.match(/^[A-Z]{3}$/)){const r=`Currency code ${e} is not valid. Please provide a valid ISO 4217 currency code.`;throw ae.errorLog(r),new Fe(Ce.ConfigurationError,r)}}function hh(e,r){var O;G(r,!0);const t=V(r,"customTranslations",19,()=>({})),a=V(r,"skipSuccessPage",3,!1),n=r.customerEmail?mh(r.customerEmail):null;let i=J($(n?void 0:r.customerEmail)),s=r.rcPackage.webBillingProduct,l=J(null);const c=r.rcPackage.webBillingProduct.identifier??null;let d=J("payment-entry-loading"),u=J(null),p=J($({})),_=J(null),m=J(null),f=J(null),h=J(null),b=new hn(t(),r.selectedLocale,r.defaultLocale),y=yn(b);Kr(kr,y),Kr(Io,(O=r.brandingInfo)==null?void 0:O.appearance),sr(()=>{r.isInElement||(F(m,$(document.documentElement.style.height)),F(f,$(document.documentElement.style.overflow)),F(h,$(document.body.style.height)),document.documentElement.style.height="100%",document.body.style.height="100%",document.documentElement.style.overflow="hidden")}),Ia(()=>{if(!r.isInElement){const w=(T,I,k)=>{k===""?T.style.removeProperty(I):T.style.setProperty(I,k)};w(document.documentElement,"height",o(m)),w(document.body,"height",o(h)),w(document.documentElement,"overflow",o(f))}}),Kr(To,r.eventsTracker),sr(async()=>{if(c===null){x(new qe(we.ErrorSettingUpPurchase,"Product ID was not set before purchase."));return}r.purchaseOperationHelper.checkoutStart(r.appUserId,c,r.purchaseOption,r.rcPackage.webBillingProduct.presentedOfferingContext,o(i),r.metadata).then(w=>{F(l,null),F(d,"payment-entry"),F(p,$(w.gateway_params)),F(_,$(w.management_url))}).catch(w=>{if(w.errorCode===we.MissingEmailError)return F(i,void 0),r.purchaseOperationHelper.checkoutStart(r.appUserId,c,r.purchaseOption,r.rcPackage.webBillingProduct.presentedOfferingContext,o(i),r.metadata).then(T=>{F(l,null),F(d,"payment-entry"),F(p,$(T.gateway_params)),F(_,$(T.management_url))}).catch(T=>{x(T)});x(w)})});const P=()=>{if(o(d)==="payment-entry"){r.purchaseOperationHelper.pollCurrentPurchaseForCompletion().then(w=>{F(u,$(w)),a()?r.onFinished(w):F(d,"success")}).catch(w=>{x(w)});return}if(o(d)==="success"||o(d)==="error"){r.onFinished(o(u));return}F(d,"success")},x=w=>{const T=$_({errorCode:w.getErrorCode().toString(),errorMessage:w.message});r.eventsTracker.trackSDKEvent(T),F(l,$(w)),F(d,"error")},z=()=>{r.onError(o(l)??new qe(we.UnknownError,"Unknown error without state set."))};var S=g(()=>r.purchases.isSandbox()),q=g(()=>o(i)??null);gh(e,{get isSandbox(){return o(S)},get currentPage(){return o(d)},get brandingInfo(){return r.brandingInfo},productDetails:s,get purchaseOptionToUse(){return r.purchaseOption},get lastError(){return o(l)},get gatewayParams(){return o(p)},get managementUrl(){return o(_)},get purchaseOperationHelper(){return r.purchaseOperationHelper},get isInElement(){return r.isInElement},get customerEmail(){return o(q)},closeWithError:z,onContinue:P,onError:x,get onClose(){return r.onClose}}),X()}function ol(e){return e==null?!0:new Date(e)>new Date}function yh(e,r,t,a){const n=r.product_identifier;if(n in t)return vh(e,r,t[n]);if(n in a)return bh(e,r,a[n]);throw new Fe(Ce.CustomerInfoError,"Could not find entitlement product in subscriptions or non-subscriptions.")}function vh(e,r,t){return{identifier:e,isActive:ol(r.expires_date),willRenew:il(r.expires_date,t),store:(t==null?void 0:t.store)??"unknown",latestPurchaseDate:new Date(r.purchase_date),originalPurchaseDate:new Date(r.purchase_date),expirationDate:st(r.expires_date),productIdentifier:r.product_identifier,productPlanIdentifier:r.product_plan_identifier??null,unsubscribeDetectedAt:st(t==null?void 0:t.unsubscribe_detected_at),billingIssueDetectedAt:st(t==null?void 0:t.billing_issues_detected_at),isSandbox:(t==null?void 0:t.is_sandbox)??!1,periodType:(t==null?void 0:t.period_type)??"normal",ownershipType:(t==null?void 0:t.ownership_type)??"UNKNOWN"}}function bh(e,r,t){return{identifier:e,isActive:!0,willRenew:!1,store:t.store,latestPurchaseDate:new Date(r.purchase_date),originalPurchaseDate:new Date(t.original_purchase_date),expirationDate:null,productIdentifier:r.product_identifier,productPlanIdentifier:null,unsubscribeDetectedAt:null,billingIssueDetectedAt:null,isSandbox:t.is_sandbox,periodType:"normal",ownershipType:"UNKNOWN"}}function kh(e,r,t){const a={},n={};for(const i in e){const s=yh(i,e[i],r,t);a[i]=s,s.isActive&&(n[i]=s)}return{all:a,active:n}}function st(e){return e==null?null:new Date(e)}function Oo(e){const r=Ph(e),t=e.subscriber,a=Eh(t.non_subscriptions),n=Object.entries(e.subscriber.non_subscriptions).flatMap(([l,c])=>c.map(d=>({transactionIdentifier:d.id,productIdentifier:l,purchaseDate:new Date(d.purchase_date||d.original_purchase_date),storeTransactionId:d.store_transaction_id||null,store:d.store}))),i=new Date(e.request_date),s=Object.fromEntries(Object.entries(e.subscriber.subscriptions).map(([l,c])=>[l,{productIdentifier:l,purchaseDate:new Date(c.purchase_date),originalPurchaseDate:st(c.original_purchase_date),expiresDate:st(c.expires_date),store:c.store,unsubscribeDetectedAt:st(c.unsubscribe_detected_at),isSandbox:c.is_sandbox,billingIssuesDetectedAt:st(c.billing_issues_detected_at),gracePeriodExpiresDate:st(c.grace_period_expires_date),ownershipType:c.ownership_type??"UNKNOWN",periodType:c.period_type,refundedAt:st(c.refunded_at),storeTransactionId:c.store_transaction_id||null,isActive:ol(c.expires_date),willRenew:il(c.expires_date,c)}]));return{entitlements:kh(t.entitlements,t.subscriptions,a),allExpirationDatesByProduct:r,allPurchaseDatesByProduct:wh(e,a),activeSubscriptions:xh(r),managementURL:t.management_url,requestDate:i,firstSeenDate:new Date(t.first_seen),originalPurchaseDate:st(t.original_purchase_date),originalAppUserId:e.subscriber.original_app_user_id,nonSubscriptionTransactions:n,subscriptionsByProductIdentifier:s}}function il(e,r){if(r==null)return!1;const t=r.store=="promotional",a=e==null,n=r.unsubscribe_detected_at!=null,i=r.billing_issues_detected_at!=null;return!(t||a||n||i)}function wh(e,r){const t={};for(const a in e.subscriber.subscriptions){const n=e.subscriber.subscriptions[a];t[a]=new Date(n.purchase_date)}for(const a in r){const n=r[a].purchase_date;n==null?t[a]=null:t[a]=new Date(n)}return t}function Ph(e){const r={};for(const t in e.subscriber.subscriptions){const a=e.subscriber.subscriptions[t];a.expires_date==null?r[t]=null:r[t]=new Date(a.expires_date)}return r}function xh(e){const r=new Set,t=new Date;for(const a in e){const n=e[a];(n==null||n>t)&&r.add(a)}return r}function Eh(e){const r={};for(const t in e){if(e[t].length===0)continue;const a=e[t].length;r[t]=e[t][a-1]}return r}const sl="1.17.1",Sh="https://api.revenuecat.com",Th="https://e.revenue.cat";var An;(function(e){e[e.CONTINUE=100]="CONTINUE",e[e.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",e[e.PROCESSING=102]="PROCESSING",e[e.EARLY_HINTS=103]="EARLY_HINTS",e[e.OK=200]="OK",e[e.CREATED=201]="CREATED",e[e.ACCEPTED=202]="ACCEPTED",e[e.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",e[e.NO_CONTENT=204]="NO_CONTENT",e[e.RESET_CONTENT=205]="RESET_CONTENT",e[e.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",e[e.MULTI_STATUS=207]="MULTI_STATUS",e[e.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",e[e.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",e[e.MOVED_TEMPORARILY=302]="MOVED_TEMPORARILY",e[e.SEE_OTHER=303]="SEE_OTHER",e[e.NOT_MODIFIED=304]="NOT_MODIFIED",e[e.USE_PROXY=305]="USE_PROXY",e[e.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",e[e.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.UNAUTHORIZED=401]="UNAUTHORIZED",e[e.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",e[e.FORBIDDEN=403]="FORBIDDEN",e[e.NOT_FOUND=404]="NOT_FOUND",e[e.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",e[e.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",e[e.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",e[e.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",e[e.CONFLICT=409]="CONFLICT",e[e.GONE=410]="GONE",e[e.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",e[e.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",e[e.REQUEST_TOO_LONG=413]="REQUEST_TOO_LONG",e[e.REQUEST_URI_TOO_LONG=414]="REQUEST_URI_TOO_LONG",e[e.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",e[e.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",e[e.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",e[e.IM_A_TEAPOT=418]="IM_A_TEAPOT",e[e.INSUFFICIENT_SPACE_ON_RESOURCE=419]="INSUFFICIENT_SPACE_ON_RESOURCE",e[e.METHOD_FAILURE=420]="METHOD_FAILURE",e[e.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",e[e.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",e[e.LOCKED=423]="LOCKED",e[e.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",e[e.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",e[e.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",e[e.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",e[e.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",e[e.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",e[e.BAD_GATEWAY=502]="BAD_GATEWAY",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",e[e.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",e[e.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",e[e.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",e[e.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED"})(An||(An={}));const Ih=/^rcb_[a-zA-Z0-9_.-]+$/,qh=/^pdl_[a-zA-Z0-9_.-]+$/,Dh=/^test_[a-zA-Z0-9_.-]+$/;function zn(e){return e?e.startsWith("rcb_sb_"):!1}function Fh(e){return e?Ih.test(e):!1}function Ah(e){return e?qh.test(e):!1}function Ct(e){return e?Dh.test(e):!1}async function zr(e,r,t){const{apiKey:a,body:n,headers:i,httpConfig:s}=r,c=`${(s==null?void 0:s.proxyURL)??Sh}${e.urlPath()}`;try{const d=await fetch(c,{method:e.method,headers:fl(a,i,s==null?void 0:s.additionalHeaders),body:Mh(n),signal:t});return await zh(d,e),await d.json()}catch(d){throw d instanceof TypeError?new Fe(Ce.NetworkError,Zt.getPublicMessage(Ce.NetworkError),d.message):d}}async function zh(e,r){const t=e.status;if(t>=An.INTERNAL_SERVER_ERROR)Lo(r,t,await e.text());else if(t>=An.BAD_REQUEST){const a=await e.json(),n=a?JSON.stringify(a):null,i=a==null?void 0:a.code,s=a==null?void 0:a.message;if(i!=null){const l=Zt.convertCodeToBackendErrorCode(i);if(l==null)Lo(r,t,n,i);else throw Fe.getForBackendError(l,s)}else Lo(r,t,n)}}function Lo(e,r,t,a){throw new Fe(Ce.UnknownBackendError,"Unknown backend error.",`Request: ${e.name}. Status code: ${r}. Body: ${t}.`,{backendErrorCode:a})}function Mh(e){return e==null?null:JSON.stringify(e)}const ll="Authorization",cl="Content-Type",dl="Accept",ul="X-Platform",pl="X-Version",_l="X-Platform-Flavor",gl="X-Platform-Flavor-Version",ml="X-Is-Sandbox",Ch=new Set([ll,cl,dl,ul,pl,ml,_l,gl]);function fl(e,r,t){let a={[ll]:`Bearer ${e}`,[cl]:"application/json",[dl]:"application/json",[ul]:"web",[pl]:sl,[ml]:`${zn(e)}`};const n=On.getPlatformInfo();if(n){const i={[_l]:n.flavor,[gl]:n.version};a={...a,...i}}return r&&(a={...a,...r}),t&&(a={...t,...a}),a}const Ua="/v1/subscribers",ta="/rcbilling/v1";class jh{constructor(r){L(this,"appUserId");L(this,"method","GET");L(this,"name","getOfferings");this.appUserId=r}urlPath(){const r=encodeURIComponent(this.appUserId);return`${Ua}/${r}/offerings`}}class Nh{constructor(r,t,a){L(this,"method","GET");L(this,"name","getProducts");L(this,"appUserId");L(this,"productIds");L(this,"currency");this.appUserId=r,this.productIds=t,this.currency=a}urlPath(){const r=encodeURIComponent(this.appUserId),t=this.productIds.map(encodeURIComponent).join("&id="),a=this.currency?`¤cy=${this.currency}`:"";return`${ta}/subscribers/${r}/products?id=${t}${a}`}}class Oh{constructor(r){L(this,"method","GET");L(this,"name","getCustomerInfo");L(this,"appUserId");this.appUserId=r}urlPath(){const r=encodeURIComponent(this.appUserId);return`${Ua}/${r}`}}class Lh{constructor(){L(this,"method","POST");L(this,"name","identify")}urlPath(){return`${Ua}/identify`}}class Bh{constructor(){L(this,"method","GET");L(this,"name","getBrandingInfo")}urlPath(){return`${ta}/branding`}}class Rh{constructor(){L(this,"method","POST");L(this,"name","postCheckoutStart")}urlPath(){return`${ta}/checkout/start`}}class Uh{constructor(r){L(this,"method","POST");L(this,"name","postCheckoutCalculateTax");L(this,"operationSessionId");this.operationSessionId=r}urlPath(){return`${ta}/checkout/${this.operationSessionId}/calculate_taxes`}}class Vh{constructor(r){L(this,"method","POST");L(this,"name","postCheckoutComplete");L(this,"operationSessionId");this.operationSessionId=r}urlPath(){return`${ta}/checkout/${this.operationSessionId}/complete`}}class Wh{constructor(r){L(this,"method","GET");L(this,"name","getCheckoutStatus");L(this,"operationSessionId");this.operationSessionId=r}urlPath(){return`${ta}/checkout/${this.operationSessionId}`}}class Hh{constructor(r){L(this,"method","POST");L(this,"name","setAttributes");L(this,"appUserId");this.appUserId=r}urlPath(){const r=encodeURIComponent(this.appUserId);return`${Ua}/${r}/attributes`}}class $h{constructor(){L(this,"method","POST");L(this,"name","postReceipt")}urlPath(){return"/v1/receipts"}}class Yh{constructor(r){L(this,"method","GET");L(this,"name","getVirtualCurrencies");L(this,"appUserId");this.appUserId=r}urlPath(){const r=encodeURIComponent(this.appUserId);return`${Ua}/${r}/virtual_currencies`}}const Bo={};class Gh{constructor(r,t=Bo){L(this,"API_KEY");L(this,"httpConfig");L(this,"isSandbox");this.API_KEY=r,this.httpConfig=t,this.isSandbox=zn(r)}getIsSandbox(){return this.isSandbox}async getOfferings(r){return await zr(new jh(r),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async getCustomerInfo(r){return await zr(new Oh(r),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async identify(r,t){const a={app_user_id:r,new_app_user_id:t};return await zr(new Lh,{apiKey:this.API_KEY,body:a,httpConfig:this.httpConfig})}async getProducts(r,t,a){return await zr(new Nh(r,t,a),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async getBrandingInfo(){return await zr(new Bh,{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async postCheckoutStart(r,t,a,n,i,s,l=void 0){const c={app_user_id:r,product_id:t,email:s,price_id:n.priceId,presented_offering_identifier:a.offeringIdentifier,trace_id:i};return l&&(c.metadata=l),n.id!=="base_option"&&(c.offer_id=n.id),a.targetingContext&&(c.applied_targeting_rule={rule_id:a.targetingContext.ruleId,revision:a.targetingContext.revision}),a.placementIdentifier&&(c.presented_placement_identifier=a.placementIdentifier),await zr(new Rh,{apiKey:this.API_KEY,body:c,httpConfig:this.httpConfig})}async postCheckoutCalculateTax(r,t,a,n){const i={country_code:t,postal_code:a};return await zr(new Uh(r),{apiKey:this.API_KEY,body:i,httpConfig:this.httpConfig},n)}async postCheckoutComplete(r,t){const a={email:t};return await zr(new Vh(r),{apiKey:this.API_KEY,body:a,httpConfig:this.httpConfig})}async getCheckoutStatus(r){return await zr(new Wh(r),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async setAttributes(r,t){const a=Date.now(),n={};for(const[s,l]of Object.entries(t))n[s]={value:l,updated_at_ms:a};const i={attributes:n};return await zr(new Hh(r),{apiKey:this.API_KEY,body:i,httpConfig:this.httpConfig})}async postReceipt(r,t,a,n,i,s){let l=null;i.targetingContext&&(l={rule_id:i.targetingContext.ruleId,revision:i.targetingContext.revision});const c={fetch_token:n,product_id:t,currency:a,app_user_id:r,presented_offering_identifier:i.offeringIdentifier,presented_placement_identifier:i.placementIdentifier,applied_targeting_rule:l,initiation_source:s};return await zr(new $h,{apiKey:this.API_KEY,body:c,httpConfig:this.httpConfig})}async getVirtualCurrencies(r){return await zr(new Yh(r),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}}function Xh(e,r){if(!(Fh(e)||Ct(e)||Ah(e)&&(r==null?void 0:r.allowPaddleAPIKey)))throw new Fe(Ce.InvalidCredentialsError,"Invalid API key. Use your Web Billing API key.")}function Ro(e){if(!e||new Set(["no_user","null","none","nil","(null)","NaN","\\x00","","unidentified","undefined","unknown"]).has(e)||e.includes("/"))throw new Fe(Ce.InvalidAppUserIdError,'Provided user id: "'+(e??"[Not provided]")+'" is not valid. See https://www.revenuecat.com/docs/customers/user-ids#tips-for-setting-app-user-ids for more information.')}function Kh(e){if(e!=null&&e.endsWith("/"))throw new Fe(Ce.ConfigurationError,"Invalid proxy URL. The proxy URL should not end with a trailing slash.")}function Zh(e){if(e){for(const r in e)if(Ch.has(r))throw new Fe(Ce.ConfigurationError,"Invalid additional headers. Some headers are reserved for internal use.")}}var Uo=(e=>(e.Current="current",e))(Uo||{});function Jh(e,r){async function t(...a){return await this.preload(),await e.call(this,...a)}return t}const hl=(e,r)=>{const t={...e.webBillingProduct,presentedOfferingContext:{...e.webBillingProduct.presentedOfferingContext,placementIdentifier:r}};return{...e,webBillingProduct:t,rcBillingProduct:t}},jt=(e,r)=>e==null?null:hl(e,r),Qh=(e,r,t)=>{const a=e.offering_ids_by_placement??null;if(a==null)return null;const n=e.fallback_offering_id??null;let i;if(t in a){const l=a[t]??null;if(l==null)return null;i=r[l],i==null&&(i=r[n])}else i=r[n];if(i==null)return null;const s=Object.fromEntries(Object.entries(i.packagesById).map(([l,c])=>[l,hl(c,t)]));return{...i,packagesById:s,availablePackages:Object.values(s),weekly:jt(i.weekly,t),monthly:jt(i.monthly,t),twoMonth:jt(i.twoMonth,t),threeMonth:jt(i.threeMonth,t),sixMonth:jt(i.sixMonth,t),annual:jt(i.annual,t),lifetime:jt(i.lifetime,t)}};function ey(e,r){const t={};r.product_details.forEach(i=>{t[i.identifier]=i});const a={};e.offerings.forEach(i=>{const s=i.identifier===e.current_offering_id,l=gm(s,i,t,e.targeting,e.ui_config);l!=null&&(a[i.identifier]=l)});const n=e.current_offering_id?a[e.current_offering_id]??null:null;return Object.keys(a).length==0&&ae.debugLog("Empty offerings. Please make sure you've configured offerings correctly in the RevenueCat dashboard and that the products are properly configured."),{all:a,current:n}}const ry=1000001,Vo=7,Mn=30,Wo=365,Cn=4.33,Ho=52,jn=12;function ty(e){switch(e.unit){case re.Year:return e.number*Wo;case re.Month:return e.number*Mn;case re.Week:return e.number*Vo;case re.Day:return e.number}}function ay(e){switch(e.unit){case re.Year:return e.number*Ho;case re.Month:return e.number*Cn;case re.Week:return e.number;case re.Day:return 0}}function ny(e){switch(e.unit){case re.Year:return e.number*jn;case re.Month:return e.number;case re.Week:case re.Day:return 0}}function oy(e){switch(e.unit){case re.Year:return e.number;case re.Month:case re.Week:case re.Day:return 0}}function $o(e,r){const{unit:t,number:a}=e;return{period:r.translatePeriodUnit(t,{noWhitespace:!0})??"",periodAbbreviated:r.translatePeriodUnit(t,{noWhitespace:!0,short:!0})??"",periodWithUnit:r.translatePeriod(a,t)??"",periodInDays:ty(e).toString(),periodInWeeks:ay(e).toString(),periodInMonths:ny(e).toString(),periodInYears:oy(e).toString()}}function iy(e,r,t){const a=t.formatPrice(e.amountMicros,e.currency);return r?r.unit===re.Year?t.formatPrice(e.amountMicros/Wo/r.number,e.currency):r.unit===re.Month?t.formatPrice(e.amountMicros/Mn/r.number,e.currency):r.unit===re.Week?t.formatPrice(e.amountMicros/Vo/r.number,e.currency):r.unit===re.Day?t.formatPrice(e.amountMicros/r.number,e.currency):a:a}function sy(e,r,t){const a=t.formatPrice(e.amountMicros,e.currency);return r?r.unit===re.Year?t.formatPrice(e.amountMicros/Ho/r.number,e.currency):r.unit===re.Month?t.formatPrice(e.amountMicros/Cn/r.number,e.currency):r.unit===re.Week?t.formatPrice(e.amountMicros/r.number,e.currency):r.unit===re.Day?t.formatPrice(e.amountMicros*Vo/r.number,e.currency):a:a}function ly(e,r,t){return r?r.unit===re.Year?t.formatPrice(e.amountMicros/jn,e.currency):r.unit===re.Month?t.formatPrice(e.amountMicros/r.number,e.currency):r.unit===re.Week?t.formatPrice(e.amountMicros*Cn/r.number,e.currency):r.unit===re.Day?t.formatPrice(e.amountMicros*Mn/r.number,e.currency):t.formatPrice(e.amountMicros/(r.number||1),e.currency):t.formatPrice(e.amountMicros,e.currency)}function cy(e,r,t){const a=t.formatPrice(e.amountMicros,e.currency);return r?r.unit===re.Year?t.formatPrice(e.amountMicros/r.number,e.currency):r.unit===re.Month?t.formatPrice(e.amountMicros*jn/r.number,e.currency):r.unit===re.Week?t.formatPrice(e.amountMicros*Ho/r.number,e.currency):r.unit===re.Day?t.formatPrice(e.amountMicros*Wo/r.number,e.currency):a:a}function yl(e,r,t){return{pricePerDay:iy(e,r,t),pricePerWeek:sy(e,r,t),pricePerMonth:ly(e,r,t),pricePerYear:cy(e,r,t)}}function dy(e,r){const t=new Date;switch(e.unit){case re.Year:t.setFullYear(t.getFullYear()+e.number);break;case re.Month:t.setMonth(t.getMonth()+e.number);break;case re.Week:t.setDate(t.getDate()+e.number*7);break;case re.Day:t.setDate(t.getDate()+e.number);break}return r.translateDate(t,{dateStyle:"long"})??""}function uy(e,r,t){const a=e.trial??e.introPrice,n=e.trial?e.introPrice:null;if(a===null)return;const{period:i,price:s}=a;if(s!==null){const l=yl(s,i,r);t["product.offer_price"]=r.formatPrice(s.amountMicros,s.currency),t["product.offer_price_per_day"]=l.pricePerDay,t["product.offer_price_per_week"]=l.pricePerWeek,t["product.offer_price_per_month"]=l.pricePerMonth,t["product.offer_price_per_year"]=l.pricePerYear}if(i!==null){const l=$o(i,r);t["product.offer_period"]=l.period,t["product.offer_period_abbreviated"]=l.periodAbbreviated,t["product.offer_period_with_unit"]=l.periodWithUnit,t["product.offer_period_in_days"]=l.periodInDays,t["product.offer_period_in_weeks"]=l.periodInWeeks,t["product.offer_period_in_months"]=l.periodInMonths,t["product.offer_period_in_years"]=l.periodInYears,t["product.offer_end_date"]=dy(i,r)}if(n!==null&&(n.price!==null&&(t["product.secondary_offer_price"]=r.formatPrice(n.price.amountMicros,n.price.currency)),n.period!==null)){const l=$o(n.period,r);t["product.secondary_offer_period"]=l.period,t["product.secondary_offer_period_abbreviated"]=l.periodAbbreviated}}function Nn(e){var n;const r=e.webBillingProduct.price,t=vl(e),a=e.webBillingProduct.period||((n=t==null?void 0:t.base)==null?void 0:n.period);if(!a||!a.number||a.number<=0)return r.amountMicros;switch(a.unit){case re.Year:return r.amountMicros/jn;case re.Month:return r.amountMicros/a.number;case re.Week:return r.amountMicros*Cn/a.number;case re.Day:return r.amountMicros*Mn/a.number;default:return r.amountMicros/(a.number||1)}}function vl(e){return e.webBillingProduct.productType===it.Subscription?e.webBillingProduct.defaultSubscriptionOption:e.webBillingProduct.defaultPurchaseOption}function py(e,r){return e===it.Subscription&&r!=null}function bl(e,r,t,a=!1){return t.translate(Y.PaywallVariablesPricePerPeriod,{formattedPrice:e,period:r.base.period?r.base.period.number===1?t.translatePeriodUnit(r.base.period.unit,{noWhitespace:!0,short:!a}):t.translatePeriod(r.base.period.number,r.base.period.unit,{noWhitespace:!0,short:!a}):""})}function _y(e,r){const t=e.availablePackages,a=t.reduce((n,i)=>{const s=Nn(n),l=Nn(i);return s>l?n:i});return t.reduce((n,i)=>(n[i.identifier]=gy(i,a,r),n),{})}function gy(e,r,t){const a=e.webBillingProduct,n=a.price,i=t.formatPrice(n.amountMicros,n.currency),s=vl(e),l=a.productType,c={"product.store_product_name":a.title,"product.price":i,"product.price_per_period":"","product.price_per_period_abbreviated":"","product.price_per_day":"","product.price_per_week":"","product.price_per_month":"","product.price_per_year":"","product.period":"","product.period_abbreviated":"","product.periodly":"","product.period_in_days":"","product.period_in_weeks":"","product.period_in_months":"","product.period_in_years":"","product.period_with_unit":"","product.currency_code":n.currency,"product.currency_symbol":t.formatPrice(0,n.currency).replace("0",""),"product.offer_price":"","product.offer_price_per_day":"","product.offer_price_per_week":"","product.offer_price_per_month":"","product.offer_price_per_year":"","product.offer_period":"","product.offer_period_abbreviated":"","product.offer_period_in_days":"","product.offer_period_in_weeks":"","product.offer_period_in_months":"","product.offer_period_in_years":"","product.offer_period_with_unit":"","product.offer_end_date":"","product.secondary_offer_price":"","product.secondary_offer_period":"","product.secondary_offer_period_abbreviated":"","product.relative_discount":""};if(py(l,s)){c["product.price_per_period_abbreviated"]=bl(i,s,t),c["product.price_per_period"]=bl(i,s,t,!0);const d=a.period||s.base.period,u=yl(n,d,t);if(c["product.price_per_day"]=u.pricePerDay,c["product.price_per_week"]=u.pricePerWeek,c["product.price_per_month"]=u.pricePerMonth,c["product.price_per_year"]=u.pricePerYear,d){const f=$o(d,t);c["product.period"]=f.period,c["product.period_abbreviated"]=f.periodAbbreviated,c["product.period_with_unit"]=f.periodWithUnit,c["product.period_in_days"]=f.periodInDays,c["product.period_in_weeks"]=f.periodInWeeks,c["product.period_in_months"]=f.periodInMonths,c["product.period_in_years"]=f.periodInYears,c["product.periodly"]=t.translatePeriodFrequency(d.number,d.unit)||""}const p=Nn(e),_=Nn(r),m=(_-p)*100/_;c["product.relative_discount"]=m<1?"":t.translate(Y.PaywallVariablesSubRelativeDiscount,{discount:m.toFixed(0)}),uy(s,t,c)}return(l===it.NonConsumable||l===it.Consumable)&&s&&(c["product.price"]=i,c["product.price_per_period"]=i,c["product.price_per_period_abbreviated"]=i,c["product.price_per_month"]=i,c["product.period_with_unit"]=t.translate(Y.PeriodsLifetime),c["product.period_in_months"]=t.translate(Y.PeriodsLifetime),c["product.periodly"]=t.translate(Y.PeriodsLifetime),c["product.price_per_week"]="",c["product.relative_discount"]="",c["product.period"]="",c["product.period_abbreviated"]=""),c}function kl(e){for(let r=0;r<e.length;r++)e[r]=Math.floor(Math.random()*256)}function Va(){const e=typeof crypto<"u"?crypto:globalThis.crypto;if(e&&e.randomUUID)return e.randomUUID();const r=new Uint8Array(16);try{e&&e.getRandomValues?e.getRandomValues(r):kl(r)}catch(a){console.log(`Error using crypto.getRandomValues(), falling back to Math.random. + ${a}`),kl(r)}r[6]=r[6]&15|64,r[8]=r[8]&63|128;const t=Array.from(r).map(a=>a.toString(16).padStart(2,"0"));return[t.slice(0,4).join(""),t.slice(4,6).join(""),t.slice(6,8).join(""),t.slice(8,10).join(""),t.slice(10,16).join("")].join("-")}var my=/(%?)(%([sdijo]))/g;function fy(e,r){switch(r){case"s":return e;case"d":case"i":return Number(e);case"j":return JSON.stringify(e);case"o":{if(typeof e=="string")return e;const t=JSON.stringify(e);return t==="{}"||t==="[]"||/^\[object .+?\]$/.test(t)?e:t}}}function Yo(e,...r){if(r.length===0)return e;let t=0,a=e.replace(my,(n,i,s,l)=>{const c=r[t],d=fy(c,l);return i?n:(t++,d)});return t<r.length&&(a+=` ${r.slice(t).join(" ")}`),a=a.replace(/%{2,2}/g,"%"),a}var hy=2;function yy(e){if(!e.stack)return;const r=e.stack.split(`
|
|
338
|
+
}`};function ph(e,r){G(r,!0),Q(e,uh);const t=w=>w==null||w==null||w==""?null:w,a=g(()=>{var w;return t((w=r.brandingInfo)==null?void 0:w.app_icon)}),n=g(()=>{var w;return t((w=r.brandingInfo)==null?void 0:w.app_icon_webp)}),i=g(()=>{var w;return t((w=r.brandingInfo)==null?void 0:w.app_wordmark)}),s=g(()=>{var w;return t((w=r.brandingInfo)==null?void 0:w.app_wordmark_webp)}),l=g(()=>o(a)?Ra(o(a)):null),c=g(()=>o(n)?Ra(o(n)):null),d=g(()=>o(i)?Ra(o(i)):null),u=g(()=>o(s)?Ra(o(s)):null),p=()=>{r.onClose&&r.onClose()};var _=dh(),m=E(_);{var f=w=>{var T=lh(),I=E(T);ah(I,{$$events:{click:p}}),v(w,T)};B(m,w=>{r.showCloseButton&&w(f)})}var h=M(m,2),b=E(h),y=E(b);{var P=w=>{sh(w,{get src(){return o(d)},get srcWebp(){return o(u)}})},x=w=>{var T=ce(),I=ee(T);{var k=D=>{eh(D,{get src(){return o(l)},get srcWebp(){return o(c)}})};B(I,D=>{o(l)!==null&&o(c)!==null&&D(k)},!0)}v(w,T)};B(y,w=>{o(d)!==null?w(P):w(x,!1)})}var z=M(y,2);{var S=w=>{de(w,{size:"body-base",children:(T,I)=>{var k=Se();C(()=>{var D;return le(k,(D=r.brandingInfo)==null?void 0:D.app_name)}),v(T,k)},$$slots:{default:!0}})};B(z,w=>{o(d)===null&&w(S)})}var q=M(h,2);{var O=w=>{var T=ch(),I=E(T);nl(I,{$$events:{click:p}}),v(w,T)};B(q,w=>{r.showCloseButton&&w(O)})}C(()=>Et(_,"rcb-with-close-button",r.showCloseButton)),v(e,_),X()}var _h=A("<!> <!> <!> <!>",1);function gh(e,r){G(r,!0);const t=V(r,"onClose",3,void 0),a=Zs(r.productDetails,r.purchaseOptionToUse);let n=J($(r.defaultPriceBreakdown??{currency:a.currency,totalAmountInMicros:a.amountMicros,totalExcludingTaxInMicros:a.amountMicros,taxCalculationStatus:"unavailable",taxAmountInMicros:null,taxBreakdown:null}));const i=s=>{F(n,$(s))};Xf(e,{get brandingInfo(){return r.brandingInfo},get isInElement(){return r.isInElement},get isSandbox(){return r.isSandbox},get onClose(){return t()},navbarHeaderContent:d=>{var u=g(()=>!r.isInElement&&!!t());ph(d,{get brandingInfo(){return r.brandingInfo},get onClose(){return t()},get showCloseButton(){return o(u)}})},navbarBodyContent:d=>{var u=g(()=>{var p,_;return((_=(p=r.brandingInfo)==null?void 0:p.appearance)==null?void 0:_.show_product_description)??!1});gf(d,{get productDetails(){return r.productDetails},get purchaseOption(){return r.purchaseOptionToUse},get showProductDescription(){return o(u)},get priceBreakdown(){return o(n)}})},mainContent:d=>{var u=_h(),p=ee(u);{var _=x=>{Bm(x)};B(p,x=>{r.currentPage==="payment-entry-loading"&&x(_)})}var m=M(p,2);{var f=x=>{om(x,{get productDetails(){return r.productDetails},get purchaseOption(){return r.purchaseOptionToUse},get brandingInfo(){return r.brandingInfo},get purchaseOperationHelper(){return r.purchaseOperationHelper},get gatewayParams(){return r.gatewayParams},get managementUrl(){return r.managementUrl},get customerEmail(){return r.customerEmail},get defaultPriceBreakdown(){return r.defaultPriceBreakdown},get onContinue(){return r.onContinue},get onError(){return r.onError},onPriceBreakdownUpdated:i})};B(m,x=>{r.currentPage==="payment-entry"&&x(f)})}var h=M(m,2);{var b=x=>{var z=g(()=>{var q;return((q=r.brandingInfo)==null?void 0:q.support_email)??null}),S=g(()=>{var q;return((q=r.brandingInfo)==null?void 0:q.app_name)??null});Om(x,{get lastError(){return r.lastError},get productDetails(){return r.productDetails},get supportEmail(){return o(z)},get onDismiss(){return r.closeWithError},get appName(){return o(S)}})};B(h,x=>{r.currentPage==="error"&&x(b)})}var y=M(h,2);{var P=x=>{Lm(x,{get onContinue(){return r.onContinue}})};B(y,x=>{r.currentPage==="success"&&x(P)})}v(d,u)},$$slots:{navbarHeaderContent:!0,navbarBodyContent:!0,mainContent:!0}}),X()}function mh(e){return e.trim()===""?"You need to provide your email address to continue.":e.match(/^[^@]+@[^@]+\.[^@]+$/)?null:"Email is not valid. Please provide a valid email address."}function fh(e){if(e&&!e.match(/^[A-Z]{3}$/)){const r=`Currency code ${e} is not valid. Please provide a valid ISO 4217 currency code.`;throw ae.errorLog(r),new Fe(Ce.ConfigurationError,r)}}function hh(e,r){var O;G(r,!0);const t=V(r,"customTranslations",19,()=>({})),a=V(r,"skipSuccessPage",3,!1),n=r.customerEmail?mh(r.customerEmail):null;let i=J($(n?void 0:r.customerEmail)),s=r.rcPackage.webBillingProduct,l=J(null);const c=r.rcPackage.webBillingProduct.identifier??null;let d=J("payment-entry-loading"),u=J(null),p=J($({})),_=J(null),m=J(null),f=J(null),h=J(null),b=new hn(t(),r.selectedLocale,r.defaultLocale),y=yn(b);Kr(kr,y),Kr(Io,(O=r.brandingInfo)==null?void 0:O.appearance),sr(()=>{r.isInElement||(F(m,$(document.documentElement.style.height)),F(f,$(document.documentElement.style.overflow)),F(h,$(document.body.style.height)),document.documentElement.style.height="100%",document.body.style.height="100%",document.documentElement.style.overflow="hidden")}),Ia(()=>{if(!r.isInElement){const w=(T,I,k)=>{k===""?T.style.removeProperty(I):T.style.setProperty(I,k)};w(document.documentElement,"height",o(m)),w(document.body,"height",o(h)),w(document.documentElement,"overflow",o(f))}}),Kr(To,r.eventsTracker),sr(async()=>{if(c===null){x(new qe(we.ErrorSettingUpPurchase,"Product ID was not set before purchase."));return}r.purchaseOperationHelper.checkoutStart(r.appUserId,c,r.purchaseOption,r.rcPackage.webBillingProduct.presentedOfferingContext,o(i),r.metadata).then(w=>{F(l,null),F(d,"payment-entry"),F(p,$(w.gateway_params)),F(_,$(w.management_url))}).catch(w=>{if(w.errorCode===we.MissingEmailError)return F(i,void 0),r.purchaseOperationHelper.checkoutStart(r.appUserId,c,r.purchaseOption,r.rcPackage.webBillingProduct.presentedOfferingContext,o(i),r.metadata).then(T=>{F(l,null),F(d,"payment-entry"),F(p,$(T.gateway_params)),F(_,$(T.management_url))}).catch(T=>{x(T)});x(w)})});const P=()=>{if(o(d)==="payment-entry"){r.purchaseOperationHelper.pollCurrentPurchaseForCompletion().then(w=>{F(u,$(w)),a()?r.onFinished(w):F(d,"success")}).catch(w=>{x(w)});return}if(o(d)==="success"||o(d)==="error"){r.onFinished(o(u));return}F(d,"success")},x=w=>{const T=$_({errorCode:w.getErrorCode().toString(),errorMessage:w.message});r.eventsTracker.trackSDKEvent(T),F(l,$(w)),F(d,"error")},z=()=>{r.onError(o(l)??new qe(we.UnknownError,"Unknown error without state set."))};var S=g(()=>r.purchases.isSandbox()),q=g(()=>o(i)??null);gh(e,{get isSandbox(){return o(S)},get currentPage(){return o(d)},get brandingInfo(){return r.brandingInfo},productDetails:s,get purchaseOptionToUse(){return r.purchaseOption},get lastError(){return o(l)},get gatewayParams(){return o(p)},get managementUrl(){return o(_)},get purchaseOperationHelper(){return r.purchaseOperationHelper},get isInElement(){return r.isInElement},get customerEmail(){return o(q)},closeWithError:z,onContinue:P,onError:x,get onClose(){return r.onClose}}),X()}function ol(e){return e==null?!0:new Date(e)>new Date}function yh(e,r,t,a){const n=r.product_identifier;if(n in t)return vh(e,r,t[n]);if(n in a)return bh(e,r,a[n]);throw new Fe(Ce.CustomerInfoError,"Could not find entitlement product in subscriptions or non-subscriptions.")}function vh(e,r,t){return{identifier:e,isActive:ol(r.expires_date),willRenew:il(r.expires_date,t),store:(t==null?void 0:t.store)??"unknown",latestPurchaseDate:new Date(r.purchase_date),originalPurchaseDate:new Date(r.purchase_date),expirationDate:st(r.expires_date),productIdentifier:r.product_identifier,productPlanIdentifier:r.product_plan_identifier??null,unsubscribeDetectedAt:st(t==null?void 0:t.unsubscribe_detected_at),billingIssueDetectedAt:st(t==null?void 0:t.billing_issues_detected_at),isSandbox:(t==null?void 0:t.is_sandbox)??!1,periodType:(t==null?void 0:t.period_type)??"normal",ownershipType:(t==null?void 0:t.ownership_type)??"UNKNOWN"}}function bh(e,r,t){return{identifier:e,isActive:!0,willRenew:!1,store:t.store,latestPurchaseDate:new Date(r.purchase_date),originalPurchaseDate:new Date(t.original_purchase_date),expirationDate:null,productIdentifier:r.product_identifier,productPlanIdentifier:null,unsubscribeDetectedAt:null,billingIssueDetectedAt:null,isSandbox:t.is_sandbox,periodType:"normal",ownershipType:"UNKNOWN"}}function kh(e,r,t){const a={},n={};for(const i in e){const s=yh(i,e[i],r,t);a[i]=s,s.isActive&&(n[i]=s)}return{all:a,active:n}}function st(e){return e==null?null:new Date(e)}function Oo(e){const r=Ph(e),t=e.subscriber,a=Eh(t.non_subscriptions),n=Object.entries(e.subscriber.non_subscriptions).flatMap(([l,c])=>c.map(d=>({transactionIdentifier:d.id,productIdentifier:l,purchaseDate:new Date(d.purchase_date||d.original_purchase_date),storeTransactionId:d.store_transaction_id||null,store:d.store}))),i=new Date(e.request_date),s=Object.fromEntries(Object.entries(e.subscriber.subscriptions).map(([l,c])=>[l,{productIdentifier:l,purchaseDate:new Date(c.purchase_date),originalPurchaseDate:st(c.original_purchase_date),expiresDate:st(c.expires_date),store:c.store,unsubscribeDetectedAt:st(c.unsubscribe_detected_at),isSandbox:c.is_sandbox,billingIssuesDetectedAt:st(c.billing_issues_detected_at),gracePeriodExpiresDate:st(c.grace_period_expires_date),ownershipType:c.ownership_type??"UNKNOWN",periodType:c.period_type,refundedAt:st(c.refunded_at),storeTransactionId:c.store_transaction_id||null,isActive:ol(c.expires_date),willRenew:il(c.expires_date,c)}]));return{entitlements:kh(t.entitlements,t.subscriptions,a),allExpirationDatesByProduct:r,allPurchaseDatesByProduct:wh(e,a),activeSubscriptions:xh(r),managementURL:t.management_url,requestDate:i,firstSeenDate:new Date(t.first_seen),originalPurchaseDate:st(t.original_purchase_date),originalAppUserId:e.subscriber.original_app_user_id,nonSubscriptionTransactions:n,subscriptionsByProductIdentifier:s}}function il(e,r){if(r==null)return!1;const t=r.store=="promotional",a=e==null,n=r.unsubscribe_detected_at!=null,i=r.billing_issues_detected_at!=null;return!(t||a||n||i)}function wh(e,r){const t={};for(const a in e.subscriber.subscriptions){const n=e.subscriber.subscriptions[a];t[a]=new Date(n.purchase_date)}for(const a in r){const n=r[a].purchase_date;n==null?t[a]=null:t[a]=new Date(n)}return t}function Ph(e){const r={};for(const t in e.subscriber.subscriptions){const a=e.subscriber.subscriptions[t];a.expires_date==null?r[t]=null:r[t]=new Date(a.expires_date)}return r}function xh(e){const r=new Set,t=new Date;for(const a in e){const n=e[a];(n==null||n>t)&&r.add(a)}return r}function Eh(e){const r={};for(const t in e){if(e[t].length===0)continue;const a=e[t].length;r[t]=e[t][a-1]}return r}const sl="1.18.0",Sh="https://api.revenuecat.com",Th="https://e.revenue.cat";var An;(function(e){e[e.CONTINUE=100]="CONTINUE",e[e.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",e[e.PROCESSING=102]="PROCESSING",e[e.EARLY_HINTS=103]="EARLY_HINTS",e[e.OK=200]="OK",e[e.CREATED=201]="CREATED",e[e.ACCEPTED=202]="ACCEPTED",e[e.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",e[e.NO_CONTENT=204]="NO_CONTENT",e[e.RESET_CONTENT=205]="RESET_CONTENT",e[e.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",e[e.MULTI_STATUS=207]="MULTI_STATUS",e[e.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",e[e.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",e[e.MOVED_TEMPORARILY=302]="MOVED_TEMPORARILY",e[e.SEE_OTHER=303]="SEE_OTHER",e[e.NOT_MODIFIED=304]="NOT_MODIFIED",e[e.USE_PROXY=305]="USE_PROXY",e[e.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",e[e.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.UNAUTHORIZED=401]="UNAUTHORIZED",e[e.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",e[e.FORBIDDEN=403]="FORBIDDEN",e[e.NOT_FOUND=404]="NOT_FOUND",e[e.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",e[e.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",e[e.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",e[e.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",e[e.CONFLICT=409]="CONFLICT",e[e.GONE=410]="GONE",e[e.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",e[e.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",e[e.REQUEST_TOO_LONG=413]="REQUEST_TOO_LONG",e[e.REQUEST_URI_TOO_LONG=414]="REQUEST_URI_TOO_LONG",e[e.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",e[e.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",e[e.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",e[e.IM_A_TEAPOT=418]="IM_A_TEAPOT",e[e.INSUFFICIENT_SPACE_ON_RESOURCE=419]="INSUFFICIENT_SPACE_ON_RESOURCE",e[e.METHOD_FAILURE=420]="METHOD_FAILURE",e[e.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",e[e.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",e[e.LOCKED=423]="LOCKED",e[e.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",e[e.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",e[e.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",e[e.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",e[e.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",e[e.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",e[e.BAD_GATEWAY=502]="BAD_GATEWAY",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",e[e.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",e[e.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",e[e.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",e[e.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED"})(An||(An={}));const Ih=/^rcb_[a-zA-Z0-9_.-]+$/,qh=/^pdl_[a-zA-Z0-9_.-]+$/,Dh=/^test_[a-zA-Z0-9_.-]+$/;function zn(e){return e?e.startsWith("rcb_sb_"):!1}function Fh(e){return e?Ih.test(e):!1}function Ah(e){return e?qh.test(e):!1}function Ct(e){return e?Dh.test(e):!1}async function zr(e,r,t){const{apiKey:a,body:n,headers:i,httpConfig:s}=r,c=`${(s==null?void 0:s.proxyURL)??Sh}${e.urlPath()}`;try{const d=await fetch(c,{method:e.method,headers:fl(a,i,s==null?void 0:s.additionalHeaders),body:Mh(n),signal:t});return await zh(d,e),await d.json()}catch(d){throw d instanceof TypeError?new Fe(Ce.NetworkError,Zt.getPublicMessage(Ce.NetworkError),d.message):d}}async function zh(e,r){const t=e.status;if(t>=An.INTERNAL_SERVER_ERROR)Lo(r,t,await e.text());else if(t>=An.BAD_REQUEST){const a=await e.json(),n=a?JSON.stringify(a):null,i=a==null?void 0:a.code,s=a==null?void 0:a.message;if(i!=null){const l=Zt.convertCodeToBackendErrorCode(i);if(l==null)Lo(r,t,n,i);else throw Fe.getForBackendError(l,s)}else Lo(r,t,n)}}function Lo(e,r,t,a){throw new Fe(Ce.UnknownBackendError,"Unknown backend error.",`Request: ${e.name}. Status code: ${r}. Body: ${t}.`,{backendErrorCode:a})}function Mh(e){return e==null?null:JSON.stringify(e)}const ll="Authorization",cl="Content-Type",dl="Accept",ul="X-Platform",pl="X-Version",_l="X-Platform-Flavor",gl="X-Platform-Flavor-Version",ml="X-Is-Sandbox",Ch=new Set([ll,cl,dl,ul,pl,ml,_l,gl]);function fl(e,r,t){let a={[ll]:`Bearer ${e}`,[cl]:"application/json",[dl]:"application/json",[ul]:"web",[pl]:sl,[ml]:`${zn(e)}`};const n=On.getPlatformInfo();if(n){const i={[_l]:n.flavor,[gl]:n.version};a={...a,...i}}return r&&(a={...a,...r}),t&&(a={...t,...a}),a}const Ua="/v1/subscribers",ta="/rcbilling/v1";class jh{constructor(r){L(this,"appUserId");L(this,"method","GET");L(this,"name","getOfferings");this.appUserId=r}urlPath(){const r=encodeURIComponent(this.appUserId);return`${Ua}/${r}/offerings`}}class Nh{constructor(r,t,a){L(this,"method","GET");L(this,"name","getProducts");L(this,"appUserId");L(this,"productIds");L(this,"currency");this.appUserId=r,this.productIds=t,this.currency=a}urlPath(){const r=encodeURIComponent(this.appUserId),t=this.productIds.map(encodeURIComponent).join("&id="),a=this.currency?`¤cy=${this.currency}`:"";return`${ta}/subscribers/${r}/products?id=${t}${a}`}}class Oh{constructor(r){L(this,"method","GET");L(this,"name","getCustomerInfo");L(this,"appUserId");this.appUserId=r}urlPath(){const r=encodeURIComponent(this.appUserId);return`${Ua}/${r}`}}class Lh{constructor(){L(this,"method","POST");L(this,"name","identify")}urlPath(){return`${Ua}/identify`}}class Bh{constructor(){L(this,"method","GET");L(this,"name","getBrandingInfo")}urlPath(){return`${ta}/branding`}}class Rh{constructor(){L(this,"method","POST");L(this,"name","postCheckoutStart")}urlPath(){return`${ta}/checkout/start`}}class Uh{constructor(r){L(this,"method","POST");L(this,"name","postCheckoutCalculateTax");L(this,"operationSessionId");this.operationSessionId=r}urlPath(){return`${ta}/checkout/${this.operationSessionId}/calculate_taxes`}}class Vh{constructor(r){L(this,"method","POST");L(this,"name","postCheckoutComplete");L(this,"operationSessionId");this.operationSessionId=r}urlPath(){return`${ta}/checkout/${this.operationSessionId}/complete`}}class Wh{constructor(r){L(this,"method","GET");L(this,"name","getCheckoutStatus");L(this,"operationSessionId");this.operationSessionId=r}urlPath(){return`${ta}/checkout/${this.operationSessionId}`}}class Hh{constructor(r){L(this,"method","POST");L(this,"name","setAttributes");L(this,"appUserId");this.appUserId=r}urlPath(){const r=encodeURIComponent(this.appUserId);return`${Ua}/${r}/attributes`}}class $h{constructor(){L(this,"method","POST");L(this,"name","postReceipt")}urlPath(){return"/v1/receipts"}}class Yh{constructor(r){L(this,"method","GET");L(this,"name","getVirtualCurrencies");L(this,"appUserId");this.appUserId=r}urlPath(){const r=encodeURIComponent(this.appUserId);return`${Ua}/${r}/virtual_currencies`}}const Bo={};class Gh{constructor(r,t=Bo){L(this,"API_KEY");L(this,"httpConfig");L(this,"isSandbox");this.API_KEY=r,this.httpConfig=t,this.isSandbox=zn(r)}getIsSandbox(){return this.isSandbox}async getOfferings(r){return await zr(new jh(r),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async getCustomerInfo(r){return await zr(new Oh(r),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async identify(r,t){const a={app_user_id:r,new_app_user_id:t};return await zr(new Lh,{apiKey:this.API_KEY,body:a,httpConfig:this.httpConfig})}async getProducts(r,t,a){return await zr(new Nh(r,t,a),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async getBrandingInfo(){return await zr(new Bh,{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async postCheckoutStart(r,t,a,n,i,s,l=void 0){const c={app_user_id:r,product_id:t,email:s,price_id:n.priceId,presented_offering_identifier:a.offeringIdentifier,trace_id:i};return l&&(c.metadata=l),n.id!=="base_option"&&(c.offer_id=n.id),a.targetingContext&&(c.applied_targeting_rule={rule_id:a.targetingContext.ruleId,revision:a.targetingContext.revision}),a.placementIdentifier&&(c.presented_placement_identifier=a.placementIdentifier),await zr(new Rh,{apiKey:this.API_KEY,body:c,httpConfig:this.httpConfig})}async postCheckoutCalculateTax(r,t,a,n){const i={country_code:t,postal_code:a};return await zr(new Uh(r),{apiKey:this.API_KEY,body:i,httpConfig:this.httpConfig},n)}async postCheckoutComplete(r,t){const a={email:t};return await zr(new Vh(r),{apiKey:this.API_KEY,body:a,httpConfig:this.httpConfig})}async getCheckoutStatus(r){return await zr(new Wh(r),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}async setAttributes(r,t){const a=Date.now(),n={};for(const[s,l]of Object.entries(t))n[s]={value:l,updated_at_ms:a};const i={attributes:n};return await zr(new Hh(r),{apiKey:this.API_KEY,body:i,httpConfig:this.httpConfig})}async postReceipt(r,t,a,n,i,s){let l=null;i.targetingContext&&(l={rule_id:i.targetingContext.ruleId,revision:i.targetingContext.revision});const c={fetch_token:n,product_id:t,currency:a,app_user_id:r,presented_offering_identifier:i.offeringIdentifier,presented_placement_identifier:i.placementIdentifier,applied_targeting_rule:l,initiation_source:s};return await zr(new $h,{apiKey:this.API_KEY,body:c,httpConfig:this.httpConfig})}async getVirtualCurrencies(r){return await zr(new Yh(r),{apiKey:this.API_KEY,httpConfig:this.httpConfig})}}function Xh(e,r){if(!(Fh(e)||Ct(e)||Ah(e)&&(r==null?void 0:r.allowPaddleAPIKey)))throw new Fe(Ce.InvalidCredentialsError,"Invalid API key. Use your Web Billing API key.")}function Ro(e){if(!e||new Set(["no_user","null","none","nil","(null)","NaN","\\x00","","unidentified","undefined","unknown"]).has(e)||e.includes("/"))throw new Fe(Ce.InvalidAppUserIdError,'Provided user id: "'+(e??"[Not provided]")+'" is not valid. See https://www.revenuecat.com/docs/customers/user-ids#tips-for-setting-app-user-ids for more information.')}function Kh(e){if(e!=null&&e.endsWith("/"))throw new Fe(Ce.ConfigurationError,"Invalid proxy URL. The proxy URL should not end with a trailing slash.")}function Zh(e){if(e){for(const r in e)if(Ch.has(r))throw new Fe(Ce.ConfigurationError,"Invalid additional headers. Some headers are reserved for internal use.")}}var Uo=(e=>(e.Current="current",e))(Uo||{});function Jh(e,r){async function t(...a){return await this.preload(),await e.call(this,...a)}return t}const hl=(e,r)=>{const t={...e.webBillingProduct,presentedOfferingContext:{...e.webBillingProduct.presentedOfferingContext,placementIdentifier:r}};return{...e,webBillingProduct:t,rcBillingProduct:t}},jt=(e,r)=>e==null?null:hl(e,r),Qh=(e,r,t)=>{const a=e.offering_ids_by_placement??null;if(a==null)return null;const n=e.fallback_offering_id??null;let i;if(t in a){const l=a[t]??null;if(l==null)return null;i=r[l],i==null&&(i=r[n])}else i=r[n];if(i==null)return null;const s=Object.fromEntries(Object.entries(i.packagesById).map(([l,c])=>[l,hl(c,t)]));return{...i,packagesById:s,availablePackages:Object.values(s),weekly:jt(i.weekly,t),monthly:jt(i.monthly,t),twoMonth:jt(i.twoMonth,t),threeMonth:jt(i.threeMonth,t),sixMonth:jt(i.sixMonth,t),annual:jt(i.annual,t),lifetime:jt(i.lifetime,t)}};function ey(e,r){const t={};r.product_details.forEach(i=>{t[i.identifier]=i});const a={};e.offerings.forEach(i=>{const s=i.identifier===e.current_offering_id,l=gm(s,i,t,e.targeting,e.ui_config);l!=null&&(a[i.identifier]=l)});const n=e.current_offering_id?a[e.current_offering_id]??null:null;return Object.keys(a).length==0&&ae.debugLog("Empty offerings. Please make sure you've configured offerings correctly in the RevenueCat dashboard and that the products are properly configured."),{all:a,current:n}}const ry=1000001,Vo=7,Mn=30,Wo=365,Cn=4.33,Ho=52,jn=12;function ty(e){switch(e.unit){case re.Year:return e.number*Wo;case re.Month:return e.number*Mn;case re.Week:return e.number*Vo;case re.Day:return e.number}}function ay(e){switch(e.unit){case re.Year:return e.number*Ho;case re.Month:return e.number*Cn;case re.Week:return e.number;case re.Day:return 0}}function ny(e){switch(e.unit){case re.Year:return e.number*jn;case re.Month:return e.number;case re.Week:case re.Day:return 0}}function oy(e){switch(e.unit){case re.Year:return e.number;case re.Month:case re.Week:case re.Day:return 0}}function $o(e,r){const{unit:t,number:a}=e;return{period:r.translatePeriodUnit(t,{noWhitespace:!0})??"",periodAbbreviated:r.translatePeriodUnit(t,{noWhitespace:!0,short:!0})??"",periodWithUnit:r.translatePeriod(a,t)??"",periodInDays:ty(e).toString(),periodInWeeks:ay(e).toString(),periodInMonths:ny(e).toString(),periodInYears:oy(e).toString()}}function iy(e,r,t){const a=t.formatPrice(e.amountMicros,e.currency);return r?r.unit===re.Year?t.formatPrice(e.amountMicros/Wo/r.number,e.currency):r.unit===re.Month?t.formatPrice(e.amountMicros/Mn/r.number,e.currency):r.unit===re.Week?t.formatPrice(e.amountMicros/Vo/r.number,e.currency):r.unit===re.Day?t.formatPrice(e.amountMicros/r.number,e.currency):a:a}function sy(e,r,t){const a=t.formatPrice(e.amountMicros,e.currency);return r?r.unit===re.Year?t.formatPrice(e.amountMicros/Ho/r.number,e.currency):r.unit===re.Month?t.formatPrice(e.amountMicros/Cn/r.number,e.currency):r.unit===re.Week?t.formatPrice(e.amountMicros/r.number,e.currency):r.unit===re.Day?t.formatPrice(e.amountMicros*Vo/r.number,e.currency):a:a}function ly(e,r,t){return r?r.unit===re.Year?t.formatPrice(e.amountMicros/jn,e.currency):r.unit===re.Month?t.formatPrice(e.amountMicros/r.number,e.currency):r.unit===re.Week?t.formatPrice(e.amountMicros*Cn/r.number,e.currency):r.unit===re.Day?t.formatPrice(e.amountMicros*Mn/r.number,e.currency):t.formatPrice(e.amountMicros/(r.number||1),e.currency):t.formatPrice(e.amountMicros,e.currency)}function cy(e,r,t){const a=t.formatPrice(e.amountMicros,e.currency);return r?r.unit===re.Year?t.formatPrice(e.amountMicros/r.number,e.currency):r.unit===re.Month?t.formatPrice(e.amountMicros*jn/r.number,e.currency):r.unit===re.Week?t.formatPrice(e.amountMicros*Ho/r.number,e.currency):r.unit===re.Day?t.formatPrice(e.amountMicros*Wo/r.number,e.currency):a:a}function yl(e,r,t){return{pricePerDay:iy(e,r,t),pricePerWeek:sy(e,r,t),pricePerMonth:ly(e,r,t),pricePerYear:cy(e,r,t)}}function dy(e,r){const t=new Date;switch(e.unit){case re.Year:t.setFullYear(t.getFullYear()+e.number);break;case re.Month:t.setMonth(t.getMonth()+e.number);break;case re.Week:t.setDate(t.getDate()+e.number*7);break;case re.Day:t.setDate(t.getDate()+e.number);break}return r.translateDate(t,{dateStyle:"long"})??""}function uy(e,r,t){const a=e.trial??e.introPrice,n=e.trial?e.introPrice:null;if(a===null)return;const{period:i,price:s}=a;if(s!==null){const l=yl(s,i,r);t["product.offer_price"]=r.formatPrice(s.amountMicros,s.currency),t["product.offer_price_per_day"]=l.pricePerDay,t["product.offer_price_per_week"]=l.pricePerWeek,t["product.offer_price_per_month"]=l.pricePerMonth,t["product.offer_price_per_year"]=l.pricePerYear}if(i!==null){const l=$o(i,r);t["product.offer_period"]=l.period,t["product.offer_period_abbreviated"]=l.periodAbbreviated,t["product.offer_period_with_unit"]=l.periodWithUnit,t["product.offer_period_in_days"]=l.periodInDays,t["product.offer_period_in_weeks"]=l.periodInWeeks,t["product.offer_period_in_months"]=l.periodInMonths,t["product.offer_period_in_years"]=l.periodInYears,t["product.offer_end_date"]=dy(i,r)}if(n!==null&&(n.price!==null&&(t["product.secondary_offer_price"]=r.formatPrice(n.price.amountMicros,n.price.currency)),n.period!==null)){const l=$o(n.period,r);t["product.secondary_offer_period"]=l.period,t["product.secondary_offer_period_abbreviated"]=l.periodAbbreviated}}function Nn(e){var n;const r=e.webBillingProduct.price,t=vl(e),a=e.webBillingProduct.period||((n=t==null?void 0:t.base)==null?void 0:n.period);if(!a||!a.number||a.number<=0)return r.amountMicros;switch(a.unit){case re.Year:return r.amountMicros/jn;case re.Month:return r.amountMicros/a.number;case re.Week:return r.amountMicros*Cn/a.number;case re.Day:return r.amountMicros*Mn/a.number;default:return r.amountMicros/(a.number||1)}}function vl(e){return e.webBillingProduct.productType===it.Subscription?e.webBillingProduct.defaultSubscriptionOption:e.webBillingProduct.defaultPurchaseOption}function py(e,r){return e===it.Subscription&&r!=null}function bl(e,r,t,a=!1){return t.translate(Y.PaywallVariablesPricePerPeriod,{formattedPrice:e,period:r.base.period?r.base.period.number===1?t.translatePeriodUnit(r.base.period.unit,{noWhitespace:!0,short:!a}):t.translatePeriod(r.base.period.number,r.base.period.unit,{noWhitespace:!0,short:!a}):""})}function _y(e,r){const t=e.availablePackages,a=t.reduce((n,i)=>{const s=Nn(n),l=Nn(i);return s>l?n:i});return t.reduce((n,i)=>(n[i.identifier]=gy(i,a,r),n),{})}function gy(e,r,t){const a=e.webBillingProduct,n=a.price,i=t.formatPrice(n.amountMicros,n.currency),s=vl(e),l=a.productType,c={"product.store_product_name":a.title,"product.price":i,"product.price_per_period":"","product.price_per_period_abbreviated":"","product.price_per_day":"","product.price_per_week":"","product.price_per_month":"","product.price_per_year":"","product.period":"","product.period_abbreviated":"","product.periodly":"","product.period_in_days":"","product.period_in_weeks":"","product.period_in_months":"","product.period_in_years":"","product.period_with_unit":"","product.currency_code":n.currency,"product.currency_symbol":t.formatPrice(0,n.currency).replace("0",""),"product.offer_price":"","product.offer_price_per_day":"","product.offer_price_per_week":"","product.offer_price_per_month":"","product.offer_price_per_year":"","product.offer_period":"","product.offer_period_abbreviated":"","product.offer_period_in_days":"","product.offer_period_in_weeks":"","product.offer_period_in_months":"","product.offer_period_in_years":"","product.offer_period_with_unit":"","product.offer_end_date":"","product.secondary_offer_price":"","product.secondary_offer_period":"","product.secondary_offer_period_abbreviated":"","product.relative_discount":""};if(py(l,s)){c["product.price_per_period_abbreviated"]=bl(i,s,t),c["product.price_per_period"]=bl(i,s,t,!0);const d=a.period||s.base.period,u=yl(n,d,t);if(c["product.price_per_day"]=u.pricePerDay,c["product.price_per_week"]=u.pricePerWeek,c["product.price_per_month"]=u.pricePerMonth,c["product.price_per_year"]=u.pricePerYear,d){const f=$o(d,t);c["product.period"]=f.period,c["product.period_abbreviated"]=f.periodAbbreviated,c["product.period_with_unit"]=f.periodWithUnit,c["product.period_in_days"]=f.periodInDays,c["product.period_in_weeks"]=f.periodInWeeks,c["product.period_in_months"]=f.periodInMonths,c["product.period_in_years"]=f.periodInYears,c["product.periodly"]=t.translatePeriodFrequency(d.number,d.unit)||""}const p=Nn(e),_=Nn(r),m=(_-p)*100/_;c["product.relative_discount"]=m<1?"":t.translate(Y.PaywallVariablesSubRelativeDiscount,{discount:m.toFixed(0)}),uy(s,t,c)}return(l===it.NonConsumable||l===it.Consumable)&&s&&(c["product.price"]=i,c["product.price_per_period"]=i,c["product.price_per_period_abbreviated"]=i,c["product.price_per_month"]=i,c["product.period_with_unit"]=t.translate(Y.PeriodsLifetime),c["product.period_in_months"]=t.translate(Y.PeriodsLifetime),c["product.periodly"]=t.translate(Y.PeriodsLifetime),c["product.price_per_week"]="",c["product.relative_discount"]="",c["product.period"]="",c["product.period_abbreviated"]=""),c}function kl(e){for(let r=0;r<e.length;r++)e[r]=Math.floor(Math.random()*256)}function Va(){const e=typeof crypto<"u"?crypto:globalThis.crypto;if(e&&e.randomUUID)return e.randomUUID();const r=new Uint8Array(16);try{e&&e.getRandomValues?e.getRandomValues(r):kl(r)}catch(a){console.log(`Error using crypto.getRandomValues(), falling back to Math.random. + ${a}`),kl(r)}r[6]=r[6]&15|64,r[8]=r[8]&63|128;const t=Array.from(r).map(a=>a.toString(16).padStart(2,"0"));return[t.slice(0,4).join(""),t.slice(4,6).join(""),t.slice(6,8).join(""),t.slice(8,10).join(""),t.slice(10,16).join("")].join("-")}var my=/(%?)(%([sdijo]))/g;function fy(e,r){switch(r){case"s":return e;case"d":case"i":return Number(e);case"j":return JSON.stringify(e);case"o":{if(typeof e=="string")return e;const t=JSON.stringify(e);return t==="{}"||t==="[]"||/^\[object .+?\]$/.test(t)?e:t}}}function Yo(e,...r){if(r.length===0)return e;let t=0,a=e.replace(my,(n,i,s,l)=>{const c=r[t],d=fy(c,l);return i?n:(t++,d)});return t<r.length&&(a+=` ${r.slice(t).join(" ")}`),a=a.replace(/%{2,2}/g,"%"),a}var hy=2;function yy(e){if(!e.stack)return;const r=e.stack.split(`
|
|
339
339
|
`);r.splice(1,hy),e.stack=r.join(`
|
|
340
340
|
`)}var vy=class extends Error{constructor(e,...r){super(e),this.message=e,this.name="Invariant Violation",this.message=Yo(e,...r),yy(this)}},wl=(e,r,...t)=>{if(!e)throw new vy(r,...t)};wl.as=(e,r,t,...a)=>{if(!r){const n=a.length===0?t:Yo(t,...a);let i;try{i=Reflect.construct(e,[n])}catch{i=e(n)}throw i}};const by="[MSW]";function Go(e,...r){const t=Yo(e,...r);return`${by} ${t}`}function ky(e,...r){console.warn(Go(e,...r))}function wy(e,...r){console.error(Go(e,...r))}const Py={formatMessage:Go,warn:ky,error:wy};function xy(){wl(typeof URL<"u",Py.formatMessage(`Global "URL" class is not defined. This likely means that you're running MSW in an environment that doesn't support all Node.js standard API (e.g. React Native). If that's the case, please use an appropriate polyfill for the "URL" class, like "react-native-url-polyfill".`))}var Pl=(e=>(e.HEAD="HEAD",e.GET="GET",e.POST="POST",e.PUT="PUT",e.PATCH="PATCH",e.OPTIONS="OPTIONS",e.DELETE="DELETE",e))(Pl||{});xy();class Ey{constructor(r,t,a,n){L(this,"initialDelay");L(this,"maxDelay");L(this,"jitterPercent");L(this,"callback");L(this,"currentDelay");L(this,"timeoutId");L(this,"executingCallback",!1);this.initialDelay=r,this.currentDelay=r,this.maxDelay=t,this.jitterPercent=a,this.callback=n}tryFlush(){if(this.backingOff()){ae.debugLog("Backing off, not flushing");return}this.clearTimeout(),this.executeCallbackWithRetries()}stop(){this.clearTimeout()}schedule(r){if(this.timeoutId!==void 0)return;const t=this.addJitter(r||this.currentDelay);this.timeoutId=setTimeout(()=>{this.timeoutId=void 0,this.executeCallbackWithRetries()},t)}backoff(){const r=this.currentDelay,t=Math.min(this.currentDelay*2,this.maxDelay);ae.debugLog(`Backing next off to ${r}ms delay`),this.clearTimeout(),this.currentDelay=t,this.schedule(r)}reset(){this.currentDelay!==this.initialDelay&&(this.clearTimeout(),this.currentDelay=this.initialDelay)}async executeCallbackWithRetries(){if(this.executingCallback){ae.debugLog("Callback already running, rescheduling"),this.schedule();return}this.executingCallback=!0;try{await this.callback(),this.reset()}catch{this.backoff()}finally{this.executingCallback=!1}}backingOff(){return this.currentDelay>this.initialDelay}clearTimeout(){clearTimeout(this.timeoutId),this.timeoutId=void 0}addJitter(r){const t=r*this.jitterPercent,a=r-t,n=r+t;return Math.floor(Math.random()*(n-a+1)+a)}}function xl(e){const r={};for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const a=t.replace(/([A-Z])/g,"_$1").toLowerCase(),n=e[t];n&&typeof n=="object"&&!Array.isArray(n)?r[a]=xl(n):r[a]=n}return r}class Sy{constructor(r){L(this,"EVENT_TYPE","web_billing");L(this,"id");L(this,"timestampMs");L(this,"data");this.id=Va(),this.timestampMs=Date.now(),this.data=r}toJSON(){return xl({id:this.id,timestampMs:this.timestampMs,type:this.EVENT_TYPE,eventName:this.data.eventName,appUserId:this.data.appUserId,context:{...this.data.context},properties:{...this.data.properties,traceId:this.data.traceId}})}}function Ty(e,r){const t=new URLSearchParams(window.location.search);let a=null,n=null;typeof screen<"u"&&screen&&(a=screen.width,n=screen.height);let i=null,s=null;return typeof document<"u"&&document&&(i=document.referrer,s=document.title),{libraryName:"purchases-js",libraryVersion:sl,locale:navigator.language,userAgent:navigator.userAgent,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,screenWidth:a,screenHeight:n,utmSource:t.get("utm_source")??null,utmMedium:t.get("utm_medium")??null,utmCampaign:t.get("utm_campaign")??null,utmContent:t.get("utm_content")??null,utmTerm:t.get("utm_term")??null,pageReferrer:i,pageUrl:`${window.location.origin}${window.location.pathname}`,pageTitle:s,source:e,rcSource:r}}const Iy=2e3,qy=5*6e4,Dy=.1;class Fy{constructor(r){L(this,"apiKey");L(this,"eventsQueue",[]);L(this,"eventsUrl");L(this,"flushManager");L(this,"traceId",Va());L(this,"appUserId");L(this,"isSilent");L(this,"rcSource");this.apiKey=r.apiKey,this.eventsUrl=`${Th}/v1/events`,this.appUserId=r.appUserId,this.isSilent=r.silent||!1,this.rcSource=r.rcSource,this.flushManager=new Ey(Iy,qy,Dy,this.flushEvents.bind(this))}async updateUser(r){this.appUserId=r}getTraceId(){return this.traceId}trackSDKEvent(r){this.trackEvent({...r,source:"sdk"})}trackExternalEvent(r){this.trackEvent({...r})}trackEvent(r){if(this.isSilent){ae.verboseLog("Skipping event tracking, the EventsTracker is silent");return}try{const t=new Sy({eventName:r.eventName,traceId:this.traceId,appUserId:this.appUserId,context:Ty(r.source,this.rcSource),properties:r.properties||{}});this.eventsQueue.push(t),this.flushManager.tryFlush()}catch(t){ae.errorLog(`Error while tracking event ${r.eventName}: ${t}`)}}dispose(){this.flushManager.stop()}flushEvents(){if(this.eventsQueue.length===0)return Promise.resolve();const r=[...this.eventsQueue];return fetch(this.eventsUrl,{method:Pl.POST,headers:fl(this.apiKey),body:JSON.stringify({events:r})}).then(t=>{if(t.status===200||t.status===201){this.eventsQueue.splice(0,r.length);return}else throw ae.debugLog("Events failed to flush due to server error"),new Error("Events failed to flush due to server error")}).catch(t=>{throw ae.debugLog("Error while flushing events"),t})}}const Ay=()=>{const e=new URLSearchParams(window.location.search),r=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],t={};return r.forEach(a=>{const n=e.get(a);n!==null&&(t[a]=n)}),t},zy=["app","embedded"],Xo={autoCollectUTMAsMetadata:!0,collectAnalyticsEvents:!0};var My=A('<p class="svelte-11vxb6p"><strong>Free Trial:</strong> </p>'),Cy=A('<p class="svelte-11vxb6p"><strong>Intro Price:</strong> </p>'),jy=A('<div class="rc-simulated-store-modal-overlay svelte-11vxb6p"><div class="rc-simulated-store-modal svelte-11vxb6p"><div class="rc-simulated-store-modal-content svelte-11vxb6p"><h2 class="rc-simulated-store-modal-title svelte-11vxb6p">Test Store Purchase</h2> <div class="rc-simulated-store-modal-details svelte-11vxb6p"><div><p class="svelte-11vxb6p"><strong>Product:</strong> </p> <p class="svelte-11vxb6p"><strong>Type:</strong> </p> <p class="svelte-11vxb6p"><strong>Price:</strong> </p> <!> <!></div></div> <div class="rc-simulated-store-modal-buttons svelte-11vxb6p"><button type="button" class="rc-simulated-store-modal-button rc-simulated-store-modal-button-primary svelte-11vxb6p">Test valid purchase</button> <button type="button" class="rc-simulated-store-modal-button rc-simulated-store-modal-button-secondary svelte-11vxb6p">Test failed purchase</button> <button type="button" class="rc-simulated-store-modal-button rc-simulated-store-modal-button-cancel svelte-11vxb6p">Cancel</button></div></div></div></div>');const Ny={hash:"svelte-11vxb6p",code:`.rc-simulated-store-modal-overlay.svelte-11vxb6p {position:fixed;top:0;left:0;width:100%;height:100%;background-color:rgba(0, 0, 0, 0.5);display:flex;justify-content:center;align-items:center;z-index:9999;}.rc-simulated-store-modal.svelte-11vxb6p {background:white;border-radius:8px;padding:0;max-width:500px;width:90%;max-height:90%;overflow-y:auto;box-shadow:0 4px 20px rgba(0, 0, 0, 0.15);}.rc-simulated-store-modal-content.svelte-11vxb6p {padding:24px;}.rc-simulated-store-modal-title.svelte-11vxb6p {margin:0 0 20px 0;font-size:24px;font-weight:600;color:#333;}.rc-simulated-store-modal-details.svelte-11vxb6p {margin-bottom:24px;}.rc-simulated-store-modal-details.svelte-11vxb6p p:where(.svelte-11vxb6p) {margin:8px 0;color:#666;line-height:1.5;}.rc-simulated-store-modal-buttons.svelte-11vxb6p {display:flex;flex-direction:column;gap:12px;}.rc-simulated-store-modal-button.svelte-11vxb6p {padding:12px 24px;border:none;border-radius:6px;font-size:16px;font-weight:500;cursor:pointer;transition:background-color 0.2s ease;}.rc-simulated-store-modal-button-primary.svelte-11vxb6p {background-color:#007aff;color:white;}.rc-simulated-store-modal-button-primary.svelte-11vxb6p:hover {background-color:#0056cc;}.rc-simulated-store-modal-button-secondary.svelte-11vxb6p {background-color:#ff3b30;color:white;}.rc-simulated-store-modal-button-secondary.svelte-11vxb6p:hover {background-color:#cc2e24;}.rc-simulated-store-modal-button-cancel.svelte-11vxb6p {background-color:#f2f2f7;color:#333;}.rc-simulated-store-modal-button-cancel.svelte-11vxb6p:hover {background-color:#e5e5ea;}
|
|
341
341
|
|
|
342
342
|
/* Mobile responsive - full screen on small screens */
|
|
343
343
|
@media (max-width: 768px) {.rc-simulated-store-modal-overlay.svelte-11vxb6p {padding:0;}.rc-simulated-store-modal.svelte-11vxb6p {width:100%;height:100%;border-radius:0;max-width:none;max-height:none;}.rc-simulated-store-modal-content.svelte-11vxb6p {height:100%;display:flex;flex-direction:column;justify-content:center;}
|
|
344
|
-
}`};function Oy(e,r){G(r,!1),Q(e,Ny);let t=V(r,"productIdentifier",8),a=V(r,"productType",8),n=V(r,"basePrice",8),i=V(r,"freeTrialPeriod",8,void 0),s=V(r,"introPriceFormatted",8,void 0),l=V(r,"onValidPurchase",8),c=V(r,"onFailedPurchase",8),d=V(r,"onCancel",8);function u(N){N.target===N.currentTarget&&d()()}Ir();var p=jy(),_=E(p),m=E(_),f=M(E(m),2),h=E(f),b=E(h),y=M(E(b)),P=M(b,2),x=M(E(P)),z=M(P,2),S=M(E(z)),q=M(z,2);{var O=N=>{var U=My(),Z=M(E(U));C(()=>le(Z,` ${i()??""}`)),v(N,U)};B(q,N=>{i()&&N(O)})}var w=M(q,2);{var T=N=>{var U=Cy(),Z=M(E(U));C(()=>le(Z,` ${s()??""}`)),v(N,U)};B(w,N=>{s()&&N(T)})}var I=M(f,2),k=E(I),D=M(k,2),W=M(D,2);C(()=>{le(y,` ${t()??""}`),le(x,` ${a()??""}`),le(S,` ${n()??""}`)}),Rr("click",k,function(...N){var U;(U=l())==null||U.apply(this,N)}),Rr("click",D,function(...N){var U;(U=c())==null||U.apply(this,N)}),Rr("click",W,function(...N){var U;(U=d())==null||U.apply(this,N)}),Rr("click",p,u),v(e,p),X()}async function El(e,r,t){const a=new Date,n=`test_${a.getTime()}_${Va()}`,i=`test_store_operation_session_${Va()}`,l={storeTransactionId:n,productIdentifier:e.identifier,purchaseDate:a},c=await r.postReceipt(t,e.identifier,e.price.currency,n,e.presentedOfferingContext,"purchase");return{customerInfo:Oo(c),redemptionInfo:null,operationSessionId:i,storeTransaction:l}}function Ly(e,r,t){const a=e.rcPackage.webBillingProduct,n=a.productType,i=a.freeTrialPhase,s=a.introPricePhase,l=a.price,c=d=>d?`${d.number} ${d.unit}${d.number>1?"s":""}`:"N/A";return new Promise((d,u)=>{var f;const p=document.createElement("div");document.body.appendChild(p);const _=()=>{m&&pn(m),document.body.removeChild(p)};let m=null;m=so(Oy,{target:p,props:{productIdentifier:a.identifier,productType:n,basePrice:l.formattedPrice,freeTrialPeriod:i?c(i.period):void 0,introPriceFormatted:(f=s==null?void 0:s.price)==null?void 0:f.formattedPrice,onValidPurchase:async()=>{_(),ae.debugLog("[Test store] Performing test purchase. This purchase won't appear in production.");try{d(await El(a,r,t))}catch(h){u(h)}},onFailedPurchase:()=>{_(),ae.debugLog("[Test store] Purchase failure simulated successfully in Test Store."),u(new Fe(Ce.TestStoreSimulatedPurchaseError,Zt.getPublicMessage(Ce.TestStoreSimulatedPurchaseError),"Simulated error successfully."))},onCancel:()=>{_(),u(new Fe(Ce.UserCancelledError))}}})})}class By{constructor(){L(this,"virtualCurrenciesCache",new Map);L(this,"CACHE_EXPIRY_MS",5*60*1e3)}invalidateAllCaches(){this.virtualCurrenciesCache.clear()}cacheVirtualCurrencies(r,t){this.virtualCurrenciesCache.set(r,{data:t,lastUpdatedAt:Date.now()})}getCachedVirtualCurrencies(r,t=!1){const a=this.virtualCurrenciesCache.get(r);return this.getCachedData(a??null,t)}invalidateVirtualCurrenciesCache(r){this.virtualCurrenciesCache.delete(r)}getCachedData(r,t=!1){return r?t?r.data:Date.now()-r.lastUpdatedAt>=this.CACHE_EXPIRY_MS?null:r.data:null}}function Ry(e){return{balance:e.balance,name:e.name,code:e.code,serverDescription:e.description??null}}function Uy(e){const r={};for(const[t,a]of Object.entries(e.virtual_currencies))r[t]=Ry(a);return{all:r}}function Vy(e){const r=e.webBillingProduct;if(r.productType!==it.Subscription)return{};const t=r.defaultSubscriptionOption;return t?{hasTrial:t.trial!==null,hasIntroOffer:t.introPrice!==null}:{}}function Wy(e){const r=Object.entries(e.packagesById).map(([t,a])=>[t,Vy(a)]);return Object.fromEntries(r)}var Sl=(e=>(e.DisplayName="$displayName",e.Email="$email",e.PhoneNumber="$phoneNumber",e.IDFA="$idfa",e.IDFV="$idfv",e.GPSAdId="$gpsAdId",e.AndroidId="$androidId",e.AmazonAdId="$amazonAdId",e.IP="$ip",e.AdjustId="$adjustId",e.AmplitudeDeviceId="$amplitudeDeviceId",e.AmplitudeUserId="$amplitudeUserId",e.AppsflyerId="$appsflyerId",e.AppsflyerSharingFilter="$appsflyerSharingFilter",e.BranchId="$branchId",e.BrazeAliasName="$brazeAliasName",e.BrazeAliasLabel="$brazeAliasLabel",e.ClevertapId="$clevertapId",e.FbAnonId="$fbAnonId",e.MparticleId="$mparticleId",e.OnesignalId="$onesignalId",e.OnesignalUserId="$onesignalUserId",e.IntercomContactId="$intercomContactId",e.MediaSource="$mediaSource",e.Campaign="$campaign",e.AdGroup="$adGroup",e.AdId="$ad",e.Keyword="$keyword",e.Creative="$creative",e.APNSTokens="$apnsTokens",e.FCMTokens="$fcmTokens",e.AirshipChannelId="$airshipChannelId",e.SegmentId="$segmentId",e.IterableUserId="$iterableUserId",e.IterableCampaignId="$iterableCampaignId",e.IterableTemplateId="$iterableTemplateId",e.FirebaseAppInstanceId="$firebaseAppInstanceId",e.MixpanelDistinctId="$mixpanelDistinctId",e.ATTConsentStatus="$attConsentStatus",e.KochavaDeviceId="$kochavaDeviceId",e.DeviceVersion="$deviceVersion",e.PosthogUserId="$posthogUserId",e.TelemetryDeckUserId="$telemetryDeckUserId",e.TelemetryDeckAppId="$telemetryDeckAppId",e.AppleRefundHandlingPreference="$appleRefundHandlingPreference",e.CustomerioId="$customerioId",e.TenjinId="$tenjinId",e))(Sl||{});const Tl="$RCAnonymousID:";Il=[Jh];const Xe=class Xe{constructor(r,t,a=Bo,n=Xo){jl(Ko,5,this);L(this,"_API_KEY");L(this,"_appUserId");L(this,"_brandingInfo",null);L(this,"_loadingResourcesPromise",null);L(this,"_flags");L(this,"backend");L(this,"purchaseOperationHelper");L(this,"eventsTracker");L(this,"inMemoryCache");this._API_KEY=r,this._appUserId=t,this._flags={...Xo,...n},zn(r)?ae.debugLog("Initializing Purchases SDK with Web billing sandbox API Key"):Ct(r)&&ae.debugLog("Initializing Purchases SDK with RC Test store API Key."),this.eventsTracker=new Fy({apiKey:this._API_KEY,appUserId:this._appUserId,silent:!this._flags.collectAnalyticsEvents,rcSource:this._flags.rcSource??null}),this.backend=new Gh(this._API_KEY,a),this.inMemoryCache=new By,this.purchaseOperationHelper=new rd(this.backend,this.eventsTracker),this.eventsTracker.trackSDKEvent({eventName:fr.SDKInitialized})}static setLogLevel(r){ae.setLogLevel(r)}static setLogHandler(r){ae.setLogHandler(r)}static setPlatformInfo(r){Xe._platformInfo=r}static getPlatformInfo(){return Xe._platformInfo}static getSharedInstance(){if(Xe.isConfigured())return Xe.instance;throw new rs}static isConfigured(){return Xe.instance!==void 0}static configure(r,t,a,n){Xe.instance!==void 0&&ae.warnLog("Purchases is already initialized. You normally should only configure Purchases once. Creating and returning new instance.");let i;if(typeof r=="object"&&r!==null)i=r;else{if(typeof r!="string")throw new Fe(Ce.ConfigurationError,"API key must be provided as a string");if(typeof t!="string")throw new Fe(Ce.ConfigurationError,"App user ID must be provided as a string");i={apiKey:r,appUserId:t,httpConfig:a,flags:n}}return Xe.configureInternal(i),Xe.getSharedInstance()}static configureInternal(r){const{apiKey:t,appUserId:a,httpConfig:n,flags:i}=r,s=n??Bo,l=i??Xo;Xe.validateConfig(r),Xe.instance=new Xe(t,a,s,l)}static validateConfig(r){var t,a;Xh(r.apiKey,r.flags),Ro(r.appUserId),Kh((t=r.httpConfig)==null?void 0:t.proxyURL),Zh((a=r.httpConfig)==null?void 0:a.additionalHeaders)}async preload(){if(this.hasLoadedResources()){ae.verboseLog("Purchases resources are loaded. Skipping.");return}if(this._loadingResourcesPromise!==null){ae.verboseLog("Purchases resources are loading. Waiting."),await this._loadingResourcesPromise;return}return this._loadingResourcesPromise=this.fetchAndCacheBrandingInfo().catch(r=>{let t=`${r}`;r instanceof Fe&&(t=`${r.message}. ${r.underlyingErrorMessage?`Underlying error: ${r.underlyingErrorMessage}`:""}`),ae.errorLog(`Error fetching branding info: ${t}`)}).finally(()=>{this._loadingResourcesPromise=null}),this._loadingResourcesPromise}async fetchAndCacheBrandingInfo(){if(Ct(this._API_KEY)){ae.warnLog("Branding info is not available for RC Test Store API keys.");return}this._brandingInfo=await this.backend.getBrandingInfo()}hasLoadedResources(){return this._brandingInfo!==null}async renderPaywall(r){console.warn("This method is @experimental, Paywalls are not generally available but they will come soon!");let a=r.htmlTarget??document.getElementById("rcb-ui-pw-root");if(a===null){const f=document.createElement("div");f.id="rcb-ui-pw-root",f.className="rcb-ui-pw-root",f.style.zIndex=`${ry}`,document.body.appendChild(f),a=f}if(a===null)throw new Error("Could not generate a mount point for the billing widget");const n=a;n.innerHTML="";const i=r.offering;if(!i.paywallComponents)throw new Error("You cannot use paywalls yet, they are coming soon!");if(!i.uiConfig)throw new Error("No ui_config found for this offering, please contact support!");const s=r.selectedLocale||navigator.language,l=new hn({},s,i.paywallComponents.default_locale),c=f=>{var b;const h=i.availablePackages.find(y=>y.identifier===f);if(h===void 0)throw new Error(`No package found for ${f}`);return this.purchase({rcPackage:h,htmlTarget:r.purchaseHtmlTarget,customerEmail:r.customerEmail,selectedLocale:s,defaultLocale:((b=i.paywallComponents)==null?void 0:b.default_locale)||zt})},d=f=>{var h;if(r.onNavigateToUrl){r.onNavigateToUrl(f);return}(h=window.open(f,"_blank"))==null||h.focus()},u=()=>{},p=()=>{if(r.onVisitCustomerCenter){r.onVisitCustomerCenter();return}},_=_y(i,l),m=Wy(i);return new Promise((f,h)=>{so(xp,{target:n,props:{paywallData:i.paywallComponents,selectedLocale:s,onNavigateToUrlClicked:d,onVisitCustomerCenterClicked:p,uiConfig:i.uiConfig,onBackClicked:()=>{if(r.onBack){r.onBack();return}n.innerHTML="",ae.debugLog("Purchase cancelled by user"),h(new Fe(Ce.UserCancelledError))},onRestorePurchasesClicked:u,onPurchaseClicked:b=>{c(b).then(y=>{f(y)}).catch(y=>h(y))},onError:b=>h(b),variablesPerPackage:_,infoPerPackage:m}})})}async getOfferings(r){fh(r==null?void 0:r.currency);const t=this._appUserId,a=await this.backend.getOfferings(t),n=(r==null?void 0:r.offeringIdentifier)===Uo.Current?a.current_offering_id:r==null?void 0:r.offeringIdentifier;return n&&(a.offerings=a.offerings.filter(i=>i.identifier===n)),await this.getAllOfferings(a,t,r)}async getCurrentOfferingForPlacement(r,t){const a=this._appUserId,n=await this.backend.getOfferings(a),i=await this.getAllOfferings(n,a,t),s=n.placements??null;return s==null?null:Qh(s,i.all,r)}async getAllOfferings(r,t,a){const n=r.offerings.flatMap(s=>s.packages).map(s=>s.platform_product_identifier),i=await this.backend.getProducts(t,n,a==null?void 0:a.currency);return this.logMissingProductIds(n,i.product_details),ey(r,i)}async isEntitledTo(r){const t=await this.getCustomerInfo();return r in t.entitlements.active}purchasePackage(r,t,a){return this.purchase({rcPackage:r,customerEmail:t,htmlTarget:a})}async purchase(r){var z;const{rcPackage:t,purchaseOption:a,htmlTarget:n,customerEmail:i,selectedLocale:s=zt,defaultLocale:l=zt,skipSuccessPage:c=!1}=r;if(Ct(this._API_KEY)){const S=await Ly(r,this.backend,this._appUserId);return this.inMemoryCache.invalidateAllCaches(),S}let d=n??document.getElementById("rcb-ui-root");if(d===null){const S=document.createElement("div");S.className="rcb-ui-root",document.body.appendChild(S),d=S}if(d===null)throw new Error("Could not generate a mount point for the billing widget");const u=d,p=this._appUserId;ae.debugLog(`Presenting purchase form for package ${t.identifier}`);const _=s||l,m=a??t.webBillingProduct.defaultPurchaseOption,f=G_({appearance:(z=this._brandingInfo)==null?void 0:z.appearance,rcPackage:t,purchaseOptionToUse:m,customerEmail:i});this.eventsTracker.trackSDKEvent(f);const b={...this._flags.autoCollectUTMAsMetadata?Ay():{},...r.metadata||{}};let y=null;const P=this._brandingInfo;P&&r.brandingAppearanceOverride&&(P.appearance=r.brandingAppearanceOverride);const x=n!==void 0;return new Promise((S,q)=>{x||window.history.pushState({checkoutOpen:!0},"");const w=this._flags.rcSource&&zy.includes(this._flags.rcSource)?void 0:()=>{const k=K_();this.eventsTracker.trackSDKEvent(k),window.removeEventListener("popstate",w),y&&pn(y),u.innerHTML="",ae.debugLog("Purchase cancelled by user"),q(new Fe(Ce.UserCancelledError))};!x&&w&&window.addEventListener("popstate",w),y=so(hh,{target:u,props:{isInElement:x,appUserId:p,rcPackage:t,purchaseOption:m,customerEmail:i,onFinished:async k=>{const D=X_({redemptionInfo:k.redemptionInfo});this.eventsTracker.trackSDKEvent(D),this.inMemoryCache.invalidateAllCaches(),ae.debugLog("Purchase finished"),y&&pn(y),u.innerHTML="";const W={customerInfo:await this._getCustomerInfoForUserId(p),redemptionInfo:k.redemptionInfo,operationSessionId:k.operationSessionId,storeTransaction:{storeTransactionId:k.storeTransactionIdentifier,productIdentifier:t.webBillingProduct.identifier,purchaseDate:k.purchaseDate}};S(W)},onClose:w,onError:k=>{var W;const D=Z_({errorCode:(W=k.errorCode)==null?void 0:W.toString(),errorMessage:k.message});this.eventsTracker.trackSDKEvent(D),y&&pn(y),u.innerHTML="",q(Fe.getForPurchasesFlowError(k))},purchases:this,eventsTracker:this.eventsTracker,brandingInfo:this._brandingInfo,purchaseOperationHelper:this.purchaseOperationHelper,selectedLocale:_,metadata:b,defaultLocale:l,customTranslations:r.labelsOverride,skipSuccessPage:c}})})}_isConfiguredWithSimulatedStore(){return Ct(this._API_KEY)}async _postSimulatedStoreReceipt(r){if(!Ct(this._API_KEY))throw new Fe(Ce.ConfigurationError,"Posting a test store receipt is only available for RC Test Store API keys.");return await El(r,this.backend,this._appUserId)}async getCustomerInfo(){return await this._getCustomerInfoForUserId(this._appUserId)}getAppUserId(){return this._appUserId}async setAttributes(r){return await this.getCustomerInfo(),await this.backend.setAttributes(this._appUserId,r)}async changeUser(r){return await this.replaceUserId(r),await this.getCustomerInfo()}async identifyUser(r){if(Ro(r),r===this._appUserId)return ae.debugLog(`aliasUser called with the current appUserID: ${r}. Ignoring.`),{customerInfo:await this.getCustomerInfo(),wasCreated:!1};const t=await this.backend.identify(this._appUserId,r);return await this.replaceUserId(r),{customerInfo:Oo(t),wasCreated:t.was_created}}async replaceUserId(r){Ro(r),this._appUserId=r,await this.eventsTracker.updateUser(r),this.inMemoryCache.invalidateAllCaches()}logMissingProductIds(r,t){const a={};t.forEach(i=>a[i.identifier]=i);const n=[];r.forEach(i=>{a[i]===void 0&&n.push(i)}),n.length>0&&ae.debugLog(`Could not find product data for product ids:
|
|
344
|
+
}`};function Oy(e,r){G(r,!1),Q(e,Ny);let t=V(r,"productIdentifier",8),a=V(r,"productType",8),n=V(r,"basePrice",8),i=V(r,"freeTrialPeriod",8,void 0),s=V(r,"introPriceFormatted",8,void 0),l=V(r,"onValidPurchase",8),c=V(r,"onFailedPurchase",8),d=V(r,"onCancel",8);function u(N){N.target===N.currentTarget&&d()()}Ir();var p=jy(),_=E(p),m=E(_),f=M(E(m),2),h=E(f),b=E(h),y=M(E(b)),P=M(b,2),x=M(E(P)),z=M(P,2),S=M(E(z)),q=M(z,2);{var O=N=>{var U=My(),Z=M(E(U));C(()=>le(Z,` ${i()??""}`)),v(N,U)};B(q,N=>{i()&&N(O)})}var w=M(q,2);{var T=N=>{var U=Cy(),Z=M(E(U));C(()=>le(Z,` ${s()??""}`)),v(N,U)};B(w,N=>{s()&&N(T)})}var I=M(f,2),k=E(I),D=M(k,2),W=M(D,2);C(()=>{le(y,` ${t()??""}`),le(x,` ${a()??""}`),le(S,` ${n()??""}`)}),Rr("click",k,function(...N){var U;(U=l())==null||U.apply(this,N)}),Rr("click",D,function(...N){var U;(U=c())==null||U.apply(this,N)}),Rr("click",W,function(...N){var U;(U=d())==null||U.apply(this,N)}),Rr("click",p,u),v(e,p),X()}async function El(e,r,t){const a=new Date,n=`test_${a.getTime()}_${Va()}`,i=`test_store_operation_session_${Va()}`,l={storeTransactionId:n,productIdentifier:e.identifier,purchaseDate:a},c=await r.postReceipt(t,e.identifier,e.price.currency,n,e.presentedOfferingContext,"purchase");return{customerInfo:Oo(c),redemptionInfo:null,operationSessionId:i,storeTransaction:l}}function Ly(e,r,t){const a=e.rcPackage.webBillingProduct,n=a.productType,i=a.freeTrialPhase,s=a.introPricePhase,l=a.price,c=d=>d?`${d.number} ${d.unit}${d.number>1?"s":""}`:"N/A";return new Promise((d,u)=>{var f;const p=document.createElement("div");document.body.appendChild(p);const _=()=>{m&&pn(m),document.body.removeChild(p)};let m=null;m=so(Oy,{target:p,props:{productIdentifier:a.identifier,productType:n,basePrice:l.formattedPrice,freeTrialPeriod:i?c(i.period):void 0,introPriceFormatted:(f=s==null?void 0:s.price)==null?void 0:f.formattedPrice,onValidPurchase:async()=>{_(),ae.debugLog("[Test store] Performing test purchase. This purchase won't appear in production.");try{d(await El(a,r,t))}catch(h){u(h)}},onFailedPurchase:()=>{_(),ae.debugLog("[Test store] Purchase failure simulated successfully in Test Store."),u(new Fe(Ce.TestStoreSimulatedPurchaseError,Zt.getPublicMessage(Ce.TestStoreSimulatedPurchaseError),"Simulated error successfully."))},onCancel:()=>{_(),u(new Fe(Ce.UserCancelledError))}}})})}class By{constructor(){L(this,"virtualCurrenciesCache",new Map);L(this,"CACHE_EXPIRY_MS",5*60*1e3)}invalidateAllCaches(){this.virtualCurrenciesCache.clear()}cacheVirtualCurrencies(r,t){this.virtualCurrenciesCache.set(r,{data:t,lastUpdatedAt:Date.now()})}getCachedVirtualCurrencies(r,t=!1){const a=this.virtualCurrenciesCache.get(r);return this.getCachedData(a??null,t)}invalidateVirtualCurrenciesCache(r){this.virtualCurrenciesCache.delete(r)}getCachedData(r,t=!1){return r?t?r.data:Date.now()-r.lastUpdatedAt>=this.CACHE_EXPIRY_MS?null:r.data:null}}function Ry(e){return{balance:e.balance,name:e.name,code:e.code,serverDescription:e.description??null}}function Uy(e){const r={};for(const[t,a]of Object.entries(e.virtual_currencies))r[t]=Ry(a);return{all:r}}function Vy(e){const r=e.webBillingProduct;if(r.productType!==it.Subscription)return{};const t=r.defaultSubscriptionOption;return t?{hasTrial:t.trial!==null,hasIntroOffer:t.introPrice!==null}:{}}function Wy(e){const r=Object.entries(e.packagesById).map(([t,a])=>[t,Vy(a)]);return Object.fromEntries(r)}var Sl=(e=>(e.DisplayName="$displayName",e.Email="$email",e.PhoneNumber="$phoneNumber",e.IDFA="$idfa",e.IDFV="$idfv",e.GPSAdId="$gpsAdId",e.AndroidId="$androidId",e.AmazonAdId="$amazonAdId",e.IP="$ip",e.AdjustId="$adjustId",e.AmplitudeDeviceId="$amplitudeDeviceId",e.AmplitudeUserId="$amplitudeUserId",e.AppsflyerId="$appsflyerId",e.AppsflyerSharingFilter="$appsflyerSharingFilter",e.BranchId="$branchId",e.BrazeAliasName="$brazeAliasName",e.BrazeAliasLabel="$brazeAliasLabel",e.ClevertapId="$clevertapId",e.FbAnonId="$fbAnonId",e.MparticleId="$mparticleId",e.OnesignalId="$onesignalId",e.OnesignalUserId="$onesignalUserId",e.IntercomContactId="$intercomContactId",e.MediaSource="$mediaSource",e.Campaign="$campaign",e.AdGroup="$adGroup",e.AdId="$ad",e.Keyword="$keyword",e.Creative="$creative",e.APNSTokens="$apnsTokens",e.FCMTokens="$fcmTokens",e.AirshipChannelId="$airshipChannelId",e.SegmentId="$segmentId",e.IterableUserId="$iterableUserId",e.IterableCampaignId="$iterableCampaignId",e.IterableTemplateId="$iterableTemplateId",e.FirebaseAppInstanceId="$firebaseAppInstanceId",e.MixpanelDistinctId="$mixpanelDistinctId",e.ATTConsentStatus="$attConsentStatus",e.KochavaDeviceId="$kochavaDeviceId",e.DeviceVersion="$deviceVersion",e.PosthogUserId="$posthogUserId",e.TelemetryDeckUserId="$telemetryDeckUserId",e.TelemetryDeckAppId="$telemetryDeckAppId",e.AppleRefundHandlingPreference="$appleRefundHandlingPreference",e.CustomerioId="$customerioId",e.TenjinId="$tenjinId",e))(Sl||{});const Tl="$RCAnonymousID:";Il=[Jh];const Xe=class Xe{constructor(r,t,a=Bo,n=Xo){jl(Ko,5,this);L(this,"_API_KEY");L(this,"_appUserId");L(this,"_brandingInfo",null);L(this,"_loadingResourcesPromise",null);L(this,"_flags");L(this,"backend");L(this,"purchaseOperationHelper");L(this,"eventsTracker");L(this,"inMemoryCache");this._API_KEY=r,this._appUserId=t,this._flags={...Xo,...n},zn(r)?ae.debugLog("Initializing Purchases SDK with Web billing sandbox API Key"):Ct(r)&&ae.debugLog("Initializing Purchases SDK with RC Test store API Key."),this.eventsTracker=new Fy({apiKey:this._API_KEY,appUserId:this._appUserId,silent:!this._flags.collectAnalyticsEvents,rcSource:this._flags.rcSource??null}),this.backend=new Gh(this._API_KEY,a),this.inMemoryCache=new By,this.purchaseOperationHelper=new rd(this.backend,this.eventsTracker),this.eventsTracker.trackSDKEvent({eventName:fr.SDKInitialized})}static setLogLevel(r){ae.setLogLevel(r)}static setLogHandler(r){ae.setLogHandler(r)}static setPlatformInfo(r){Xe._platformInfo=r}static getPlatformInfo(){return Xe._platformInfo}static getSharedInstance(){if(Xe.isConfigured())return Xe.instance;throw new rs}static isConfigured(){return Xe.instance!==void 0}static configure(r,t,a,n){Xe.instance!==void 0&&ae.warnLog("Purchases is already initialized. You normally should only configure Purchases once. Creating and returning new instance.");let i;if(typeof r=="object"&&r!==null)i=r;else{if(typeof r!="string")throw new Fe(Ce.ConfigurationError,"API key must be provided as a string");if(typeof t!="string")throw new Fe(Ce.ConfigurationError,"App user ID must be provided as a string");i={apiKey:r,appUserId:t,httpConfig:a,flags:n}}return Xe.configureInternal(i),Xe.getSharedInstance()}static configureInternal(r){const{apiKey:t,appUserId:a,httpConfig:n,flags:i}=r,s=n??Bo,l=i??Xo;Xe.validateConfig(r),Xe.instance=new Xe(t,a,s,l)}static validateConfig(r){var t,a;Xh(r.apiKey,r.flags),Ro(r.appUserId),Kh((t=r.httpConfig)==null?void 0:t.proxyURL),Zh((a=r.httpConfig)==null?void 0:a.additionalHeaders)}async preload(){if(this.hasLoadedResources()){ae.verboseLog("Purchases resources are loaded. Skipping.");return}if(this._loadingResourcesPromise!==null){ae.verboseLog("Purchases resources are loading. Waiting."),await this._loadingResourcesPromise;return}return this._loadingResourcesPromise=this.fetchAndCacheBrandingInfo().catch(r=>{let t=`${r}`;r instanceof Fe&&(t=`${r.message}. ${r.underlyingErrorMessage?`Underlying error: ${r.underlyingErrorMessage}`:""}`),ae.errorLog(`Error fetching branding info: ${t}`)}).finally(()=>{this._loadingResourcesPromise=null}),this._loadingResourcesPromise}async fetchAndCacheBrandingInfo(){if(Ct(this._API_KEY)){ae.warnLog("Branding info is not available for RC Test Store API keys.");return}this._brandingInfo=await this.backend.getBrandingInfo()}hasLoadedResources(){return this._brandingInfo!==null}async presentPaywall(r){let a=r.htmlTarget??document.getElementById("rcb-ui-pw-root");if(a===null){const f=document.createElement("div");f.id="rcb-ui-pw-root",f.className="rcb-ui-pw-root",f.style.zIndex=`${ry}`,document.body.appendChild(f),a=f}if(a===null)throw new Error("Could not generate a mount point for the billing widget");const n=a;n.innerHTML="";const i=r.offering?r.offering:(await this.getOfferings()).current;if(!i)throw new Error("No offering found.");if(!i.paywallComponents)throw new Error("This offering doesn't have a paywall attached.");if(!i.uiConfig)throw new Error("No ui_config found for this offering, please contact support!");const s=r.selectedLocale||navigator.language,l=new hn({},s,i.paywallComponents.default_locale),c=f=>{var b;const h=i.availablePackages.find(y=>y.identifier===f);if(h===void 0)throw new Error(`No package found for ${f}`);return this.purchase({rcPackage:h,htmlTarget:r.purchaseHtmlTarget,customerEmail:r.customerEmail,selectedLocale:s,defaultLocale:((b=i.paywallComponents)==null?void 0:b.default_locale)||zt})},d=f=>{var h;if(r.onNavigateToUrl){r.onNavigateToUrl(f);return}(h=window.open(f,"_blank"))==null||h.focus()},u=()=>{},p=()=>{if(r.onVisitCustomerCenter){r.onVisitCustomerCenter();return}},_=_y(i,l),m=Wy(i);return new Promise((f,h)=>{so(xp,{target:n,props:{paywallData:i.paywallComponents,selectedLocale:s,onNavigateToUrlClicked:d,onVisitCustomerCenterClicked:p,uiConfig:i.uiConfig,onBackClicked:()=>{if(r.onBack){r.onBack();return}n.innerHTML="",ae.debugLog("Purchase cancelled by user"),h(new Fe(Ce.UserCancelledError))},onRestorePurchasesClicked:u,onPurchaseClicked:b=>{c(b).then(y=>{f(y)}).catch(y=>h(y))},onError:b=>h(b),variablesPerPackage:_,infoPerPackage:m}})})}async getOfferings(r){fh(r==null?void 0:r.currency);const t=this._appUserId,a=await this.backend.getOfferings(t),n=(r==null?void 0:r.offeringIdentifier)===Uo.Current?a.current_offering_id:r==null?void 0:r.offeringIdentifier;return n&&(a.offerings=a.offerings.filter(i=>i.identifier===n)),await this.getAllOfferings(a,t,r)}async getCurrentOfferingForPlacement(r,t){const a=this._appUserId,n=await this.backend.getOfferings(a),i=await this.getAllOfferings(n,a,t),s=n.placements??null;return s==null?null:Qh(s,i.all,r)}async getAllOfferings(r,t,a){const n=r.offerings.flatMap(s=>s.packages).map(s=>s.platform_product_identifier),i=await this.backend.getProducts(t,n,a==null?void 0:a.currency);return this.logMissingProductIds(n,i.product_details),ey(r,i)}async isEntitledTo(r){const t=await this.getCustomerInfo();return r in t.entitlements.active}purchasePackage(r,t,a){return this.purchase({rcPackage:r,customerEmail:t,htmlTarget:a})}async purchase(r){var z;const{rcPackage:t,purchaseOption:a,htmlTarget:n,customerEmail:i,selectedLocale:s=zt,defaultLocale:l=zt,skipSuccessPage:c=!1}=r;if(Ct(this._API_KEY)){const S=await Ly(r,this.backend,this._appUserId);return this.inMemoryCache.invalidateAllCaches(),S}let d=n??document.getElementById("rcb-ui-root");if(d===null){const S=document.createElement("div");S.className="rcb-ui-root",document.body.appendChild(S),d=S}if(d===null)throw new Error("Could not generate a mount point for the billing widget");const u=d,p=this._appUserId;ae.debugLog(`Presenting purchase form for package ${t.identifier}`);const _=s||l,m=a??t.webBillingProduct.defaultPurchaseOption,f=G_({appearance:(z=this._brandingInfo)==null?void 0:z.appearance,rcPackage:t,purchaseOptionToUse:m,customerEmail:i});this.eventsTracker.trackSDKEvent(f);const b={...this._flags.autoCollectUTMAsMetadata?Ay():{},...r.metadata||{}};let y=null;const P=this._brandingInfo;P&&r.brandingAppearanceOverride&&(P.appearance=r.brandingAppearanceOverride);const x=n!==void 0;return new Promise((S,q)=>{x||window.history.pushState({checkoutOpen:!0},"");const w=this._flags.rcSource&&zy.includes(this._flags.rcSource)?void 0:()=>{const k=K_();this.eventsTracker.trackSDKEvent(k),window.removeEventListener("popstate",w),y&&pn(y),u.innerHTML="",ae.debugLog("Purchase cancelled by user"),q(new Fe(Ce.UserCancelledError))};!x&&w&&window.addEventListener("popstate",w),y=so(hh,{target:u,props:{isInElement:x,appUserId:p,rcPackage:t,purchaseOption:m,customerEmail:i,onFinished:async k=>{const D=X_({redemptionInfo:k.redemptionInfo});this.eventsTracker.trackSDKEvent(D),this.inMemoryCache.invalidateAllCaches(),ae.debugLog("Purchase finished"),y&&pn(y),u.innerHTML="";const W={customerInfo:await this._getCustomerInfoForUserId(p),redemptionInfo:k.redemptionInfo,operationSessionId:k.operationSessionId,storeTransaction:{storeTransactionId:k.storeTransactionIdentifier,productIdentifier:t.webBillingProduct.identifier,purchaseDate:k.purchaseDate}};S(W)},onClose:w,onError:k=>{var W;const D=Z_({errorCode:(W=k.errorCode)==null?void 0:W.toString(),errorMessage:k.message});this.eventsTracker.trackSDKEvent(D),y&&pn(y),u.innerHTML="",q(Fe.getForPurchasesFlowError(k))},purchases:this,eventsTracker:this.eventsTracker,brandingInfo:this._brandingInfo,purchaseOperationHelper:this.purchaseOperationHelper,selectedLocale:_,metadata:b,defaultLocale:l,customTranslations:r.labelsOverride,skipSuccessPage:c}})})}_isConfiguredWithSimulatedStore(){return Ct(this._API_KEY)}async _postSimulatedStoreReceipt(r){if(!Ct(this._API_KEY))throw new Fe(Ce.ConfigurationError,"Posting a test store receipt is only available for RC Test Store API keys.");return await El(r,this.backend,this._appUserId)}async getCustomerInfo(){return await this._getCustomerInfoForUserId(this._appUserId)}getAppUserId(){return this._appUserId}async setAttributes(r){return await this.getCustomerInfo(),await this.backend.setAttributes(this._appUserId,r)}async changeUser(r){return await this.replaceUserId(r),await this.getCustomerInfo()}async identifyUser(r){if(Ro(r),r===this._appUserId)return ae.debugLog(`aliasUser called with the current appUserID: ${r}. Ignoring.`),{customerInfo:await this.getCustomerInfo(),wasCreated:!1};const t=await this.backend.identify(this._appUserId,r);return await this.replaceUserId(r),{customerInfo:Oo(t),wasCreated:t.was_created}}async replaceUserId(r){Ro(r),this._appUserId=r,await this.eventsTracker.updateUser(r),this.inMemoryCache.invalidateAllCaches()}logMissingProductIds(r,t){const a={};t.forEach(i=>a[i.identifier]=i);const n=[];r.forEach(i=>{a[i]===void 0&&n.push(i)}),n.length>0&&ae.debugLog(`Could not find product data for product ids:
|
|
345
345
|
${n.join()}.
|
|
346
346
|
Please check that your product configuration is correct.`)}isSandbox(){return zn(this._API_KEY)||Ct(this._API_KEY)}isAnonymous(){return this._appUserId.startsWith(Tl)}async getVirtualCurrencies(){return await this._getVirtualCurrenciesForUserId(this._appUserId)}getCachedVirtualCurrencies(){return this.inMemoryCache.getCachedVirtualCurrencies(this._appUserId,!0)}invalidateVirtualCurrenciesCache(){this.inMemoryCache.invalidateVirtualCurrenciesCache(this._appUserId)}close(){Xe.instance===this?(this.eventsTracker&&this.eventsTracker.dispose(),Xe.instance=void 0):ae.warnLog("Trying to close a Purchases instance that is not the current instance. Ignoring.")}async _getCustomerInfoForUserId(r){const t=await this.backend.getCustomerInfo(r);return Oo(t)}async _getVirtualCurrenciesForUserId(r){const t=this.inMemoryCache.getCachedVirtualCurrencies(r);if(t)return ae.debugLog("Vending VirtualCurrencies from cache."),t;const a=await this.backend.getVirtualCurrencies(r),n=Uy(a);return ae.debugLog("VirtualCurrencies updated from the network."),this.inMemoryCache.cacheVirtualCurrencies(r,n),n}static generateRevenueCatAnonymousAppUserId(){return`${Tl}${Va().replace(/-/g,"")}`}_trackEvent(r){this.eventsTracker.trackExternalEvent(r)}};Ko=Ml(null),Nl(Ko,1,"purchase",Il,Xe),Qo(Ko,Xe),L(Xe,"_platformInfo"),L(Xe,"instance");let On=Xe;H.ErrorCode=Ce,H.LogLevel=mr,H.OfferingKeyword=Uo,H.PackageType=Qs,H.PeriodUnit=re,H.ProductType=it,H.Purchases=On,H.PurchasesError=Fe,H.ReservedCustomerAttribute=Sl,H.UninitializedPurchasesError=rs,Object.defineProperty(H,Symbol.toStringTag,{value:"Module"})});
|