@tinkerlandai/longplay-sdk 0.10.65 → 0.10.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +10 -0
  3. package/README.zh-CN.md +1 -1
  4. package/dist/check-response-WOTPYNDN.js +1 -0
  5. package/dist/{chunk-EB7MIZ4T.js → chunk-3Q3DZEP3.js} +1 -1
  6. package/dist/{chunk-R4CYPCBI.js → chunk-45MWDZ42.js} +1 -1
  7. package/dist/{chunk-TK3WOD2O.js → chunk-46USIMCJ.js} +1 -1
  8. package/dist/{chunk-ZCJEXNJD.js → chunk-47FCHF3Y.js} +1 -1
  9. package/dist/{chunk-ZRGL2CAP.js → chunk-56YCOGQZ.js} +1 -1
  10. package/dist/{chunk-S5RM3VO6.js → chunk-5WFI36LF.js} +1 -1
  11. package/dist/{chunk-77O2O552.js → chunk-74T76RE4.js} +1 -1
  12. package/dist/{chunk-4LQX4K5Q.js → chunk-7D5462NE.js} +1 -1
  13. package/dist/{chunk-HUYKZH3H.js → chunk-7EENIOSJ.js} +1 -1
  14. package/dist/chunk-7NKBMAOB.js +1 -0
  15. package/dist/{chunk-FQMZY5VP.js → chunk-7OJIW75D.js} +1 -1
  16. package/dist/{chunk-QXDLOPZK.js → chunk-A22QPPNY.js} +1 -1
  17. package/dist/{chunk-EKUDMQXT.js → chunk-AD35L6BX.js} +1 -1
  18. package/dist/{chunk-AHRBQWCA.js → chunk-C5FSL4XH.js} +2 -2
  19. package/dist/{chunk-PGLBFTRK.js → chunk-DCMA7W7N.js} +1 -1
  20. package/dist/{chunk-C3HZCZVJ.js → chunk-E3FUZSTM.js} +1 -1
  21. package/dist/{chunk-7PY3ACZY.js → chunk-EYTP23EK.js} +1 -1
  22. package/dist/{chunk-32AEJKJW.js → chunk-FUP5JVDE.js} +1 -1
  23. package/dist/{chunk-EE6QNOCL.js → chunk-G2OLUFYT.js} +1 -1
  24. package/dist/{chunk-PJHTN5NJ.js → chunk-GE6RSO2C.js} +1 -1
  25. package/dist/{chunk-YFOIOYTZ.js → chunk-HT5SLWWG.js} +1 -1
  26. package/dist/{chunk-7STWC4L4.js → chunk-IGE2UMXG.js} +1 -1
  27. package/dist/{chunk-5LNX7MHO.js → chunk-JBN6ADWQ.js} +1 -1
  28. package/dist/{chunk-IM5OXTEH.js → chunk-K675GO7R.js} +1 -1
  29. package/dist/{chunk-NDNHTG5B.js → chunk-KVLOMX2G.js} +1 -1
  30. package/dist/{chunk-OMJSBFMI.js → chunk-M6MXJHJ5.js} +1 -1
  31. package/dist/{chunk-DBYRJ4QV.js → chunk-MNICOIQ6.js} +1 -1
  32. package/dist/chunk-MUCDKWMP.js +1 -0
  33. package/dist/{chunk-US4MQ4ZG.js → chunk-MUP7FNNY.js} +1 -1
  34. package/dist/{chunk-JBSJ3JU2.js → chunk-N5HX3K5J.js} +1 -1
  35. package/dist/{chunk-KTWKDR5L.js → chunk-O5YYORDW.js} +1 -1
  36. package/dist/{chunk-VW2K4TZI.js → chunk-OFG3SGEX.js} +1 -1
  37. package/dist/{chunk-XCFAKO23.js → chunk-OKPWZZZW.js} +1 -1
  38. package/dist/{chunk-W7ATFFBO.js → chunk-OT55LG4U.js} +1 -1
  39. package/dist/{chunk-JEDRJAJ5.js → chunk-PNX7Y2K3.js} +1 -1
  40. package/dist/{chunk-2KM537QH.js → chunk-PQ4ISW55.js} +1 -1
  41. package/dist/{chunk-VXDVMAS6.js → chunk-Q523TPZM.js} +1 -1
  42. package/dist/{chunk-NAFHQVSX.js → chunk-QPVA644N.js} +1 -1
  43. package/dist/{chunk-G2CBJZEI.js → chunk-RHILCVPZ.js} +1 -1
  44. package/dist/{chunk-2RFI2DEV.js → chunk-RNCUAYLQ.js} +1 -1
  45. package/dist/{chunk-4SI4SQ3C.js → chunk-SAPICYY3.js} +1 -1
  46. package/dist/{chunk-BJW4AXFL.js → chunk-TXVLJFZG.js} +1 -1
  47. package/dist/{chunk-RIEWU4MN.js → chunk-XIBJF5E6.js} +1 -1
  48. package/dist/{chunk-KPILWKMK.js → chunk-YA5YKHDE.js} +1 -1
  49. package/dist/{chunk-VNYUL3PV.js → chunk-YUL23NAW.js} +1 -1
  50. package/dist/chunk-ZLSZBGJG.js +1 -0
  51. package/dist/{chunk-4OODZM64.js → chunk-ZWNWVMCH.js} +1 -1
  52. package/dist/{content-7HVO5QRZ.js → content-WWME7E27.js} +1 -1
  53. package/dist/funnel-host-purchase-XIGJ7P7M.js +1 -0
  54. package/dist/{funnel-host-recovery-paywall-D3VA3OIW.js → funnel-host-recovery-paywall-POMEY6I2.js} +1 -1
  55. package/dist/{funnel-paywall-copies-U3JIYQJ5.js → funnel-paywall-copies-DUZ3YX67.js} +1 -1
  56. package/dist/funnel-paywall-prerender-5NU457SR.js +1 -0
  57. package/dist/funnel-route-prediction-EW3HVH46.js +1 -0
  58. package/dist/funnel-route-source-YVFAFCVG.js +1 -0
  59. package/dist/funnel-runtime-host-J2HWW5IN.js +1 -0
  60. package/dist/index.d.ts +12 -6
  61. package/dist/index.js +1 -1
  62. package/dist/merchant-bridge-contracts-PNRVNTCN.js +1 -0
  63. package/dist/native-shell.js +1 -1
  64. package/dist/openrouter.js +1 -1
  65. package/dist/operation-contracts-6ORJSGYH.js +1 -0
  66. package/dist/page.js +1 -1
  67. package/dist/paywall-YRB7LQUS.js +1 -0
  68. package/dist/paywall-content-QLJIOFR3.js +1 -0
  69. package/dist/paywall-session-Q6ZYXUOU.js +1 -0
  70. package/dist/popup.js +1 -1
  71. package/dist/react-native.js +1 -1
  72. package/dist/screen-renderer-P6U5UBFX.js +1 -0
  73. package/dist/server.js +1 -1
  74. package/dist/visual.js +1 -1
  75. package/package.json +1 -1
  76. package/dist/check-response-K56UEZ6E.js +0 -1
  77. package/dist/chunk-6GIWQMRH.js +0 -1
  78. package/dist/chunk-75537OEL.js +0 -1
  79. package/dist/chunk-N7WQEC3L.js +0 -1
  80. package/dist/funnel-host-purchase-WNJ77ZPW.js +0 -1
  81. package/dist/funnel-paywall-prerender-AHG6D2TY.js +0 -1
  82. package/dist/funnel-route-prediction-XYWNKGQZ.js +0 -1
  83. package/dist/funnel-route-source-4ZVBFNYV.js +0 -1
  84. package/dist/funnel-runtime-host-KD2MR2MG.js +0 -1
  85. package/dist/merchant-bridge-contracts-IZ7ARRRO.js +0 -1
  86. package/dist/operation-contracts-6RQ33K66.js +0 -1
  87. package/dist/paywall-I3UXNTKB.js +0 -1
  88. package/dist/paywall-content-KYHTDMWU.js +0 -1
  89. package/dist/paywall-session-TNFSCXH6.js +0 -1
  90. package/dist/screen-renderer-3YO6EUWD.js +0 -1
  91. /package/dist/{chunk-AHRBQWCA.js.LEGAL.txt → chunk-C5FSL4XH.js.LEGAL.txt} +0 -0
  92. /package/dist/{chunk-PZTWDJHN.js → chunk-YLH3AYCK.js} +0 -0
