@tinkerlandai/longplay-sdk 0.10.58 → 0.10.59

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 (98) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +1 -0
  3. package/README.zh-CN.md +1 -0
  4. package/dist/check-response-K56UEZ6E.js +1 -0
  5. package/dist/{chunk-GCTD4RXV.js → chunk-2RFI2DEV.js} +1 -1
  6. package/dist/{chunk-KXA4JHFW.js → chunk-32AEJKJW.js} +1 -1
  7. package/dist/{chunk-XQAGF6SQ.js → chunk-45PGU2HW.js} +1 -1
  8. package/dist/{chunk-P2JQEGYV.js → chunk-4OODZM64.js} +1 -1
  9. package/dist/{chunk-YJ2IOBHW.js → chunk-4SI4SQ3C.js} +1 -1
  10. package/dist/{chunk-4VZCPOVE.js → chunk-5LNX7MHO.js} +1 -1
  11. package/dist/chunk-5MRSFLQA.js +1 -0
  12. package/dist/{chunk-AIRW6CZ7.js → chunk-6426YKPK.js} +1 -1
  13. package/dist/{chunk-GLVCBJL5.js → chunk-66W37FEV.js} +1 -1
  14. package/dist/{chunk-4BHGHPI5.js → chunk-725CAWOK.js} +1 -1
  15. package/dist/{chunk-LDNDI6G3.js → chunk-77O2O552.js} +1 -1
  16. package/dist/{chunk-RXEYS3X5.js → chunk-7STWC4L4.js} +1 -1
  17. package/dist/{chunk-EHYW66EH.js → chunk-BJW4AXFL.js} +1 -1
  18. package/dist/{chunk-227Z7LU4.js → chunk-C3HZCZVJ.js} +1 -1
  19. package/dist/{chunk-YIHMOK6T.js → chunk-DBYRJ4QV.js} +1 -1
  20. package/dist/{chunk-NQZ23AGQ.js → chunk-EB7MIZ4T.js} +1 -1
  21. package/dist/{chunk-G2JC7G3R.js → chunk-EE6QNOCL.js} +1 -1
  22. package/dist/{chunk-PZTFSADV.js → chunk-EKUDMQXT.js} +1 -1
  23. package/dist/{chunk-ZG3EYP5L.js → chunk-FBNEQ2K5.js} +1 -1
  24. package/dist/{chunk-T7AK4QLG.js → chunk-FQMZY5VP.js} +1 -1
  25. package/dist/{chunk-6VWVBQFR.js → chunk-HUYKZH3H.js} +1 -1
  26. package/dist/{chunk-6UQ7BKSR.js → chunk-IMFPRZUY.js} +1 -1
  27. package/dist/chunk-J3RW4GMO.js +1 -0
  28. package/dist/{chunk-EP2L4VTS.js → chunk-J5K4PNII.js} +1 -1
  29. package/dist/chunk-J7VGTAJ7.js +1 -0
  30. package/dist/{chunk-GIX2F53I.js → chunk-JBSJ3JU2.js} +1 -1
  31. package/dist/{chunk-6HNCADWS.js → chunk-JEDRJAJ5.js} +1 -1
  32. package/dist/{chunk-2PY7INHO.js → chunk-KTWKDR5L.js} +1 -1
  33. package/dist/{chunk-IJQFSZQG.js → chunk-LUDTXNMH.js} +1 -1
  34. package/dist/{chunk-46MFVWRW.js → chunk-MB2U2GWJ.js} +1 -1
  35. package/dist/{chunk-RB2SBQMM.js → chunk-MZ6NEOOQ.js} +1 -1
  36. package/dist/{chunk-NFZUVZJP.js → chunk-NAFHQVSX.js} +1 -1
  37. package/dist/{chunk-NPKNI2UD.js → chunk-NDNHTG5B.js} +1 -1
  38. package/dist/{chunk-HIH6IEV7.js → chunk-O2V4MTM6.js} +1 -1
  39. package/dist/{chunk-XQJW2RXY.js → chunk-PGLBFTRK.js} +1 -1
  40. package/dist/{chunk-D26ZQC46.js → chunk-PJHTN5NJ.js} +1 -1
  41. package/dist/chunk-PTNMDAND.js +1 -0
  42. package/dist/{chunk-PYTI77BV.js → chunk-R4CYPCBI.js} +1 -1
  43. package/dist/{chunk-LB2ZRTRA.js → chunk-RIEWU4MN.js} +1 -1
  44. package/dist/{chunk-QA3LXFSK.js → chunk-S5RM3VO6.js} +1 -1
  45. package/dist/{chunk-Y2DUFDPV.js → chunk-TK3WOD2O.js} +1 -1
  46. package/dist/chunk-U2NEVISJ.js +1 -0
  47. package/dist/{chunk-RSKDG2VD.js → chunk-VNYUL3PV.js} +1 -1
  48. package/dist/{chunk-LTWU7HH5.js → chunk-VXDVMAS6.js} +1 -1
  49. package/dist/{chunk-4UOJT46E.js → chunk-WUPNZGE2.js} +1 -1
  50. package/dist/{chunk-XBF44N3Z.js → chunk-XCFAKO23.js} +1 -1
  51. package/dist/chunk-XY2X6YJF.js +1 -0
  52. package/dist/{chunk-WILVPHE6.js → chunk-YB3PQ75M.js} +2 -2
  53. package/dist/{chunk-XH2JMWC6.js → chunk-ZCJEXNJD.js} +1 -1
  54. package/dist/{chunk-NTYIQ5YC.js → chunk-ZRGL2CAP.js} +1 -1
  55. package/dist/content-5OMLKBPP.js +1 -0
  56. package/dist/funnel-host-purchase-53LYWG4V.js +1 -0
  57. package/dist/funnel-host-recovery-paywall-FC3XQU2U.js +1 -0
  58. package/dist/funnel-paywall-copies-U3JIYQJ5.js +1 -0
  59. package/dist/funnel-paywall-prerender-YCATKDAY.js +1 -0
  60. package/dist/funnel-route-prediction-XYWNKGQZ.js +1 -0
  61. package/dist/funnel-route-source-4ZVBFNYV.js +1 -0
  62. package/dist/funnel-runtime-host-LQ6X5B6R.js +1 -0
  63. package/dist/index.d.ts +792 -0
  64. package/dist/index.js +1 -1
  65. package/dist/merchant-bridge-contracts-IZ7ARRRO.js +1 -0
  66. package/dist/openrouter.js +1 -1
  67. package/dist/operation-contracts-6RQ33K66.js +1 -0
  68. package/dist/page.js +1 -1
  69. package/dist/paywall-KQIBPACY.js +1 -0
  70. package/dist/paywall-content-NQXU3O4D.js +1 -0
  71. package/dist/paywall-session-W42F6DIF.js +1 -0
  72. package/dist/popup.js +1 -1
  73. package/dist/react-native.js +1 -1
  74. package/dist/screen-renderer-2ZDV2WYD.js +1 -0
  75. package/dist/server.js +1 -1
  76. package/dist/visual.js +1 -1
  77. package/package.json +1 -1
  78. package/dist/check-response-EYOK5EU5.js +0 -1
  79. package/dist/chunk-6PVQF4FJ.js +0 -1
  80. package/dist/chunk-F4E42S54.js +0 -1
  81. package/dist/chunk-QY5TS3OY.js +0 -1
  82. package/dist/chunk-UB5SVEM6.js +0 -1
  83. package/dist/chunk-XFOU4DZG.js +0 -1
  84. package/dist/content-2SRJS3E3.js +0 -1
  85. package/dist/funnel-host-purchase-PBCM5VL5.js +0 -1
  86. package/dist/funnel-host-recovery-paywall-7Z4VOQCV.js +0 -1
  87. package/dist/funnel-paywall-prerender-4J5EFPFQ.js +0 -1
  88. package/dist/funnel-route-prediction-4CW6WOJY.js +0 -1
  89. package/dist/funnel-route-source-UM5O7FJS.js +0 -1
  90. package/dist/funnel-runtime-host-F6B7XCVB.js +0 -1
  91. package/dist/merchant-bridge-contracts-YVMAYBE2.js +0 -1
  92. package/dist/operation-contracts-WX2HYHD5.js +0 -1
  93. package/dist/paywall-PWWDHKVH.js +0 -1
  94. package/dist/paywall-content-DSZJWOTF.js +0 -1
  95. package/dist/paywall-session-OOXP3SRE.js +0 -1
  96. package/dist/screen-renderer-WZFPWLB5.js +0 -1
  97. /package/dist/{chunk-COMZFFUA.js → chunk-PZTWDJHN.js} +0 -0
  98. /package/dist/{chunk-WILVPHE6.js.LEGAL.txt → chunk-YB3PQ75M.js.LEGAL.txt} +0 -0
