@tinkerlandai/longplay-sdk 0.10.84 → 0.10.85
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/CHANGELOG.md +4 -0
- package/README.md +3 -0
- package/dist/check-response-SOTWWQ3J.js +1 -0
- package/dist/{chunk-P6O6ULXW.js → chunk-2FDRWKO4.js} +1 -1
- package/dist/{chunk-MCQGIPH7.js → chunk-3IDEYQBG.js} +1 -1
- package/dist/{chunk-HFLMTQ5S.js → chunk-4HCUQJOA.js} +1 -1
- package/dist/{chunk-BKN33GVY.js → chunk-4SDB3T2F.js} +1 -1
- package/dist/{chunk-HVWHUYSF.js → chunk-52G77TMV.js} +2 -2
- package/dist/{chunk-TQIZN3GB.js → chunk-533YCYLO.js} +1 -1
- package/dist/{chunk-U3TW2YVO.js → chunk-5O6YRAHQ.js} +1 -1
- package/dist/{chunk-SY3GVNMT.js → chunk-7C4OOGQX.js} +1 -1
- package/dist/{chunk-YJHL2DPP.js → chunk-7ROXL6N2.js} +1 -1
- package/dist/{chunk-SBZFPW6N.js → chunk-7SQPGOJV.js} +1 -1
- package/dist/{chunk-BNVQIMXY.js → chunk-AECGOS7O.js} +1 -1
- package/dist/{chunk-UDVFPFL6.js → chunk-AJHLDSPG.js} +1 -1
- package/dist/{chunk-TGY77F4A.js → chunk-BQUSJPMG.js} +1 -1
- package/dist/{chunk-Q2ZKKRIB.js → chunk-BZ7HAITJ.js} +1 -1
- package/dist/{chunk-BJSY53HD.js → chunk-CQYEM7U6.js} +1 -1
- package/dist/{chunk-B3FNR6MN.js → chunk-DJTZR2NR.js} +1 -1
- package/dist/{chunk-S7UDY3NL.js → chunk-DT2OMMAT.js} +1 -1
- package/dist/{chunk-HVDAQX2D.js → chunk-E6ND7YQW.js} +1 -1
- package/dist/{chunk-CTDXIKX3.js → chunk-EXHNZVTM.js} +1 -1
- package/dist/{chunk-4CWYR6NX.js → chunk-F53UXSUI.js} +1 -1
- package/dist/{chunk-3QRVHAWK.js → chunk-F54HTDAC.js} +1 -1
- package/dist/{chunk-25LM2JXB.js → chunk-FBHEBXK4.js} +1 -1
- package/dist/{chunk-W5MSVU2K.js → chunk-FGAIHKFS.js} +1 -1
- package/dist/{chunk-TG7FSNRF.js → chunk-HMT4SHIK.js} +1 -1
- package/dist/{chunk-FRWORXER.js → chunk-HSNAFHCP.js} +1 -1
- package/dist/{chunk-45RTRADT.js → chunk-JJEOS374.js} +1 -1
- package/dist/{chunk-NBIHNC2C.js → chunk-JTCS63ER.js} +1 -1
- package/dist/{chunk-3AUMX2ZW.js → chunk-JUI7TMIM.js} +1 -1
- package/dist/{chunk-UO3DDQEW.js → chunk-KICIH4PE.js} +1 -1
- package/dist/chunk-LIWSSQAG.js +1 -0
- package/dist/{chunk-ZBVIIFB4.js → chunk-MDNT2TC3.js} +1 -1
- package/dist/{chunk-DGGXLPHI.js → chunk-MEBCS2JG.js} +1 -1
- package/dist/{chunk-EPKQGOCT.js → chunk-MGVWCLVQ.js} +1 -1
- package/dist/{chunk-VUGDBVIZ.js → chunk-MMAMK7OQ.js} +1 -1
- package/dist/{chunk-VJXGTINT.js → chunk-MUU6LV3R.js} +1 -1
- package/dist/{chunk-YBDTPMGD.js → chunk-OKHCU6ET.js} +1 -1
- package/dist/chunk-OT6DGH5B.js +1 -0
- package/dist/{chunk-OT3ED6TT.js → chunk-RGXNLSFL.js} +1 -1
- package/dist/{chunk-RWGMLH42.js → chunk-TORHBU45.js} +1 -1
- package/dist/{chunk-Q3K63EFB.js → chunk-U2JO7MX2.js} +1 -1
- package/dist/{chunk-AH36XJ2P.js → chunk-WFRZHLIV.js} +1 -1
- package/dist/{chunk-KHJZA73V.js → chunk-WJDHBJGU.js} +1 -1
- package/dist/{chunk-X6WXJJED.js → chunk-XMZ2FNYA.js} +1 -1
- package/dist/{chunk-Z42LII54.js → chunk-Y7Z6F6Y3.js} +1 -1
- package/dist/{chunk-YMNCFP4X.js → chunk-YEUQXQWK.js} +1 -1
- package/dist/{chunk-K6Q64QHZ.js → chunk-YQ2TU6TG.js} +1 -1
- package/dist/{chunk-R6NVHYXW.js → chunk-ZAD5WJWS.js} +1 -1
- package/dist/{chunk-HJLZY2VK.js → chunk-ZMDKCBLI.js} +1 -1
- package/dist/{content-YCHZNM7Y.js → content-KXWLR6IG.js} +1 -1
- package/dist/{funnel-host-purchase-O2XMLQLO.js → funnel-host-purchase-IT23CWX7.js} +1 -1
- package/dist/funnel-host-recovery-paywall-QGH574CM.js +1 -0
- package/dist/{funnel-paywall-copies-GHMZFYUK.js → funnel-paywall-copies-LZZILAWG.js} +1 -1
- package/dist/funnel-paywall-prerender-BKPL2SLY.js +1 -0
- package/dist/funnel-route-prediction-7B5FGESC.js +1 -0
- package/dist/funnel-route-source-F5OML4HC.js +1 -0
- package/dist/funnel-runtime-host-7UOEQRZV.js +1 -0
- package/dist/index.js +1 -1
- package/dist/merchant-bridge-contracts-47PO4USZ.js +1 -0
- package/dist/openrouter.js +1 -1
- package/dist/operation-contracts-EDUVKUPX.js +1 -0
- package/dist/page.js +1 -1
- package/dist/paywall-GUW4NI2B.js +1 -0
- package/dist/paywall-content-HMUHTWWL.js +1 -0
- package/dist/paywall-session-NJHRHCKM.js +1 -0
- package/dist/popup.js +1 -1
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-XJDNUC7B.js +1 -0
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/check-response-AB52X53M.js +0 -1
- package/dist/chunk-57NEGKC5.js +0 -1
- package/dist/chunk-J6F2XFDL.js +0 -1
- package/dist/funnel-host-recovery-paywall-3OLSW5TK.js +0 -1
- package/dist/funnel-paywall-prerender-ZUE3E5CD.js +0 -1
- package/dist/funnel-route-prediction-EFAGTU7F.js +0 -1
- package/dist/funnel-route-source-D66HFVVK.js +0 -1
- package/dist/funnel-runtime-host-CHUEAXTG.js +0 -1
- package/dist/merchant-bridge-contracts-RF4XQQTE.js +0 -1
- package/dist/operation-contracts-IAMHNJCL.js +0 -1
- package/dist/paywall-SMS52HSX.js +0 -1
- package/dist/paywall-content-ZJWLT3BD.js +0 -1
- package/dist/paywall-session-YNYTE7BE.js +0 -1
- package/dist/screen-renderer-MVJ5BKQS.js +0 -1
- /package/dist/{chunk-HVWHUYSF.js.LEGAL.txt → chunk-52G77TMV.js.LEGAL.txt} +0 -0
- /package/dist/{chunk-VITB5MIL.js → chunk-ZL247MPX.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b as o,c as i}from"./chunk-
|
|
1
|
+
import{a,b as o,c as i}from"./chunk-BZ7HAITJ.js";import{a as p}from"./chunk-AECGOS7O.js";function c(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new p("INVALID_REQUEST","Customer requests use the verified session identity")}function I(e){return{async previewUpdate(t){t=a(t),c(t);let r=await o(e,"previewUpdate");return i(e,r,t)},async update(t){t=a(t),c(t);let r=await o(e,"update");return i(e,r,t)},async readSubscriptionUpdate(t){t=a(t),c(t);let r=await o(e,"readSubscriptionUpdate");return i(e,r,t)},async restoreNativePurchase(t){t=a(t),c(t);let r=await o(e,"restoreNativePurchase");return i(e,r,t)},async previewAttach(t){t=a(t),c(t);let r=await o(e,"previewAttach");return i(e,r,t)},async attach(t){t=a(t),c(t);let r=await o(e,"attach");return i(e,r,t)},async readSubscriptionOperation(t){t=a(t),c(t);let r=await o(e,"readSubscriptionOperation");return i(e,r,t)}}}export{c as a,I as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as xn,c as Sn,d as Lt,f as Mt,g as Tn,k as On}from"./chunk-YMNCFP4X.js";import{a as Cn,b as Ye}from"./chunk-W32FI2A2.js";import{e as Pn,f as vn,g as kn,h as In,j as Ut,k as ct,l as En,m as An,n as Rn}from"./chunk-RWGMLH42.js";import{a as Ot,b as yn,d as Nt,e as gn,f as wn}from"./chunk-TG7FSNRF.js";import{a as st,b as oe,d as Dt,f as _t,j as bn}from"./chunk-VJXGTINT.js";import{b as ke}from"./chunk-R6NVHYXW.js";import{B as L,C as ot,D as Ge,E as Se,y as mn}from"./chunk-3QRVHAWK.js";import{r as Le,t as Ie}from"./chunk-YBDTPMGD.js";import{i as hn}from"./chunk-W5MSVU2K.js";import{c as ve,j as We}from"./chunk-VUGDBVIZ.js";import{c as Tt}from"./chunk-Q3K63EFB.js";import{a as k}from"./chunk-BNVQIMXY.js";import{a as K}from"./chunk-DSPLGTQI.js";async function Nn(j,a,A){if(!Ge(a))throw new k("INVALID_RESPONSE","A verified completed purchase is required");let N=j?We.parse(j):null;if(await A.onComplete?.(a),!N||!A.check)return;let G=We.parse(await A.check());if(G.internal_feature_id!==N.internal_feature_id||G.quantity!==N.quantity||N.observation!==void 0&&(G.observation===void 0||G.observation.requirementDigest!==N.observation.requirementDigest||G.observation.authority!==N.observation.authority||Tt(G.observation.subject)!==Tt(N.observation.subject)))throw new k("INVALID_RESPONSE","The access requirement changed");G.allowed&&await A.onAccessGranted?.(G)}function Dn(j){return Object.entries(j.document.buttons).filter(([,a])=>a.type==="checkout"&&a.product.type==="fixed"&&!ke(a.product,{},j.capabilities)).map(([a])=>a)}function _n(j,a){let A=L(a)?void 0:a.lines[0];if(!L(a)&&(a.lines.length!==1||!A))return;let N=L(a)?a.productVersionId:A.productVersionId,{screen:G,buttons:se}=j.document,Q=new Map(L(a)?Object.entries(a.featureQuantities??{}):(A?.prepaid??[]).map(C=>[C.internal_feature_id,C.quantity]));function ce(C,d){if(C.hidden)return!1;if(C.type==="plan_picker"&&j.capabilities.pickers[C.id]?.options.includes(N))return d[C.id]=N,!0;if(C.type==="quantity_picker"){let ne=Q.get(C.internalFeatureId);return ne!==void 0&&(!C.bind?.plan||C.bind.plan===N)&&(d[C.id]=ne),!1}if(C.type==="button"&&C.action){let ne=se[C.action];return ne?.type==="checkout"&&ne.product.type==="fixed"&&ne.product.productVersionId===N}if(C.type!=="stack")return!1;let te=C.interaction,i=C.bind?.plan===N;for(let[ne,h]of C.children.entries()){let Z={},M=ce(h,Z);if(te?.type==="toggle"||te?.type==="tabs"){if(!M)continue;return d[C.id]=te.type==="toggle"?ne===0:h.id,Object.assign(d,Z),!0}Object.assign(d,Z),M&&(i=!0,te?.type==="select"&&te.purpose==="product"&&te.pickerId&&h.type==="stack"&&h.bind?.plan===N&&(d[C.id]=h.id,d[te.pickerId]=N))}return i}for(let C of G.pages){let d={__page:C.id};if(ce(C.root,d))return d}}var qn="position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0";async function kr(j,a,A){let N=a.focusAtReveal?()=>{}:Ut(j.ownerDocument),G=()=>{Q.finish("dismissed"),N()},se=()=>G(),Q=En(j,a,"paywall",()=>{G(),K(a.onDismiss)},xn);a.signal?.throwIfAborted(),a.signal?.addEventListener("abort",se,{once:!0});let ce=null,C,d,te;try{if(Q.start(!0,a.loadingDocument?.screen.strings.defaultLocale,a.loadingDocument??null),Q.cancelled)throw new DOMException("Presentation cancelled","AbortError");if(ce=a.check?We.parse(await Q.wait(a.check(),ct)):null,ce?.allowed)return Q.finish("skipped"),a.signal?.removeEventListener("abort",se),N(),await a.onAccessGranted?.(ce),{check:ce,host:null};let[e,n]=await Promise.allSettled([Q.wait(import("./screen-renderer-MVJ5BKQS.js")),Q.wait(a.start().then(r=>(Q.cancelled&&r.destroy(),r)),ct)]);if(e.status==="rejected")throw n.status==="fulfilled"&&n.value.destroy(),e.reason;if(n.status==="rejected")throw n.reason;te=e.value,C=n.value,a.signal?.throwIfAborted(),C.signal?.throwIfAborted(),C.signal?.addEventListener("abort",se,{once:!0});let t=C.view??await Q.wait(C.refresh(),ct);if(!t)throw new k("INVALID_RESPONSE","Paywall presentation is missing");C.signal?.throwIfAborted(),d=t}catch(e){throw Q.finish("error",e),A?.retainedDialog?.release(),a.signal?.removeEventListener("abort",se),C?.signal?.removeEventListener("abort",se),C?.destroy(),N(),e}let i=C,{mountScreenPreview:ne}=te,h=j.ownerDocument,Z=new AbortController,M=h.createElement("section"),pe=h.createElement("div"),Y=h.createElement("div"),lt=a.mountControls,ee=lt?h.createElement("div"):void 0,f=h.createElement("p"),y=h.createElement("button"),le=h.createElement("button"),_=h.createElement("button");(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&A?.hostPaywallTarget&&!A.retainedDialog&&d.document.presentation.type==="modal"&&(A.retainedDialog=In(A.hostPaywallTarget));let ue=A?.retainedDialog,S=ue?.dialog??h.createElement("dialog"),Me=ue&&d.document.presentation.type==="inline"?{type:"modal",size:"md"}:d.document.presentation,re=Me.type==="inline"?Y:h.createElement("div"),ut=i.locale||d.document.screen.strings.defaultLocale,o=ut.toLowerCase().startsWith("zh"),Un=o?"正在处理…":"Processing…",Ln=o?"正在准备报价…":"Preparing your price…",U=Sn(d.document.screen.theme);M.dataset.indianaPaywall="",M.setAttribute("aria-label",d.document.name),M.style.cssText=U.root,Y.style.cssText=U.controls,f.style.cssText=U.message,f.setAttribute("role","status"),_.style.cssText=U.link,_.textContent=o?"关闭":"Close",y.style.cssText=U.secondary,y.textContent=o?"重试":"Retry",y.hidden=!0,le.type="button",le.style.cssText=U.primary,le.textContent=o?"继续付款":"Continue payment",le.hidden=!0,re.append(f,le,y),Y.append(_),ee&&(ee.style.cssText="flex:1 0 100%;min-width:0",ee.hidden=!0,Y.prepend(ee)),re!==Y&&(re.dataset.indianaPaywallStatus="",re.style.cssText="display:none;padding:0",M.append(re)),M.append(pe,Y);let dt=()=>{let e=$n();f.style.cssText=e?`${U.message};${qn}`:U.message,Kt();let n=c=>!c.hidden&&(c!==f||!!f.textContent&&!e);if(re!==Y&&(re.style.cssText=!ie&&[...re.children].some(n)?`${U.controls};padding:12px 64px 12px 20px;flex-shrink:0`:e?"padding:0":"display:none;padding:0"),ee){let c=!ee.childElementCount&&!ee.textContent?.trim();ee.hidden!==c&&(ee.hidden=c)}let t=me??Y,r=![...t.children].some(n),l=[...t.children].some(c=>c!==_&&n(c));t.style.cssText=r?U.controls.replace(/padding:[^;]+/,"padding:0"):l?`${U.controls};${U.pinned}`:U.controls,ft()},Vt=typeof MutationObserver>"u"?void 0:new MutationObserver(dt);Vt?.observe(M,{attributes:!0,attributeFilter:["hidden"],characterData:!0,childList:!0,subtree:!0});let Mn=Object.entries(d.document.buttons).filter(([,e])=>e.type==="close").map(([e])=>e),D,$t,Ve=!1,Ht=JSON.stringify(d.capabilities),q;function xe(e){let n=Dn(e);if(q||fe&&!ae||F&&(P||!be()||we))return Oe(e).map(({actionId:r})=>r);if(Ct()||!P&&be())return n;let t=P?bt(e):Pt(e);return[...new Set([...n,...Oe(e).map(({actionId:r})=>r).filter(r=>!t.includes(r))])]}function $e(e){if(w)return;let n=d.id!==e.id;d=e;let t=JSON.stringify(e.capabilities);if(n||t!==Ht){let r=!b&&!i.quote&&!i.operation?st(e,J,jt):J;n||JSON.stringify(r)!==JSON.stringify(J)?(J=r,D?.update(e.document.screen,ut,{capabilities:oe(e),unavailableActions:xe(e),serverInput:{bindings:[],answers:{}},selection:J})):D?.updateCapabilities(oe(e),xe(e)),Ht=t}Hn(e),Ee(),Ze()}let V,pt=0;function Qt(){return(me??Y).getBoundingClientRect().height+(re===Y?0:re.getBoundingClientRect().height)}function ft(){let e=h.defaultView;if(!V?.responsive||!e)return;let n=me??Y,t=e.innerHeight-(V.type==="modal"?32:0);n.style.maxHeight=`${Math.max(1,t)}px`,n.style.overflowY="auto",n.style.flexShrink="0",pt=Math.max(1,t-Qt()),D?.resizeViewport?.(pt,e.innerWidth)}let w=!1,fe=!1,b=null,ht,ze=!1,Bt=!1,he=!1,mt,Ke=!1,ie,me;function Vn(){return fe||w||ie||Ke?{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null}:Nt(i)}let E=()=>!w&&!ze&&!ie&&a.canInteract?.()!==!1,$,ye=!1,Te=!1,yt,m=null,de=null,Je="",ge=()=>a.checkoutNavigation==="after_confirmation"&&!!(a.terminateCheckout||a.resumeCheckout),J={},jt=new Set,ae,P;function gt(e){return!!e&&L(e)&&e.timing==="immediate"&&e.execution.provider==="merchant"}let wt=o?"正在确认付款…":"Confirming payment…",F=null,we,Xe,qt=!1,be=()=>a.allowNewPurchase!==!1||qt;function Ft(){return JSON.stringify([d.id,d.capabilities])}function Wt(){let e=yt;return e&&e.read===a.prepareSubscriptionChange&&e.basis===Ft()?e:void 0}function Ze(){let e=a.prepareSubscriptionChange;if(!e||!he||!E()||!be()||a.onPurchaseIntent||h.visibilityState==="hidden"||b||i.quote||i.operation||!Oe(d).length||Wt())return;let n=Z.signal,t=new Promise(r=>{let l=()=>r(void 0);n.addEventListener("abort",l,{once:!0}),Promise.resolve().then(()=>(n.throwIfAborted(),e(n))).then(c=>r(n.aborted?void 0:c),l).finally(()=>n.removeEventListener("abort",l))});yt={read:e,basis:Ft(),result:t}}let Gt=()=>{h.visibilityState==="hidden"?yt=void 0:Ze()};h.addEventListener("visibilitychange",Gt);function Oe(e){return Object.entries(e.document.buttons).flatMap(([n,t])=>t.type==="checkout"?[{actionId:n,policy:t}]:[])}function Yt(e){let n=P?.quote;return n?Oe(e).filter(({actionId:t,policy:r})=>Ne(n,e,t,r.product,J)).map(({actionId:t})=>t):[]}function bt(e){return P?.phase==="payment"?Yt(e):[]}function Ct(){return(P?P.phase==="payment":!be())&&(be()||!!a.prepareUpgradeReplacement)&&ge()&&!!a.terminateCheckout&&!!i.quote&&i.canReselect===!1&&!!i.operation&&R(i.operation).type==="checkout"}function Pt(e){let n=i.quote;return!ge()||F||!n||!i.operation||R(i.operation).type!=="checkout"?[]:Oe(e).filter(({actionId:t,policy:r})=>Ne(n,e,t,r.product,J)).map(({actionId:t})=>t)}function Ee(){let e=q?[]:P?bt(d):Pt(d),n=a.allowNewPurchase===!1&&!!i.operation&&R(i.operation).type==="checkout";le.hidden=!!q||(P?P.phase!=="payment":!n)||e.length>0,Kt(e)}function zt(){if(!(ae===void 0||q))return f.textContent?f.textContent:P?.phase==="checking"?wt:void 0}function $n(){return!!D?.updateCheckoutControls&&!!f.textContent&&zt()!==void 0}let et;function Kt(e=q?[]:P?bt(d):Pt(d)){if(!D?.updateCheckoutControls)return;let n=zt(),t=ge()||!!P;if(!n&&!t&&et?.on!==D)return;let r={actions:Oe(d).map(({actionId:c})=>c),resume:n?[ae]:t?e:[],resumeLabel:n??(o?"继续付款":P?"Continue payment":"Continue checkout"),busy:ae},l=JSON.stringify(r);et?.on===D&&et.key===l||(et={on:D,key:l},D.updateCheckoutControls(r))}function Jt(){de?.remove(),de=null}async function tt(){if(F)return;if(a.resumeCheckout&&i.operation){let n=i.operation.operationId;try{await a.resumeCheckout(n)}catch(t){if(!(t instanceof k&&t.code==="PURCHASE_PENDING"))throw t;let r=await i.read();if(!E())return;if(r.operationId!==n||R(r).type==="checkout")throw t;await H(r,!1)}return}let e=await i.read();if(R(e).type!=="checkout")return H(e,!1);E()&&(He.delete(e.operationId),await Qe(e))}function vt(){we?.destroy(),we=void 0,Xe=void 0}function Xt(){let e=F;if(!e||we)return;let n=o?"仍在核对原订单,暂时无法更换套餐。":"We’re still checking the original purchase before changing plans.",t=Date.now()+6e5,r=Cn({document:h,delay:()=>Date.now()<t?5e3:void 0,async run(){if(!E())return;let l=await i.read();if(we!==r||!E())return;if(l.operationId!==e.operationId)throw new k("PURCHASE_PENDING","The original Checkout changed");let c=R(l);c.type==="native"?(vt(),f.textContent=o?"原订单已关闭。你可以继续更换套餐。":"The original checkout is closed. You can continue changing plans.",y.textContent=o?"继续更换套餐":"Continue changing plans",m=()=>nt(),y.hidden=!1):(c.type==="complete"||c.type==="fulfillment"||c.type==="recording")&&(vt(),F=null,y.hidden=!0,await H(l,!1))}});we=r,Xe=async()=>{try{await r.refresh()}finally{we===r&&(f.textContent=n,y.hidden=!1)}},m=Xe,y.textContent=o?"查询结果":"Check result",y.hidden=!1,f.textContent=n,r.schedule()}async function nt(e=!1,n=!1){let t=F;if(!t)return;m=()=>nt(),P&&(y.textContent=o?"查询状态":"Check status"),y.hidden=!0;let r=async()=>{if(!be()&&a.prepareUpgradeReplacement){let c=await a.prepareUpgradeReplacement(t.operationId,t.intent);if(!E())return;qt=!0,$e(c)}F=null,P&&De(P.quote),Jt(),b=t.selection,$=t.coupon,ye=!1,Te=!1,await qe()};if(n&&!be()&&a.prepareUpgradeReplacement)return r();let l=Date.now()+2e4;for(;E();){let c=await i.read();if(c.operationId!==t.operationId)throw new k("PURCHASE_PENDING","The original Checkout changed");if(!E())break;let s=R(c);if(s.type==="native"){await r();return}if(s.type==="complete"||s.type==="fulfillment"||s.type==="recording"){F=null,P?await Ae(P.quote,c):await H(c,!1);return}if(e&&s.type==="checkout"){e=!1;try{await a.terminateCheckout(t.operationId)}catch(u){K(a.onError,u)}}if(Date.now()>=l){P&&s.type==="checkout"&&(F=null,await Ae(P.quote,c));break}await Ye(1e3,h,Z.signal)}!F||w||(P?(f.textContent=o?"仍在核对原升级单,暂时无法更换套餐。":"We’re still checking the original upgrade before changing plans.",y.hidden=!1):Xt())}async function Zt(e,n,t,r){if(m=()=>Zt(e,n,t,r),await a.beforeCheckoutReplacement?.(structuredClone(r)),!E())return;let l=i.operation;if(l?.operationId!==e||R(l).type!=="checkout"){m=null,l&&await H(l,!1);return}F={operationId:e,selection:n,coupon:t,intent:r},P&&(f.textContent=o?"正在切换套餐…":"Changing plan…",y.hidden=!0);let c=!1,s=!1;try{let u=await a.terminateCheckout(e);s=(Array.isArray(u?.purchases)?u.purchases:[]).some(p=>p.operationId===e&&p.type==="native")}catch(u){if(u instanceof k&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(u.code)){F=null,P&&(m=It,y.textContent=o?"查询状态":"Check status",y.hidden=!1),f.textContent=o?"请继续原订单,或等待它过期后再更换方案。":"Continue your original checkout, or wait for it to expire before changing plans.",K(a.onError,u);return}c=u instanceof k&&(u.status??0)>=500,K(a.onError,u)}E()&&await nt(c,s)}function rt(e,n,t,r,l){let c=oe(e).checkoutCoupons?.[n],s=c?c.products[t]:a.claimCoupon&&l?hn(e.capabilities,l,r):void 0;return s?.couponId&&s.planVersionId===t?{id:s.couponId,offerId:s.offerId}:void 0}function Hn(e){fe||b||i.quote||i.operation||Je&&f.textContent===Je||(f.textContent=Object.values(e.capabilities.plans).some(n=>n.available)?"":o?"当前账号暂无可购买的方案。":"No plans are currently available for this account.")}let He=new Map,it=!1;function Ne(e,n,t,r,l,c){let s=L(e),u=!s&&e.lines.length===1?e.lines[0]:void 0,I=ke(r,l,n.capabilities);if(!I||I!==(s?e.productVersionId:u?.productVersionId))return!1;let p=rt(n,t,I,l,c),x;try{x=Ie(n.document.screen,I,l,n.capabilities)}catch{return!1}if(s){let X=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return Object.keys(x).length===Object.keys(e.featureQuantities??{}).length&&Object.entries(x).every(([Ue,St])=>e.featureQuantities?.[Ue]===St)&&(!p||X?.couponId===p.id&&(!p.offerId||X.grantId===p.offerId))}if((p||oe(n).checkoutCoupons?.[t])&&(p?.id??null)!==(e.discount?.couponId??null))return!1;let T=Object.fromEntries((u?.prepaid??[]).map(X=>[X.internal_feature_id,X.quantity]));return[...new Set([...Object.keys(x),...Object.keys(T)])].every(X=>(x[X]??0)===(T[X]??0))}let R=e=>yn({quote:i.quote,operation:e,requestId:null,pending:!1,destroyed:w,canReselect:i.canReselect});async function Qe(e){let n=e.merchantExecution,t=R(e),r=t.type==="checkout"?t.checkoutUrl:e.checkoutUrl;if(!(!E()||!r||ot(e)&&t.type!=="checkout"||a.checkoutNavigation==="after_confirmation"&&t.type!=="checkout"||n?.type==="purchase"&&!["not_started","pending"].includes(n.paymentStatus)||He.get(e.operationId)===r)){He.set(e.operationId,r);try{a.onCheckoutUrl?await a.onCheckoutUrl(r):h.defaultView?.location.assign(r)}catch(l){throw He.delete(e.operationId),l}}}let Ce=(e,n=!1)=>{if(e instanceof Dt)m=null,f.textContent=e.customerMessage(o);else if(Tn(e))m=null,f.textContent=n?o?"当前无法在此购买,付款尚未开始。请联系商户。":"Purchases aren’t available here right now. Payment hasn’t started. Contact the merchant for help.":Mt(e,o);else if(n){let t=e instanceof k?e.code:void 0;t==="CAPABILITY_UNAVAILABLE"||t==="NOT_CONFIGURED"?(m=null,f.textContent=o?"暂时无法为此套餐报价,付款尚未开始。":"Pricing for this plan is unavailable. Payment hasn’t started."):i.canReselect===!0&&!b?f.textContent=o?"未能取得报价,付款尚未开始。请重新选择套餐。":"We couldn’t prepare your price. Payment hasn’t started. Choose a plan again.":t==="COMMAND_PENDING"?f.textContent=o?"仍在准备报价,请重试以查看结果。":"Your price is still being prepared. Retry to check the result.":f.textContent=o?"未能取得报价,付款尚未开始。请重试。":"We couldn’t prepare your price. Payment hasn’t started. Try again."}else f.textContent=e instanceof k&&(e.code==="NETWORK_ERROR"||e.code==="TIMEOUT")?Mt(e,o):e instanceof k?e.message:o?"操作未完成,请重试。":"This action couldn’t be completed. Try again.";y.hidden=m===null,Je=f.textContent,n&&ae===void 0&&!V?.responsive&&f.scrollIntoView?.({block:"nearest"}),K(n&&A?.quoteError?A.quoteError:a.onError,e)},Be=new WeakMap;function je(e){fe=e,y.disabled=e,le.disabled=e,D?.updateCapabilities?.(oe(d),xe(d));for(let n of de?.querySelectorAll("button")??[])e?(Be.has(n)||Be.set(n,n.disabled),n.disabled=!0):Be.has(n)&&(n.disabled=Be.get(n),Be.delete(n)),Lt(n)}function en(){q&&(f.textContent=q.message,y.textContent=o?"重试":"Retry",y.disabled=!1,y.hidden=!q.retry,le.disabled=!0)}function kt(){f.textContent=o?"暂时无法操作,请稍后重试。":"This action is unavailable right now. Try again in a moment."}let tn=new WeakSet;async function Qn(e){if(a.beforeAction)try{await a.beforeAction({purchaseIntent:tn.has(e)})}catch(n){throw n instanceof Dt?(b=null,ye=!1,Te=!1,m=null):m=e,n}}async function W(e,n){if(fe||w||q)return;if(!E()){kt();return}let t=e===qe,r=t?Ln:Un;ae=n!==void 0&&D?.updateCheckoutControls?n:void 0,f.textContent=r,je(!0),Ee(),y.hidden=!0;try{if(e!==cn&&e!==It&&e!==xt&&e!==Xe&&(e!==tt||!a.resumeCheckout)&&await Qn(e),w||q)return;if(!E()){m=e,y.hidden=!1,kt();return}await e()}catch(l){w||Ce(l,t)}finally{ae=void 0,je(!1),Ee(),q?en():f.textContent===r&&(f.textContent="")}}async function nn(e){await Nn(ce,e,a)}function De(e,n){P=n?{quote:e,phase:n}:void 0,n==="checking"?(ae??=b?.actionId??Yt(d)[0],f.textContent=wt,m=It,y.textContent=o?"查询状态":"Check status",y.hidden=!0):ae=void 0,D?.updateCapabilities(oe(d),xe(d)),Ee()}function rn(e){return e instanceof k&&(e.code==="COMMAND_PENDING"||e.reason==="RESULT_UNKNOWN"||e.code==="NETWORK_ERROR"||e.code==="TIMEOUT"||e.status===429||(e.status??0)>=500)}function an(e,n){_t(e,{...n,featureQuantities:n.featureQuantities??{}},"Purchase operation changed")}async function It(){P&&await Ae(P.quote)}async function Ae(e,n){De(e,"checking"),Je="";let t=1e3;Ve=!0,K(a.onObservationChange,!0);try{for(let r=n;E();r=void 0){if(!r){try{r=await i.read()}catch(l){if(!rn(l))throw l}if(!E())return}if(r){an(r,e);let l=R(r);if(l.type==="checkout"){De(e,"payment"),f.textContent=o?"请先完成原订单的付款。":"Finish paying for this upgrade.",y.hidden=!1;return}if(l.type==="complete"){De(e,"complete"),m=null;let c=d.capabilities.plans[e.productVersionId]?.name,s=e.merchantTerms?.subscriptionTerms?.items,u=s?.length===1?s[0].interval:void 0,I=u==="year"?o?"年付":"annual billing":u==="month"?o?"月付":"monthly billing":null;f.textContent=c?o?`已升级到 ${c}${I?" "+I:""}。`:`Upgraded to ${c}${I?" ("+I+")":""}.`:o?"已成功升级。":"Plan upgraded.",await nn(r);return}if(l.type==="native"&&!Se(r)){De(e),b=null,m=null,f.textContent=o?"付款没有成功,套餐未变更。请检查付款方式后重新选择套餐。":"Your payment didn’t go through, so your plan is unchanged. Check your payment method, then choose a plan again.",y.textContent=o?"重试":"Retry";return}if(r.problem&&!["RESULT_UNKNOWN","STATE_CHANGED"].includes(r.problem.reason??""))throw new k(r.problem.code,o?"暂时无法完成升级。":"The upgrade needs attention.",void 0,void 0,r.problem)}await Ye(t,h,Z.signal),t=Math.min(t*1.5,15e3)}}finally{Ve=!1,K(a.onObservationChange,!1)}}async function xt(){let e=P?.quote;if(!e)return;let n=await i.read();if(an(n,e),R(n).type!=="checkout")return Ae(e,n);if(a.resumeCheckout){await a.resumeCheckout(n.operationId);return}He.delete(n.operationId),await Qe(n)}function on(e){return Nt(i).type==="recording"||R(e).type==="recording"}function sn(e){let n=e.merchantTerms,t=n?.subscriptionTerms?.items??[],r=n?n.totalMinor:L(e)?e.totalMinor:e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),l=n?t.length===1&&t[0]?.amountMinor===r&&t[0]:!L(e)&&e.lines.length===1&&e.lines[0]?.catalogAmountMinor===r&&e.lines[0],c=r===null?ve(n.subtotalMinor-n.discountMinor,e.currency)+(o?" + 待确认税费":" + tax confirmed at checkout"):ve(r,e.currency)+(l?Le(l.interval,o?"zh-CN":"en",l.intervalCount??1):""),s=L(e)?i.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(u=>u.productName).join(", ");return{label:s?`${s} · ${c}`:c,recurring:l}}async function H(e,n=a.checkoutNavigation!=="after_confirmation"){if(w)return;if(!E()){m=async()=>H(await i.read()),y.hidden=!1;return}let t=e.quote??i.quote;if(gt(t)&&(e.confirmedAt||e.merchantExecution))return Ae(t,e);if(f.textContent=On(e.status,o),on(e)){let p=e.merchantExecution?.recordingStatus==="failed";f.textContent=p?o?"付款和商户处理已完成,但交易记录失败。请联系商户修复,勿重复购买。":"Payment and fulfillment succeeded, but recording failed. Contact the merchant to repair this purchase; do not buy again.":o?"付款和商户处理已完成,正在确认交易记录。请勿重复购买。":"Payment and merchant fulfillment are complete. Recording is pending confirmation; do not purchase again.",y.textContent=o?"查询记录":"Check recording",m=async()=>H(await i.read()),y.hidden=!1;return}if(e.problem&&R(e).type!=="native"){let p=e.problem;m=_e,y.textContent=o?"检查并恢复原操作":"Check and recover original purchase",Ce(new k(p.code,p.reason==="RESULT_UNKNOWN"?o?"付款结果尚未确定,请恢复原操作,暂勿重复购买。":"The payment result is unknown. Recover the original purchase before buying again.":p.phase==="fulfillment"?o?"付款已记录,商户权益处理需要核对。":"Payment was recorded. Access fulfillment needs attention.":p.code==="CAPABILITY_UNAVAILABLE"?o?"商户尚不支持本次购买所需的完整能力,请处理后恢复原操作。":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":p.code==="NOT_CONFIGURED"?o?"付款服务连接需要处理,请联系商户后恢复原操作。":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":o?"原购买操作需要处理,请查询或恢复此操作。":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,p));return}if((e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"||e.merchantExecution?.type==="subscription_change"&&e.merchantExecution.status==="applied")&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(f.textContent=o?"付款已记录,正在等待商户完成处理。":"Payment was recorded. Waiting for merchant fulfillment."),Ge(e)&&R(e).type==="complete"){m=null,await nn(e);return}let r=Ot(e);if((r||!Se(e))&&R(e).type!=="fulfillment"){if(i.canReselect===!1||r&&Se(e)&&i.canReselect!==!0){f.textContent=o?"正在核对原购买结果":"Checking the original purchase result",y.textContent=o?"查询结果":"Check result",m=async()=>H(await i.read()),y.hidden=!1;return}r?f.textContent=o?"结账未启动,可以重新选择方案。":"Checkout didn’t start. Choose a plan to try again.":e.status==="cancelled"?f.textContent=o?"这笔购买已取消,可以重新选择方案。":"This purchase was cancelled. Choose a plan to start again.":e.status==="failed"&&(f.textContent=o?"这笔购买未能完成,可以重新选择方案。":"This purchase didn’t go through. Choose a plan to try again."),y.textContent=o?"重试":"Retry",m=null,b=null;return}if(!n&&R(e).type==="checkout"){if(F){Xt();return}if(ge()){f.textContent="",it=!1,m=null,y.hidden=!0,D?.updateCapabilities?.(oe(d),xe(d)),Ee();return}let p=i.quote,x=p?.operationId===e.operationId?sn(p).label:"";f.textContent=it?x?o?`${x} 尚未付款。再次选择该方案即可继续付款。`:`${x} is still unpaid. Choose it again to continue paying.`:o?"之前的购买尚未付款。再次选择该方案即可继续付款。":"Your earlier purchase is still unpaid. Choose that plan again to continue paying.":"",it=!1,m=null;return}await Qe(e);let l=Date.now(),c=l+6e5,s=2e3,u=R(e).type!=="checkout",I=()=>u&&Date.now()-l<15e3;Ve=!0,K(a.onObservationChange,!0);try{for(;!w&&Date.now()<c;){if(await Ye(I()?700:s,h,Z.signal),w)return;if(!E()){m=async()=>H(await i.read()),y.hidden=!1;return}let p=await i.read();if(R(p).type==="checkout"&&(u=!1),!n&&R(p).type==="checkout"){await H(p,!1);return}if(!p.problem&&Se(p)&&await Qe(p),!Se(p)||Ot(p)||p.problem||on(p)){await H(p);return}I()||(s=Math.min(s*1.5,3e4))}}finally{Ve=!1,K(a.onObservationChange,!1)}m=async()=>H(await i.read()),y.hidden=!1}async function Et(e=!1){let n=await i.read();if(w)return;if(!E()){m=()=>Et(e),y.hidden=!1;return}let t=i.quote;if(t&&_t(n,{operationId:t.operationId,currency:t.currency},"The original purchase operation changed"),t&&(ot(n)?["prepared","quoted"].includes(n.status):n.status==="pending")&&(ot(n)||n.quoteFinalized===!1)&&!n.confirmedAt&&!n.checkoutUrl&&!("nativePurchase"in n&&n.nativePurchase)&&!n.merchantExecution&&!n.problem&&!i.pendingCancellation){if(a.purchaseConfirmation!=="paywall"){e?await _e():m=null;return}setTimeout(ln,0,t);return}await H(n,e||void 0)}async function cn(){await Et()}async function Bn(e){f.textContent=wt;let n=Date.now()+12e3;for(;!w&&Date.now()<n&&(await Ye(1500,h,Z.signal),!(w||!E()));){let t;try{t=await i.read()}catch{break}if(t.problem?.reason!=="RESULT_UNKNOWN")return t}return e}async function _e(){if(i.quote&&!(Date.parse(i.quote.expiresAt)>Date.now()))throw new k("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");Jt();let e=i.quote;if(gt(e)){De(e,"checking");let t;try{t=await i.confirm()}catch(r){if(!rn(r))throw r;return Ae(e)}return Ae(e,t)}m=_e;let n=await i.confirm();if(!E()){m=_e,y.hidden=!1;return}if(n.problem?.reason==="RESULT_UNKNOWN"&&(n=await Bn(n)),n.problem){await H(n);return}if(Se(n)){if(R(n).type==="checkout")await Qe(n);else if(n.execution&&n.execution.provider!=="merchant"||"nativePurchase"in n&&n.nativePurchase){if(!a.onPurchase)throw new k("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await a.onPurchase({operation:n,signal:Z.signal})}}m=async()=>H(await i.read()),await H(n,!0)}function ln(e){if(w)return;de?.remove();let n=!(Date.parse(e.expiresAt)>Date.now());f.textContent=n?o?"此报价已过期。请先取消,再重新选择。":"This quote has expired. Cancel it, then choose again.":"";let t=h.createElement("div"),r=h.createElement("button"),l=h.createElement("button"),c=h.createElement("div"),s=h.createElement("p"),u=e.merchantTerms,I=o?"zh-CN":"en",p=u?.subscriptionTerms?.items??[],x=u?u.subscriptionTerms?.trial?.days:L(e)?void 0:e.lines.find(g=>g.trial)?.trial?.days,T=L(e)?u?u.totalMinor:e.totalMinor:x===void 0?null:u?u.totalMinor:e.charge?e.charge.totalMinor:e.lines.every(g=>g.trial)?0:null,Pe=(g,v)=>o?`${v} 天试用结束后 ${g}`:`Then ${g} after the ${v}-day trial`,{label:X,recurring:Ue}=sn(e),St=L(e)?i.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(g=>g.productName).join(", "),pn=T===null?"":`${o?"今天应付":"Due today"} ${ve(T,e.currency)}`;s.textContent=pn?[St,pn].filter(Boolean).join(" · "):X,r.textContent=L(e)?o?"确认变更":"Confirm change":o?"确认购买":"Confirm purchase",r.disabled=n,l.textContent=o?"取消":"Cancel",t.style.cssText=U.panel,s.style.cssText=U.summary,c.style.cssText=U.actions,r.style.cssText=U.primary,l.style.cssText=U.secondary,Lt(r),r.onclick=()=>{W(_e)};let fn=async()=>{let g=await i.cancel();w||(t.remove(),de=null,await H(g))};l.onclick=()=>{m=fn,W(fn)};let z=h.createElement("div");if(z.style.cssText=U.terms,L(e)){for(let[v,O]of Object.entries(e.featureQuantities??{})){let B=i.view?.capabilities.plans[e.productVersionId]?.prepaid?.find(jn=>jn.internalFeatureId===v),at=h.createElement("p");at.textContent=`${B?.name??v} · ${O} ${o?"份":"packs"}${B?` × ${B.terms.units}`:""}`,z.append(at)}for(let[v,O]of[[o?"原订阅抵扣":"Unused subscription credit",e.creditMinor],[o?"新套餐费用":"New plan charge",e.debitMinor],[o?"优惠减免":"Offer savings",u?.discountMinor??e.discountMinor],[o?"税费":"Tax",u?u.taxMinor:e.taxMinor]]){let B=h.createElement("p");B.textContent=`${v}: ${O===null?o?"结账时确认":"Confirmed at checkout":ve(O,e.currency)}`,z.append(B)}let g=h.createElement("p");g.textContent=`${o?"生效时间":"Effective"}: ${e.effectiveAt}`,z.append(g)}if(u){for(let v of p){if(T===null&&v===Ue)continue;let O=h.createElement("p"),B=ve(v.amountMinor,e.currency)+Le(v.interval,I,v.intervalCount);O.textContent=T!==null&&x!==void 0?Pe(B,x):B,v.amountAfterOfferMinor!==void 0&&(O.textContent+=` · ${o?"优惠结束后":"After the offer"} ${ve(v.amountAfterOfferMinor,e.currency)}${Le(v.interval,I,v.intervalCount)}`),z.append(O)}let g=u.subscriptionTerms?.trial;if(g){let v=h.createElement("p");v.textContent=o?`试用 ${g.days} 天;${g.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${g.days}; ${g.cardRequired?"a payment method is required":"no payment method is required"}`,z.append(v)}for(let v of[...u.expectedEffects.map(O=>O.description),...u.requiredConsents.map(O=>O.summary)]){let O=h.createElement("p");O.textContent=v,z.append(O)}}else if(!L(e)){for(let g of e.lines){if(T!==null||g!==Ue){let v=h.createElement("p"),O=`${ve(g.catalogAmountMinor,e.currency)}${Le(g.interval,I,g.intervalCount??1)}`;v.textContent=T!==null&&g.trial?(e.lines.length>1?`${g.productName} · `:"")+Pe(O,g.trial.days):`${g.productName} · ${O}`,z.append(v)}for(let v of g.prepaid??[]){let O=h.createElement("p"),B=i.view?.capabilities.plans[g.productVersionId]?.prepaid?.find(at=>at.internalFeatureId===v.internal_feature_id);O.textContent=`${B?.name??v.internal_feature_id} · ${v.quantity} ${o?"份":"packs"} × ${v.terms.units}`,B&&(O.textContent+=Le(B.reset==="week"||B.reset==="month"||B.reset==="year"?B.reset:"one_time",I,B.resetCount)),z.append(O)}if(g.trial){let v=h.createElement("p");v.textContent=o?`试用 ${g.trial.days} 天;${g.trial.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${g.trial.days}; ${g.trial.cardRequired?"a payment method is required":"no payment method is required"}`,z.append(v)}}if(!e.charge){let g=h.createElement("p");g.textContent=o?"目录价格;最终金额以结账时税费和试用规则为准。":"Catalog price; the final charge depends on checkout taxes and trial terms.",z.append(g)}}for(let g of z.children)g.style.margin="0";c.append(r,l),t.append(s,...z.childElementCount?[z]:[],c),Y.prepend(t),V?.responsive||t.scrollIntoView?.({block:"nearest"}),r.focus({preventScroll:!0}),de=t,fe&&je(!0),m=null}async function qe(){if(!b)return;if(a.onPurchaseIntent&&!ye&&!i.quote&&!i.operation){let t=b,r=i.view,l=r?.document.buttons[t.actionId],c=r&&l?.type==="checkout"?ke(l.product,t.selection,r.capabilities):null;if(!r||!c)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");let s={actionId:t.actionId,productVersionId:c,selection:structuredClone(t.selection),featureQuantities:Ie(r.document.screen,c,t.selection,r.capabilities),...$&&{coupon:{id:$.id,...$.offerId&&{offerId:$.offerId}}}};b=null,$=void 0,m=null,Ke=!0,await a.onPurchaseIntent(s);return}if(m=qe,!ye){let t=i.view,r=t?.document.buttons[b.actionId],l=t&&r?.type==="checkout"?ke(r.product,b.selection,t.capabilities):null;if(!t||!l)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");if(!Te){let s=Wt(),u=s?await s.result:void 0;if(w)return;let I=a.resolveSubscriptionChange;if(I||u){let p={actionId:b.actionId,productVersionId:l,featureQuantities:Ie(t.document.screen,l,b.selection,t.capabilities)},x=u?[async()=>u(p)]:[],T=I?await I(p,...x):await x[0]?.();if(w)return;T!==void 0&&(b.subscriptionChange=mn.parse(T))}Te=!0}let c=$?.offerId;if($&&!c){if(!a.claimCoupon)throw new k("CAPABILITY_UNAVAILABLE","Coupon claiming is unavailable");let{offer:s}=await a.claimCoupon($.id,b.requestId);if(w)return;if(!s||s.couponId!==$.id||s.status!=="issued"||!(Date.parse(s.expiresAt)>Date.now()))throw b=null,$=void 0,m=async()=>{$e(await i.refresh()),m=null},new k("COUPON_UNAVAILABLE","This Coupon is no longer available for this purchase");c=s.id}if(!$&&!t.document.screen.actions.some(s=>s.id===b?.actionId&&typeof s.properties.couponBinding=="string")&&(c=await a.resolveOfferId?.({actionId:b.actionId,productVersionId:l,featureQuantities:Ie(t.document.screen,l,b.selection,t.capabilities)})),w)return;c!==void 0&&(b.offerId=c),ye=!0}if(!E()){y.hidden=!1;return}let e;try{e=await i.preview(b)}catch(t){throw i.canReselect===!0&&(b=null,ye=!1,Te=!1,$=void 0,m=null),t}if(b.acceptHostedMonthly!==void 0){let t=i.operation;if(!t||t.operationId!==e.operationId||!t.confirmedAt)throw new k("INVALID_RESPONSE","The confirmed Checkout is missing");w||await H(t,!0);return}if($&&(L(e)?(()=>{let t=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return t?.couponId!==$.id||t.grantId!==b.offerId})():e.discount?.couponId!==$.id||e.discount.offerId!==b.offerId))throw new k("INVALID_RESPONSE","The quote did not apply the Coupon selected on this Paywall");if(w)return;let n=e.merchantTerms;if(a.purchaseConfirmation!=="paywall"||a.confirmOnHostedCheckout&&E()&&!L(e)&&e.provider==="merchant"&&e.billingSubscriptionId===null&&n?.request.action==="purchase"&&n.request.mode==="subscription"&&n.subscriptionTerms?.trial===null&&n.requiredConsents.length===0&&Date.parse(e.expiresAt)>Date.now()){if(!E()){y.hidden=!1;return}if(!(Date.parse(e.expiresAt)>Date.now()))throw new k("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");let t=ae?"":o?"正在打开收银台…":"Opening checkout…";f.textContent=t;try{await _e()}catch(r){w||Ce(r)}finally{f.textContent===t&&(f.textContent="")}return}ln(e)}function Re(e="destroy",n=!1){if(w)return;w=!0;let t=ht;ht=void 0,K(t),a.signal?.removeEventListener("abort",se),i.signal?.removeEventListener("abort",se),Q.finish("dismissed"),$t?.(),vt(),h.removeEventListener("visibilitychange",Gt),Z.abort(),Vt?.disconnect(),D?.destroy(),i.destroy(),S.removeEventListener("cancel",dn),_.remove(),M.remove(),n||un(),e==="dismiss"&&K(a.onDismiss)}function un(){if(V?.destroy(),ue){ue.release();return}S.open&&S.close(),S.remove(),N()}G=Re;async function Fe(){if(!he||w||ze||ie==="closing"||!ie&&!E())return;if(!A){Re("dismiss");return}let e=h.createElement("p");e.setAttribute("role","status"),e.textContent=o?"正在关闭…":"Closing…",me||(me=h.createElement("div"),me.style.cssText=Y.style.cssText,Y.replaceWith(me),pe.inert=!0),_.hidden=!1,me.replaceChildren(e,_),ie="closing",_.setAttribute("aria-disabled","true"),_.focus({preventScroll:!0});try{await A.dismiss()}catch(n){w||K(a.onError,n)}w||(ie="retry",e.textContent=o?"未能确认关闭,请重试。":"Could not confirm closure. Try again.",_.textContent=o?"重试关闭":"Retry closing",_.removeAttribute("aria-label"),_.removeAttribute("aria-disabled"))}_.onclick=()=>{Fe()};function dn(e){e.preventDefault(),Fe()}S.addEventListener("cancel",dn),le.onclick=()=>{W(P?xt:tt)},y.onclick=()=>{if(q){q.retry?.();return}m&&W(m)};function At(e){Q.finish("error",e),Re()}function Rt(){if(!(!Bt||he||w||ze||V&&!E()))try{let e=n=>{a.focusAtReveal&&(N=Ut(h)),a.settleMotionAtReveal?D?.setHidden?.(!1,!0):D?.setHidden?.(!1),mt?.(),V&&(S.open||S.showModal(),V.responsive&&S.focus({preventScroll:!0}),!n&&a.loading!=="host"&&vn(S,V.type,V.responsive)),n&&a.loading!=="host"&&typeof pe.animate=="function"&&!h.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches&&pe.animate([{opacity:.55},{opacity:1}],{duration:160,easing:"ease-out"}),he=!0,Ze()};A?A.present(n=>Q.present(t=>e(n??t))):Q.present(e)}catch(e){At(e),Ce(e)}}try{if(Me.type==="inline"?(dt(),mt=Rn(M,j),j.append(M)):(S.setAttribute("aria-label",d.document.name),_.textContent="×",_.setAttribute("aria-label",o?"关闭":"Close"),kn(_,d.document.screen.theme),_.hidden=bn(d.document),(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&ue?.content?ue.content.append(_,M):S.replaceChildren(_,M),ue||j.append(S),V=Pn(S,{...d.document.screen,presentation:Me},ft),V.latch(),V.responsive&&(M.style.display="flex",M.style.flexDirection="column",M.style.maxHeight="100%",pe.style.overflow="clip",pe.style.minHeight="0"),ue||(mt=An(S))),lt&&ee){let t=lt(ee);if(typeof t=="function"&&(w?K(t):ht=t),w)throw new DOMException("Presentation cancelled","AbortError");dt()}D=ne(pe,{mode:"live",rendererUrl:"bundled",title:d.document.name,closeActions:Mn,onAuthoredClose(t){ie||w||(_.hidden=t)},hostPresentation:()=>V?.type??Me.type,reportContentHeight:V?.responsive,onResize:t=>{if(!V?.responsive)return;let r=Math.min(t,pt);pe.style.height=`${r}px`,V.setContentHeight(r+Qt())},onSelection(t){for(let[r,l]of Object.entries(t))typeof l=="number"&&typeof J[r]=="number"&&J[r]!==l&&jt.add(r);J=t,Ee(),Ze()},onAction(t,r={},l,c){if(!he||w||ie)return;let s=i.view,u=s?.document.buttons[t];if(!u)return;if(q){u.type==="close"&&Fe();return}if(u.type==="close"&&A&&a.resumeCheckout&&i.operation&&gn(R(i.operation))){Fe();return}if(fe)return;if(!E()){kt();return}if(u.type==="close"){W(async()=>{A?.closeAction?await A.closeAction(t):await a.onAction?.(t),Re(a.onAction?"action":"dismiss")});return}if(u.type==="action"){m=async()=>{if(u.action.type==="event"){if(!a.onEvent)throw new k("EVENT_HANDLER_REQUIRED","Provide the event handler");await a.onEvent(u.action.event)}else a.onOpenUrl?await a.onOpenUrl(u.action.url):h.defaultView?.location.assign(u.action.url);await a.onAction?.(t),m=null},W(m);return}if(ge()&&F){!we&&F.selection.actionId===t&&W(()=>nt(!0),t);return}if(P){if(P.phase==="payment"&&s&&Ne(P.quote,s,t,u.product,r,c)){W(xt,t);return}if(!Ct())return}if(!be()&&!Ct()){ge()&&s&&i.quote&&i.operation&&R(i.operation).type==="checkout"&&Ne(i.quote,s,t,u.product,r,c)?W(tt,t):f.textContent=o?"当前只能继续原订单。":"Only your original checkout is available.";return}if(de&&i.canReselect===!1){f.textContent=o?"请先确认或取消当前购买。":"Confirm or cancel the current purchase first.",V?.responsive||de.scrollIntoView?.({block:"nearest"}),de.querySelector("button")?.focus({preventScroll:!0});return}if(ge()&&a.terminateCheckout&&s&&i.quote&&i.operation&&i.canReselect===!1&&R(i.operation).type==="checkout"){if(Ne(i.quote,s,t,u.product,r,c)){W(tt,t);return}let p=ke(u.product,r,s.capabilities),x;try{if(!p)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");x=Ie(s.document.screen,p,r,s.capabilities)}catch(Ue){Ce(Ue);return}let T=i.operation.operationId,Pe={actionId:t,requestId:crypto.randomUUID(),selection:structuredClone(r)},X=rt(s,t,p,r,c);W(()=>Zt(T,Pe,X,{actionId:t,productVersionId:p,selection:Pe.selection,featureQuantities:x}),t);return}if((i.quote||b)&&i.canReselect===!1){let p=!!s&&!!i.quote&&Ne(i.quote,s,t,u.product,r,c);it=!!i.quote&&!p,m=i.quote?()=>Et(p):qe,W(m,t);return}let I=s&&ke(u.product,r,s.capabilities);if(!s||!I){Ce(new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(a.onPurchaseIntent){m=null;let p=async()=>{let x={actionId:t,productVersionId:I,selection:structuredClone(r),featureQuantities:Ie(s.document.screen,I,r,s.capabilities)},T=rt(s,t,I,r,c);T&&(x.coupon={id:T.id,...T.offerId&&{offerId:T.offerId}}),Ke=!0,await a.onPurchaseIntent(x)};tn.add(p),W(p,t);return}if(b&&b.actionId!==t){Ce(new k("COMMAND_PENDING","Finish the current purchase"));return}if(!b){$=rt(s,t,I,r,c),b={requestId:crypto.randomUUID(),actionId:t,selection:structuredClone(r)};let p=s.document.screen.actions.find(Pe=>Pe.id===t)?.properties,x=p?.hostedMonthlyPriceMinor,T=p?.hostedMonthlyAutomaticTax;a.purchaseConfirmation==="purchase_button"&&a.confirmOnHostedCheckout&&i.supportsHostedCheckout===!0&&!$&&u.product.type==="fixed"&&typeof T=="boolean"&&typeof x=="number"&&Number.isSafeInteger(x)&&x>0&&x<=1e8&&Object.keys(Ie(s.document.screen,I,r,s.capabilities)).length===0&&(b.acceptHostedMonthly={amountMinor:x,automaticTax:T}),ye=b.acceptHostedMonthly!==void 0,Te=ye}W(qe,t)},onEscape:()=>{Fe()},onError:t=>{let r=new Error(t);!he&&!w&&At(r),Ce(r)},onRendered:t=>{t&&S.setAttribute("aria-label",t),Bt=!0,Rt()}}),D.setHidden?.(!0),ft();let e=ge()&&!!i.quote&&!!i.operation&&R(i.operation).type==="checkout";J=i.quote?_n(d,i.quote)??st(d,{}):st(d,{}),D.update(d.document.screen,ut,{capabilities:oe(d),unavailableActions:xe(d),serverInput:{bindings:[],answers:{}},...Object.keys(J).length?{selection:J}:{}}),$t=i.subscribe?.($e),$e(i.view??d),await Q.wait(D.ready);let n=i.operation;(!e||gt(i.quote))&&(i.quote||n&&(n.confirmedAt||n.checkoutUrl||Ge(n)))&&(m=cn,W(m))}catch(e){throw At(e),e}return{check:ce,host:{get currentResolution(){return d},setPurchaseRecovery(e,n){q={message:e,retry:n},D?.updateCapabilities?.(oe(d),xe(d)),Ee(),en()},get subscriptionUpgradeActive(){return P!==void 0},get observing(){return Ve},get recovery(){return Vn()},async prepareFallback(){if(fe||w||ie||Ke)return{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null};je(!0);try{let e=await wn(i);return e.type==="native"&&Re(),e}finally{je(!1)}},setSuspended(e){ze=e,M.hidden=e,e&&S.open?S.close():!e&&!he?Rt():!e&&!w&&he&&Me.type!=="inline"&&!S.open&&S.showModal()},destroy:Re,retainPurchaseDialog(){if(!(w||!S.open||!S.isConnected))return Re("destroy",!0),{dialog:S,content:ue?.content,release:un}},refresh:async()=>{if(!E()){if(i.view)return i.view;throw new k("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await i.refresh();return $e(e),Rt(),e}}}}export{kr as a};
|
|
1
|
+
import{a as xn,c as Sn,d as Lt,f as Mt,g as Tn,k as On}from"./chunk-YEUQXQWK.js";import{a as Cn,b as Ye}from"./chunk-W32FI2A2.js";import{e as Pn,f as vn,g as kn,h as In,j as Ut,k as ct,l as En,m as An,n as Rn}from"./chunk-TORHBU45.js";import{a as Ot,b as yn,d as Nt,e as gn,f as wn}from"./chunk-HMT4SHIK.js";import{a as st,b as oe,d as Dt,f as _t,j as bn}from"./chunk-MUU6LV3R.js";import{b as ke}from"./chunk-ZAD5WJWS.js";import{B as L,C as ot,D as Ge,E as Se,y as mn}from"./chunk-F54HTDAC.js";import{r as Le,t as Ie}from"./chunk-OKHCU6ET.js";import{i as hn}from"./chunk-FGAIHKFS.js";import{c as ve,j as We}from"./chunk-MMAMK7OQ.js";import{c as Tt}from"./chunk-U2JO7MX2.js";import{a as k}from"./chunk-AECGOS7O.js";import{a as K}from"./chunk-DSPLGTQI.js";async function Nn(j,a,A){if(!Ge(a))throw new k("INVALID_RESPONSE","A verified completed purchase is required");let N=j?We.parse(j):null;if(await A.onComplete?.(a),!N||!A.check)return;let G=We.parse(await A.check());if(G.internal_feature_id!==N.internal_feature_id||G.quantity!==N.quantity||N.observation!==void 0&&(G.observation===void 0||G.observation.requirementDigest!==N.observation.requirementDigest||G.observation.authority!==N.observation.authority||Tt(G.observation.subject)!==Tt(N.observation.subject)))throw new k("INVALID_RESPONSE","The access requirement changed");G.allowed&&await A.onAccessGranted?.(G)}function Dn(j){return Object.entries(j.document.buttons).filter(([,a])=>a.type==="checkout"&&a.product.type==="fixed"&&!ke(a.product,{},j.capabilities)).map(([a])=>a)}function _n(j,a){let A=L(a)?void 0:a.lines[0];if(!L(a)&&(a.lines.length!==1||!A))return;let N=L(a)?a.productVersionId:A.productVersionId,{screen:G,buttons:se}=j.document,Q=new Map(L(a)?Object.entries(a.featureQuantities??{}):(A?.prepaid??[]).map(C=>[C.internal_feature_id,C.quantity]));function ce(C,d){if(C.hidden)return!1;if(C.type==="plan_picker"&&j.capabilities.pickers[C.id]?.options.includes(N))return d[C.id]=N,!0;if(C.type==="quantity_picker"){let ne=Q.get(C.internalFeatureId);return ne!==void 0&&(!C.bind?.plan||C.bind.plan===N)&&(d[C.id]=ne),!1}if(C.type==="button"&&C.action){let ne=se[C.action];return ne?.type==="checkout"&&ne.product.type==="fixed"&&ne.product.productVersionId===N}if(C.type!=="stack")return!1;let te=C.interaction,i=C.bind?.plan===N;for(let[ne,h]of C.children.entries()){let Z={},M=ce(h,Z);if(te?.type==="toggle"||te?.type==="tabs"){if(!M)continue;return d[C.id]=te.type==="toggle"?ne===0:h.id,Object.assign(d,Z),!0}Object.assign(d,Z),M&&(i=!0,te?.type==="select"&&te.purpose==="product"&&te.pickerId&&h.type==="stack"&&h.bind?.plan===N&&(d[C.id]=h.id,d[te.pickerId]=N))}return i}for(let C of G.pages){let d={__page:C.id};if(ce(C.root,d))return d}}var qn="position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0";async function kr(j,a,A){let N=a.focusAtReveal?()=>{}:Ut(j.ownerDocument),G=()=>{Q.finish("dismissed"),N()},se=()=>G(),Q=En(j,a,"paywall",()=>{G(),K(a.onDismiss)},xn);a.signal?.throwIfAborted(),a.signal?.addEventListener("abort",se,{once:!0});let ce=null,C,d,te;try{if(Q.start(!0,a.loadingDocument?.screen.strings.defaultLocale,a.loadingDocument??null),Q.cancelled)throw new DOMException("Presentation cancelled","AbortError");if(ce=a.check?We.parse(await Q.wait(a.check(),ct)):null,ce?.allowed)return Q.finish("skipped"),a.signal?.removeEventListener("abort",se),N(),await a.onAccessGranted?.(ce),{check:ce,host:null};let[e,n]=await Promise.allSettled([Q.wait(import("./screen-renderer-XJDNUC7B.js")),Q.wait(a.start().then(r=>(Q.cancelled&&r.destroy(),r)),ct)]);if(e.status==="rejected")throw n.status==="fulfilled"&&n.value.destroy(),e.reason;if(n.status==="rejected")throw n.reason;te=e.value,C=n.value,a.signal?.throwIfAborted(),C.signal?.throwIfAborted(),C.signal?.addEventListener("abort",se,{once:!0});let t=C.view??await Q.wait(C.refresh(),ct);if(!t)throw new k("INVALID_RESPONSE","Paywall presentation is missing");C.signal?.throwIfAborted(),d=t}catch(e){throw Q.finish("error",e),A?.retainedDialog?.release(),a.signal?.removeEventListener("abort",se),C?.signal?.removeEventListener("abort",se),C?.destroy(),N(),e}let i=C,{mountScreenPreview:ne}=te,h=j.ownerDocument,Z=new AbortController,M=h.createElement("section"),pe=h.createElement("div"),Y=h.createElement("div"),lt=a.mountControls,ee=lt?h.createElement("div"):void 0,f=h.createElement("p"),y=h.createElement("button"),le=h.createElement("button"),_=h.createElement("button");(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&A?.hostPaywallTarget&&!A.retainedDialog&&d.document.presentation.type==="modal"&&(A.retainedDialog=In(A.hostPaywallTarget));let ue=A?.retainedDialog,S=ue?.dialog??h.createElement("dialog"),Me=ue&&d.document.presentation.type==="inline"?{type:"modal",size:"md"}:d.document.presentation,re=Me.type==="inline"?Y:h.createElement("div"),ut=i.locale||d.document.screen.strings.defaultLocale,o=ut.toLowerCase().startsWith("zh"),Un=o?"正在处理…":"Processing…",Ln=o?"正在准备报价…":"Preparing your price…",U=Sn(d.document.screen.theme);M.dataset.indianaPaywall="",M.setAttribute("aria-label",d.document.name),M.style.cssText=U.root,Y.style.cssText=U.controls,f.style.cssText=U.message,f.setAttribute("role","status"),_.style.cssText=U.link,_.textContent=o?"关闭":"Close",y.style.cssText=U.secondary,y.textContent=o?"重试":"Retry",y.hidden=!0,le.type="button",le.style.cssText=U.primary,le.textContent=o?"继续付款":"Continue payment",le.hidden=!0,re.append(f,le,y),Y.append(_),ee&&(ee.style.cssText="flex:1 0 100%;min-width:0",ee.hidden=!0,Y.prepend(ee)),re!==Y&&(re.dataset.indianaPaywallStatus="",re.style.cssText="display:none;padding:0",M.append(re)),M.append(pe,Y);let dt=()=>{let e=$n();f.style.cssText=e?`${U.message};${qn}`:U.message,Kt();let n=c=>!c.hidden&&(c!==f||!!f.textContent&&!e);if(re!==Y&&(re.style.cssText=!ie&&[...re.children].some(n)?`${U.controls};padding:12px 64px 12px 20px;flex-shrink:0`:e?"padding:0":"display:none;padding:0"),ee){let c=!ee.childElementCount&&!ee.textContent?.trim();ee.hidden!==c&&(ee.hidden=c)}let t=me??Y,r=![...t.children].some(n),l=[...t.children].some(c=>c!==_&&n(c));t.style.cssText=r?U.controls.replace(/padding:[^;]+/,"padding:0"):l?`${U.controls};${U.pinned}`:U.controls,ft()},Vt=typeof MutationObserver>"u"?void 0:new MutationObserver(dt);Vt?.observe(M,{attributes:!0,attributeFilter:["hidden"],characterData:!0,childList:!0,subtree:!0});let Mn=Object.entries(d.document.buttons).filter(([,e])=>e.type==="close").map(([e])=>e),D,$t,Ve=!1,Ht=JSON.stringify(d.capabilities),q;function xe(e){let n=Dn(e);if(q||fe&&!ae||F&&(P||!be()||we))return Oe(e).map(({actionId:r})=>r);if(Ct()||!P&&be())return n;let t=P?bt(e):Pt(e);return[...new Set([...n,...Oe(e).map(({actionId:r})=>r).filter(r=>!t.includes(r))])]}function $e(e){if(w)return;let n=d.id!==e.id;d=e;let t=JSON.stringify(e.capabilities);if(n||t!==Ht){let r=!b&&!i.quote&&!i.operation?st(e,J,jt):J;n||JSON.stringify(r)!==JSON.stringify(J)?(J=r,D?.update(e.document.screen,ut,{capabilities:oe(e),unavailableActions:xe(e),serverInput:{bindings:[],answers:{}},selection:J})):D?.updateCapabilities(oe(e),xe(e)),Ht=t}Hn(e),Ee(),Ze()}let V,pt=0;function Qt(){return(me??Y).getBoundingClientRect().height+(re===Y?0:re.getBoundingClientRect().height)}function ft(){let e=h.defaultView;if(!V?.responsive||!e)return;let n=me??Y,t=e.innerHeight-(V.type==="modal"?32:0);n.style.maxHeight=`${Math.max(1,t)}px`,n.style.overflowY="auto",n.style.flexShrink="0",pt=Math.max(1,t-Qt()),D?.resizeViewport?.(pt,e.innerWidth)}let w=!1,fe=!1,b=null,ht,ze=!1,Bt=!1,he=!1,mt,Ke=!1,ie,me;function Vn(){return fe||w||ie||Ke?{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null}:Nt(i)}let E=()=>!w&&!ze&&!ie&&a.canInteract?.()!==!1,$,ye=!1,Te=!1,yt,m=null,de=null,Je="",ge=()=>a.checkoutNavigation==="after_confirmation"&&!!(a.terminateCheckout||a.resumeCheckout),J={},jt=new Set,ae,P;function gt(e){return!!e&&L(e)&&e.timing==="immediate"&&e.execution.provider==="merchant"}let wt=o?"正在确认付款…":"Confirming payment…",F=null,we,Xe,qt=!1,be=()=>a.allowNewPurchase!==!1||qt;function Ft(){return JSON.stringify([d.id,d.capabilities])}function Wt(){let e=yt;return e&&e.read===a.prepareSubscriptionChange&&e.basis===Ft()?e:void 0}function Ze(){let e=a.prepareSubscriptionChange;if(!e||!he||!E()||!be()||a.onPurchaseIntent||h.visibilityState==="hidden"||b||i.quote||i.operation||!Oe(d).length||Wt())return;let n=Z.signal,t=new Promise(r=>{let l=()=>r(void 0);n.addEventListener("abort",l,{once:!0}),Promise.resolve().then(()=>(n.throwIfAborted(),e(n))).then(c=>r(n.aborted?void 0:c),l).finally(()=>n.removeEventListener("abort",l))});yt={read:e,basis:Ft(),result:t}}let Gt=()=>{h.visibilityState==="hidden"?yt=void 0:Ze()};h.addEventListener("visibilitychange",Gt);function Oe(e){return Object.entries(e.document.buttons).flatMap(([n,t])=>t.type==="checkout"?[{actionId:n,policy:t}]:[])}function Yt(e){let n=P?.quote;return n?Oe(e).filter(({actionId:t,policy:r})=>Ne(n,e,t,r.product,J)).map(({actionId:t})=>t):[]}function bt(e){return P?.phase==="payment"?Yt(e):[]}function Ct(){return(P?P.phase==="payment":!be())&&(be()||!!a.prepareUpgradeReplacement)&&ge()&&!!a.terminateCheckout&&!!i.quote&&i.canReselect===!1&&!!i.operation&&R(i.operation).type==="checkout"}function Pt(e){let n=i.quote;return!ge()||F||!n||!i.operation||R(i.operation).type!=="checkout"?[]:Oe(e).filter(({actionId:t,policy:r})=>Ne(n,e,t,r.product,J)).map(({actionId:t})=>t)}function Ee(){let e=q?[]:P?bt(d):Pt(d),n=a.allowNewPurchase===!1&&!!i.operation&&R(i.operation).type==="checkout";le.hidden=!!q||(P?P.phase!=="payment":!n)||e.length>0,Kt(e)}function zt(){if(!(ae===void 0||q))return f.textContent?f.textContent:P?.phase==="checking"?wt:void 0}function $n(){return!!D?.updateCheckoutControls&&!!f.textContent&&zt()!==void 0}let et;function Kt(e=q?[]:P?bt(d):Pt(d)){if(!D?.updateCheckoutControls)return;let n=zt(),t=ge()||!!P;if(!n&&!t&&et?.on!==D)return;let r={actions:Oe(d).map(({actionId:c})=>c),resume:n?[ae]:t?e:[],resumeLabel:n??(o?"继续付款":P?"Continue payment":"Continue checkout"),busy:ae},l=JSON.stringify(r);et?.on===D&&et.key===l||(et={on:D,key:l},D.updateCheckoutControls(r))}function Jt(){de?.remove(),de=null}async function tt(){if(F)return;if(a.resumeCheckout&&i.operation){let n=i.operation.operationId;try{await a.resumeCheckout(n)}catch(t){if(!(t instanceof k&&t.code==="PURCHASE_PENDING"))throw t;let r=await i.read();if(!E())return;if(r.operationId!==n||R(r).type==="checkout")throw t;await H(r,!1)}return}let e=await i.read();if(R(e).type!=="checkout")return H(e,!1);E()&&(He.delete(e.operationId),await Qe(e))}function vt(){we?.destroy(),we=void 0,Xe=void 0}function Xt(){let e=F;if(!e||we)return;let n=o?"仍在核对原订单,暂时无法更换套餐。":"We’re still checking the original purchase before changing plans.",t=Date.now()+6e5,r=Cn({document:h,delay:()=>Date.now()<t?5e3:void 0,async run(){if(!E())return;let l=await i.read();if(we!==r||!E())return;if(l.operationId!==e.operationId)throw new k("PURCHASE_PENDING","The original Checkout changed");let c=R(l);c.type==="native"?(vt(),f.textContent=o?"原订单已关闭。你可以继续更换套餐。":"The original checkout is closed. You can continue changing plans.",y.textContent=o?"继续更换套餐":"Continue changing plans",m=()=>nt(),y.hidden=!1):(c.type==="complete"||c.type==="fulfillment"||c.type==="recording")&&(vt(),F=null,y.hidden=!0,await H(l,!1))}});we=r,Xe=async()=>{try{await r.refresh()}finally{we===r&&(f.textContent=n,y.hidden=!1)}},m=Xe,y.textContent=o?"查询结果":"Check result",y.hidden=!1,f.textContent=n,r.schedule()}async function nt(e=!1,n=!1){let t=F;if(!t)return;m=()=>nt(),P&&(y.textContent=o?"查询状态":"Check status"),y.hidden=!0;let r=async()=>{if(!be()&&a.prepareUpgradeReplacement){let c=await a.prepareUpgradeReplacement(t.operationId,t.intent);if(!E())return;qt=!0,$e(c)}F=null,P&&De(P.quote),Jt(),b=t.selection,$=t.coupon,ye=!1,Te=!1,await qe()};if(n&&!be()&&a.prepareUpgradeReplacement)return r();let l=Date.now()+2e4;for(;E();){let c=await i.read();if(c.operationId!==t.operationId)throw new k("PURCHASE_PENDING","The original Checkout changed");if(!E())break;let s=R(c);if(s.type==="native"){await r();return}if(s.type==="complete"||s.type==="fulfillment"||s.type==="recording"){F=null,P?await Ae(P.quote,c):await H(c,!1);return}if(e&&s.type==="checkout"){e=!1;try{await a.terminateCheckout(t.operationId)}catch(u){K(a.onError,u)}}if(Date.now()>=l){P&&s.type==="checkout"&&(F=null,await Ae(P.quote,c));break}await Ye(1e3,h,Z.signal)}!F||w||(P?(f.textContent=o?"仍在核对原升级单,暂时无法更换套餐。":"We’re still checking the original upgrade before changing plans.",y.hidden=!1):Xt())}async function Zt(e,n,t,r){if(m=()=>Zt(e,n,t,r),await a.beforeCheckoutReplacement?.(structuredClone(r)),!E())return;let l=i.operation;if(l?.operationId!==e||R(l).type!=="checkout"){m=null,l&&await H(l,!1);return}F={operationId:e,selection:n,coupon:t,intent:r},P&&(f.textContent=o?"正在切换套餐…":"Changing plan…",y.hidden=!0);let c=!1,s=!1;try{let u=await a.terminateCheckout(e);s=(Array.isArray(u?.purchases)?u.purchases:[]).some(p=>p.operationId===e&&p.type==="native")}catch(u){if(u instanceof k&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(u.code)){F=null,P&&(m=It,y.textContent=o?"查询状态":"Check status",y.hidden=!1),f.textContent=o?"请继续原订单,或等待它过期后再更换方案。":"Continue your original checkout, or wait for it to expire before changing plans.",K(a.onError,u);return}c=u instanceof k&&(u.status??0)>=500,K(a.onError,u)}E()&&await nt(c,s)}function rt(e,n,t,r,l){let c=oe(e).checkoutCoupons?.[n],s=c?c.products[t]:a.claimCoupon&&l?hn(e.capabilities,l,r):void 0;return s?.couponId&&s.planVersionId===t?{id:s.couponId,offerId:s.offerId}:void 0}function Hn(e){fe||b||i.quote||i.operation||Je&&f.textContent===Je||(f.textContent=Object.values(e.capabilities.plans).some(n=>n.available)?"":o?"当前账号暂无可购买的方案。":"No plans are currently available for this account.")}let He=new Map,it=!1;function Ne(e,n,t,r,l,c){let s=L(e),u=!s&&e.lines.length===1?e.lines[0]:void 0,I=ke(r,l,n.capabilities);if(!I||I!==(s?e.productVersionId:u?.productVersionId))return!1;let p=rt(n,t,I,l,c),x;try{x=Ie(n.document.screen,I,l,n.capabilities)}catch{return!1}if(s){let X=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return Object.keys(x).length===Object.keys(e.featureQuantities??{}).length&&Object.entries(x).every(([Ue,St])=>e.featureQuantities?.[Ue]===St)&&(!p||X?.couponId===p.id&&(!p.offerId||X.grantId===p.offerId))}if((p||oe(n).checkoutCoupons?.[t])&&(p?.id??null)!==(e.discount?.couponId??null))return!1;let T=Object.fromEntries((u?.prepaid??[]).map(X=>[X.internal_feature_id,X.quantity]));return[...new Set([...Object.keys(x),...Object.keys(T)])].every(X=>(x[X]??0)===(T[X]??0))}let R=e=>yn({quote:i.quote,operation:e,requestId:null,pending:!1,destroyed:w,canReselect:i.canReselect});async function Qe(e){let n=e.merchantExecution,t=R(e),r=t.type==="checkout"?t.checkoutUrl:e.checkoutUrl;if(!(!E()||!r||ot(e)&&t.type!=="checkout"||a.checkoutNavigation==="after_confirmation"&&t.type!=="checkout"||n?.type==="purchase"&&!["not_started","pending"].includes(n.paymentStatus)||He.get(e.operationId)===r)){He.set(e.operationId,r);try{a.onCheckoutUrl?await a.onCheckoutUrl(r):h.defaultView?.location.assign(r)}catch(l){throw He.delete(e.operationId),l}}}let Ce=(e,n=!1)=>{if(e instanceof Dt)m=null,f.textContent=e.customerMessage(o);else if(Tn(e))m=null,f.textContent=n?o?"当前无法在此购买,付款尚未开始。请联系商户。":"Purchases aren’t available here right now. Payment hasn’t started. Contact the merchant for help.":Mt(e,o);else if(n){let t=e instanceof k?e.code:void 0;t==="CAPABILITY_UNAVAILABLE"||t==="NOT_CONFIGURED"?(m=null,f.textContent=o?"暂时无法为此套餐报价,付款尚未开始。":"Pricing for this plan is unavailable. Payment hasn’t started."):i.canReselect===!0&&!b?f.textContent=o?"未能取得报价,付款尚未开始。请重新选择套餐。":"We couldn’t prepare your price. Payment hasn’t started. Choose a plan again.":t==="COMMAND_PENDING"?f.textContent=o?"仍在准备报价,请重试以查看结果。":"Your price is still being prepared. Retry to check the result.":f.textContent=o?"未能取得报价,付款尚未开始。请重试。":"We couldn’t prepare your price. Payment hasn’t started. Try again."}else f.textContent=e instanceof k&&(e.code==="NETWORK_ERROR"||e.code==="TIMEOUT")?Mt(e,o):e instanceof k?e.message:o?"操作未完成,请重试。":"This action couldn’t be completed. Try again.";y.hidden=m===null,Je=f.textContent,n&&ae===void 0&&!V?.responsive&&f.scrollIntoView?.({block:"nearest"}),K(n&&A?.quoteError?A.quoteError:a.onError,e)},Be=new WeakMap;function je(e){fe=e,y.disabled=e,le.disabled=e,D?.updateCapabilities?.(oe(d),xe(d));for(let n of de?.querySelectorAll("button")??[])e?(Be.has(n)||Be.set(n,n.disabled),n.disabled=!0):Be.has(n)&&(n.disabled=Be.get(n),Be.delete(n)),Lt(n)}function en(){q&&(f.textContent=q.message,y.textContent=o?"重试":"Retry",y.disabled=!1,y.hidden=!q.retry,le.disabled=!0)}function kt(){f.textContent=o?"暂时无法操作,请稍后重试。":"This action is unavailable right now. Try again in a moment."}let tn=new WeakSet;async function Qn(e){if(a.beforeAction)try{await a.beforeAction({purchaseIntent:tn.has(e)})}catch(n){throw n instanceof Dt?(b=null,ye=!1,Te=!1,m=null):m=e,n}}async function W(e,n){if(fe||w||q)return;if(!E()){kt();return}let t=e===qe,r=t?Ln:Un;ae=n!==void 0&&D?.updateCheckoutControls?n:void 0,f.textContent=r,je(!0),Ee(),y.hidden=!0;try{if(e!==cn&&e!==It&&e!==xt&&e!==Xe&&(e!==tt||!a.resumeCheckout)&&await Qn(e),w||q)return;if(!E()){m=e,y.hidden=!1,kt();return}await e()}catch(l){w||Ce(l,t)}finally{ae=void 0,je(!1),Ee(),q?en():f.textContent===r&&(f.textContent="")}}async function nn(e){await Nn(ce,e,a)}function De(e,n){P=n?{quote:e,phase:n}:void 0,n==="checking"?(ae??=b?.actionId??Yt(d)[0],f.textContent=wt,m=It,y.textContent=o?"查询状态":"Check status",y.hidden=!0):ae=void 0,D?.updateCapabilities(oe(d),xe(d)),Ee()}function rn(e){return e instanceof k&&(e.code==="COMMAND_PENDING"||e.reason==="RESULT_UNKNOWN"||e.code==="NETWORK_ERROR"||e.code==="TIMEOUT"||e.status===429||(e.status??0)>=500)}function an(e,n){_t(e,{...n,featureQuantities:n.featureQuantities??{}},"Purchase operation changed")}async function It(){P&&await Ae(P.quote)}async function Ae(e,n){De(e,"checking"),Je="";let t=1e3;Ve=!0,K(a.onObservationChange,!0);try{for(let r=n;E();r=void 0){if(!r){try{r=await i.read()}catch(l){if(!rn(l))throw l}if(!E())return}if(r){an(r,e);let l=R(r);if(l.type==="checkout"){De(e,"payment"),f.textContent=o?"请先完成原订单的付款。":"Finish paying for this upgrade.",y.hidden=!1;return}if(l.type==="complete"){De(e,"complete"),m=null;let c=d.capabilities.plans[e.productVersionId]?.name,s=e.merchantTerms?.subscriptionTerms?.items,u=s?.length===1?s[0].interval:void 0,I=u==="year"?o?"年付":"annual billing":u==="month"?o?"月付":"monthly billing":null;f.textContent=c?o?`已升级到 ${c}${I?" "+I:""}。`:`Upgraded to ${c}${I?" ("+I+")":""}.`:o?"已成功升级。":"Plan upgraded.",await nn(r);return}if(l.type==="native"&&!Se(r)){De(e),b=null,m=null,f.textContent=o?"付款没有成功,套餐未变更。请检查付款方式后重新选择套餐。":"Your payment didn’t go through, so your plan is unchanged. Check your payment method, then choose a plan again.",y.textContent=o?"重试":"Retry";return}if(r.problem&&!["RESULT_UNKNOWN","STATE_CHANGED"].includes(r.problem.reason??""))throw new k(r.problem.code,o?"暂时无法完成升级。":"The upgrade needs attention.",void 0,void 0,r.problem)}await Ye(t,h,Z.signal),t=Math.min(t*1.5,15e3)}}finally{Ve=!1,K(a.onObservationChange,!1)}}async function xt(){let e=P?.quote;if(!e)return;let n=await i.read();if(an(n,e),R(n).type!=="checkout")return Ae(e,n);if(a.resumeCheckout){await a.resumeCheckout(n.operationId);return}He.delete(n.operationId),await Qe(n)}function on(e){return Nt(i).type==="recording"||R(e).type==="recording"}function sn(e){let n=e.merchantTerms,t=n?.subscriptionTerms?.items??[],r=n?n.totalMinor:L(e)?e.totalMinor:e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),l=n?t.length===1&&t[0]?.amountMinor===r&&t[0]:!L(e)&&e.lines.length===1&&e.lines[0]?.catalogAmountMinor===r&&e.lines[0],c=r===null?ve(n.subtotalMinor-n.discountMinor,e.currency)+(o?" + 待确认税费":" + tax confirmed at checkout"):ve(r,e.currency)+(l?Le(l.interval,o?"zh-CN":"en",l.intervalCount??1):""),s=L(e)?i.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(u=>u.productName).join(", ");return{label:s?`${s} · ${c}`:c,recurring:l}}async function H(e,n=a.checkoutNavigation!=="after_confirmation"){if(w)return;if(!E()){m=async()=>H(await i.read()),y.hidden=!1;return}let t=e.quote??i.quote;if(gt(t)&&(e.confirmedAt||e.merchantExecution))return Ae(t,e);if(f.textContent=On(e.status,o),on(e)){let p=e.merchantExecution?.recordingStatus==="failed";f.textContent=p?o?"付款和商户处理已完成,但交易记录失败。请联系商户修复,勿重复购买。":"Payment and fulfillment succeeded, but recording failed. Contact the merchant to repair this purchase; do not buy again.":o?"付款和商户处理已完成,正在确认交易记录。请勿重复购买。":"Payment and merchant fulfillment are complete. Recording is pending confirmation; do not purchase again.",y.textContent=o?"查询记录":"Check recording",m=async()=>H(await i.read()),y.hidden=!1;return}if(e.problem&&R(e).type!=="native"){let p=e.problem;m=_e,y.textContent=o?"检查并恢复原操作":"Check and recover original purchase",Ce(new k(p.code,p.reason==="RESULT_UNKNOWN"?o?"付款结果尚未确定,请恢复原操作,暂勿重复购买。":"The payment result is unknown. Recover the original purchase before buying again.":p.phase==="fulfillment"?o?"付款已记录,商户权益处理需要核对。":"Payment was recorded. Access fulfillment needs attention.":p.code==="CAPABILITY_UNAVAILABLE"?o?"商户尚不支持本次购买所需的完整能力,请处理后恢复原操作。":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":p.code==="NOT_CONFIGURED"?o?"付款服务连接需要处理,请联系商户后恢复原操作。":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":o?"原购买操作需要处理,请查询或恢复此操作。":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,p));return}if((e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"||e.merchantExecution?.type==="subscription_change"&&e.merchantExecution.status==="applied")&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(f.textContent=o?"付款已记录,正在等待商户完成处理。":"Payment was recorded. Waiting for merchant fulfillment."),Ge(e)&&R(e).type==="complete"){m=null,await nn(e);return}let r=Ot(e);if((r||!Se(e))&&R(e).type!=="fulfillment"){if(i.canReselect===!1||r&&Se(e)&&i.canReselect!==!0){f.textContent=o?"正在核对原购买结果":"Checking the original purchase result",y.textContent=o?"查询结果":"Check result",m=async()=>H(await i.read()),y.hidden=!1;return}r?f.textContent=o?"结账未启动,可以重新选择方案。":"Checkout didn’t start. Choose a plan to try again.":e.status==="cancelled"?f.textContent=o?"这笔购买已取消,可以重新选择方案。":"This purchase was cancelled. Choose a plan to start again.":e.status==="failed"&&(f.textContent=o?"这笔购买未能完成,可以重新选择方案。":"This purchase didn’t go through. Choose a plan to try again."),y.textContent=o?"重试":"Retry",m=null,b=null;return}if(!n&&R(e).type==="checkout"){if(F){Xt();return}if(ge()){f.textContent="",it=!1,m=null,y.hidden=!0,D?.updateCapabilities?.(oe(d),xe(d)),Ee();return}let p=i.quote,x=p?.operationId===e.operationId?sn(p).label:"";f.textContent=it?x?o?`${x} 尚未付款。再次选择该方案即可继续付款。`:`${x} is still unpaid. Choose it again to continue paying.`:o?"之前的购买尚未付款。再次选择该方案即可继续付款。":"Your earlier purchase is still unpaid. Choose that plan again to continue paying.":"",it=!1,m=null;return}await Qe(e);let l=Date.now(),c=l+6e5,s=2e3,u=R(e).type!=="checkout",I=()=>u&&Date.now()-l<15e3;Ve=!0,K(a.onObservationChange,!0);try{for(;!w&&Date.now()<c;){if(await Ye(I()?700:s,h,Z.signal),w)return;if(!E()){m=async()=>H(await i.read()),y.hidden=!1;return}let p=await i.read();if(R(p).type==="checkout"&&(u=!1),!n&&R(p).type==="checkout"){await H(p,!1);return}if(!p.problem&&Se(p)&&await Qe(p),!Se(p)||Ot(p)||p.problem||on(p)){await H(p);return}I()||(s=Math.min(s*1.5,3e4))}}finally{Ve=!1,K(a.onObservationChange,!1)}m=async()=>H(await i.read()),y.hidden=!1}async function Et(e=!1){let n=await i.read();if(w)return;if(!E()){m=()=>Et(e),y.hidden=!1;return}let t=i.quote;if(t&&_t(n,{operationId:t.operationId,currency:t.currency},"The original purchase operation changed"),t&&(ot(n)?["prepared","quoted"].includes(n.status):n.status==="pending")&&(ot(n)||n.quoteFinalized===!1)&&!n.confirmedAt&&!n.checkoutUrl&&!("nativePurchase"in n&&n.nativePurchase)&&!n.merchantExecution&&!n.problem&&!i.pendingCancellation){if(a.purchaseConfirmation!=="paywall"){e?await _e():m=null;return}setTimeout(ln,0,t);return}await H(n,e||void 0)}async function cn(){await Et()}async function Bn(e){f.textContent=wt;let n=Date.now()+12e3;for(;!w&&Date.now()<n&&(await Ye(1500,h,Z.signal),!(w||!E()));){let t;try{t=await i.read()}catch{break}if(t.problem?.reason!=="RESULT_UNKNOWN")return t}return e}async function _e(){if(i.quote&&!(Date.parse(i.quote.expiresAt)>Date.now()))throw new k("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");Jt();let e=i.quote;if(gt(e)){De(e,"checking");let t;try{t=await i.confirm()}catch(r){if(!rn(r))throw r;return Ae(e)}return Ae(e,t)}m=_e;let n=await i.confirm();if(!E()){m=_e,y.hidden=!1;return}if(n.problem?.reason==="RESULT_UNKNOWN"&&(n=await Bn(n)),n.problem){await H(n);return}if(Se(n)){if(R(n).type==="checkout")await Qe(n);else if(n.execution&&n.execution.provider!=="merchant"||"nativePurchase"in n&&n.nativePurchase){if(!a.onPurchase)throw new k("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await a.onPurchase({operation:n,signal:Z.signal})}}m=async()=>H(await i.read()),await H(n,!0)}function ln(e){if(w)return;de?.remove();let n=!(Date.parse(e.expiresAt)>Date.now());f.textContent=n?o?"此报价已过期。请先取消,再重新选择。":"This quote has expired. Cancel it, then choose again.":"";let t=h.createElement("div"),r=h.createElement("button"),l=h.createElement("button"),c=h.createElement("div"),s=h.createElement("p"),u=e.merchantTerms,I=o?"zh-CN":"en",p=u?.subscriptionTerms?.items??[],x=u?u.subscriptionTerms?.trial?.days:L(e)?void 0:e.lines.find(g=>g.trial)?.trial?.days,T=L(e)?u?u.totalMinor:e.totalMinor:x===void 0?null:u?u.totalMinor:e.charge?e.charge.totalMinor:e.lines.every(g=>g.trial)?0:null,Pe=(g,v)=>o?`${v} 天试用结束后 ${g}`:`Then ${g} after the ${v}-day trial`,{label:X,recurring:Ue}=sn(e),St=L(e)?i.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(g=>g.productName).join(", "),pn=T===null?"":`${o?"今天应付":"Due today"} ${ve(T,e.currency)}`;s.textContent=pn?[St,pn].filter(Boolean).join(" · "):X,r.textContent=L(e)?o?"确认变更":"Confirm change":o?"确认购买":"Confirm purchase",r.disabled=n,l.textContent=o?"取消":"Cancel",t.style.cssText=U.panel,s.style.cssText=U.summary,c.style.cssText=U.actions,r.style.cssText=U.primary,l.style.cssText=U.secondary,Lt(r),r.onclick=()=>{W(_e)};let fn=async()=>{let g=await i.cancel();w||(t.remove(),de=null,await H(g))};l.onclick=()=>{m=fn,W(fn)};let z=h.createElement("div");if(z.style.cssText=U.terms,L(e)){for(let[v,O]of Object.entries(e.featureQuantities??{})){let B=i.view?.capabilities.plans[e.productVersionId]?.prepaid?.find(jn=>jn.internalFeatureId===v),at=h.createElement("p");at.textContent=`${B?.name??v} · ${O} ${o?"份":"packs"}${B?` × ${B.terms.units}`:""}`,z.append(at)}for(let[v,O]of[[o?"原订阅抵扣":"Unused subscription credit",e.creditMinor],[o?"新套餐费用":"New plan charge",e.debitMinor],[o?"优惠减免":"Offer savings",u?.discountMinor??e.discountMinor],[o?"税费":"Tax",u?u.taxMinor:e.taxMinor]]){let B=h.createElement("p");B.textContent=`${v}: ${O===null?o?"结账时确认":"Confirmed at checkout":ve(O,e.currency)}`,z.append(B)}let g=h.createElement("p");g.textContent=`${o?"生效时间":"Effective"}: ${e.effectiveAt}`,z.append(g)}if(u){for(let v of p){if(T===null&&v===Ue)continue;let O=h.createElement("p"),B=ve(v.amountMinor,e.currency)+Le(v.interval,I,v.intervalCount);O.textContent=T!==null&&x!==void 0?Pe(B,x):B,v.amountAfterOfferMinor!==void 0&&(O.textContent+=` · ${o?"优惠结束后":"After the offer"} ${ve(v.amountAfterOfferMinor,e.currency)}${Le(v.interval,I,v.intervalCount)}`),z.append(O)}let g=u.subscriptionTerms?.trial;if(g){let v=h.createElement("p");v.textContent=o?`试用 ${g.days} 天;${g.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${g.days}; ${g.cardRequired?"a payment method is required":"no payment method is required"}`,z.append(v)}for(let v of[...u.expectedEffects.map(O=>O.description),...u.requiredConsents.map(O=>O.summary)]){let O=h.createElement("p");O.textContent=v,z.append(O)}}else if(!L(e)){for(let g of e.lines){if(T!==null||g!==Ue){let v=h.createElement("p"),O=`${ve(g.catalogAmountMinor,e.currency)}${Le(g.interval,I,g.intervalCount??1)}`;v.textContent=T!==null&&g.trial?(e.lines.length>1?`${g.productName} · `:"")+Pe(O,g.trial.days):`${g.productName} · ${O}`,z.append(v)}for(let v of g.prepaid??[]){let O=h.createElement("p"),B=i.view?.capabilities.plans[g.productVersionId]?.prepaid?.find(at=>at.internalFeatureId===v.internal_feature_id);O.textContent=`${B?.name??v.internal_feature_id} · ${v.quantity} ${o?"份":"packs"} × ${v.terms.units}`,B&&(O.textContent+=Le(B.reset==="week"||B.reset==="month"||B.reset==="year"?B.reset:"one_time",I,B.resetCount)),z.append(O)}if(g.trial){let v=h.createElement("p");v.textContent=o?`试用 ${g.trial.days} 天;${g.trial.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${g.trial.days}; ${g.trial.cardRequired?"a payment method is required":"no payment method is required"}`,z.append(v)}}if(!e.charge){let g=h.createElement("p");g.textContent=o?"目录价格;最终金额以结账时税费和试用规则为准。":"Catalog price; the final charge depends on checkout taxes and trial terms.",z.append(g)}}for(let g of z.children)g.style.margin="0";c.append(r,l),t.append(s,...z.childElementCount?[z]:[],c),Y.prepend(t),V?.responsive||t.scrollIntoView?.({block:"nearest"}),r.focus({preventScroll:!0}),de=t,fe&&je(!0),m=null}async function qe(){if(!b)return;if(a.onPurchaseIntent&&!ye&&!i.quote&&!i.operation){let t=b,r=i.view,l=r?.document.buttons[t.actionId],c=r&&l?.type==="checkout"?ke(l.product,t.selection,r.capabilities):null;if(!r||!c)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");let s={actionId:t.actionId,productVersionId:c,selection:structuredClone(t.selection),featureQuantities:Ie(r.document.screen,c,t.selection,r.capabilities),...$&&{coupon:{id:$.id,...$.offerId&&{offerId:$.offerId}}}};b=null,$=void 0,m=null,Ke=!0,await a.onPurchaseIntent(s);return}if(m=qe,!ye){let t=i.view,r=t?.document.buttons[b.actionId],l=t&&r?.type==="checkout"?ke(r.product,b.selection,t.capabilities):null;if(!t||!l)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");if(!Te){let s=Wt(),u=s?await s.result:void 0;if(w)return;let I=a.resolveSubscriptionChange;if(I||u){let p={actionId:b.actionId,productVersionId:l,featureQuantities:Ie(t.document.screen,l,b.selection,t.capabilities)},x=u?[async()=>u(p)]:[],T=I?await I(p,...x):await x[0]?.();if(w)return;T!==void 0&&(b.subscriptionChange=mn.parse(T))}Te=!0}let c=$?.offerId;if($&&!c){if(!a.claimCoupon)throw new k("CAPABILITY_UNAVAILABLE","Coupon claiming is unavailable");let{offer:s}=await a.claimCoupon($.id,b.requestId);if(w)return;if(!s||s.couponId!==$.id||s.status!=="issued"||!(Date.parse(s.expiresAt)>Date.now()))throw b=null,$=void 0,m=async()=>{$e(await i.refresh()),m=null},new k("COUPON_UNAVAILABLE","This Coupon is no longer available for this purchase");c=s.id}if(!$&&!t.document.screen.actions.some(s=>s.id===b?.actionId&&typeof s.properties.couponBinding=="string")&&(c=await a.resolveOfferId?.({actionId:b.actionId,productVersionId:l,featureQuantities:Ie(t.document.screen,l,b.selection,t.capabilities)})),w)return;c!==void 0&&(b.offerId=c),ye=!0}if(!E()){y.hidden=!1;return}let e;try{e=await i.preview(b)}catch(t){throw i.canReselect===!0&&(b=null,ye=!1,Te=!1,$=void 0,m=null),t}if(b.acceptHostedMonthly!==void 0){let t=i.operation;if(!t||t.operationId!==e.operationId||!t.confirmedAt)throw new k("INVALID_RESPONSE","The confirmed Checkout is missing");w||await H(t,!0);return}if($&&(L(e)?(()=>{let t=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return t?.couponId!==$.id||t.grantId!==b.offerId})():e.discount?.couponId!==$.id||e.discount.offerId!==b.offerId))throw new k("INVALID_RESPONSE","The quote did not apply the Coupon selected on this Paywall");if(w)return;let n=e.merchantTerms;if(a.purchaseConfirmation!=="paywall"||a.confirmOnHostedCheckout&&E()&&!L(e)&&e.provider==="merchant"&&e.billingSubscriptionId===null&&n?.request.action==="purchase"&&n.request.mode==="subscription"&&n.subscriptionTerms?.trial===null&&n.requiredConsents.length===0&&Date.parse(e.expiresAt)>Date.now()){if(!E()){y.hidden=!1;return}if(!(Date.parse(e.expiresAt)>Date.now()))throw new k("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");let t=ae?"":o?"正在打开收银台…":"Opening checkout…";f.textContent=t;try{await _e()}catch(r){w||Ce(r)}finally{f.textContent===t&&(f.textContent="")}return}ln(e)}function Re(e="destroy",n=!1){if(w)return;w=!0;let t=ht;ht=void 0,K(t),a.signal?.removeEventListener("abort",se),i.signal?.removeEventListener("abort",se),Q.finish("dismissed"),$t?.(),vt(),h.removeEventListener("visibilitychange",Gt),Z.abort(),Vt?.disconnect(),D?.destroy(),i.destroy(),S.removeEventListener("cancel",dn),_.remove(),M.remove(),n||un(),e==="dismiss"&&K(a.onDismiss)}function un(){if(V?.destroy(),ue){ue.release();return}S.open&&S.close(),S.remove(),N()}G=Re;async function Fe(){if(!he||w||ze||ie==="closing"||!ie&&!E())return;if(!A){Re("dismiss");return}let e=h.createElement("p");e.setAttribute("role","status"),e.textContent=o?"正在关闭…":"Closing…",me||(me=h.createElement("div"),me.style.cssText=Y.style.cssText,Y.replaceWith(me),pe.inert=!0),_.hidden=!1,me.replaceChildren(e,_),ie="closing",_.setAttribute("aria-disabled","true"),_.focus({preventScroll:!0});try{await A.dismiss()}catch(n){w||K(a.onError,n)}w||(ie="retry",e.textContent=o?"未能确认关闭,请重试。":"Could not confirm closure. Try again.",_.textContent=o?"重试关闭":"Retry closing",_.removeAttribute("aria-label"),_.removeAttribute("aria-disabled"))}_.onclick=()=>{Fe()};function dn(e){e.preventDefault(),Fe()}S.addEventListener("cancel",dn),le.onclick=()=>{W(P?xt:tt)},y.onclick=()=>{if(q){q.retry?.();return}m&&W(m)};function At(e){Q.finish("error",e),Re()}function Rt(){if(!(!Bt||he||w||ze||V&&!E()))try{let e=n=>{a.focusAtReveal&&(N=Ut(h)),a.settleMotionAtReveal?D?.setHidden?.(!1,!0):D?.setHidden?.(!1),mt?.(),V&&(S.open||S.showModal(),V.responsive&&S.focus({preventScroll:!0}),!n&&a.loading!=="host"&&vn(S,V.type,V.responsive)),n&&a.loading!=="host"&&typeof pe.animate=="function"&&!h.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches&&pe.animate([{opacity:.55},{opacity:1}],{duration:160,easing:"ease-out"}),he=!0,Ze()};A?A.present(n=>Q.present(t=>e(n??t))):Q.present(e)}catch(e){At(e),Ce(e)}}try{if(Me.type==="inline"?(dt(),mt=Rn(M,j),j.append(M)):(S.setAttribute("aria-label",d.document.name),_.textContent="×",_.setAttribute("aria-label",o?"关闭":"Close"),kn(_,d.document.screen.theme),_.hidden=bn(d.document),(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&ue?.content?ue.content.append(_,M):S.replaceChildren(_,M),ue||j.append(S),V=Pn(S,{...d.document.screen,presentation:Me},ft),V.latch(),V.responsive&&(M.style.display="flex",M.style.flexDirection="column",M.style.maxHeight="100%",pe.style.overflow="clip",pe.style.minHeight="0"),ue||(mt=An(S))),lt&&ee){let t=lt(ee);if(typeof t=="function"&&(w?K(t):ht=t),w)throw new DOMException("Presentation cancelled","AbortError");dt()}D=ne(pe,{mode:"live",rendererUrl:"bundled",title:d.document.name,closeActions:Mn,onAuthoredClose(t){ie||w||(_.hidden=t)},hostPresentation:()=>V?.type??Me.type,reportContentHeight:V?.responsive,onResize:t=>{if(!V?.responsive)return;let r=Math.min(t,pt);pe.style.height=`${r}px`,V.setContentHeight(r+Qt())},onSelection(t){for(let[r,l]of Object.entries(t))typeof l=="number"&&typeof J[r]=="number"&&J[r]!==l&&jt.add(r);J=t,Ee(),Ze()},onAction(t,r={},l,c){if(!he||w||ie)return;let s=i.view,u=s?.document.buttons[t];if(!u)return;if(q){u.type==="close"&&Fe();return}if(u.type==="close"&&A&&a.resumeCheckout&&i.operation&&gn(R(i.operation))){Fe();return}if(fe)return;if(!E()){kt();return}if(u.type==="close"){W(async()=>{A?.closeAction?await A.closeAction(t):await a.onAction?.(t),Re(a.onAction?"action":"dismiss")});return}if(u.type==="action"){m=async()=>{if(u.action.type==="event"){if(!a.onEvent)throw new k("EVENT_HANDLER_REQUIRED","Provide the event handler");await a.onEvent(u.action.event)}else a.onOpenUrl?await a.onOpenUrl(u.action.url):h.defaultView?.location.assign(u.action.url);await a.onAction?.(t),m=null},W(m);return}if(ge()&&F){!we&&F.selection.actionId===t&&W(()=>nt(!0),t);return}if(P){if(P.phase==="payment"&&s&&Ne(P.quote,s,t,u.product,r,c)){W(xt,t);return}if(!Ct())return}if(!be()&&!Ct()){ge()&&s&&i.quote&&i.operation&&R(i.operation).type==="checkout"&&Ne(i.quote,s,t,u.product,r,c)?W(tt,t):f.textContent=o?"当前只能继续原订单。":"Only your original checkout is available.";return}if(de&&i.canReselect===!1){f.textContent=o?"请先确认或取消当前购买。":"Confirm or cancel the current purchase first.",V?.responsive||de.scrollIntoView?.({block:"nearest"}),de.querySelector("button")?.focus({preventScroll:!0});return}if(ge()&&a.terminateCheckout&&s&&i.quote&&i.operation&&i.canReselect===!1&&R(i.operation).type==="checkout"){if(Ne(i.quote,s,t,u.product,r,c)){W(tt,t);return}let p=ke(u.product,r,s.capabilities),x;try{if(!p)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");x=Ie(s.document.screen,p,r,s.capabilities)}catch(Ue){Ce(Ue);return}let T=i.operation.operationId,Pe={actionId:t,requestId:crypto.randomUUID(),selection:structuredClone(r)},X=rt(s,t,p,r,c);W(()=>Zt(T,Pe,X,{actionId:t,productVersionId:p,selection:Pe.selection,featureQuantities:x}),t);return}if((i.quote||b)&&i.canReselect===!1){let p=!!s&&!!i.quote&&Ne(i.quote,s,t,u.product,r,c);it=!!i.quote&&!p,m=i.quote?()=>Et(p):qe,W(m,t);return}let I=s&&ke(u.product,r,s.capabilities);if(!s||!I){Ce(new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(a.onPurchaseIntent){m=null;let p=async()=>{let x={actionId:t,productVersionId:I,selection:structuredClone(r),featureQuantities:Ie(s.document.screen,I,r,s.capabilities)},T=rt(s,t,I,r,c);T&&(x.coupon={id:T.id,...T.offerId&&{offerId:T.offerId}}),Ke=!0,await a.onPurchaseIntent(x)};tn.add(p),W(p,t);return}if(b&&b.actionId!==t){Ce(new k("COMMAND_PENDING","Finish the current purchase"));return}if(!b){$=rt(s,t,I,r,c),b={requestId:crypto.randomUUID(),actionId:t,selection:structuredClone(r)};let p=s.document.screen.actions.find(Pe=>Pe.id===t)?.properties,x=p?.hostedMonthlyPriceMinor,T=p?.hostedMonthlyAutomaticTax;a.purchaseConfirmation==="purchase_button"&&a.confirmOnHostedCheckout&&i.supportsHostedCheckout===!0&&!$&&u.product.type==="fixed"&&typeof T=="boolean"&&typeof x=="number"&&Number.isSafeInteger(x)&&x>0&&x<=1e8&&Object.keys(Ie(s.document.screen,I,r,s.capabilities)).length===0&&(b.acceptHostedMonthly={amountMinor:x,automaticTax:T}),ye=b.acceptHostedMonthly!==void 0,Te=ye}W(qe,t)},onEscape:()=>{Fe()},onError:t=>{let r=new Error(t);!he&&!w&&At(r),Ce(r)},onRendered:t=>{t&&S.setAttribute("aria-label",t),Bt=!0,Rt()}}),D.setHidden?.(!0),ft();let e=ge()&&!!i.quote&&!!i.operation&&R(i.operation).type==="checkout";J=i.quote?_n(d,i.quote)??st(d,{}):st(d,{}),D.update(d.document.screen,ut,{capabilities:oe(d),unavailableActions:xe(d),serverInput:{bindings:[],answers:{}},...Object.keys(J).length?{selection:J}:{}}),$t=i.subscribe?.($e),$e(i.view??d),await Q.wait(D.ready);let n=i.operation;(!e||gt(i.quote))&&(i.quote||n&&(n.confirmedAt||n.checkoutUrl||Ge(n)))&&(m=cn,W(m))}catch(e){throw At(e),e}return{check:ce,host:{get currentResolution(){return d},setPurchaseRecovery(e,n){q={message:e,retry:n},D?.updateCapabilities?.(oe(d),xe(d)),Ee(),en()},get subscriptionUpgradeActive(){return P!==void 0},get observing(){return Ve},get recovery(){return Vn()},async prepareFallback(){if(fe||w||ie||Ke)return{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null};je(!0);try{let e=await wn(i);return e.type==="native"&&Re(),e}finally{je(!1)}},setSuspended(e){ze=e,M.hidden=e,e&&S.open?S.close():!e&&!he?Rt():!e&&!w&&he&&Me.type!=="inline"&&!S.open&&S.showModal()},destroy:Re,retainPurchaseDialog(){if(!(w||!S.open||!S.isConnected))return Re("destroy",!0),{dialog:S,content:ue?.content,release:un}},refresh:async()=>{if(!E()){if(i.view)return i.view;throw new k("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await i.refresh();return $e(e),Rt(),e}}}}export{kr as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as o}from"./chunk-
|
|
1
|
+
import{f as o}from"./chunk-CQYEM7U6.js";var n=class extends Error{constructor(t,s,y,i,r){super(s);this.code=t;this.status=y;this.requestId=i;this.name="IndianaError",this.reason=r?.reason;let e=o(t,y??0,{...r,retryAfter:r?.retryAfterSeconds===void 0?void 0:String(r.retryAfterSeconds)});this.retryable=e.retryable,this.recovery=e.recovery,this.retryAfterSeconds=e.retryAfterSeconds}code;status;requestId;commandRequestId;retryable;recovery;retryAfterSeconds;reason};export{n as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as B}from"./chunk-AEQUKR4O.js";import{b as Y}from"./chunk-TG7FSNRF.js";import{c as W,e as X,f as Z,g as $,h as ee,i as te}from"./chunk-VJXGTINT.js";import{K as L}from"./chunk-DGGXLPHI.js";import{b as J}from"./chunk-R6NVHYXW.js";import{B as V}from"./chunk-3QRVHAWK.js";import{x as H}from"./chunk-HJLZY2VK.js";import{t as z}from"./chunk-YBDTPMGD.js";import{a as u}from"./chunk-BNVQIMXY.js";import{a as K}from"./chunk-DSPLGTQI.js";async function ye(r){let{session:f,load:d}=ie(r);try{return await d(),f}catch(h){throw f.destroy(),h}}function ie(r){let f=r.view;if(!f?.paywall)throw new u("INVALID_REQUEST","The current node is not a Paywall");let d=f.paywall.receiptId,h=f.nodeId,E=f.visit,R=f.paywall.resolution,n=f.paywall,N="document"in R?{document:R.document,offering:R.offering,capabilities:R.capabilities}:null;function D(){let e=n.resolution;return"document"in e?e:N&&{...e,document:N.document,offering:N.offering,capabilities:W(e.capabilities,N.capabilities)}}function F(e){if(!X(e,R))throw new u("INVALID_RESPONSE","The pinned Paywall binding changed")}let p=!1,A=new Set,_=null;function G(){let e=D();if(e&&!p)for(let o of A)K(o,structuredClone(e))}async function M(){b();let e=D();if(e)return structuredClone(e);if(!_){let o=(async()=>{if("document"in n.resolution||!r.resolvePaywall)throw new u("INVALID_RESPONSE","Public Paywall reader is unavailable");let s=await B(r,n.resolution);return b(),F(s),N={document:s.document,offering:s.offering,capabilities:s.capabilities},G(),D()})();_=o;let t=()=>{_===o&&(_=null)};o.then(t,t)}return _.then(o=>structuredClone(o))}let q=new AbortController,m=(r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])).find(e=>e.operation==="submit"&&e.nodeId===h&&e.visit===E&&e.input.type==="paywall_quote")?.requestId??f.paywall.purchaseRequestId,C=0,g=null,T=new Set,I=null,v=new Map;function U(e){if(e.purchase&&e.purchase.receiptId!==d)throw new u("INVALID_RESPONSE","Purchase receipt changed");let o=e.run.paywall;return e.purchase??(o?.receiptId===d?o:null)}function b(){if(p)throw new u("IDENTITY_CHANGED","Paywall presentation has closed")}function S(e,o,t){if(b(),o!==C||t!==void 0&&n.quote?.operationId!==t)return!1;let s=n.selectionGeneration??0,i=e.run.paywall;if(i?.receiptId===d){if((i.selectionGeneration??0)<(n.selectionGeneration??0))return!1;F(i.resolution)}let a=U(e),c=i?.receiptId===d&&(i.selectionGeneration??0)>s,l=c?a?.quote??null:a?.quote??n.quote,y=a?.operation??(l?.operationId===n.quote?.operationId?n.operation:null);return n.quote&&l&&ee(n.quote,l),l&&y&&Z(y,{operationId:l.operationId,membershipId:V(l)?l.membershipId:null,...V(l)?{featureQuantities:l.featureQuantities??{}}:{}},"Purchase operation changed"),(c||l?.operationId!==n.quote?.operationId)&&(C++,i?.receiptId===d&&(m=i.purchaseRequestId)),i?.canReselect===!0&&i.purchaseRequestId===I&&!(r.pendingCommands??[r.pendingCommand]).some(w=>w?.requestId===I)&&(I=null),n={...n,...i?.receiptId===d?i:{},...t!==void 0&&!c&&a?.canReselect!==void 0?{canReselect:a.canReselect}:{},quote:l,operation:te(n.operation,y,!0)},G(),!0}function O(e,o,t){return new Promise((s,i)=>{let a=!1,c=()=>{clearTimeout(P),q.signal.removeEventListener("abort",w)},l=Q=>{a||(a=!0,c(),s(Q))},y=Q=>{a||(a=!0,c(),i(Q))},w=()=>y(new u("IDENTITY_CHANGED","Paywall presentation has closed")),P=setTimeout(()=>y(new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t)),Math.max(0,o-Date.now()));q.signal.addEventListener("abort",w,{once:!0}),q.signal.aborted&&w(),e.then(l,y)})}function ne(e){return new Promise(o=>{let t=()=>{clearTimeout(s),q.signal.removeEventListener("abort",t),o()},s=setTimeout(t,e);q.signal.addEventListener("abort",t,{once:!0}),q.signal.aborted&&t()})}function j(e,o){b();let t=v.get(e)??r.pendingCommands?.find(a=>a.requestId===e)??r.pendingCommand;if(t?.operation==="submit"&&t.requestId===e&&t.nodeId===h&&t.visit===E){o.type==="paywall_quote"&&t.input.type==="paywall_quote"&&t.input.predecessor&&!o.predecessor&&(o={...o,predecessor:t.input.predecessor});let a=L.parse(t),c=L.parse({...t,input:o});if(a.operation!=="submit"||c.operation!=="submit"||JSON.stringify(a.input)!==JSON.stringify(c.input))throw new u("CONFLICT","A purchase request cannot change its input");return v.set(e,a),a}let s=r.view;if(!s||s.nodeId!==h||s.visit!==E||s.paywall?.receiptId!==d)throw new u("PRECONDITION_FAILED","The Paywall visit has changed");let i=L.parse({operation:"submit",requestId:e,nodeId:h,visit:E,revision:s.revision,input:structuredClone(o)});if(i.operation!=="submit")throw new u("INVALID_REQUEST","A purchase submission is required");return v.set(e,i),i}async function x(e,o){b();let{requestId:t,input:s}=e,i=Date.now()+3e4;T.add(t);try{let a=await O(r.submit(e),i,t);for(;a.run.pendingRequest?.requestId===t&&Date.now()<i&&!p&&(await ne(Math.min(1e3,i-Date.now())),!(p||Date.now()>=i));)a=await O(r.resume(t),i,t);if(p)throw new u("IDENTITY_CHANGED","Paywall presentation has closed");if(a.run.pendingRequest?.requestId===t)throw new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t);if(!S(a,o,s.type==="paywall_confirm"||s.type==="paywall_cancel"?s.operationId:void 0))throw new u("PRECONDITION_FAILED","The purchase selection has changed");I===t&&(I=null)}catch(a){if(I=t,s.type==="paywall_quote"&&r.settle&&!p&&a instanceof u&&a.status!==void 0&&![401,425].includes(a.status)&&!a.retryable&&a.recovery!=="recover_operation")try{if((await O(r.settle(t),i,t)).settlement?.state==="settled"){let l=await O(r.get(),i,t);S(l,o)&&l.run.paywall?.purchaseRequestId===t&&n.canReselect===!0&&v.delete(t)}}catch{}throw a instanceof u&&a.code==="COMMAND_PENDING"&&a.status===void 0&&v.delete(t),a}finally{T.delete(t)}}async function k(e){if(!n.quote)throw new u("INVALID_REQUEST","A quoted purchase is required");let o=e==="confirm"?"paywall_confirm":"paywall_cancel",t=[...v.values(),...r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])].find(i=>i.operation==="submit"&&i.input.type===o&&"operationId"in i.input&&i.input.operationId===n.quote.operationId),s=t?.operation==="submit"&&t.input.type===o&&"operationId"in t.input&&t.input.operationId===n.quote.operationId?t.requestId:crypto.randomUUID();if(await x(j(s,{type:e==="confirm"?"paywall_confirm":"paywall_cancel",operationId:n.quote.operationId,...e==="confirm"&&n.quote.merchantTerms?{merchantConfirmation:H(n.quote.merchantTerms)}:{}}),C),!n.operation)throw new u("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(n.operation)}let oe={get supportsHostedCheckout(){return!m&&!n.operation&&(n.selectionGeneration??0)===0},get view(){return structuredClone(D())},get quote(){return n.quote?structuredClone(n.quote):null},get operation(){return n.operation?structuredClone(n.operation):null},get webViewUrl(){return r.webViewUrl},get locale(){return r.view?.locale??f.locale},get canReselect(){return n.canReselect===!0&&I===null},get recovery(){let e=r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[]),o=r.pendingPurchase;if(o&&(o.receiptId!==d||o.operationId!==n.quote?.operationId))return{type:"recover",operationId:o.operationId,requestId:e[0]?.requestId??null};let t=Y({quote:n.quote,operation:n.operation,requestId:e[0]?.requestId??I??m,pending:T.size>0||e.length>0||I!==null,destroyed:p,canReselect:n.canReselect});return t.type==="recover"&&t.requestId===null&&!p&&r.hasDurableJournal===!0&&!n.quote&&!n.operation&&(n.selectionGeneration??0)===0&&!o&&!e.length&&!T.size&&!m?{type:"native",operationId:null}:t},get pendingCancellation(){return!p&&(r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])).some(e=>e.operation==="submit"&&e.nodeId===h&&e.visit===E&&e.input.type==="paywall_cancel"&&e.input.operationId===n.quote?.operationId)},subscribe(e){return p?()=>{}:(A.add(e),()=>A.delete(e))},async refresh(){b();let e=C,o=await r.get();if(S(o,e),o.run.paywall?.receiptId!==d)throw new u("PRECONDITION_FAILED","Paywall presentation has changed");return M()},preview(e){let o=D();if(!o)return Promise.reject(new u("PRECONDITION_FAILED","Load the Paywall presentation first"));if(m&&m!==e.requestId&&(g||n.canReselect!==!0))return Promise.reject(new u("COMMAND_PENDING","Retry the original purchase before starting another"));let t=o.document.buttons[e.actionId],s=t?.type==="checkout"?J(t.product,e.selection,o.capabilities):null;if(!s)return Promise.reject(new u("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let i=z(o.document.screen,s,e.selection,o.capabilities),a=m!==e.requestId&&(n.selectionGeneration??0)>0?{operationId:n.quote?.operationId??null,generation:n.selectionGeneration??0}:void 0,c=r.view?.parameters.commerce;if(c&&typeof c=="object"&&!Array.isArray(c)&&c.intent==="subscription_change"&&!e.subscriptionChange)return Promise.reject(new u("INVALID_REQUEST","Choose the existing membership for this subscription change"));if(e.subscriptionChange&&e.nativeOffer)return Promise.reject(new u("INVALID_REQUEST","A web membership change cannot include a store offer"));if(a&&n.canReselect!==!0)return Promise.reject(new u("COMMAND_PENDING","Original purchase requires authoritative termination"));let l;try{l=j(e.requestId,{type:"paywall_quote",...e.acceptHostedMonthly===void 0?{}:{acceptHostedMonthly:e.acceptHostedMonthly},actionId:e.actionId,productVersionId:s,...Object.keys(i).length?{featureQuantities:i}:{},...a?{predecessor:a}:{},...e.offerId?{offerId:e.offerId}:{},...e.nativeOffer?{nativeOffer:e.nativeOffer}:{},...e.subscriptionChange?{subscriptionChange:e.subscriptionChange}:{}})}catch(P){return Promise.reject(P)}if(m===e.requestId&&g)return g;m!==e.requestId&&C++;let y=C;m=e.requestId;let w=(async()=>{if(await x(l,y),!n.quote)throw new u("INVALID_RESPONSE","The accepted quote is missing");return $(n.quote,{productVersionId:s,featureQuantities:i,subscriptionChange:e.subscriptionChange},"The selected purchase changed"),structuredClone(n.quote)})();return g=w,w.then(()=>{g===w&&(g=null)},P=>{g===w&&(g=null),m===e.requestId&&r.pendingCommand?.requestId!==e.requestId&&P instanceof u&&P.status!==void 0&&P.status<500&&![401,425].includes(P.status)&&(m=null)}),w},confirm:()=>k("confirm"),cancel:()=>k("cancel"),async read(){if(b(),!n.quote)throw new u("INVALID_REQUEST","A quoted purchase is required");let e=n.quote.operationId,o=C,t=r.pendingCommands?.find(l=>l.operation==="submit"&&(l.input.type==="paywall_confirm"||l.input.type==="paywall_cancel")&&l.input.operationId===e)??r.pendingCommand;t?.operation==="submit"&&(t.input.type==="paywall_confirm"||t.input.type==="paywall_cancel")&&t.input.operationId===e&&await r.settle?.(t.requestId);let s=await r.get(void 0,{receiptId:d,operationId:e});b();let i=U(s);if(i?.quote&&i.quote.operationId!==e||i?.operation&&i.operation.operationId!==e)throw new u("INVALID_RESPONSE","Purchase operation changed");let a=S(s,o,e),c=a?n.operation:i?.operation;if(!c)throw new u("INVALID_RESPONSE","The current purchase result is missing");return a&&T.size===0&&!(r.pendingCommands?.length??(r.pendingCommand?1:0))&&(I=null),structuredClone(c)},destroy(){p=!0,re(),A.clear(),q.abort(),v.clear()}},re=r.subscribe(e=>{p||e.nodeId!==h||e.visit!==E||e.paywall?.receiptId!==d||(e.paywall.selectionGeneration??0)<(n.selectionGeneration??0)||(F(e.paywall.resolution),n={...n,resolution:e.paywall.resolution},G())});return{session:oe,load:M}}export{ye as a};
|
|
1
|
+
import{b as B}from"./chunk-AEQUKR4O.js";import{b as Y}from"./chunk-HMT4SHIK.js";import{c as W,e as X,f as Z,g as $,h as ee,i as te}from"./chunk-MUU6LV3R.js";import{K as L}from"./chunk-MEBCS2JG.js";import{b as J}from"./chunk-ZAD5WJWS.js";import{B as V}from"./chunk-F54HTDAC.js";import{x as H}from"./chunk-ZMDKCBLI.js";import{t as z}from"./chunk-OKHCU6ET.js";import{a as u}from"./chunk-AECGOS7O.js";import{a as K}from"./chunk-DSPLGTQI.js";async function ye(r){let{session:f,load:d}=ie(r);try{return await d(),f}catch(h){throw f.destroy(),h}}function ie(r){let f=r.view;if(!f?.paywall)throw new u("INVALID_REQUEST","The current node is not a Paywall");let d=f.paywall.receiptId,h=f.nodeId,E=f.visit,R=f.paywall.resolution,n=f.paywall,N="document"in R?{document:R.document,offering:R.offering,capabilities:R.capabilities}:null;function D(){let e=n.resolution;return"document"in e?e:N&&{...e,document:N.document,offering:N.offering,capabilities:W(e.capabilities,N.capabilities)}}function F(e){if(!X(e,R))throw new u("INVALID_RESPONSE","The pinned Paywall binding changed")}let p=!1,A=new Set,_=null;function G(){let e=D();if(e&&!p)for(let o of A)K(o,structuredClone(e))}async function M(){b();let e=D();if(e)return structuredClone(e);if(!_){let o=(async()=>{if("document"in n.resolution||!r.resolvePaywall)throw new u("INVALID_RESPONSE","Public Paywall reader is unavailable");let s=await B(r,n.resolution);return b(),F(s),N={document:s.document,offering:s.offering,capabilities:s.capabilities},G(),D()})();_=o;let t=()=>{_===o&&(_=null)};o.then(t,t)}return _.then(o=>structuredClone(o))}let q=new AbortController,m=(r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])).find(e=>e.operation==="submit"&&e.nodeId===h&&e.visit===E&&e.input.type==="paywall_quote")?.requestId??f.paywall.purchaseRequestId,C=0,g=null,T=new Set,I=null,v=new Map;function U(e){if(e.purchase&&e.purchase.receiptId!==d)throw new u("INVALID_RESPONSE","Purchase receipt changed");let o=e.run.paywall;return e.purchase??(o?.receiptId===d?o:null)}function b(){if(p)throw new u("IDENTITY_CHANGED","Paywall presentation has closed")}function S(e,o,t){if(b(),o!==C||t!==void 0&&n.quote?.operationId!==t)return!1;let s=n.selectionGeneration??0,i=e.run.paywall;if(i?.receiptId===d){if((i.selectionGeneration??0)<(n.selectionGeneration??0))return!1;F(i.resolution)}let a=U(e),c=i?.receiptId===d&&(i.selectionGeneration??0)>s,l=c?a?.quote??null:a?.quote??n.quote,y=a?.operation??(l?.operationId===n.quote?.operationId?n.operation:null);return n.quote&&l&&ee(n.quote,l),l&&y&&Z(y,{operationId:l.operationId,membershipId:V(l)?l.membershipId:null,...V(l)?{featureQuantities:l.featureQuantities??{}}:{}},"Purchase operation changed"),(c||l?.operationId!==n.quote?.operationId)&&(C++,i?.receiptId===d&&(m=i.purchaseRequestId)),i?.canReselect===!0&&i.purchaseRequestId===I&&!(r.pendingCommands??[r.pendingCommand]).some(w=>w?.requestId===I)&&(I=null),n={...n,...i?.receiptId===d?i:{},...t!==void 0&&!c&&a?.canReselect!==void 0?{canReselect:a.canReselect}:{},quote:l,operation:te(n.operation,y,!0)},G(),!0}function O(e,o,t){return new Promise((s,i)=>{let a=!1,c=()=>{clearTimeout(P),q.signal.removeEventListener("abort",w)},l=Q=>{a||(a=!0,c(),s(Q))},y=Q=>{a||(a=!0,c(),i(Q))},w=()=>y(new u("IDENTITY_CHANGED","Paywall presentation has closed")),P=setTimeout(()=>y(new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t)),Math.max(0,o-Date.now()));q.signal.addEventListener("abort",w,{once:!0}),q.signal.aborted&&w(),e.then(l,y)})}function ne(e){return new Promise(o=>{let t=()=>{clearTimeout(s),q.signal.removeEventListener("abort",t),o()},s=setTimeout(t,e);q.signal.addEventListener("abort",t,{once:!0}),q.signal.aborted&&t()})}function j(e,o){b();let t=v.get(e)??r.pendingCommands?.find(a=>a.requestId===e)??r.pendingCommand;if(t?.operation==="submit"&&t.requestId===e&&t.nodeId===h&&t.visit===E){o.type==="paywall_quote"&&t.input.type==="paywall_quote"&&t.input.predecessor&&!o.predecessor&&(o={...o,predecessor:t.input.predecessor});let a=L.parse(t),c=L.parse({...t,input:o});if(a.operation!=="submit"||c.operation!=="submit"||JSON.stringify(a.input)!==JSON.stringify(c.input))throw new u("CONFLICT","A purchase request cannot change its input");return v.set(e,a),a}let s=r.view;if(!s||s.nodeId!==h||s.visit!==E||s.paywall?.receiptId!==d)throw new u("PRECONDITION_FAILED","The Paywall visit has changed");let i=L.parse({operation:"submit",requestId:e,nodeId:h,visit:E,revision:s.revision,input:structuredClone(o)});if(i.operation!=="submit")throw new u("INVALID_REQUEST","A purchase submission is required");return v.set(e,i),i}async function x(e,o){b();let{requestId:t,input:s}=e,i=Date.now()+3e4;T.add(t);try{let a=await O(r.submit(e),i,t);for(;a.run.pendingRequest?.requestId===t&&Date.now()<i&&!p&&(await ne(Math.min(1e3,i-Date.now())),!(p||Date.now()>=i));)a=await O(r.resume(t),i,t);if(p)throw new u("IDENTITY_CHANGED","Paywall presentation has closed");if(a.run.pendingRequest?.requestId===t)throw new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t);if(!S(a,o,s.type==="paywall_confirm"||s.type==="paywall_cancel"?s.operationId:void 0))throw new u("PRECONDITION_FAILED","The purchase selection has changed");I===t&&(I=null)}catch(a){if(I=t,s.type==="paywall_quote"&&r.settle&&!p&&a instanceof u&&a.status!==void 0&&![401,425].includes(a.status)&&!a.retryable&&a.recovery!=="recover_operation")try{if((await O(r.settle(t),i,t)).settlement?.state==="settled"){let l=await O(r.get(),i,t);S(l,o)&&l.run.paywall?.purchaseRequestId===t&&n.canReselect===!0&&v.delete(t)}}catch{}throw a instanceof u&&a.code==="COMMAND_PENDING"&&a.status===void 0&&v.delete(t),a}finally{T.delete(t)}}async function k(e){if(!n.quote)throw new u("INVALID_REQUEST","A quoted purchase is required");let o=e==="confirm"?"paywall_confirm":"paywall_cancel",t=[...v.values(),...r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])].find(i=>i.operation==="submit"&&i.input.type===o&&"operationId"in i.input&&i.input.operationId===n.quote.operationId),s=t?.operation==="submit"&&t.input.type===o&&"operationId"in t.input&&t.input.operationId===n.quote.operationId?t.requestId:crypto.randomUUID();if(await x(j(s,{type:e==="confirm"?"paywall_confirm":"paywall_cancel",operationId:n.quote.operationId,...e==="confirm"&&n.quote.merchantTerms?{merchantConfirmation:H(n.quote.merchantTerms)}:{}}),C),!n.operation)throw new u("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(n.operation)}let oe={get supportsHostedCheckout(){return!m&&!n.operation&&(n.selectionGeneration??0)===0},get view(){return structuredClone(D())},get quote(){return n.quote?structuredClone(n.quote):null},get operation(){return n.operation?structuredClone(n.operation):null},get webViewUrl(){return r.webViewUrl},get locale(){return r.view?.locale??f.locale},get canReselect(){return n.canReselect===!0&&I===null},get recovery(){let e=r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[]),o=r.pendingPurchase;if(o&&(o.receiptId!==d||o.operationId!==n.quote?.operationId))return{type:"recover",operationId:o.operationId,requestId:e[0]?.requestId??null};let t=Y({quote:n.quote,operation:n.operation,requestId:e[0]?.requestId??I??m,pending:T.size>0||e.length>0||I!==null,destroyed:p,canReselect:n.canReselect});return t.type==="recover"&&t.requestId===null&&!p&&r.hasDurableJournal===!0&&!n.quote&&!n.operation&&(n.selectionGeneration??0)===0&&!o&&!e.length&&!T.size&&!m?{type:"native",operationId:null}:t},get pendingCancellation(){return!p&&(r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])).some(e=>e.operation==="submit"&&e.nodeId===h&&e.visit===E&&e.input.type==="paywall_cancel"&&e.input.operationId===n.quote?.operationId)},subscribe(e){return p?()=>{}:(A.add(e),()=>A.delete(e))},async refresh(){b();let e=C,o=await r.get();if(S(o,e),o.run.paywall?.receiptId!==d)throw new u("PRECONDITION_FAILED","Paywall presentation has changed");return M()},preview(e){let o=D();if(!o)return Promise.reject(new u("PRECONDITION_FAILED","Load the Paywall presentation first"));if(m&&m!==e.requestId&&(g||n.canReselect!==!0))return Promise.reject(new u("COMMAND_PENDING","Retry the original purchase before starting another"));let t=o.document.buttons[e.actionId],s=t?.type==="checkout"?J(t.product,e.selection,o.capabilities):null;if(!s)return Promise.reject(new u("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let i=z(o.document.screen,s,e.selection,o.capabilities),a=m!==e.requestId&&(n.selectionGeneration??0)>0?{operationId:n.quote?.operationId??null,generation:n.selectionGeneration??0}:void 0,c=r.view?.parameters.commerce;if(c&&typeof c=="object"&&!Array.isArray(c)&&c.intent==="subscription_change"&&!e.subscriptionChange)return Promise.reject(new u("INVALID_REQUEST","Choose the existing membership for this subscription change"));if(e.subscriptionChange&&e.nativeOffer)return Promise.reject(new u("INVALID_REQUEST","A web membership change cannot include a store offer"));if(a&&n.canReselect!==!0)return Promise.reject(new u("COMMAND_PENDING","Original purchase requires authoritative termination"));let l;try{l=j(e.requestId,{type:"paywall_quote",...e.acceptHostedMonthly===void 0?{}:{acceptHostedMonthly:e.acceptHostedMonthly},actionId:e.actionId,productVersionId:s,...Object.keys(i).length?{featureQuantities:i}:{},...a?{predecessor:a}:{},...e.offerId?{offerId:e.offerId}:{},...e.nativeOffer?{nativeOffer:e.nativeOffer}:{},...e.subscriptionChange?{subscriptionChange:e.subscriptionChange}:{}})}catch(P){return Promise.reject(P)}if(m===e.requestId&&g)return g;m!==e.requestId&&C++;let y=C;m=e.requestId;let w=(async()=>{if(await x(l,y),!n.quote)throw new u("INVALID_RESPONSE","The accepted quote is missing");return $(n.quote,{productVersionId:s,featureQuantities:i,subscriptionChange:e.subscriptionChange},"The selected purchase changed"),structuredClone(n.quote)})();return g=w,w.then(()=>{g===w&&(g=null)},P=>{g===w&&(g=null),m===e.requestId&&r.pendingCommand?.requestId!==e.requestId&&P instanceof u&&P.status!==void 0&&P.status<500&&![401,425].includes(P.status)&&(m=null)}),w},confirm:()=>k("confirm"),cancel:()=>k("cancel"),async read(){if(b(),!n.quote)throw new u("INVALID_REQUEST","A quoted purchase is required");let e=n.quote.operationId,o=C,t=r.pendingCommands?.find(l=>l.operation==="submit"&&(l.input.type==="paywall_confirm"||l.input.type==="paywall_cancel")&&l.input.operationId===e)??r.pendingCommand;t?.operation==="submit"&&(t.input.type==="paywall_confirm"||t.input.type==="paywall_cancel")&&t.input.operationId===e&&await r.settle?.(t.requestId);let s=await r.get(void 0,{receiptId:d,operationId:e});b();let i=U(s);if(i?.quote&&i.quote.operationId!==e||i?.operation&&i.operation.operationId!==e)throw new u("INVALID_RESPONSE","Purchase operation changed");let a=S(s,o,e),c=a?n.operation:i?.operation;if(!c)throw new u("INVALID_RESPONSE","The current purchase result is missing");return a&&T.size===0&&!(r.pendingCommands?.length??(r.pendingCommand?1:0))&&(I=null),structuredClone(c)},destroy(){p=!0,re(),A.clear(),q.abort(),v.clear()}},re=r.subscribe(e=>{p||e.nodeId!==h||e.visit!==E||e.paywall?.receiptId!==d||(e.paywall.selectionGeneration??0)<(n.selectionGeneration??0)||(F(e.paywall.resolution),n={...n,resolution:e.paywall.resolution},G())});return{session:oe,load:M}}export{ye as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as T,b as se}from"./chunk-YJHL2DPP.js";import{b as re,h as ae,j as ce}from"./chunk-4CWYR6NX.js";import{E as M,a as J}from"./chunk-BKN33GVY.js";import{a as b,b as f,c as m}from"./chunk-Q2ZKKRIB.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-U3TW2YVO.js";import{a as oe,b as j}from"./chunk-25LM2JXB.js";import{b as W,j as X}from"./chunk-ZBVIIFB4.js";import{n as $}from"./chunk-DGGXLPHI.js";import{b as ie}from"./chunk-TQIZN3GB.js";import{a as B}from"./chunk-FRWORXER.js";import{a as s}from"./chunk-BNVQIMXY.js";import{h as Q}from"./chunk-BJSY53HD.js";import{b as K}from"./chunk-VITB5MIL.js";import{a as z}from"./chunk-DSPLGTQI.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},Se=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ue(t,e,n){let r=null,o=0,a=0,d=0,y=Promise.resolve(),g=!1;if(t&&(!n||Q.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(g)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==o)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function F(i){let c=l();if(!c.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=c.sha256?await c.sha256(Uint8Array.from(i,A=>A.charCodeAt(0))):await Se(i);if(!/^[a-f0-9]{64}$/.test(u))throw new s("INVALID_STATE","Push credential digest is invalid");return u}function p(i){let c=G.parse(i);if(c.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let u=l(),A={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...c},w=await u.sign(ne(i,u.scope,A));return{...A,signature:w}}let I=(i,c,u)=>e.requestWithCredential?e.requestWithCredential(i,c,u):e.request(i,c);async function q(){let i=l(),c=o,u=r?await(e.session?.access()??r):null,A=_(i,v=>v),w;if(A.detachSeq!==null){let v=A.detachSeq,V=Z.parse(await S("detach",{sequence:v,platform:i.platform}));try{let k=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!k||typeof k!="object"||!("installation"in k))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let x=p(k.installation);if(x.bound||x.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(k){if(k instanceof s&&k.status===404)w=k;else if(!(k instanceof s)||k.status!==412)throw k}w||_(i,k=>({...k,detachSeq:k.detachSeq===v?null:k.detachSeq}))}if(O(c),!u){if(w)throw w;return null}let C=(await import("./operation-contracts-IAMHNJCL.js")).apiOperations.bindPushInstallation,D=C.request.parse(await S("bind",{sequence:d,platform:i.platform,credentialDigest:await F(u)}));O(c);let R=C.response.parse(await I(C.path,D,u));O(c);let N=p(R.installation);if(!N.bound||N.identitySeq!==d)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return w&&A.detachSeq!==null&&d>A.detachSeq&&_(i,v=>({...v,detachSeq:v.detachSeq===A.detachSeq?null:v.detachSeq})),N}async function h(){l();let i=o,c=r?await(e.session?.access()??r):null;if(!c)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let u=(await import("./operation-contracts-IAMHNJCL.js")).apiOperations.readPushInstallation,A=u.request.parse(await S("read",{credentialDigest:await F(c)}));O(i);let w=u.response.parse(await I(u.path,A,c));return O(i),p(w.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),c}async function E(i,c,u){let A=l(),w=c.identity,C=c.observation,D=r?await(e.session?.access()??r):null;if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");if(!D)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(w),await q(),O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(A,x=>u?x:{...x,addressSeq:U(x.addressSeq)}),v=await S(u?"recovery_confirm":"recovery_request",{...i,sequence:R.addressSeq,credentialDigest:await F(D),...u?{challenge:u}:{}}),V=u?te.parse(v):ee.parse(v);if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let k=await I(`push/installations/recovery/${u?"confirm":"request"}`,V,D);if(O(w),C!==a||_(A,x=>x).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(u){let{apiOperations:x}=await import("./operation-contracts-IAMHNJCL.js");if(O(w),C!==a||_(A,Oe=>Oe).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");let Ae=x.updatePushAddress.response.parse(k),L=p(Ae.installation);if(!L.bound||L.identitySeq!==d||L.addressSeq!==R.addressSeq||L.connectionId!==i.connectionId||L.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return L}if(!k||typeof k!="object"||!("recovery"in k))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return H.parse(k.recovery)})}return{recoveryObserver(){l();let i={identity:o,observation:++a};return{async request(c){return H.parse(await E(c,i))},async confirm(c,u){return G.parse(await E(u,i,c))}}},identify(i){if(!t)return;d=_(t,u=>({...u,identitySeq:U(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,o++,a++}},start(){t&&!g&&P()},destroy(){g=!0,r=null,o++,a++},async sync(){return await P()},read:h,async recover(){let i=l(),c=o,u=d;return a++,await P(async()=>{O(c);let A=await h();return O(c),d=_(i,C=>{if(C.identitySeq!==u)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...C,identitySeq:U(Math.max(C.identitySeq,A.identitySeq)),addressSeq:Math.max(C.addressSeq,A.addressSeq)}}).identitySeq,await q()})},tokenObserver(){l();let i=++a,c=o;return async u=>{if(i!==a||c!==o)return null;let A=l(),w=r?await(e.session?.access()??r):null;if(!w)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let C=_(A,v=>({...v,addressSeq:U(v.addressSeq)})),D=(await import("./operation-contracts-IAMHNJCL.js")).apiOperations.updatePushAddress,R=D.request.parse(await S("address",{...u,sequence:C.addressSeq,credentialDigest:await F(w)}));if(O(c),i!==a)return null;let N=await I(D.path,R,w);return O(c),i!==a||_(A,v=>v).addressSeq!==C.addressSeq?null:p(D.response.parse(N).installation)}}}}function de(t,e){let n={async preference(r){let o=await f(t,"readMessagingPreference");return(await m(t,o,{channel:r})).preference},async setPreference(r){r=b(r);let o=await f(t,"setMessagingPreference");return(await m(t,o,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return r=b(r),n.setPreference({...r,channel:"push"})}}}}function le(t,e,n={}){let r=!1;function o(){if(r)throw new s("CLOSED","SDK client was destroyed")}let a=new Set,d=g=>{for(let l of a)try{l(g)}catch{}},y=t.session.subscribeIdentity(()=>{d(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:o,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(g){return o(),a.add(g),()=>{a.delete(g)}},identify(g){o();let l=typeof g=="string"?g:g.accessToken;if(!B.test(l))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(l),t.identify(g)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function pe(t){return{async checkEntitlement(e){e=b(e),T(e);let n=await f(t,"checkEntitlement"),r=n.request.parse(e),o=await m(t,n,r);return oe(r.requirement,o.check,void 0,o.scope),o},async readHoldings(e={}){e=b(e);let n=await f(t,"readHoldings"),r={...n,request:n.request.omit({customerId:!0})};return m(t,r,e)}}}function fe(t){return{async readLedger(e){e=b(e);let n=await f(t,"readLedger");return m(t,n,{query:e})},async readCreditStatement(e){e=b(e),T(e);let n=await f(t,"readCreditStatement");return m(t,n,e)},async quoteBalance(e){e=b(e),T(e);let n=await f(t,"quoteBalance");return m(t,n,{command:e})}}}function me(t){return{async setupPayment(e){e=b(e),T(e);let n=await f(t,"setupPayment");return m(t,n,e)},async readPaymentSetup(e){e=b(e),T(e);let n=await f(t,"readPaymentSetup");return m(t,n,e)},async readBillingInvoice(e){e=b(e),T(e);let n=await f(t,"readBillingInvoice");return m(t,n,e)},async readBillingControls(e={}){e=b(e),T(e);let n=await f(t,"readBillingControls");return m(t,n,e)},async prepareBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"prepareBillingAuthorization");return m(t,n,e)},async confirmBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"confirmBillingAuthorization");return m(t,n,e)},async setBillingCoupons(e){e=b(e),T(e);let n=await f(t,"setBillingCoupons");return m(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"revokeBillingAuthorization");return m(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){e=b(e),T(e);let n=await f(t,"listBillingInvoices");return m(t,n,e)},async confirmBillingAdjustment(e){e=b(e),T(e);let n=await f(t,"confirmBillingAdjustment");return m(t,n,e)}}}function ye(t){return{async redeemReward(e){return e=b(e),T(e),(await m(t,await f(t,"redeemReward"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return e=b(e),T(e),(await m(t,await f(t,"claimRewardProduct"),e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return e=b(e),T(e),(await m(t,await f(t,"createReferralCode"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){typeof e=="string"&&(e=e.trim().toUpperCase());let r=await m(t,await f(t,"redeemCoupon"),{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await m(t,await f(t,"grantOffer"),{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await m(t,await f(t,"listOffers"),{},{response:"Invalid offers response"})).offers}}}function Ie(t){return{...pe(t),...fe(t),...me(t),...se(t),...ye(t)}}function he(t){return{async resolveContent(e){e=b(e),T(e);let n=await f(t,"resolveContent");return m(t,n,e)},async resolvePaywall(e){e=b(e),T(e);let n=await f(t,"resolvePaywall"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.paywall.check,o.scope),o},async resolveOffering(e){e=b(e),T(e);let n=await f(t,"resolveOffering"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.check,o.scope),o}}}var Y=t=>new TextEncoder().encode(JSON.stringify(t)).length,we=16384,Pe=5e3,Ce=6e4,Re=5;function Te(t){return t instanceof s&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function ge(t,e){let n=0,r,o=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],d=null,y,g=0;function l(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(Pe*2**g,Ce)),typeof y=="object"&&"unref"in y&&y.unref())}function F(h){if(l(),r&&Date.now()<r.until&&!W(r.config,h.kind))return;q();let P=X.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(Y({events:[P]})>we)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function p(h,P={},E={}){F({kind:"custom",name:h,properties:P,...E})}async function S(h=!1){if(l(),d)return d;let P=n,E=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let u=[],A=Y({events:[]});for(let C of a.slice(0,Math.min(c,100))){let D=Y(C)+(u.length?1:0);if(u.length&&A+D>we)break;u.push(C),A+=D}let w;try{let C=await f(t,"trackEvents");if(w=await m(t,C,{events:u},void 0,{keepalive:h}),P!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==u.length||w.rejections.length!==w.rejected)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(C){throw P===n&&(g++,(Te(C)||g>=Re)&&(a.splice(0,u.length),g=0)),C}g=0,o(w.analyticsConfig),a.splice(0,u.length),c-=u.length,i.inserted+=w.inserted,i.duplicates+=w.duplicates,i.rejected+=w.rejected,i.skipped+=w.skipped,i.rejections.push(...w.rejections)}return i})();d=E;try{return await E}finally{d===E&&(d=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:o,track:p,observe:F,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],g=0,d=null},detachVisibility(){I?.(),I=void 0}}}function ve(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var qe=new Set([...$,"merchandiseId","merchandise"]);function ke(t){let e=ve(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!qe.has(r))),...e?{merchandise:e}:{}}}function Ee(t,e,n,r,o){if(o&&r&&(o.scope.projectId!==r.projectId||o.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,d=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function g(l={}){o||y();let O=a,F=!1,p=async()=>{if(F||O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=o?{scope:{projectId:o.scope.projectId,environment:o.scope.environment},payload:await o.features()}:await m(t,await f(t,"getFeatures"),{});if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await p(),I=!0,q,h=R=>{try{l.onError?.(R)}catch{}},P=(R,N)=>{try{let v=ve(N);n.observe({...R,...v?{merchandise:v}:{}})}catch(v){h(v)}},E=ae({assertUsable:o?.assertFeatures,scope:S.scope,attributes:l.attributes,onError:l.onError,load:async()=>I?(I=!1,S.payload):(await p()).payload,evaluateRemote:async R=>{if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let N=await f(t,"evaluateFeatures"),v=await m(t,N,{...R,attributes:ke(R.attributes)});if(v.scope.projectId!==S.scope.projectId||v.scope.environment!==S.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,N,v,V)=>P({kind:"experiment_exposure",generation:V,experimentId:R.key,variationId:N.key},v),onFeatureUsage:(R,N,v,V)=>P({kind:"feature_usage",generation:V,feature:R,value:N.value??null,source:N.source,ruleId:N.ruleId,...N.experimentResult?{variationId:N.experimentResult.key}:{}},v)}),i=E.refresh;function c(){clearTimeout(q),!o&&(F||O!==a||!E.expiresAt||(q=setTimeout(()=>{u().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(E.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function u(){try{return await i()}finally{c()}}let A=()=>{F||u().catch(h)},w=E.subscribe(c),C=o?.subscribe(()=>{!F&&o.fresh&&u().catch(h)});function D(){F||(F=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",A),w(),C?.(),E.reset(),d.delete(D))}d.add(D);try{await E.init(),(l.attributes?.merchandise||l.attributes?.merchandiseId)&&await E.refreshRemote()}catch(R){throw D(),R}return c(),!o&&typeof window<"u"&&window.addEventListener("focus",A),Object.assign(E,{refresh:u,destroy:D})}return{features:g,reset(l){a++,l();for(let O of d)O()}}}function be(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=K.object({funnelId:J.shape.id,funnelVersionId:J.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let o=Object.freeze(r.data);function a(d){if("customerId"in d)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in d&&d.funnelId!==void 0&&d.funnelId!==o.funnelId||"funnelVersionId"in d&&d.funnelVersionId!==void 0&&d.funnelVersionId!==o.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...d,...o}}return{async claimCoupon(d,y=crypto.randomUUID()){let g=await f(t,"grantOffer"),l=await m(t,g,a({couponId:d,requestId:y}));return{offer:l.offer,reason:l.reason}},async resolveOffering(d){d=b(d);let y=await f(t,"resolveOffering"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.check,l.scope),l},async resolvePaywall(d){d=b(d);let y=await f(t,"resolvePaywall"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.paywall.check,l.scope),l},async previewAttach(d){d=b(d);let y=await f(t,"previewAttach");return m(t,y,a(d))}}}function xt(t){return Ne(t)}function Ne(t){let e=ie(t),n=e.request,r;try{r=ue(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let o=le(e,()=>{d.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ge(n,o.isIdentified),d=Ee(n,o.isIdentified,a,t.scope,t.configuration);return{session:e.session,...de(n,r),...Ie(n),...he(n),forFunnel(y){return o.assertActive(),be(n,y)},async features(y={}){return o.assertActive(),d.features(y)},track(y,g,l={}){return a.track(y,g,l)},flush(){return a.flush()},...o.methods}}function Mt(t){if(!B.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=ce({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),o=M({...t,runToken:r.runToken,initialResponse:r});o.identify(t.customerToken);let a=await o.get();return{...r,...a,controller:o}}}}function Kt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,o=new Set,a=new Map,d=new Map;async function y(p){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(p),I])}finally{clearTimeout(S)}}function g(p){throw p instanceof s&&(p.status===401||p.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear()),p}function l(p,S){if(S!==r)throw new s("IDENTITY_CHANGED","Process was detached during a request");let I=re.parse(p);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let A of o)z(A,I.run);I.run.instruction?.type==="authentication_required"&&z(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&d.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:E,settlement:i,...c}=I,u=i&&(({accepted:A,...w})=>w)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...u?{settlement:u}:{}}}let O=p=>(a.has(p)||a.set(p,e?.run.identity.binding?.id??null),a.get(p));async function F(p){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return g(P)};if(p.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(p.release,p.usedReceiptIds)).catch(q)}let h;if(p.operation==="get"){let{operation:P,customerToken:E,...i}=p;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(p.operation==="review")h=await y(()=>t.adapter.review(p.receiptId)).catch(q);else{if(p.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...E}=p;h=await y(()=>t.adapter.command(E,O(E.requestId))).catch(q)}}return l(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(p){let S=r,I=await y(()=>t.adapter.open(p)).catch(g),q=l(I,S);if(!n){n=M({...t,runToken:I.runToken,initialResponse:q,process:{request:F,binding:O,restore(E){for(let[i,c]of Object.entries(E))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async E=>{try{return await P(E)}catch(i){if(!(i instanceof s)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||E.operation!=="submit"||E.input.type!=="screen"||a.get(E.requestId)!==null)throw i;await h.settle?.(E.requestId),await h.get();let c=h.view;if(d.get(E.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==E.nodeId||c.visit!==E.visit||!e?.run.identity.binding)throw i;return P({...E,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let p=r;l(await y(()=>t.adapter.syncIdentity()).catch(g),p),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),await y(()=>t.adapter.detach())},forProcess(p){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:p}},subscribe(p){return o.add(p),()=>{o.delete(p)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),o.clear()}}}export{xt as a,Ne as b,Mt as c,Kt as d};
|
|
1
|
+
import{a as T,b as se}from"./chunk-7ROXL6N2.js";import{b as re,h as ae,j as ce}from"./chunk-F53UXSUI.js";import{E as M,a as J}from"./chunk-4SDB3T2F.js";import{a as b,b as f,c as m}from"./chunk-BZ7HAITJ.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-5O6YRAHQ.js";import{a as oe,b as j}from"./chunk-FBHEBXK4.js";import{b as W,j as X}from"./chunk-MDNT2TC3.js";import{n as $}from"./chunk-MEBCS2JG.js";import{b as ie}from"./chunk-533YCYLO.js";import{a as B}from"./chunk-HSNAFHCP.js";import{a as s}from"./chunk-AECGOS7O.js";import{h as Q}from"./chunk-CQYEM7U6.js";import{b as K}from"./chunk-ZL247MPX.js";import{a as z}from"./chunk-DSPLGTQI.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},Se=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ue(t,e,n){let r=null,o=0,a=0,d=0,y=Promise.resolve(),g=!1;if(t&&(!n||Q.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(g)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==o)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function F(i){let c=l();if(!c.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=c.sha256?await c.sha256(Uint8Array.from(i,A=>A.charCodeAt(0))):await Se(i);if(!/^[a-f0-9]{64}$/.test(u))throw new s("INVALID_STATE","Push credential digest is invalid");return u}function p(i){let c=G.parse(i);if(c.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let u=l(),A={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...c},w=await u.sign(ne(i,u.scope,A));return{...A,signature:w}}let I=(i,c,u)=>e.requestWithCredential?e.requestWithCredential(i,c,u):e.request(i,c);async function q(){let i=l(),c=o,u=r?await(e.session?.access()??r):null,A=_(i,v=>v),w;if(A.detachSeq!==null){let v=A.detachSeq,V=Z.parse(await S("detach",{sequence:v,platform:i.platform}));try{let k=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!k||typeof k!="object"||!("installation"in k))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let x=p(k.installation);if(x.bound||x.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(k){if(k instanceof s&&k.status===404)w=k;else if(!(k instanceof s)||k.status!==412)throw k}w||_(i,k=>({...k,detachSeq:k.detachSeq===v?null:k.detachSeq}))}if(O(c),!u){if(w)throw w;return null}let C=(await import("./operation-contracts-EDUVKUPX.js")).apiOperations.bindPushInstallation,D=C.request.parse(await S("bind",{sequence:d,platform:i.platform,credentialDigest:await F(u)}));O(c);let R=C.response.parse(await I(C.path,D,u));O(c);let N=p(R.installation);if(!N.bound||N.identitySeq!==d)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return w&&A.detachSeq!==null&&d>A.detachSeq&&_(i,v=>({...v,detachSeq:v.detachSeq===A.detachSeq?null:v.detachSeq})),N}async function h(){l();let i=o,c=r?await(e.session?.access()??r):null;if(!c)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let u=(await import("./operation-contracts-EDUVKUPX.js")).apiOperations.readPushInstallation,A=u.request.parse(await S("read",{credentialDigest:await F(c)}));O(i);let w=u.response.parse(await I(u.path,A,c));return O(i),p(w.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),c}async function E(i,c,u){let A=l(),w=c.identity,C=c.observation,D=r?await(e.session?.access()??r):null;if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");if(!D)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(w),await q(),O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(A,x=>u?x:{...x,addressSeq:U(x.addressSeq)}),v=await S(u?"recovery_confirm":"recovery_request",{...i,sequence:R.addressSeq,credentialDigest:await F(D),...u?{challenge:u}:{}}),V=u?te.parse(v):ee.parse(v);if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let k=await I(`push/installations/recovery/${u?"confirm":"request"}`,V,D);if(O(w),C!==a||_(A,x=>x).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(u){let{apiOperations:x}=await import("./operation-contracts-EDUVKUPX.js");if(O(w),C!==a||_(A,Oe=>Oe).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");let Ae=x.updatePushAddress.response.parse(k),L=p(Ae.installation);if(!L.bound||L.identitySeq!==d||L.addressSeq!==R.addressSeq||L.connectionId!==i.connectionId||L.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return L}if(!k||typeof k!="object"||!("recovery"in k))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return H.parse(k.recovery)})}return{recoveryObserver(){l();let i={identity:o,observation:++a};return{async request(c){return H.parse(await E(c,i))},async confirm(c,u){return G.parse(await E(u,i,c))}}},identify(i){if(!t)return;d=_(t,u=>({...u,identitySeq:U(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,o++,a++}},start(){t&&!g&&P()},destroy(){g=!0,r=null,o++,a++},async sync(){return await P()},read:h,async recover(){let i=l(),c=o,u=d;return a++,await P(async()=>{O(c);let A=await h();return O(c),d=_(i,C=>{if(C.identitySeq!==u)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...C,identitySeq:U(Math.max(C.identitySeq,A.identitySeq)),addressSeq:Math.max(C.addressSeq,A.addressSeq)}}).identitySeq,await q()})},tokenObserver(){l();let i=++a,c=o;return async u=>{if(i!==a||c!==o)return null;let A=l(),w=r?await(e.session?.access()??r):null;if(!w)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let C=_(A,v=>({...v,addressSeq:U(v.addressSeq)})),D=(await import("./operation-contracts-EDUVKUPX.js")).apiOperations.updatePushAddress,R=D.request.parse(await S("address",{...u,sequence:C.addressSeq,credentialDigest:await F(w)}));if(O(c),i!==a)return null;let N=await I(D.path,R,w);return O(c),i!==a||_(A,v=>v).addressSeq!==C.addressSeq?null:p(D.response.parse(N).installation)}}}}function de(t,e){let n={async preference(r){let o=await f(t,"readMessagingPreference");return(await m(t,o,{channel:r})).preference},async setPreference(r){r=b(r);let o=await f(t,"setMessagingPreference");return(await m(t,o,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return r=b(r),n.setPreference({...r,channel:"push"})}}}}function le(t,e,n={}){let r=!1;function o(){if(r)throw new s("CLOSED","SDK client was destroyed")}let a=new Set,d=g=>{for(let l of a)try{l(g)}catch{}},y=t.session.subscribeIdentity(()=>{d(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:o,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(g){return o(),a.add(g),()=>{a.delete(g)}},identify(g){o();let l=typeof g=="string"?g:g.accessToken;if(!B.test(l))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(l),t.identify(g)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function pe(t){return{async checkEntitlement(e){e=b(e),T(e);let n=await f(t,"checkEntitlement"),r=n.request.parse(e),o=await m(t,n,r);return oe(r.requirement,o.check,void 0,o.scope),o},async readHoldings(e={}){e=b(e);let n=await f(t,"readHoldings"),r={...n,request:n.request.omit({customerId:!0})};return m(t,r,e)}}}function fe(t){return{async readLedger(e){e=b(e);let n=await f(t,"readLedger");return m(t,n,{query:e})},async readCreditStatement(e){e=b(e),T(e);let n=await f(t,"readCreditStatement");return m(t,n,e)},async quoteBalance(e){e=b(e),T(e);let n=await f(t,"quoteBalance");return m(t,n,{command:e})}}}function me(t){return{async setupPayment(e){e=b(e),T(e);let n=await f(t,"setupPayment");return m(t,n,e)},async readPaymentSetup(e){e=b(e),T(e);let n=await f(t,"readPaymentSetup");return m(t,n,e)},async readBillingInvoice(e){e=b(e),T(e);let n=await f(t,"readBillingInvoice");return m(t,n,e)},async readBillingControls(e={}){e=b(e),T(e);let n=await f(t,"readBillingControls");return m(t,n,e)},async prepareBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"prepareBillingAuthorization");return m(t,n,e)},async confirmBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"confirmBillingAuthorization");return m(t,n,e)},async setBillingCoupons(e){e=b(e),T(e);let n=await f(t,"setBillingCoupons");return m(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"revokeBillingAuthorization");return m(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){e=b(e),T(e);let n=await f(t,"listBillingInvoices");return m(t,n,e)},async confirmBillingAdjustment(e){e=b(e),T(e);let n=await f(t,"confirmBillingAdjustment");return m(t,n,e)}}}function ye(t){return{async redeemReward(e){return e=b(e),T(e),(await m(t,await f(t,"redeemReward"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return e=b(e),T(e),(await m(t,await f(t,"claimRewardProduct"),e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return e=b(e),T(e),(await m(t,await f(t,"createReferralCode"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){typeof e=="string"&&(e=e.trim().toUpperCase());let r=await m(t,await f(t,"redeemCoupon"),{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await m(t,await f(t,"grantOffer"),{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await m(t,await f(t,"listOffers"),{},{response:"Invalid offers response"})).offers}}}function Ie(t){return{...pe(t),...fe(t),...me(t),...se(t),...ye(t)}}function he(t){return{async resolveContent(e){e=b(e),T(e);let n=await f(t,"resolveContent");return m(t,n,e)},async resolvePaywall(e){e=b(e),T(e);let n=await f(t,"resolvePaywall"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.paywall.check,o.scope),o},async resolveOffering(e){e=b(e),T(e);let n=await f(t,"resolveOffering"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.check,o.scope),o}}}var Y=t=>new TextEncoder().encode(JSON.stringify(t)).length,we=16384,Pe=5e3,Ce=6e4,Re=5;function Te(t){return t instanceof s&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function ge(t,e){let n=0,r,o=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],d=null,y,g=0;function l(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(Pe*2**g,Ce)),typeof y=="object"&&"unref"in y&&y.unref())}function F(h){if(l(),r&&Date.now()<r.until&&!W(r.config,h.kind))return;q();let P=X.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(Y({events:[P]})>we)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function p(h,P={},E={}){F({kind:"custom",name:h,properties:P,...E})}async function S(h=!1){if(l(),d)return d;let P=n,E=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let u=[],A=Y({events:[]});for(let C of a.slice(0,Math.min(c,100))){let D=Y(C)+(u.length?1:0);if(u.length&&A+D>we)break;u.push(C),A+=D}let w;try{let C=await f(t,"trackEvents");if(w=await m(t,C,{events:u},void 0,{keepalive:h}),P!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==u.length||w.rejections.length!==w.rejected)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(C){throw P===n&&(g++,(Te(C)||g>=Re)&&(a.splice(0,u.length),g=0)),C}g=0,o(w.analyticsConfig),a.splice(0,u.length),c-=u.length,i.inserted+=w.inserted,i.duplicates+=w.duplicates,i.rejected+=w.rejected,i.skipped+=w.skipped,i.rejections.push(...w.rejections)}return i})();d=E;try{return await E}finally{d===E&&(d=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:o,track:p,observe:F,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],g=0,d=null},detachVisibility(){I?.(),I=void 0}}}function ve(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var qe=new Set([...$,"merchandiseId","merchandise"]);function ke(t){let e=ve(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!qe.has(r))),...e?{merchandise:e}:{}}}function Ee(t,e,n,r,o){if(o&&r&&(o.scope.projectId!==r.projectId||o.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,d=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function g(l={}){o||y();let O=a,F=!1,p=async()=>{if(F||O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=o?{scope:{projectId:o.scope.projectId,environment:o.scope.environment},payload:await o.features()}:await m(t,await f(t,"getFeatures"),{});if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await p(),I=!0,q,h=R=>{try{l.onError?.(R)}catch{}},P=(R,N)=>{try{let v=ve(N);n.observe({...R,...v?{merchandise:v}:{}})}catch(v){h(v)}},E=ae({assertUsable:o?.assertFeatures,scope:S.scope,attributes:l.attributes,onError:l.onError,load:async()=>I?(I=!1,S.payload):(await p()).payload,evaluateRemote:async R=>{if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let N=await f(t,"evaluateFeatures"),v=await m(t,N,{...R,attributes:ke(R.attributes)});if(v.scope.projectId!==S.scope.projectId||v.scope.environment!==S.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,N,v,V)=>P({kind:"experiment_exposure",generation:V,experimentId:R.key,variationId:N.key},v),onFeatureUsage:(R,N,v,V)=>P({kind:"feature_usage",generation:V,feature:R,value:N.value??null,source:N.source,ruleId:N.ruleId,...N.experimentResult?{variationId:N.experimentResult.key}:{}},v)}),i=E.refresh;function c(){clearTimeout(q),!o&&(F||O!==a||!E.expiresAt||(q=setTimeout(()=>{u().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(E.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function u(){try{return await i()}finally{c()}}let A=()=>{F||u().catch(h)},w=E.subscribe(c),C=o?.subscribe(()=>{!F&&o.fresh&&u().catch(h)});function D(){F||(F=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",A),w(),C?.(),E.reset(),d.delete(D))}d.add(D);try{await E.init(),(l.attributes?.merchandise||l.attributes?.merchandiseId)&&await E.refreshRemote()}catch(R){throw D(),R}return c(),!o&&typeof window<"u"&&window.addEventListener("focus",A),Object.assign(E,{refresh:u,destroy:D})}return{features:g,reset(l){a++,l();for(let O of d)O()}}}function be(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=K.object({funnelId:J.shape.id,funnelVersionId:J.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let o=Object.freeze(r.data);function a(d){if("customerId"in d)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in d&&d.funnelId!==void 0&&d.funnelId!==o.funnelId||"funnelVersionId"in d&&d.funnelVersionId!==void 0&&d.funnelVersionId!==o.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...d,...o}}return{async claimCoupon(d,y=crypto.randomUUID()){let g=await f(t,"grantOffer"),l=await m(t,g,a({couponId:d,requestId:y}));return{offer:l.offer,reason:l.reason}},async resolveOffering(d){d=b(d);let y=await f(t,"resolveOffering"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.check,l.scope),l},async resolvePaywall(d){d=b(d);let y=await f(t,"resolvePaywall"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.paywall.check,l.scope),l},async previewAttach(d){d=b(d);let y=await f(t,"previewAttach");return m(t,y,a(d))}}}function xt(t){return Ne(t)}function Ne(t){let e=ie(t),n=e.request,r;try{r=ue(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let o=le(e,()=>{d.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ge(n,o.isIdentified),d=Ee(n,o.isIdentified,a,t.scope,t.configuration);return{session:e.session,...de(n,r),...Ie(n),...he(n),forFunnel(y){return o.assertActive(),be(n,y)},async features(y={}){return o.assertActive(),d.features(y)},track(y,g,l={}){return a.track(y,g,l)},flush(){return a.flush()},...o.methods}}function Mt(t){if(!B.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=ce({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),o=M({...t,runToken:r.runToken,initialResponse:r});o.identify(t.customerToken);let a=await o.get();return{...r,...a,controller:o}}}}function Kt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,o=new Set,a=new Map,d=new Map;async function y(p){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(p),I])}finally{clearTimeout(S)}}function g(p){throw p instanceof s&&(p.status===401||p.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear()),p}function l(p,S){if(S!==r)throw new s("IDENTITY_CHANGED","Process was detached during a request");let I=re.parse(p);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let A of o)z(A,I.run);I.run.instruction?.type==="authentication_required"&&z(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&d.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:E,settlement:i,...c}=I,u=i&&(({accepted:A,...w})=>w)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...u?{settlement:u}:{}}}let O=p=>(a.has(p)||a.set(p,e?.run.identity.binding?.id??null),a.get(p));async function F(p){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return g(P)};if(p.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(p.release,p.usedReceiptIds)).catch(q)}let h;if(p.operation==="get"){let{operation:P,customerToken:E,...i}=p;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(p.operation==="review")h=await y(()=>t.adapter.review(p.receiptId)).catch(q);else{if(p.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...E}=p;h=await y(()=>t.adapter.command(E,O(E.requestId))).catch(q)}}return l(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(p){let S=r,I=await y(()=>t.adapter.open(p)).catch(g),q=l(I,S);if(!n){n=M({...t,runToken:I.runToken,initialResponse:q,process:{request:F,binding:O,restore(E){for(let[i,c]of Object.entries(E))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async E=>{try{return await P(E)}catch(i){if(!(i instanceof s)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||E.operation!=="submit"||E.input.type!=="screen"||a.get(E.requestId)!==null)throw i;await h.settle?.(E.requestId),await h.get();let c=h.view;if(d.get(E.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==E.nodeId||c.visit!==E.visit||!e?.run.identity.binding)throw i;return P({...E,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let p=r;l(await y(()=>t.adapter.syncIdentity()).catch(g),p),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),await y(()=>t.adapter.detach())},forProcess(p){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:p}},subscribe(p){return o.add(p),()=>{o.delete(p)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),o.clear()}}}export{xt as a,Ne as b,Mt as c,Kt as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as p}from"./chunk-
|
|
1
|
+
import{a as p}from"./chunk-AECGOS7O.js";import{a as d}from"./chunk-ZL247MPX.js";function I(n,r,i){if(!["subscriptions/operations/read","subscriptions/updates/read","subscriptions/refunds/read"].includes(n))return;let e=r,s=i,o=s.operation;if(o.operationId!==e.operationId||[o.authority,o.merchantExecution].some(t=>t&&(t.operationId!==e.operationId||e.customerId!==void 0&&t.customerId!==e.customerId))||o.authority&&(o.authority.scope.projectId!==s.scope.projectId||o.authority.scope.environment!==s.scope.environment))throw new p("INVALID_RESPONSE","Original commerce operation changed")}function g(n){try{return structuredClone(n)}catch{return n}}async function E(n,r){let i=n.captureIdentity?.(),{apiOperations:e}=await import("./operation-contracts-EDUVKUPX.js");return i?.(),e[r]}function m(n,r,i,e){try{return n.parse(r)}catch(s){throw e&&s instanceof d?new p(i,e):s}}async function P(n,r,i,e={},s){let o=typeof e=="function"?{}:e,t=m(r.request,i,"INVALID_REQUEST",o.request);try{let a=await n(r.path,t,r.method,s),u=typeof e=="function"?e:e.parseResponse,c=u?u(r.response,a):m(r.response,a,"INVALID_RESPONSE",o.response);return I(r.path,t,c),c}catch(a){throw a instanceof p&&t!==null&&typeof t=="object"&&"requestId"in t&&typeof t.requestId=="string"&&(a.commandRequestId??=t.requestId),a}}export{g as a,E as b,P as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as r}from"./chunk-
|
|
1
|
+
import{b as r}from"./chunk-ZL247MPX.js";var R=r.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),H=r.enum([...R.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED","SENSITIVE_OUTPUT_REQUIRED"]),j=r.enum([...R.options,"stale_revision"]),v=r.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),x=r.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","IDENTITY_CONTEXT_CHANGED","CUSTOMER_BINDING_CONFLICT","RUN_CONTRACT_MISMATCH","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED","FUNNEL_PAUSED"]),L={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};var S={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",CUSTOMER_SESSION_REQUIRED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",INVALID_STATE:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",PURCHASE_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",PURCHASE_STORAGE_CONFLICT:"resolve_conflict",PURCHASE_STORAGE_INVALID:"recover_operation",EXECUTION_POLICY_REFUSED:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",ROUTE_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",COUPON_UNAVAILABLE:"reload_state",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function g(e,o){if(e==="CONFLICT"&&o===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&o===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION"||e==="SENSITIVE_OUTPUT_REQUIRED")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(S,e)){let n=S[e];return{retryable:n==="retry_same_request",recovery:n}}let t=R.safeParse(e);return t.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:L[t.data].recovery}:{retryable:!1,recovery:"contact_support"}}function Q(e,o){let t=R.safeParse(e);if(t.success)return e==="CONFLICT"?[409,412,425].includes(o):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(o):e==="INVALID_REQUEST"?[400,405,415,422].includes(o):e==="NOT_CONFIGURED"?[501,503].includes(o):L[t.data].status===o;let n={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],SENSITIVE_OUTPUT_REQUIRED:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(n,e)&&(n[e]?.includes(o)??!1)}function P(e,o=Date.now()){if(e===null)return;let t=e.trim();if(/^\d+$/.test(t)){let s=Number(t);return Number.isSafeInteger(s)?s:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(t))return;let n=Date.parse(t);return Number.isFinite(n)?Math.max(0,Math.ceil((n-o)/1e3)):void 0}var y=r.object({retryable:r.boolean(),recovery:v,reason:x.optional(),retryAfterSeconds:r.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),b=r.object({requestId:r.uuid().optional(),error:r.object({code:r.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:r.string(),...y.partial().shape})}),z=r.object({error:b.shape.error.extend({requestId:r.uuid().optional()})}),Y=r.object({error:r.string(),code:r.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:r.uuid(),...y.shape});function $(e,o,t={}){let n=g(e,o),s=t.reason==="RESULT_UNKNOWN"?"recover_operation":t.recovery??n.recovery,A=n.retryable&&t.retryable!==!1&&s!=="recover_operation",i=A?P(t.retryAfter??null):void 0;return{...n,retryable:A,recovery:s,...i===void 0?{}:{retryAfterSeconds:i},...t.reason?{reason:t.reason}:{}}}var V=r.enum(["sandbox","live"]),W=r.object({projectId:r.string().min(1),environment:V}).strict();var J=r.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),u=r.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),M=r.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let o=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return o==="-0"?"0":o}),p=u.refine(e=>/[1-9]/.test(e),"数量必须大于 0"),D=r.string().min(1).max(64),B=r.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),C=r.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),ee=r.record(D,r.union([r.string().max(120),r.number().finite(),r.boolean()])).refine(e=>Object.keys(e).length<=16,"最多 16 个计价属性").transform(e=>Object.fromEntries(Object.entries(e).map(([o,t])=>[o,String(t)]))),U=r.record(D,r.union([r.string().max(120),r.number().finite(),r.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"匹配条件最多 8 个属性"),I=e=>{let o=e.startsWith("-");o&&(e=e.slice(1));let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");let s=BigInt(t)*BigInt("1000000")+BigInt(n.padEnd(6,"0"));return o?-s:s},h=r.array(r.object({upTo:p.nullable(),cost:u}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((o,t)=>{let n=e[t-1]?.upTo;return o.upTo!==null&&(t===0||n!=null&&I(o.upTo)>I(n))}),"阶梯上限必须递增,最后一档为无限"),G=r.object({key:C,match:U,priority:r.number().int().default(0),cost:u.optional(),tiers:h.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"维度需要指定单价或阶梯"),F=r.object({key:C,match:U,factor:p.optional(),add:M.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),k=r.object({units:p.default("1"),cost:u,tiers:h.optional(),dimensions:r.array(G).max(12).optional(),multipliers:r.array(F).max(4).optional()}).strict().superRefine((e,o)=>{let t=e.dimensions??[],n=e.multipliers??[];(new Set(t.map(i=>i.key)).size!==t.length||new Set(n.map(i=>i.key)).size!==n.length)&&o.addIssue({code:"custom",message:"维度和倍率的 ID 不能重复"});for(let[i,a]of t.entries())for(let c of t.slice(i+1))Object.keys(a.match).length===Object.keys(c.match).length&&a.priority===c.priority&&!Object.keys(a.match).some(E=>c.match[E]!==void 0&&c.match[E]!==a.match[E])&&o.addIssue({code:"custom",message:"维度可能同时匹配,请调整优先级"});let s=[e.cost,...(e.tiers??[]).map(i=>i.cost),...t.flatMap(i=>[...i.cost===void 0?[]:[i.cost],...(i.tiers??[]).map(a=>a.cost)])],A=I(e.units);for(let i of s)for(let a=0;a<1<<n.length;a++){let c=n.filter((N,_)=>a&1<<_);if(c.some((N,_)=>c.slice(_+1).some(d=>Object.keys(N.match).some(l=>d.match[l]!==void 0&&d.match[l]!==N.match[l]))))continue;let E=I(i),O=BigInt("1"),f=BigInt("0");for(let[N,_]of n.entries())a&1<<N&&(E*=I(_.factor??"1"),O*=BigInt("1000000"),f+=I(_.add??"0"));let T=(E+f*O)*BigInt("1000000"),m=O*A;(T<BigInt("0")||T%m!==BigInt("0")||T/m>BigInt("999999999999999999"))&&o.addIssue({code:"custom",message:"每个业务单位的最终单价必须非负、在范围内且能精确表示为最多 6 位小数"})}}),re=k.safeExtend({featureKey:B});export{R as a,v as b,x as c,Q as d,b as e,$ as f,V as g,W as h,J as i,u as j,M as k,B as l,ee as m};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as e}from"./chunk-
|
|
1
|
+
import{b as e}from"./chunk-ZL247MPX.js";var y=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),z=e.discriminatedUnion("type",[e.object({type:e.literal("fixed"),productVersionId:e.string().min(1).max(200)}).strict(),e.object({type:e.literal("picker"),pickerId:y,allowedProductVersionIds:e.array(e.string().min(1).max(200)).min(1).max(20)}).strict().refine(t=>new Set(t.allowedProductVersionIds).size===t.allowedProductVersionIds.length,"Product choices must be unique")]),x=e.strictObject({min:e.number().finite().min(1).max(1800),max:e.number().finite().min(1).max(1800),viewport:e.number().finite().min(1).max(100)}).refine(t=>t.min<=t.max,"Desktop width range is reversed"),f={desktopWidth:x.optional(),mobile:e.enum(["sheet","fullscreen"]).optional(),backdrop:e.enum(["none","scrim","dim","strong-dim","blur"]).optional()},G=e.discriminatedUnion("type",[e.strictObject({type:e.literal("modal"),position:e.enum(["center","top","bottom"]).optional(),size:e.enum(["sm","md","lg"]),...f}),e.strictObject({type:e.literal("sheet"),size:e.enum(["sm","md","lg"]),...f}),e.strictObject({type:e.literal("fullscreen")}),e.strictObject({type:e.literal("inline")})]),V={sm:360,md:420,lg:560};var c=e.json().superRefine((t,i)=>{let s=0;function o(n,r){if(++s>1e4||r>20){i.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof n=="string"&&(n.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(n))&&i.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(n))n.forEach(a=>o(a,r+1));else if(n&&typeof n=="object")for(let[a,u]of Object.entries(n))(a.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(a)||["__proto__","prototype","constructor"].includes(a))&&i.addIssue({code:"custom",message:"Reserved JSON property"}),o(u,r+1)}o(t,0),new TextEncoder().encode(JSON.stringify(t)).byteLength>65536&&i.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),l=e.record(e.string().min(1).max(128),c).superRefine((t,i)=>{(!c.safeParse(t).success||Object.keys(t).length>128||new TextEncoder().encode(JSON.stringify(t)).byteLength>65536||["__proto__","constructor","prototype"].some(s=>Object.hasOwn(t,s)))&&i.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),S=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),d=l.superRefine((t,i)=>{function s(o){if(Array.isArray(o))o.forEach(s);else if(o&&typeof o=="object")for(let[n,r]of Object.entries(o)){if(n==="$savedGroup"&&!e.strictObject({id:e.uuid(),attributeKey:e.string().min(1).max(128).optional()}).safeParse(r).success&&i.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!n.startsWith("$")&&n.split(".").some(a=>["__proto__","prototype","constructor"].includes(a))&&i.addIssue({code:"custom",message:"Reserved attribute path"}),n.startsWith("$")&&!S.has(n)&&i.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${n}`}),["$regex","$regexi"].includes(n)&&typeof r=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(r)||[...r.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(a=>Number(a[1])>255||Number(a[2]||0)>255)||n==="$regexi"&&/[^\x00-\x7f]/.test(r.replace(/\\u([0-9a-f]{4})/gi,(a,u)=>String.fromCharCode(Number.parseInt(u,16)))))&&i.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(r)}catch{i.addIssue({code:"custom",message:"Invalid regular expression"})}}s(r)}}typeof t.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(t.source)&&("operator"in t||"predicates"in t||"groupId"in t)&&i.addIssue({code:"custom",message:"Obsolete condition protocol"}),s(t)}),w=e.discriminatedUnion("type",[e.strictObject({type:e.literal("condition"),condition:d}),e.strictObject({type:e.literal("list"),attributeKey:e.string().min(1).max(128),values:e.array(e.union([e.string(),e.number().finite()])).max(1e5)})]).refine(t=>t.type!=="list"||new TextEncoder().encode(JSON.stringify(t.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function $(t){let i=new Set;function s(o){if(Array.isArray(o))o.forEach(s);else if(o&&typeof o=="object")for(let[n,r]of Object.entries(o))n==="$savedGroup"&&r&&typeof r=="object"&&!Array.isArray(r)&&typeof r.id=="string"?i.add(r.id):["$inGroup","$notInGroup"].includes(n)&&typeof r=="string"?i.add(r):["$eq","$ne","$in","$nin","$ini","$nini"].includes(n)||s(r)}return s(t),[...i]}var O=e.record(e.uuid(),w).superRefine((t,i)=>{let s=new Set,o=new Set;function n(r){if(s.has(r)){i.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(o.has(r))return;let a=t[r];if(!a){i.addIssue({code:"custom",message:"Missing saved group dependency"});return}s.add(r),a.type==="condition"&&$(a.condition).forEach(n),s.delete(r),o.add(r)}Object.keys(t).forEach(n)}),g=e.tuple([e.number().min(0).max(1),e.number().min(0).max(1)]).refine(([t,i])=>t<=i),h=e.strictObject({attribute:e.string().optional(),seed:e.string().min(1),hashVersion:e.literal(2),ranges:e.array(g).min(1).max(100)}),j=e.strictObject({id:e.string().min(1).max(128),condition:d,gate:e.boolean().optional()}),p={id:e.string().max(128).optional(),condition:d.optional(),parentConditions:e.array(j).max(50).optional(),filters:e.array(h).max(20).optional()},v=e.union([e.strictObject({...p}),e.strictObject({...p,force:c,coverage:e.number().min(0).max(1).optional(),range:g.optional(),seed:e.string().min(1).optional(),hashAttribute:e.string().optional(),hashVersion:e.literal(2).optional()}),e.strictObject({...p,type:e.literal("experiment-ref"),experimentId:e.uuid(),values:e.record(e.string().min(1),c),meta:e.record(e.string().min(1),e.strictObject({passthrough:e.boolean()})).optional()})]),k=e.strictObject({defaultValue:c,rules:e.array(v).max(100)}),U=e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),k).superRefine((t,i)=>{Object.keys(t).length>100&&i.addIssue({code:"custom",message:"Too many Features"});let s=new Set,o=new Set;function n(r){if(s.has(r)){i.addIssue({code:"custom",message:`Cyclic Feature dependency: ${r}`});return}if(o.has(r))return;let a=t[r];if(!a){i.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${r}`});return}s.add(r);for(let u of a.rules)for(let m of u.parentConditions??[])n(m.id);s.delete(r),o.add(r)}Object.keys(t).forEach(n)}),F=e.strictObject({name:e.string().max(80),reason:e.string().max(500),dateStarted:e.iso.datetime({offset:!0}),dateEnded:e.iso.datetime({offset:!0}).nullable(),coverage:e.number().min(0).max(1),variationWeights:e.array(e.number().min(0).max(1)).min(2).max(20).refine(t=>Math.abs(t.reduce((i,s)=>i+s,0)-1)<=.01),condition:d,savedGroups:e.array(e.strictObject({match:e.enum(["any","all","none"]),ids:e.array(e.uuid()).min(1)})).max(50),namespace:e.strictObject({id:e.uuid(),ranges:e.array(g).min(1)}).nullable(),seed:e.string().min(1).max(128)}),A=e.strictObject({key:e.string().min(1).max(128),name:e.string().min(1).max(80),hypothesis:e.string().max(2e3),status:e.enum(["draft","running","stopped"]),hashAttribute:e.string().min(1).max(128),fallbackAttribute:e.string().max(128).nullable(),hashVersion:e.literal(2),disableStickyBucketing:e.boolean(),bucketVersion:e.number().int().min(0).max(1e3),minBucketVersion:e.number().int().min(0).max(1e3),variations:e.array(e.strictObject({id:e.string().min(1),key:e.string().min(1),name:e.string().max(80),description:e.string().max(500)})).min(2).max(20),phases:e.array(F).min(1).max(100),releasedVariationId:e.string().nullable(),excludeFromPayload:e.boolean(),statusSchedule:e.strictObject({startAt:e.iso.datetime({offset:!0}).nullable(),stopAt:e.iso.datetime({offset:!0}).nullable(),stopAfter:e.strictObject({value:e.number().int().positive().max(36500),unit:e.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((t,i)=>{(t.minBucketVersion>t.bucketVersion||t.statusSchedule?.stopAt&&t.statusSchedule?.stopAfter||t.phases.some((s,o)=>{if(o===0)return!1;let n=t.phases[o-1];return!n?.dateEnded||Date.parse(s.dateStarted)<Date.parse(n.dateStarted)||Date.parse(n.dateEnded)>Date.parse(s.dateStarted)})||new Set(t.variations.map(s=>s.key)).size!==t.variations.length||new Set(t.variations.map(s=>s.id)).size!==t.variations.length||t.releasedVariationId!==null&&!t.variations.some(s=>s.id===t.releasedVariationId)||t.statusSchedule?.startAt&&t.statusSchedule?.stopAt&&Date.parse(t.statusSchedule.startAt)>=Date.parse(t.statusSchedule.stopAt)||t.phases.some(s=>s.dateEnded&&Date.parse(s.dateStarted)>=Date.parse(s.dateEnded)||s.namespace?.ranges.some(([o,n],r,a)=>o>=n||a.some(([u,m],b)=>b!==r&&o<m&&u<n)))||t.phases.some(s=>s.variationWeights.length!==t.variations.length))&&i.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var I=A.safeExtend({filters:e.array(h).optional()}),D=e.strictObject({experiments:e.record(e.uuid(),I),savedGroups:O}),E=e.strictObject({attributeName:e.string(),attributeValue:e.string(),assignments:e.record(e.string(),e.string())}),M=e.strictObject({snapshot:D,attributes:l,results:l,stickyBucketAssignmentDocs:e.record(e.string(),E)}),W=e.strictObject({variantKey:e.string().nullable(),bucketVersion:e.number().int().min(0),source:e.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:e.number().min(0).max(1).optional(),stickyBucketUsed:e.boolean().optional(),hashUsed:e.boolean().optional()});export{z as a,G as b,V as c,c as d,l as e,d as f,$ as g,E as h};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as p,c as d}from"./chunk-
|
|
1
|
+
import{b as p,c as d}from"./chunk-MEBCS2JG.js";import{t as a,w as u,z as m}from"./chunk-FGAIHKFS.js";import{b as e}from"./chunk-ZL247MPX.js";var s=e.enum(["page","popup","banner"]),y=3e5,f=e.strictObject({type:e.enum(["string","number","boolean","strings","json"]),nullable:e.boolean()}),h=e.strictObject({inputs:e.record(a,f.extend({required:e.boolean()})).refine(t=>Object.keys(t).length<=40,"Too many content inputs"),outputs:e.record(a,f).refine(t=>Object.keys(t).length<=40,"Too many content outputs")}),g=e.strictObject({kind:s,schemaVersion:e.literal(1),name:e.string().trim().min(1).max(80),screen:u,contract:h}),c=g.superRefine((t,r)=>{let n=(o,b)=>r.addIssue({code:"custom",message:o,path:b});t.screen.surface!==t.kind&&n("Content surface must match its domain",["screen","surface"]),t.screen.name!==t.name&&n("Content has one editable name",["screen","name"]),t.kind==="banner"&&t.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),t.kind!=="banner"&&t.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),t.screen.actions.some(o=>o.type!=="event"&&o.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let i=new Set(t.screen.actions.filter(o=>o.type==="event").map(o=>o.id));(Object.keys(t.contract.outputs).some(o=>!i.has(o))||[...i].some(o=>!Object.hasOwn(t.contract.outputs,o)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),d(t)>y&&n("Content document exceeds its byte budget",[])});function S(t,r){if(t===null)return r.nullable;switch(r.type){case"json":return!0;case"string":return typeof t=="string";case"number":return typeof t=="number"&&Number.isFinite(t);case"boolean":return typeof t=="boolean";case"strings":return Array.isArray(t)&&t.every(n=>typeof n=="string")}}var x=c.superRefine((t,r)=>{for(let n of p(t.screen))Object.keys(t.contract.inputs).some(i=>n===i||n.startsWith(i+"."))||r.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of t.screen.actions){if(n.type!=="event")continue;let i=t.contract.outputs[n.id],o=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;i&&!S(o,i)&&r.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}m(t.screen).some(n=>!n.complete)&&r.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),l=e.strictObject({id:e.uuid(),kind:s,projectId:e.uuid(),environmentId:e.uuid(),name:e.string(),revision:e.number().int().nonnegative(),status:e.enum(["draft","published","archived"]),publishedVersionId:e.uuid().nullable(),createdAt:e.iso.datetime({offset:!0}),updatedAt:e.iso.datetime({offset:!0})}),D=l.extend({draft:c}),I=e.strictObject({rows:e.array(l).max(200),nextCursor:e.uuid().nullable()}),v=e.strictObject({id:e.uuid(),kind:s,resourceId:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),version:e.number().int().positive(),sourceRevision:e.number().int().nonnegative(),document:x,createdAt:e.iso.datetime({offset:!0})}),z=v.omit({document:!0}),V=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),kind:s,id:e.uuid(),document:c}),e.strictObject({action:e.literal("save"),kind:s,id:e.uuid(),revision:e.number().int().nonnegative(),document:c}),e.strictObject({action:e.enum(["publish","archive"]),kind:s,id:e.uuid(),revision:e.number().int().nonnegative()})]).superRefine((t,r)=>{"document"in t&&t.document.kind!==t.kind&&r.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});export{s as a,v as b};
|