@@ -1 +1 @@
1
- import{b as Jn}from"./chunk-6GIWQMRH.js";import{a as yn}from"./chunk-R4CYPCBI.js";import{a as Nn,b as Vn,c as mn,d as wn,e as $e,f as $n,h as Mn,i as xn,j as zn,k as Bn}from"./chunk-QXDLOPZK.js";import{a as Gn}from"./chunk-45PGU2HW.js";import{a as On}from"./chunk-W32FI2A2.js";import{c as qn,e as Hn,f as Ln,i as _n,j as He,k as tn,l as Un,m as rn}from"./chunk-IM5OXTEH.js";import{b as Dn}from"./chunk-ZCJEXNJD.js";import{a as fn,d as Sn}from"./chunk-NDNHTG5B.js";import{C as An}from"./chunk-ZRGL2CAP.js";import{a as te}from"./chunk-TK3WOD2O.js";import{a as Ce}from"./chunk-DSPLGTQI.js";function Qn(i){let b=new Set,N=new Set,n=null;async function p(a,f){let L=!1;for(;!i.stopped&&i.key===a&&i.client.pendingCommand?.requestId===f;){if(!i.client.settle)throw new te("COMMAND_PENDING","The original display acknowledgement is still pending");await i.client.settle(f),L=!0,i.client.pendingCommand?.requestId===f&&await new Promise(S=>setTimeout(S,1500))}i.stopped||i.key!==a||(L&&await i.client.get(),!(i.stopped||i.key!==a)&&b.add(a))}function E(a,f){n=f;let L=()=>{n===f&&(n=null),N.delete(a)};return f.then(L,S=>{L(),i.busy||i.fail(S)}),f}function X(a){if(i.reviewing||b.has(a)||N.has(a)||i.stopped)return;N.add(a);let f=async()=>{if(i.reviewing||i.stopped||i.key!==a||b.has(a)){N.delete(a);return}if(i.busy||i.client.pendingCommand){setTimeout(()=>{f()},250);return}let L=(async()=>{if(i.staleRead){if(await i.staleRead,i.stopped||i.key!==a)return;if(i.client.pendingCommand){setTimeout(()=>{f()},250);return}}let S=i.client.view,le=i.expected(),_=le.requestId;try{await i.client.submit({operation:"shown",...le})}catch(o){if(!(o instanceof te)||o.code!=="CONFLICT"||o.status!==409||i.client.pendingCommand)throw o;await i.client.get();let u=i.client.view;if(i.stopped||i.reviewing||i.key!==a||!u||!S||u.id!==S.id||u.source.versionId!==S.source.versionId||u.nodeId!==le.nodeId||u.visit!==le.visit||u.revision<=le.revision||u.stopped||!u.screen&&(!u.paywall||u.paywall.receiptId!==S.paywall?.receiptId)||!["running","waiting"].includes(u.status)||i.client.pendingCommand)throw o;let P=i.expected();_=P.requestId,await i.client.submit({operation:"shown",...P})}await p(a,_)})();E(a,L)};f()}function v(){if(n)return n;let a=i.client.pendingCommand;if(a?.operation!=="shown")return null;let f=i.key;return N.add(f),E(f,(async()=>{await i.client.retry(),await p(f,a.requestId)})())}return{report:X,settled:v,get inFlight(){return n}}}function Wn(i){let b={},N=new Map;async function n(p){let E=i.client.view,X=E?.screen,v=X?.customerData.nodes[p.nodeId];if(i.stopped||i.busy||!E||!X||!v)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(p.action)){let o=i.document,u=o?An(o,p.nodeId):null,P=u?.type==="customer_data"?u.data.outputs?.[p.action]:void 0;P&&X.outputs.includes(P)?await i.perform(()=>i.client.submit({operation:"submit",...i.expected(),input:{type:"screen",output:P,answers:i.answers,selection:p.value?{[p.nodeId]:p.value}:{}}})):await i.onIntent?.(p,E);return}let f=p.action.startsWith("sources_")?v.resources.find(o=>o.key===p.value):null;if(p.action.startsWith("sources_")&&!f)throw new te("INVALID_REQUEST","Choose a current resource");let L=`${E.visit}:${p.nodeId}:${f?.key??""}`,S=N.get(L)??[null],_=b[p.nodeId]??{page:1,after:null,filter:"all",...f?{resourceKey:f.key}:{}};if(p.action==="filter"){let o=p.value;if(!o||!(v.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(o))throw new te("INVALID_REQUEST","Unknown data filter");_={page:1,after:null,filter:o},S.splice(0,S.length,null)}else if(p.action==="next"||p.action==="sources_next"){let o=f?.sources.at(-1),u=f?o?{kind:"ledger",cursor:{at:o.detail[0],id:o.id,type:"source"}}:null:X.dataCursors[p.nodeId];if(!u||!f&&!v.hasNext)return;S[_.page]=u,_={..._,page:_.page+1,after:u}}else if(p.action==="previous"||p.action==="sources_previous"){if(_.page<=1)return;_={..._,page:_.page-1,after:S[_.page-2]??null}}N.set(L,S),b={...b,[p.nodeId]:_},await i.perform(()=>i.client.get({nodeId:E.nodeId,visit:E.visit,revision:E.revision,components:b}))}return{get queries(){return b},intent:n,reset(){b={},N.clear()}}}function jn(i){let{doc:b,holder:N,reviewHolder:n,mountScreenPreview:p}=i,E=!1,X,v=0,a=null,f="",L,S=new Map,le=u=>u?`${u.id}:${u.nodeId}:${u.visit}:${u.revision}:${u.paywall?.quote?.operationId??""}`:"";async function _(u){if(i.stopped||!i.client.review||E&&u===X&&L?.active)return;let P=!E||u!==X;E||(f=le(i.client.view),S.set(f,structuredClone(i.answers))),E=!0,X=u,N.hidden=!0,i.suspend(!0),n.hidden=!1;let c=++v;P&&(L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),L=tn(n,i.loadingOptions,"funnel",()=>{o()}));let k=P?L:void 0;try{if(k?.start(!1,i.client.view?.locale),c!==v||i.stopped)return;let U=i.client.review(u),j=await(k?.wait(U,He)??U);if(i.stopped||c!==v||!E)return;if(!j.review)throw new te("INVALID_RESPONSE","Historical projection is missing");a?.destroy(),a=null,k||n.replaceChildren();let M=b.createElement("div"),ye=k?rn(M,n):()=>{};n.append(M);let O=j.run.locale.startsWith("zh"),q=i.chrome;M.style.cssText=q.history;let F=b.createElement("p");F.textContent=O?"只读回看":"Read-only history",F.style.cssText=q.historyTitle,M.append(F);let Y=b.createElement("p");Y.style.cssText=q.historyNote,Y.textContent=j.review.pages.length?O?"选择一页查看当时的内容,回看不会改动任何信息。":"Choose a page to see it as it was. Nothing here can be changed.":O?"还没有可回看的页面。":"There are no earlier pages yet.",M.append(Y);let D=j.review.page?.receiptId,Ie=b.createElement("div");Ie.style.cssText=q.historyPages;for(let[T,x]of j.review.pages.entries()){let R=b.createElement("button");R.type="button",R.textContent=O?`第 ${T+1} 页`:`Page ${T+1}`;let J=D!==void 0&&x.receiptId===D;R.style.cssText=J?q.primary:q.secondary,J&&R.setAttribute("aria-current","page"),$e(R,()=>i.chrome.focus),R.onclick=()=>{_(x.receiptId)},Ie.append(R)}if(Ie.childElementCount&&M.append(Ie),j.review.page){let T=j.review.page,x=b.createElement("div");x.inert=!0,x.style.cssText=q.historyPage,M.append(x),a=p(x,{mode:"live",rendererUrl:i.client.webViewUrl,title:T.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{c===v&&!i.stopped&&k?.present(ye)},onError:J=>{if(c!==v||i.stopped)return;let Fe=new Error(J);k?.finish("error",Fe),a?.destroy(),a=null,M.remove(),i.fail(Fe)},onEscape:()=>{o()}});let R=a;if(R.update(T.document,j.run.locale,{serverInput:{bindings:T.inputs,answers:T.answers,values:T.values}}),await R.ready,i.stopped||c!==v||!E)return}let Le=O?{issued:"已领取",reserved:"已预留",redeemed:"已使用",expired:"已过期",revoked:"已撤销",unknown:"状态待确认"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},se=b.createElement("div");se.style.cssText=q.historyRecords;for(let T of[...j.review.coupons.map((x,R)=>`${O?"优惠券":"Coupon"} ${R+1}: ${Le[x.status]}`),...j.review.purchases.map((x,R)=>`${O?"购买":"Purchase"} ${R+1}: ${Bn(x.status,O)}`)]){let x=b.createElement("p");x.textContent=T,x.style.margin="0",se.append(x)}se.childElementCount&&M.append(se),j.review.page||k?.present(ye),i.client.view&&await i.enqueue(i.client.view)}catch(U){if(c!==v||i.stopped)return;k?.finish("error",U),a?.destroy(),a=null,n.replaceChildren(),i.fail(U)}}async function o(){if(!E||i.stopped||!i.client.review)return;let u=++v;L?.finish("dismissed");try{if(await i.client.review(),i.stopped||u!==v)return;E=!1,v++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,N.hidden=!1;let P=i.client.view;le(P)!==f?(S.set(f,structuredClone(i.answers)),i.resetScreen()):(S.delete(f),i.suspend(!1)),P&&await i.enqueue(P)}catch(P){if(u!==v||i.stopped)return;a?.destroy(),a=null,n.replaceChildren(),i.fail(P)}}return{get active(){return E},get receipt(){return X},open:_,exit:o,get drafts(){return new Map([...S].map(([u,P])=>[u,structuredClone(P)]))},stop(){E=!1,v++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,N.hidden=!1}}}var vn=5e3;async function nt(i,b,N){let n=b,p=n.prepared&&Jn(n.prepared),E=()=>{},X;function v(){n.prepared&&n.prepared.state!=="adopted"&&p?.release()}let a=()=>n.prepared?.state==="shown"&&!!p?.modal,f=n.client.identitySignal,L;try{L=await Promise.all([import("./screen-renderer-3YO6EUWD.js"),import("./paywall-I3UXNTKB.js")]),n.signal?.throwIfAborted(),f?.throwIfAborted()}catch(e){throw v(),e}let[{mountScreenPreview:S},{showPaywall:le}]=L,_=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.appManifestRelease?Gn({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;_?.start();let o=i.ownerDocument,u=_n(o),P=!1,c=o.createElement("section"),k=o.createElement("div"),U=o.createElement("div"),j=o.createElement("div"),M=o.createElement("button");j.hidden=!0,M.type="button";let ye=o.createElement("p"),O=o.createElement("p"),q=o.createElement("button"),F=o.createElement("button"),Y=o.createElement("button"),D=o.createElement("dialog"),Ie,Le=!1;c.dataset.indianaFunnel="",c.dataset.longplayCloseOwner="sdk",c.setAttribute("aria-busy","false"),ye.setAttribute("role","status"),O.setAttribute("role","alert"),O.hidden=!0,q.type=F.type=Y.type="button",U.append(q,M,ye,O,Y,F),c.append(k,j,U),i.append(c);let se=Vn,T=mn(se),x="",R=(o.documentElement.lang||"").startsWith("zh"),J,Fe="",Me;for(let e of[q,M,Y,F])$e(e,()=>T.focus);function gn(){let e=R?"关闭":"Close";F.parentElement===D?(F.textContent="×",F.setAttribute("aria-label",e),Ln(F,se)):(F.textContent=e,F.removeAttribute("aria-label"),F.style.cssText=T.link+";margin-inline-start:auto")}function xe(e){let t=e?.screen?.content.document.theme??se,r=JSON.stringify([t.primary,t.background,t.text,t.radius,t.font,F.parentElement===D]);if(r===x)return;x=r,se=t;let g=F.parentElement===D;T=mn(se,g),c.style.cssText=T.root+";min-width:0"+(g?";display:flex;flex-direction:column;min-height:100%":""),U.style.cssText=T.bar+(g?";margin-top:auto":""),U.hidden&&(U.style.display="none"),q.style.cssText=M.style.cssText=T.secondary,Y.style.cssText=T.primary,ye.style.cssText=T.status,O.style.cssText=T.alert,gn(),wn(q)}function be(){U.hidden=q.hidden&&M.hidden&&Y.hidden&&O.hidden&&!ye.textContent&&(F.hidden||F.parentElement!==U),U.style.display=U.hidden?"none":"flex",J?.responsive&&Me!==void 0&&J.setContentHeight(Me+U.getBoundingClientRect().height)}xe();let de=null,h=null,ue=null,ve="",ne="",Pe=!1,ze="",on="",Be="",s=!1,Z=0,Je=!1,hn="",sn=null,an=Promise.resolve(),In=!n.client.view,Ne,A=N,Ge=n.hostPaywallTarget,Te,_e,Qe="",We,ie=!1,Re=null,pe=!1,je=()=>n.client.pendingCommand?.operation==="close",re=null,V=null,ln=On({document:o,run:async()=>{(!h?.observing||n.client.pendingCommand)&&await un()},delay:()=>{if(!oe.pending&&!(s||!ue||!["running","waiting"].includes(ue.status)&&!n.client.pendingCommand)&&!(h?.observing&&!n.client.pendingCommand))return ue.pendingRequest||n.client.pendingCommand?1500:vn},hiddenDelay:()=>!s&&!oe.pending&&n.client.pendingCommand?15e3:void 0}),z=null;function dn(){return V&&n.client.hasDurableJournal===!0&&z?.acknowledged===!0&&z.operationId===V.operationId&&n.client.view?.id===z.runId&&n.client.view?.status==="closed"&&n.client.view.revision===z.revision+1&&!(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0))&&!n.client.pendingPurchase?V:null}function Cn(e){let t=e.run.paywall;if(z&&e.settlement?.requestId===z.requestId&&e.settlement.state==="settled"&&e.settlement.operationId===null&&e.run.id===z.runId&&e.run.status==="closed"&&!e.run.pendingRequest&&e.run.revision===z.revision+1&&e.run.nodeId===z.nodeId&&e.run.visit===z.visit&&t?.receiptId===z.receiptId&&t.selectionGeneration===z.selectionGeneration&&(t.quote?.operationId??null)===z.operationId&&(t.operation?.operationId??t.quote?.operationId??null)===z.operationId){let r=z.operationId===null&&t.selectionGeneration===0&&!t.quote&&!t.operation&&!t.purchaseRequestId,g=fn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect});(r||t.canReselect===!0&&g.type==="native")&&(z.acknowledged=!0)}}let Ee=null,Ue=new Set,fe={},Ae=!1,K=(e,t=null)=>{s||(e instanceof te&&e.status===409&&e.reason==="STATE_CHANGED"&&e.recovery==="recover_operation"&&ln.destroy(),Ee=t,Ae=!1,O.textContent=$n(e,R),O.hidden=!1,Y.hidden=n.client.pendingCommand===null,be(),Ce(n.onError,e))},oe=Dn({client:n.client,document:o,conceal(){s||(me(),A?.finish("dismissed"),c.hidden=!0,P||(P=!0,u()))},async receive(e){s||await ae(n.client.view??e.run)},failed(e){if(!s){if(!oe.pending){pe=!1;let t=n.client.view;t&&ae(t).then(()=>K(e),K);return}Ke(),c.parentElement!==i&&i.append(c),c.hidden=!1,q.hidden=M.hidden=F.hidden=!0,ye.textContent="",xe(),K(e,n.client.pendingCommand?.requestId??null)}}}),bn=()=>{s||(Ee=null,O.textContent=xn(R),O.hidden=!1,Y.hidden=!0,be())};function ke(){let e=n.client.view;if(!e)throw new te("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}let w=jn({client:n.client,doc:o,holder:k,reviewHolder:j,mountScreenPreview:S,loadingOptions:n,get chrome(){return T},get stopped(){return s},get answers(){return fe},suspend(e){h?.setSuspended(e)},resetScreen(){ve="",ne="",ze=""},enqueue:ae,fail:K}),Ve=Qn({client:n.client,expected:ke,fail:K,get stopped(){return s},get reviewing(){return w.active},get key(){return ve},get busy(){return Z},get staleRead(){return sn}}),Xe=Wn({client:n.client,expected:ke,perform:Se,onIntent:n.onCustomerDataIntent,get stopped(){return s},get busy(){return Z},get document(){return de?.document},get answers(){return fe}}),Ye=e=>`${e.id}:${e.nodeId}:${e.visit}`,De=e=>e&&(e.screen||e.paywall)?Ye(e):"";function ge(){let e=n.client.view;q.disabled=!w.active&&(Z>0||!!n.client.pendingCommand||!e?.canBack||e.stopped||!["running","waiting"].includes(e.status)||!De(e)||ne!==De(e)),q.hidden=!w.active&&!e?.canBack,wn(q);let t=!!h&&!w.active;F.hidden=t&&!A?.active||Le&&!w.active,M.hidden=!n.client.review||!w.active&&!e?.canBack;let r=e?.locale.startsWith("zh");ye.textContent=t?"":Z>0||e?.pendingRequest?r?"正在处理":"Processing":e?.instruction?.type==="wait"?r?"等待中":"Waiting":"",be()}async function Pn(e){if(!e)return;let t=n.client.view;await e;let r=n.client.view;if(!t||!r||r.id!==t.id||r.nodeId!==t.nodeId||r.visit!==t.visit||r.stopped||!["running","waiting"].includes(r.status))throw new te("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Se(e,t=!1,r){if(!((Z||pe||re||V)&&!t||s||w.active&&!t)){Z++,c.setAttribute("aria-busy","true"),O.hidden=!0,Ee=null,Ae=!1,ge();try{if(t||await Pn(Ve.inFlight),s)return;let g=await e();s||await ae(n.client.view??g.run)}catch(g){r?.(g)&&n.client.pendingCommand===null?bn():oe.pending||K(g,n.client.pendingCommand?.requestId??null)}finally{Z=Math.max(0,Z-1),c.setAttribute("aria-busy",String(Z>0)),s||(Y.hidden=n.client.pendingCommand===null,ge())}}}function Oe(){ln.schedule()}async function un(){if(!(s||Je||Z)&&!oe.pending){if(w.active){await w.open(w.receipt);return}Je=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let t=n.client.view,r=Xe.queries,g=await n.client.get(t?.screen&&Object.keys(r).length?{nodeId:t.nodeId,visit:t.visit,revision:t.revision,components:r}:void 0);Ae&&!s&&(Ae=!1,O.hidden=!0,be()),!s&&r===Xe.queries&&await ae(n.client.view??g.run)}catch(e){K(e),Ae=!s}finally{Je=!1}}}function Ze(e,t,r){if(A?.active){let ee=A;return ee.setDismissHandler(()=>Rn(ee)),ee}let g=tn(i,n,"funnel",()=>Rn(g),Nn);return A=g,g.start(e,t,r),g}function Rn(e){s||ie||(ie=!0,e.finish("dismissed"),me(),c.hidden=!0,n.client.view?he().finally(G):G())}function cn(){clearTimeout(We?.timeout),We=void 0}function me(e){Le=!1,cn(),Te?.abort(),Te=void 0,de?.destroy(),de=null,h?.destroy(),h=null,Ne=void 0,_e?.(),_e=void 0,D.open&&D.close();for(let t of Array.from(k.children))(!e||!t.contains(e))&&t.remove();k.style.cssText="",Me=void 0,ve="",ne="",Pe=!1,ze="",Be=""}function En(){let e=o.defaultView;J?.responsive&&e&&de?.resizeViewport?.(e.innerHeight,e.innerWidth)}function Ke(){J?.destroy(),J=void 0,Fe=""}function en(e){let t=e.screen?.presentation;if(!t||t.type==="inline"){D.open&&D.close(),Ke(),F.parentElement!==U&&U.append(F),c.parentElement!==i&&i.append(c);for(let ee of["flex","display","flex-direction","justify-content"])k.style.removeProperty(ee);xe(e),be();return}c.parentElement!==D&&(D.append(F,c),i.append(D)),k.style.flex="1 0 auto",k.style.display="flex",k.style.flexDirection="column",k.style.justifyContent="center",xe(e);let r=e.screen.content.document,g=JSON.stringify([t,x]);if(g!==Fe){Ke(),Fe=g;let ee={sm:420,md:640,lg:900},we="size"in t&&!t.backdrop?",0 0 0 100vmax #16142566":"";D.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${se.background};color:${se.text};`+(t.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ee[t.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${we};`+(t.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),J=qn(D,{presentation:t,theme:r.theme,pages:r.pages},En),J.latch()}be(),D.setAttribute("aria-label",(Ie?.screen===e.screen?.content.document.name?Ie?.label:void 0)??de?.document?.name??e.screen?.content.document.name??"Funnel")}async function Xn(e){if(s||ie)return;if(oe.observe(),oe.pending){ue=e;return}if(pe&&(je()||["running","waiting"].includes(e.status))||(ue=e,Ee&&n.client.pendingCommand?.requestId!==Ee&&(O.hidden=!0,Ee=null),R=e.locale.startsWith("zh"),M.textContent=R?"回看":"History",q.textContent=w.active?R?"返回当前":"Return to current":R?"返回":"Back",gn(),Y.textContent=R?"重试":"Retry",Y.hidden=n.client.pendingCommand===null,ge(),hn!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(hn=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,Ce(n.onState,structuredClone(e))),s||ie))return;if((!e.pendingRequest||pe&&e.status==="closed")&&["closed","ineligible","failed"].includes(e.status)){G();return}if(e.stopped&&a()){G();return}if(e.stopped||n.client.configurationReady===!1){w.stop(),v(),me(),A?.finish("skipped"),c.hidden=!0,Oe();return}if(c.hidden=!1,w.active){Oe();return}if(e.status==="completed"&&h?.subscriptionUpgradeActive){Oe();return}let t=De(e),r=n.client.view;if(r&&r.revision>e.revision&&De(r)!==t)return;let g=!e.instruction&&!e.pendingRequest&&e.nodeType==="screen"&&["running","waiting"].includes(e.status);t!==ve&&(ve&&A?.finish("dismissed"),me(),ve=t,fe={...e.answers},Xe.reset());let ee=Ye(e);if(Qe===ee){c.hidden=!0;return}if(g&&!t){c.hidden=!0;let I=n.prepared?.state==="shown"?null:Ze(!0,e.locale);!s&&!ie&&We?.key!==ee&&(cn(),We={key:ee,timeout:setTimeout(()=>{let l=n.client.view;if(s||!I?.active&&n.prepared?.state!=="shown"||!l||Ye(l)!==ee)return;Qe=ee;let H=new Error("Funnel screen preparation timed out");I?.finish("error",H),v(),me(),K(H)},He)}),Oe();return}cn();let $=I=>{let l=n.client.view;return!s&&!ie&&!Re&&!I.aborted&&n.client.configurationReady!==!1&&!!l&&!l.stopped&&!["closed","ineligible","failed"].includes(l.status)&&(De(l)===t||l.status==="completed"&&h?.subscriptionUpgradeActive===!0)},we=(I,l)=>{$(l)&&(Qe=t,A?.finish("error",I),me(),c.hidden=!0,K(I))};if(t||((e.instruction&&e.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(e.status))&&v(),en(e),e.instruction?.type!=="event"&&e.instruction?.type!=="open_url"&&A?.finish("skipped")),e.screen){Ge=void 0,v();let I=e.screen.content;if(!de){let W=e.screen.presentation.type!=="inline",C=Ze(W,e.locale);if(s||ie)return;let B=(Te=new AbortController).signal;en(e),_e=W?Un(D):rn(c,i),de=S(k,{mode:"live",closeActions:Array.from(new Set([...n.closeActions??[],...I.document.actions.filter(y=>y.type==="event"&&y.close).map(y=>y.id)])),onAuthoredClose(y){$(B)&&(Le=y,ge())},rendererUrl:n.client.webViewUrl,title:I.document.name,...W?{hostPresentation:()=>J?.type??e.screen.presentation.type}:{},onResize:y=>{Me=y,J?.responsive&&J.setContentHeight(y+U.getBoundingClientRect().height)},onAction(y,d={},ce={}){if(w.active||!$(B)||ne!==t)return;fe={...fe,...ce};let pn=e.screen?.inputs??[],Tn=Object.fromEntries(pn.filter(({variable:qe})=>Object.hasOwn(fe,qe)).map(({variable:qe})=>[qe,fe[qe]]));if(zn(pn,Tn).length){bn();return}Se(()=>n.client.submit({operation:"submit",...ke(),input:{type:"screen",output:y,answers:Tn,selection:d}}),!1,qe=>Mn(qe,pn))},onAnswers:y=>{w.active||!$(B)||ne!==t||(fe={...fe,...y})},onCustomerDataIntent:y=>{w.active||!$(B)||ne!==t||Xe.intent(y).catch(K)},onEscape:()=>{!$(B)||ne!==t||w.active||re||V||he()},onError:y=>{let d=new Error(y);ne===t?K(d):we(d,B)},onRendered:y=>{if(!(!$(B)||ne===t))try{C.present(d=>{_e?.(),_e=void 0,y&&(Ie={screen:I.document.name,label:y},D.setAttribute("aria-label",y)),W&&(D.showModal(),P=!1,J?.responsive&&D.focus({preventScroll:!0}),!d&&n.loading!=="host"&&Hn(D,J?.type??e.screen.presentation.type,J?.responsive)),ne=t,Pe=W,ge()}),$(B)&&Ve.report(t)}catch(d){we(d,B)}}}),En()}let l={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:fe,values:e.screen.values}},H=JSON.stringify([I,e.locale,l.parameters,e.screen.inputs,e.screen.values]);if(H!==ze)de.update(I.document,e.locale,l),ze=H,on=JSON.stringify(l.capabilities),Be=JSON.stringify(l.customerData);else{let W=JSON.stringify(l.capabilities);W!==on&&(de.updateCapabilities(l.capabilities),on=W),JSON.stringify(l.customerData)!==Be&&(de.updateCustomerData(l.customerData),Be=JSON.stringify(l.customerData))}let Q=de;if(Q)try{await(A?.wait(Q.ready)??Q.ready)}catch(W){Te&&we(W,Te.signal)}}else if(e.paywall&&!h){let I=e.paywall.resolution,l="document"in I?I.document:null,H=p,Q=n.mountPaywallControls,W=null,C=(Te=new AbortController).signal,B={loading:"host",signal:C,...Q&&{mountControls:d=>Q(d,e)},canInteract:()=>$(C)&&!w.active&&!re&&!V,beforeAction:async()=>{Z++;try{await Pn(Ve.settled()),O.hidden=!0,Ee=null,Ae=!1,be()}finally{Z=Math.max(0,Z-1)}},start:async()=>{let d=await yn(n.client),ce=X;return X=void 0,d.view&&ce?.(d.view),d},onObservationChange:Oe,onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resumeCheckout:n.resumeCheckout,allowNewPurchase:n.allowNewPurchase,checkoutNavigation:n.checkoutNavigation,terminateCheckout:n.terminateCheckout,beforeCheckoutReplacement:n.beforeCheckoutReplacement,purchaseConfirmation:n.purchaseConfirmation,confirmOnHostedCheckout:n.confirmOnHostedCheckout,resolveOfferId:n.resolveOfferId,resolveSubscriptionChange:n.resolveSubscriptionChange,claimCoupon:n.claimCoupon,onEvent:n.onEvent,onOpenUrl:d=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:d,openIn:"same_window"}):o.defaultView?.location.assign(d),onAction:async d=>{if(w.active)return;let ce=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:d,answers:{}}});await ae(n.client.view??ce.run)},onError:d=>{ne===t?K(d):we(d,C)}},y={quoteError:d=>Ce(n.onError,d),present(d){$(C)&&(W?.present(ce=>{d(ce),ne=t,Pe=y.retainedDialog?.dialog.open??!!k.querySelector("dialog[open]"),Pe&&(P=!1),ge()}),$(C)&&Ve.report(t))},async closeAction(d){s||w.active||await oe.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:d,answers:{}}})},async dismiss(){if(s||C.aborted||w.active||re||V||!pe&&!$(C))return;pe=!0;let d=n.client.view;if(d?.status==="completed"&&h?.subscriptionUpgradeActive){Ue.add(`complete:${d.id}`),Ce(n.onComplete,structuredClone(d)),G();return}if((n.resumeCheckout||n.terminateCheckout)&&et()){ue=n.client.view,G();return}await he()}};if(H&&Q)v();else if(H){let d=await H.adopt(e,{options:B,handoff:y,start:()=>yn(n.client)});d&&$(C)&&!s?(en(e),h=d,Ne={runId:e.id,receiptId:e.paywall.receiptId},A?.active&&A.present(()=>{}),ne=t,Pe=H.modal,Pe&&(P=!1),ge(),Ve.report(t),w.active&&h.setSuspended(!0)):(d?.destroy(),v(),X=ce=>p?.remember(ce))}if(s||ie)return;if(!h){if(W=Ze(!0,e.locale,l),s||ie)return;(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.loading==="host"&&Ge?.ownerDocument===o&&(y.hostPaywallTarget=Ge),Ge=void 0,en(e);let d=await le(k,B,y).catch(ce=>(we(ce,C),null));!$(C)&&!(pe&&!s&&!C.aborted)?d?.host?.destroy():d&&(h=d.host,h&&(Ne={runId:e.id,receiptId:e.paywall.receiptId}),h?.setSuspended(w.active))}}if(s||ie)return;ge();let m=e.instruction;if(m&&(m.type==="open_url"||m.type==="event")&&!Ue.has(m.receiptId)){let I=o.createElement("button");I.type="button",I.style.cssText=T.primary,$e(I,()=>T.focus),k.style.cssText=T.stage,I.textContent=m.type==="open_url"?`${R?"前往":"Continue to"} ${new URL(m.url).host}`:R?"继续":"Continue",I.onclick=()=>{let l=ke(),H=m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="new_window"?Yn(m.url):null;Se(async()=>{let Q="success";if(m.type==="open_url")if(n.onOpenUrl)try{Q=await n.onOpenUrl({receiptId:m.receiptId,url:m.url,openIn:m.openIn})===!1?"failed":"opened"}catch(C){Ce(n.onError,C),Q="failed"}else Q=m.openIn==="new_window"&&!H?"failed":"opened";if(m.type==="event"){if(!n.onEvent)throw new te("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(m.event)}if(s||n.client.view?.nodeId!==l.nodeId||n.client.view.visit!==l.visit)throw new te("PRECONDITION_FAILED","The client action visit changed");let W=await n.client.submit({operation:"submit",...l,input:{type:"client_action",receiptId:m.receiptId,outcome:Q}});return Ue.add(m.receiptId),m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="same_window"&&o.defaultView?.location.assign(m.url),W})},A?.active?A.present(()=>k.replaceChildren(I)):k.replaceChildren(I)}!e.pendingRequest&&e.status==="completed"&&!Ue.has(`complete:${e.id}`)&&(Ue.add(`complete:${e.id}`),Ce(n.onComplete,structuredClone(e))),Oe()}function Yn(e){let t=o.defaultView?.open(e,"_blank")??null;return t&&(t.opener=null),t}function ae(e){return ge(),an=an.catch(()=>{}).then(async()=>{try{await Xn(e)}catch(t){throw A?.active&&(Qe=Ye(e),A.finish("error",t),me(),c.hidden=!0),t}}),an}let Zn=n.client.subscribe(e=>{if(!In){if(e.stopped&&(Pe||a())&&!pe){ue=e,G();return}!pe&&(e.stopped||n.client.configurationReady===!1||ve&&ne!==ve&&(De(e)!==ve||["closed","ineligible","failed"].includes(e.status)))&&(me(),A?.finish("dismissed"),c.hidden=!0),ae(e).catch(K)}}),Kn=n.client.subscribeError?.(e=>{oe.pending||K(e)});function et(){let e=n.client.view,t=e?.paywall;return!!t?.operation&&!!e&&["running","waiting"].includes(e.status)&&Sn(fn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect}))}function he(e){if(Re)return Re;if(s||!e&&(re||V))return Promise.resolve();let t=!e&&je();return!t&&n.client.view&&!["running","waiting"].includes(n.client.view.status)?(ue=n.client.view,G(),Promise.resolve()):(Re=Se(async()=>{let r=t?await n.client.retry():await(e?n.client.submit.bind(n.client):oe.submit)({operation:"close",...e??ke()});return e&&Cn(r),r},!0).then(()=>{let r=n.client.view;r?.status==="closed"&&!je()&&(ue=r,G())}).finally(()=>{Re=null}),Re)}function G(){kn()}function kn(e){_?.destroy(),!s&&(s=!0,oe.destroy(),E(),v(),n.signal?.removeEventListener("abort",G),f?.removeEventListener("abort",G),A?.finish("dismissed"),ln.destroy(),Zn(),Kn?.(),me(e),Ke(),w.stop(),D.remove(),!e||!c.contains(e)?c.remove():(U.remove(),j.remove()),!e&&!P&&u(),Ce(n.onDismiss,ue?structuredClone(ue):null))}q.onclick=()=>{if(!q.disabled){if(w.active){w.exit();return}Se(()=>n.client.submit({operation:"back",...ke()}))}},M.onclick=()=>{w.open()},F.onclick=()=>{A?.active?A.dismiss():re||he()},Y.onclick=()=>{oe.pending?oe.retry().catch(()=>{}):je()?he():Se(()=>n.client.retry())},D.addEventListener("cancel",e=>{e.preventDefault(),A?.active?A.dismiss():re||he()}),n.signal?.addEventListener("abort",G,{once:!0}),f?.addEventListener("abort",G,{once:!0});let nn=!1;p&&(E=p.onClose(()=>{s||ie||(ie=!0,A?.finish("dismissed"),me(),c.hidden=!0,n.client.view?he().finally(G):nn=!0)}));let Fn={destroy:G,refresh:un,get recoveryPaywall(){if(h&&Ne)return{...Ne,view:h.currentResolution}},setPurchaseRecovery(e,t){return h?.setPurchaseRecovery(e,t),h!==null},retainPurchaseDialog(){let e=h?.retainPurchaseDialog();if(e)return h=null,kn(e.dialog),{dialog:e.dialog,release(){e.release(),c.remove(),P||u()}}},get recovery(){let e=dn();if(e)return e;if(!s&&!Z&&!pe&&!re&&h){let t=h.recovery;if(t.type!=="native")return t}return{type:"recover",operationId:n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??V?.operationId??null,requestId:n.client.pendingCommand?.requestId??null}},prepareFallback(){if(re)return re;let e=dn();if(e)return Promise.resolve(e);let t=n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??V?.operationId??null,r=()=>({type:"recover",operationId:t,requestId:n.client.pendingCommand?.requestId??null});if(n.client.hasDurableJournal!==!0){let m=h?.recovery;return Promise.resolve(m&&m.type!=="native"&&m.type!=="cancel"?m:r())}let g=(n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[])).some(m=>m.operation==="close");if(s&&!(g||V&&n.client.view?.status==="closed")||Z||Je||Re||w.active||!h&&!V&&!g)return Promise.resolve(r());let ee=h,$=(async()=>{try{if(!V&&g){let l=await n.client.retry();return await ae(n.client.view??l.run),r()}if(!V){let l=await ee.prepareFallback();if(l.type!=="native")return l;if(n.client.hasDurableJournal!==!0)return r();V=l}let m=n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[]);if(m.length){let l=m.find(Q=>Q.operation==="close");if(!l||!z||l.requestId!==z.requestId)return r();let H=await n.client.retry();Cn(H),await ae(n.client.view??H.run)}else{let l=n.client.view,H=l?.paywall;if(!l||!H||H.selectionGeneration===void 0||(H.quote?.operationId??null)!==V.operationId||V.operationId!==null&&H.canReselect!==!0)return r();let Q=H.selectionGeneration,W=await n.client.get();await ae(n.client.view??W.run);let C=n.client.view,B=C?.paywall;if(!C||!B||!["running","waiting"].includes(C.status)||C.stopped||C.id!==l.id||C.nodeId!==l.nodeId||C.visit!==l.visit||B.receiptId!==H.receiptId||B.selectionGeneration!==Q||(B.quote?.operationId??null)!==V.operationId||V.operationId!==null&&B.canReselect!==!0||n.client.pendingPurchase||(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0)))return r();let y=ke();z={runId:C.id,operationId:V.operationId,revision:y.revision,requestId:y.requestId,nodeId:C.nodeId,visit:C.visit,receiptId:B.receiptId,selectionGeneration:Q,acknowledged:!1},await he(y)}let I=dn();return I?(G(),I):r()}catch(m){return K(m),r()}})();re=$;let we=()=>{re===$&&(re=null)};return $.then(we,we),$},review:w.open,exitReview:w.exit,get unappliedDrafts(){return w.drafts}};try{let e=n.client.view;if(e)((n.client.viewAgeMs??vn)>=vn||e.instruction?.type==="evaluate_segment")&&(sn=un().finally(()=>{sn=null})),await ae(e);else{if(c.hidden=!0,s)throw new DOMException("Presentation cancelled","AbortError");let t=nn||n.prepared?.state==="shown"?null:Ze(n.client.view?.screen?.presentation.type!=="inline",n.client.view?.locale);if(s||ie&&!nn)throw new DOMException("Presentation cancelled","AbortError");let r=n.client.get(),g=await(t?t.wait(r,He):tt(r,He));if(In=!1,nn)return s||await he().finally(G),Fn;await ae(n.client.view??g.run)}}catch(e){throw A?.finish("error",e),G(),e}return Fn}function tt(i,b){let N;return Promise.race([i,new Promise((n,p)=>{N=setTimeout(()=>p(new Error("Presentation data timed out")),b)})]).finally(()=>clearTimeout(N))}function Ot(i,b,N){return nt(i,b,N)}export{nt as a,Ot as b};
1
+ import{b as Jn}from"./chunk-7NKBMAOB.js";import{a as yn}from"./chunk-45MWDZ42.js";import{a as Nn,b as Vn,c as mn,d as wn,e as $e,f as $n,h as Mn,i as xn,j as zn,k as Bn}from"./chunk-A22QPPNY.js";import{a as Gn}from"./chunk-45PGU2HW.js";import{a as On}from"./chunk-W32FI2A2.js";import{c as qn,e as Hn,f as Ln,i as _n,j as He,k as tn,l as Un,m as rn}from"./chunk-K675GO7R.js";import{b as Dn}from"./chunk-47FCHF3Y.js";import{a as fn,d as Sn}from"./chunk-KVLOMX2G.js";import{C as An}from"./chunk-56YCOGQZ.js";import{a as te}from"./chunk-46USIMCJ.js";import{a as Ce}from"./chunk-DSPLGTQI.js";function Qn(i){let b=new Set,N=new Set,n=null;async function p(a,f){let L=!1;for(;!i.stopped&&i.key===a&&i.client.pendingCommand?.requestId===f;){if(!i.client.settle)throw new te("COMMAND_PENDING","The original display acknowledgement is still pending");await i.client.settle(f),L=!0,i.client.pendingCommand?.requestId===f&&await new Promise(S=>setTimeout(S,1500))}i.stopped||i.key!==a||(L&&await i.client.get(),!(i.stopped||i.key!==a)&&b.add(a))}function E(a,f){n=f;let L=()=>{n===f&&(n=null),N.delete(a)};return f.then(L,S=>{L(),i.busy||i.fail(S)}),f}function X(a){if(i.reviewing||b.has(a)||N.has(a)||i.stopped)return;N.add(a);let f=async()=>{if(i.reviewing||i.stopped||i.key!==a||b.has(a)){N.delete(a);return}if(i.busy||i.client.pendingCommand){setTimeout(()=>{f()},250);return}let L=(async()=>{if(i.staleRead){if(await i.staleRead,i.stopped||i.key!==a)return;if(i.client.pendingCommand){setTimeout(()=>{f()},250);return}}let S=i.client.view,le=i.expected(),_=le.requestId;try{await i.client.submit({operation:"shown",...le})}catch(o){if(!(o instanceof te)||o.code!=="CONFLICT"||o.status!==409||i.client.pendingCommand)throw o;await i.client.get();let u=i.client.view;if(i.stopped||i.reviewing||i.key!==a||!u||!S||u.id!==S.id||u.source.versionId!==S.source.versionId||u.nodeId!==le.nodeId||u.visit!==le.visit||u.revision<=le.revision||u.stopped||!u.screen&&(!u.paywall||u.paywall.receiptId!==S.paywall?.receiptId)||!["running","waiting"].includes(u.status)||i.client.pendingCommand)throw o;let P=i.expected();_=P.requestId,await i.client.submit({operation:"shown",...P})}await p(a,_)})();E(a,L)};f()}function g(){if(n)return n;let a=i.client.pendingCommand;if(a?.operation!=="shown")return null;let f=i.key;return N.add(f),E(f,(async()=>{await i.client.retry(),await p(f,a.requestId)})())}return{report:X,settled:g,get inFlight(){return n}}}function Wn(i){let b={},N=new Map;async function n(p){let E=i.client.view,X=E?.screen,g=X?.customerData.nodes[p.nodeId];if(i.stopped||i.busy||!E||!X||!g)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(p.action)){let o=i.document,u=o?An(o,p.nodeId):null,P=u?.type==="customer_data"?u.data.outputs?.[p.action]:void 0;P&&X.outputs.includes(P)?await i.perform(()=>i.client.submit({operation:"submit",...i.expected(),input:{type:"screen",output:P,answers:i.answers,selection:p.value?{[p.nodeId]:p.value}:{}}})):await i.onIntent?.(p,E);return}let f=p.action.startsWith("sources_")?g.resources.find(o=>o.key===p.value):null;if(p.action.startsWith("sources_")&&!f)throw new te("INVALID_REQUEST","Choose a current resource");let L=`${E.visit}:${p.nodeId}:${f?.key??""}`,S=N.get(L)??[null],_=b[p.nodeId]??{page:1,after:null,filter:"all",...f?{resourceKey:f.key}:{}};if(p.action==="filter"){let o=p.value;if(!o||!(g.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(o))throw new te("INVALID_REQUEST","Unknown data filter");_={page:1,after:null,filter:o},S.splice(0,S.length,null)}else if(p.action==="next"||p.action==="sources_next"){let o=f?.sources.at(-1),u=f?o?{kind:"ledger",cursor:{at:o.detail[0],id:o.id,type:"source"}}:null:X.dataCursors[p.nodeId];if(!u||!f&&!g.hasNext)return;S[_.page]=u,_={..._,page:_.page+1,after:u}}else if(p.action==="previous"||p.action==="sources_previous"){if(_.page<=1)return;_={..._,page:_.page-1,after:S[_.page-2]??null}}N.set(L,S),b={...b,[p.nodeId]:_},await i.perform(()=>i.client.get({nodeId:E.nodeId,visit:E.visit,revision:E.revision,components:b}))}return{get queries(){return b},intent:n,reset(){b={},N.clear()}}}function jn(i){let{doc:b,holder:N,reviewHolder:n,mountScreenPreview:p}=i,E=!1,X,g=0,a=null,f="",L,S=new Map,le=u=>u?`${u.id}:${u.nodeId}:${u.visit}:${u.revision}:${u.paywall?.quote?.operationId??""}`:"";async function _(u){if(i.stopped||!i.client.review||E&&u===X&&L?.active)return;let P=!E||u!==X;E||(f=le(i.client.view),S.set(f,structuredClone(i.answers))),E=!0,X=u,N.hidden=!0,i.suspend(!0),n.hidden=!1;let c=++g;P&&(L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),L=tn(n,i.loadingOptions,"funnel",()=>{o()}));let k=P?L:void 0;try{if(k?.start(!1,i.client.view?.locale),c!==g||i.stopped)return;let U=i.client.review(u),j=await(k?.wait(U,He)??U);if(i.stopped||c!==g||!E)return;if(!j.review)throw new te("INVALID_RESPONSE","Historical projection is missing");a?.destroy(),a=null,k||n.replaceChildren();let M=b.createElement("div"),ye=k?rn(M,n):()=>{};n.append(M);let O=j.run.locale.startsWith("zh"),q=i.chrome;M.style.cssText=q.history;let F=b.createElement("p");F.textContent=O?"只读回看":"Read-only history",F.style.cssText=q.historyTitle,M.append(F);let Y=b.createElement("p");Y.style.cssText=q.historyNote,Y.textContent=j.review.pages.length?O?"选择一页查看当时的内容,回看不会改动任何信息。":"Choose a page to see it as it was. Nothing here can be changed.":O?"还没有可回看的页面。":"There are no earlier pages yet.",M.append(Y);let D=j.review.page?.receiptId,Ie=b.createElement("div");Ie.style.cssText=q.historyPages;for(let[T,x]of j.review.pages.entries()){let R=b.createElement("button");R.type="button",R.textContent=O?`第 ${T+1} 页`:`Page ${T+1}`;let J=D!==void 0&&x.receiptId===D;R.style.cssText=J?q.primary:q.secondary,J&&R.setAttribute("aria-current","page"),$e(R,()=>i.chrome.focus),R.onclick=()=>{_(x.receiptId)},Ie.append(R)}if(Ie.childElementCount&&M.append(Ie),j.review.page){let T=j.review.page,x=b.createElement("div");x.inert=!0,x.style.cssText=q.historyPage,M.append(x),a=p(x,{mode:"live",rendererUrl:i.client.webViewUrl,title:T.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{c===g&&!i.stopped&&k?.present(ye)},onError:J=>{if(c!==g||i.stopped)return;let Fe=new Error(J);k?.finish("error",Fe),a?.destroy(),a=null,M.remove(),i.fail(Fe)},onEscape:()=>{o()}});let R=a;if(R.update(T.document,j.run.locale,{serverInput:{bindings:T.inputs,answers:T.answers,values:T.values}}),await R.ready,i.stopped||c!==g||!E)return}let Le=O?{issued:"已领取",reserved:"已预留",redeemed:"已使用",expired:"已过期",revoked:"已撤销",unknown:"状态待确认"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},se=b.createElement("div");se.style.cssText=q.historyRecords;for(let T of[...j.review.coupons.map((x,R)=>`${O?"优惠券":"Coupon"} ${R+1}: ${Le[x.status]}`),...j.review.purchases.map((x,R)=>`${O?"购买":"Purchase"} ${R+1}: ${Bn(x.status,O)}`)]){let x=b.createElement("p");x.textContent=T,x.style.margin="0",se.append(x)}se.childElementCount&&M.append(se),j.review.page||k?.present(ye),i.client.view&&await i.enqueue(i.client.view)}catch(U){if(c!==g||i.stopped)return;k?.finish("error",U),a?.destroy(),a=null,n.replaceChildren(),i.fail(U)}}async function o(){if(!E||i.stopped||!i.client.review)return;let u=++g;L?.finish("dismissed");try{if(await i.client.review(),i.stopped||u!==g)return;E=!1,g++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,N.hidden=!1;let P=i.client.view;le(P)!==f?(S.set(f,structuredClone(i.answers)),i.resetScreen()):(S.delete(f),i.suspend(!1)),P&&await i.enqueue(P)}catch(P){if(u!==g||i.stopped)return;a?.destroy(),a=null,n.replaceChildren(),i.fail(P)}}return{get active(){return E},get receipt(){return X},open:_,exit:o,get drafts(){return new Map([...S].map(([u,P])=>[u,structuredClone(P)]))},stop(){E=!1,g++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,N.hidden=!1}}}var gn=5e3;async function nt(i,b,N){let n=b,p=n.prepared&&Jn(n.prepared),E=()=>{},X;function g(){n.prepared&&n.prepared.state!=="adopted"&&p?.release()}let a=()=>n.prepared?.state==="shown"&&!!p?.modal,f=n.client.identitySignal,L;try{L=await Promise.all([import("./screen-renderer-P6U5UBFX.js"),import("./paywall-YRB7LQUS.js")]),n.signal?.throwIfAborted(),f?.throwIfAborted()}catch(e){throw g(),e}let[{mountScreenPreview:S},{showPaywall:le}]=L,_=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.appManifestRelease?Gn({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;_?.start();let o=i.ownerDocument,u=_n(o),P=!1,c=o.createElement("section"),k=o.createElement("div"),U=o.createElement("div"),j=o.createElement("div"),M=o.createElement("button");j.hidden=!0,M.type="button";let ye=o.createElement("p"),O=o.createElement("p"),q=o.createElement("button"),F=o.createElement("button"),Y=o.createElement("button"),D=o.createElement("dialog"),Ie,Le=!1;c.dataset.indianaFunnel="",c.dataset.longplayCloseOwner="sdk",c.setAttribute("aria-busy","false"),ye.setAttribute("role","status"),O.setAttribute("role","alert"),O.hidden=!0,q.type=F.type=Y.type="button",U.append(q,M,ye,O,Y,F),c.append(k,j,U),i.append(c);let se=Vn,T=mn(se),x="",R=(o.documentElement.lang||"").startsWith("zh"),J,Fe="",Me;for(let e of[q,M,Y,F])$e(e,()=>T.focus);function vn(){let e=R?"关闭":"Close";F.parentElement===D?(F.textContent="×",F.setAttribute("aria-label",e),Ln(F,se)):(F.textContent=e,F.removeAttribute("aria-label"),F.style.cssText=T.link+";margin-inline-start:auto")}function xe(e){let t=e?.screen?.content.document.theme??se,r=JSON.stringify([t.primary,t.background,t.text,t.radius,t.font,F.parentElement===D]);if(r===x)return;x=r,se=t;let v=F.parentElement===D;T=mn(se,v),c.style.cssText=T.root+";min-width:0"+(v?";display:flex;flex-direction:column;min-height:100%":""),U.style.cssText=T.bar+(v?";margin-top:auto":""),U.hidden&&(U.style.display="none"),q.style.cssText=M.style.cssText=T.secondary,Y.style.cssText=T.primary,ye.style.cssText=T.status,O.style.cssText=T.alert,vn(),wn(q)}function be(){U.hidden=q.hidden&&M.hidden&&Y.hidden&&O.hidden&&!ye.textContent&&(F.hidden||F.parentElement!==U),U.style.display=U.hidden?"none":"flex",J?.responsive&&Me!==void 0&&J.setContentHeight(Me+U.getBoundingClientRect().height)}xe();let de=null,h=null,ue=null,ge="",ne="",Pe=!1,ze="",on="",Be="",s=!1,Z=0,Je=!1,hn="",sn=null,an=Promise.resolve(),In=!n.client.view,Ne,A=N,Ge=n.hostPaywallTarget,Te,_e,Qe="",We,ie=!1,Re=null,pe=!1,je=()=>n.client.pendingCommand?.operation==="close",re=null,V=null,ln=On({document:o,run:async()=>{(!h?.observing||n.client.pendingCommand)&&await un()},delay:()=>{if(!oe.pending&&!(s||!ue||!["running","waiting"].includes(ue.status)&&!n.client.pendingCommand)&&!(h?.observing&&!n.client.pendingCommand))return ue.pendingRequest||n.client.pendingCommand?1500:gn},hiddenDelay:()=>!s&&!oe.pending&&n.client.pendingCommand?15e3:void 0}),z=null;function dn(){return V&&n.client.hasDurableJournal===!0&&z?.acknowledged===!0&&z.operationId===V.operationId&&n.client.view?.id===z.runId&&n.client.view?.status==="closed"&&n.client.view.revision===z.revision+1&&!(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0))&&!n.client.pendingPurchase?V:null}function Cn(e){let t=e.run.paywall;if(z&&e.settlement?.requestId===z.requestId&&e.settlement.state==="settled"&&e.settlement.operationId===null&&e.run.id===z.runId&&e.run.status==="closed"&&!e.run.pendingRequest&&e.run.revision===z.revision+1&&e.run.nodeId===z.nodeId&&e.run.visit===z.visit&&t?.receiptId===z.receiptId&&t.selectionGeneration===z.selectionGeneration&&(t.quote?.operationId??null)===z.operationId&&(t.operation?.operationId??t.quote?.operationId??null)===z.operationId){let r=z.operationId===null&&t.selectionGeneration===0&&!t.quote&&!t.operation&&!t.purchaseRequestId,v=fn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect});(r||t.canReselect===!0&&v.type==="native")&&(z.acknowledged=!0)}}let Ee=null,Ue=new Set,fe={},Ae=!1,K=(e,t=null)=>{s||(e instanceof te&&e.status===409&&e.reason==="STATE_CHANGED"&&e.recovery==="recover_operation"&&ln.destroy(),Ee=t,Ae=!1,O.textContent=$n(e,R),O.hidden=!1,Y.hidden=n.client.pendingCommand===null,be(),Ce(n.onError,e))},oe=Dn({client:n.client,document:o,conceal(){s||(me(),A?.finish("dismissed"),c.hidden=!0,P||(P=!0,u()))},async receive(e){s||await ae(n.client.view??e.run)},failed(e){if(!s){if(!oe.pending){pe=!1;let t=n.client.view;t&&ae(t).then(()=>K(e),K);return}Ke(),c.parentElement!==i&&i.append(c),c.hidden=!1,q.hidden=M.hidden=F.hidden=!0,ye.textContent="",xe(),K(e,n.client.pendingCommand?.requestId??null)}}}),bn=()=>{s||(Ee=null,O.textContent=xn(R),O.hidden=!1,Y.hidden=!0,be())};function ke(){let e=n.client.view;if(!e)throw new te("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}let w=jn({client:n.client,doc:o,holder:k,reviewHolder:j,mountScreenPreview:S,loadingOptions:n,get chrome(){return T},get stopped(){return s},get answers(){return fe},suspend(e){h?.setSuspended(e)},resetScreen(){ge="",ne="",ze=""},enqueue:ae,fail:K}),Ve=Qn({client:n.client,expected:ke,fail:K,get stopped(){return s},get reviewing(){return w.active},get key(){return ge},get busy(){return Z},get staleRead(){return sn}}),Xe=Wn({client:n.client,expected:ke,perform:Se,onIntent:n.onCustomerDataIntent,get stopped(){return s},get busy(){return Z},get document(){return de?.document},get answers(){return fe}}),Ye=e=>`${e.id}:${e.nodeId}:${e.visit}`,De=e=>e&&(e.screen||e.paywall)?Ye(e):"";function ve(){let e=n.client.view;q.disabled=!w.active&&(Z>0||!!n.client.pendingCommand||!e?.canBack||e.stopped||!["running","waiting"].includes(e.status)||!De(e)||ne!==De(e)),q.hidden=!w.active&&!e?.canBack,wn(q);let t=!!h&&!w.active;F.hidden=t&&!A?.active||Le&&!w.active,M.hidden=!n.client.review||!w.active&&!e?.canBack;let r=e?.locale.startsWith("zh");ye.textContent=t?"":Z>0||e?.pendingRequest?r?"正在处理":"Processing":e?.instruction?.type==="wait"?r?"等待中":"Waiting":"",be()}async function Pn(e){if(!e)return;let t=n.client.view;await e;let r=n.client.view;if(!t||!r||r.id!==t.id||r.nodeId!==t.nodeId||r.visit!==t.visit||r.stopped||!["running","waiting"].includes(r.status))throw new te("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Se(e,t=!1,r){if(!((Z||pe||re||V)&&!t||s||w.active&&!t)){Z++,c.setAttribute("aria-busy","true"),O.hidden=!0,Ee=null,Ae=!1,ve();try{if(t||await Pn(Ve.inFlight),s)return;let v=await e();s||await ae(n.client.view??v.run)}catch(v){r?.(v)&&n.client.pendingCommand===null?bn():oe.pending||K(v,n.client.pendingCommand?.requestId??null)}finally{Z=Math.max(0,Z-1),c.setAttribute("aria-busy",String(Z>0)),s||(Y.hidden=n.client.pendingCommand===null,ve())}}}function Oe(){ln.schedule()}async function un(){if(!(s||Je||Z)&&!oe.pending){if(w.active){await w.open(w.receipt);return}Je=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let t=n.client.view,r=Xe.queries,v=await n.client.get(t?.screen&&Object.keys(r).length?{nodeId:t.nodeId,visit:t.visit,revision:t.revision,components:r}:void 0);Ae&&!s&&(Ae=!1,O.hidden=!0,be()),!s&&r===Xe.queries&&await ae(n.client.view??v.run)}catch(e){K(e),Ae=!s}finally{Je=!1}}}function Ze(e,t,r){if(A?.active){let ee=A;return ee.setDismissHandler(()=>Rn(ee)),ee}let v=tn(i,n,"funnel",()=>Rn(v),Nn);return A=v,v.start(e,t,r),v}function Rn(e){s||ie||(ie=!0,e.finish("dismissed"),me(),c.hidden=!0,n.client.view?he().finally(G):G())}function cn(){clearTimeout(We?.timeout),We=void 0}function me(e){Le=!1,cn(),Te?.abort(),Te=void 0,de?.destroy(),de=null,h?.destroy(),h=null,Ne=void 0,_e?.(),_e=void 0,D.open&&D.close();for(let t of Array.from(k.children))(!e||!t.contains(e))&&t.remove();k.style.cssText="",Me=void 0,ge="",ne="",Pe=!1,ze="",Be=""}function En(){let e=o.defaultView;J?.responsive&&e&&de?.resizeViewport?.(e.innerHeight,e.innerWidth)}function Ke(){J?.destroy(),J=void 0,Fe=""}function en(e){let t=e.screen?.presentation;if(!t||t.type==="inline"){D.open&&D.close(),Ke(),F.parentElement!==U&&U.append(F),c.parentElement!==i&&i.append(c);for(let ee of["flex","display","flex-direction","justify-content"])k.style.removeProperty(ee);xe(e),be();return}c.parentElement!==D&&(D.append(F,c),i.append(D)),k.style.flex="1 0 auto",k.style.display="flex",k.style.flexDirection="column",k.style.justifyContent="center",xe(e);let r=e.screen.content.document,v=JSON.stringify([t,x]);if(v!==Fe){Ke(),Fe=v;let ee={sm:420,md:640,lg:900},we="size"in t&&!t.backdrop?",0 0 0 100vmax #16142566":"";D.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${se.background};color:${se.text};`+(t.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ee[t.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${we};`+(t.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),J=qn(D,{presentation:t,theme:r.theme,pages:r.pages},En),J.latch()}be(),D.setAttribute("aria-label",(Ie?.screen===e.screen?.content.document.name?Ie?.label:void 0)??de?.document?.name??e.screen?.content.document.name??"Funnel")}async function Xn(e){if(s||ie)return;if(oe.observe(),oe.pending){ue=e;return}if(pe&&(je()||["running","waiting"].includes(e.status))||(ue=e,Ee&&n.client.pendingCommand?.requestId!==Ee&&(O.hidden=!0,Ee=null),R=e.locale.startsWith("zh"),M.textContent=R?"回看":"History",q.textContent=w.active?R?"返回当前":"Return to current":R?"返回":"Back",vn(),Y.textContent=R?"重试":"Retry",Y.hidden=n.client.pendingCommand===null,ve(),hn!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(hn=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,Ce(n.onState,structuredClone(e))),s||ie))return;if((!e.pendingRequest||pe&&e.status==="closed")&&["closed","ineligible","failed"].includes(e.status)){G();return}if(e.stopped&&a()){G();return}if(e.stopped||n.client.configurationReady===!1){w.stop(),g(),me(),A?.finish("skipped"),c.hidden=!0,Oe();return}if(c.hidden=!1,w.active){Oe();return}if(e.status==="completed"&&h?.subscriptionUpgradeActive){Oe();return}let t=De(e),r=n.client.view;if(r&&r.revision>e.revision&&De(r)!==t)return;let v=!e.instruction&&!e.pendingRequest&&e.nodeType==="screen"&&["running","waiting"].includes(e.status);t!==ge&&(ge&&A?.finish("dismissed"),me(),ge=t,fe={...e.answers},Xe.reset());let ee=Ye(e);if(Qe===ee){c.hidden=!0;return}if(v&&!t){c.hidden=!0;let I=n.prepared?.state==="shown"?null:Ze(!0,e.locale);!s&&!ie&&We?.key!==ee&&(cn(),We={key:ee,timeout:setTimeout(()=>{let l=n.client.view;if(s||!I?.active&&n.prepared?.state!=="shown"||!l||Ye(l)!==ee)return;Qe=ee;let H=new Error("Funnel screen preparation timed out");I?.finish("error",H),g(),me(),K(H)},He)}),Oe();return}cn();let $=I=>{let l=n.client.view;return!s&&!ie&&!Re&&!I.aborted&&n.client.configurationReady!==!1&&!!l&&!l.stopped&&!["closed","ineligible","failed"].includes(l.status)&&(De(l)===t||l.status==="completed"&&h?.subscriptionUpgradeActive===!0)},we=(I,l)=>{$(l)&&(Qe=t,A?.finish("error",I),me(),c.hidden=!0,K(I))};if(t||((e.instruction&&e.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(e.status))&&g(),en(e),e.instruction?.type!=="event"&&e.instruction?.type!=="open_url"&&A?.finish("skipped")),e.screen){Ge=void 0,g();let I=e.screen.content;if(!de){let W=e.screen.presentation.type!=="inline",C=Ze(W,e.locale);if(s||ie)return;let B=(Te=new AbortController).signal;en(e),_e=W?Un(D):rn(c,i),de=S(k,{mode:"live",closeActions:Array.from(new Set([...n.closeActions??[],...I.document.actions.filter(y=>y.type==="event"&&y.close).map(y=>y.id)])),onAuthoredClose(y){$(B)&&(Le=y,ve())},rendererUrl:n.client.webViewUrl,title:I.document.name,...W?{hostPresentation:()=>J?.type??e.screen.presentation.type}:{},onResize:y=>{Me=y,J?.responsive&&J.setContentHeight(y+U.getBoundingClientRect().height)},onAction(y,d={},ce={}){if(w.active||!$(B)||ne!==t)return;fe={...fe,...ce};let pn=e.screen?.inputs??[],Tn=Object.fromEntries(pn.filter(({variable:qe})=>Object.hasOwn(fe,qe)).map(({variable:qe})=>[qe,fe[qe]]));if(zn(pn,Tn).length){bn();return}Se(()=>n.client.submit({operation:"submit",...ke(),input:{type:"screen",output:y,answers:Tn,selection:d}}),!1,qe=>Mn(qe,pn))},onAnswers:y=>{w.active||!$(B)||ne!==t||(fe={...fe,...y})},onCustomerDataIntent:y=>{w.active||!$(B)||ne!==t||Xe.intent(y).catch(K)},onEscape:()=>{!$(B)||ne!==t||w.active||re||V||he()},onError:y=>{let d=new Error(y);ne===t?K(d):we(d,B)},onRendered:y=>{if(!(!$(B)||ne===t))try{C.present(d=>{_e?.(),_e=void 0,y&&(Ie={screen:I.document.name,label:y},D.setAttribute("aria-label",y)),W&&(D.showModal(),P=!1,J?.responsive&&D.focus({preventScroll:!0}),!d&&n.loading!=="host"&&Hn(D,J?.type??e.screen.presentation.type,J?.responsive)),ne=t,Pe=W,ve()}),$(B)&&Ve.report(t)}catch(d){we(d,B)}}}),En()}let l={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:fe,values:e.screen.values}},H=JSON.stringify([I,e.locale,l.parameters,e.screen.inputs,e.screen.values]);if(H!==ze)de.update(I.document,e.locale,l),ze=H,on=JSON.stringify(l.capabilities),Be=JSON.stringify(l.customerData);else{let W=JSON.stringify(l.capabilities);W!==on&&(de.updateCapabilities(l.capabilities),on=W),JSON.stringify(l.customerData)!==Be&&(de.updateCustomerData(l.customerData),Be=JSON.stringify(l.customerData))}let Q=de;if(Q)try{await(A?.wait(Q.ready)??Q.ready)}catch(W){Te&&we(W,Te.signal)}}else if(e.paywall&&!h){let I=e.paywall.resolution,l="document"in I?I.document:null,H=p,Q=n.mountPaywallControls,W=null,C=(Te=new AbortController).signal,B={loading:"host",signal:C,...Q&&{mountControls:d=>Q(d,e)},canInteract:()=>$(C)&&!w.active&&!re&&!V,beforeAction:async()=>{Z++;try{await Pn(Ve.settled()),O.hidden=!0,Ee=null,Ae=!1,be()}finally{Z=Math.max(0,Z-1)}},start:async()=>{let d=await yn(n.client),ce=X;return X=void 0,d.view&&ce?.(d.view),d},onObservationChange:Oe,onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resumeCheckout:n.resumeCheckout,allowNewPurchase:n.allowNewPurchase,checkoutNavigation:n.checkoutNavigation,terminateCheckout:n.terminateCheckout,beforeCheckoutReplacement:n.beforeCheckoutReplacement,purchaseConfirmation:n.purchaseConfirmation,confirmOnHostedCheckout:n.confirmOnHostedCheckout,resolveOfferId:n.resolveOfferId,prepareSubscriptionChange:n.prepareSubscriptionChange,resolveSubscriptionChange:n.resolveSubscriptionChange,claimCoupon:n.claimCoupon,onEvent:n.onEvent,onOpenUrl:d=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:d,openIn:"same_window"}):o.defaultView?.location.assign(d),onAction:async d=>{if(w.active)return;let ce=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:d,answers:{}}});await ae(n.client.view??ce.run)},onError:d=>{ne===t?K(d):we(d,C)}},y={quoteError:d=>Ce(n.onError,d),present(d){$(C)&&(W?.present(ce=>{d(ce),ne=t,Pe=y.retainedDialog?.dialog.open??!!k.querySelector("dialog[open]"),Pe&&(P=!1),ve()}),$(C)&&Ve.report(t))},async closeAction(d){s||w.active||await oe.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:d,answers:{}}})},async dismiss(){if(s||C.aborted||w.active||re||V||!pe&&!$(C))return;pe=!0;let d=n.client.view;if(d?.status==="completed"&&h?.subscriptionUpgradeActive){Ue.add(`complete:${d.id}`),Ce(n.onComplete,structuredClone(d)),G();return}if((n.resumeCheckout||n.terminateCheckout)&&et()){ue=n.client.view,G();return}await he()}};if(H&&Q)g();else if(H){let d=await H.adopt(e,{options:B,handoff:y,start:()=>yn(n.client)});d&&$(C)&&!s?(en(e),h=d,Ne={runId:e.id,receiptId:e.paywall.receiptId},A?.active&&A.present(()=>{}),ne=t,Pe=H.modal,Pe&&(P=!1),ve(),Ve.report(t),w.active&&h.setSuspended(!0)):(d?.destroy(),g(),X=ce=>p?.remember(ce))}if(s||ie)return;if(!h){if(W=Ze(!0,e.locale,l),s||ie)return;(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.loading==="host"&&Ge?.ownerDocument===o&&(y.hostPaywallTarget=Ge),Ge=void 0,en(e);let d=await le(k,B,y).catch(ce=>(we(ce,C),null));!$(C)&&!(pe&&!s&&!C.aborted)?d?.host?.destroy():d&&(h=d.host,h&&(Ne={runId:e.id,receiptId:e.paywall.receiptId}),h?.setSuspended(w.active))}}if(s||ie)return;ve();let m=e.instruction;if(m&&(m.type==="open_url"||m.type==="event")&&!Ue.has(m.receiptId)){let I=o.createElement("button");I.type="button",I.style.cssText=T.primary,$e(I,()=>T.focus),k.style.cssText=T.stage,I.textContent=m.type==="open_url"?`${R?"前往":"Continue to"} ${new URL(m.url).host}`:R?"继续":"Continue",I.onclick=()=>{let l=ke(),H=m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="new_window"?Yn(m.url):null;Se(async()=>{let Q="success";if(m.type==="open_url")if(n.onOpenUrl)try{Q=await n.onOpenUrl({receiptId:m.receiptId,url:m.url,openIn:m.openIn})===!1?"failed":"opened"}catch(C){Ce(n.onError,C),Q="failed"}else Q=m.openIn==="new_window"&&!H?"failed":"opened";if(m.type==="event"){if(!n.onEvent)throw new te("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(m.event)}if(s||n.client.view?.nodeId!==l.nodeId||n.client.view.visit!==l.visit)throw new te("PRECONDITION_FAILED","The client action visit changed");let W=await n.client.submit({operation:"submit",...l,input:{type:"client_action",receiptId:m.receiptId,outcome:Q}});return Ue.add(m.receiptId),m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="same_window"&&o.defaultView?.location.assign(m.url),W})},A?.active?A.present(()=>k.replaceChildren(I)):k.replaceChildren(I)}!e.pendingRequest&&e.status==="completed"&&!Ue.has(`complete:${e.id}`)&&(Ue.add(`complete:${e.id}`),Ce(n.onComplete,structuredClone(e))),Oe()}function Yn(e){let t=o.defaultView?.open(e,"_blank")??null;return t&&(t.opener=null),t}function ae(e){return ve(),an=an.catch(()=>{}).then(async()=>{try{await Xn(e)}catch(t){throw A?.active&&(Qe=Ye(e),A.finish("error",t),me(),c.hidden=!0),t}}),an}let Zn=n.client.subscribe(e=>{if(!In){if(e.stopped&&(Pe||a())&&!pe){ue=e,G();return}!pe&&(e.stopped||n.client.configurationReady===!1||ge&&ne!==ge&&(De(e)!==ge||["closed","ineligible","failed"].includes(e.status)))&&(me(),A?.finish("dismissed"),c.hidden=!0),ae(e).catch(K)}}),Kn=n.client.subscribeError?.(e=>{oe.pending||K(e)});function et(){let e=n.client.view,t=e?.paywall;return!!t?.operation&&!!e&&["running","waiting"].includes(e.status)&&Sn(fn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect}))}function he(e){if(Re)return Re;if(s||!e&&(re||V))return Promise.resolve();let t=!e&&je();return!t&&n.client.view&&!["running","waiting"].includes(n.client.view.status)?(ue=n.client.view,G(),Promise.resolve()):(Re=Se(async()=>{let r=t?await n.client.retry():await(e?n.client.submit.bind(n.client):oe.submit)({operation:"close",...e??ke()});return e&&Cn(r),r},!0).then(()=>{let r=n.client.view;r?.status==="closed"&&!je()&&(ue=r,G())}).finally(()=>{Re=null}),Re)}function G(){kn()}function kn(e){_?.destroy(),!s&&(s=!0,oe.destroy(),E(),g(),n.signal?.removeEventListener("abort",G),f?.removeEventListener("abort",G),A?.finish("dismissed"),ln.destroy(),Zn(),Kn?.(),me(e),Ke(),w.stop(),D.remove(),!e||!c.contains(e)?c.remove():(U.remove(),j.remove()),!e&&!P&&u(),Ce(n.onDismiss,ue?structuredClone(ue):null))}q.onclick=()=>{if(!q.disabled){if(w.active){w.exit();return}Se(()=>n.client.submit({operation:"back",...ke()}))}},M.onclick=()=>{w.open()},F.onclick=()=>{A?.active?A.dismiss():re||he()},Y.onclick=()=>{oe.pending?oe.retry().catch(()=>{}):je()?he():Se(()=>n.client.retry())},D.addEventListener("cancel",e=>{e.preventDefault(),A?.active?A.dismiss():re||he()}),n.signal?.addEventListener("abort",G,{once:!0}),f?.addEventListener("abort",G,{once:!0});let nn=!1;p&&(E=p.onClose(()=>{s||ie||(ie=!0,A?.finish("dismissed"),me(),c.hidden=!0,n.client.view?he().finally(G):nn=!0)}));let Fn={destroy:G,refresh:un,get recoveryPaywall(){if(h&&Ne)return{...Ne,view:h.currentResolution}},setPurchaseRecovery(e,t){return h?.setPurchaseRecovery(e,t),h!==null},retainPurchaseDialog(){let e=h?.retainPurchaseDialog();if(e)return h=null,kn(e.dialog),{dialog:e.dialog,release(){e.release(),c.remove(),P||u()}}},get recovery(){let e=dn();if(e)return e;if(!s&&!Z&&!pe&&!re&&h){let t=h.recovery;if(t.type!=="native")return t}return{type:"recover",operationId:n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??V?.operationId??null,requestId:n.client.pendingCommand?.requestId??null}},prepareFallback(){if(re)return re;let e=dn();if(e)return Promise.resolve(e);let t=n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??V?.operationId??null,r=()=>({type:"recover",operationId:t,requestId:n.client.pendingCommand?.requestId??null});if(n.client.hasDurableJournal!==!0){let m=h?.recovery;return Promise.resolve(m&&m.type!=="native"&&m.type!=="cancel"?m:r())}let v=(n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[])).some(m=>m.operation==="close");if(s&&!(v||V&&n.client.view?.status==="closed")||Z||Je||Re||w.active||!h&&!V&&!v)return Promise.resolve(r());let ee=h,$=(async()=>{try{if(!V&&v){let l=await n.client.retry();return await ae(n.client.view??l.run),r()}if(!V){let l=await ee.prepareFallback();if(l.type!=="native")return l;if(n.client.hasDurableJournal!==!0)return r();V=l}let m=n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[]);if(m.length){let l=m.find(Q=>Q.operation==="close");if(!l||!z||l.requestId!==z.requestId)return r();let H=await n.client.retry();Cn(H),await ae(n.client.view??H.run)}else{let l=n.client.view,H=l?.paywall;if(!l||!H||H.selectionGeneration===void 0||(H.quote?.operationId??null)!==V.operationId||V.operationId!==null&&H.canReselect!==!0)return r();let Q=H.selectionGeneration,W=await n.client.get();await ae(n.client.view??W.run);let C=n.client.view,B=C?.paywall;if(!C||!B||!["running","waiting"].includes(C.status)||C.stopped||C.id!==l.id||C.nodeId!==l.nodeId||C.visit!==l.visit||B.receiptId!==H.receiptId||B.selectionGeneration!==Q||(B.quote?.operationId??null)!==V.operationId||V.operationId!==null&&B.canReselect!==!0||n.client.pendingPurchase||(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0)))return r();let y=ke();z={runId:C.id,operationId:V.operationId,revision:y.revision,requestId:y.requestId,nodeId:C.nodeId,visit:C.visit,receiptId:B.receiptId,selectionGeneration:Q,acknowledged:!1},await he(y)}let I=dn();return I?(G(),I):r()}catch(m){return K(m),r()}})();re=$;let we=()=>{re===$&&(re=null)};return $.then(we,we),$},review:w.open,exitReview:w.exit,get unappliedDrafts(){return w.drafts}};try{let e=n.client.view;if(e)((n.client.viewAgeMs??gn)>=gn||e.instruction?.type==="evaluate_segment")&&(sn=un().finally(()=>{sn=null})),await ae(e);else{if(c.hidden=!0,s)throw new DOMException("Presentation cancelled","AbortError");let t=nn||n.prepared?.state==="shown"?null:Ze(n.client.view?.screen?.presentation.type!=="inline",n.client.view?.locale);if(s||ie&&!nn)throw new DOMException("Presentation cancelled","AbortError");let r=n.client.get(),v=await(t?t.wait(r,He):tt(r,He));if(In=!1,nn)return s||await he().finally(G),Fn;await ae(n.client.view??v.run)}}catch(e){throw A?.finish("error",e),G(),e}return Fn}function tt(i,b){let N;return Promise.race([i,new Promise((n,p)=>{N=setTimeout(()=>p(new Error("Presentation data timed out")),b)})]).finally(()=>clearTimeout(N))}function Ot(i,b,N){return nt(i,b,N)}export{nt as a,Ot as b};
@@ -1 +1 @@
1
- import{d as t}from"./chunk-PGLBFTRK.js";async function u(e,n){try{let{route:r}=await e.funnelRoute(n.funnelId),a=t(r,{customerId:n.customerId,parameters:n.parameters??{}});return{funnelId:n.funnelId,...a}}catch(r){return{funnelId:n.funnelId,type:"unavailable",reason:r?.code?.toLowerCase()??"error",path:[]}}}function l(e){switch(e.type){case"paywall":return null;case"screen":return`first_screen_${e.surface}`;case"external_page":return"first_screen_external_page";case"end":return`route_end_${e.outcome}`;case"unknown":return`route_unknown_${e.reason}`;case"unavailable":return e.reason.startsWith("route_")?e.reason:`route_${e.reason}`}}async function s(e,n){if(n.type!=="paywall")return null;try{let{document:r}=await e.paywall(n.paywallId,n.paywallVersionId);return{presentation:r.presentation,screen:r.screen,buttons:r.buttons}}catch{return null}}export{u as a,l as b,s as c};
1
+ import{d as t}from"./chunk-DCMA7W7N.js";async function u(e,n){try{let{route:r}=await e.funnelRoute(n.funnelId),a=t(r,{customerId:n.customerId,parameters:n.parameters??{}});return{funnelId:n.funnelId,...a}}catch(r){return{funnelId:n.funnelId,type:"unavailable",reason:r?.code?.toLowerCase()??"error",path:[]}}}function l(e){switch(e.type){case"paywall":return null;case"screen":return`first_screen_${e.surface}`;case"external_page":return"first_screen_external_page";case"end":return`route_end_${e.outcome}`;case"unknown":return`route_unknown_${e.reason}`;case"unavailable":return e.reason.startsWith("route_")?e.reason:`route_${e.reason}`}}async function s(e,n){if(n.type!=="paywall")return null;try{let{document:r}=await e.paywall(n.paywallId,n.paywallVersionId);return{presentation:r.presentation,screen:r.screen,buttons:r.buttons}}catch{return null}}export{u as a,l as b,s as c};
@@ -1 +1 @@
1
- import{a as s,b as c,c as u}from"./chunk-XCFAKO23.js";import{j as m,m as p}from"./chunk-RIEWU4MN.js";import{b as e}from"./chunk-PZTWDJHN.js";var y=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],i=e.enum(y);function x(t){let n=i.parse(t.toUpperCase());return["JPY","KRW","VND"].includes(n)?0:2}function I(t,n,r="en",f={}){let a=i.parse(n.toUpperCase());return new Intl.NumberFormat(r,{style:"currency",currency:a,...f}).format(t/10**x(a))}var l=e.enum(["stripe","apple","google","merchant"]),w=e.enum(["membership","credit_pack","lifetime"]),v=e.enum(["active","grace","suspended","inactive","revoked"]),z=e.strictObject({currency:e.string().regex(/^[A-Z]{3}$/),micros:e.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var d=e.object({provider:l,currency:i,intent:e.literal("subscription_change").optional()}).strict();var o=e.strictObject({internal_feature_id:e.uuid(),quantity:m.refine(t=>/[1-9]/.test(t)),properties:p,entityId:e.uuid().optional()}),B=e.strictObject({requirement:o,commerce:d.optional(),paywallId:e.uuid().optional()}),g=e.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),b=e.strictObject({productId:e.string().min(1),productVersionId:e.string().min(1),name:e.string().min(1).max(120),action:e.enum(["purchase","upgrade","addon","topup"]),membershipId:e.string().min(1).nullable(),featureQuantities:e.record(e.uuid(),e.number().int().min(0).max(1e4)).refine(t=>Object.keys(t).length<=100).optional(),currency:i,amountMinor:e.string().regex(/^(0|[1-9]\d{0,8})$/),interval:e.enum(["free","week","month","year","one_time"]),intervalCount:e.number().int().min(1).max(156)}),h=e.strictObject({subject:c,authority:e.enum(["longplay","merchant"]),observedAt:e.iso.datetime({offset:!0}),sourceRevision:e.string().min(1).max(128),requirementDigest:s});function S(t,n){return u({subject:c.parse(t),requirement:o.parse(n)})}var C=e.strictObject({internal_feature_id:e.string().min(1),name:e.string().min(1).max(120),kind:e.enum(["access","metered","credit"]),quantity:m,allowed:e.boolean(),observation:h.optional(),reason:g.nullable(),preview:e.strictObject({scenario:e.enum(["feature_flag","usage_limit"]),candidates:e.array(b).max(20)}).nullable()}).superRefine((t,n)=>{(t.allowed!==(t.reason===null)||t.allowed&&t.preview!==null||new Set(t.preview?.candidates.map(r=>r.productVersionId)).size!==(t.preview?.candidates.length??0)||t.preview?.candidates.some(r=>r.action==="upgrade"!=(r.membershipId!==null)))&&n.addIssue({code:"custom",message:"Invalid access recommendation"})}),T=e.strictObject({paywallId:e.uuid(),requirement:o}),U=e.strictObject({subject:c,requirement:o}),$=C.safeExtend({observation:h.extend({authority:e.literal("merchant")})});function F(t,n){let r=o.parse(t);return n.internal_feature_id===r.internal_feature_id&&n.quantity===r.quantity&&(!n.observation||n.observation.requirementDigest===S(n.observation.subject,r))}export{i as a,x as b,I as c,w as d,d as e,o as f,B as g,b as h,S as i,C as j,U as k,$ as l,F as m};
1
+ import{a as s,b as c,c as u}from"./chunk-OKPWZZZW.js";import{j as m,m as p}from"./chunk-XIBJF5E6.js";import{b as e}from"./chunk-YLH3AYCK.js";var y=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],i=e.enum(y);function x(t){let n=i.parse(t.toUpperCase());return["JPY","KRW","VND"].includes(n)?0:2}function I(t,n,r="en",f={}){let a=i.parse(n.toUpperCase());return new Intl.NumberFormat(r,{style:"currency",currency:a,...f}).format(t/10**x(a))}var l=e.enum(["stripe","apple","google","merchant"]),w=e.enum(["membership","credit_pack","lifetime"]),v=e.enum(["active","grace","suspended","inactive","revoked"]),z=e.strictObject({currency:e.string().regex(/^[A-Z]{3}$/),micros:e.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var d=e.object({provider:l,currency:i,intent:e.literal("subscription_change").optional()}).strict();var o=e.strictObject({internal_feature_id:e.uuid(),quantity:m.refine(t=>/[1-9]/.test(t)),properties:p,entityId:e.uuid().optional()}),B=e.strictObject({requirement:o,commerce:d.optional(),paywallId:e.uuid().optional()}),g=e.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),b=e.strictObject({productId:e.string().min(1),productVersionId:e.string().min(1),name:e.string().min(1).max(120),action:e.enum(["purchase","upgrade","addon","topup"]),membershipId:e.string().min(1).nullable(),featureQuantities:e.record(e.uuid(),e.number().int().min(0).max(1e4)).refine(t=>Object.keys(t).length<=100).optional(),currency:i,amountMinor:e.string().regex(/^(0|[1-9]\d{0,8})$/),interval:e.enum(["free","week","month","year","one_time"]),intervalCount:e.number().int().min(1).max(156)}),h=e.strictObject({subject:c,authority:e.enum(["longplay","merchant"]),observedAt:e.iso.datetime({offset:!0}),sourceRevision:e.string().min(1).max(128),requirementDigest:s});function S(t,n){return u({subject:c.parse(t),requirement:o.parse(n)})}var C=e.strictObject({internal_feature_id:e.string().min(1),name:e.string().min(1).max(120),kind:e.enum(["access","metered","credit"]),quantity:m,allowed:e.boolean(),observation:h.optional(),reason:g.nullable(),preview:e.strictObject({scenario:e.enum(["feature_flag","usage_limit"]),candidates:e.array(b).max(20)}).nullable()}).superRefine((t,n)=>{(t.allowed!==(t.reason===null)||t.allowed&&t.preview!==null||new Set(t.preview?.candidates.map(r=>r.productVersionId)).size!==(t.preview?.candidates.length??0)||t.preview?.candidates.some(r=>r.action==="upgrade"!=(r.membershipId!==null)))&&n.addIssue({code:"custom",message:"Invalid access recommendation"})}),T=e.strictObject({paywallId:e.uuid(),requirement:o}),U=e.strictObject({subject:c,requirement:o}),$=C.safeExtend({observation:h.extend({authority:e.literal("merchant")})});function F(t,n){let r=o.parse(t);return n.internal_feature_id===r.internal_feature_id&&n.quantity===r.quantity&&(!n.observation||n.observation.requirementDigest===S(n.observation.subject,r))}export{i as a,x as b,I as c,w as d,d as e,o as f,B as g,b as h,S as i,C as j,U as k,$ as l,F as m};
@@ -1 +1 @@
1
- import{a as T,b as se}from"./chunk-77O2O552.js";import{b as re,h as ae,j as ce}from"./chunk-OMJSBFMI.js";import{E as M,a as J}from"./chunk-G2CBJZEI.js";import{a as b,b as f,c as m}from"./chunk-VNYUL3PV.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-4SI4SQ3C.js";import{a as oe,b as j}from"./chunk-C3HZCZVJ.js";import{b as W,j as X}from"./chunk-32AEJKJW.js";import{n as $}from"./chunk-EKUDMQXT.js";import{b as ie}from"./chunk-4LQX4K5Q.js";import{a as B}from"./chunk-HUYKZH3H.js";import{a as s}from"./chunk-TK3WOD2O.js";import{h as Q}from"./chunk-RIEWU4MN.js";import{b as K}from"./chunk-PZTWDJHN.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-6RQ33K66.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-6RQ33K66.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-6RQ33K66.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-6RQ33K66.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-74T76RE4.js";import{b as re,h as ae,j as ce}from"./chunk-M6MXJHJ5.js";import{E as M,a as J}from"./chunk-RHILCVPZ.js";import{a as b,b as f,c as m}from"./chunk-YUL23NAW.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-SAPICYY3.js";import{a as oe,b as j}from"./chunk-E3FUZSTM.js";import{b as W,j as X}from"./chunk-FUP5JVDE.js";import{n as $}from"./chunk-AD35L6BX.js";import{b as ie}from"./chunk-7D5462NE.js";import{a as B}from"./chunk-7EENIOSJ.js";import{a as s}from"./chunk-46USIMCJ.js";import{h as Q}from"./chunk-XIBJF5E6.js";import{b as K}from"./chunk-YLH3AYCK.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-6ORJSGYH.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-6ORJSGYH.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-6ORJSGYH.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-6ORJSGYH.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{g as p}from"./chunk-RIEWU4MN.js";import{b as r}from"./chunk-PZTWDJHN.js";import{a as i,b as s}from"./chunk-CILM5XMH.js";var b=r.string().regex(/^[a-f0-9]{64}$/),j=r.strictObject({scope:r.strictObject({projectId:r.uuid(),environmentId:r.uuid(),environment:p}),customerId:r.uuid()});function l(u){let n=e=>{if(Array.isArray(e))return`[${e.map(n).join(",")}]`;if(e!==null&&typeof e=="object"){let c=Object.getPrototypeOf(e);if(c!==Object.prototype&&c!==null)throw new TypeError("Commerce protocol digests require JSON objects");return`{${Object.entries(e).filter(([,o])=>o!==void 0).sort(([o],[t])=>o<t?-1:o>t?1:0).map(([o,t])=>`${JSON.stringify(o)}:${n(t)}`).join(",")}}`}if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return JSON.stringify(e);throw new TypeError("Commerce protocol digests require JSON values")};return i(s(new TextEncoder().encode(n(u))))}export{b as a,j as b,l as c};
1
+ import{g as p}from"./chunk-XIBJF5E6.js";import{b as r}from"./chunk-YLH3AYCK.js";import{a as i,b as s}from"./chunk-CILM5XMH.js";var b=r.string().regex(/^[a-f0-9]{64}$/),j=r.strictObject({scope:r.strictObject({projectId:r.uuid(),environmentId:r.uuid(),environment:p}),customerId:r.uuid()});function l(u){let n=e=>{if(Array.isArray(e))return`[${e.map(n).join(",")}]`;if(e!==null&&typeof e=="object"){let c=Object.getPrototypeOf(e);if(c!==Object.prototype&&c!==null)throw new TypeError("Commerce protocol digests require JSON objects");return`{${Object.entries(e).filter(([,o])=>o!==void 0).sort(([o],[t])=>o<t?-1:o>t?1:0).map(([o,t])=>`${JSON.stringify(o)}:${n(t)}`).join(",")}}`}if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return JSON.stringify(e);throw new TypeError("Commerce protocol digests require JSON values")};return i(s(new TextEncoder().encode(n(u))))}export{b as a,j as b,l as c};
@@ -1 +1 @@
1
- import{b as Ve}from"./chunk-77O2O552.js";import{a as $}from"./chunk-PJHTN5NJ.js";import{D as K,F as ze,c as Ue,e as z,j as Te,u as He,v as Le,x as Me,z as Ge}from"./chunk-G2CBJZEI.js";import{a as Fe,b as Ne,c as je}from"./chunk-VNYUL3PV.js";import{a as se}from"./chunk-NDNHTG5B.js";import{i as ue}from"./chunk-5LNX7MHO.js";import{K as G}from"./chunk-EKUDMQXT.js";import{A as ae,B as ie,C as J,E as Ae}from"./chunk-EB7MIZ4T.js";import{x as ye}from"./chunk-S5RM3VO6.js";import{b as De}from"./chunk-4LQX4K5Q.js";import{a as l}from"./chunk-TK3WOD2O.js";import{h as oe}from"./chunk-RIEWU4MN.js";import{a as xe}from"./chunk-5MRSFLQA.js";import{b as r}from"./chunk-PZTWDJHN.js";import{a as ge}from"./chunk-DSPLGTQI.js";var v=G.options,it=r.discriminatedUnion("operation",[v[1].omit({customerToken:!0}),v[2].omit({customerToken:!0}),v[3].omit({customerToken:!0}),v[4].omit({customerToken:!0}),v[5].omit({customerToken:!0}),v[6].omit({customerToken:!0}),v[7].omit({customerToken:!0}),v[8].omit({customerToken:!0}),Te.omit({customerToken:!0})]),Pe=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),It=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("find_purchase")}),r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume","start"]),start:r.strictObject({requestId:v[0].shape.requestId,funnelId:v[0].shape.funnelId,locale:v[0].shape.locale,parameters:v[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe,includePaywallVersion:r.literal(!0).optional()}),r.strictObject({operation:r.literal("terminate_checkout"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[v[3].omit({customerToken:!0}),v[4].omit({customerToken:!0}),v[5].omit({customerToken:!0}),v[6].omit({customerToken:!0}),v[7].omit({customerToken:!0})]).optional()}).refine(i=>!i.command||i.requestId===i.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:it})]),ce=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:z.shape.run.shape.status}),H={scope:oe,customerId:r.uuid()},Qe=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...H,outcome:r.literal("resolved"),target:ce,view:z.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((i,d)=>{i.outcome==="resolved"&&(i.access.type==="customer"!=(i.view!==null)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Be=r.strictObject({...H,target:ce,view:z.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:z.shape.purchase.unwrap().nullable()}).superRefine((i,d)=>{let f=i.settlement;(f.acceptance==="accepted"!=(f.receiptPhase!==null)||f.acceptance==="accepted"&&f.basis!=="receipt"||f.acceptance==="unknown"&&(f.state!=="unknown"||f.basis!=="none")||f.acceptance!=="accepted"&&(f.operationId!==null||f.receiptId!==null)||f.acceptance==="not_accepted"&&(f.state!=="settled"||!["run_terminal","position_advanced"].includes(f.basis))||i.purchase&&(i.purchase.receiptId!==f.receiptId||i.purchase.operation&&i.purchase.operation.operationId!==f.operationId||i.purchase.quote&&i.purchase.quote.operationId!==f.operationId)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ye=r.strictObject({...H,target:ce,purchase:z.shape.purchase.unwrap(),paywallVersionId:r.uuid().optional()}).superRefine((i,d)=>{(!i.purchase.operation||typeof i.purchase.canReselect!="boolean"||i.purchase.quote&&i.purchase.quote.operationId!==i.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),Je=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("none")}),r.strictObject({...H,outcome:r.literal("blocked")}),r.strictObject({...H,outcome:r.literal("found"),target:ce,start:r.strictObject({locale:v[0].shape.locale,parameters:v[0].shape.parameters}),purchase:Pe})]);var st=G.options[0].refine(i=>!i.customer&&!i.customerData),ut=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),Ke=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:oe,customerId:r.uuid(),sessionId:r.uuid(),start:st,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:Ue.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ut).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:He.nullable()})});function $e(i){return Me({...i,namespace:"purchases",identity:[i.scope.projectId,i.scope.environment,i.customerId]})}function We(i){let d=new URL(i.baseUrl??xe).href,f=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function R(){i.assertCurrent();try{let C=await i.storage.read();if(i.assertCurrent(),!Number.isSafeInteger(C.revision)||C.revision<0)throw f();let c=C.entry===null?null:Ke.parse(C.entry);if(c&&(c.baseUrl!==d||c.customerId!==i.customerId||c.scope.projectId!==i.scope.projectId||c.scope.environment!==i.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(c?.journal.entry&&(c.journal.entry.scope.projectId!==c.scope.projectId||c.journal.entry.scope.environment!==c.scope.environment||c.journal.entry.funnelId!==c.start.funnelId||c.journal.entry.runId!==c.run?.id||c.journal.entry.versionId!==c.run?.versionId)||c?.operationCommand&&!c.purchases.some(q=>q.operationId===c.operationCommand?.operationId))throw f();return{revision:C.revision,entry:c}}catch(C){throw C instanceof l?C:f()}}async function W(C){for(let c=0;c<8;c++){let q=await R(),O=C(structuredClone(q.entry));if(JSON.stringify(O)===JSON.stringify(q.entry))return O;O&&Ke.parse(O),i.assertCurrent();let j;try{j=await i.storage.write(q.revision,O)}catch{throw f()}if(i.assertCurrent(),j!==null){if(!Number.isSafeInteger(j)||j<=q.revision)throw f();return O}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:R,update:W,baseUrl:d}}var ct=5*6e4,lt=2e3;function dt(i,d){let f=i.purchases.find(R=>R.type==="checkout");if(!i.actions.includes("continue_checkout")||f?.type!=="checkout"||d!==void 0&&f.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return f.checkoutUrl}function zt(i){let d={...i,scope:{...i.scope},executionPolicy:structuredClone(i.executionPolicy)},f=d.session.snapshot();if(!f)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:R,sessionId:W}=f,C=!1,c=null,q,O,j=null,F=!1,U,X,Z,E={mode:"idle",status:"idle",actions:["start"],purchases:[]},g=new Map,ve=new Map,T=new Map,le=new AbortController,ee=new Set,Q=De(d),te=Ve(Q.request);function B(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function P(){if(C||d.session.snapshot()?.customerId!==R)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let w=We({...d,customerId:R,assertCurrent:P,storage:d.storage??$e({baseUrl:d.baseUrl,scope:d.scope,customerId:R})}),Xe,Re=()=>Xe??=import("./funnel-paywall-copies-U3JIYQJ5.js").then(({createPaywallCopies:e})=>e({baseUrl:d.baseUrl,scope:d.scope,customerId:R})),Ze={read:async e=>(await Re()).read(e),write:async(e,t)=>(await Re()).write(e,t)},et=d.session.subscribeIdentity(Se);function Se(){C||(C=!0,clearTimeout(Z),le.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),et(),c?.reset(),c=null,j=null,Q.dispose(),ee.clear(),g.clear(),T.clear())}function S(e){P();let t=JSON.stringify(e)!==JSON.stringify(E);E=e,clearTimeout(Z),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Z=setTimeout(()=>{M().catch(()=>{})},5e3)),t&&ge(d.onRecovery,structuredClone(e));for(let n of t?ee:[]){if(C)break;ge(n,structuredClone(e))}return structuredClone(e)}function y(e){if(P(),!e||e.start.requestId!==O)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function _(e){let t=[...e.purchases],n=e.journal.entry?.purchase;return n&&!t.some(o=>o.operationId===n.operationId)&&t.push({receiptId:n.receiptId,operationId:n.operationId,terminal:null}),t}function x(e){let t=_(e),n=F&&t.length>0&&t.every(o=>o.terminal==="native"&&D(g.get(o.operationId))==="native")&&t.some(o=>{let s=g.get(o.operationId);return!!s&&J(s)&&T.get(o.operationId)===!0});return e.run&&(n||!["running","waiting"].includes(e.run.status))&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&t.every(o=>o.terminal!==null)}function A(e,t){let n=e.journal.entry?.command??e.journal.entry?.closeCommand,o=_(e).map(I=>{let k=g.get(I.operationId);return I.terminal&&!k?{type:I.terminal,operationId:I.operationId}:se({quote:k?.quote??null,operation:k??null,requestId:n?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(I.operationId)===!0})}),s=o.filter(I=>!["complete","native"].includes(I.type)),u=s[0],a=s.length===1&&u?.operationId?g.get(u.operationId):void 0;if(a&&(u?.type==="checkout"||u?.type==="cancel"))try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote)}catch(I){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:B(I)}}let m;if(t==="operation"&&!n&&u?.type==="cancel"&&a?.quote&&!a.problem&&!a.confirmedAt)try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote),Date.parse(a.quote.expiresAt)>Date.now()&&(m={operationId:a.operationId,quote:a.quote})}catch{}let p=o.length>0&&s.length===0,h=x(e)||t==="operation"&&p&&!n&&!e.operationCommand?"complete":u?.type==="checkout"?"checkout":u?.type==="fulfillment"?"fulfillment":u?.type==="recording"?"recording":n||e.operationCommand||u&&u.type!=="cancel"||t==="operation"&&!m?"waiting_result":"ready";return{mode:t,status:h,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...x(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...s.length===1&&u?.type==="checkout"?["continue_checkout"]:[]]}}function D(e){let t=se({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function de(e){if(!e.operation)return;let t=ae.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==R)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let n=ue(g.get(t.operationId)??null,t);g.set(t.operationId,n),n===t&&T.set(t.operationId,e.canReselect===!0)}async function tt(e){P();for(let n of[e.purchase,e.run.paywall])n&&de(n);let t=await w.update(n=>{if(y(n),n.run&&(n.run.id!==e.run.id||n.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=_(n);for(let s of[e.purchase,e.run.paywall]){let u=s?.operation?.operationId??s?.quote?.operationId;if(!s||!u)continue;let a=o.find(p=>p.operationId===u);if(a&&a.receiptId!==s.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=D(g.get(u));a?a.terminal??=m:o.push({receiptId:s.receiptId,operationId:u,terminal:m})}return{...n,purchases:o,run:n.run&&(n.run.revision>e.run.revision||!["running","waiting"].includes(n.run.status)&&["running","waiting"].includes(e.run.status))?n.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});y(t),t.run&&!["running","waiting"].includes(t.run.status)&&_(t).some(n=>!n.terminal)&&(t=await L(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(n=>!!n)))),y(t),S(A(t,"run"))}function nt(){return{async read(){let{entry:e}=await w.read();return y(e),structuredClone(e.journal)},async write(e,t){let n=null;return await w.update(o=>{if(y(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return n=null,o.journal.revision!==e?o:(n=e+1,{...o,journal:{revision:n,entry:t}})}),n}}}async function L(e,t=!1,n=new Set){y(e);let o=_(e);for(let u of o){if(u.terminal)continue;let a=n.has(u.operationId)?g.get(u.operationId):void 0;if(a??=await V(e,u),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(a.merchantExecution&&a.merchantExecution.customerId!==R)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&se({quote:a.quote??null,operation:a,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let m=J(a)?await te.update({operationId:u.operationId,intent:"cancel"}):await te.attach({operationId:u.operationId,intent:"cancel"});if(a=ae.parse(m.operation),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");a=await V(e,u)}g.set(u.operationId,ue(g.get(u.operationId)??null,a))}let s=await w.update(u=>{y(u);let a=u.operationCommand&&g.get(u.operationCommand.operationId);return{...u,...a&&(a.confirmedAt||a.merchantExecution||!Ae(a))?{operationCommand:void 0}:{},purchases:_(u).map(m=>({...m,terminal:m.terminal??D(g.get(m.operationId))}))}});return y(s),s}async function Y(e){P();let t=await Q.request("funnels",e);return P(),t}async function rt(e){try{return await Y(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return Y({...e,intent:"resume"})}}async function ot(){let e=$(Je,await Y({operation:"find_purchase"}));if(e.customerId!==R||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:n}=e;return await w.update(o=>o&&!x(o)?o:{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:R,sessionId:W,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...n,terminal:null}],journal:{revision:0,entry:null}}),"found"}let ne;function pe(e){let t=ne;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<ct))return t.job;let n={at:Date.now(),job:ot().then(o=>(n.outcome=o,n.at=Date.now(),o),o=>{throw ne===n&&(ne=void 0),o})};return ne=n,n.job}async function V(e,t,n="recover_purchase",o=!1){let s=$(Ye,await Y({operation:n,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId},...o?{includePaywallVersion:!0}:{}}));if(me(e,s),s.purchase.receiptId!==t.receiptId||s.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return de(s.purchase),o&&s.paywallVersionId&&ve.set(t.operationId,s.paywallVersionId),g.get(t.operationId)}async function Ce(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let n=$(Be,await Y({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(me(e,n),n.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");n.purchase&&de(n.purchase);let o=await w.update(s=>{y(s);let u=_(s),{receiptId:a,operationId:m}=n.settlement;if(a&&m){let h=u.find(I=>I.operationId===m);if(h&&h.receiptId!==a)throw new l("INVALID_RESPONSE","Original Receipt changed");h||u.push({receiptId:a,operationId:m,terminal:D(g.get(m))})}let p=n.settlement.state==="settled"?Le(s.journal.entry,t.requestId):s.journal.entry;return{...s,purchases:u,journal:p===s.journal.entry?s.journal:{revision:s.journal.revision+1,entry:p}}});y(o),e=o}return e}function me(e,t){if(t.customerId!==R||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function fe(e,t){if(y(e),e.run&&(e=await Ce(e)),!_(e).length&&x(e))return S(A(e,"operation"));if(!_(e).length)return S({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(t)});F=!0;let n=_(e);if(e.run&&["running","waiting"].includes(e.run.status)&&n.every(s=>s.terminal==="native"))for(let s of n)D(g.get(s.operationId))!=="native"&&await V(e,s);let o=await L(e);return S(A(o,"operation"))}async function re(e,t=!1,n=!0,o=!1){if(O=e.start.requestId,j=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!c){let s=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await rt(s)}catch(h){if(!e.run&&h instanceof l&&(h.status===void 0||h.status>=500))return S({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:E.purchases,error:B(h)});throw h}let a=$(Qe,u);if(a.customerId!==R||a.scope.projectId!==d.scope.projectId||a.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(a.outcome==="unknown")return S({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:E.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});me(e,a);let m=await w.update(h=>(y(h),{...h,run:{id:a.target.runId,versionId:a.target.versionId,status:a.target.status,revision:a.view?.revision??h.run?.revision??0,runExpiresAt:a.target.runExpiresAt}}));if(y(m),e=m,a.access.type==="operation_only")return fe(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ce(e);let p=a.view;if(p.locale!==e.start.locale||!Ge(p.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");c=ze({...d,customerRun:{runId:a.target.runId,customerId:R,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(h=>d.executionPolicy.allowed.includes(h))},funnelCommandStorage:nt(),onAcceptedResponse:tt},{scope:a.scope,run:p})}try{let s=o&&q?.controller===c?performance.now()-q.at:1/0;(s>=lt||c.pendingCommands?.length||(c.viewAgeMs??0)<s)&&(q=void 0,await c.get(),q={controller:c,at:performance.now()}),c.view?.pendingRequest?.requestId===e.start.requestId&&!c.pendingCommands?.length&&await c.resume(c.view.pendingRequest.requestId);for(let a of c.pendingCommands??[])a.operation!=="close"&&await c.settle?.(a.requestId);c.pendingCommands?.length&&await c.retry(),P();let u=(await w.read()).entry;return y(u),S(A(u,"run"))}catch(s){if(P(),n&&s instanceof l&&(s.status===401||s.status===409&&s.reason==="STATE_CHANGED")){c.reset(),c=null;let u=(await w.read()).entry;return y(u),re(u,!1,!1,!1)}throw s}}function N(e,t="read",n){if(P(),U)return t==="read"||t===X?U:U.then(()=>N(e,t,n),()=>N(e,t,n));clearTimeout(Z);let o=e().catch(s=>{throw!C&&!n?.(s)&&S({mode:"blocked",status:"blocked",actions:["refresh"],purchases:E.purchases,error:B(s)}),s});return U=o,X=t,o.then(()=>{U===o&&(U=void 0,X=void 0)},()=>{U===o&&(U=void 0,X=void 0)}),o}function M(e){let t=e?.reuseRecentRead===!0;return N(async()=>{let{entry:n}=await w.read();if(!n||x(n)){if(await pe(!1)==="blocked")return Ee();({entry:n}=await w.read())}return n?(O&&n.start.requestId!==O&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F&&O===n.start.requestId?fe(n,E.error):re(n,!1,!0,t)):S({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function Ee(){return S({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function be(){let e=await M();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:N(async()=>{let t=(await w.read()).entry;if(y(t),!F){if(!c?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=c.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(J(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return S(A(t,"run"));if(c.pendingCommands?.length)await c.retry();else{let I=c.view;await c.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:I.nodeId,visit:I.visit,revision:I.revision,input:{type:"paywall_confirm",operationId:I.paywall.quote.operationId,...I.paywall.quote.merchantTerms?{merchantConfirmation:ye(I.paywall.quote.merchantTerms)}:{}}})}let h=(await w.read()).entry;return y(h),S(A(h,"run"))}let n=t.operationCommand?.operationId??E.confirmation?.operationId,o=n&&g.get(n);if(!n||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");K({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await w.update(p=>{if(y(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==n)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:n,intent:"confirm"}}});let s={operationId:n,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:ye(o.quote.merchantTerms)}:{}},u=J(o)?await te.update(s):await te.attach(s),a=ae.parse(u.operation);if(P(),u.operation.operationId!==n)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");g.set(n,ue(o,a));let m=(await w.read()).entry;return y(m),S(A(await L(m,!1,new Set([n])),"operation"))},"confirm")}function at(e){let t=e?.quote;return t&&ie(t)&&t.timing==="immediate"&&t.execution.provider==="merchant"&&(e.confirmedAt||e.merchantExecution)?t:null}function Oe(){if(E.mode!=="operation"||E.status==="blocked")return null;let e=E.purchases.filter(({type:n})=>n!=="complete"&&n!=="native"),t=e.length===1&&e[0]?.operationId;return t?at(g.get(t)):null}async function _e(){P();let{entry:e}=await w.read();return e?x(e)?"finished":"pending":"none"}return{get controller(){return c},get recovery(){return structuredClone(E)},get attempt(){return P(),structuredClone(j)},get identitySignal(){return le.signal},get customerId(){return R},retained:_e,get paywallCopies(){return Ze},async findPurchase(){let e=await _e();if(e==="pending")return e;let t=await pe(!0);return P(),t==="none"?e:t},async readPaywall(e){P();let t=Fe(e),[n,{readPaywallContent:o},{validateResourceCheck:s}]=await Promise.all([Ne(Q.request,"resolvePaywall"),import("./paywall-content-KYHTDMWU.js"),import("./check-response-K56UEZ6E.js")]);P();let u=n.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),a=await je(Q.request,n,u);s(u,a.paywall.check,a.scope);let m=await o(d,a.paywall);if(P(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},get canRestoreUpgradePaywall(){return Oe()!==null},recoverUpgradePaywall(){let e=Oe();return e?this.recoverPurchasePaywall(void 0,e.operationId):Promise.resolve(null)},async recoverPurchasePaywall(e,t){if(E.mode!=="operation"||E.status==="blocked")return null;let{entry:n}=await w.read();if(!n?.run)return null;y(n);let o=_(n),s=o.filter(b=>!b.terminal),u=o.filter(b=>b.terminal==="complete"),a=s.length===1?s[0]:s.length?void 0:u.find(b=>e&&e.runId===n.run?.id&&b.receiptId===e.receiptId)??(u.length===1?u[0]:void 0);if(!a||t&&a.operationId!==t)return null;let m=e?.runId===n.run.id&&e.receiptId===a.receiptId?e.view:void 0,p;try{p=await V(n,a,"recover_purchase",!0)}catch(b){if(!(b instanceof l&&b.status===400&&b.code==="INVALID_REQUEST"))throw b;if(!m)return null;p=await V(n,a)}let h=p.quote;if(!h||ie(h)&&(h.timing!=="immediate"||h.execution.provider!=="merchant")||!(p.confirmedAt||p.merchantExecution||p.checkoutUrl||D(p)==="complete"))return null;D(p)!=="complete"&&K({allowed:n.allowed.filter(b=>d.executionPolicy.allowed.includes(b))},h);let I=ve.get(a.operationId),k=n.start.parameters?.commerce,ke=n.start.locale??"en",he=m;if(I){if(typeof k!="object"||!k||!("provider"in k)||typeof k.provider!="string"||!("currency"in k)||typeof k.currency!="string")return null;he=await this.readPaywall({paywallVersionId:I,locale:ke,commerce:{provider:k.provider,currency:k.currency,...ie(h)?{intent:"subscription_change"}:{}}})}if(!he)return null;P();let qe=he,we=!1,Ie=async()=>{throw new l("PURCHASE_PENDING","Only the original purchase can be recovered")};return{signal:le.signal,view:qe,quote:h,locale:ke,get operation(){return p},get canReselect(){return T.get(a.operationId)===!0},async refresh(){return qe},preview:Ie,confirm:Ie,cancel:Ie,async read(){if(we)throw new DOMException("Purchase view closed","AbortError");p=await V(n,a);let b=await L(n,!1,new Set([a.operationId]));return we||S(A(b,"operation")),structuredClone(p)},destroy(){we=!0}}},start(e){let t=G.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return N(async()=>{let n=(await w.read()).entry;if((!n||x(n))&&await pe(!0)==="blocked")return Ee();let o=await w.update(s=>{if(s&&!x(s)){if(s.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return s}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:R,sessionId:W,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return O!==o.start.requestId&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F?fe(o,E.error):re(o,!0,!0,!0)},`start:${t.funnelId}`)},refresh:M,confirm:be,retry:()=>F?be():N(async()=>{let{entry:e}=await w.read();return e?re(e,!0):S({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return c?.view?N(async()=>{if(!c?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(c.pendingCommands?.find(n=>n.operation==="close"))await c.retry();else if(["running","waiting"].includes(c.view.status)){let n=c.view;await c.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision})}let t=(await w.read()).entry;return y(t),S(A(t,"run"))},"close"):M()},async continueCheckout(e,t){let n=t?await N(async()=>{let{entry:o}=await w.read();if(y(o),!o.run||!_(o).some(u=>u.operationId===t&&!u.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let s=await L(o);return S(A(s,F?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await M();P(),await e(dt(n,t))},async terminateCheckout(e){let t=await M();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return N(async()=>{let{entry:o}=await w.read();y(o);let s=_(o).find(a=>a.operationId===e&&!a.terminal);if(!s||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await V(o,s,"terminate_checkout");let u=await L(o,!1,new Set([e]));return S(A(u,F?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return ee.add(e),()=>{ee.delete(e)}},destroy:Se}}export{$e as a,dt as b,zt as c};
1
+ import{b as Ve}from"./chunk-74T76RE4.js";import{a as $}from"./chunk-GE6RSO2C.js";import{D as K,F as ze,c as Ue,e as z,j as Te,u as He,v as Le,x as Me,z as Ge}from"./chunk-RHILCVPZ.js";import{a as Fe,b as Ne,c as je}from"./chunk-YUL23NAW.js";import{a as se}from"./chunk-KVLOMX2G.js";import{i as ue}from"./chunk-JBN6ADWQ.js";import{K as G}from"./chunk-AD35L6BX.js";import{A as ae,B as ie,C as J,E as Ae}from"./chunk-3Q3DZEP3.js";import{x as ye}from"./chunk-5WFI36LF.js";import{b as De}from"./chunk-7D5462NE.js";import{a as l}from"./chunk-46USIMCJ.js";import{h as oe}from"./chunk-XIBJF5E6.js";import{a as xe}from"./chunk-5MRSFLQA.js";import{b as r}from"./chunk-YLH3AYCK.js";import{a as ge}from"./chunk-DSPLGTQI.js";var v=G.options,it=r.discriminatedUnion("operation",[v[1].omit({customerToken:!0}),v[2].omit({customerToken:!0}),v[3].omit({customerToken:!0}),v[4].omit({customerToken:!0}),v[5].omit({customerToken:!0}),v[6].omit({customerToken:!0}),v[7].omit({customerToken:!0}),v[8].omit({customerToken:!0}),Te.omit({customerToken:!0})]),Pe=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),It=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("find_purchase")}),r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume","start"]),start:r.strictObject({requestId:v[0].shape.requestId,funnelId:v[0].shape.funnelId,locale:v[0].shape.locale,parameters:v[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe,includePaywallVersion:r.literal(!0).optional()}),r.strictObject({operation:r.literal("terminate_checkout"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[v[3].omit({customerToken:!0}),v[4].omit({customerToken:!0}),v[5].omit({customerToken:!0}),v[6].omit({customerToken:!0}),v[7].omit({customerToken:!0})]).optional()}).refine(i=>!i.command||i.requestId===i.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:it})]),ce=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:z.shape.run.shape.status}),H={scope:oe,customerId:r.uuid()},Qe=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...H,outcome:r.literal("resolved"),target:ce,view:z.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((i,d)=>{i.outcome==="resolved"&&(i.access.type==="customer"!=(i.view!==null)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Be=r.strictObject({...H,target:ce,view:z.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:z.shape.purchase.unwrap().nullable()}).superRefine((i,d)=>{let f=i.settlement;(f.acceptance==="accepted"!=(f.receiptPhase!==null)||f.acceptance==="accepted"&&f.basis!=="receipt"||f.acceptance==="unknown"&&(f.state!=="unknown"||f.basis!=="none")||f.acceptance!=="accepted"&&(f.operationId!==null||f.receiptId!==null)||f.acceptance==="not_accepted"&&(f.state!=="settled"||!["run_terminal","position_advanced"].includes(f.basis))||i.purchase&&(i.purchase.receiptId!==f.receiptId||i.purchase.operation&&i.purchase.operation.operationId!==f.operationId||i.purchase.quote&&i.purchase.quote.operationId!==f.operationId)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ye=r.strictObject({...H,target:ce,purchase:z.shape.purchase.unwrap(),paywallVersionId:r.uuid().optional()}).superRefine((i,d)=>{(!i.purchase.operation||typeof i.purchase.canReselect!="boolean"||i.purchase.quote&&i.purchase.quote.operationId!==i.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),Je=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("none")}),r.strictObject({...H,outcome:r.literal("blocked")}),r.strictObject({...H,outcome:r.literal("found"),target:ce,start:r.strictObject({locale:v[0].shape.locale,parameters:v[0].shape.parameters}),purchase:Pe})]);var st=G.options[0].refine(i=>!i.customer&&!i.customerData),ut=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),Ke=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:oe,customerId:r.uuid(),sessionId:r.uuid(),start:st,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:Ue.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ut).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:He.nullable()})});function $e(i){return Me({...i,namespace:"purchases",identity:[i.scope.projectId,i.scope.environment,i.customerId]})}function We(i){let d=new URL(i.baseUrl??xe).href,f=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function R(){i.assertCurrent();try{let C=await i.storage.read();if(i.assertCurrent(),!Number.isSafeInteger(C.revision)||C.revision<0)throw f();let c=C.entry===null?null:Ke.parse(C.entry);if(c&&(c.baseUrl!==d||c.customerId!==i.customerId||c.scope.projectId!==i.scope.projectId||c.scope.environment!==i.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(c?.journal.entry&&(c.journal.entry.scope.projectId!==c.scope.projectId||c.journal.entry.scope.environment!==c.scope.environment||c.journal.entry.funnelId!==c.start.funnelId||c.journal.entry.runId!==c.run?.id||c.journal.entry.versionId!==c.run?.versionId)||c?.operationCommand&&!c.purchases.some(q=>q.operationId===c.operationCommand?.operationId))throw f();return{revision:C.revision,entry:c}}catch(C){throw C instanceof l?C:f()}}async function W(C){for(let c=0;c<8;c++){let q=await R(),O=C(structuredClone(q.entry));if(JSON.stringify(O)===JSON.stringify(q.entry))return O;O&&Ke.parse(O),i.assertCurrent();let j;try{j=await i.storage.write(q.revision,O)}catch{throw f()}if(i.assertCurrent(),j!==null){if(!Number.isSafeInteger(j)||j<=q.revision)throw f();return O}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:R,update:W,baseUrl:d}}var ct=5*6e4,lt=2e3;function dt(i,d){let f=i.purchases.find(R=>R.type==="checkout");if(!i.actions.includes("continue_checkout")||f?.type!=="checkout"||d!==void 0&&f.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return f.checkoutUrl}function zt(i){let d={...i,scope:{...i.scope},executionPolicy:structuredClone(i.executionPolicy)},f=d.session.snapshot();if(!f)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:R,sessionId:W}=f,C=!1,c=null,q,O,j=null,F=!1,U,X,Z,E={mode:"idle",status:"idle",actions:["start"],purchases:[]},g=new Map,ve=new Map,T=new Map,le=new AbortController,ee=new Set,Q=De(d),te=Ve(Q.request);function B(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function P(){if(C||d.session.snapshot()?.customerId!==R)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let w=We({...d,customerId:R,assertCurrent:P,storage:d.storage??$e({baseUrl:d.baseUrl,scope:d.scope,customerId:R})}),Xe,Re=()=>Xe??=import("./funnel-paywall-copies-DUZ3YX67.js").then(({createPaywallCopies:e})=>e({baseUrl:d.baseUrl,scope:d.scope,customerId:R})),Ze={read:async e=>(await Re()).read(e),write:async(e,t)=>(await Re()).write(e,t)},et=d.session.subscribeIdentity(Se);function Se(){C||(C=!0,clearTimeout(Z),le.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),et(),c?.reset(),c=null,j=null,Q.dispose(),ee.clear(),g.clear(),T.clear())}function S(e){P();let t=JSON.stringify(e)!==JSON.stringify(E);E=e,clearTimeout(Z),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Z=setTimeout(()=>{M().catch(()=>{})},5e3)),t&&ge(d.onRecovery,structuredClone(e));for(let n of t?ee:[]){if(C)break;ge(n,structuredClone(e))}return structuredClone(e)}function y(e){if(P(),!e||e.start.requestId!==O)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function _(e){let t=[...e.purchases],n=e.journal.entry?.purchase;return n&&!t.some(o=>o.operationId===n.operationId)&&t.push({receiptId:n.receiptId,operationId:n.operationId,terminal:null}),t}function x(e){let t=_(e),n=F&&t.length>0&&t.every(o=>o.terminal==="native"&&D(g.get(o.operationId))==="native")&&t.some(o=>{let s=g.get(o.operationId);return!!s&&J(s)&&T.get(o.operationId)===!0});return e.run&&(n||!["running","waiting"].includes(e.run.status))&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&t.every(o=>o.terminal!==null)}function A(e,t){let n=e.journal.entry?.command??e.journal.entry?.closeCommand,o=_(e).map(I=>{let k=g.get(I.operationId);return I.terminal&&!k?{type:I.terminal,operationId:I.operationId}:se({quote:k?.quote??null,operation:k??null,requestId:n?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(I.operationId)===!0})}),s=o.filter(I=>!["complete","native"].includes(I.type)),u=s[0],a=s.length===1&&u?.operationId?g.get(u.operationId):void 0;if(a&&(u?.type==="checkout"||u?.type==="cancel"))try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote)}catch(I){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:B(I)}}let m;if(t==="operation"&&!n&&u?.type==="cancel"&&a?.quote&&!a.problem&&!a.confirmedAt)try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote),Date.parse(a.quote.expiresAt)>Date.now()&&(m={operationId:a.operationId,quote:a.quote})}catch{}let p=o.length>0&&s.length===0,h=x(e)||t==="operation"&&p&&!n&&!e.operationCommand?"complete":u?.type==="checkout"?"checkout":u?.type==="fulfillment"?"fulfillment":u?.type==="recording"?"recording":n||e.operationCommand||u&&u.type!=="cancel"||t==="operation"&&!m?"waiting_result":"ready";return{mode:t,status:h,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...x(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...s.length===1&&u?.type==="checkout"?["continue_checkout"]:[]]}}function D(e){let t=se({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function de(e){if(!e.operation)return;let t=ae.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==R)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let n=ue(g.get(t.operationId)??null,t);g.set(t.operationId,n),n===t&&T.set(t.operationId,e.canReselect===!0)}async function tt(e){P();for(let n of[e.purchase,e.run.paywall])n&&de(n);let t=await w.update(n=>{if(y(n),n.run&&(n.run.id!==e.run.id||n.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=_(n);for(let s of[e.purchase,e.run.paywall]){let u=s?.operation?.operationId??s?.quote?.operationId;if(!s||!u)continue;let a=o.find(p=>p.operationId===u);if(a&&a.receiptId!==s.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=D(g.get(u));a?a.terminal??=m:o.push({receiptId:s.receiptId,operationId:u,terminal:m})}return{...n,purchases:o,run:n.run&&(n.run.revision>e.run.revision||!["running","waiting"].includes(n.run.status)&&["running","waiting"].includes(e.run.status))?n.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});y(t),t.run&&!["running","waiting"].includes(t.run.status)&&_(t).some(n=>!n.terminal)&&(t=await L(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(n=>!!n)))),y(t),S(A(t,"run"))}function nt(){return{async read(){let{entry:e}=await w.read();return y(e),structuredClone(e.journal)},async write(e,t){let n=null;return await w.update(o=>{if(y(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return n=null,o.journal.revision!==e?o:(n=e+1,{...o,journal:{revision:n,entry:t}})}),n}}}async function L(e,t=!1,n=new Set){y(e);let o=_(e);for(let u of o){if(u.terminal)continue;let a=n.has(u.operationId)?g.get(u.operationId):void 0;if(a??=await V(e,u),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(a.merchantExecution&&a.merchantExecution.customerId!==R)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&se({quote:a.quote??null,operation:a,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let m=J(a)?await te.update({operationId:u.operationId,intent:"cancel"}):await te.attach({operationId:u.operationId,intent:"cancel"});if(a=ae.parse(m.operation),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");a=await V(e,u)}g.set(u.operationId,ue(g.get(u.operationId)??null,a))}let s=await w.update(u=>{y(u);let a=u.operationCommand&&g.get(u.operationCommand.operationId);return{...u,...a&&(a.confirmedAt||a.merchantExecution||!Ae(a))?{operationCommand:void 0}:{},purchases:_(u).map(m=>({...m,terminal:m.terminal??D(g.get(m.operationId))}))}});return y(s),s}async function Y(e){P();let t=await Q.request("funnels",e);return P(),t}async function rt(e){try{return await Y(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return Y({...e,intent:"resume"})}}async function ot(){let e=$(Je,await Y({operation:"find_purchase"}));if(e.customerId!==R||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:n}=e;return await w.update(o=>o&&!x(o)?o:{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:R,sessionId:W,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...n,terminal:null}],journal:{revision:0,entry:null}}),"found"}let ne;function pe(e){let t=ne;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<ct))return t.job;let n={at:Date.now(),job:ot().then(o=>(n.outcome=o,n.at=Date.now(),o),o=>{throw ne===n&&(ne=void 0),o})};return ne=n,n.job}async function V(e,t,n="recover_purchase",o=!1){let s=$(Ye,await Y({operation:n,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId},...o?{includePaywallVersion:!0}:{}}));if(me(e,s),s.purchase.receiptId!==t.receiptId||s.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return de(s.purchase),o&&s.paywallVersionId&&ve.set(t.operationId,s.paywallVersionId),g.get(t.operationId)}async function Ce(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let n=$(Be,await Y({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(me(e,n),n.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");n.purchase&&de(n.purchase);let o=await w.update(s=>{y(s);let u=_(s),{receiptId:a,operationId:m}=n.settlement;if(a&&m){let h=u.find(I=>I.operationId===m);if(h&&h.receiptId!==a)throw new l("INVALID_RESPONSE","Original Receipt changed");h||u.push({receiptId:a,operationId:m,terminal:D(g.get(m))})}let p=n.settlement.state==="settled"?Le(s.journal.entry,t.requestId):s.journal.entry;return{...s,purchases:u,journal:p===s.journal.entry?s.journal:{revision:s.journal.revision+1,entry:p}}});y(o),e=o}return e}function me(e,t){if(t.customerId!==R||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function fe(e,t){if(y(e),e.run&&(e=await Ce(e)),!_(e).length&&x(e))return S(A(e,"operation"));if(!_(e).length)return S({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(t)});F=!0;let n=_(e);if(e.run&&["running","waiting"].includes(e.run.status)&&n.every(s=>s.terminal==="native"))for(let s of n)D(g.get(s.operationId))!=="native"&&await V(e,s);let o=await L(e);return S(A(o,"operation"))}async function re(e,t=!1,n=!0,o=!1){if(O=e.start.requestId,j=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!c){let s=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await rt(s)}catch(h){if(!e.run&&h instanceof l&&(h.status===void 0||h.status>=500))return S({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:E.purchases,error:B(h)});throw h}let a=$(Qe,u);if(a.customerId!==R||a.scope.projectId!==d.scope.projectId||a.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(a.outcome==="unknown")return S({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:E.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});me(e,a);let m=await w.update(h=>(y(h),{...h,run:{id:a.target.runId,versionId:a.target.versionId,status:a.target.status,revision:a.view?.revision??h.run?.revision??0,runExpiresAt:a.target.runExpiresAt}}));if(y(m),e=m,a.access.type==="operation_only")return fe(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ce(e);let p=a.view;if(p.locale!==e.start.locale||!Ge(p.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");c=ze({...d,customerRun:{runId:a.target.runId,customerId:R,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(h=>d.executionPolicy.allowed.includes(h))},funnelCommandStorage:nt(),onAcceptedResponse:tt},{scope:a.scope,run:p})}try{let s=o&&q?.controller===c?performance.now()-q.at:1/0;(s>=lt||c.pendingCommands?.length||(c.viewAgeMs??0)<s)&&(q=void 0,await c.get(),q={controller:c,at:performance.now()}),c.view?.pendingRequest?.requestId===e.start.requestId&&!c.pendingCommands?.length&&await c.resume(c.view.pendingRequest.requestId);for(let a of c.pendingCommands??[])a.operation!=="close"&&await c.settle?.(a.requestId);c.pendingCommands?.length&&await c.retry(),P();let u=(await w.read()).entry;return y(u),S(A(u,"run"))}catch(s){if(P(),n&&s instanceof l&&(s.status===401||s.status===409&&s.reason==="STATE_CHANGED")){c.reset(),c=null;let u=(await w.read()).entry;return y(u),re(u,!1,!1,!1)}throw s}}function N(e,t="read",n){if(P(),U)return t==="read"||t===X?U:U.then(()=>N(e,t,n),()=>N(e,t,n));clearTimeout(Z);let o=e().catch(s=>{throw!C&&!n?.(s)&&S({mode:"blocked",status:"blocked",actions:["refresh"],purchases:E.purchases,error:B(s)}),s});return U=o,X=t,o.then(()=>{U===o&&(U=void 0,X=void 0)},()=>{U===o&&(U=void 0,X=void 0)}),o}function M(e){let t=e?.reuseRecentRead===!0;return N(async()=>{let{entry:n}=await w.read();if(!n||x(n)){if(await pe(!1)==="blocked")return Ee();({entry:n}=await w.read())}return n?(O&&n.start.requestId!==O&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F&&O===n.start.requestId?fe(n,E.error):re(n,!1,!0,t)):S({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function Ee(){return S({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function be(){let e=await M();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:N(async()=>{let t=(await w.read()).entry;if(y(t),!F){if(!c?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=c.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(J(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return S(A(t,"run"));if(c.pendingCommands?.length)await c.retry();else{let I=c.view;await c.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:I.nodeId,visit:I.visit,revision:I.revision,input:{type:"paywall_confirm",operationId:I.paywall.quote.operationId,...I.paywall.quote.merchantTerms?{merchantConfirmation:ye(I.paywall.quote.merchantTerms)}:{}}})}let h=(await w.read()).entry;return y(h),S(A(h,"run"))}let n=t.operationCommand?.operationId??E.confirmation?.operationId,o=n&&g.get(n);if(!n||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");K({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await w.update(p=>{if(y(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==n)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:n,intent:"confirm"}}});let s={operationId:n,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:ye(o.quote.merchantTerms)}:{}},u=J(o)?await te.update(s):await te.attach(s),a=ae.parse(u.operation);if(P(),u.operation.operationId!==n)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");g.set(n,ue(o,a));let m=(await w.read()).entry;return y(m),S(A(await L(m,!1,new Set([n])),"operation"))},"confirm")}function at(e){let t=e?.quote;return t&&ie(t)&&t.timing==="immediate"&&t.execution.provider==="merchant"&&(e.confirmedAt||e.merchantExecution)?t:null}function Oe(){if(E.mode!=="operation"||E.status==="blocked")return null;let e=E.purchases.filter(({type:n})=>n!=="complete"&&n!=="native"),t=e.length===1&&e[0]?.operationId;return t?at(g.get(t)):null}async function _e(){P();let{entry:e}=await w.read();return e?x(e)?"finished":"pending":"none"}return{get controller(){return c},get recovery(){return structuredClone(E)},get attempt(){return P(),structuredClone(j)},get identitySignal(){return le.signal},get customerId(){return R},retained:_e,get paywallCopies(){return Ze},async findPurchase(){let e=await _e();if(e==="pending")return e;let t=await pe(!0);return P(),t==="none"?e:t},async readPaywall(e){P();let t=Fe(e),[n,{readPaywallContent:o},{validateResourceCheck:s}]=await Promise.all([Ne(Q.request,"resolvePaywall"),import("./paywall-content-QLJIOFR3.js"),import("./check-response-WOTPYNDN.js")]);P();let u=n.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),a=await je(Q.request,n,u);s(u,a.paywall.check,a.scope);let m=await o(d,a.paywall);if(P(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},get canRestoreUpgradePaywall(){return Oe()!==null},recoverUpgradePaywall(){let e=Oe();return e?this.recoverPurchasePaywall(void 0,e.operationId):Promise.resolve(null)},async recoverPurchasePaywall(e,t){if(E.mode!=="operation"||E.status==="blocked")return null;let{entry:n}=await w.read();if(!n?.run)return null;y(n);let o=_(n),s=o.filter(b=>!b.terminal),u=o.filter(b=>b.terminal==="complete"),a=s.length===1?s[0]:s.length?void 0:u.find(b=>e&&e.runId===n.run?.id&&b.receiptId===e.receiptId)??(u.length===1?u[0]:void 0);if(!a||t&&a.operationId!==t)return null;let m=e?.runId===n.run.id&&e.receiptId===a.receiptId?e.view:void 0,p;try{p=await V(n,a,"recover_purchase",!0)}catch(b){if(!(b instanceof l&&b.status===400&&b.code==="INVALID_REQUEST"))throw b;if(!m)return null;p=await V(n,a)}let h=p.quote;if(!h||ie(h)&&(h.timing!=="immediate"||h.execution.provider!=="merchant")||!(p.confirmedAt||p.merchantExecution||p.checkoutUrl||D(p)==="complete"))return null;D(p)!=="complete"&&K({allowed:n.allowed.filter(b=>d.executionPolicy.allowed.includes(b))},h);let I=ve.get(a.operationId),k=n.start.parameters?.commerce,ke=n.start.locale??"en",he=m;if(I){if(typeof k!="object"||!k||!("provider"in k)||typeof k.provider!="string"||!("currency"in k)||typeof k.currency!="string")return null;he=await this.readPaywall({paywallVersionId:I,locale:ke,commerce:{provider:k.provider,currency:k.currency,...ie(h)?{intent:"subscription_change"}:{}}})}if(!he)return null;P();let qe=he,we=!1,Ie=async()=>{throw new l("PURCHASE_PENDING","Only the original purchase can be recovered")};return{signal:le.signal,view:qe,quote:h,locale:ke,get operation(){return p},get canReselect(){return T.get(a.operationId)===!0},async refresh(){return qe},preview:Ie,confirm:Ie,cancel:Ie,async read(){if(we)throw new DOMException("Purchase view closed","AbortError");p=await V(n,a);let b=await L(n,!1,new Set([a.operationId]));return we||S(A(b,"operation")),structuredClone(p)},destroy(){we=!0}}},start(e){let t=G.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return N(async()=>{let n=(await w.read()).entry;if((!n||x(n))&&await pe(!0)==="blocked")return Ee();let o=await w.update(s=>{if(s&&!x(s)){if(s.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return s}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:R,sessionId:W,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return O!==o.start.requestId&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F?fe(o,E.error):re(o,!0,!0,!0)},`start:${t.funnelId}`)},refresh:M,confirm:be,retry:()=>F?be():N(async()=>{let{entry:e}=await w.read();return e?re(e,!0):S({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return c?.view?N(async()=>{if(!c?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(c.pendingCommands?.find(n=>n.operation==="close"))await c.retry();else if(["running","waiting"].includes(c.view.status)){let n=c.view;await c.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision})}let t=(await w.read()).entry;return y(t),S(A(t,"run"))},"close"):M()},async continueCheckout(e,t){let n=t?await N(async()=>{let{entry:o}=await w.read();if(y(o),!o.run||!_(o).some(u=>u.operationId===t&&!u.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let s=await L(o);return S(A(s,F?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await M();P(),await e(dt(n,t))},async terminateCheckout(e){let t=await M();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return N(async()=>{let{entry:o}=await w.read();y(o);let s=_(o).find(a=>a.operationId===e&&!a.terminal);if(!s||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await V(o,s,"terminate_checkout");let u=await L(o,!1,new Set([e]));return S(A(u,F?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return ee.add(e),()=>{ee.delete(e)}},destroy:Se}}export{$e as a,dt as b,zt as c};
@@ -1 +1 @@
1
- import{h as c}from"./chunk-DBYRJ4QV.js";import{b as p}from"./chunk-PZTWDJHN.js";import{d as x,e as y,f as g}from"./chunk-VPT5MFDG.js";import{a as m,b as d}from"./chunk-CILM5XMH.js";var u=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function F(e,t,f){let i={},l,s,n,o="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let r=e.cases.findIndex(b=>x(t.attributes??{},b.condition,t.savedGroups??{}));o=r<0?"default":`case:${r}`,a=r<0?e.default:e.cases[r].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new u("Required GB Feature is unavailable");l=g(e.featureKey,t),n=l.value,Object.assign(i,c(e,{value:n})),a=e.next;break;case"split":{let r=f[e.experimentId];if(!r)throw new u("Required GB Experiment is unavailable");if(s=y(r,t),n=s.value,o=s.inExperiment&&!s.passthrough&&typeof n=="string"?n:"notParticipating",a=o==="notParticipating"?e.notParticipating:e.routes[o],!a)throw new u("Experiment Variation has no published route");break}case"offering":{let r=e.configuration.source==="fixed"?e.configuration.versionId:g(e.configuration.featureKey,t).value;n={type:"offering_version",id:p.uuid().parse(r)},Object.assign(i,c(e,{value:n})),a=e.next;break}case"coupon":case"coupons":n=e.type==="coupons"?e.couponIds.map(r=>({type:"reward",id:r})):{type:"reward",id:e.couponId},Object.assign(i,c(e,{value:n})),a=e.next;break}return{port:o,target:a,projections:i,...n===void 0?{}:{value:n},...l?{feature:l}:{},...s?{experiment:s}:{}}}function E(e,t,f){p.uuid().parse(e),p.number().int().nonnegative().parse(t);let i=m(d(new TextEncoder().encode(JSON.stringify([e,t,f])))).slice(0,32);return`${i.slice(0,8)}-${i.slice(8,12)}-5${i.slice(13,16)}-a${i.slice(17,20)}-${i.slice(20)}`}export{F as a,E as b};
1
+ import{h as c}from"./chunk-MNICOIQ6.js";import{b as p}from"./chunk-YLH3AYCK.js";import{d as x,e as y,f as g}from"./chunk-VPT5MFDG.js";import{a as m,b as d}from"./chunk-CILM5XMH.js";var u=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function F(e,t,f){let i={},l,s,n,o="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let r=e.cases.findIndex(b=>x(t.attributes??{},b.condition,t.savedGroups??{}));o=r<0?"default":`case:${r}`,a=r<0?e.default:e.cases[r].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new u("Required GB Feature is unavailable");l=g(e.featureKey,t),n=l.value,Object.assign(i,c(e,{value:n})),a=e.next;break;case"split":{let r=f[e.experimentId];if(!r)throw new u("Required GB Experiment is unavailable");if(s=y(r,t),n=s.value,o=s.inExperiment&&!s.passthrough&&typeof n=="string"?n:"notParticipating",a=o==="notParticipating"?e.notParticipating:e.routes[o],!a)throw new u("Experiment Variation has no published route");break}case"offering":{let r=e.configuration.source==="fixed"?e.configuration.versionId:g(e.configuration.featureKey,t).value;n={type:"offering_version",id:p.uuid().parse(r)},Object.assign(i,c(e,{value:n})),a=e.next;break}case"coupon":case"coupons":n=e.type==="coupons"?e.couponIds.map(r=>({type:"reward",id:r})):{type:"reward",id:e.couponId},Object.assign(i,c(e,{value:n})),a=e.next;break}return{port:o,target:a,projections:i,...n===void 0?{}:{value:n},...l?{feature:l}:{},...s?{experiment:s}:{}}}function E(e,t,f){p.uuid().parse(e),p.number().int().nonnegative().parse(t);let i=m(d(new TextEncoder().encode(JSON.stringify([e,t,f])))).slice(0,32);return`${i.slice(0,8)}-${i.slice(8,12)}-5${i.slice(13,16)}-a${i.slice(17,20)}-${i.slice(20)}`}export{F as a,E as b};