@@ -1 +1 @@
1
- import{b as Bn}from"./chunk-QY5TS3OY.js";import{a as wn}from"./chunk-PYTI77BV.js";import{a as _n,b as Un,c as fn,d as mn,e as $e,f as Vn,h as $n,i as Mn,j as xn,k as zn}from"./chunk-6UQ7BKSR.js";import{a as Jn}from"./chunk-XQAGF6SQ.js";import{a as Sn}from"./chunk-W32FI2A2.js";import{c as On,e as qn,f as Ln,i as Hn,j as He,k as nn,l as Nn,m as tn}from"./chunk-EP2L4VTS.js";import{b as An}from"./chunk-XH2JMWC6.js";import{a as pn,d as Dn}from"./chunk-NPKNI2UD.js";import{C as Tn}from"./chunk-NTYIQ5YC.js";import{a as ne}from"./chunk-Y2DUFDPV.js";import{a as Ie}from"./chunk-DSPLGTQI.js";function Gn(i){let E=new Set,U=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 ne("COMMAND_PENDING","The original display acknowledgement is still pending");await i.client.settle(f),L=!0,i.client.pendingCommand?.requestId===f&&await new Promise(H=>setTimeout(H,1500))}i.stopped||i.key!==a||(L&&await i.client.get(),!(i.stopped||i.key!==a)&&E.add(a))}function k(a,f){n=f;let L=()=>{n===f&&(n=null),U.delete(a)};return f.then(L,H=>{L(),i.busy||i.fail(H)}),f}function V(a){if(i.reviewing||E.has(a)||U.has(a)||i.stopped)return;U.add(a);let f=async()=>{if(i.reviewing||i.stopped||i.key!==a||E.has(a)){U.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 H=i.client.view,oe=i.expected(),u=oe.requestId;try{await i.client.submit({operation:"shown",...oe})}catch(P){if(!(P instanceof ne)||P.code!=="CONFLICT"||P.status!==409||i.client.pendingCommand)throw P;await i.client.get();let s=i.client.view;if(i.stopped||i.reviewing||i.key!==a||!s||!H||s.id!==H.id||s.source.versionId!==H.source.versionId||s.nodeId!==oe.nodeId||s.visit!==oe.visit||s.revision<=oe.revision||s.stopped||!s.screen&&(!s.paywall||s.paywall.receiptId!==H.paywall?.receiptId)||!["running","waiting"].includes(s.status)||i.client.pendingCommand)throw P;let r=i.expected();u=r.requestId,await i.client.submit({operation:"shown",...r})}await p(a,u)})();k(a,L)};f()}function D(){if(n)return n;let a=i.client.pendingCommand;if(a?.operation!=="shown")return null;let f=i.key;return U.add(f),k(f,(async()=>{await i.client.retry(),await p(f,a.requestId)})())}return{report:V,settled:D,get inFlight(){return n}}}function Qn(i){let E={},U=new Map;async function n(p){let k=i.client.view,V=k?.screen,D=V?.customerData.nodes[p.nodeId];if(i.stopped||i.busy||!k||!V||!D)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(p.action)){let P=i.document,s=P?Tn(P,p.nodeId):null,r=s?.type==="customer_data"?s.data.outputs?.[p.action]:void 0;r&&V.outputs.includes(r)?await i.perform(()=>i.client.submit({operation:"submit",...i.expected(),input:{type:"screen",output:r,answers:i.answers,selection:p.value?{[p.nodeId]:p.value}:{}}})):await i.onIntent?.(p,k);return}let f=p.action.startsWith("sources_")?D.resources.find(P=>P.key===p.value):null;if(p.action.startsWith("sources_")&&!f)throw new ne("INVALID_REQUEST","Choose a current resource");let L=`${k.visit}:${p.nodeId}:${f?.key??""}`,H=U.get(L)??[null],u=E[p.nodeId]??{page:1,after:null,filter:"all",...f?{resourceKey:f.key}:{}};if(p.action==="filter"){let P=p.value;if(!P||!(D.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(P))throw new ne("INVALID_REQUEST","Unknown data filter");u={page:1,after:null,filter:P},H.splice(0,H.length,null)}else if(p.action==="next"||p.action==="sources_next"){let P=f?.sources.at(-1),s=f?P?{kind:"ledger",cursor:{at:P.detail[0],id:P.id,type:"source"}}:null:V.dataCursors[p.nodeId];if(!s||!f&&!D.hasNext)return;H[u.page]=s,u={...u,page:u.page+1,after:s}}else if(p.action==="previous"||p.action==="sources_previous"){if(u.page<=1)return;u={...u,page:u.page-1,after:H[u.page-2]??null}}U.set(L,H),E={...E,[p.nodeId]:u},await i.perform(()=>i.client.get({nodeId:k.nodeId,visit:k.visit,revision:k.revision,components:E}))}return{get queries(){return E},intent:n,reset(){E={},U.clear()}}}function Wn(i){let{doc:E,holder:U,reviewHolder:n,mountScreenPreview:p}=i,k=!1,V,D=0,a=null,f="",L,H=new Map,oe=s=>s?`${s.id}:${s.nodeId}:${s.visit}:${s.revision}:${s.paywall?.quote?.operationId??""}`:"";async function u(s){if(i.stopped||!i.client.review||k&&s===V&&L?.active)return;let r=!k||s!==V;k||(f=oe(i.client.view),H.set(f,structuredClone(i.answers))),k=!0,V=s,U.hidden=!0,i.suspend(!0),n.hidden=!1;let S=++D;r&&(L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),L=nn(n,i.loadingOptions,"funnel",()=>{P()}));let A=r?L:void 0;try{if(A?.start(!1,i.client.view?.locale),S!==D||i.stopped)return;let de=i.client.review(s),N=await(A?.wait(de,He)??de);if(i.stopped||S!==D||!k)return;if(!N.review)throw new ne("INVALID_RESPONSE","Historical projection is missing");a?.destroy(),a=null,A||n.replaceChildren();let Q=E.createElement("div"),W=A?tn(Q,n):()=>{};n.append(Q);let O=N.run.locale.startsWith("zh"),g=i.chrome;Q.style.cssText=g.history;let j=E.createElement("p");j.textContent=O?"只读回看":"Read-only history",j.style.cssText=g.historyTitle,Q.append(j);let F=E.createElement("p");F.style.cssText=g.historyNote,F.textContent=N.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.",Q.append(F);let Te=N.review.page?.receiptId,ve=E.createElement("div");ve.style.cssText=g.historyPages;for(let[K,R]of N.review.pages.entries()){let v=E.createElement("button");v.type="button",v.textContent=O?`第 ${K+1} 页`:`Page ${K+1}`;let he=Te!==void 0&&R.receiptId===Te;v.style.cssText=he?g.primary:g.secondary,he&&v.setAttribute("aria-current","page"),$e(v,()=>i.chrome.focus),v.onclick=()=>{u(R.receiptId)},ve.append(v)}if(ve.childElementCount&&Q.append(ve),N.review.page){let K=N.review.page,R=E.createElement("div");R.inert=!0,R.style.cssText=g.historyPage,Q.append(R),a=p(R,{mode:"live",rendererUrl:i.client.webViewUrl,title:K.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{S===D&&!i.stopped&&A?.present(W)},onError:he=>{if(S!==D||i.stopped)return;let Ce=new Error(he);A?.finish("error",Ce),a?.destroy(),a=null,Q.remove(),i.fail(Ce)},onEscape:()=>{P()}});let v=a;if(v.update(K.document,N.run.locale,{serverInput:{bindings:K.inputs,answers:K.answers,values:K.values}}),await v.ready,i.stopped||S!==D||!k)return}let me=O?{issued:"已领取",reserved:"已预留",redeemed:"已使用",expired:"已过期",revoked:"已撤销",unknown:"状态待确认"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},z=E.createElement("div");z.style.cssText=g.historyRecords;for(let K of[...N.review.coupons.map((R,v)=>`${O?"优惠券":"Coupon"} ${v+1}: ${me[R.status]}`),...N.review.purchases.map((R,v)=>`${O?"购买":"Purchase"} ${v+1}: ${zn(R.status,O)}`)]){let R=E.createElement("p");R.textContent=K,R.style.margin="0",z.append(R)}z.childElementCount&&Q.append(z),N.review.page||A?.present(W),i.client.view&&await i.enqueue(i.client.view)}catch(de){if(S!==D||i.stopped)return;A?.finish("error",de),a?.destroy(),a=null,n.replaceChildren(),i.fail(de)}}async function P(){if(!k||i.stopped||!i.client.review)return;let s=++D;L?.finish("dismissed");try{if(await i.client.review(),i.stopped||s!==D)return;k=!1,D++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,U.hidden=!1;let r=i.client.view;oe(r)!==f?(H.set(f,structuredClone(i.answers)),i.resetScreen()):(H.delete(f),i.suspend(!1)),r&&await i.enqueue(r)}catch(r){if(s!==D||i.stopped)return;a?.destroy(),a=null,n.replaceChildren(),i.fail(r)}}return{get active(){return k},get receipt(){return V},open:u,exit:P,get drafts(){return new Map([...H].map(([s,r])=>[s,structuredClone(r)]))},stop(){k=!1,D++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,U.hidden=!1}}}var yn=5e3;async function et(i,E,U){let n=E,p=n.prepared&&Bn(n.prepared),k=()=>{};function V(){n.prepared&&n.prepared.state!=="adopted"&&p?.release()}let D=()=>n.prepared?.state==="shown"&&!!p?.modal,a=n.client.identitySignal,f;try{f=await Promise.all([import("./screen-renderer-WZFPWLB5.js"),import("./paywall-PWWDHKVH.js")]),n.signal?.throwIfAborted(),a?.throwIfAborted()}catch(e){throw V(),e}let[{mountScreenPreview:L},{showPaywall:H}]=f,oe=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.appManifestRelease?Jn({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;oe?.start();let u=i.ownerDocument,P=Hn(u),s=!1,r=u.createElement("section"),S=u.createElement("div"),A=u.createElement("div"),de=u.createElement("div"),N=u.createElement("button");de.hidden=!0,N.type="button";let Q=u.createElement("p"),W=u.createElement("p"),O=u.createElement("button"),g=u.createElement("button"),j=u.createElement("button"),F=u.createElement("dialog"),Te,ve=!1;r.dataset.indianaFunnel="",r.dataset.longplayCloseOwner="sdk",r.setAttribute("aria-busy","false"),Q.setAttribute("role","status"),W.setAttribute("role","alert"),W.hidden=!0,O.type=g.type=j.type="button",A.append(O,N,Q,W,j,g),r.append(S,de,A),i.append(r);let me=Un,z=fn(me),K="",R=(u.documentElement.lang||"").startsWith("zh"),v,he="",Ce;for(let e of[O,N,j,g])$e(e,()=>z.focus);function gn(){let e=R?"关闭":"Close";g.parentElement===F?(g.textContent="×",g.setAttribute("aria-label",e),Ln(g,me)):(g.textContent=e,g.removeAttribute("aria-label"),g.style.cssText=z.link+";margin-inline-start:auto")}function Me(e){let t=e?.screen?.content.document.theme??me,o=JSON.stringify([t.primary,t.background,t.text,t.radius,t.font,g.parentElement===F]);if(o===K)return;K=o,me=t;let h=g.parentElement===F;z=fn(me,h),r.style.cssText=z.root+";min-width:0"+(h?";display:flex;flex-direction:column;min-height:100%":""),A.style.cssText=z.bar+(h?";margin-top:auto":""),A.hidden&&(A.style.display="none"),O.style.cssText=N.style.cssText=z.secondary,j.style.cssText=z.primary,Q.style.cssText=z.status,W.style.cssText=z.alert,gn(),mn(O)}function be(){A.hidden=O.hidden&&N.hidden&&j.hidden&&W.hidden&&!Q.textContent&&(g.hidden||g.parentElement!==A),A.style.display=A.hidden?"none":"flex",v?.responsive&&Ce!==void 0&&v.setContentHeight(Ce+A.getBoundingClientRect().height)}Me();let ae=null,I=null,le=null,we="",ee="",Pe=!1,xe="",rn="",ze="",l=!1,X=0,Be=!1,vn="",on=null,sn=Promise.resolve(),hn=!n.client.view,Ne,T=U,Je=n.hostPaywallTarget,Ae,_e,Ge="",Qe,te=!1,Re=null,ue=!1,We=()=>n.client.pendingCommand?.operation==="close",ie=null,$=null,an=Sn({document:u,run:async()=>{(!I?.observing||n.client.pendingCommand)&&await dn()},delay:()=>{if(!re.pending&&!(l||!le||!["running","waiting"].includes(le.status)&&!n.client.pendingCommand)&&!(I?.observing&&!n.client.pendingCommand))return le.pendingRequest||n.client.pendingCommand?1500:yn},hiddenDelay:()=>!l&&!re.pending&&n.client.pendingCommand?15e3:void 0}),M=null;function ln(){return $&&n.client.hasDurableJournal===!0&&M?.acknowledged===!0&&M.operationId===$.operationId&&n.client.view?.id===M.runId&&n.client.view?.status==="closed"&&n.client.view.revision===M.revision+1&&!(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0))&&!n.client.pendingPurchase?$:null}function In(e){let t=e.run.paywall;if(M&&e.settlement?.requestId===M.requestId&&e.settlement.state==="settled"&&e.settlement.operationId===null&&e.run.id===M.runId&&e.run.status==="closed"&&!e.run.pendingRequest&&e.run.revision===M.revision+1&&e.run.nodeId===M.nodeId&&e.run.visit===M.visit&&t?.receiptId===M.receiptId&&t.selectionGeneration===M.selectionGeneration&&(t.quote?.operationId??null)===M.operationId&&(t.operation?.operationId??t.quote?.operationId??null)===M.operationId){let o=M.operationId===null&&t.selectionGeneration===0&&!t.quote&&!t.operation&&!t.purchaseRequestId,h=pn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect});(o||t.canReselect===!0&&h.type==="native")&&(M.acknowledged=!0)}}let Ee=null,Ue=new Set,ce={},De=!1,Y=(e,t=null)=>{l||(e instanceof ne&&e.status===409&&e.reason==="STATE_CHANGED"&&e.recovery==="recover_operation"&&an.destroy(),Ee=t,De=!1,W.textContent=Vn(e,R),W.hidden=!1,j.hidden=n.client.pendingCommand===null,be(),Ie(n.onError,e))},re=An({client:n.client,document:u,conceal(){l||(pe(),T?.finish("dismissed"),r.hidden=!0,s||(s=!0,P()))},async receive(e){l||await se(n.client.view??e.run)},failed(e){if(!l){if(!re.pending){ue=!1;let t=n.client.view;t&&se(t).then(()=>Y(e),Y);return}Ze(),r.parentElement!==i&&i.append(r),r.hidden=!1,O.hidden=N.hidden=g.hidden=!0,Q.textContent="",Me(),Y(e,n.client.pendingCommand?.requestId??null)}}}),Cn=()=>{l||(Ee=null,W.textContent=Mn(R),W.hidden=!1,j.hidden=!0,be())};function ke(){let e=n.client.view;if(!e)throw new ne("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}let w=Wn({client:n.client,doc:u,holder:S,reviewHolder:de,mountScreenPreview:L,loadingOptions:n,get chrome(){return z},get stopped(){return l},get answers(){return ce},suspend(e){I?.setSuspended(e)},resetScreen(){we="",ee="",xe=""},enqueue:se,fail:Y}),Ve=Gn({client:n.client,expected:ke,fail:Y,get stopped(){return l},get reviewing(){return w.active},get key(){return we},get busy(){return X},get staleRead(){return on}}),je=Qn({client:n.client,expected:ke,perform:Oe,onIntent:n.onCustomerDataIntent,get stopped(){return l},get busy(){return X},get document(){return ae?.document},get answers(){return ce}}),Xe=e=>`${e.id}:${e.nodeId}:${e.visit}`,Se=e=>e&&(e.screen||e.paywall)?Xe(e):"";function ye(){let e=n.client.view;O.disabled=!w.active&&(X>0||!!n.client.pendingCommand||!e?.canBack||e.stopped||!["running","waiting"].includes(e.status)||!Se(e)||ee!==Se(e)),O.hidden=!w.active&&!e?.canBack,mn(O);let t=!!I&&!w.active;g.hidden=t&&!T?.active||ve&&!w.active,N.hidden=!n.client.review||!w.active&&!e?.canBack;let o=e?.locale.startsWith("zh");Q.textContent=t?"":X>0||e?.pendingRequest?o?"正在处理":"Processing":e?.instruction?.type==="wait"?o?"等待中":"Waiting":"",be()}async function bn(e){if(!e)return;let t=n.client.view;await e;let o=n.client.view;if(!t||!o||o.id!==t.id||o.nodeId!==t.nodeId||o.visit!==t.visit||o.stopped||!["running","waiting"].includes(o.status))throw new ne("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Oe(e,t=!1,o){if(!((X||ue||ie||$)&&!t||l||w.active&&!t)){X++,r.setAttribute("aria-busy","true"),W.hidden=!0,Ee=null,De=!1,ye();try{if(t||await bn(Ve.inFlight),l)return;let h=await e();l||await se(n.client.view??h.run)}catch(h){o?.(h)&&n.client.pendingCommand===null?Cn():re.pending||Y(h,n.client.pendingCommand?.requestId??null)}finally{X=Math.max(0,X-1),r.setAttribute("aria-busy",String(X>0)),l||(j.hidden=n.client.pendingCommand===null,ye())}}}function qe(){an.schedule()}async function dn(){if(!(l||Be||X)&&!re.pending){if(w.active){await w.open(w.receipt);return}Be=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let t=n.client.view,o=je.queries,h=await n.client.get(t?.screen&&Object.keys(o).length?{nodeId:t.nodeId,visit:t.visit,revision:t.revision,components:o}:void 0);De&&!l&&(De=!1,W.hidden=!0,be()),!l&&o===je.queries&&await se(n.client.view??h.run)}catch(e){Y(e),De=!l}finally{Be=!1}}}function Ye(e,t,o){if(T?.active){let Z=T;return Z.setDismissHandler(()=>Pn(Z)),Z}let h=nn(i,n,"funnel",()=>Pn(h),_n);return T=h,h.start(e,t,o),h}function Pn(e){l||te||(te=!0,e.finish("dismissed"),pe(),r.hidden=!0,n.client.view?ge().finally(B):B())}function un(){clearTimeout(Qe?.timeout),Qe=void 0}function pe(e){ve=!1,un(),Ae?.abort(),Ae=void 0,ae?.destroy(),ae=null,I?.destroy(),I=null,Ne=void 0,_e?.(),_e=void 0,F.open&&F.close();for(let t of Array.from(S.children))(!e||!t.contains(e))&&t.remove();S.style.cssText="",Ce=void 0,we="",ee="",Pe=!1,xe="",ze=""}function Rn(){let e=u.defaultView;v?.responsive&&e&&ae?.resizeViewport?.(e.innerHeight,e.innerWidth)}function Ze(){v?.destroy(),v=void 0,he=""}function Ke(e){let t=e.screen?.presentation;if(!t||t.type==="inline"){F.open&&F.close(),Ze(),g.parentElement!==A&&A.append(g),r.parentElement!==i&&i.append(r);for(let Z of["flex","display","flex-direction","justify-content"])S.style.removeProperty(Z);Me(e),be();return}r.parentElement!==F&&(F.append(g,r),i.append(F)),S.style.flex="1 0 auto",S.style.display="flex",S.style.flexDirection="column",S.style.justifyContent="center",Me(e);let o=e.screen.content.document,h=JSON.stringify([t,K]);if(h!==he){Ze(),he=h;let Z={sm:420,md:640,lg:900},fe="size"in t&&!t.backdrop?",0 0 0 100vmax #16142566":"";F.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${me.background};color:${me.text};`+(t.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${Z[t.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${fe};`+(t.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),v=On(F,{presentation:t,theme:o.theme,pages:o.pages},Rn),v.latch()}be(),F.setAttribute("aria-label",(Te?.screen===e.screen?.content.document.name?Te?.label:void 0)??ae?.document?.name??e.screen?.content.document.name??"Funnel")}async function jn(e){if(l||te)return;if(re.observe(),re.pending){le=e;return}if(ue&&(We()||["running","waiting"].includes(e.status))||(le=e,Ee&&n.client.pendingCommand?.requestId!==Ee&&(W.hidden=!0,Ee=null),R=e.locale.startsWith("zh"),N.textContent=R?"回看":"History",O.textContent=w.active?R?"返回当前":"Return to current":R?"返回":"Back",gn(),j.textContent=R?"重试":"Retry",j.hidden=n.client.pendingCommand===null,ye(),vn!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(vn=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,Ie(n.onState,structuredClone(e))),l||te))return;if((!e.pendingRequest||ue&&e.status==="closed")&&["closed","ineligible","failed"].includes(e.status)){B();return}if(e.stopped&&D()){B();return}if(e.stopped||n.client.configurationReady===!1){w.stop(),V(),pe(),T?.finish("skipped"),r.hidden=!0,qe();return}if(r.hidden=!1,w.active){qe();return}if(e.status==="completed"&&I?.subscriptionUpgradeActive){qe();return}let t=Se(e),o=n.client.view;if(o&&o.revision>e.revision&&Se(o)!==t)return;let h=!e.instruction&&!e.pendingRequest&&e.nodeType==="screen"&&["running","waiting"].includes(e.status);t!==we&&(we&&T?.finish("dismissed"),pe(),we=t,ce={...e.answers},je.reset());let Z=Xe(e);if(Ge===Z){r.hidden=!0;return}if(h&&!t){r.hidden=!0;let C=n.prepared?.state==="shown"?null:Ye(!0,e.locale);!l&&!te&&Qe?.key!==Z&&(un(),Qe={key:Z,timeout:setTimeout(()=>{let d=n.client.view;if(l||!C?.active&&n.prepared?.state!=="shown"||!d||Xe(d)!==Z)return;Ge=Z;let q=new Error("Funnel screen preparation timed out");C?.finish("error",q),V(),pe(),Y(q)},He)}),qe();return}un();let _=C=>{let d=n.client.view;return!l&&!te&&!Re&&!C.aborted&&n.client.configurationReady!==!1&&!!d&&!d.stopped&&!["closed","ineligible","failed"].includes(d.status)&&(Se(d)===t||d.status==="completed"&&I?.subscriptionUpgradeActive===!0)},fe=(C,d)=>{_(d)&&(Ge=t,T?.finish("error",C),pe(),r.hidden=!0,Y(C))};if(t||((e.instruction&&e.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(e.status))&&V(),Ke(e),e.instruction?.type!=="event"&&e.instruction?.type!=="open_url"&&T?.finish("skipped")),e.screen){Je=void 0,V();let C=e.screen.content;if(!ae){let J=e.screen.presentation.type!=="inline",b=Ye(J,e.locale);if(l||te)return;let x=(Ae=new AbortController).signal;Ke(e),_e=J?Nn(F):tn(r,i),ae=L(S,{mode:"live",closeActions:Array.from(new Set([...n.closeActions??[],...C.document.actions.filter(y=>y.type==="event"&&y.close).map(y=>y.id)])),onAuthoredClose(y){_(x)&&(ve=y,ye())},rendererUrl:n.client.webViewUrl,title:C.document.name,...J?{hostPresentation:()=>v?.type??e.screen.presentation.type}:{},onResize:y=>{Ce=y,v?.responsive&&v.setContentHeight(y+A.getBoundingClientRect().height)},onAction(y,c={},Fe={}){if(w.active||!_(x)||ee!==t)return;ce={...ce,...Fe};let cn=e.screen?.inputs??[],Fn=Object.fromEntries(cn.filter(({variable:Le})=>Object.hasOwn(ce,Le)).map(({variable:Le})=>[Le,ce[Le]]));if(xn(cn,Fn).length){Cn();return}Oe(()=>n.client.submit({operation:"submit",...ke(),input:{type:"screen",output:y,answers:Fn,selection:c}}),!1,Le=>$n(Le,cn))},onAnswers:y=>{w.active||!_(x)||ee!==t||(ce={...ce,...y})},onCustomerDataIntent:y=>{w.active||!_(x)||ee!==t||je.intent(y).catch(Y)},onEscape:()=>{!_(x)||ee!==t||w.active||ie||$||ge()},onError:y=>{let c=new Error(y);ee===t?Y(c):fe(c,x)},onRendered:y=>{if(!(!_(x)||ee===t))try{b.present(c=>{_e?.(),_e=void 0,y&&(Te={screen:C.document.name,label:y},F.setAttribute("aria-label",y)),J&&(F.showModal(),s=!1,v?.responsive&&F.focus({preventScroll:!0}),!c&&n.loading!=="host"&&qn(F,v?.type??e.screen.presentation.type,v?.responsive)),ee=t,Pe=J,ye()}),_(x)&&Ve.report(t)}catch(c){fe(c,x)}}}),Rn()}let d={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:ce,values:e.screen.values}},q=JSON.stringify([C,e.locale,d.parameters,e.screen.inputs,e.screen.values]);if(q!==xe)ae.update(C.document,e.locale,d),xe=q,rn=JSON.stringify(d.capabilities),ze=JSON.stringify(d.customerData);else{let J=JSON.stringify(d.capabilities);J!==rn&&(ae.updateCapabilities(d.capabilities),rn=J),JSON.stringify(d.customerData)!==ze&&(ae.updateCustomerData(d.customerData),ze=JSON.stringify(d.customerData))}let G=ae;if(G)try{await(T?.wait(G.ready)??G.ready)}catch(J){Ae&&fe(J,Ae.signal)}}else if(e.paywall&&!I){let C=e.paywall.resolution,d="document"in C?C.document:null,q=p,G=n.mountPaywallControls,J=null,b=(Ae=new AbortController).signal,x={loading:"host",signal:b,...G&&{mountControls:c=>G(c,e)},canInteract:()=>_(b)&&!w.active&&!ie&&!$,beforeAction:async()=>{X++;try{await bn(Ve.settled()),W.hidden=!0,Ee=null,De=!1,be()}finally{X=Math.max(0,X-1)}},start:()=>wn(n.client),onObservationChange:qe,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:c=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:c,openIn:"same_window"}):u.defaultView?.location.assign(c),onAction:async c=>{if(w.active)return;let Fe=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:c,answers:{}}});await se(n.client.view??Fe.run)},onError:c=>{ee===t?Y(c):fe(c,b)}},y={quoteError:c=>Ie(n.onError,c),loadingLayout:()=>_(b)?J?.getLoadingLayout?.():void 0,present(c){_(b)&&(J?.present(Fe=>{c(Fe),ee=t,Pe=y.retainedDialog?.dialog.open??!!S.querySelector("dialog[open]"),Pe&&(s=!1),ye()}),_(b)&&Ve.report(t))},async closeAction(c){l||w.active||await re.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:c,answers:{}}})},async dismiss(){if(l||b.aborted||w.active||ie||$||!ue&&!_(b))return;ue=!0;let c=n.client.view;if(c?.status==="completed"&&I?.subscriptionUpgradeActive){Ue.add(`complete:${c.id}`),Ie(n.onComplete,structuredClone(c)),B();return}if((n.resumeCheckout||n.terminateCheckout)&&Kn()){le=n.client.view,B();return}await ge()}};if(q&&G)V();else if(q){let c=await q.adopt(e,{options:x,handoff:y,start:()=>wn(n.client)});c&&_(b)&&!l?(Ke(e),I=c,Ne={runId:e.id,receiptId:e.paywall.receiptId},T?.active&&T.present(()=>{}),ee=t,Pe=q.modal,Pe&&(s=!1),ye(),Ve.report(t),w.active&&I.setSuspended(!0)):(c?.destroy(),V())}if(l||te)return;if(!I){if(J=Ye(!0,e.locale,d),l||te)return;(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.loading==="host"&&Je?.ownerDocument===u&&(y.hostPaywallTarget=Je),Je=void 0,Ke(e);let c=await H(S,x,y).catch(Fe=>(fe(Fe,b),null));!_(b)&&!(ue&&!l&&!b.aborted)?c?.host?.destroy():c&&(I=c.host,I&&(Ne={runId:e.id,receiptId:e.paywall.receiptId}),I?.setSuspended(w.active))}}if(l||te)return;ye();let m=e.instruction;if(m&&(m.type==="open_url"||m.type==="event")&&!Ue.has(m.receiptId)){let C=u.createElement("button");C.type="button",C.style.cssText=z.primary,$e(C,()=>z.focus),S.style.cssText=z.stage,C.textContent=m.type==="open_url"?`${R?"前往":"Continue to"} ${new URL(m.url).host}`:R?"继续":"Continue",C.onclick=()=>{let d=ke(),q=m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="new_window"?Xn(m.url):null;Oe(async()=>{let G="success";if(m.type==="open_url")if(n.onOpenUrl)try{G=await n.onOpenUrl({receiptId:m.receiptId,url:m.url,openIn:m.openIn})===!1?"failed":"opened"}catch(b){Ie(n.onError,b),G="failed"}else G=m.openIn==="new_window"&&!q?"failed":"opened";if(m.type==="event"){if(!n.onEvent)throw new ne("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(m.event)}if(l||n.client.view?.nodeId!==d.nodeId||n.client.view.visit!==d.visit)throw new ne("PRECONDITION_FAILED","The client action visit changed");let J=await n.client.submit({operation:"submit",...d,input:{type:"client_action",receiptId:m.receiptId,outcome:G}});return Ue.add(m.receiptId),m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="same_window"&&u.defaultView?.location.assign(m.url),J})},T?.active?T.present(()=>S.replaceChildren(C)):S.replaceChildren(C)}!e.pendingRequest&&e.status==="completed"&&!Ue.has(`complete:${e.id}`)&&(Ue.add(`complete:${e.id}`),Ie(n.onComplete,structuredClone(e))),qe()}function Xn(e){let t=u.defaultView?.open(e,"_blank")??null;return t&&(t.opener=null),t}function se(e){return ye(),sn=sn.catch(()=>{}).then(async()=>{try{await jn(e)}catch(t){throw T?.active&&(Ge=Xe(e),T.finish("error",t),pe(),r.hidden=!0),t}}),sn}let Yn=n.client.subscribe(e=>{if(!hn){if(e.stopped&&(Pe||D())&&!ue){le=e,B();return}!ue&&(e.stopped||n.client.configurationReady===!1||we&&ee!==we&&(Se(e)!==we||["closed","ineligible","failed"].includes(e.status)))&&(pe(),T?.finish("dismissed"),r.hidden=!0),se(e).catch(Y)}}),Zn=n.client.subscribeError?.(e=>{re.pending||Y(e)});function Kn(){let e=n.client.view,t=e?.paywall;return!!t?.operation&&!!e&&["running","waiting"].includes(e.status)&&Dn(pn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect}))}function ge(e){if(Re)return Re;if(l||!e&&(ie||$))return Promise.resolve();let t=!e&&We();return!t&&n.client.view&&!["running","waiting"].includes(n.client.view.status)?(le=n.client.view,B(),Promise.resolve()):(Re=Oe(async()=>{let o=t?await n.client.retry():await(e?n.client.submit.bind(n.client):re.submit)({operation:"close",...e??ke()});return e&&In(o),o},!0).then(()=>{let o=n.client.view;o?.status==="closed"&&!We()&&(le=o,B())}).finally(()=>{Re=null}),Re)}function B(){En()}function En(e){oe?.destroy(),!l&&(l=!0,re.destroy(),k(),V(),n.signal?.removeEventListener("abort",B),a?.removeEventListener("abort",B),T?.finish("dismissed"),an.destroy(),Yn(),Zn?.(),pe(e),Ze(),w.stop(),F.remove(),!e||!r.contains(e)?r.remove():(A.remove(),de.remove()),!e&&!s&&P(),Ie(n.onDismiss,le?structuredClone(le):null))}O.onclick=()=>{if(!O.disabled){if(w.active){w.exit();return}Oe(()=>n.client.submit({operation:"back",...ke()}))}},N.onclick=()=>{w.open()},g.onclick=()=>{T?.active?T.dismiss():ie||ge()},j.onclick=()=>{re.pending?re.retry().catch(()=>{}):We()?ge():Oe(()=>n.client.retry())},F.addEventListener("cancel",e=>{e.preventDefault(),T?.active?T.dismiss():ie||ge()}),n.signal?.addEventListener("abort",B,{once:!0}),a?.addEventListener("abort",B,{once:!0});let en=!1;p&&(k=p.onClose(()=>{l||te||(te=!0,T?.finish("dismissed"),pe(),r.hidden=!0,n.client.view?ge().finally(B):en=!0)}));let kn={destroy:B,refresh:dn,get recoveryPaywall(){if(I&&Ne)return{...Ne,view:I.currentResolution}},setPurchaseRecovery(e,t){return I?.setPurchaseRecovery(e,t),I!==null},retainPurchaseDialog(){let e=I?.retainPurchaseDialog();if(e)return I=null,En(e.dialog),{dialog:e.dialog,release(){e.release(),r.remove(),s||P()}}},get recovery(){let e=ln();if(e)return e;if(!l&&!X&&!ue&&!ie&&I){let t=I.recovery;if(t.type!=="native")return t}return{type:"recover",operationId:n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??$?.operationId??null,requestId:n.client.pendingCommand?.requestId??null}},prepareFallback(){if(ie)return ie;let e=ln();if(e)return Promise.resolve(e);let t=n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??$?.operationId??null,o=()=>({type:"recover",operationId:t,requestId:n.client.pendingCommand?.requestId??null});if(n.client.hasDurableJournal!==!0){let m=I?.recovery;return Promise.resolve(m&&m.type!=="native"&&m.type!=="cancel"?m:o())}let h=(n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[])).some(m=>m.operation==="close");if(l&&!(h||$&&n.client.view?.status==="closed")||X||Be||Re||w.active||!I&&!$&&!h)return Promise.resolve(o());let Z=I,_=(async()=>{try{if(!$&&h){let d=await n.client.retry();return await se(n.client.view??d.run),o()}if(!$){let d=await Z.prepareFallback();if(d.type!=="native")return d;if(n.client.hasDurableJournal!==!0)return o();$=d}let m=n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[]);if(m.length){let d=m.find(G=>G.operation==="close");if(!d||!M||d.requestId!==M.requestId)return o();let q=await n.client.retry();In(q),await se(n.client.view??q.run)}else{let d=n.client.view,q=d?.paywall;if(!d||!q||q.selectionGeneration===void 0||(q.quote?.operationId??null)!==$.operationId||$.operationId!==null&&q.canReselect!==!0)return o();let G=q.selectionGeneration,J=await n.client.get();await se(n.client.view??J.run);let b=n.client.view,x=b?.paywall;if(!b||!x||!["running","waiting"].includes(b.status)||b.stopped||b.id!==d.id||b.nodeId!==d.nodeId||b.visit!==d.visit||x.receiptId!==q.receiptId||x.selectionGeneration!==G||(x.quote?.operationId??null)!==$.operationId||$.operationId!==null&&x.canReselect!==!0||n.client.pendingPurchase||(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0)))return o();let y=ke();M={runId:b.id,operationId:$.operationId,revision:y.revision,requestId:y.requestId,nodeId:b.nodeId,visit:b.visit,receiptId:x.receiptId,selectionGeneration:G,acknowledged:!1},await ge(y)}let C=ln();return C?(B(),C):o()}catch(m){return Y(m),o()}})();ie=_;let fe=()=>{ie===_&&(ie=null)};return _.then(fe,fe),_},review:w.open,exitReview:w.exit,get unappliedDrafts(){return w.drafts}};try{let e=n.client.view;if(e)((n.client.viewAgeMs??yn)>=yn||e.instruction?.type==="evaluate_segment")&&(on=dn().finally(()=>{on=null})),await se(e);else{if(r.hidden=!0,l)throw new DOMException("Presentation cancelled","AbortError");let t=en||n.prepared?.state==="shown"?null:Ye(n.client.view?.screen?.presentation.type!=="inline",n.client.view?.locale);if(l||te&&!en)throw new DOMException("Presentation cancelled","AbortError");let o=n.client.get(),h=await(t?t.wait(o,He):nt(o,He));if(hn=!1,en)return l||await ge().finally(B),kn;await se(n.client.view??h.run)}}catch(e){throw T?.finish("error",e),B(),e}return kn}function nt(i,E){let U;return Promise.race([i,new Promise((n,p)=>{U=setTimeout(()=>p(new Error("Presentation data timed out")),E)})]).finally(()=>clearTimeout(U))}function St(i,E,U){return et(i,E,U)}export{et as a,St as b};
1
+ import{b as Bn}from"./chunk-PTNMDAND.js";import{a as wn}from"./chunk-R4CYPCBI.js";import{a as _n,b as Un,c as fn,d as mn,e as $e,f as Vn,h as $n,i as Mn,j as xn,k as zn}from"./chunk-IMFPRZUY.js";import{a as Jn}from"./chunk-45PGU2HW.js";import{a as Sn}from"./chunk-W32FI2A2.js";import{c as On,e as qn,f as Ln,i as Hn,j as He,k as nn,l as Nn,m as tn}from"./chunk-J5K4PNII.js";import{b as An}from"./chunk-ZCJEXNJD.js";import{a as pn,d as Dn}from"./chunk-NDNHTG5B.js";import{C as Tn}from"./chunk-ZRGL2CAP.js";import{a as ne}from"./chunk-TK3WOD2O.js";import{a as Ie}from"./chunk-DSPLGTQI.js";function Gn(i){let E=new Set,U=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 ne("COMMAND_PENDING","The original display acknowledgement is still pending");await i.client.settle(f),L=!0,i.client.pendingCommand?.requestId===f&&await new Promise(H=>setTimeout(H,1500))}i.stopped||i.key!==a||(L&&await i.client.get(),!(i.stopped||i.key!==a)&&E.add(a))}function k(a,f){n=f;let L=()=>{n===f&&(n=null),U.delete(a)};return f.then(L,H=>{L(),i.busy||i.fail(H)}),f}function V(a){if(i.reviewing||E.has(a)||U.has(a)||i.stopped)return;U.add(a);let f=async()=>{if(i.reviewing||i.stopped||i.key!==a||E.has(a)){U.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 H=i.client.view,oe=i.expected(),u=oe.requestId;try{await i.client.submit({operation:"shown",...oe})}catch(P){if(!(P instanceof ne)||P.code!=="CONFLICT"||P.status!==409||i.client.pendingCommand)throw P;await i.client.get();let s=i.client.view;if(i.stopped||i.reviewing||i.key!==a||!s||!H||s.id!==H.id||s.source.versionId!==H.source.versionId||s.nodeId!==oe.nodeId||s.visit!==oe.visit||s.revision<=oe.revision||s.stopped||!s.screen&&(!s.paywall||s.paywall.receiptId!==H.paywall?.receiptId)||!["running","waiting"].includes(s.status)||i.client.pendingCommand)throw P;let r=i.expected();u=r.requestId,await i.client.submit({operation:"shown",...r})}await p(a,u)})();k(a,L)};f()}function D(){if(n)return n;let a=i.client.pendingCommand;if(a?.operation!=="shown")return null;let f=i.key;return U.add(f),k(f,(async()=>{await i.client.retry(),await p(f,a.requestId)})())}return{report:V,settled:D,get inFlight(){return n}}}function Qn(i){let E={},U=new Map;async function n(p){let k=i.client.view,V=k?.screen,D=V?.customerData.nodes[p.nodeId];if(i.stopped||i.busy||!k||!V||!D)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(p.action)){let P=i.document,s=P?Tn(P,p.nodeId):null,r=s?.type==="customer_data"?s.data.outputs?.[p.action]:void 0;r&&V.outputs.includes(r)?await i.perform(()=>i.client.submit({operation:"submit",...i.expected(),input:{type:"screen",output:r,answers:i.answers,selection:p.value?{[p.nodeId]:p.value}:{}}})):await i.onIntent?.(p,k);return}let f=p.action.startsWith("sources_")?D.resources.find(P=>P.key===p.value):null;if(p.action.startsWith("sources_")&&!f)throw new ne("INVALID_REQUEST","Choose a current resource");let L=`${k.visit}:${p.nodeId}:${f?.key??""}`,H=U.get(L)??[null],u=E[p.nodeId]??{page:1,after:null,filter:"all",...f?{resourceKey:f.key}:{}};if(p.action==="filter"){let P=p.value;if(!P||!(D.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(P))throw new ne("INVALID_REQUEST","Unknown data filter");u={page:1,after:null,filter:P},H.splice(0,H.length,null)}else if(p.action==="next"||p.action==="sources_next"){let P=f?.sources.at(-1),s=f?P?{kind:"ledger",cursor:{at:P.detail[0],id:P.id,type:"source"}}:null:V.dataCursors[p.nodeId];if(!s||!f&&!D.hasNext)return;H[u.page]=s,u={...u,page:u.page+1,after:s}}else if(p.action==="previous"||p.action==="sources_previous"){if(u.page<=1)return;u={...u,page:u.page-1,after:H[u.page-2]??null}}U.set(L,H),E={...E,[p.nodeId]:u},await i.perform(()=>i.client.get({nodeId:k.nodeId,visit:k.visit,revision:k.revision,components:E}))}return{get queries(){return E},intent:n,reset(){E={},U.clear()}}}function Wn(i){let{doc:E,holder:U,reviewHolder:n,mountScreenPreview:p}=i,k=!1,V,D=0,a=null,f="",L,H=new Map,oe=s=>s?`${s.id}:${s.nodeId}:${s.visit}:${s.revision}:${s.paywall?.quote?.operationId??""}`:"";async function u(s){if(i.stopped||!i.client.review||k&&s===V&&L?.active)return;let r=!k||s!==V;k||(f=oe(i.client.view),H.set(f,structuredClone(i.answers))),k=!0,V=s,U.hidden=!0,i.suspend(!0),n.hidden=!1;let S=++D;r&&(L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),L=nn(n,i.loadingOptions,"funnel",()=>{P()}));let A=r?L:void 0;try{if(A?.start(!1,i.client.view?.locale),S!==D||i.stopped)return;let de=i.client.review(s),N=await(A?.wait(de,He)??de);if(i.stopped||S!==D||!k)return;if(!N.review)throw new ne("INVALID_RESPONSE","Historical projection is missing");a?.destroy(),a=null,A||n.replaceChildren();let Q=E.createElement("div"),W=A?tn(Q,n):()=>{};n.append(Q);let O=N.run.locale.startsWith("zh"),g=i.chrome;Q.style.cssText=g.history;let j=E.createElement("p");j.textContent=O?"只读回看":"Read-only history",j.style.cssText=g.historyTitle,Q.append(j);let F=E.createElement("p");F.style.cssText=g.historyNote,F.textContent=N.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.",Q.append(F);let Te=N.review.page?.receiptId,ve=E.createElement("div");ve.style.cssText=g.historyPages;for(let[K,R]of N.review.pages.entries()){let v=E.createElement("button");v.type="button",v.textContent=O?`第 ${K+1} 页`:`Page ${K+1}`;let he=Te!==void 0&&R.receiptId===Te;v.style.cssText=he?g.primary:g.secondary,he&&v.setAttribute("aria-current","page"),$e(v,()=>i.chrome.focus),v.onclick=()=>{u(R.receiptId)},ve.append(v)}if(ve.childElementCount&&Q.append(ve),N.review.page){let K=N.review.page,R=E.createElement("div");R.inert=!0,R.style.cssText=g.historyPage,Q.append(R),a=p(R,{mode:"live",rendererUrl:i.client.webViewUrl,title:K.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{S===D&&!i.stopped&&A?.present(W)},onError:he=>{if(S!==D||i.stopped)return;let Ce=new Error(he);A?.finish("error",Ce),a?.destroy(),a=null,Q.remove(),i.fail(Ce)},onEscape:()=>{P()}});let v=a;if(v.update(K.document,N.run.locale,{serverInput:{bindings:K.inputs,answers:K.answers,values:K.values}}),await v.ready,i.stopped||S!==D||!k)return}let me=O?{issued:"已领取",reserved:"已预留",redeemed:"已使用",expired:"已过期",revoked:"已撤销",unknown:"状态待确认"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},z=E.createElement("div");z.style.cssText=g.historyRecords;for(let K of[...N.review.coupons.map((R,v)=>`${O?"优惠券":"Coupon"} ${v+1}: ${me[R.status]}`),...N.review.purchases.map((R,v)=>`${O?"购买":"Purchase"} ${v+1}: ${zn(R.status,O)}`)]){let R=E.createElement("p");R.textContent=K,R.style.margin="0",z.append(R)}z.childElementCount&&Q.append(z),N.review.page||A?.present(W),i.client.view&&await i.enqueue(i.client.view)}catch(de){if(S!==D||i.stopped)return;A?.finish("error",de),a?.destroy(),a=null,n.replaceChildren(),i.fail(de)}}async function P(){if(!k||i.stopped||!i.client.review)return;let s=++D;L?.finish("dismissed");try{if(await i.client.review(),i.stopped||s!==D)return;k=!1,D++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,U.hidden=!1;let r=i.client.view;oe(r)!==f?(H.set(f,structuredClone(i.answers)),i.resetScreen()):(H.delete(f),i.suspend(!1)),r&&await i.enqueue(r)}catch(r){if(s!==D||i.stopped)return;a?.destroy(),a=null,n.replaceChildren(),i.fail(r)}}return{get active(){return k},get receipt(){return V},open:u,exit:P,get drafts(){return new Map([...H].map(([s,r])=>[s,structuredClone(r)]))},stop(){k=!1,D++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,U.hidden=!1}}}var yn=5e3;async function et(i,E,U){let n=E,p=n.prepared&&Bn(n.prepared),k=()=>{};function V(){n.prepared&&n.prepared.state!=="adopted"&&p?.release()}let D=()=>n.prepared?.state==="shown"&&!!p?.modal,a=n.client.identitySignal,f;try{f=await Promise.all([import("./screen-renderer-2ZDV2WYD.js"),import("./paywall-KQIBPACY.js")]),n.signal?.throwIfAborted(),a?.throwIfAborted()}catch(e){throw V(),e}let[{mountScreenPreview:L},{showPaywall:H}]=f,oe=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.appManifestRelease?Jn({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;oe?.start();let u=i.ownerDocument,P=Hn(u),s=!1,r=u.createElement("section"),S=u.createElement("div"),A=u.createElement("div"),de=u.createElement("div"),N=u.createElement("button");de.hidden=!0,N.type="button";let Q=u.createElement("p"),W=u.createElement("p"),O=u.createElement("button"),g=u.createElement("button"),j=u.createElement("button"),F=u.createElement("dialog"),Te,ve=!1;r.dataset.indianaFunnel="",r.dataset.longplayCloseOwner="sdk",r.setAttribute("aria-busy","false"),Q.setAttribute("role","status"),W.setAttribute("role","alert"),W.hidden=!0,O.type=g.type=j.type="button",A.append(O,N,Q,W,j,g),r.append(S,de,A),i.append(r);let me=Un,z=fn(me),K="",R=(u.documentElement.lang||"").startsWith("zh"),v,he="",Ce;for(let e of[O,N,j,g])$e(e,()=>z.focus);function gn(){let e=R?"关闭":"Close";g.parentElement===F?(g.textContent="×",g.setAttribute("aria-label",e),Ln(g,me)):(g.textContent=e,g.removeAttribute("aria-label"),g.style.cssText=z.link+";margin-inline-start:auto")}function Me(e){let t=e?.screen?.content.document.theme??me,o=JSON.stringify([t.primary,t.background,t.text,t.radius,t.font,g.parentElement===F]);if(o===K)return;K=o,me=t;let h=g.parentElement===F;z=fn(me,h),r.style.cssText=z.root+";min-width:0"+(h?";display:flex;flex-direction:column;min-height:100%":""),A.style.cssText=z.bar+(h?";margin-top:auto":""),A.hidden&&(A.style.display="none"),O.style.cssText=N.style.cssText=z.secondary,j.style.cssText=z.primary,Q.style.cssText=z.status,W.style.cssText=z.alert,gn(),mn(O)}function be(){A.hidden=O.hidden&&N.hidden&&j.hidden&&W.hidden&&!Q.textContent&&(g.hidden||g.parentElement!==A),A.style.display=A.hidden?"none":"flex",v?.responsive&&Ce!==void 0&&v.setContentHeight(Ce+A.getBoundingClientRect().height)}Me();let ae=null,I=null,le=null,we="",ee="",Pe=!1,xe="",rn="",ze="",l=!1,X=0,Be=!1,vn="",on=null,sn=Promise.resolve(),hn=!n.client.view,Ne,T=U,Je=n.hostPaywallTarget,Ae,_e,Ge="",Qe,te=!1,Re=null,ue=!1,We=()=>n.client.pendingCommand?.operation==="close",ie=null,$=null,an=Sn({document:u,run:async()=>{(!I?.observing||n.client.pendingCommand)&&await dn()},delay:()=>{if(!re.pending&&!(l||!le||!["running","waiting"].includes(le.status)&&!n.client.pendingCommand)&&!(I?.observing&&!n.client.pendingCommand))return le.pendingRequest||n.client.pendingCommand?1500:yn},hiddenDelay:()=>!l&&!re.pending&&n.client.pendingCommand?15e3:void 0}),M=null;function ln(){return $&&n.client.hasDurableJournal===!0&&M?.acknowledged===!0&&M.operationId===$.operationId&&n.client.view?.id===M.runId&&n.client.view?.status==="closed"&&n.client.view.revision===M.revision+1&&!(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0))&&!n.client.pendingPurchase?$:null}function In(e){let t=e.run.paywall;if(M&&e.settlement?.requestId===M.requestId&&e.settlement.state==="settled"&&e.settlement.operationId===null&&e.run.id===M.runId&&e.run.status==="closed"&&!e.run.pendingRequest&&e.run.revision===M.revision+1&&e.run.nodeId===M.nodeId&&e.run.visit===M.visit&&t?.receiptId===M.receiptId&&t.selectionGeneration===M.selectionGeneration&&(t.quote?.operationId??null)===M.operationId&&(t.operation?.operationId??t.quote?.operationId??null)===M.operationId){let o=M.operationId===null&&t.selectionGeneration===0&&!t.quote&&!t.operation&&!t.purchaseRequestId,h=pn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect});(o||t.canReselect===!0&&h.type==="native")&&(M.acknowledged=!0)}}let Ee=null,Ue=new Set,ce={},De=!1,Y=(e,t=null)=>{l||(e instanceof ne&&e.status===409&&e.reason==="STATE_CHANGED"&&e.recovery==="recover_operation"&&an.destroy(),Ee=t,De=!1,W.textContent=Vn(e,R),W.hidden=!1,j.hidden=n.client.pendingCommand===null,be(),Ie(n.onError,e))},re=An({client:n.client,document:u,conceal(){l||(pe(),T?.finish("dismissed"),r.hidden=!0,s||(s=!0,P()))},async receive(e){l||await se(n.client.view??e.run)},failed(e){if(!l){if(!re.pending){ue=!1;let t=n.client.view;t&&se(t).then(()=>Y(e),Y);return}Ze(),r.parentElement!==i&&i.append(r),r.hidden=!1,O.hidden=N.hidden=g.hidden=!0,Q.textContent="",Me(),Y(e,n.client.pendingCommand?.requestId??null)}}}),Cn=()=>{l||(Ee=null,W.textContent=Mn(R),W.hidden=!1,j.hidden=!0,be())};function ke(){let e=n.client.view;if(!e)throw new ne("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}let w=Wn({client:n.client,doc:u,holder:S,reviewHolder:de,mountScreenPreview:L,loadingOptions:n,get chrome(){return z},get stopped(){return l},get answers(){return ce},suspend(e){I?.setSuspended(e)},resetScreen(){we="",ee="",xe=""},enqueue:se,fail:Y}),Ve=Gn({client:n.client,expected:ke,fail:Y,get stopped(){return l},get reviewing(){return w.active},get key(){return we},get busy(){return X},get staleRead(){return on}}),je=Qn({client:n.client,expected:ke,perform:Oe,onIntent:n.onCustomerDataIntent,get stopped(){return l},get busy(){return X},get document(){return ae?.document},get answers(){return ce}}),Xe=e=>`${e.id}:${e.nodeId}:${e.visit}`,Se=e=>e&&(e.screen||e.paywall)?Xe(e):"";function ye(){let e=n.client.view;O.disabled=!w.active&&(X>0||!!n.client.pendingCommand||!e?.canBack||e.stopped||!["running","waiting"].includes(e.status)||!Se(e)||ee!==Se(e)),O.hidden=!w.active&&!e?.canBack,mn(O);let t=!!I&&!w.active;g.hidden=t&&!T?.active||ve&&!w.active,N.hidden=!n.client.review||!w.active&&!e?.canBack;let o=e?.locale.startsWith("zh");Q.textContent=t?"":X>0||e?.pendingRequest?o?"正在处理":"Processing":e?.instruction?.type==="wait"?o?"等待中":"Waiting":"",be()}async function bn(e){if(!e)return;let t=n.client.view;await e;let o=n.client.view;if(!t||!o||o.id!==t.id||o.nodeId!==t.nodeId||o.visit!==t.visit||o.stopped||!["running","waiting"].includes(o.status))throw new ne("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Oe(e,t=!1,o){if(!((X||ue||ie||$)&&!t||l||w.active&&!t)){X++,r.setAttribute("aria-busy","true"),W.hidden=!0,Ee=null,De=!1,ye();try{if(t||await bn(Ve.inFlight),l)return;let h=await e();l||await se(n.client.view??h.run)}catch(h){o?.(h)&&n.client.pendingCommand===null?Cn():re.pending||Y(h,n.client.pendingCommand?.requestId??null)}finally{X=Math.max(0,X-1),r.setAttribute("aria-busy",String(X>0)),l||(j.hidden=n.client.pendingCommand===null,ye())}}}function qe(){an.schedule()}async function dn(){if(!(l||Be||X)&&!re.pending){if(w.active){await w.open(w.receipt);return}Be=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let t=n.client.view,o=je.queries,h=await n.client.get(t?.screen&&Object.keys(o).length?{nodeId:t.nodeId,visit:t.visit,revision:t.revision,components:o}:void 0);De&&!l&&(De=!1,W.hidden=!0,be()),!l&&o===je.queries&&await se(n.client.view??h.run)}catch(e){Y(e),De=!l}finally{Be=!1}}}function Ye(e,t,o){if(T?.active){let Z=T;return Z.setDismissHandler(()=>Pn(Z)),Z}let h=nn(i,n,"funnel",()=>Pn(h),_n);return T=h,h.start(e,t,o),h}function Pn(e){l||te||(te=!0,e.finish("dismissed"),pe(),r.hidden=!0,n.client.view?ge().finally(B):B())}function un(){clearTimeout(Qe?.timeout),Qe=void 0}function pe(e){ve=!1,un(),Ae?.abort(),Ae=void 0,ae?.destroy(),ae=null,I?.destroy(),I=null,Ne=void 0,_e?.(),_e=void 0,F.open&&F.close();for(let t of Array.from(S.children))(!e||!t.contains(e))&&t.remove();S.style.cssText="",Ce=void 0,we="",ee="",Pe=!1,xe="",ze=""}function Rn(){let e=u.defaultView;v?.responsive&&e&&ae?.resizeViewport?.(e.innerHeight,e.innerWidth)}function Ze(){v?.destroy(),v=void 0,he=""}function Ke(e){let t=e.screen?.presentation;if(!t||t.type==="inline"){F.open&&F.close(),Ze(),g.parentElement!==A&&A.append(g),r.parentElement!==i&&i.append(r);for(let Z of["flex","display","flex-direction","justify-content"])S.style.removeProperty(Z);Me(e),be();return}r.parentElement!==F&&(F.append(g,r),i.append(F)),S.style.flex="1 0 auto",S.style.display="flex",S.style.flexDirection="column",S.style.justifyContent="center",Me(e);let o=e.screen.content.document,h=JSON.stringify([t,K]);if(h!==he){Ze(),he=h;let Z={sm:420,md:640,lg:900},fe="size"in t&&!t.backdrop?",0 0 0 100vmax #16142566":"";F.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${me.background};color:${me.text};`+(t.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${Z[t.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${fe};`+(t.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),v=On(F,{presentation:t,theme:o.theme,pages:o.pages},Rn),v.latch()}be(),F.setAttribute("aria-label",(Te?.screen===e.screen?.content.document.name?Te?.label:void 0)??ae?.document?.name??e.screen?.content.document.name??"Funnel")}async function jn(e){if(l||te)return;if(re.observe(),re.pending){le=e;return}if(ue&&(We()||["running","waiting"].includes(e.status))||(le=e,Ee&&n.client.pendingCommand?.requestId!==Ee&&(W.hidden=!0,Ee=null),R=e.locale.startsWith("zh"),N.textContent=R?"回看":"History",O.textContent=w.active?R?"返回当前":"Return to current":R?"返回":"Back",gn(),j.textContent=R?"重试":"Retry",j.hidden=n.client.pendingCommand===null,ye(),vn!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(vn=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,Ie(n.onState,structuredClone(e))),l||te))return;if((!e.pendingRequest||ue&&e.status==="closed")&&["closed","ineligible","failed"].includes(e.status)){B();return}if(e.stopped&&D()){B();return}if(e.stopped||n.client.configurationReady===!1){w.stop(),V(),pe(),T?.finish("skipped"),r.hidden=!0,qe();return}if(r.hidden=!1,w.active){qe();return}if(e.status==="completed"&&I?.subscriptionUpgradeActive){qe();return}let t=Se(e),o=n.client.view;if(o&&o.revision>e.revision&&Se(o)!==t)return;let h=!e.instruction&&!e.pendingRequest&&e.nodeType==="screen"&&["running","waiting"].includes(e.status);t!==we&&(we&&T?.finish("dismissed"),pe(),we=t,ce={...e.answers},je.reset());let Z=Xe(e);if(Ge===Z){r.hidden=!0;return}if(h&&!t){r.hidden=!0;let C=n.prepared?.state==="shown"?null:Ye(!0,e.locale);!l&&!te&&Qe?.key!==Z&&(un(),Qe={key:Z,timeout:setTimeout(()=>{let d=n.client.view;if(l||!C?.active&&n.prepared?.state!=="shown"||!d||Xe(d)!==Z)return;Ge=Z;let q=new Error("Funnel screen preparation timed out");C?.finish("error",q),V(),pe(),Y(q)},He)}),qe();return}un();let _=C=>{let d=n.client.view;return!l&&!te&&!Re&&!C.aborted&&n.client.configurationReady!==!1&&!!d&&!d.stopped&&!["closed","ineligible","failed"].includes(d.status)&&(Se(d)===t||d.status==="completed"&&I?.subscriptionUpgradeActive===!0)},fe=(C,d)=>{_(d)&&(Ge=t,T?.finish("error",C),pe(),r.hidden=!0,Y(C))};if(t||((e.instruction&&e.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(e.status))&&V(),Ke(e),e.instruction?.type!=="event"&&e.instruction?.type!=="open_url"&&T?.finish("skipped")),e.screen){Je=void 0,V();let C=e.screen.content;if(!ae){let J=e.screen.presentation.type!=="inline",b=Ye(J,e.locale);if(l||te)return;let x=(Ae=new AbortController).signal;Ke(e),_e=J?Nn(F):tn(r,i),ae=L(S,{mode:"live",closeActions:Array.from(new Set([...n.closeActions??[],...C.document.actions.filter(y=>y.type==="event"&&y.close).map(y=>y.id)])),onAuthoredClose(y){_(x)&&(ve=y,ye())},rendererUrl:n.client.webViewUrl,title:C.document.name,...J?{hostPresentation:()=>v?.type??e.screen.presentation.type}:{},onResize:y=>{Ce=y,v?.responsive&&v.setContentHeight(y+A.getBoundingClientRect().height)},onAction(y,c={},Fe={}){if(w.active||!_(x)||ee!==t)return;ce={...ce,...Fe};let cn=e.screen?.inputs??[],Fn=Object.fromEntries(cn.filter(({variable:Le})=>Object.hasOwn(ce,Le)).map(({variable:Le})=>[Le,ce[Le]]));if(xn(cn,Fn).length){Cn();return}Oe(()=>n.client.submit({operation:"submit",...ke(),input:{type:"screen",output:y,answers:Fn,selection:c}}),!1,Le=>$n(Le,cn))},onAnswers:y=>{w.active||!_(x)||ee!==t||(ce={...ce,...y})},onCustomerDataIntent:y=>{w.active||!_(x)||ee!==t||je.intent(y).catch(Y)},onEscape:()=>{!_(x)||ee!==t||w.active||ie||$||ge()},onError:y=>{let c=new Error(y);ee===t?Y(c):fe(c,x)},onRendered:y=>{if(!(!_(x)||ee===t))try{b.present(c=>{_e?.(),_e=void 0,y&&(Te={screen:C.document.name,label:y},F.setAttribute("aria-label",y)),J&&(F.showModal(),s=!1,v?.responsive&&F.focus({preventScroll:!0}),!c&&n.loading!=="host"&&qn(F,v?.type??e.screen.presentation.type,v?.responsive)),ee=t,Pe=J,ye()}),_(x)&&Ve.report(t)}catch(c){fe(c,x)}}}),Rn()}let d={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:ce,values:e.screen.values}},q=JSON.stringify([C,e.locale,d.parameters,e.screen.inputs,e.screen.values]);if(q!==xe)ae.update(C.document,e.locale,d),xe=q,rn=JSON.stringify(d.capabilities),ze=JSON.stringify(d.customerData);else{let J=JSON.stringify(d.capabilities);J!==rn&&(ae.updateCapabilities(d.capabilities),rn=J),JSON.stringify(d.customerData)!==ze&&(ae.updateCustomerData(d.customerData),ze=JSON.stringify(d.customerData))}let G=ae;if(G)try{await(T?.wait(G.ready)??G.ready)}catch(J){Ae&&fe(J,Ae.signal)}}else if(e.paywall&&!I){let C=e.paywall.resolution,d="document"in C?C.document:null,q=p,G=n.mountPaywallControls,J=null,b=(Ae=new AbortController).signal,x={loading:"host",signal:b,...G&&{mountControls:c=>G(c,e)},canInteract:()=>_(b)&&!w.active&&!ie&&!$,beforeAction:async()=>{X++;try{await bn(Ve.settled()),W.hidden=!0,Ee=null,De=!1,be()}finally{X=Math.max(0,X-1)}},start:()=>wn(n.client),onObservationChange:qe,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:c=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:c,openIn:"same_window"}):u.defaultView?.location.assign(c),onAction:async c=>{if(w.active)return;let Fe=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:c,answers:{}}});await se(n.client.view??Fe.run)},onError:c=>{ee===t?Y(c):fe(c,b)}},y={quoteError:c=>Ie(n.onError,c),loadingLayout:()=>_(b)?J?.getLoadingLayout?.():void 0,present(c){_(b)&&(J?.present(Fe=>{c(Fe),ee=t,Pe=y.retainedDialog?.dialog.open??!!S.querySelector("dialog[open]"),Pe&&(s=!1),ye()}),_(b)&&Ve.report(t))},async closeAction(c){l||w.active||await re.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:c,answers:{}}})},async dismiss(){if(l||b.aborted||w.active||ie||$||!ue&&!_(b))return;ue=!0;let c=n.client.view;if(c?.status==="completed"&&I?.subscriptionUpgradeActive){Ue.add(`complete:${c.id}`),Ie(n.onComplete,structuredClone(c)),B();return}if((n.resumeCheckout||n.terminateCheckout)&&Kn()){le=n.client.view,B();return}await ge()}};if(q&&G)V();else if(q){let c=await q.adopt(e,{options:x,handoff:y,start:()=>wn(n.client)});c&&_(b)&&!l?(Ke(e),I=c,Ne={runId:e.id,receiptId:e.paywall.receiptId},T?.active&&T.present(()=>{}),ee=t,Pe=q.modal,Pe&&(s=!1),ye(),Ve.report(t),w.active&&I.setSuspended(!0)):(c?.destroy(),V())}if(l||te)return;if(!I){if(J=Ye(!0,e.locale,d),l||te)return;(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.loading==="host"&&Je?.ownerDocument===u&&(y.hostPaywallTarget=Je),Je=void 0,Ke(e);let c=await H(S,x,y).catch(Fe=>(fe(Fe,b),null));!_(b)&&!(ue&&!l&&!b.aborted)?c?.host?.destroy():c&&(I=c.host,I&&(Ne={runId:e.id,receiptId:e.paywall.receiptId}),I?.setSuspended(w.active))}}if(l||te)return;ye();let m=e.instruction;if(m&&(m.type==="open_url"||m.type==="event")&&!Ue.has(m.receiptId)){let C=u.createElement("button");C.type="button",C.style.cssText=z.primary,$e(C,()=>z.focus),S.style.cssText=z.stage,C.textContent=m.type==="open_url"?`${R?"前往":"Continue to"} ${new URL(m.url).host}`:R?"继续":"Continue",C.onclick=()=>{let d=ke(),q=m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="new_window"?Xn(m.url):null;Oe(async()=>{let G="success";if(m.type==="open_url")if(n.onOpenUrl)try{G=await n.onOpenUrl({receiptId:m.receiptId,url:m.url,openIn:m.openIn})===!1?"failed":"opened"}catch(b){Ie(n.onError,b),G="failed"}else G=m.openIn==="new_window"&&!q?"failed":"opened";if(m.type==="event"){if(!n.onEvent)throw new ne("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(m.event)}if(l||n.client.view?.nodeId!==d.nodeId||n.client.view.visit!==d.visit)throw new ne("PRECONDITION_FAILED","The client action visit changed");let J=await n.client.submit({operation:"submit",...d,input:{type:"client_action",receiptId:m.receiptId,outcome:G}});return Ue.add(m.receiptId),m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="same_window"&&u.defaultView?.location.assign(m.url),J})},T?.active?T.present(()=>S.replaceChildren(C)):S.replaceChildren(C)}!e.pendingRequest&&e.status==="completed"&&!Ue.has(`complete:${e.id}`)&&(Ue.add(`complete:${e.id}`),Ie(n.onComplete,structuredClone(e))),qe()}function Xn(e){let t=u.defaultView?.open(e,"_blank")??null;return t&&(t.opener=null),t}function se(e){return ye(),sn=sn.catch(()=>{}).then(async()=>{try{await jn(e)}catch(t){throw T?.active&&(Ge=Xe(e),T.finish("error",t),pe(),r.hidden=!0),t}}),sn}let Yn=n.client.subscribe(e=>{if(!hn){if(e.stopped&&(Pe||D())&&!ue){le=e,B();return}!ue&&(e.stopped||n.client.configurationReady===!1||we&&ee!==we&&(Se(e)!==we||["closed","ineligible","failed"].includes(e.status)))&&(pe(),T?.finish("dismissed"),r.hidden=!0),se(e).catch(Y)}}),Zn=n.client.subscribeError?.(e=>{re.pending||Y(e)});function Kn(){let e=n.client.view,t=e?.paywall;return!!t?.operation&&!!e&&["running","waiting"].includes(e.status)&&Dn(pn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect}))}function ge(e){if(Re)return Re;if(l||!e&&(ie||$))return Promise.resolve();let t=!e&&We();return!t&&n.client.view&&!["running","waiting"].includes(n.client.view.status)?(le=n.client.view,B(),Promise.resolve()):(Re=Oe(async()=>{let o=t?await n.client.retry():await(e?n.client.submit.bind(n.client):re.submit)({operation:"close",...e??ke()});return e&&In(o),o},!0).then(()=>{let o=n.client.view;o?.status==="closed"&&!We()&&(le=o,B())}).finally(()=>{Re=null}),Re)}function B(){En()}function En(e){oe?.destroy(),!l&&(l=!0,re.destroy(),k(),V(),n.signal?.removeEventListener("abort",B),a?.removeEventListener("abort",B),T?.finish("dismissed"),an.destroy(),Yn(),Zn?.(),pe(e),Ze(),w.stop(),F.remove(),!e||!r.contains(e)?r.remove():(A.remove(),de.remove()),!e&&!s&&P(),Ie(n.onDismiss,le?structuredClone(le):null))}O.onclick=()=>{if(!O.disabled){if(w.active){w.exit();return}Oe(()=>n.client.submit({operation:"back",...ke()}))}},N.onclick=()=>{w.open()},g.onclick=()=>{T?.active?T.dismiss():ie||ge()},j.onclick=()=>{re.pending?re.retry().catch(()=>{}):We()?ge():Oe(()=>n.client.retry())},F.addEventListener("cancel",e=>{e.preventDefault(),T?.active?T.dismiss():ie||ge()}),n.signal?.addEventListener("abort",B,{once:!0}),a?.addEventListener("abort",B,{once:!0});let en=!1;p&&(k=p.onClose(()=>{l||te||(te=!0,T?.finish("dismissed"),pe(),r.hidden=!0,n.client.view?ge().finally(B):en=!0)}));let kn={destroy:B,refresh:dn,get recoveryPaywall(){if(I&&Ne)return{...Ne,view:I.currentResolution}},setPurchaseRecovery(e,t){return I?.setPurchaseRecovery(e,t),I!==null},retainPurchaseDialog(){let e=I?.retainPurchaseDialog();if(e)return I=null,En(e.dialog),{dialog:e.dialog,release(){e.release(),r.remove(),s||P()}}},get recovery(){let e=ln();if(e)return e;if(!l&&!X&&!ue&&!ie&&I){let t=I.recovery;if(t.type!=="native")return t}return{type:"recover",operationId:n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??$?.operationId??null,requestId:n.client.pendingCommand?.requestId??null}},prepareFallback(){if(ie)return ie;let e=ln();if(e)return Promise.resolve(e);let t=n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??$?.operationId??null,o=()=>({type:"recover",operationId:t,requestId:n.client.pendingCommand?.requestId??null});if(n.client.hasDurableJournal!==!0){let m=I?.recovery;return Promise.resolve(m&&m.type!=="native"&&m.type!=="cancel"?m:o())}let h=(n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[])).some(m=>m.operation==="close");if(l&&!(h||$&&n.client.view?.status==="closed")||X||Be||Re||w.active||!I&&!$&&!h)return Promise.resolve(o());let Z=I,_=(async()=>{try{if(!$&&h){let d=await n.client.retry();return await se(n.client.view??d.run),o()}if(!$){let d=await Z.prepareFallback();if(d.type!=="native")return d;if(n.client.hasDurableJournal!==!0)return o();$=d}let m=n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[]);if(m.length){let d=m.find(G=>G.operation==="close");if(!d||!M||d.requestId!==M.requestId)return o();let q=await n.client.retry();In(q),await se(n.client.view??q.run)}else{let d=n.client.view,q=d?.paywall;if(!d||!q||q.selectionGeneration===void 0||(q.quote?.operationId??null)!==$.operationId||$.operationId!==null&&q.canReselect!==!0)return o();let G=q.selectionGeneration,J=await n.client.get();await se(n.client.view??J.run);let b=n.client.view,x=b?.paywall;if(!b||!x||!["running","waiting"].includes(b.status)||b.stopped||b.id!==d.id||b.nodeId!==d.nodeId||b.visit!==d.visit||x.receiptId!==q.receiptId||x.selectionGeneration!==G||(x.quote?.operationId??null)!==$.operationId||$.operationId!==null&&x.canReselect!==!0||n.client.pendingPurchase||(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0)))return o();let y=ke();M={runId:b.id,operationId:$.operationId,revision:y.revision,requestId:y.requestId,nodeId:b.nodeId,visit:b.visit,receiptId:x.receiptId,selectionGeneration:G,acknowledged:!1},await ge(y)}let C=ln();return C?(B(),C):o()}catch(m){return Y(m),o()}})();ie=_;let fe=()=>{ie===_&&(ie=null)};return _.then(fe,fe),_},review:w.open,exitReview:w.exit,get unappliedDrafts(){return w.drafts}};try{let e=n.client.view;if(e)((n.client.viewAgeMs??yn)>=yn||e.instruction?.type==="evaluate_segment")&&(on=dn().finally(()=>{on=null})),await se(e);else{if(r.hidden=!0,l)throw new DOMException("Presentation cancelled","AbortError");let t=en||n.prepared?.state==="shown"?null:Ye(n.client.view?.screen?.presentation.type!=="inline",n.client.view?.locale);if(l||te&&!en)throw new DOMException("Presentation cancelled","AbortError");let o=n.client.get(),h=await(t?t.wait(o,He):nt(o,He));if(hn=!1,en)return l||await ge().finally(B),kn;await se(n.client.view??h.run)}}catch(e){throw T?.finish("error",e),B(),e}return kn}function nt(i,E){let U;return Promise.race([i,new Promise((n,p)=>{U=setTimeout(()=>p(new Error("Presentation data timed out")),E)})]).finally(()=>clearTimeout(U))}function St(i,E,U){return et(i,E,U)}export{et as a,St as b};
@@ -1 +1 @@
1
- import{a as h}from"./chunk-6HNCADWS.js";import{a as b,c as w,l as x,m as O}from"./chunk-YIHMOK6T.js";import{a as I}from"./chunk-VILB5M4X.js";import{b as y,f as g,g as v}from"./chunk-T7AK4QLG.js";import{b as t}from"./chunk-COMZFFUA.js";var d=O,R=t.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),j=t.tuple([t.number().min(0).max(1),t.number().min(0).max(1)]).refine(([e,r])=>e<=r),F=t.strictObject({seed:t.string().min(1).max(255),variations:t.array(R).min(2).max(20),weights:t.array(t.number().min(0).max(1)).max(20).optional(),coverage:t.number().min(0).max(1).optional(),ranges:t.array(j).max(20).optional(),filters:t.array(t.strictObject({seed:t.string().min(1).max(255),ranges:t.array(j).max(100)})).max(100).optional(),passthrough:t.array(t.number().int().min(0).max(19)).max(20).optional(),condition:g.optional(),active:t.literal(!1).optional(),force:t.number().int().min(-1).max(19).optional()}),_=t.discriminatedUnion("type",[t.strictObject({type:t.literal("pass"),next:d}),t.strictObject({type:t.literal("condition"),cases:t.array(t.strictObject({condition:g,target:d})).min(1).max(50),default:d}),t.strictObject({type:t.literal("split"),experimentId:t.uuid(),bucketing:F,routes:t.record(R,d).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:d}),t.strictObject({type:t.literal("paywall"),paywallId:t.uuid(),paywallVersionId:t.uuid(),presentation:y}),t.strictObject({type:t.literal("screen"),surface:t.enum(["page","popup","onboarding"]),presentation:y}),t.strictObject({type:t.literal("external_page")}),t.strictObject({type:t.literal("end"),outcome:t.enum(["completed","closed","ineligible","failed"])}),t.strictObject({type:t.literal("server"),reason:t.enum(["action","wait","feature","condition","experiment","resource"])})]),P={nodes:500,maxBytes:262144},S=t.strictObject({kind:t.literal("funnel_route"),formatVersion:t.literal(1),funnelId:t.uuid(),versionId:t.uuid(),entry:d,maxTransitions:t.number().int().min(1).max(1e4),variables:t.record(b,w),nodes:t.record(d,_)}).superRefine((e,r)=>{let s=a=>r.addIssue({code:"custom",message:a});Object.keys(e.nodes).length>P.nodes&&s("Too many route nodes"),Object.hasOwn(e.nodes,e.entry)||s("Route entry is missing");for(let a of Object.values(e.variables))["parameter","input"].includes(a.source.type)||s("Only start parameters and inputs can be public");for(let a of Object.values(e.nodes)){for(let c of V(a))Object.hasOwn(e.nodes,c)||s("Route target is missing");a.type==="split"&&a.bucketing.variations.some(c=>!Object.hasOwn(a.routes,c))&&s("Every Variation needs a route")}});function V(e){switch(e.type){case"pass":return[e.next];case"condition":return[...e.cases.map(r=>r.target),e.default];case"split":return[...Object.values(e.routes),e.notParticipating];default:return[]}}function E(e,r,s=[]){if(e==="id")return!0;if(!e.startsWith("variables."))return!1;let a=e.slice(10),c=i=>a===i||a.startsWith(`${i}.`)||i.startsWith(`${a}.`);return r.some(i=>a===i||a.startsWith(`${i}.`))&&!s.some(c)}function m(e,r,s=[]){return v(e).length===0&&I(e).every(a=>E(a,r,s))}function W(e){let{document:r}=e,s={},a=[];for(let[n,o]of Object.entries(r.variables))["parameter","input"].includes(o.source.type)?s[n]=o:a.push(n);let c=Object.keys(s),i=new Map(r.graph.nodes.map(n=>[n.id,n])),l={},u=[r.graph.entry],f=n=>{switch(n.type){case"entry":case"offering":case"coupon":case"coupons":return{type:"pass",next:n.next};case"condition":return n.cases.every(o=>m(o.condition,c,a))?{type:"condition",cases:n.cases.map(o=>({condition:o.condition,target:o.target})),default:n.default}:{type:"server",reason:"condition"};case"split":{let o=N(Object.hasOwn(e.experiments,n.experimentId)?e.experiments[n.experimentId]:void 0,n.routes,c,a);return o?{type:"split",experimentId:n.experimentId,bucketing:o,routes:{...n.routes},notParticipating:n.notParticipating}:{type:"server",reason:"experiment"}}case"screen":{let o=r.screens.find(p=>p.id===n.screenId);if(o?.type==="paywall"){let p=e.paywallOf(o.paywallVersionId);return p?{type:"paywall",paywallId:p,paywallVersionId:o.paywallVersionId,presentation:n.presentation}:{type:"server",reason:"resource"}}return o?.type==="owned"?{type:"screen",surface:o.document.surface,presentation:n.presentation}:{type:"server",reason:"resource"}}case"external_page":return{type:"external_page"};case"end":return{type:"end",outcome:n.outcome};case"output":return{type:"end",outcome:"completed"};case"feature":return{type:"server",reason:"feature"};case"action":return{type:"server",reason:"action"};case"wait":return{type:"server",reason:"wait"}}};for(;u.length;){let n=u.shift();if(Object.hasOwn(l,n))continue;let o=i.get(n);if(!o)throw new Error("Funnel route target is missing");let p=f(o);l[n]=p,u.push(...V(p))}return S.parse({kind:"funnel_route",formatVersion:1,funnelId:e.funnelId,versionId:e.versionId,entry:r.graph.entry,maxTransitions:r.execution.maxTransitions,variables:s,nodes:l})}function N(e,r,s,a){if(!e||(e.hashAttribute??"id")!=="id"||e.fallbackAttribute||e.parentConditions?.length||e.urlPatterns?.length||(e.hashVersion??2)!==2||(e.filters??[]).some(i=>(i.attribute??"id")!=="id")||e.condition&&!m(e.condition,s,a)||e.variations.some(i=>typeof i!="string"||!Object.hasOwn(r,i)))return;let c=(e.meta??[]).flatMap((i,l)=>i.passthrough?[l]:[]);return F.parse({seed:e.seed??e.key,variations:e.variations,...e.weights?{weights:e.weights}:{},...e.coverage!==void 0?{coverage:e.coverage}:{},...e.ranges?{ranges:e.ranges}:{},...e.filters?.length?{filters:e.filters.map(i=>({seed:i.seed,ranges:i.ranges}))}:{},...c.length?{passthrough:c}:{},...e.condition?{condition:e.condition}:{},...e.active===!1?{active:!1}:{},...e.force!==void 0?{force:e.force}:{}})}function G(e,r){return{key:e,seed:r.seed,hashAttribute:"id",hashVersion:2,variations:r.variations,...r.weights?{weights:r.weights}:{},...r.coverage!==void 0?{coverage:r.coverage}:{},...r.ranges?{ranges:r.ranges}:{},...r.filters?{filters:r.filters.map(s=>({attribute:"id",seed:s.seed,hashVersion:2,ranges:s.ranges}))}:{},...r.passthrough?{meta:r.variations.map((s,a)=>({passthrough:r.passthrough.includes(a)}))}:{},...r.condition?{condition:r.condition}:{},...r.active===!1?{active:!1}:{},...r.force!==void 0?{force:r.force}:{}}}function $(e,r){let s=[],a={versionId:e.versionId,path:s},c=f=>({...a,type:"unknown",reason:f}),i;try{i=x({declarations:e.variables,answers:{},parameters:r.parameters,attributes:{id:r.customerId},savedGroups:{},results:{}})}catch{return c("invalid_parameters")}let l=Object.keys(e.variables),u=e.entry;for(let f=0;;f++){let n=e.nodes[u];switch(s.push(u),n.type){case"paywall":return{...a,type:"paywall",paywallId:n.paywallId,paywallVersionId:n.paywallVersionId,presentation:n.presentation};case"screen":return{...a,type:"screen",surface:n.surface,presentation:n.presentation};case"external_page":return{...a,type:"external_page"};case"end":return{...a,type:"end",outcome:n.outcome};case"server":return c("server_step")}if(f>=e.maxTransitions)return c("transition_limit");if(n.type==="pass"){u=n.next;continue}if(n.type==="condition"){if(!n.cases.every(o=>m(o.condition,l)))return c("server_attribute");u=h({id:u,name:u,type:"condition",cases:n.cases,default:n.default},{attributes:i,savedGroups:{}},{}).target;continue}if(n.bucketing.condition&&!m(n.bucketing.condition,l))return c("server_attribute");u=h({id:u,name:u,type:"split",experimentId:n.experimentId,routes:n.routes,notParticipating:n.notParticipating},{attributes:i,savedGroups:{}},{[n.experimentId]:G(n.experimentId,n.bucketing)}).target}}export{P as a,S as b,W as c,$ as d};
1
+ import{a as h}from"./chunk-JEDRJAJ5.js";import{a as b,c as w,l as x,m as O}from"./chunk-DBYRJ4QV.js";import{a as I}from"./chunk-VILB5M4X.js";import{b as y,f as g,g as v}from"./chunk-FQMZY5VP.js";import{b as t}from"./chunk-PZTWDJHN.js";var d=O,R=t.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),j=t.tuple([t.number().min(0).max(1),t.number().min(0).max(1)]).refine(([e,r])=>e<=r),F=t.strictObject({seed:t.string().min(1).max(255),variations:t.array(R).min(2).max(20),weights:t.array(t.number().min(0).max(1)).max(20).optional(),coverage:t.number().min(0).max(1).optional(),ranges:t.array(j).max(20).optional(),filters:t.array(t.strictObject({seed:t.string().min(1).max(255),ranges:t.array(j).max(100)})).max(100).optional(),passthrough:t.array(t.number().int().min(0).max(19)).max(20).optional(),condition:g.optional(),active:t.literal(!1).optional(),force:t.number().int().min(-1).max(19).optional()}),_=t.discriminatedUnion("type",[t.strictObject({type:t.literal("pass"),next:d}),t.strictObject({type:t.literal("condition"),cases:t.array(t.strictObject({condition:g,target:d})).min(1).max(50),default:d}),t.strictObject({type:t.literal("split"),experimentId:t.uuid(),bucketing:F,routes:t.record(R,d).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:d}),t.strictObject({type:t.literal("paywall"),paywallId:t.uuid(),paywallVersionId:t.uuid(),presentation:y}),t.strictObject({type:t.literal("screen"),surface:t.enum(["page","popup","onboarding"]),presentation:y}),t.strictObject({type:t.literal("external_page")}),t.strictObject({type:t.literal("end"),outcome:t.enum(["completed","closed","ineligible","failed"])}),t.strictObject({type:t.literal("server"),reason:t.enum(["action","wait","feature","condition","experiment","resource"])})]),P={nodes:500,maxBytes:262144},S=t.strictObject({kind:t.literal("funnel_route"),formatVersion:t.literal(1),funnelId:t.uuid(),versionId:t.uuid(),entry:d,maxTransitions:t.number().int().min(1).max(1e4),variables:t.record(b,w),nodes:t.record(d,_)}).superRefine((e,r)=>{let s=a=>r.addIssue({code:"custom",message:a});Object.keys(e.nodes).length>P.nodes&&s("Too many route nodes"),Object.hasOwn(e.nodes,e.entry)||s("Route entry is missing");for(let a of Object.values(e.variables))["parameter","input"].includes(a.source.type)||s("Only start parameters and inputs can be public");for(let a of Object.values(e.nodes)){for(let c of V(a))Object.hasOwn(e.nodes,c)||s("Route target is missing");a.type==="split"&&a.bucketing.variations.some(c=>!Object.hasOwn(a.routes,c))&&s("Every Variation needs a route")}});function V(e){switch(e.type){case"pass":return[e.next];case"condition":return[...e.cases.map(r=>r.target),e.default];case"split":return[...Object.values(e.routes),e.notParticipating];default:return[]}}function E(e,r,s=[]){if(e==="id")return!0;if(!e.startsWith("variables."))return!1;let a=e.slice(10),c=i=>a===i||a.startsWith(`${i}.`)||i.startsWith(`${a}.`);return r.some(i=>a===i||a.startsWith(`${i}.`))&&!s.some(c)}function m(e,r,s=[]){return v(e).length===0&&I(e).every(a=>E(a,r,s))}function W(e){let{document:r}=e,s={},a=[];for(let[n,o]of Object.entries(r.variables))["parameter","input"].includes(o.source.type)?s[n]=o:a.push(n);let c=Object.keys(s),i=new Map(r.graph.nodes.map(n=>[n.id,n])),l={},u=[r.graph.entry],f=n=>{switch(n.type){case"entry":case"offering":case"coupon":case"coupons":return{type:"pass",next:n.next};case"condition":return n.cases.every(o=>m(o.condition,c,a))?{type:"condition",cases:n.cases.map(o=>({condition:o.condition,target:o.target})),default:n.default}:{type:"server",reason:"condition"};case"split":{let o=N(Object.hasOwn(e.experiments,n.experimentId)?e.experiments[n.experimentId]:void 0,n.routes,c,a);return o?{type:"split",experimentId:n.experimentId,bucketing:o,routes:{...n.routes},notParticipating:n.notParticipating}:{type:"server",reason:"experiment"}}case"screen":{let o=r.screens.find(p=>p.id===n.screenId);if(o?.type==="paywall"){let p=e.paywallOf(o.paywallVersionId);return p?{type:"paywall",paywallId:p,paywallVersionId:o.paywallVersionId,presentation:n.presentation}:{type:"server",reason:"resource"}}return o?.type==="owned"?{type:"screen",surface:o.document.surface,presentation:n.presentation}:{type:"server",reason:"resource"}}case"external_page":return{type:"external_page"};case"end":return{type:"end",outcome:n.outcome};case"output":return{type:"end",outcome:"completed"};case"feature":return{type:"server",reason:"feature"};case"action":return{type:"server",reason:"action"};case"wait":return{type:"server",reason:"wait"}}};for(;u.length;){let n=u.shift();if(Object.hasOwn(l,n))continue;let o=i.get(n);if(!o)throw new Error("Funnel route target is missing");let p=f(o);l[n]=p,u.push(...V(p))}return S.parse({kind:"funnel_route",formatVersion:1,funnelId:e.funnelId,versionId:e.versionId,entry:r.graph.entry,maxTransitions:r.execution.maxTransitions,variables:s,nodes:l})}function N(e,r,s,a){if(!e||(e.hashAttribute??"id")!=="id"||e.fallbackAttribute||e.parentConditions?.length||e.urlPatterns?.length||(e.hashVersion??2)!==2||(e.filters??[]).some(i=>(i.attribute??"id")!=="id")||e.condition&&!m(e.condition,s,a)||e.variations.some(i=>typeof i!="string"||!Object.hasOwn(r,i)))return;let c=(e.meta??[]).flatMap((i,l)=>i.passthrough?[l]:[]);return F.parse({seed:e.seed??e.key,variations:e.variations,...e.weights?{weights:e.weights}:{},...e.coverage!==void 0?{coverage:e.coverage}:{},...e.ranges?{ranges:e.ranges}:{},...e.filters?.length?{filters:e.filters.map(i=>({seed:i.seed,ranges:i.ranges}))}:{},...c.length?{passthrough:c}:{},...e.condition?{condition:e.condition}:{},...e.active===!1?{active:!1}:{},...e.force!==void 0?{force:e.force}:{}})}function G(e,r){return{key:e,seed:r.seed,hashAttribute:"id",hashVersion:2,variations:r.variations,...r.weights?{weights:r.weights}:{},...r.coverage!==void 0?{coverage:r.coverage}:{},...r.ranges?{ranges:r.ranges}:{},...r.filters?{filters:r.filters.map(s=>({attribute:"id",seed:s.seed,hashVersion:2,ranges:s.ranges}))}:{},...r.passthrough?{meta:r.variations.map((s,a)=>({passthrough:r.passthrough.includes(a)}))}:{},...r.condition?{condition:r.condition}:{},...r.active===!1?{active:!1}:{},...r.force!==void 0?{force:r.force}:{}}}function $(e,r){let s=[],a={versionId:e.versionId,path:s},c=f=>({...a,type:"unknown",reason:f}),i;try{i=x({declarations:e.variables,answers:{},parameters:r.parameters,attributes:{id:r.customerId},savedGroups:{},results:{}})}catch{return c("invalid_parameters")}let l=Object.keys(e.variables),u=e.entry;for(let f=0;;f++){let n=e.nodes[u];switch(s.push(u),n.type){case"paywall":return{...a,type:"paywall",paywallId:n.paywallId,paywallVersionId:n.paywallVersionId,presentation:n.presentation};case"screen":return{...a,type:"screen",surface:n.surface,presentation:n.presentation};case"external_page":return{...a,type:"external_page"};case"end":return{...a,type:"end",outcome:n.outcome};case"server":return c("server_step")}if(f>=e.maxTransitions)return c("transition_limit");if(n.type==="pass"){u=n.next;continue}if(n.type==="condition"){if(!n.cases.every(o=>m(o.condition,l)))return c("server_attribute");u=h({id:u,name:u,type:"condition",cases:n.cases,default:n.default},{attributes:i,savedGroups:{}},{}).target;continue}if(n.bucketing.condition&&!m(n.bucketing.condition,l))return c("server_attribute");u=h({id:u,name:u,type:"split",experimentId:n.experimentId,routes:n.routes,notParticipating:n.notParticipating},{attributes:i,savedGroups:{}},{[n.experimentId]:G(n.experimentId,n.bucketing)}).target}}export{P as a,S as b,W as c,$ as d};
@@ -1 +1 @@
1
- import{a as n}from"./chunk-Y2DUFDPV.js";function o(r,e){try{return r.parse(e)}catch{throw new n("INVALID_RESPONSE","Invalid gateway response")}}export{o as a};
1
+ import{a as n}from"./chunk-TK3WOD2O.js";function o(r,e){try{return r.parse(e)}catch{throw new n("INVALID_RESPONSE","Invalid gateway response")}}export{o as a};
@@ -0,0 +1 @@
1
+ import{a as Se,b as Ce}from"./chunk-JBSJ3JU2.js";import{d as Ie,e as J}from"./chunk-5LNX7MHO.js";import{a as ve}from"./chunk-TK3WOD2O.js";import{a as S}from"./chunk-DSPLGTQI.js";var Fe=5*6e4,Le=15e3,Ae=new WeakMap;function je(c){return Ae.get(c)}var C=c=>Array.isArray(c)?c.map(C):c&&typeof c=="object"?Object.fromEntries(Object.keys(c).sort().map(a=>[a,C(c[a])])):c,O=(c,a)=>JSON.stringify(C(c))===JSON.stringify(C(a)),le=c=>JSON.stringify(C([c.funnelId,c.locale??null,c.parameters??{}])),Ne=["onObservationChange","onPurchase","onCheckoutUrl","resumeCheckout","allowNewPurchase","checkoutNavigation","terminateCheckout","beforeCheckoutReplacement","purchaseConfirmation","confirmOnHostedCheckout","resolveOfferId","resolveSubscriptionChange","onOpenUrl","onEvent","onAction","onComplete","onError"];function Je(c,a){let ie=e=>structuredClone({funnelId:e.funnelId,locale:e.locale,parameters:e.parameters}),m,U="",H=a.start instanceof Promise?void 0:ie(a.start),G=e=>e?.parameters?.commerce,se=Promise.resolve(a.start).then(e=>e?ie(e):void 0),W=a.maxAgeMs??Fe,ce=new AbortController,y=AbortSignal.any([ce.signal,a.client.identitySignal,...a.signal?[a.signal]:[]]),K=()=>d("released","aborted"),r="preparing",de,F,B=()=>{},L=0,b=null,P=null,v=null,f=null,h,X,ue=new Map,w=null,N=new Set,A=new Map,$,fe=new Promise(e=>$=e),z,Re=new Promise(e=>z=e);function x(e,n){r!==e&&(r=e,de=n,S(a.onState,e))}function ke(){y.removeEventListener("abort",K),M(),P?.destroy(),P=null,b?.remove(),b=null,v=null}function d(e,n){["adopted","unavailable","released","closed"].includes(r)||(x(e,n),ke(),$(!1),z(null))}function E(e){r!=="shown"&&d("unavailable",e)}let g,Q=a.client.paywallCopies,Y,Ee=new Promise(e=>Y=e);function pe(e){Ee.then(n=>{n&&Q&&Q.write(n,e).catch(()=>{})})}let Z=e=>`error:${e?.code??e?.name??"unknown"}`,ee=c.ownerDocument.defaultView,_=!0,ye=null,R=!1,_e=e=>e.storageArea===ee?.localStorage&&(e.key===null||e.key.startsWith("indiana.funnel.purchases.")),we=e=>{_e(e)&&q()},Ve=a.client.subscribe(()=>q());function M(){_&&(_=!1,ee?.removeEventListener("storage",we),Ve(),B())}let ne=()=>_&&(r==="ready"||r==="preparing");function ae(e){(r==="ready"||r==="preparing")&&d("unavailable",e)}function q(){if(r==="ready"&&Date.now()-L>=W)return M();R=!0,ye??=(async()=>{for(;R&&m&&ne();){R=!1;try{await a.client.retained()==="pending"&&ae("purchase_pending")}catch(e){y.aborted?d("released","aborted"):ae(Z(e))}}})().finally(()=>{ye=null,R&&m&&ne()&&q()})}ee?.addEventListener("storage",we),y.addEventListener("abort",K,{once:!0});let me=a.client.findPurchase();me.catch(()=>{});let T;function j(e){let n=JSON.stringify(C(e)),t=ue.get(n);if(!t){let l=T?.paywallVersionId??a.paywallVersionId??(g?void 0:f?.id);t=a.client.readPaywall({paywallVersionId:l,...l?{}:{paywallId:T?.paywallId??a.paywallId},...e}),ue.set(n,t)}return t}function k(e,n){let t=Object.values(e.capabilities.plans),l=Object.values(e.document.buttons).some(o=>o.type==="checkout");return l&&t.length===0?!1:n.intent==="subscription_change"&&l?t.some(o=>o.available):t.every(o=>o.available)}function re(e,n){if(f&&!J(e,f))return d("unavailable","paywall_changed"),!1;f=e,X=n;for(let t of A.keys())S(t,structuredClone(e));return!0}function ge(e,n){if(!(!f||!["preparing","ready","shown"].includes(r))){if(!J(e,f))return E("paywall_changed");if(!k(e,n.commerce))return E("plan_unavailable");re(e,n)}}async function V(){let e=await Re;if(!e)throw new ve("PURCHASE_PENDING","The purchase did not start; open it again");return e}let De={get view(){return w?w.view:f},get signal(){return w?.signal??a.client.identitySignal},get quote(){return w?.quote??null},get operation(){return w?.operation??null},webViewUrl:"bundled",get canReselect(){return w?.canReselect},get recovery(){return w?.recovery},get pendingCancellation(){return w?.pendingCancellation},subscribe(e){return A.set(e,w?.subscribe?.(e)??(()=>{})),()=>{A.get(e)?.(),A.delete(e)}},refresh:async()=>w?w.refresh():structuredClone(f),preview:async e=>(await V()).preview(e),confirm:async()=>(await V()).confirm(),cancel:async()=>(await V()).cancel(),read:async()=>(await V()).read(),destroy(){w?.destroy()}},u={options:{},handoff:{}},he={loading:"host",focusAtReveal:!0,signal:a.client.identitySignal,start:async()=>De,canInteract:()=>u.options.canInteract?u.options.canInteract():!["unavailable","released","closed"].includes(r),async beforeAction(){let e=r!=="adopted",n=f?.capabilities,t=await V();if(e&&!O(t.view?.capabilities,n))throw new Ie;await u.options.beforeAction?.()}};for(let e of Ne)Object.defineProperty(he,e,{enumerable:!0,get:()=>u.options[e]});function te(){r!=="preparing"||!v||!P||!g&&(!m||!O(X?.commerce,G(m))||X?.locale!==m.locale)||(x("ready"),$(!0))}let Pe={loadingLayout:()=>u.handoff.loadingLayout?.(),present(e){if(u.handoff.present)return u.handoff.present(e);r==="preparing"&&(v=e,L=Date.now(),te())},async dismiss(){if(u.handoff.dismiss)return u.handoff.dismiss();d("closed");for(let e of[...N])S(e)},async closeAction(e){if(u.handoff.closeAction)return u.handoff.closeAction(e);u.options.onAction?await u.options.onAction(e):await Pe.dismiss()},quoteError(e){u.handoff.quoteError?u.handoff.quoteError(e):S(u.options.onError,e)}};async function Oe(){if(a.paywallVersionId||a.paywallId)return{paywallVersionId:a.paywallVersionId,paywallId:a.paywallId};let e=a.configuration;if(!e)return d("unavailable","paywall_missing"),null;let n=await Promise.resolve(a.start).catch(()=>null);if(!n||r!=="preparing")return null;let t=()=>Se(e,{funnelId:n.funnelId,customerId:a.client.customerId,parameters:n.parameters??{}});if(F=await t(),r!=="preparing")return null;let l=F;if(l.type!=="paywall")return d("unavailable",Ce(l)??"route"),null;let o=!1;return B=e.subscribe(()=>{o||!ne()||(o=!0,t().then(i=>{!(i.type==="unavailable"&&!["funnel_stopped","route_unavailable"].includes(i.reason))&&(i.type!=="paywall"||i.paywallVersionId!==l.paywallVersionId)&&ae("route_changed")}).finally(()=>o=!1))}),_||B(),{paywallVersionId:l.paywallVersionId}}(async()=>{try{let[{showPaywall:e},n]=await Promise.all([import("./paywall-KQIBPACY.js"),Oe()]),t=a.commerce??G(H),l=a.locale??H?.locale,o=n&&t&&l?JSON.stringify(C([n.paywallVersionId??null,n.paywallId??null,{commerce:t,locale:l}])):null;if(Y(o),y.throwIfAborted(),r!=="preparing"||!n)return;if(!t)return d("unavailable","commerce_missing");if(!l)return d("unavailable","locale_missing");T=n;let i={commerce:t,locale:l},p=o?await Q?.read(o).catch(()=>null):null;if(y.throwIfAborted(),r!=="preparing")return;p&&(!H||p.funnelId===H.funnelId)&&(n.paywallVersionId?p.resolution.id===n.paywallVersionId:p.resolution.paywallId===n.paywallId)&&k(p.resolution,p.context.commerce)&&(g=p);let s;if(g){let oe=g.context;i=oe,s=structuredClone(g.resolution),j(oe).then(He=>ge(He,oe),()=>{})}else s=await j(i);if(y.throwIfAborted(),r!=="preparing"||(!k(s,i.commerce)&&a.start instanceof Promise&&!h&&await se,!g&&h&&!O(i,h)&&(i=h,s=await j(i)),y.throwIfAborted(),r!=="preparing"))return;if(!k(s,i.commerce))return d("unavailable","plan_unavailable");if(!re(s,i))return;b=c.ownerDocument.createElement("div"),c.append(b);let D=setTimeout(()=>r==="preparing"&&d("unavailable","timeout"),Le);fe.then(()=>clearTimeout(D));let I=await e(b,he,Pe);if(!I.host||y.aborted||r!=="preparing"){I.host?.destroy(),d(y.aborted?"released":"unavailable","error");return}P=I.host,te()}catch(e){d(y.aborted?"released":"unavailable",Z(e))}finally{Y(null)}})(),se.then(async e=>{let n=i=>{pe(null),E(i)};if(!e)return n("gated");let t=e,l=G(t),o=a.commerce??l;if(!O(l&&{...l,intent:void 0},o&&{...o,intent:void 0})||a.locale!==void 0&&t.locale!==a.locale)return n("start_mismatch");if(!l)return n("commerce_missing");h={commerce:l,locale:t.locale},g&&["preparing","ready","shown"].includes(r)&&(m=t,U=le(t));try{let i=await me,p=i==="pending"?"purchase_pending":i==="found"?"original_purchase":i==="blocked"?"purchase_blocked":void 0;if(p)return n(p);if(!["preparing","ready","shown"].includes(r))return;if(_&&(R=!1,await a.client.retained()==="pending"))return n("purchase_pending");if(T||a.paywallId||a.paywallVersionId||f){let s=await j(h);if(y.throwIfAborted(),pe(k(s,h.commerce)?{savedAt:Date.now(),funnelId:t.funnelId,context:h,resolution:s}:null),g)ge(s,h);else{if(r!=="preparing")return;if(f){if(!k(s,h.commerce))return d("unavailable","plan_unavailable");if(!re(s,h))return}}}}catch(i){return y.aborted?d("released","aborted"):E(Z(i))}["preparing","ready","shown"].includes(r)&&(m=t,U=le(t),te(),R&&q())},()=>E("gated"));let be={get state(){return r},get reason(){return de},ready:fe,get start(){return m},get prediction(){return F?structuredClone(F):void 0},matches:e=>m?le(e)===U:!!g&&e.funnelId===g.funnelId&&e.locale===g.context.locale,open(){if(r==="preparing")return"pending";if(r!=="ready"||!v)return!1;if(Date.now()-L>=W)return d("unavailable","expired"),!1;let e=v;return v=null,M(),x("shown"),e(),"shown"},destroy(){ce.abort()}};return Ae.set(be,{onClose(e){return r==="closed"?(S(e),()=>{}):(N.add(e),()=>{N.delete(e)})},claim(){M()},async adopt(e,n){let t=e.paywall?.resolution,l=e.paywall&&!e.paywall.quote&&!e.paywall.operation&&!e.paywall.purchaseRequestId&&!(e.paywall.selectionGeneration??0);if(r!=="shown"||!P||!f||!t||!l||e.source.id!==m?.funnelId||e.locale!==m?.locale||!O(e.parameters??{},m?.parameters??{})||!["running","waiting"].includes(e.status)||!J(t,f))return null;let o;try{o=await n.start()}catch{return null}if(r!=="shown"||!P)return o.destroy(),null;w=o,u.options=n.options,u.handoff=n.handoff;for(let[s]of A)A.set(s,o.subscribe?.(s)??(()=>{})),o.view&&S(s,structuredClone(o.view));y.removeEventListener("abort",K),x("adopted"),z(o),N.clear();let i=P,p=b;return P=null,b=null,v=null,new Proxy(i,{get(s,D){return D==="destroy"?()=>{s.destroy(),p?.remove()}:D==="retainPurchaseDialog"?()=>{let I=s.retainPurchaseDialog();if(I)return{dialog:I.dialog,release(){I.release(),p?.remove()}}}:Reflect.get(s,D,s)}})},retainPurchaseDialog(){if(r!=="shown")return;let e=P?.retainPurchaseDialog();if(!e)return;let n=b;return P=null,b=null,d("released"),{dialog:e.dialog,release(){e.release(),n?.remove()}}},get modal(){return f?.document.presentation.type!=="inline"},get revealable(){return r==="ready"&&!!v&&Date.now()-L<W},release(){d("released")}}),be}export{Fe as a,je as b,Je as c};
@@ -1 +1 @@
1
- import{b as B}from"./chunk-AEQUKR4O.js";import{K as L}from"./chunk-PZTFSADV.js";import{a as Y}from"./chunk-NPKNI2UD.js";import{c as W,e as X,f as Z,g as $,h as ee,i as te}from"./chunk-4VZCPOVE.js";import{b as J}from"./chunk-P2JQEGYV.js";import{B as V}from"./chunk-NQZ23AGQ.js";import{x as H}from"./chunk-QA3LXFSK.js";import{t as z}from"./chunk-LTWU7HH5.js";import{a as u}from"./chunk-Y2DUFDPV.js";import{a as K}from"./chunk-DSPLGTQI.js";async function ye(r){let{session:m,load:d}=ie(r);try{return await d(),m}catch(h){throw m.destroy(),h}}function ie(r){let m=r.view;if(!m?.paywall)throw new u("INVALID_REQUEST","The current node is not a Paywall");let d=m.paywall.receiptId,h=m.nodeId,E=m.visit,R=m.paywall.resolution,n=m.paywall,N="document"in R?{document:R.document,offering:R.offering,capabilities:R.capabilities}:null;function D(){let e=n.resolution;return"document"in e?e:N&&{...e,document:N.document,offering:N.offering,capabilities:W(e.capabilities,N.capabilities)}}function F(e){if(!X(e,R))throw new u("INVALID_RESPONSE","The pinned Paywall binding changed")}let p=!1,A=new Set,_=null;function G(){let e=D();if(e&&!p)for(let o of A)K(o,structuredClone(e))}async function M(){b();let e=D();if(e)return structuredClone(e);if(!_){let o=(async()=>{if("document"in n.resolution||!r.resolvePaywall)throw new u("INVALID_RESPONSE","Public Paywall reader is unavailable");let s=await B(r,n.resolution);return b(),F(s),N={document:s.document,offering:s.offering,capabilities:s.capabilities},G(),D()})();_=o;let t=()=>{_===o&&(_=null)};o.then(t,t)}return _.then(o=>structuredClone(o))}let q=new AbortController,f=(r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])).find(e=>e.operation==="submit"&&e.nodeId===h&&e.visit===E&&e.input.type==="paywall_quote")?.requestId??m.paywall.purchaseRequestId,C=0,g=null,T=new Set,I=null,v=new Map;function U(e){if(e.purchase&&e.purchase.receiptId!==d)throw new u("INVALID_RESPONSE","Purchase receipt changed");let o=e.run.paywall;return e.purchase??(o?.receiptId===d?o:null)}function b(){if(p)throw new u("IDENTITY_CHANGED","Paywall presentation has closed")}function S(e,o,t){if(b(),o!==C||t!==void 0&&n.quote?.operationId!==t)return!1;let s=n.selectionGeneration??0,i=e.run.paywall;if(i?.receiptId===d){if((i.selectionGeneration??0)<(n.selectionGeneration??0))return!1;F(i.resolution)}let a=U(e),c=i?.receiptId===d&&(i.selectionGeneration??0)>s,l=c?a?.quote??null:a?.quote??n.quote,y=a?.operation??(l?.operationId===n.quote?.operationId?n.operation:null);return n.quote&&l&&ee(n.quote,l),l&&y&&Z(y,{operationId:l.operationId,membershipId:V(l)?l.membershipId:null,...V(l)?{featureQuantities:l.featureQuantities??{}}:{}},"Purchase operation changed"),(c||l?.operationId!==n.quote?.operationId)&&(C++,i?.receiptId===d&&(f=i.purchaseRequestId)),i?.canReselect===!0&&i.purchaseRequestId===I&&!(r.pendingCommands??[r.pendingCommand]).some(w=>w?.requestId===I)&&(I=null),n={...n,...i?.receiptId===d?i:{},...t!==void 0&&!c&&a?.canReselect!==void 0?{canReselect:a.canReselect}:{},quote:l,operation:te(n.operation,y,!0)},G(),!0}function O(e,o,t){return new Promise((s,i)=>{let a=!1,c=()=>{clearTimeout(P),q.signal.removeEventListener("abort",w)},l=Q=>{a||(a=!0,c(),s(Q))},y=Q=>{a||(a=!0,c(),i(Q))},w=()=>y(new u("IDENTITY_CHANGED","Paywall presentation has closed")),P=setTimeout(()=>y(new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t)),Math.max(0,o-Date.now()));q.signal.addEventListener("abort",w,{once:!0}),q.signal.aborted&&w(),e.then(l,y)})}function ne(e){return new Promise(o=>{let t=()=>{clearTimeout(s),q.signal.removeEventListener("abort",t),o()},s=setTimeout(t,e);q.signal.addEventListener("abort",t,{once:!0}),q.signal.aborted&&t()})}function j(e,o){b();let t=v.get(e)??r.pendingCommands?.find(a=>a.requestId===e)??r.pendingCommand;if(t?.operation==="submit"&&t.requestId===e&&t.nodeId===h&&t.visit===E){o.type==="paywall_quote"&&t.input.type==="paywall_quote"&&t.input.predecessor&&!o.predecessor&&(o={...o,predecessor:t.input.predecessor});let a=L.parse(t),c=L.parse({...t,input:o});if(a.operation!=="submit"||c.operation!=="submit"||JSON.stringify(a.input)!==JSON.stringify(c.input))throw new u("CONFLICT","A purchase request cannot change its input");return v.set(e,a),a}let s=r.view;if(!s||s.nodeId!==h||s.visit!==E||s.paywall?.receiptId!==d)throw new u("PRECONDITION_FAILED","The Paywall visit has changed");let i=L.parse({operation:"submit",requestId:e,nodeId:h,visit:E,revision:s.revision,input:structuredClone(o)});if(i.operation!=="submit")throw new u("INVALID_REQUEST","A purchase submission is required");return v.set(e,i),i}async function x(e,o){b();let{requestId:t,input:s}=e,i=Date.now()+3e4;T.add(t);try{let a=await O(r.submit(e),i,t);for(;a.run.pendingRequest?.requestId===t&&Date.now()<i&&!p&&(await ne(Math.min(1e3,i-Date.now())),!(p||Date.now()>=i));)a=await O(r.resume(t),i,t);if(p)throw new u("IDENTITY_CHANGED","Paywall presentation has closed");if(a.run.pendingRequest?.requestId===t)throw new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t);if(!S(a,o,s.type==="paywall_confirm"||s.type==="paywall_cancel"?s.operationId:void 0))throw new u("PRECONDITION_FAILED","The purchase selection has changed");I===t&&(I=null)}catch(a){if(I=t,s.type==="paywall_quote"&&r.settle&&!p&&a instanceof u&&a.status!==void 0&&![401,425].includes(a.status)&&!a.retryable&&a.recovery!=="recover_operation")try{if((await O(r.settle(t),i,t)).settlement?.state==="settled"){let l=await O(r.get(),i,t);S(l,o)&&l.run.paywall?.purchaseRequestId===t&&n.canReselect===!0&&v.delete(t)}}catch{}throw a instanceof u&&a.code==="COMMAND_PENDING"&&a.status===void 0&&v.delete(t),a}finally{T.delete(t)}}async function k(e){if(!n.quote)throw new u("INVALID_REQUEST","A quoted purchase is required");let o=e==="confirm"?"paywall_confirm":"paywall_cancel",t=[...v.values(),...r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])].find(i=>i.operation==="submit"&&i.input.type===o&&"operationId"in i.input&&i.input.operationId===n.quote.operationId),s=t?.operation==="submit"&&t.input.type===o&&"operationId"in t.input&&t.input.operationId===n.quote.operationId?t.requestId:crypto.randomUUID();if(await x(j(s,{type:e==="confirm"?"paywall_confirm":"paywall_cancel",operationId:n.quote.operationId,...e==="confirm"&&n.quote.merchantTerms?{merchantConfirmation:H(n.quote.merchantTerms)}:{}}),C),!n.operation)throw new u("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(n.operation)}let oe={get view(){return structuredClone(D())},get quote(){return n.quote?structuredClone(n.quote):null},get operation(){return n.operation?structuredClone(n.operation):null},get webViewUrl(){return r.webViewUrl},get locale(){return r.view?.locale??m.locale},get canReselect(){return n.canReselect===!0&&I===null},get recovery(){let e=r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[]),o=r.pendingPurchase;if(o&&(o.receiptId!==d||o.operationId!==n.quote?.operationId))return{type:"recover",operationId:o.operationId,requestId:e[0]?.requestId??null};let t=Y({quote:n.quote,operation:n.operation,requestId:e[0]?.requestId??I??f,pending:T.size>0||e.length>0||I!==null,destroyed:p,canReselect:n.canReselect});return t.type==="recover"&&t.requestId===null&&!p&&r.hasDurableJournal===!0&&!n.quote&&!n.operation&&(n.selectionGeneration??0)===0&&!o&&!e.length&&!T.size&&!f?{type:"native",operationId:null}:t},get pendingCancellation(){return!p&&(r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])).some(e=>e.operation==="submit"&&e.nodeId===h&&e.visit===E&&e.input.type==="paywall_cancel"&&e.input.operationId===n.quote?.operationId)},subscribe(e){return p?()=>{}:(A.add(e),()=>A.delete(e))},async refresh(){b();let e=C,o=await r.get();if(S(o,e),o.run.paywall?.receiptId!==d)throw new u("PRECONDITION_FAILED","Paywall presentation has changed");return M()},preview(e){let o=D();if(!o)return Promise.reject(new u("PRECONDITION_FAILED","Load the Paywall presentation first"));if(f&&f!==e.requestId&&(g||n.canReselect!==!0))return Promise.reject(new u("COMMAND_PENDING","Retry the original purchase before starting another"));let t=o.document.buttons[e.actionId],s=t?.type==="checkout"?J(t.product,e.selection,o.capabilities):null;if(!s)return Promise.reject(new u("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let i=z(o.document.screen,s,e.selection,o.capabilities),a=f!==e.requestId&&(n.selectionGeneration??0)>0?{operationId:n.quote?.operationId??null,generation:n.selectionGeneration??0}:void 0,c=r.view?.parameters.commerce;if(c&&typeof c=="object"&&!Array.isArray(c)&&c.intent==="subscription_change"&&!e.subscriptionChange)return Promise.reject(new u("INVALID_REQUEST","Choose the existing membership for this subscription change"));if(e.subscriptionChange&&e.nativeOffer)return Promise.reject(new u("INVALID_REQUEST","A web membership change cannot include a store offer"));if(a&&n.canReselect!==!0)return Promise.reject(new u("COMMAND_PENDING","Original purchase requires authoritative termination"));let l;try{l=j(e.requestId,{type:"paywall_quote",actionId:e.actionId,productVersionId:s,...Object.keys(i).length?{featureQuantities:i}:{},...a?{predecessor:a}:{},...e.offerId?{offerId:e.offerId}:{},...e.nativeOffer?{nativeOffer:e.nativeOffer}:{},...e.subscriptionChange?{subscriptionChange:e.subscriptionChange}:{}})}catch(P){return Promise.reject(P)}if(f===e.requestId&&g)return g;f!==e.requestId&&C++;let y=C;f=e.requestId;let w=(async()=>{if(await x(l,y),!n.quote)throw new u("INVALID_RESPONSE","The accepted quote is missing");return $(n.quote,{productVersionId:s,featureQuantities:i,subscriptionChange:e.subscriptionChange},"The selected purchase changed"),structuredClone(n.quote)})();return g=w,w.then(()=>{g===w&&(g=null)},P=>{g===w&&(g=null),f===e.requestId&&r.pendingCommand?.requestId!==e.requestId&&P instanceof u&&P.status!==void 0&&P.status<500&&![401,425].includes(P.status)&&(f=null)}),w},confirm:()=>k("confirm"),cancel:()=>k("cancel"),async read(){if(b(),!n.quote)throw new u("INVALID_REQUEST","A quoted purchase is required");let e=n.quote.operationId,o=C,t=r.pendingCommands?.find(l=>l.operation==="submit"&&(l.input.type==="paywall_confirm"||l.input.type==="paywall_cancel")&&l.input.operationId===e)??r.pendingCommand;t?.operation==="submit"&&(t.input.type==="paywall_confirm"||t.input.type==="paywall_cancel")&&t.input.operationId===e&&await r.settle?.(t.requestId);let s=await r.get(void 0,{receiptId:d,operationId:e});b();let i=U(s);if(i?.quote&&i.quote.operationId!==e||i?.operation&&i.operation.operationId!==e)throw new u("INVALID_RESPONSE","Purchase operation changed");let a=S(s,o,e),c=a?n.operation:i?.operation;if(!c)throw new u("INVALID_RESPONSE","The current purchase result is missing");return a&&T.size===0&&!(r.pendingCommands?.length??(r.pendingCommand?1:0))&&(I=null),structuredClone(c)},destroy(){p=!0,re(),A.clear(),q.abort(),v.clear()}},re=r.subscribe(e=>{p||e.nodeId!==h||e.visit!==E||e.paywall?.receiptId!==d||(e.paywall.selectionGeneration??0)<(n.selectionGeneration??0)||(F(e.paywall.resolution),n={...n,resolution:e.paywall.resolution},G())});return{session:oe,load:M}}export{ye as a};
1
+ import{b as B}from"./chunk-AEQUKR4O.js";import{a as Y}from"./chunk-NDNHTG5B.js";import{c as W,e as X,f as Z,g as $,h as ee,i as te}from"./chunk-5LNX7MHO.js";import{K as L}from"./chunk-EKUDMQXT.js";import{b as J}from"./chunk-4OODZM64.js";import{B as V}from"./chunk-EB7MIZ4T.js";import{x as H}from"./chunk-S5RM3VO6.js";import{t as z}from"./chunk-VXDVMAS6.js";import{a as u}from"./chunk-TK3WOD2O.js";import{a as K}from"./chunk-DSPLGTQI.js";async function ye(r){let{session:m,load:d}=ie(r);try{return await d(),m}catch(h){throw m.destroy(),h}}function ie(r){let m=r.view;if(!m?.paywall)throw new u("INVALID_REQUEST","The current node is not a Paywall");let d=m.paywall.receiptId,h=m.nodeId,E=m.visit,R=m.paywall.resolution,n=m.paywall,N="document"in R?{document:R.document,offering:R.offering,capabilities:R.capabilities}:null;function D(){let e=n.resolution;return"document"in e?e:N&&{...e,document:N.document,offering:N.offering,capabilities:W(e.capabilities,N.capabilities)}}function F(e){if(!X(e,R))throw new u("INVALID_RESPONSE","The pinned Paywall binding changed")}let p=!1,A=new Set,_=null;function G(){let e=D();if(e&&!p)for(let o of A)K(o,structuredClone(e))}async function M(){b();let e=D();if(e)return structuredClone(e);if(!_){let o=(async()=>{if("document"in n.resolution||!r.resolvePaywall)throw new u("INVALID_RESPONSE","Public Paywall reader is unavailable");let s=await B(r,n.resolution);return b(),F(s),N={document:s.document,offering:s.offering,capabilities:s.capabilities},G(),D()})();_=o;let t=()=>{_===o&&(_=null)};o.then(t,t)}return _.then(o=>structuredClone(o))}let q=new AbortController,f=(r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])).find(e=>e.operation==="submit"&&e.nodeId===h&&e.visit===E&&e.input.type==="paywall_quote")?.requestId??m.paywall.purchaseRequestId,C=0,g=null,T=new Set,I=null,v=new Map;function U(e){if(e.purchase&&e.purchase.receiptId!==d)throw new u("INVALID_RESPONSE","Purchase receipt changed");let o=e.run.paywall;return e.purchase??(o?.receiptId===d?o:null)}function b(){if(p)throw new u("IDENTITY_CHANGED","Paywall presentation has closed")}function S(e,o,t){if(b(),o!==C||t!==void 0&&n.quote?.operationId!==t)return!1;let s=n.selectionGeneration??0,i=e.run.paywall;if(i?.receiptId===d){if((i.selectionGeneration??0)<(n.selectionGeneration??0))return!1;F(i.resolution)}let a=U(e),c=i?.receiptId===d&&(i.selectionGeneration??0)>s,l=c?a?.quote??null:a?.quote??n.quote,y=a?.operation??(l?.operationId===n.quote?.operationId?n.operation:null);return n.quote&&l&&ee(n.quote,l),l&&y&&Z(y,{operationId:l.operationId,membershipId:V(l)?l.membershipId:null,...V(l)?{featureQuantities:l.featureQuantities??{}}:{}},"Purchase operation changed"),(c||l?.operationId!==n.quote?.operationId)&&(C++,i?.receiptId===d&&(f=i.purchaseRequestId)),i?.canReselect===!0&&i.purchaseRequestId===I&&!(r.pendingCommands??[r.pendingCommand]).some(w=>w?.requestId===I)&&(I=null),n={...n,...i?.receiptId===d?i:{},...t!==void 0&&!c&&a?.canReselect!==void 0?{canReselect:a.canReselect}:{},quote:l,operation:te(n.operation,y,!0)},G(),!0}function O(e,o,t){return new Promise((s,i)=>{let a=!1,c=()=>{clearTimeout(P),q.signal.removeEventListener("abort",w)},l=Q=>{a||(a=!0,c(),s(Q))},y=Q=>{a||(a=!0,c(),i(Q))},w=()=>y(new u("IDENTITY_CHANGED","Paywall presentation has closed")),P=setTimeout(()=>y(new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t)),Math.max(0,o-Date.now()));q.signal.addEventListener("abort",w,{once:!0}),q.signal.aborted&&w(),e.then(l,y)})}function ne(e){return new Promise(o=>{let t=()=>{clearTimeout(s),q.signal.removeEventListener("abort",t),o()},s=setTimeout(t,e);q.signal.addEventListener("abort",t,{once:!0}),q.signal.aborted&&t()})}function j(e,o){b();let t=v.get(e)??r.pendingCommands?.find(a=>a.requestId===e)??r.pendingCommand;if(t?.operation==="submit"&&t.requestId===e&&t.nodeId===h&&t.visit===E){o.type==="paywall_quote"&&t.input.type==="paywall_quote"&&t.input.predecessor&&!o.predecessor&&(o={...o,predecessor:t.input.predecessor});let a=L.parse(t),c=L.parse({...t,input:o});if(a.operation!=="submit"||c.operation!=="submit"||JSON.stringify(a.input)!==JSON.stringify(c.input))throw new u("CONFLICT","A purchase request cannot change its input");return v.set(e,a),a}let s=r.view;if(!s||s.nodeId!==h||s.visit!==E||s.paywall?.receiptId!==d)throw new u("PRECONDITION_FAILED","The Paywall visit has changed");let i=L.parse({operation:"submit",requestId:e,nodeId:h,visit:E,revision:s.revision,input:structuredClone(o)});if(i.operation!=="submit")throw new u("INVALID_REQUEST","A purchase submission is required");return v.set(e,i),i}async function x(e,o){b();let{requestId:t,input:s}=e,i=Date.now()+3e4;T.add(t);try{let a=await O(r.submit(e),i,t);for(;a.run.pendingRequest?.requestId===t&&Date.now()<i&&!p&&(await ne(Math.min(1e3,i-Date.now())),!(p||Date.now()>=i));)a=await O(r.resume(t),i,t);if(p)throw new u("IDENTITY_CHANGED","Paywall presentation has closed");if(a.run.pendingRequest?.requestId===t)throw new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t);if(!S(a,o,s.type==="paywall_confirm"||s.type==="paywall_cancel"?s.operationId:void 0))throw new u("PRECONDITION_FAILED","The purchase selection has changed");I===t&&(I=null)}catch(a){if(I=t,s.type==="paywall_quote"&&r.settle&&!p&&a instanceof u&&a.status!==void 0&&![401,425].includes(a.status)&&!a.retryable&&a.recovery!=="recover_operation")try{if((await O(r.settle(t),i,t)).settlement?.state==="settled"){let l=await O(r.get(),i,t);S(l,o)&&l.run.paywall?.purchaseRequestId===t&&n.canReselect===!0&&v.delete(t)}}catch{}throw a instanceof u&&a.code==="COMMAND_PENDING"&&a.status===void 0&&v.delete(t),a}finally{T.delete(t)}}async function k(e){if(!n.quote)throw new u("INVALID_REQUEST","A quoted purchase is required");let o=e==="confirm"?"paywall_confirm":"paywall_cancel",t=[...v.values(),...r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])].find(i=>i.operation==="submit"&&i.input.type===o&&"operationId"in i.input&&i.input.operationId===n.quote.operationId),s=t?.operation==="submit"&&t.input.type===o&&"operationId"in t.input&&t.input.operationId===n.quote.operationId?t.requestId:crypto.randomUUID();if(await x(j(s,{type:e==="confirm"?"paywall_confirm":"paywall_cancel",operationId:n.quote.operationId,...e==="confirm"&&n.quote.merchantTerms?{merchantConfirmation:H(n.quote.merchantTerms)}:{}}),C),!n.operation)throw new u("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(n.operation)}let oe={get view(){return structuredClone(D())},get quote(){return n.quote?structuredClone(n.quote):null},get operation(){return n.operation?structuredClone(n.operation):null},get webViewUrl(){return r.webViewUrl},get locale(){return r.view?.locale??m.locale},get canReselect(){return n.canReselect===!0&&I===null},get recovery(){let e=r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[]),o=r.pendingPurchase;if(o&&(o.receiptId!==d||o.operationId!==n.quote?.operationId))return{type:"recover",operationId:o.operationId,requestId:e[0]?.requestId??null};let t=Y({quote:n.quote,operation:n.operation,requestId:e[0]?.requestId??I??f,pending:T.size>0||e.length>0||I!==null,destroyed:p,canReselect:n.canReselect});return t.type==="recover"&&t.requestId===null&&!p&&r.hasDurableJournal===!0&&!n.quote&&!n.operation&&(n.selectionGeneration??0)===0&&!o&&!e.length&&!T.size&&!f?{type:"native",operationId:null}:t},get pendingCancellation(){return!p&&(r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])).some(e=>e.operation==="submit"&&e.nodeId===h&&e.visit===E&&e.input.type==="paywall_cancel"&&e.input.operationId===n.quote?.operationId)},subscribe(e){return p?()=>{}:(A.add(e),()=>A.delete(e))},async refresh(){b();let e=C,o=await r.get();if(S(o,e),o.run.paywall?.receiptId!==d)throw new u("PRECONDITION_FAILED","Paywall presentation has changed");return M()},preview(e){let o=D();if(!o)return Promise.reject(new u("PRECONDITION_FAILED","Load the Paywall presentation first"));if(f&&f!==e.requestId&&(g||n.canReselect!==!0))return Promise.reject(new u("COMMAND_PENDING","Retry the original purchase before starting another"));let t=o.document.buttons[e.actionId],s=t?.type==="checkout"?J(t.product,e.selection,o.capabilities):null;if(!s)return Promise.reject(new u("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let i=z(o.document.screen,s,e.selection,o.capabilities),a=f!==e.requestId&&(n.selectionGeneration??0)>0?{operationId:n.quote?.operationId??null,generation:n.selectionGeneration??0}:void 0,c=r.view?.parameters.commerce;if(c&&typeof c=="object"&&!Array.isArray(c)&&c.intent==="subscription_change"&&!e.subscriptionChange)return Promise.reject(new u("INVALID_REQUEST","Choose the existing membership for this subscription change"));if(e.subscriptionChange&&e.nativeOffer)return Promise.reject(new u("INVALID_REQUEST","A web membership change cannot include a store offer"));if(a&&n.canReselect!==!0)return Promise.reject(new u("COMMAND_PENDING","Original purchase requires authoritative termination"));let l;try{l=j(e.requestId,{type:"paywall_quote",actionId:e.actionId,productVersionId:s,...Object.keys(i).length?{featureQuantities:i}:{},...a?{predecessor:a}:{},...e.offerId?{offerId:e.offerId}:{},...e.nativeOffer?{nativeOffer:e.nativeOffer}:{},...e.subscriptionChange?{subscriptionChange:e.subscriptionChange}:{}})}catch(P){return Promise.reject(P)}if(f===e.requestId&&g)return g;f!==e.requestId&&C++;let y=C;f=e.requestId;let w=(async()=>{if(await x(l,y),!n.quote)throw new u("INVALID_RESPONSE","The accepted quote is missing");return $(n.quote,{productVersionId:s,featureQuantities:i,subscriptionChange:e.subscriptionChange},"The selected purchase changed"),structuredClone(n.quote)})();return g=w,w.then(()=>{g===w&&(g=null)},P=>{g===w&&(g=null),f===e.requestId&&r.pendingCommand?.requestId!==e.requestId&&P instanceof u&&P.status!==void 0&&P.status<500&&![401,425].includes(P.status)&&(f=null)}),w},confirm:()=>k("confirm"),cancel:()=>k("cancel"),async read(){if(b(),!n.quote)throw new u("INVALID_REQUEST","A quoted purchase is required");let e=n.quote.operationId,o=C,t=r.pendingCommands?.find(l=>l.operation==="submit"&&(l.input.type==="paywall_confirm"||l.input.type==="paywall_cancel")&&l.input.operationId===e)??r.pendingCommand;t?.operation==="submit"&&(t.input.type==="paywall_confirm"||t.input.type==="paywall_cancel")&&t.input.operationId===e&&await r.settle?.(t.requestId);let s=await r.get(void 0,{receiptId:d,operationId:e});b();let i=U(s);if(i?.quote&&i.quote.operationId!==e||i?.operation&&i.operation.operationId!==e)throw new u("INVALID_RESPONSE","Purchase operation changed");let a=S(s,o,e),c=a?n.operation:i?.operation;if(!c)throw new u("INVALID_RESPONSE","The current purchase result is missing");return a&&T.size===0&&!(r.pendingCommands?.length??(r.pendingCommand?1:0))&&(I=null),structuredClone(c)},destroy(){p=!0,re(),A.clear(),q.abort(),v.clear()}},re=r.subscribe(e=>{p||e.nodeId!==h||e.visit!==E||e.paywall?.receiptId!==d||(e.paywall.selectionGeneration??0)<(n.selectionGeneration??0)||(F(e.paywall.resolution),n={...n,resolution:e.paywall.resolution},G())});return{session:oe,load:M}}export{ye as a};
@@ -1 +1 @@
1
- import{b as r}from"./chunk-COMZFFUA.js";var R=r.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),H=r.enum([...R.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED","SENSITIVE_OUTPUT_REQUIRED"]),j=r.enum([...R.options,"stale_revision"]),v=r.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),x=r.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","IDENTITY_CONTEXT_CHANGED","CUSTOMER_BINDING_CONFLICT","RUN_CONTRACT_MISMATCH","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED","FUNNEL_PAUSED"]),L={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};var S={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",CUSTOMER_SESSION_REQUIRED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",INVALID_STATE:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",PURCHASE_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",PURCHASE_STORAGE_CONFLICT:"resolve_conflict",PURCHASE_STORAGE_INVALID:"recover_operation",EXECUTION_POLICY_REFUSED:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",ROUTE_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",COUPON_UNAVAILABLE:"reload_state",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function g(e,o){if(e==="CONFLICT"&&o===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&o===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION"||e==="SENSITIVE_OUTPUT_REQUIRED")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(S,e)){let n=S[e];return{retryable:n==="retry_same_request",recovery:n}}let t=R.safeParse(e);return t.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:L[t.data].recovery}:{retryable:!1,recovery:"contact_support"}}function Q(e,o){let t=R.safeParse(e);if(t.success)return e==="CONFLICT"?[409,412,425].includes(o):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(o):e==="INVALID_REQUEST"?[400,405,415,422].includes(o):e==="NOT_CONFIGURED"?[501,503].includes(o):L[t.data].status===o;let n={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],SENSITIVE_OUTPUT_REQUIRED:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(n,e)&&(n[e]?.includes(o)??!1)}function P(e,o=Date.now()){if(e===null)return;let t=e.trim();if(/^\d+$/.test(t)){let s=Number(t);return Number.isSafeInteger(s)?s:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(t))return;let n=Date.parse(t);return Number.isFinite(n)?Math.max(0,Math.ceil((n-o)/1e3)):void 0}var y=r.object({retryable:r.boolean(),recovery:v,reason:x.optional(),retryAfterSeconds:r.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),b=r.object({requestId:r.uuid().optional(),error:r.object({code:r.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:r.string(),...y.partial().shape})}),z=r.object({error:b.shape.error.extend({requestId:r.uuid().optional()})}),Y=r.object({error:r.string(),code:r.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:r.uuid(),...y.shape});function $(e,o,t={}){let n=g(e,o),s=t.reason==="RESULT_UNKNOWN"?"recover_operation":t.recovery??n.recovery,A=n.retryable&&t.retryable!==!1&&s!=="recover_operation",i=A?P(t.retryAfter??null):void 0;return{...n,retryable:A,recovery:s,...i===void 0?{}:{retryAfterSeconds:i},...t.reason?{reason:t.reason}:{}}}var V=r.enum(["sandbox","live"]),W=r.object({projectId:r.string().min(1),environment:V}).strict();var J=r.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),u=r.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),M=r.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let o=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return o==="-0"?"0":o}),p=u.refine(e=>/[1-9]/.test(e),"数量必须大于 0"),D=r.string().min(1).max(64),B=r.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),C=r.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),ee=r.record(D,r.union([r.string().max(120),r.number().finite(),r.boolean()])).refine(e=>Object.keys(e).length<=16,"最多 16 个计价属性").transform(e=>Object.fromEntries(Object.entries(e).map(([o,t])=>[o,String(t)]))),U=r.record(D,r.union([r.string().max(120),r.number().finite(),r.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"匹配条件最多 8 个属性"),I=e=>{let o=e.startsWith("-");o&&(e=e.slice(1));let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");let s=BigInt(t)*BigInt("1000000")+BigInt(n.padEnd(6,"0"));return o?-s:s},h=r.array(r.object({upTo:p.nullable(),cost:u}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((o,t)=>{let n=e[t-1]?.upTo;return o.upTo!==null&&(t===0||n!=null&&I(o.upTo)>I(n))}),"阶梯上限必须递增,最后一档为无限"),G=r.object({key:C,match:U,priority:r.number().int().default(0),cost:u.optional(),tiers:h.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"维度需要指定单价或阶梯"),F=r.object({key:C,match:U,factor:p.optional(),add:M.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),k=r.object({units:p.default("1"),cost:u,tiers:h.optional(),dimensions:r.array(G).max(12).optional(),multipliers:r.array(F).max(4).optional()}).strict().superRefine((e,o)=>{let t=e.dimensions??[],n=e.multipliers??[];(new Set(t.map(i=>i.key)).size!==t.length||new Set(n.map(i=>i.key)).size!==n.length)&&o.addIssue({code:"custom",message:"维度和倍率的 ID 不能重复"});for(let[i,a]of t.entries())for(let c of t.slice(i+1))Object.keys(a.match).length===Object.keys(c.match).length&&a.priority===c.priority&&!Object.keys(a.match).some(E=>c.match[E]!==void 0&&c.match[E]!==a.match[E])&&o.addIssue({code:"custom",message:"维度可能同时匹配,请调整优先级"});let s=[e.cost,...(e.tiers??[]).map(i=>i.cost),...t.flatMap(i=>[...i.cost===void 0?[]:[i.cost],...(i.tiers??[]).map(a=>a.cost)])],A=I(e.units);for(let i of s)for(let a=0;a<1<<n.length;a++){let c=n.filter((N,_)=>a&1<<_);if(c.some((N,_)=>c.slice(_+1).some(d=>Object.keys(N.match).some(l=>d.match[l]!==void 0&&d.match[l]!==N.match[l]))))continue;let E=I(i),O=BigInt("1"),f=BigInt("0");for(let[N,_]of n.entries())a&1<<N&&(E*=I(_.factor??"1"),O*=BigInt("1000000"),f+=I(_.add??"0"));let T=(E+f*O)*BigInt("1000000"),m=O*A;(T<BigInt("0")||T%m!==BigInt("0")||T/m>BigInt("999999999999999999"))&&o.addIssue({code:"custom",message:"每个业务单位的最终单价必须非负、在范围内且能精确表示为最多 6 位小数"})}}),re=k.safeExtend({featureKey:B});export{R as a,v as b,x as c,Q as d,b as e,$ as f,V as g,W as h,J as i,u as j,M as k,B as l,ee as m};
1
+ import{b as r}from"./chunk-PZTWDJHN.js";var R=r.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),H=r.enum([...R.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED","SENSITIVE_OUTPUT_REQUIRED"]),j=r.enum([...R.options,"stale_revision"]),v=r.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),x=r.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","IDENTITY_CONTEXT_CHANGED","CUSTOMER_BINDING_CONFLICT","RUN_CONTRACT_MISMATCH","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED","FUNNEL_PAUSED"]),L={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};var S={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",CUSTOMER_SESSION_REQUIRED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",INVALID_STATE:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",PURCHASE_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",PURCHASE_STORAGE_CONFLICT:"resolve_conflict",PURCHASE_STORAGE_INVALID:"recover_operation",EXECUTION_POLICY_REFUSED:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",ROUTE_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",COUPON_UNAVAILABLE:"reload_state",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function g(e,o){if(e==="CONFLICT"&&o===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&o===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION"||e==="SENSITIVE_OUTPUT_REQUIRED")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(S,e)){let n=S[e];return{retryable:n==="retry_same_request",recovery:n}}let t=R.safeParse(e);return t.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:L[t.data].recovery}:{retryable:!1,recovery:"contact_support"}}function Q(e,o){let t=R.safeParse(e);if(t.success)return e==="CONFLICT"?[409,412,425].includes(o):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(o):e==="INVALID_REQUEST"?[400,405,415,422].includes(o):e==="NOT_CONFIGURED"?[501,503].includes(o):L[t.data].status===o;let n={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],SENSITIVE_OUTPUT_REQUIRED:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(n,e)&&(n[e]?.includes(o)??!1)}function P(e,o=Date.now()){if(e===null)return;let t=e.trim();if(/^\d+$/.test(t)){let s=Number(t);return Number.isSafeInteger(s)?s:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(t))return;let n=Date.parse(t);return Number.isFinite(n)?Math.max(0,Math.ceil((n-o)/1e3)):void 0}var y=r.object({retryable:r.boolean(),recovery:v,reason:x.optional(),retryAfterSeconds:r.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),b=r.object({requestId:r.uuid().optional(),error:r.object({code:r.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:r.string(),...y.partial().shape})}),z=r.object({error:b.shape.error.extend({requestId:r.uuid().optional()})}),Y=r.object({error:r.string(),code:r.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:r.uuid(),...y.shape});function $(e,o,t={}){let n=g(e,o),s=t.reason==="RESULT_UNKNOWN"?"recover_operation":t.recovery??n.recovery,A=n.retryable&&t.retryable!==!1&&s!=="recover_operation",i=A?P(t.retryAfter??null):void 0;return{...n,retryable:A,recovery:s,...i===void 0?{}:{retryAfterSeconds:i},...t.reason?{reason:t.reason}:{}}}var V=r.enum(["sandbox","live"]),W=r.object({projectId:r.string().min(1),environment:V}).strict();var J=r.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),u=r.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),M=r.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let o=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return o==="-0"?"0":o}),p=u.refine(e=>/[1-9]/.test(e),"数量必须大于 0"),D=r.string().min(1).max(64),B=r.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),C=r.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),ee=r.record(D,r.union([r.string().max(120),r.number().finite(),r.boolean()])).refine(e=>Object.keys(e).length<=16,"最多 16 个计价属性").transform(e=>Object.fromEntries(Object.entries(e).map(([o,t])=>[o,String(t)]))),U=r.record(D,r.union([r.string().max(120),r.number().finite(),r.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"匹配条件最多 8 个属性"),I=e=>{let o=e.startsWith("-");o&&(e=e.slice(1));let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");let s=BigInt(t)*BigInt("1000000")+BigInt(n.padEnd(6,"0"));return o?-s:s},h=r.array(r.object({upTo:p.nullable(),cost:u}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((o,t)=>{let n=e[t-1]?.upTo;return o.upTo!==null&&(t===0||n!=null&&I(o.upTo)>I(n))}),"阶梯上限必须递增,最后一档为无限"),G=r.object({key:C,match:U,priority:r.number().int().default(0),cost:u.optional(),tiers:h.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"维度需要指定单价或阶梯"),F=r.object({key:C,match:U,factor:p.optional(),add:M.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),k=r.object({units:p.default("1"),cost:u,tiers:h.optional(),dimensions:r.array(G).max(12).optional(),multipliers:r.array(F).max(4).optional()}).strict().superRefine((e,o)=>{let t=e.dimensions??[],n=e.multipliers??[];(new Set(t.map(i=>i.key)).size!==t.length||new Set(n.map(i=>i.key)).size!==n.length)&&o.addIssue({code:"custom",message:"维度和倍率的 ID 不能重复"});for(let[i,a]of t.entries())for(let c of t.slice(i+1))Object.keys(a.match).length===Object.keys(c.match).length&&a.priority===c.priority&&!Object.keys(a.match).some(E=>c.match[E]!==void 0&&c.match[E]!==a.match[E])&&o.addIssue({code:"custom",message:"维度可能同时匹配,请调整优先级"});let s=[e.cost,...(e.tiers??[]).map(i=>i.cost),...t.flatMap(i=>[...i.cost===void 0?[]:[i.cost],...(i.tiers??[]).map(a=>a.cost)])],A=I(e.units);for(let i of s)for(let a=0;a<1<<n.length;a++){let c=n.filter((N,_)=>a&1<<_);if(c.some((N,_)=>c.slice(_+1).some(d=>Object.keys(N.match).some(l=>d.match[l]!==void 0&&d.match[l]!==N.match[l]))))continue;let E=I(i),O=BigInt("1"),f=BigInt("0");for(let[N,_]of n.entries())a&1<<N&&(E*=I(_.factor??"1"),O*=BigInt("1000000"),f+=I(_.add??"0"));let T=(E+f*O)*BigInt("1000000"),m=O*A;(T<BigInt("0")||T%m!==BigInt("0")||T/m>BigInt("999999999999999999"))&&o.addIssue({code:"custom",message:"每个业务单位的最终单价必须非负、在范围内且能精确表示为最多 6 位小数"})}}),re=k.safeExtend({featureKey:B});export{R as a,v as b,x as c,Q as d,b as e,$ as f,V as g,W as h,J as i,u as j,M as k,B as l,ee as m};
@@ -1 +1 @@
1
- import{b as Q}from"./chunk-6VWVBQFR.js";import{a as j,b as Z,c as x}from"./chunk-XBF44N3Z.js";import{a as L,b as F,c as H,j as l}from"./chunk-LB2ZRTRA.js";import{b as e}from"./chunk-COMZFFUA.js";var fe=["purchase.subscription","purchase.one_time","purchase.prepaid","purchase.trial","purchase.seats","purchase.tiered","tax.automatic","discount.percent.once","discount.percent.repeating","discount.percent.forever","discount.amount.once","discount.amount.repeating","discount.amount.forever","subscription.cancel.immediate","subscription.cancel.renewal","subscription.resume","subscription.plan.immediate","subscription.plan.renewal","subscription.seats","subscription.quantity","subscription.billing_cycle","subscription.proration","refund.full","refund.partial","refund.revoke"],G=e.enum(fe),K=e.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","subscription.change.closed","invoice.paid","refund.updated"]);var W=e.enum(["replace","stack_native"]);var o=e.string().min(1).max(200),c=e.iso.datetime({offset:!0}),i=e.number().int().nonnegative().max(1e8),y=e.string().regex(/^[A-Z]{3}$/),ge=e.record(e.uuid(),e.number().int().min(0).max(1e4)).refine(t=>Object.keys(t).length<=100),m=e.strictObject({priceId:e.uuid(),productVersionId:e.uuid(),productId:o,quantity:e.number().int().min(1).max(1e6),unitAmountMinor:i,totalMinor:i,interval:e.enum(["week","month","year","one_off"]),intervalCount:e.number().int().min(1).max(52),kind:e.enum(["fixed","prepaid","seat"]),tiers:e.strictObject({mode:e.enum(["graduated","volume"]),tiers:e.array(e.strictObject({upTo:e.number().int().positive().nullable(),unitAmountMinor:i,flatAmountMinor:i.optional()})).min(2).max(12)}).nullable()}),I=e.strictObject({grantId:e.uuid(),couponId:e.uuid(),amountMinor:i,applicationPolicy:W.optional(),applicableProductIds:e.array(o).min(1).max(100).optional(),terms:e.discriminatedUnion("type",[e.strictObject({type:e.literal("percent"),percentOff:e.number().gt(0).max(100)}),e.strictObject({type:e.literal("amount"),amountOffMinor:i,currency:y})]),duration:e.discriminatedUnion("type",[e.strictObject({type:e.literal("once")}),e.strictObject({type:e.literal("forever")}),e.strictObject({type:e.literal("repeating"),months:e.number().int().min(1).max(36)})])}),E={provider:e.literal("merchant"),executor:e.literal("merchant"),operationId:e.uuid(),customerId:e.uuid(),configurationRevision:e.number().int().nonnegative(),connectionRevision:e.number().int().nonnegative(),currency:y,expiresAt:c},xe=e.strictObject({...E,type:e.literal("purchase"),mode:e.enum(["payment","subscription"]),lineItems:e.array(m).min(1).max(100),catalogAmountMinor:i,nativeDiscountMinor:i.optional(),discount:I.nullable(),trialPeriodDays:e.number().int().min(1).max(730).nullable(),automaticTax:e.boolean()}).refine(t=>t.lineItems.reduce((n,r)=>n+r.totalMinor,0)===t.catalogAmountMinor&&(t.discount?.amountMinor??0)+(t.nativeDiscountMinor??0)<=t.catalogAmountMinor&&new Set(t.lineItems.map(n=>n.priceId)).size===t.lineItems.length,"Purchase lines must retain the original total and unique Price identities"),S=e.strictObject({...E,type:e.literal("subscription_change"),subscriptionId:e.uuid(),merchantSubscriptionId:o,membershipId:e.uuid(),subscriptionAction:e.enum(["update","cancel","schedule","release"]),supersedesOperationId:e.uuid().nullable(),change:e.discriminatedUnion("type",[e.strictObject({type:e.literal("cancel")}),e.strictObject({type:e.literal("uncancel")}),e.strictObject({type:e.literal("plan"),productVersionId:e.uuid(),featureQuantities:ge.optional()}),e.strictObject({type:e.literal("seats"),licenseKey:o,quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("quantity"),internal_feature_id:e.uuid(),quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("billing_cycle"),billingCycleAnchor:e.union([e.literal("now"),e.number().int().positive()])})]),timing:e.enum(["immediate","renewal"]),effectiveAt:c,creditMinor:i,debitMinor:i,totalMinor:i,discountMinor:i,discount:I.nullable().optional(),taxMinor:i,proration:e.enum(["none","create_prorations","always_invoice"]),lineItems:e.array(m.extend({quantity:e.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:e.array(e.uuid()).max(100),sourceLineItems:e.array(m).min(1).max(100).optional()}),ye=e.strictObject({...E,type:e.literal("refund"),invoiceId:e.uuid(),merchantInvoiceId:o,amountMinor:i.refine(t=>t>0),mode:e.enum(["full","partial"]),entitlementAction:e.enum(["retain","revoke"]),cancelSubscriptions:e.array(o).max(100)}),Y=e.discriminatedUnion("type",[xe,S,ye]);function Ye(t){let n=new Set;if(t.type==="purchase")n.add(t.mode==="subscription"?"purchase.subscription":"purchase.one_time"),t.lineItems.some(r=>r.kind==="prepaid")&&n.add("purchase.prepaid"),t.lineItems.some(r=>r.kind==="seat")&&n.add("purchase.seats"),t.lineItems.some(r=>r.tiers!==null)&&n.add("purchase.tiered"),t.trialPeriodDays!==null&&n.add("purchase.trial"),t.automaticTax&&n.add("tax.automatic"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`);else if(t.type==="refund")n.add(`refund.${t.mode}`),t.entitlementAction==="revoke"&&n.add("refund.revoke");else{let r=t.change.type;r==="cancel"?n.add(`subscription.cancel.${t.timing}`):r==="uncancel"?n.add("subscription.resume"):r==="plan"?n.add(`subscription.plan.${t.timing}`):n.add(`subscription.${r}`),t.proration!=="none"&&n.add("subscription.proration"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`)}return[...n].sort()}function et(t){return t.type==="purchase"?t.mode==="subscription"?["purchase.completed","purchase.closed","subscription.observed","invoice.paid"]:["purchase.completed","purchase.closed"]:t.type==="subscription_change"?["subscription.change.completed","subscription.change.closed","subscription.observed",...t.change.type==="cancel"||t.change.type==="uncancel"?[]:["invoice.paid"]]:["refund.updated",...t.entitlementAction==="revoke"&&t.cancelSubscriptions.length?["subscription.observed"]:[]]}var Ie=e.strictObject({phase:e.enum(["execution","payment","fulfillment","recording"]),code:L,reason:H.optional(),recovery:F,retryable:e.boolean()}).refine(t=>t.reason!=="RESULT_UNKNOWN"||!t.retryable&&t.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),Se=e.strictObject({type:e.literal("redirect"),url:e.url().startsWith("https://"),expiresAt:c}),B={operationId:e.uuid(),customerId:e.uuid(),merchantExecutionId:o,fulfillmentStatus:e.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:e.enum(["not_ready","pending","accepted","failed"]),updatedAt:c,problem:Ie.nullable(),pollAfterMs:e.number().int().min(1e3).max(6e4).nullable()},k=e.discriminatedUnion("type",[e.strictObject({...B,type:e.literal("purchase"),merchantOrderId:o.nullable(),paymentStatus:e.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:e.url().refine(t=>new URL(t).protocol==="https:").nullable(),checkoutExpiresAt:c.nullable()}).refine(t=>!t.checkoutUrl||["not_started","pending"].includes(t.paymentStatus)&&t.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),e.strictObject({...B,type:e.literal("subscription_change"),status:e.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:o,scheduledFor:c.nullable(),nextAction:Se.optional()}).refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"A scheduled change retains its future effective time"),e.strictObject({...B,type:e.literal("refund"),status:e.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:o.nullable()}).refine(t=>t.status!=="succeeded"||t.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),ee=e.discriminatedUnion("lookup",[e.strictObject({lookup:e.literal("found"),operationId:e.uuid(),customerId:e.uuid(),execution:k,readAt:c}),e.strictObject({lookup:e.literal("not_received"),operationId:e.uuid(),customerId:e.uuid(),execution:e.null(),readAt:c})]).refine(t=>!t.execution||t.execution.operationId===t.operationId&&t.execution.customerId===t.customerId,"Lookup must retain the original Customer and operation"),te=e.strictObject({merchantPriceId:o,productId:o,kind:e.enum(["fixed","prepaid"]),currency:y,unitAmountMinor:i,interval:e.enum(["one_off","day","week","month","year"]),intervalCount:e.number().int().min(1).max(100)}),X={merchantItemId:o,quantity:e.number().int().positive().max(1e6)},Me=t=>t.priceId??JSON.stringify(t.nativePrice),T=e.strictObject({merchantSubscriptionId:o,revision:e.number().int().positive(),status:e.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:c,periodEndsAt:c,cancelAtPeriodEnd:e.boolean(),hasDiscounts:e.boolean(),items:e.array(e.union([e.strictObject({...X,priceId:e.uuid()}),e.strictObject({...X,nativePrice:te})])).min(1).max(100)}).refine(t=>Date.parse(t.periodEndsAt)>Date.parse(t.periodStartsAt)&&new Set(t.items.map(Me)).size===t.items.length&&new Set(t.items.map(n=>n.merchantItemId)).size===t.items.length,"Subscription periods and Price identities must be unambiguous"),J={merchantLineId:o,quantity:e.number().int().nonnegative().max(1e6),subtotalMinor:e.number().int().min(-1e8).max(1e8),discountMinor:i,taxMinor:i,totalMinor:e.number().int().min(-1e8).max(2e8),periodStartsAt:c.nullable(),periodEndsAt:c.nullable()},R=e.strictObject({merchantInvoiceId:o,reason:e.enum(["renewal","adjustment"]).optional(),currency:y,subtotalMinor:i,discountMinor:i,taxMinor:i,totalMinor:i,paidMinor:i,periodStartsAt:c.nullable(),periodEndsAt:c.nullable(),lines:e.array(e.union([e.strictObject({...J,priceId:e.uuid()}),e.strictObject({...J,nativePrice:te})]).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&(t.subtotalMinor<0?t.discountMinor===0&&t.taxMinor===0:t.discountMinor<=t.subtotalMinor),"Invoice line amounts must retain the complete debit or credit")).min(1).max(100)}).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&t.discountMinor<=t.subtotalMinor&&t.paidMinor===t.totalMinor&&new Set(t.lines.map(n=>n.merchantLineId)).size===t.lines.length&&t.lines.reduce((n,r)=>n+r.subtotalMinor,0)===t.subtotalMinor&&t.lines.reduce((n,r)=>n+r.discountMinor,0)===t.discountMinor&&t.lines.reduce((n,r)=>n+r.taxMinor,0)===t.taxMinor&&t.lines.reduce((n,r)=>n+r.totalMinor,0)===t.totalMinor,"A paid Invoice retains the complete financial amounts"),p={eventId:e.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:e.uuid(),occurredAt:c},_e=e.strictObject({...p,type:e.literal("purchase.completed"),operationId:e.uuid(),merchantOrderId:o,paymentStatus:e.enum(["paid","trialing","no_payment_required"]),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable(),subscription:T.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),Oe=e.strictObject({...p,type:e.literal("purchase.closed"),operationId:e.uuid(),status:e.enum(["failed","expired","canceled"])}),ve=e.strictObject({...p,type:e.literal("subscription.observed"),operationId:e.uuid().nullable(),subscription:T}),Ae=e.strictObject({...p,type:e.literal("subscription.change.completed"),operationId:e.uuid(),status:e.enum(["scheduled","applied"]),scheduledFor:c.nullable(),subscription:T.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities"),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),je=e.strictObject({...p,type:e.literal("subscription.change.closed"),operationId:e.uuid(),merchantSubscriptionId:o,merchantInvoiceId:o.nullable(),status:e.enum(["failed","expired","canceled"])}),Pe=e.strictObject({...p,type:e.literal("invoice.paid"),merchantSubscriptionId:o.nullable(),invoice:R}),qe=e.strictObject({...p,type:e.literal("refund.updated"),operationId:e.uuid().nullable(),merchantInvoiceId:o.optional(),merchantRefundId:o,status:e.enum(["pending","succeeded","failed"]),amountMinor:i.refine(t=>t>0),currency:y}),tt=[_e.refine(t=>t.paymentStatus!=="paid"||t.invoice!==null,"A paid purchase includes its Invoice"),Oe,ve.refine(t=>t.operationId===null||t.subscription.items.every(n=>"priceId"in n),"Native Price references cannot replace an operation's quoted Prices"),Ae.refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),je,Pe,qe.refine(t=>t.operationId!==null||t.merchantInvoiceId!==void 0,"A native refund names its Invoice")];var z=e.strictObject({days:e.number().int().min(1).max(730),cardRequired:e.boolean()}),at=e.object({...z.shape,featureAllowances:e.record(e.uuid(),e.number().int().min(0).max(1e9)),creditAmounts:e.record(e.uuid(),l)}).strict(),ct=e.object({id:e.uuid(),planVersionId:e.uuid(),slot:e.string(),cardRequired:e.boolean(),status:e.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),createdAt:e.iso.datetime()}).strict();var Ce=e.number().int().positive().max(2e8),ne=e.number().int().min(0).max(2e8),re=t=>t.mode==="partial"==(t.amountMinor!==void 0),P=e.strictObject({mode:e.enum(["full","partial"]),amountMinor:Ce.optional(),entitlementAction:e.enum(["retain","revoke"])});var a=e.string().min(1).max(200),b=e.iso.datetime({offset:!0}),f=ne,ie=f.maxValue,C=e.number().int().min(-ie).max(ie),q=e.string().regex(/^[A-Z]{3}$/),oe=e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),ae=e.array(a).max(100).refine(t=>new Set(t).size===t.length),Be=e.strictObject({merchantProductId:a,merchantPriceId:a,productVersionId:e.uuid().optional(),quantity:l.refine(t=>/[1-9]/.test(t))}),D={subject:Z,operationId:e.uuid(),configurationRevision:oe,connectionRevision:oe,expiresAt:b},w=e.discriminatedUnion("action",[e.strictObject({...D,action:e.literal("purchase"),mode:e.enum(["payment","subscription"]),currency:q,items:e.array(Be).min(1).max(100),offerRefs:ae}),e.strictObject({...D,action:e.literal("subscription_change"),currency:q,merchantSubscriptionId:a,change:S.shape.change,timing:S.shape.timing,proration:S.shape.proration,offerRefs:ae}),e.strictObject({...D,action:e.literal("refund"),currency:q,merchantInvoiceId:a,mode:P.shape.mode,amountMinor:P.shape.amountMinor,entitlementAction:P.shape.entitlementAction}).refine(re,"Only a partial refund chooses amountMinor")]),gt=e.strictObject({request:w,requestedAt:b,preparationAllowed:e.boolean()}).refine(t=>!t.preparationAllowed||Date.parse(t.requestedAt)<Date.parse(t.request.expiresAt),"Preparation authority must be within its original validity"),Ee=e.strictObject({merchantLineId:a,merchantPriceId:a.nullable(),quantity:l.refine(t=>/[1-9]/.test(t)),subtotalMinor:C,discountMinor:f,taxMinor:f.nullable(),totalMinor:C.nullable()}).refine(t=>t.taxMinor===null==(t.totalMinor===null)&&(t.totalMinor===null||t.totalMinor===t.subtotalMinor-t.discountMinor+t.taxMinor),"A quote line retains exact known totals; unknown tax is not zero"),ke=e.strictObject({items:e.array(e.strictObject({merchantPriceId:a,quantity:l.refine(t=>/[1-9]/.test(t)),interval:m.shape.interval.exclude(["one_off"]),intervalCount:m.shape.intervalCount,amountMinor:m.shape.totalMinor,amountAfterOfferMinor:m.shape.totalMinor.optional()})).min(1).max(100),trial:z.nullable(),discount:I.nullable().optional(),discountExpiresAt:b.nullable().optional(),initialAmountMinor:m.shape.totalMinor.optional()}),ce=e.strictObject({request:w,requestDigest:j,merchantQuoteId:a,quoteTermsDigest:j,termsVersion:a,sourceRevisions:e.array(e.strictObject({reference:a,revision:a})).max(100),observedAt:b,expiresAt:b,currency:q,automaticTax:e.boolean(),lines:e.array(Ee).max(100),subscriptionTerms:ke.nullable(),subtotalMinor:C,discountMinor:f,nativeDiscountMinor:f.optional(),discount:I.nullable().optional(),taxMinor:f.nullable(),totalMinor:C.nullable(),effectiveAt:b.nullable(),expectedEffects:e.array(e.strictObject({reference:a,kind:e.enum(["grant","revoke","change"]),description:e.string().min(1).max(1e3),quantity:l.nullable(),unit:a.nullable()}).refine(t=>t.quantity===null==(t.unit===null),"Quantified effects name their native unit")).max(100),requiredConsents:e.array(e.strictObject({reference:a,version:a,summary:e.string().min(1).max(1e3)})).max(20)}),U=ce.superRefine((t,n)=>{let{quoteTermsDigest:r,...u}=t,h=t.lines.every(s=>s.taxMinor!==null),A=t.request.action==="purchase"&&t.request.mode==="subscription"!=(t.subscriptionTerms!==null),be=t.subscriptionTerms!==null&&(t.request.action==="refund"||t.request.action==="subscription_change"&&t.request.change.type==="cancel");(t.requestDigest!==x(t.request)||t.quoteTermsDigest!==x(u)||t.currency!==t.request.currency||A||be||t.lines.length===0&&(t.request.action!=="subscription_change"||t.subtotalMinor!==0||t.discountMinor!==0||t.taxMinor!==0||t.totalMinor!==0)||Date.parse(t.observedAt)>=Date.parse(t.expiresAt)||Date.parse(t.expiresAt)>Date.parse(t.request.expiresAt)||new Set(t.lines.map(s=>s.merchantLineId)).size!==t.lines.length||new Set(t.sourceRevisions.map(s=>s.reference)).size!==t.sourceRevisions.length||new Set(t.requiredConsents.map(s=>s.reference)).size!==t.requiredConsents.length||t.subtotalMinor!==t.lines.reduce((s,g)=>s+g.subtotalMinor,0)||t.discountMinor!==t.lines.reduce((s,g)=>s+g.discountMinor,0)||t.taxMinor!==null!==h||!h&&!t.automaticTax||t.taxMinor===null!=(t.totalMinor===null)||h&&(t.taxMinor!==t.lines.reduce((s,g)=>s+g.taxMinor,0)||t.totalMinor!==t.subtotalMinor-t.discountMinor+t.taxMinor)||t.request.action!=="subscription_change"&&(t.subtotalMinor<0||t.totalMinor!==null&&t.totalMinor<0)||t.request.action==="refund"&&(t.taxMinor===null||t.totalMinor===null||t.totalMinor<=0||t.request.mode==="partial"&&t.totalMinor!==t.request.amountMinor))&&n.addIssue({code:"custom",message:"Merchant terms must retain the original selection, scope, validity, digest and totals"})});function xt(t,n,r,u){return t.request.operationId===n&&t.request.action===r&&t.currency===u}function yt(t){return x(w.parse(t))}function It(t){return x(ce.omit({quoteTermsDigest:!0}).parse(t))}var Te=e.strictObject({quoteTermsDigest:j,consents:e.array(e.strictObject({reference:a,version:a})).max(20)});function St(t){return{quoteTermsDigest:t.quoteTermsDigest,consents:t.requiredConsents.map(({reference:n,version:r})=>({reference:n,version:r}))}}var Re=Te.extend({operationId:e.uuid()}).refine(t=>new Set(t.consents.map(n=>n.reference)).size===t.consents.length);function Mt(t,n){let r=U.parse(t),u=Re.parse(n);return u.operationId===r.request.operationId&&u.quoteTermsDigest===r.quoteTermsDigest&&u.consents.length===r.requiredConsents.length&&r.requiredConsents.every(h=>u.consents.some(A=>A.reference===h.reference&&A.version===h.version))}var M=3,jt="/integrations/indiana",Pt="X-Indiana-Merchant-Bridge-Version",ze=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],De=e.enum(ze),qt={session:{command:"session.create",authority:"merchant_user"},catalog:{command:"catalog.read",authority:"merchant_catalog_reader"},customer_commerce:{command:"customer.commerce.read",authority:"merchant_user"},presentation:{command:"presentation.resolve",authority:"merchant_user"},presentation_events:{command:"presentation.report",authority:"merchant_user"},purchases:{command:"purchase.execute",authority:"merchant_user"},operation_status:{command:"operation.read",authority:"merchant_user"},billing_records:{command:null,authority:"indiana_server_key"},subscription_changes:{command:"subscription.change",authority:"merchant_user"},refunds:{command:"refund.execute",authority:"merchant_refund_authority"}},$=e.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),ue=e.string().regex(/^[A-Za-z0-9_-]{1,64}$/),we=e.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(t=>"AEIMQUYcgkosw048".includes(t.at(-1)),"Use canonical base64url for a 32-byte key"),Ue=e.strictObject({keyId:ue,signingSecret:we}),$e=e.string().max(300).superRefine((t,n)=>{try{let r=new URL(t);if(r.protocol!=="https:"||r.username||r.password||r.search||r.hash||r.pathname!=="/"||r.port&&r.port!=="443"||!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,63}$/.test(r.hostname)||/(?:^|\.)(?:localhost|local|internal)$/.test(r.hostname))throw new Error("invalid origin")}catch{n.addIssue({code:"custom",message:"Use an exact public HTTPS origin"})}}).transform(t=>new URL(t).origin),me=e.array(De).max(10).refine(t=>new Set(t).size===t.length,"Capabilities must be unique"),V=e.strictObject({bridgeVersion:e.literal(M),projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),capabilities:me,catalog:e.enum(["endpoint","static","none"]),billingEvents:e.array(K).max(7),profiles:e.array(G).max(32).refine(t=>new Set(t).size===t.length,"Profiles must be unique")}).superRefine((t,n)=>{let r=u=>t.capabilities.includes(u);r("catalog")!==(t.catalog!=="none")&&n.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(r("billing_records")!==t.billingEvents.length>0||new Set(t.billingEvents).size!==t.billingEvents.length)&&n.addIssue({code:"custom",path:["billingEvents"],message:"Declare the unique supported billing events"})}),de=e.strictObject({origin:$e,requiredCapabilities:me}),Ve=e.strictObject({revision:e.number().int().nonnegative(),checkedAt:e.iso.datetime(),outcome:e.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:e.strictObject({ping:e.enum(["passed","failed","not_checked"]),authentication:e.enum(["passed","failed","not_checked"]),catalog:e.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:V.nullable()}).superRefine((t,n)=>{t.outcome==="valid"!=(t.manifest!==null)&&n.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),Ct=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),execution:e.enum(["indiana","record_only"]),accountId:e.string().nullable(),revision:e.number().int().nonnegative(),authentication:e.strictObject({keyId:ue}).nullable(),secretStoreConfigured:e.boolean().optional(),connection:de.nullable(),check:Ve.nullable()});var se=e.strictObject({projectId:e.uuid(),environmentId:e.uuid()}),Bt=e.discriminatedUnion("action",[se.extend({action:e.literal("save"),revision:e.number().int().nonnegative(),connection:de,authentication:Ue.optional()}),se.extend({action:e.literal("check"),revision:e.number().int().nonnegative()})]),_=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"])});function Et(t){return e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:$,scope:_,data:t})}var le=e.strictObject({nativeUserId:e.string().min(1).max(128),session:Q.strict()}),pe=e.strictObject({nativeUserId:e.string().min(1).max(128),presentation:e.strictObject({customerId:e.uuid(),decisionId:e.uuid(),offeringVersionId:e.uuid(),paywallVersionId:e.uuid(),variant:e.string().min(1).max(128)}).nullable()}),he=e.strictObject({decisionId:e.uuid(),eventId:e.uuid()}),O=e.strictObject({operationId:e.uuid(),customerId:e.uuid()}),kt=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:e.string().min(1).max(64),scope:_,error:e.strictObject({code:e.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:e.string().min(1).max(500),retryable:e.boolean(),recovery:e.string().min(1).max(80)})});var Ut=e.strictObject({scope:_,operationId:e.uuid(),customerId:e.uuid(),confirmedAt:e.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:e.boolean(),instruction:Y,merchantTerms:U.optional()}).refine(t=>t.operationId===t.instruction.operationId&&t.customerId===t.instruction.customerId&&(!t.merchantTerms||t.merchantTerms.request.operationId===t.operationId&&t.merchantTerms.request.subject.customerId===t.customerId&&t.merchantTerms.request.action===t.instruction.type&&t.merchantTerms.currency===t.instruction.currency&&Object.entries(t.scope).every(([n,r])=>t.merchantTerms.request.subject.scope[n]===r)),"Authority must refer to the original Customer and operation"),N=k,d=e.string().min(1).max(120),Ne=e.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),Le=e.strictObject({revision:d,updatedAt:e.iso.datetime(),provider:e.literal("merchant"),items:e.array(e.strictObject({merchantProductId:d,productVersionId:e.uuid(),name:e.string().min(1).max(255),kind:e.enum(["subscription","credit_pack"]),merchantPriceId:d,currency:e.string().regex(/^[a-z]{3}$/),amountMinor:e.number().int().nonnegative().max(1e8),interval:e.enum(["one_time","month","year"]),intervalCount:e.literal(1),includedCredits:e.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:e.enum(["none","month"]),creditPolicyId:d,available:e.boolean()}).superRefine((t,n)=>{(t.kind==="credit_pack"&&(t.interval!=="one_time"||t.creditReset!=="none")||t.kind==="subscription"&&t.interval==="one_time"||t.available&&t.amountMinor===0)&&n.addIssue({code:"custom",message:"Unsupported version 1 catalog terms"})})).max(500)}),Fe=e.strictObject({customerId:e.uuid(),revision:e.string().min(1).max(128),observedAt:e.iso.datetime(),subscriptions:e.array(e.strictObject({merchantSubscriptionId:d,merchantProductId:d,productVersionId:e.uuid().nullable(),status:e.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:e.iso.datetime().nullable(),currentPeriodEndsAt:e.iso.datetime().nullable(),cancelAtPeriodEnd:e.boolean(),scheduledChange:e.strictObject({effectiveAt:e.iso.datetime(),merchantProductId:d}).nullable()})).max(100),purchaseHistory:e.strictObject({complete:e.boolean(),hasPaidPurchase:e.boolean(),lastPaidAt:e.iso.datetime().nullable()}),balances:e.array(e.strictObject({bucketId:d,key:d,available:Ne,expiresAt:e.iso.datetime().nullable(),nextResetAt:e.iso.datetime().nullable()})).max(100)}),v=e.strictObject({}),He={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":v,"session.create":v,"catalog.read":v,"customer.commerce.read":v,"presentation.resolve":v,"presentation.report":he,"purchase.execute":O,"operation.read":O,"subscription.change":O,"refund.execute":O},$t={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":V,"session.create":le,"catalog.read":Le,"customer.commerce.read":Fe,"presentation.resolve":pe,"presentation.report":e.strictObject({queued:e.literal(!0)}),"purchase.execute":N,"operation.read":ee,"subscription.change":N,"refund.execute":N},Vt=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),scope:_,command:$,data:e.unknown()}).superRefine((t,n)=>{He[t.command].safeParse(t.data).success||n.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});export{W as a,ge as b,xe as c,S as d,ye as e,Ye as f,et as g,Ie as h,k as i,ee as j,p as k,tt as l,z as m,Ce as n,ne as o,re as p,P as q,gt as r,U as s,xt as t,yt as u,It as v,Te as w,St as x,Mt as y,M as z,jt as A,Pt as B,ze as C,qt as D,Ue as E,$e as F,V as G,_ as H,Et as I,le as J,pe as K,he as L,O as M,kt as N,Ut as O,N as P,Fe as Q,He as R,$t as S,Vt as T};
1
+ import{b as Q}from"./chunk-HUYKZH3H.js";import{a as j,b as Z,c as x}from"./chunk-XCFAKO23.js";import{a as L,b as F,c as H,j as l}from"./chunk-RIEWU4MN.js";import{b as e}from"./chunk-PZTWDJHN.js";var fe=["purchase.subscription","purchase.one_time","purchase.prepaid","purchase.trial","purchase.seats","purchase.tiered","tax.automatic","discount.percent.once","discount.percent.repeating","discount.percent.forever","discount.amount.once","discount.amount.repeating","discount.amount.forever","subscription.cancel.immediate","subscription.cancel.renewal","subscription.resume","subscription.plan.immediate","subscription.plan.renewal","subscription.seats","subscription.quantity","subscription.billing_cycle","subscription.proration","refund.full","refund.partial","refund.revoke"],G=e.enum(fe),K=e.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","subscription.change.closed","invoice.paid","refund.updated"]);var W=e.enum(["replace","stack_native"]);var o=e.string().min(1).max(200),c=e.iso.datetime({offset:!0}),i=e.number().int().nonnegative().max(1e8),y=e.string().regex(/^[A-Z]{3}$/),ge=e.record(e.uuid(),e.number().int().min(0).max(1e4)).refine(t=>Object.keys(t).length<=100),m=e.strictObject({priceId:e.uuid(),productVersionId:e.uuid(),productId:o,quantity:e.number().int().min(1).max(1e6),unitAmountMinor:i,totalMinor:i,interval:e.enum(["week","month","year","one_off"]),intervalCount:e.number().int().min(1).max(52),kind:e.enum(["fixed","prepaid","seat"]),tiers:e.strictObject({mode:e.enum(["graduated","volume"]),tiers:e.array(e.strictObject({upTo:e.number().int().positive().nullable(),unitAmountMinor:i,flatAmountMinor:i.optional()})).min(2).max(12)}).nullable()}),I=e.strictObject({grantId:e.uuid(),couponId:e.uuid(),amountMinor:i,applicationPolicy:W.optional(),applicableProductIds:e.array(o).min(1).max(100).optional(),terms:e.discriminatedUnion("type",[e.strictObject({type:e.literal("percent"),percentOff:e.number().gt(0).max(100)}),e.strictObject({type:e.literal("amount"),amountOffMinor:i,currency:y})]),duration:e.discriminatedUnion("type",[e.strictObject({type:e.literal("once")}),e.strictObject({type:e.literal("forever")}),e.strictObject({type:e.literal("repeating"),months:e.number().int().min(1).max(36)})])}),E={provider:e.literal("merchant"),executor:e.literal("merchant"),operationId:e.uuid(),customerId:e.uuid(),configurationRevision:e.number().int().nonnegative(),connectionRevision:e.number().int().nonnegative(),currency:y,expiresAt:c},xe=e.strictObject({...E,type:e.literal("purchase"),mode:e.enum(["payment","subscription"]),lineItems:e.array(m).min(1).max(100),catalogAmountMinor:i,nativeDiscountMinor:i.optional(),discount:I.nullable(),trialPeriodDays:e.number().int().min(1).max(730).nullable(),automaticTax:e.boolean()}).refine(t=>t.lineItems.reduce((n,r)=>n+r.totalMinor,0)===t.catalogAmountMinor&&(t.discount?.amountMinor??0)+(t.nativeDiscountMinor??0)<=t.catalogAmountMinor&&new Set(t.lineItems.map(n=>n.priceId)).size===t.lineItems.length,"Purchase lines must retain the original total and unique Price identities"),S=e.strictObject({...E,type:e.literal("subscription_change"),subscriptionId:e.uuid(),merchantSubscriptionId:o,membershipId:e.uuid(),subscriptionAction:e.enum(["update","cancel","schedule","release"]),supersedesOperationId:e.uuid().nullable(),change:e.discriminatedUnion("type",[e.strictObject({type:e.literal("cancel")}),e.strictObject({type:e.literal("uncancel")}),e.strictObject({type:e.literal("plan"),productVersionId:e.uuid(),featureQuantities:ge.optional()}),e.strictObject({type:e.literal("seats"),licenseKey:o,quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("quantity"),internal_feature_id:e.uuid(),quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("billing_cycle"),billingCycleAnchor:e.union([e.literal("now"),e.number().int().positive()])})]),timing:e.enum(["immediate","renewal"]),effectiveAt:c,creditMinor:i,debitMinor:i,totalMinor:i,discountMinor:i,discount:I.nullable().optional(),taxMinor:i,proration:e.enum(["none","create_prorations","always_invoice"]),lineItems:e.array(m.extend({quantity:e.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:e.array(e.uuid()).max(100),sourceLineItems:e.array(m).min(1).max(100).optional()}),ye=e.strictObject({...E,type:e.literal("refund"),invoiceId:e.uuid(),merchantInvoiceId:o,amountMinor:i.refine(t=>t>0),mode:e.enum(["full","partial"]),entitlementAction:e.enum(["retain","revoke"]),cancelSubscriptions:e.array(o).max(100)}),Y=e.discriminatedUnion("type",[xe,S,ye]);function Ye(t){let n=new Set;if(t.type==="purchase")n.add(t.mode==="subscription"?"purchase.subscription":"purchase.one_time"),t.lineItems.some(r=>r.kind==="prepaid")&&n.add("purchase.prepaid"),t.lineItems.some(r=>r.kind==="seat")&&n.add("purchase.seats"),t.lineItems.some(r=>r.tiers!==null)&&n.add("purchase.tiered"),t.trialPeriodDays!==null&&n.add("purchase.trial"),t.automaticTax&&n.add("tax.automatic"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`);else if(t.type==="refund")n.add(`refund.${t.mode}`),t.entitlementAction==="revoke"&&n.add("refund.revoke");else{let r=t.change.type;r==="cancel"?n.add(`subscription.cancel.${t.timing}`):r==="uncancel"?n.add("subscription.resume"):r==="plan"?n.add(`subscription.plan.${t.timing}`):n.add(`subscription.${r}`),t.proration!=="none"&&n.add("subscription.proration"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`)}return[...n].sort()}function et(t){return t.type==="purchase"?t.mode==="subscription"?["purchase.completed","purchase.closed","subscription.observed","invoice.paid"]:["purchase.completed","purchase.closed"]:t.type==="subscription_change"?["subscription.change.completed","subscription.change.closed","subscription.observed",...t.change.type==="cancel"||t.change.type==="uncancel"?[]:["invoice.paid"]]:["refund.updated",...t.entitlementAction==="revoke"&&t.cancelSubscriptions.length?["subscription.observed"]:[]]}var Ie=e.strictObject({phase:e.enum(["execution","payment","fulfillment","recording"]),code:L,reason:H.optional(),recovery:F,retryable:e.boolean()}).refine(t=>t.reason!=="RESULT_UNKNOWN"||!t.retryable&&t.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),Se=e.strictObject({type:e.literal("redirect"),url:e.url().startsWith("https://"),expiresAt:c}),B={operationId:e.uuid(),customerId:e.uuid(),merchantExecutionId:o,fulfillmentStatus:e.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:e.enum(["not_ready","pending","accepted","failed"]),updatedAt:c,problem:Ie.nullable(),pollAfterMs:e.number().int().min(1e3).max(6e4).nullable()},k=e.discriminatedUnion("type",[e.strictObject({...B,type:e.literal("purchase"),merchantOrderId:o.nullable(),paymentStatus:e.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:e.url().refine(t=>new URL(t).protocol==="https:").nullable(),checkoutExpiresAt:c.nullable()}).refine(t=>!t.checkoutUrl||["not_started","pending"].includes(t.paymentStatus)&&t.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),e.strictObject({...B,type:e.literal("subscription_change"),status:e.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:o,scheduledFor:c.nullable(),nextAction:Se.optional()}).refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"A scheduled change retains its future effective time"),e.strictObject({...B,type:e.literal("refund"),status:e.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:o.nullable()}).refine(t=>t.status!=="succeeded"||t.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),ee=e.discriminatedUnion("lookup",[e.strictObject({lookup:e.literal("found"),operationId:e.uuid(),customerId:e.uuid(),execution:k,readAt:c}),e.strictObject({lookup:e.literal("not_received"),operationId:e.uuid(),customerId:e.uuid(),execution:e.null(),readAt:c})]).refine(t=>!t.execution||t.execution.operationId===t.operationId&&t.execution.customerId===t.customerId,"Lookup must retain the original Customer and operation"),te=e.strictObject({merchantPriceId:o,productId:o,kind:e.enum(["fixed","prepaid"]),currency:y,unitAmountMinor:i,interval:e.enum(["one_off","day","week","month","year"]),intervalCount:e.number().int().min(1).max(100)}),X={merchantItemId:o,quantity:e.number().int().positive().max(1e6)},Me=t=>t.priceId??JSON.stringify(t.nativePrice),T=e.strictObject({merchantSubscriptionId:o,revision:e.number().int().positive(),status:e.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:c,periodEndsAt:c,cancelAtPeriodEnd:e.boolean(),hasDiscounts:e.boolean(),items:e.array(e.union([e.strictObject({...X,priceId:e.uuid()}),e.strictObject({...X,nativePrice:te})])).min(1).max(100)}).refine(t=>Date.parse(t.periodEndsAt)>Date.parse(t.periodStartsAt)&&new Set(t.items.map(Me)).size===t.items.length&&new Set(t.items.map(n=>n.merchantItemId)).size===t.items.length,"Subscription periods and Price identities must be unambiguous"),J={merchantLineId:o,quantity:e.number().int().nonnegative().max(1e6),subtotalMinor:e.number().int().min(-1e8).max(1e8),discountMinor:i,taxMinor:i,totalMinor:e.number().int().min(-1e8).max(2e8),periodStartsAt:c.nullable(),periodEndsAt:c.nullable()},R=e.strictObject({merchantInvoiceId:o,reason:e.enum(["renewal","adjustment"]).optional(),currency:y,subtotalMinor:i,discountMinor:i,taxMinor:i,totalMinor:i,paidMinor:i,periodStartsAt:c.nullable(),periodEndsAt:c.nullable(),lines:e.array(e.union([e.strictObject({...J,priceId:e.uuid()}),e.strictObject({...J,nativePrice:te})]).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&(t.subtotalMinor<0?t.discountMinor===0&&t.taxMinor===0:t.discountMinor<=t.subtotalMinor),"Invoice line amounts must retain the complete debit or credit")).min(1).max(100)}).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&t.discountMinor<=t.subtotalMinor&&t.paidMinor===t.totalMinor&&new Set(t.lines.map(n=>n.merchantLineId)).size===t.lines.length&&t.lines.reduce((n,r)=>n+r.subtotalMinor,0)===t.subtotalMinor&&t.lines.reduce((n,r)=>n+r.discountMinor,0)===t.discountMinor&&t.lines.reduce((n,r)=>n+r.taxMinor,0)===t.taxMinor&&t.lines.reduce((n,r)=>n+r.totalMinor,0)===t.totalMinor,"A paid Invoice retains the complete financial amounts"),p={eventId:e.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:e.uuid(),occurredAt:c},_e=e.strictObject({...p,type:e.literal("purchase.completed"),operationId:e.uuid(),merchantOrderId:o,paymentStatus:e.enum(["paid","trialing","no_payment_required"]),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable(),subscription:T.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),Oe=e.strictObject({...p,type:e.literal("purchase.closed"),operationId:e.uuid(),status:e.enum(["failed","expired","canceled"])}),ve=e.strictObject({...p,type:e.literal("subscription.observed"),operationId:e.uuid().nullable(),subscription:T}),Ae=e.strictObject({...p,type:e.literal("subscription.change.completed"),operationId:e.uuid(),status:e.enum(["scheduled","applied"]),scheduledFor:c.nullable(),subscription:T.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities"),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),je=e.strictObject({...p,type:e.literal("subscription.change.closed"),operationId:e.uuid(),merchantSubscriptionId:o,merchantInvoiceId:o.nullable(),status:e.enum(["failed","expired","canceled"])}),Pe=e.strictObject({...p,type:e.literal("invoice.paid"),merchantSubscriptionId:o.nullable(),invoice:R}),qe=e.strictObject({...p,type:e.literal("refund.updated"),operationId:e.uuid().nullable(),merchantInvoiceId:o.optional(),merchantRefundId:o,status:e.enum(["pending","succeeded","failed"]),amountMinor:i.refine(t=>t>0),currency:y}),tt=[_e.refine(t=>t.paymentStatus!=="paid"||t.invoice!==null,"A paid purchase includes its Invoice"),Oe,ve.refine(t=>t.operationId===null||t.subscription.items.every(n=>"priceId"in n),"Native Price references cannot replace an operation's quoted Prices"),Ae.refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),je,Pe,qe.refine(t=>t.operationId!==null||t.merchantInvoiceId!==void 0,"A native refund names its Invoice")];var z=e.strictObject({days:e.number().int().min(1).max(730),cardRequired:e.boolean()}),at=e.object({...z.shape,featureAllowances:e.record(e.uuid(),e.number().int().min(0).max(1e9)),creditAmounts:e.record(e.uuid(),l)}).strict(),ct=e.object({id:e.uuid(),planVersionId:e.uuid(),slot:e.string(),cardRequired:e.boolean(),status:e.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),createdAt:e.iso.datetime()}).strict();var Ce=e.number().int().positive().max(2e8),ne=e.number().int().min(0).max(2e8),re=t=>t.mode==="partial"==(t.amountMinor!==void 0),P=e.strictObject({mode:e.enum(["full","partial"]),amountMinor:Ce.optional(),entitlementAction:e.enum(["retain","revoke"])});var a=e.string().min(1).max(200),b=e.iso.datetime({offset:!0}),f=ne,ie=f.maxValue,C=e.number().int().min(-ie).max(ie),q=e.string().regex(/^[A-Z]{3}$/),oe=e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),ae=e.array(a).max(100).refine(t=>new Set(t).size===t.length),Be=e.strictObject({merchantProductId:a,merchantPriceId:a,productVersionId:e.uuid().optional(),quantity:l.refine(t=>/[1-9]/.test(t))}),D={subject:Z,operationId:e.uuid(),configurationRevision:oe,connectionRevision:oe,expiresAt:b},w=e.discriminatedUnion("action",[e.strictObject({...D,action:e.literal("purchase"),mode:e.enum(["payment","subscription"]),currency:q,items:e.array(Be).min(1).max(100),offerRefs:ae}),e.strictObject({...D,action:e.literal("subscription_change"),currency:q,merchantSubscriptionId:a,change:S.shape.change,timing:S.shape.timing,proration:S.shape.proration,offerRefs:ae}),e.strictObject({...D,action:e.literal("refund"),currency:q,merchantInvoiceId:a,mode:P.shape.mode,amountMinor:P.shape.amountMinor,entitlementAction:P.shape.entitlementAction}).refine(re,"Only a partial refund chooses amountMinor")]),gt=e.strictObject({request:w,requestedAt:b,preparationAllowed:e.boolean()}).refine(t=>!t.preparationAllowed||Date.parse(t.requestedAt)<Date.parse(t.request.expiresAt),"Preparation authority must be within its original validity"),Ee=e.strictObject({merchantLineId:a,merchantPriceId:a.nullable(),quantity:l.refine(t=>/[1-9]/.test(t)),subtotalMinor:C,discountMinor:f,taxMinor:f.nullable(),totalMinor:C.nullable()}).refine(t=>t.taxMinor===null==(t.totalMinor===null)&&(t.totalMinor===null||t.totalMinor===t.subtotalMinor-t.discountMinor+t.taxMinor),"A quote line retains exact known totals; unknown tax is not zero"),ke=e.strictObject({items:e.array(e.strictObject({merchantPriceId:a,quantity:l.refine(t=>/[1-9]/.test(t)),interval:m.shape.interval.exclude(["one_off"]),intervalCount:m.shape.intervalCount,amountMinor:m.shape.totalMinor,amountAfterOfferMinor:m.shape.totalMinor.optional()})).min(1).max(100),trial:z.nullable(),discount:I.nullable().optional(),discountExpiresAt:b.nullable().optional(),initialAmountMinor:m.shape.totalMinor.optional()}),ce=e.strictObject({request:w,requestDigest:j,merchantQuoteId:a,quoteTermsDigest:j,termsVersion:a,sourceRevisions:e.array(e.strictObject({reference:a,revision:a})).max(100),observedAt:b,expiresAt:b,currency:q,automaticTax:e.boolean(),lines:e.array(Ee).max(100),subscriptionTerms:ke.nullable(),subtotalMinor:C,discountMinor:f,nativeDiscountMinor:f.optional(),discount:I.nullable().optional(),taxMinor:f.nullable(),totalMinor:C.nullable(),effectiveAt:b.nullable(),expectedEffects:e.array(e.strictObject({reference:a,kind:e.enum(["grant","revoke","change"]),description:e.string().min(1).max(1e3),quantity:l.nullable(),unit:a.nullable()}).refine(t=>t.quantity===null==(t.unit===null),"Quantified effects name their native unit")).max(100),requiredConsents:e.array(e.strictObject({reference:a,version:a,summary:e.string().min(1).max(1e3)})).max(20)}),U=ce.superRefine((t,n)=>{let{quoteTermsDigest:r,...u}=t,h=t.lines.every(s=>s.taxMinor!==null),A=t.request.action==="purchase"&&t.request.mode==="subscription"!=(t.subscriptionTerms!==null),be=t.subscriptionTerms!==null&&(t.request.action==="refund"||t.request.action==="subscription_change"&&t.request.change.type==="cancel");(t.requestDigest!==x(t.request)||t.quoteTermsDigest!==x(u)||t.currency!==t.request.currency||A||be||t.lines.length===0&&(t.request.action!=="subscription_change"||t.subtotalMinor!==0||t.discountMinor!==0||t.taxMinor!==0||t.totalMinor!==0)||Date.parse(t.observedAt)>=Date.parse(t.expiresAt)||Date.parse(t.expiresAt)>Date.parse(t.request.expiresAt)||new Set(t.lines.map(s=>s.merchantLineId)).size!==t.lines.length||new Set(t.sourceRevisions.map(s=>s.reference)).size!==t.sourceRevisions.length||new Set(t.requiredConsents.map(s=>s.reference)).size!==t.requiredConsents.length||t.subtotalMinor!==t.lines.reduce((s,g)=>s+g.subtotalMinor,0)||t.discountMinor!==t.lines.reduce((s,g)=>s+g.discountMinor,0)||t.taxMinor!==null!==h||!h&&!t.automaticTax||t.taxMinor===null!=(t.totalMinor===null)||h&&(t.taxMinor!==t.lines.reduce((s,g)=>s+g.taxMinor,0)||t.totalMinor!==t.subtotalMinor-t.discountMinor+t.taxMinor)||t.request.action!=="subscription_change"&&(t.subtotalMinor<0||t.totalMinor!==null&&t.totalMinor<0)||t.request.action==="refund"&&(t.taxMinor===null||t.totalMinor===null||t.totalMinor<=0||t.request.mode==="partial"&&t.totalMinor!==t.request.amountMinor))&&n.addIssue({code:"custom",message:"Merchant terms must retain the original selection, scope, validity, digest and totals"})});function xt(t,n,r,u){return t.request.operationId===n&&t.request.action===r&&t.currency===u}function yt(t){return x(w.parse(t))}function It(t){return x(ce.omit({quoteTermsDigest:!0}).parse(t))}var Te=e.strictObject({quoteTermsDigest:j,consents:e.array(e.strictObject({reference:a,version:a})).max(20)});function St(t){return{quoteTermsDigest:t.quoteTermsDigest,consents:t.requiredConsents.map(({reference:n,version:r})=>({reference:n,version:r}))}}var Re=Te.extend({operationId:e.uuid()}).refine(t=>new Set(t.consents.map(n=>n.reference)).size===t.consents.length);function Mt(t,n){let r=U.parse(t),u=Re.parse(n);return u.operationId===r.request.operationId&&u.quoteTermsDigest===r.quoteTermsDigest&&u.consents.length===r.requiredConsents.length&&r.requiredConsents.every(h=>u.consents.some(A=>A.reference===h.reference&&A.version===h.version))}var M=3,jt="/integrations/indiana",Pt="X-Indiana-Merchant-Bridge-Version",ze=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],De=e.enum(ze),qt={session:{command:"session.create",authority:"merchant_user"},catalog:{command:"catalog.read",authority:"merchant_catalog_reader"},customer_commerce:{command:"customer.commerce.read",authority:"merchant_user"},presentation:{command:"presentation.resolve",authority:"merchant_user"},presentation_events:{command:"presentation.report",authority:"merchant_user"},purchases:{command:"purchase.execute",authority:"merchant_user"},operation_status:{command:"operation.read",authority:"merchant_user"},billing_records:{command:null,authority:"indiana_server_key"},subscription_changes:{command:"subscription.change",authority:"merchant_user"},refunds:{command:"refund.execute",authority:"merchant_refund_authority"}},$=e.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),ue=e.string().regex(/^[A-Za-z0-9_-]{1,64}$/),we=e.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(t=>"AEIMQUYcgkosw048".includes(t.at(-1)),"Use canonical base64url for a 32-byte key"),Ue=e.strictObject({keyId:ue,signingSecret:we}),$e=e.string().max(300).superRefine((t,n)=>{try{let r=new URL(t);if(r.protocol!=="https:"||r.username||r.password||r.search||r.hash||r.pathname!=="/"||r.port&&r.port!=="443"||!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,63}$/.test(r.hostname)||/(?:^|\.)(?:localhost|local|internal)$/.test(r.hostname))throw new Error("invalid origin")}catch{n.addIssue({code:"custom",message:"Use an exact public HTTPS origin"})}}).transform(t=>new URL(t).origin),me=e.array(De).max(10).refine(t=>new Set(t).size===t.length,"Capabilities must be unique"),V=e.strictObject({bridgeVersion:e.literal(M),projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),capabilities:me,catalog:e.enum(["endpoint","static","none"]),billingEvents:e.array(K).max(7),profiles:e.array(G).max(32).refine(t=>new Set(t).size===t.length,"Profiles must be unique")}).superRefine((t,n)=>{let r=u=>t.capabilities.includes(u);r("catalog")!==(t.catalog!=="none")&&n.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(r("billing_records")!==t.billingEvents.length>0||new Set(t.billingEvents).size!==t.billingEvents.length)&&n.addIssue({code:"custom",path:["billingEvents"],message:"Declare the unique supported billing events"})}),de=e.strictObject({origin:$e,requiredCapabilities:me}),Ve=e.strictObject({revision:e.number().int().nonnegative(),checkedAt:e.iso.datetime(),outcome:e.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:e.strictObject({ping:e.enum(["passed","failed","not_checked"]),authentication:e.enum(["passed","failed","not_checked"]),catalog:e.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:V.nullable()}).superRefine((t,n)=>{t.outcome==="valid"!=(t.manifest!==null)&&n.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),Ct=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),execution:e.enum(["indiana","record_only"]),accountId:e.string().nullable(),revision:e.number().int().nonnegative(),authentication:e.strictObject({keyId:ue}).nullable(),secretStoreConfigured:e.boolean().optional(),connection:de.nullable(),check:Ve.nullable()});var se=e.strictObject({projectId:e.uuid(),environmentId:e.uuid()}),Bt=e.discriminatedUnion("action",[se.extend({action:e.literal("save"),revision:e.number().int().nonnegative(),connection:de,authentication:Ue.optional()}),se.extend({action:e.literal("check"),revision:e.number().int().nonnegative()})]),_=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"])});function Et(t){return e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:$,scope:_,data:t})}var le=e.strictObject({nativeUserId:e.string().min(1).max(128),session:Q.strict()}),pe=e.strictObject({nativeUserId:e.string().min(1).max(128),presentation:e.strictObject({customerId:e.uuid(),decisionId:e.uuid(),offeringVersionId:e.uuid(),paywallVersionId:e.uuid(),variant:e.string().min(1).max(128)}).nullable()}),he=e.strictObject({decisionId:e.uuid(),eventId:e.uuid()}),O=e.strictObject({operationId:e.uuid(),customerId:e.uuid()}),kt=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:e.string().min(1).max(64),scope:_,error:e.strictObject({code:e.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:e.string().min(1).max(500),retryable:e.boolean(),recovery:e.string().min(1).max(80)})});var Ut=e.strictObject({scope:_,operationId:e.uuid(),customerId:e.uuid(),confirmedAt:e.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:e.boolean(),instruction:Y,merchantTerms:U.optional()}).refine(t=>t.operationId===t.instruction.operationId&&t.customerId===t.instruction.customerId&&(!t.merchantTerms||t.merchantTerms.request.operationId===t.operationId&&t.merchantTerms.request.subject.customerId===t.customerId&&t.merchantTerms.request.action===t.instruction.type&&t.merchantTerms.currency===t.instruction.currency&&Object.entries(t.scope).every(([n,r])=>t.merchantTerms.request.subject.scope[n]===r)),"Authority must refer to the original Customer and operation"),N=k,d=e.string().min(1).max(120),Ne=e.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),Le=e.strictObject({revision:d,updatedAt:e.iso.datetime(),provider:e.literal("merchant"),items:e.array(e.strictObject({merchantProductId:d,productVersionId:e.uuid(),name:e.string().min(1).max(255),kind:e.enum(["subscription","credit_pack"]),merchantPriceId:d,currency:e.string().regex(/^[a-z]{3}$/),amountMinor:e.number().int().nonnegative().max(1e8),interval:e.enum(["one_time","month","year"]),intervalCount:e.literal(1),includedCredits:e.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:e.enum(["none","month"]),creditPolicyId:d,available:e.boolean()}).superRefine((t,n)=>{(t.kind==="credit_pack"&&(t.interval!=="one_time"||t.creditReset!=="none")||t.kind==="subscription"&&t.interval==="one_time"||t.available&&t.amountMinor===0)&&n.addIssue({code:"custom",message:"Unsupported version 1 catalog terms"})})).max(500)}),Fe=e.strictObject({customerId:e.uuid(),revision:e.string().min(1).max(128),observedAt:e.iso.datetime(),subscriptions:e.array(e.strictObject({merchantSubscriptionId:d,merchantProductId:d,productVersionId:e.uuid().nullable(),status:e.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:e.iso.datetime().nullable(),currentPeriodEndsAt:e.iso.datetime().nullable(),cancelAtPeriodEnd:e.boolean(),scheduledChange:e.strictObject({effectiveAt:e.iso.datetime(),merchantProductId:d}).nullable()})).max(100),purchaseHistory:e.strictObject({complete:e.boolean(),hasPaidPurchase:e.boolean(),lastPaidAt:e.iso.datetime().nullable()}),balances:e.array(e.strictObject({bucketId:d,key:d,available:Ne,expiresAt:e.iso.datetime().nullable(),nextResetAt:e.iso.datetime().nullable()})).max(100)}),v=e.strictObject({}),He={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":v,"session.create":v,"catalog.read":v,"customer.commerce.read":v,"presentation.resolve":v,"presentation.report":he,"purchase.execute":O,"operation.read":O,"subscription.change":O,"refund.execute":O},$t={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":V,"session.create":le,"catalog.read":Le,"customer.commerce.read":Fe,"presentation.resolve":pe,"presentation.report":e.strictObject({queued:e.literal(!0)}),"purchase.execute":N,"operation.read":ee,"subscription.change":N,"refund.execute":N},Vt=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),scope:_,command:$,data:e.unknown()}).superRefine((t,n)=>{He[t.command].safeParse(t.data).success||n.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});export{W as a,ge as b,xe as c,S as d,ye as e,Ye as f,et as g,Ie as h,k as i,ee as j,p as k,tt as l,z as m,Ce as n,ne as o,re as p,P as q,gt as r,U as s,xt as t,yt as u,It as v,Te as w,St as x,Mt as y,M as z,jt as A,Pt as B,ze as C,qt as D,Ue as E,$e as F,V as G,_ as H,Et as I,le as J,pe as K,he as L,O as M,kt as N,Ut as O,N as P,Fe as Q,He as R,$t as S,Vt as T};
@@ -1 +1 @@
1
- import{f as o}from"./chunk-LB2ZRTRA.js";var n=class extends Error{constructor(t,s,y,i,r){super(s);this.code=t;this.status=y;this.requestId=i;this.name="IndianaError",this.reason=r?.reason;let e=o(t,y??0,{...r,retryAfter:r?.retryAfterSeconds===void 0?void 0:String(r.retryAfterSeconds)});this.retryable=e.retryable,this.recovery=e.recovery,this.retryAfterSeconds=e.retryAfterSeconds}code;status;requestId;commandRequestId;retryable;recovery;retryAfterSeconds;reason};export{n as a};
1
+ import{f as o}from"./chunk-RIEWU4MN.js";var n=class extends Error{constructor(t,s,y,i,r){super(s);this.code=t;this.status=y;this.requestId=i;this.name="IndianaError",this.reason=r?.reason;let e=o(t,y??0,{...r,retryAfter:r?.retryAfterSeconds===void 0?void 0:String(r.retryAfterSeconds)});this.retryable=e.retryable,this.recovery=e.recovery,this.retryAfterSeconds=e.retryAfterSeconds}code;status;requestId;commandRequestId;retryable;recovery;retryAfterSeconds;reason};export{n as a};