@tinkerlandai/longplay-sdk 0.10.27 → 0.10.29

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 (71) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/{chunk-XZMM34BS.js → chunk-2JTMXZ5M.js} +1 -1
  3. package/dist/chunk-3GT4A3TA.js +1 -0
  4. package/dist/{chunk-SYQMGS6O.js → chunk-4OBCF5H3.js} +2 -2
  5. package/dist/{chunk-TJMODHSS.js → chunk-4WBIACS2.js} +1 -1
  6. package/dist/{chunk-AEERSTTW.js → chunk-5X6WAPH3.js} +1 -1
  7. package/dist/{chunk-2TQEJ6GM.js → chunk-6QJRT23Q.js} +1 -1
  8. package/dist/{chunk-67JOPO63.js → chunk-77GCT2VP.js} +1 -1
  9. package/dist/{chunk-S4X6YX5D.js → chunk-7EPE2PUN.js} +1 -1
  10. package/dist/{chunk-ANZB6OLR.js → chunk-AZ53RDWO.js} +1 -1
  11. package/dist/{chunk-HWQVZL7I.js → chunk-CGSZBPSX.js} +1 -1
  12. package/dist/{chunk-MBLWCMAI.js → chunk-EUVKRGMO.js} +1 -1
  13. package/dist/{chunk-COMWJEMO.js → chunk-FDCINOOI.js} +1 -1
  14. package/dist/{chunk-WKH23DZE.js → chunk-GOYKJHDV.js} +1 -1
  15. package/dist/{chunk-G2QO6ZWP.js → chunk-HZYCK4XJ.js} +1 -1
  16. package/dist/chunk-IDMOAV63.js +1 -0
  17. package/dist/chunk-JAUJZWYJ.js +1 -0
  18. package/dist/{chunk-D4CDG535.js → chunk-JPHYIUIR.js} +1 -1
  19. package/dist/chunk-K72QA2PO.js +1 -0
  20. package/dist/{chunk-26YREQNF.js → chunk-KAXKYBSI.js} +1 -1
  21. package/dist/{chunk-LHOSUSTZ.js → chunk-MBKZYWPF.js} +1 -1
  22. package/dist/{chunk-WU4SDY27.js → chunk-MMZR4I5X.js} +1 -1
  23. package/dist/{chunk-5OJVM7Q4.js → chunk-O4KXODTJ.js} +1 -1
  24. package/dist/{chunk-EBXWLW4D.js → chunk-PKY55SBA.js} +1 -1
  25. package/dist/{chunk-FB7X4MFC.js → chunk-PNHGULO2.js} +1 -1
  26. package/dist/{chunk-WCKOWAIL.js → chunk-PQJJ5BSY.js} +1 -1
  27. package/dist/{chunk-VTZHKUZO.js → chunk-Q2TQLDEH.js} +1 -1
  28. package/dist/{chunk-7CFSTOTX.js → chunk-QZG2YXM4.js} +1 -1
  29. package/dist/{chunk-DC7UHEC6.js → chunk-S4JIOALC.js} +1 -1
  30. package/dist/{chunk-LHXRT32T.js → chunk-SBSLHDBE.js} +1 -1
  31. package/dist/{chunk-S67P7ZQ6.js → chunk-TLGKBSXC.js} +1 -1
  32. package/dist/chunk-TNN4S6VO.js +1 -0
  33. package/dist/{chunk-5M536ISX.js → chunk-UWAZDSWO.js} +1 -1
  34. package/dist/{chunk-2ZPCWVFU.js → chunk-VC2H3LFP.js} +1 -1
  35. package/dist/chunk-VKDBROTE.js +1 -0
  36. package/dist/{chunk-LI4B43FT.js → chunk-VSWKFI3L.js} +1 -1
  37. package/dist/{chunk-MTKM26F7.js → chunk-YBX2LLRG.js} +1 -1
  38. package/dist/{content-4V7YBP3O.js → content-S5MXIR7Y.js} +1 -1
  39. package/dist/{funnel-host-purchase-LJYQF6AX.js → funnel-host-purchase-7BRXGIJX.js} +1 -1
  40. package/dist/funnel-runtime-host-ITKTYBDS.js +1 -0
  41. package/dist/index.js +1 -1
  42. package/dist/merchant-bridge-contracts-JCDMP54Z.js +1 -0
  43. package/dist/native-shell.js +1 -1
  44. package/dist/openrouter.js +1 -1
  45. package/dist/operation-contracts-B7I45NS3.js +1 -0
  46. package/dist/page.js +1 -1
  47. package/dist/paywall-BEFHTZW7.js +1 -0
  48. package/dist/paywall-session-YVGZPSFM.js +1 -0
  49. package/dist/popup.d.ts +2 -0
  50. package/dist/popup.js +1 -1
  51. package/dist/react-native.js +1 -1
  52. package/dist/screen-renderer-ITUUNF4E.js +1 -0
  53. package/dist/server.js +1 -1
  54. package/dist/{visual-dom-CAOVBSVC.js → visual-dom-5LUN4AHO.js} +1 -1
  55. package/dist/visual.js +1 -1
  56. package/package.json +1 -1
  57. package/dist/chunk-2GMWNOOE.js +0 -1
  58. package/dist/chunk-JGG4R75K.js +0 -1
  59. package/dist/chunk-VRCN5YLM.js +0 -1
  60. package/dist/chunk-WPLSGFYT.js +0 -1
  61. package/dist/chunk-XBVJHXSP.js +0 -1
  62. package/dist/chunk-Z6RZQ5KJ.js +0 -1
  63. package/dist/funnel-runtime-host-XWXG4SIU.js +0 -1
  64. package/dist/merchant-bridge-contracts-OL3ME2AL.js +0 -1
  65. package/dist/operation-contracts-NJPUHGUM.js +0 -1
  66. package/dist/paywall-INF4ZZ7J.js +0 -1
  67. package/dist/paywall-session-3JV2JMUI.js +0 -1
  68. package/dist/screen-renderer-ZRSVFBLQ.js +0 -1
  69. /package/dist/{chunk-ZGBSTK22.js → chunk-7GD2UTBU.js} +0 -0
  70. /package/dist/{chunk-QENDBHBQ.js → chunk-CILM5XMH.js} +0 -0
  71. /package/dist/{chunk-D6SDVDXZ.js → chunk-OJM6ORHE.js} +0 -0
@@ -0,0 +1 @@
1
+ import{a as kn,b as rn,c as on,d as _e,e as Fn,f as We,h as Dn}from"./chunk-K72QA2PO.js";import{c as Cn,d as Pn,e as Rn,f as Ae,g as Be,h as En,i as je,k as qn}from"./chunk-GOYKJHDV.js";import{$ as Qe}from"./chunk-2JTMXZ5M.js";import{a as ze,e as gn,f as vn,g as hn,h as In,i as bn}from"./chunk-KAXKYBSI.js";import{b as wn}from"./chunk-AZ53RDWO.js";import{R as fn,qa as yn}from"./chunk-4WBIACS2.js";import{a as P}from"./chunk-7EPE2PUN.js";import{b as Sn,e as On}from"./chunk-SLUA7ABW.js";import{d as Tn}from"./chunk-QZG2YXM4.js";import{a as le}from"./chunk-DSPLGTQI.js";import{b as mn}from"./chunk-O4KXODTJ.js";var Te=new WeakMap;function Bn(t){let y=t.view,w=y?.paywall?.resolution;if(!y||!["running","waiting"].includes(y.status)||y.stopped||!w||"document"in w||!t.resolvePaywall||t.identitySignal?.aborted)return;let e=JSON.stringify(w);if(Te.get(t)?.key===e)return;let c=JSON.parse(e),D=t.identitySignal,a=Promise.resolve().then(async()=>{D?.throwIfAborted();let o=await t.resolvePaywall(c);return D?.throwIfAborted(),o}),S={key:e,content:a};return Te.set(t,S),a.catch(()=>{}),()=>{Te.get(t)===S&&Te.delete(t)}}function Nn(t,y){let w=Te.get(t);return Te.delete(t),w?.key===JSON.stringify(y)?w.content:t.resolvePaywall(y)}async function An(t){let{session:y,load:w}=Qn(t);try{return await w(),y}catch(e){throw y.destroy(),e}}function Qn(t){let y=t.view;if(!y?.paywall)throw new P("INVALID_REQUEST","The current node is not a Paywall");let w=y.paywall.receiptId,e=y.nodeId,c=y.visit,D=y.paywall.resolution,a=y.paywall,S="document"in D?{document:D.document,offering:D.offering,capabilities:D.capabilities}:null;function o(){let i=a.resolution;return"document"in i?i:S&&{...i,document:S.document,offering:S.offering,capabilities:gn(i.capabilities,S.capabilities)}}function g(i){if(!vn(i,D))throw new P("INVALID_RESPONSE","The pinned Paywall binding changed")}let u=!1,q=new Set,A=null;function L(){let i=o();if(i&&!u)for(let l of q)le(l,structuredClone(i))}async function k(){U();let i=o();if(i)return structuredClone(i);if(!A){let l=(async()=>{if("document"in a.resolution||!t.resolvePaywall)throw new P("INVALID_RESPONSE","Public Paywall reader is unavailable");let p=await Nn(t,a.resolution);return U(),g(p),S={document:p.document,offering:p.offering,capabilities:p.capabilities},L(),o()})();A=l;let s=()=>{A===l&&(A=null)};l.then(s,s)}return A.then(l=>structuredClone(l))}let d=new AbortController,F=(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===c&&i.input.type==="paywall_quote")?.requestId??y.paywall.purchaseRequestId,R=0,V=null,b=new Set,J=null,h=new Map;function _(i){if(i.purchase&&i.purchase.receiptId!==w)throw new P("INVALID_RESPONSE","Purchase receipt changed");let l=i.run.paywall;return i.purchase??(l?.receiptId===w?l:null)}function U(){if(u)throw new P("IDENTITY_CHANGED","Paywall presentation has closed")}function z(i,l,s){if(U(),l!==R||s!==void 0&&a.quote?.operationId!==s)return!1;let p=a.selectionGeneration??0,I=i.run.paywall;if(I?.receiptId===w){if((I.selectionGeneration??0)<(a.selectionGeneration??0))return!1;g(I.resolution)}let C=_(i),B=I?.receiptId===w&&(I.selectionGeneration??0)>p,Q=B?C?.quote??null:C?.quote??a.quote,v=C?.operation??(Q?.operationId===a.quote?.operationId?a.operation:null);return Q&&v&&hn(v,{operationId:Q.operationId},"Purchase operation changed"),(B||Q?.operationId!==a.quote?.operationId)&&(R++,I?.receiptId===w&&(F=I.purchaseRequestId)),a={...a,...I?.receiptId===w?I:{},quote:Q,operation:bn(a.operation,v,!0)},L(),!0}function $(i,l,s){return new Promise((p,I)=>{let C=!1,B=()=>{clearTimeout(Re),d.signal.removeEventListener("abort",x)},Q=Ee=>{C||(C=!0,B(),p(Ee))},v=Ee=>{C||(C=!0,B(),I(Ee))},x=()=>v(new P("IDENTITY_CHANGED","Paywall presentation has closed")),Re=setTimeout(()=>v(new P("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,s)),Math.max(0,l-Date.now()));d.signal.addEventListener("abort",x,{once:!0}),d.signal.aborted&&x(),i.then(Q,v)})}function de(i){return new Promise(l=>{let s=()=>{clearTimeout(p),d.signal.removeEventListener("abort",s),l()},p=setTimeout(s,i);d.signal.addEventListener("abort",s,{once:!0}),d.signal.aborted&&s()})}function Y(i,l){U();let s=h.get(i)??t.pendingCommands?.find(C=>C.requestId===i)??t.pendingCommand;if(s?.operation==="submit"&&s.requestId===i&&s.nodeId===e&&s.visit===c){l.type==="paywall_quote"&&s.input.type==="paywall_quote"&&s.input.predecessor&&!l.predecessor&&(l={...l,predecessor:s.input.predecessor});let C=Qe.parse(s),B=Qe.parse({...s,input:l});if(C.operation!=="submit"||B.operation!=="submit"||JSON.stringify(C.input)!==JSON.stringify(B.input))throw new P("CONFLICT","A purchase request cannot change its input");return h.set(i,C),C}let p=t.view;if(!p||p.nodeId!==e||p.visit!==c||p.paywall?.receiptId!==w)throw new P("PRECONDITION_FAILED","The Paywall visit has changed");let I=Qe.parse({operation:"submit",requestId:i,nodeId:e,visit:c,revision:p.revision,input:structuredClone(l)});if(I.operation!=="submit")throw new P("INVALID_REQUEST","A purchase submission is required");return h.set(i,I),I}async function ce(i,l){U();let{requestId:s,input:p}=i,I=Date.now()+3e4;b.add(s);try{let C=await $(t.submit(i),I,s);for(;C.run.pendingRequest?.requestId===s&&Date.now()<I&&!u&&(await de(Math.min(1e3,I-Date.now())),!(u||Date.now()>=I));)C=await $(t.resume(s),I,s);if(u)throw new P("IDENTITY_CHANGED","Paywall presentation has closed");if(C.run.pendingRequest?.requestId===s)throw new P("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,s);if(!z(C,l,p.type==="paywall_confirm"||p.type==="paywall_cancel"?p.operationId:void 0))throw new P("PRECONDITION_FAILED","The purchase selection has changed");J===s&&(J=null)}catch(C){throw J=s,C instanceof P&&C.code==="COMMAND_PENDING"&&C.status===void 0&&h.delete(s),C}finally{b.delete(s)}}async function re(i){if(!a.quote)throw new P("INVALID_REQUEST","A quoted purchase is required");let l=i==="confirm"?"paywall_confirm":"paywall_cancel",s=[...h.values(),...t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])].find(I=>I.operation==="submit"&&I.input.type===l&&"operationId"in I.input&&I.input.operationId===a.quote.operationId),p=s?.operation==="submit"&&s.input.type===l&&"operationId"in s.input&&s.input.operationId===a.quote.operationId?s.requestId:crypto.randomUUID();if(await ce(Y(p,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:a.quote.operationId}),R),!a.operation)throw new P("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(a.operation)}let T={get view(){return structuredClone(o())},get quote(){return a.quote?structuredClone(a.quote):null},get operation(){return a.operation?structuredClone(a.operation):null},get webViewUrl(){return t.webViewUrl},get canReselect(){return a.canReselect===!0},get recovery(){let i=t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[]),l=t.pendingPurchase;if(l&&(l.receiptId!==w||l.operationId!==a.quote?.operationId))return{type:"recover",operationId:l.operationId,requestId:i[0]?.requestId??null};let s=ze({quote:a.quote,operation:a.operation,requestId:i[0]?.requestId??J??F,pending:b.size>0||i.length>0||J!==null,destroyed:u,canReselect:a.canReselect});return s.type==="recover"&&s.requestId===null&&!u&&t.hasDurableJournal===!0&&!a.quote&&!a.operation&&(a.selectionGeneration??0)===0&&!l&&!i.length&&!b.size&&!F?{type:"native",operationId:null}:s},get pendingCancellation(){return!u&&(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===c&&i.input.type==="paywall_cancel"&&i.input.operationId===a.quote?.operationId)},subscribe(i){return u?()=>{}:(q.add(i),()=>q.delete(i))},async refresh(){U();let i=R,l=await t.get();if(z(l,i),l.run.paywall?.receiptId!==w)throw new P("PRECONDITION_FAILED","Paywall presentation has changed");return k()},preview(i){let l=o();if(!l)return Promise.reject(new P("PRECONDITION_FAILED","Load the Paywall presentation first"));if(F&&F!==i.requestId&&(V||a.canReselect!==!0))return Promise.reject(new P("COMMAND_PENDING","Retry the original purchase before starting another"));let s=l.document.buttons[i.actionId],p=s?.type==="checkout"?wn(s.product,i.selection,l.capabilities):null;if(!p)return Promise.reject(new P("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let I=yn(l.document.screen,p,i.selection,l.capabilities),C=F!==i.requestId&&(a.selectionGeneration??0)>0?{operationId:a.quote?.operationId??null,generation:a.selectionGeneration??0}:void 0;if(C&&a.canReselect!==!0)return Promise.reject(new P("COMMAND_PENDING","Original purchase requires authoritative termination"));let B;try{B=Y(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:p,...Object.keys(I).length?{featureQuantities:I}:{},...C?{predecessor:C}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}})}catch(x){return Promise.reject(x)}if(F===i.requestId&&V)return V;F!==i.requestId&&R++;let Q=R;F=i.requestId;let v=(async()=>{if(await ce(B,Q),!a.quote)throw new P("INVALID_RESPONSE","The accepted quote is missing");return In(a.quote,{productVersionId:p,featureQuantities:I},"The selected purchase changed"),structuredClone(a.quote)})();return V=v,v.then(()=>{V===v&&(V=null)},x=>{V===v&&(V=null),F===i.requestId&&t.pendingCommand?.requestId!==i.requestId&&x instanceof P&&x.status!==void 0&&x.status<500&&![401,425].includes(x.status)&&(F=null)}),v},confirm:()=>re("confirm"),cancel:()=>re("cancel"),async read(){if(U(),!a.quote)throw new P("INVALID_REQUEST","A quoted purchase is required");let i=a.quote.operationId,l=R,s=t.pendingCommands?.find(Q=>Q.operation==="submit"&&(Q.input.type==="paywall_confirm"||Q.input.type==="paywall_cancel")&&Q.input.operationId===i)??t.pendingCommand;s?.operation==="submit"&&(s.input.type==="paywall_confirm"||s.input.type==="paywall_cancel")&&s.input.operationId===i&&await t.settle?.(s.requestId);let p=await t.get(void 0,{receiptId:w,operationId:i});U();let I=_(p);if(I?.quote&&I.quote.operationId!==i||I?.operation&&I.operation.operationId!==i)throw new P("INVALID_RESPONSE","Purchase operation changed");let C=z(p,l,i),B=C?a.operation:I?.operation;if(!B)throw new P("INVALID_RESPONSE","The current purchase result is missing");return C&&b.size===0&&!(t.pendingCommands?.length??(t.pendingCommand?1:0))&&(J=null),structuredClone(B)},destroy(){u=!0,E(),q.clear(),d.abort(),h.clear()}},E=t.subscribe(i=>{u||i.nodeId!==e||i.visit!==c||i.paywall?.receiptId!==w||(i.paywall.selectionGeneration??0)<(a.selectionGeneration??0)||(g(i.paywall.resolution),a={...a,resolution:i.paywall.resolution},L())});return{session:T,load:k}}function _n(t){let y=new Set,w=new Set,e=null;async function c(o,g){let u=!1;for(;!t.stopped&&t.key===o&&t.client.pendingCommand?.requestId===g;){if(!t.client.settle)throw new P("COMMAND_PENDING","The original display acknowledgement is still pending");await t.client.settle(g),u=!0,t.client.pendingCommand?.requestId===g&&await new Promise(q=>setTimeout(q,1500))}t.stopped||t.key!==o||(u&&await t.client.get(),!(t.stopped||t.key!==o)&&y.add(o))}function D(o,g){e=g;let u=()=>{e===g&&(e=null),w.delete(o)};return g.then(u,q=>{u(),t.busy||t.fail(q)}),g}function a(o){if(t.reviewing||y.has(o)||w.has(o)||t.stopped)return;w.add(o);let g=async()=>{if(t.reviewing||t.stopped||t.key!==o||y.has(o)){w.delete(o);return}if(t.busy||t.client.pendingCommand){setTimeout(()=>{g()},250);return}let u=(async()=>{if(t.staleRead){if(await t.staleRead,t.stopped||t.key!==o)return;if(t.client.pendingCommand){setTimeout(()=>{g()},250);return}}let q=t.client.view,A=t.expected(),L=A.requestId;try{await t.client.submit({operation:"shown",...A})}catch(k){if(!(k instanceof P)||k.code!=="CONFLICT"||k.status!==409||t.client.pendingCommand)throw k;await t.client.get();let d=t.client.view;if(t.stopped||t.reviewing||t.key!==o||!d||!q||d.id!==q.id||d.source.versionId!==q.source.versionId||d.nodeId!==A.nodeId||d.visit!==A.visit||d.revision<=A.revision||d.stopped||!d.screen&&(!d.paywall||d.paywall.receiptId!==q.paywall?.receiptId)||!["running","waiting"].includes(d.status)||t.client.pendingCommand)throw k;let O=t.expected();L=O.requestId,await t.client.submit({operation:"shown",...O})}await c(o,L)})();D(o,u)};g()}function S(){if(e)return e;let o=t.client.pendingCommand;if(o?.operation!=="shown")return null;let g=t.key;return w.add(g),D(g,(async()=>{await t.client.retry(),await c(g,o.requestId)})())}return{report:a,settled:S,get inFlight(){return e}}}function Ln(t){let y={},w=new Map;async function e(c){let D=t.client.view,a=D?.screen,S=a?.customerData.nodes[c.nodeId];if(t.stopped||t.busy||!D||!a||!S)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(c.action)){let k=t.document,d=k?fn(k,c.nodeId):null,O=d?.type==="customer_data"?d.data.outputs?.[c.action]:void 0;O&&a.outputs.includes(O)?await t.perform(()=>t.client.submit({operation:"submit",...t.expected(),input:{type:"screen",output:O,answers:t.answers,selection:c.value?{[c.nodeId]:c.value}:{}}})):await t.onIntent?.(c,D);return}let g=c.action.startsWith("sources_")?S.resources.find(k=>k.key===c.value):null;if(c.action.startsWith("sources_")&&!g)throw new P("INVALID_REQUEST","Choose a current resource");let u=`${D.visit}:${c.nodeId}:${g?.key??""}`,q=w.get(u)??[null],L=y[c.nodeId]??{page:1,after:null,filter:"all",...g?{resourceKey:g.key}:{}};if(c.action==="filter"){let k=c.value;if(!k||!(S.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(k))throw new P("INVALID_REQUEST","Unknown data filter");L={page:1,after:null,filter:k},q.splice(0,q.length,null)}else if(c.action==="next"||c.action==="sources_next"){let k=g?.sources.at(-1),d=g?k?{kind:"ledger",cursor:{at:k.detail[0],id:k.id,type:"source"}}:null:a.dataCursors[c.nodeId];if(!d||!g&&!S.hasNext)return;q[L.page]=d,L={...L,page:L.page+1,after:d}}else if(c.action==="previous"||c.action==="sources_previous"){if(L.page<=1)return;L={...L,page:L.page-1,after:q[L.page-2]??null}}w.set(u,q),y={...y,[c.nodeId]:L},await t.perform(()=>t.client.get({nodeId:D.nodeId,visit:D.visit,revision:D.revision,components:y}))}return{get queries(){return y},intent:e,reset(){y={},w.clear()}}}function Vn(t){let{doc:y,holder:w,reviewHolder:e,mountScreenPreview:c}=t,D=!1,a,S=0,o=null,g="",u,q=new Map,A=d=>d?`${d.id}:${d.nodeId}:${d.visit}:${d.revision}:${d.paywall?.quote?.operationId??""}`:"";async function L(d){if(t.stopped||!t.client.review||D&&d===a&&u?.active)return;let O=!D||d!==a;D||(g=A(t.client.view),q.set(g,structuredClone(t.answers))),D=!0,a=d,w.hidden=!0,t.suspend(!0),e.hidden=!1;let F=++S;O&&(u?.finish("dismissed"),o?.destroy(),o=null,e.replaceChildren(),u=Be(e,t.loadingOptions,"funnel",()=>{k()}));let R=O?u:void 0;try{if(R?.start(!1,t.client.view?.locale),F!==S||t.stopped)return;let V=t.client.review(d),b=await(R?.wait(V,Ae)??V);if(t.stopped||F!==S||!D)return;if(!b.review)throw new P("INVALID_RESPONSE","Historical projection is missing");o?.destroy(),o=null,R||e.replaceChildren();let J=y.createElement("div"),h=R?je(J,e):()=>{};e.append(J);let _=b.run.locale.startsWith("zh"),U=t.chrome;J.style.cssText=U.history;let z=y.createElement("p");z.textContent=_?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",z.style.cssText=U.historyTitle,J.append(z);let $=y.createElement("p");$.style.cssText=U.historyNote,$.textContent=b.review.pages.length?_?"\u9009\u62E9\u4E00\u9875\u67E5\u770B\u5F53\u65F6\u7684\u5185\u5BB9\uFF0C\u56DE\u770B\u4E0D\u4F1A\u6539\u52A8\u4EFB\u4F55\u4FE1\u606F\u3002":"Choose a page to see it as it was. Nothing here can be changed.":_?"\u8FD8\u6CA1\u6709\u53EF\u56DE\u770B\u7684\u9875\u9762\u3002":"There are no earlier pages yet.",J.append($);let de=b.review.page?.receiptId,Y=y.createElement("div");Y.style.cssText=U.historyPages;for(let[T,E]of b.review.pages.entries()){let i=y.createElement("button");i.type="button",i.textContent=_?`\u7B2C ${T+1} \u9875`:`Page ${T+1}`;let l=de!==void 0&&E.receiptId===de;i.style.cssText=l?U.primary:U.secondary,l&&i.setAttribute("aria-current","page"),_e(i,()=>t.chrome.focus),i.onclick=()=>{L(E.receiptId)},Y.append(i)}if(Y.childElementCount&&J.append(Y),b.review.page){let T=b.review.page,E=y.createElement("div");E.inert=!0,E.style.cssText=U.historyPage,J.append(E),o=c(E,{mode:"live",rendererUrl:t.client.webViewUrl,title:T.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{F===S&&!t.stopped&&R?.present(h)},onError:l=>{if(F!==S||t.stopped)return;let s=new Error(l);R?.finish("error",s),o?.destroy(),o=null,J.remove(),t.fail(s)},onEscape:()=>{k()}});let i=o;if(i.update(T.document,b.run.locale,{serverInput:{bindings:T.inputs,answers:T.answers,values:T.values}}),await i.ready,t.stopped||F!==S||!D)return}let ce=_?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},re=y.createElement("div");re.style.cssText=U.historyRecords;for(let T of[...b.review.coupons.map((E,i)=>`${_?"\u4F18\u60E0\u5238":"Coupon"} ${i+1}: ${ce[E.status]}`),...b.review.purchases.map((E,i)=>`${_?"\u8D2D\u4E70":"Purchase"} ${i+1}: ${Dn(E.status,_)}`)]){let E=y.createElement("p");E.textContent=T,E.style.margin="0",re.append(E)}re.childElementCount&&J.append(re),b.review.page||R?.present(h),t.client.view&&await t.enqueue(t.client.view)}catch(V){if(F!==S||t.stopped)return;R?.finish("error",V),o?.destroy(),o=null,e.replaceChildren(),t.fail(V)}}async function k(){if(!D||t.stopped||!t.client.review)return;let d=++S;u?.finish("dismissed");try{if(await t.client.review(),t.stopped||d!==S)return;D=!1,S++,u?.finish("dismissed"),o?.destroy(),o=null,e.replaceChildren(),e.hidden=!0,w.hidden=!1;let O=t.client.view;A(O)!==g?(q.set(g,structuredClone(t.answers)),t.resetScreen()):(q.delete(g),t.suspend(!1)),O&&await t.enqueue(O)}catch(O){if(d!==S||t.stopped)return;o?.destroy(),o=null,e.replaceChildren(),t.fail(O)}}return{get active(){return D},get receipt(){return a},open:L,exit:k,get drafts(){return new Map([...q].map(([d,O])=>[d,structuredClone(O)]))},stop(){D=!1,S++,u?.finish("dismissed"),o?.destroy(),o=null,e.replaceChildren(),e.hidden=!0,w.hidden=!1}}}function Mn(t){if(!t.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let y=t.client.pageExperiments.bind(t.client),w=!1,e=!1,c=0,D=!1,a=!1,S="",o=()=>{let h=t.client.view;return JSON.stringify([h?.id,h?.source.versionId,h?.visit,h?.revision,h?.status,h?.stopped])},g=new Map,u=new Set,q={},A=new Map,L=Sn(t.appManifestRelease),k=()=>{for(let h of g.values())h.effect.revert();g.clear()},d=()=>{k();for(let h of A.values())h();A.clear()};function O(h){if(w||u.has(h))return;u.add(h);let _=c;y(t.appManifestRelease,[h]).catch(U=>{u.delete(h),!w&&_===c&&le(t.onError,U)})}async function F(){if(w)return;S=o();let h=t.client.view;if(!h||h.stopped||!["running","waiting"].includes(h.status)){c++,d();return}if(document.visibilityState==="hidden")return;if(D){a=!0;return}D=!0;let _=++c,U=`${h.id}:${h.visit}:${h.revision}`,z=location.href;try{let[$,{applyVisualVariation:de}]=await Promise.all([y(t.appManifestRelease),import("./visual-dom-5LUN4AHO.js")]),Y=t.client.view;if(w||_!==c||!Y||Y.stopped||!["running","waiting"].includes(Y.status)||`${Y.id}:${Y.visit}:${Y.revision}`!==U||location.href!==z)return;let ce=new Set,re=new Set;for(let T of $.assignments){let E=`${$.payload.environmentId}:${T.experimentKey}`;if(re.add(E),A.has(E)||A.set(E,On(E,q)),!!T.inExperiment)for(let i of $.payload.experiments){if(i.key!==T.experimentKey||!mn(location.href,i.urlPatterns??[]))continue;let l=i.meta?.findIndex(Q=>Q.key===T.variationKey)??-1,s=i.variations[l];if(!s?.renderGuard)continue;let p=T.receiptId+":"+i.changeId,I=JSON.stringify([T.variationKey,s]);ce.add(p);let C=g.get(p);if(C?.signature===I){C.effect.applied&&O(T.receiptId);continue}g.get(p)?.effect.revert(),g.delete(p);let B=de(s,{requireUniqueTargets:!0,boundVariations:i.variations,allowJs:!1,onApplied:()=>O(T.receiptId),onError:Q=>le(t.onError,Q)});g.set(p,{signature:I,effect:B}),B.applied&&O(T.receiptId)}}for(let[T,E]of g)ce.has(T)||(E.effect.revert(),g.delete(T));for(let[T,E]of A)re.has(T)||(E(),A.delete(T))}catch($){_===c&&d(),!w&&_===c&&le(t.onError,$)}finally{D=!1,a&&!w&&(a=!1,F())}}let R=t.client.subscribe(()=>{if(o()===S)return;S=o(),c++;let h=t.client.view;(!h||h.stopped||!["running","waiting"].includes(h.status))&&d(),e&&F()}),V=Tn(()=>{c++,d(),e&&F()}),b=()=>{c++,k()};document.addEventListener("visibilitychange",b);let J=We({document,run:async()=>{e&&await F()},delay:()=>e&&!w?15e3:void 0});return{async start(){e||w||(e=!0,await J.refresh())},refresh:F,destroy(){w=!0,c++,J.destroy(),document.removeEventListener("visibilitychange",b),R(),V(),d(),L.destroy()}}}var sn=5e3;async function zn(t,y,w){let e=y,[{mountScreenPreview:c},{showPaywall:D}]=await Promise.all([import("./screen-renderer-ITUUNF4E.js"),import("./paywall-BEFHTZW7.js")]),a=e.client.identitySignal;e.signal?.throwIfAborted(),a?.throwIfAborted();let S=e.appManifestRelease?Mn({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;S?.start();let o=t.ownerDocument,g=qn(o),u=o.createElement("section"),q=o.createElement("div"),A=o.createElement("div"),L=o.createElement("div"),k=o.createElement("button");L.hidden=!0,k.type="button";let d=o.createElement("p"),O=o.createElement("p"),F=o.createElement("button"),R=o.createElement("button"),V=o.createElement("button"),b=o.createElement("dialog"),J;u.dataset.indianaFunnel="",u.setAttribute("aria-busy","false"),d.setAttribute("role","status"),O.setAttribute("role","alert"),O.hidden=!0,F.type=R.type=V.type="button",A.append(F,k,d,O,V,R),u.append(q,L,A),t.append(u);let h=kn,_=rn(h),U="",z=(o.documentElement.lang||"").startsWith("zh"),$,de="",Y;for(let n of[F,k,V,R])_e(n,()=>_.focus);function ce(){let n=z?"\u5173\u95ED":"Close";R.parentElement===b?(R.textContent="\xD7",R.setAttribute("aria-label",n),Rn(R,h)):(R.textContent=n,R.removeAttribute("aria-label"),R.style.cssText=_.link+";margin-inline-start:auto")}function re(n){let r=n?.screen?.content.document.theme??h,f=JSON.stringify([r.primary,r.background,r.text,r.radius,r.font,R.parentElement===b]);f!==U&&(U=f,h=r,_=rn(h,R.parentElement===b),u.style.cssText=_.root+";min-width:0",A.style.cssText=_.bar,F.style.cssText=k.style.cssText=_.secondary,V.style.cssText=_.primary,d.style.cssText=_.status,O.style.cssText=_.alert,ce(),on(F))}function T(){A.hidden=F.hidden&&k.hidden&&V.hidden&&O.hidden&&!d.textContent&&(R.hidden||R.parentElement!==A),$?.responsive&&Y!==void 0&&$.setContentHeight(Y+A.getBoundingClientRect().height)}re();let E=null,i=null,l=null,s="",p="",I=!1,C="",B="",Q="",v=!1,x=0,Re=!1,Ee="",Ke=null,Ye=Promise.resolve(),an=!e.client.view,W=w,qe,Oe,Le="",Ve,pe=!1,Ie=null,ye=!1,Me=()=>e.client.pendingCommand?.operation==="close",se=null,K=null,ln=We({document:o,run:async()=>{(!i?.observing||e.client.pendingCommand)&&await Ze()},delay:()=>{if(!(v||!l||!["running","waiting"].includes(l.status)&&!e.client.pendingCommand)&&!(i?.observing&&!e.client.pendingCommand))return l.pendingRequest||e.client.pendingCommand?1500:sn},hiddenDelay:()=>!v&&e.client.pendingCommand?15e3:void 0}),X=null;function Xe(){return K&&e.client.hasDurableJournal===!0&&X?.acknowledged===!0&&X.operationId===K.operationId&&e.client.view?.id===X.runId&&e.client.view?.status==="closed"&&e.client.view.revision===X.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?K:null}function un(n){let r=n.run.paywall;if(X&&n.settlement?.requestId===X.requestId&&n.settlement.state==="settled"&&n.settlement.operationId===null&&n.run.id===X.runId&&n.run.status==="closed"&&!n.run.pendingRequest&&n.run.revision===X.revision+1&&n.run.nodeId===X.nodeId&&n.run.visit===X.visit&&r?.receiptId===X.receiptId&&r.selectionGeneration===X.selectionGeneration&&(r.quote?.operationId??null)===X.operationId&&(r.operation?.operationId??r.quote?.operationId??null)===X.operationId){let f=X.operationId===null&&r.selectionGeneration===0&&!r.quote&&!r.operation&&!r.purchaseRequestId,ne=ze({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect});(f||r.canReselect===!0&&ne.type==="native")&&(X.acknowledged=!0)}}let ke=null,He=new Set,fe={},Fe=!1,ue=(n,r=null)=>{v||(ke=r,Fe=!1,O.textContent=Fn(n,z),O.hidden=!1,V.hidden=e.client.pendingCommand===null,T(),le(e.onError,n))};function be(){let n=e.client.view;if(!n)throw new P("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision}}let M=Vn({client:e.client,doc:o,holder:q,reviewHolder:L,mountScreenPreview:c,loadingOptions:e,get chrome(){return _},get stopped(){return v},get answers(){return fe},suspend(n){i?.setSuspended(n)},resetScreen(){s="",p="",C=""},enqueue:me,fail:ue}),$e=_n({client:e.client,expected:be,fail:ue,get stopped(){return v},get reviewing(){return M.active},get key(){return s},get busy(){return x},get staleRead(){return Ke}}),Ue=Ln({client:e.client,expected:be,perform:Se,onIntent:e.onCustomerDataIntent,get stopped(){return v},get busy(){return x},get document(){return E?.document},get answers(){return fe}}),xe=n=>`${n.id}:${n.nodeId}:${n.visit}`,De=n=>n&&(n.screen||n.paywall)?xe(n):"";function Ce(){let n=e.client.view;F.disabled=!M.active&&(x>0||!!e.client.pendingCommand||!n?.canBack||n.stopped||!["running","waiting"].includes(n.status)||!De(n)||p!==De(n)),F.hidden=!M.active&&!n?.canBack,on(F);let r=!!i&&!M.active;R.hidden=r&&!W?.active,k.hidden=!e.client.review||r&&!n?.canBack,r&&(d.textContent=""),T()}async function dn(n){if(!n)return;let r=e.client.view;await n;let f=e.client.view;if(!r||!f||f.id!==r.id||f.nodeId!==r.nodeId||f.visit!==r.visit||f.stopped||!["running","waiting"].includes(f.status))throw new P("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Se(n,r=!1){if(!((x||ye||se||K)&&!r||v||M.active&&!r)){x++,u.setAttribute("aria-busy","true"),O.hidden=!0,ke=null,Fe=!1,Ce();try{if(r||await dn($e.inFlight),v)return;let f=await n();v||await me(e.client.view??f.run)}catch(f){ue(f,e.client.pendingCommand?.requestId??null)}finally{x=Math.max(0,x-1),u.setAttribute("aria-busy",String(x>0)),v||(V.hidden=e.client.pendingCommand===null,Ce())}}}function Ne(){ln.schedule()}async function Ze(){if(!(v||Re||x)){if(M.active){await M.open(M.receipt);return}Re=!0;try{let n=e.client.pendingCommand;n&&e.client.settle&&await e.client.settle(n.requestId);let r=e.client.view,f=Ue.queries,ne=await e.client.get(r?.screen&&Object.keys(f).length?{nodeId:r.nodeId,visit:r.visit,revision:r.revision,components:f}:void 0);Fe&&!v&&(Fe=!1,O.hidden=!0,T()),!v&&f===Ue.queries&&await me(e.client.view??ne.run)}catch(n){ue(n),Fe=!v}finally{Re=!1}}}function Ge(n,r){if(W?.active){let ne=W;return ne.setDismissHandler(()=>cn(ne)),ne}let f=Be(t,e,"funnel",()=>cn(f));return W=f,f.start(n,r),f}function cn(n){v||pe||(pe=!0,n.finish("dismissed"),ve(),u.hidden=!0,e.client.view?Pe().finally(ae):ae())}function en(){clearTimeout(Ve?.timeout),Ve=void 0}function ve(){en(),qe?.abort(),qe=void 0,E?.destroy(),E=null,i?.destroy(),i=null,Oe?.(),Oe=void 0,b.open&&b.close(),q.replaceChildren(),q.style.cssText="",Y=void 0,s="",p="",I=!1,C="",Q=""}function pn(){let n=o.defaultView;$?.responsive&&n&&E?.resizeViewport?.(n.innerHeight,n.innerWidth)}function nn(){$?.destroy(),$=void 0,de=""}function tn(n){let r=n.screen?.presentation;if(!r||r.type==="inline"){b.open&&b.close(),nn(),R.parentElement!==A&&A.append(R),u.parentElement!==t&&t.append(u),re(n),T();return}u.parentElement!==b&&(b.append(R,u),t.append(b)),re(n);let f=n.screen.content.document,ne=JSON.stringify([r,U]);if(ne!==de){nn(),de=ne;let ge={sm:420,md:640,lg:900},we="size"in r&&!r.backdrop?",0 0 0 100vmax #16142566":"";b.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${h.background};color:${h.text};`+(r.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ge[r.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${we};`+(r.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),$=Cn(b,{presentation:r,theme:f.theme,pages:f.pages},pn),$.latch()}T(),b.setAttribute("aria-label",(J?.screen===n.screen?.content.document.name?J?.label:void 0)??E?.document?.name??n.screen?.content.document.name??"Funnel")}async function Hn(n){if(v||pe||ye&&(Me()||["running","waiting"].includes(n.status))||(l=n,ke&&e.client.pendingCommand?.requestId!==ke&&(O.hidden=!0,ke=null),z=n.locale.startsWith("zh"),k.textContent=z?"\u56DE\u770B":"History",F.textContent=M.active?z?"\u8FD4\u56DE\u5F53\u524D":"Return to current":z?"\u8FD4\u56DE":"Back",ce(),V.textContent=z?"\u91CD\u8BD5":"Retry",V.hidden=e.client.pendingCommand===null,d.textContent=n.pendingRequest?z?"\u6B63\u5728\u5904\u7406":"Processing":n.instruction?.type==="wait"?z?"\u7B49\u5F85\u4E2D":"Waiting":"",Ce(),Ee!==`${n.revision}:${n.visit}:${n.status}:${n.stopped}`&&(Ee=`${n.revision}:${n.visit}:${n.status}:${n.stopped}`,le(e.onState,structuredClone(n))),v||pe))return;if((!n.pendingRequest||ye&&n.status==="closed")&&["closed","ineligible","failed"].includes(n.status)){ae();return}if(n.stopped||e.client.configurationReady===!1){M.stop(),ve(),W?.finish("skipped"),u.hidden=!0,Ne();return}if(u.hidden=!1,M.active){Ne();return}let r=De(n),f=e.client.view;if(f&&f.revision>n.revision&&De(f)!==r)return;let ne=!n.instruction&&!n.pendingRequest&&n.nodeType==="screen"&&["running","waiting"].includes(n.status);r!==s&&(s&&W?.finish("dismissed"),ve(),s=r,fe={...n.answers},Ue.reset());let ge=xe(n);if(Le===ge){u.hidden=!0;return}if(ne&&!r){u.hidden=!0;let G=Ge(!0,n.locale);!v&&!pe&&Ve?.key!==ge&&(en(),Ve={key:ge,timeout:setTimeout(()=>{let m=e.client.view;if(!G.active||!m||xe(m)!==ge)return;Le=ge;let j=new Error("Funnel screen preparation timed out");G.finish("error",j),ve(),ue(j)},Ae)}),Ne();return}en();let Z=G=>{let m=e.client.view;return!v&&!pe&&!Ie&&!G.aborted&&e.client.configurationReady!==!1&&!!m&&!m.stopped&&!["closed","ineligible","failed"].includes(m.status)&&De(m)===r},we=(G,m)=>{Z(m)&&(Le=r,W?.finish("error",G),ve(),u.hidden=!0,ue(G))};if(r||(tn(n),n.instruction?.type!=="event"&&n.instruction?.type!=="open_url"&&W?.finish("skipped")),n.screen){let G=n.screen.content;if(!E){let te=n.screen.presentation.type!=="inline",oe=Ge(te,n.locale);if(v||pe)return;let ie=(qe=new AbortController).signal;tn(n),Oe=te?En(b):je(u,t),E=c(q,{mode:"live",rendererUrl:e.client.webViewUrl,title:G.document.name,...te?{hostPresentation:()=>$?.type??n.screen.presentation.type}:{},onResize:ee=>{Y=ee,$?.responsive&&$.setContentHeight(ee+A.getBoundingClientRect().height)},onAction(ee,he={},Gn={}){if(M.active||!Z(ie)||p!==r)return;fe={...fe,...Gn};let Jn=Object.fromEntries((n.screen?.inputs??[]).filter(({variable:Je})=>Object.hasOwn(fe,Je)).map(({variable:Je})=>[Je,fe[Je]]));Se(()=>e.client.submit({operation:"submit",...be(),input:{type:"screen",output:ee,answers:Jn,selection:he}}))},onAnswers:ee=>{M.active||!Z(ie)||p!==r||(fe={...fe,...ee})},onCustomerDataIntent:ee=>{M.active||!Z(ie)||p!==r||Ue.intent(ee).catch(ue)},onEscape:()=>{!Z(ie)||p!==r||M.active||se||K||Pe()},onError:ee=>{let he=new Error(ee);p===r?ue(he):we(he,ie)},onRendered:ee=>{if(!(!Z(ie)||p===r))try{oe.present(he=>{Oe?.(),Oe=void 0,ee&&(J={screen:G.document.name,label:ee},b.setAttribute("aria-label",ee)),te&&(b.showModal(),$?.responsive&&b.focus({preventScroll:!0}),!he&&e.loading!=="host"&&Pn(b,$?.type??n.screen.presentation.type,$?.responsive)),p=r,I=te,Ce()}),Z(ie)&&$e.report(r)}catch(he){we(he,ie)}}}),pn()}let m={capabilities:n.screen.capabilities,customerData:n.screen.customerData,parameters:n.parameters,serverInput:{bindings:n.screen.inputs,answers:fe,values:n.screen.values}},j=JSON.stringify([G,n.locale,m.parameters,n.screen.inputs,n.screen.values]);if(j!==C)E.update(G.document,n.locale,m),C=j,B=JSON.stringify(m.capabilities),Q=JSON.stringify(m.customerData);else{let te=JSON.stringify(m.capabilities);te!==B&&(E.updateCapabilities(m.capabilities),B=te),JSON.stringify(m.customerData)!==Q&&(E.updateCustomerData(m.customerData),Q=JSON.stringify(m.customerData))}let H=E;if(H)try{await(W?.wait(H.ready)??H.ready)}catch(te){qe&&we(te,qe.signal)}}else if(n.paywall&&!i){let G=Ge(!0,n.locale);if(v||pe)return;let m=(qe=new AbortController).signal;tn(n);let j=await D(q,{loading:"host",signal:m,canInteract:()=>Z(m)&&!M.active&&!se&&!K,beforeAction:async()=>{x++;try{await dn($e.settled()),O.hidden=!0,ke=null,Fe=!1,T()}finally{x=Math.max(0,x-1)}},start:()=>An(e.client),onObservationChange:Ne,onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,checkoutNavigation:e.checkoutNavigation,confirmOnHostedCheckout:e.confirmOnHostedCheckout,resolveOfferId:e.resolveOfferId,onEvent:e.onEvent,onOpenUrl:H=>e.onOpenUrl?e.onOpenUrl({receiptId:n.paywall.receiptId,url:H,openIn:"same_window"}):o.defaultView?.location.assign(H),onAction:async H=>{if(M.active)return;let te=await e.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:e.client.view?.revision??n.revision,input:{type:"screen",output:H,answers:{}}});await me(e.client.view??te.run)},onError:H=>{p===r?ue(H):we(H,m)}},{quoteError:H=>le(e.onError,H),present(H){Z(m)&&(G.present(()=>{H(),p=r,I=!!q.querySelector("dialog[open]"),Ce()}),Z(m)&&$e.report(r))},async dismiss(){v||m.aborted||M.active||se||K||!ye&&!Z(m)||(ye=!0,await Pe())}}).catch(H=>(we(H,m),null));!Z(m)&&!(ye&&!v&&!m.aborted)?j?.host?.destroy():j&&(i=j.host,i?.setSuspended(M.active))}if(v||pe)return;Ce();let N=n.instruction;if(N&&(N.type==="open_url"||N.type==="event")&&!He.has(N.receiptId)){let G=o.createElement("button");G.type="button",G.style.cssText=_.primary,_e(G,()=>_.focus),q.style.cssText=_.stage,G.textContent=N.type==="open_url"?`${z?"\u524D\u5F80":"Continue to"} ${new URL(N.url).host}`:z?"\u7EE7\u7EED":"Continue",G.onclick=()=>{let m=be(),j=N.type==="open_url"&&!e.onOpenUrl&&N.openIn==="new_window"?$n(N.url):null;Se(async()=>{let H="success";if(N.type==="open_url")if(e.onOpenUrl)try{H=await e.onOpenUrl({receiptId:N.receiptId,url:N.url,openIn:N.openIn})===!1?"failed":"opened"}catch(oe){le(e.onError,oe),H="failed"}else H=N.openIn==="new_window"&&!j?"failed":"opened";if(N.type==="event"){if(!e.onEvent)throw new P("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent(N.event)}if(v||e.client.view?.nodeId!==m.nodeId||e.client.view.visit!==m.visit)throw new P("PRECONDITION_FAILED","The client action visit changed");let te=await e.client.submit({operation:"submit",...m,input:{type:"client_action",receiptId:N.receiptId,outcome:H}});return He.add(N.receiptId),N.type==="open_url"&&!e.onOpenUrl&&N.openIn==="same_window"&&o.defaultView?.location.assign(N.url),te})},W?.active?W.present(()=>q.replaceChildren(G)):q.replaceChildren(G)}!n.pendingRequest&&n.status==="completed"&&!He.has(`complete:${n.id}`)&&(He.add(`complete:${n.id}`),le(e.onComplete,structuredClone(n))),Ne()}function $n(n){let r=o.defaultView?.open(n,"_blank")??null;return r&&(r.opener=null),r}function me(n){return Ce(),Ye=Ye.catch(()=>{}).then(async()=>{try{await Hn(n)}catch(r){throw W?.active&&(Le=xe(n),W.finish("error",r),ve(),u.hidden=!0),r}}),Ye}let Un=e.client.subscribe(n=>{if(!an){if(n.stopped&&I&&!ye){l=n,ae();return}!ye&&(n.stopped||e.client.configurationReady===!1||s&&p!==s&&(De(n)!==s||["closed","ineligible","failed"].includes(n.status)))&&(ve(),W?.finish("dismissed"),u.hidden=!0),me(n).catch(ue)}}),xn=e.client.subscribeError?.(ue);function Pe(n){if(Ie)return Ie;if(v||!n&&(se||K))return Promise.resolve();let r=!n&&Me();return!r&&e.client.view&&!["running","waiting"].includes(e.client.view.status)?(l=e.client.view,ae(),Promise.resolve()):(Ie=Se(async()=>{let f=r?await e.client.retry():await e.client.submit({operation:"close",...n??be()});return n&&un(f),f},!0).then(()=>{let f=e.client.view;f?.status==="closed"&&!Me()&&(l=f,ae())}).finally(()=>{Ie=null}),Ie)}function ae(){S?.destroy(),!v&&(v=!0,e.signal?.removeEventListener("abort",ae),a?.removeEventListener("abort",ae),W?.finish("dismissed"),ln.destroy(),Un(),xn?.(),ve(),nn(),M.stop(),b.remove(),u.remove(),g(),le(e.onDismiss,l?structuredClone(l):null))}F.onclick=()=>{if(!F.disabled){if(M.active){M.exit();return}Se(()=>e.client.submit({operation:"back",...be()}))}},k.onclick=()=>{M.open()},R.onclick=()=>{W?.active?W.dismiss():se||Pe()},V.onclick=()=>{Me()?Pe():Se(()=>e.client.retry())},b.addEventListener("cancel",n=>{n.preventDefault(),W?.active?W.dismiss():se||Pe()}),e.signal?.addEventListener("abort",ae,{once:!0}),a?.addEventListener("abort",ae,{once:!0});try{let n=e.client.view;if(n)((e.client.viewAgeMs??sn)>=sn||n.instruction?.type==="evaluate_segment")&&(Ke=Ze().finally(()=>{Ke=null})),await me(n);else{u.hidden=!0;let r=Ge(e.client.view?.screen?.presentation.type!=="inline",e.client.view?.locale);if(v||pe)throw new DOMException("Presentation cancelled","AbortError");let f=await r.wait(e.client.get(),Ae);an=!1,await me(e.client.view??f.run)}}catch(n){throw W?.finish("error",n),ae(),n}return{destroy:ae,refresh:Ze,get recovery(){let n=Xe();if(n)return n;if(!v&&!x&&!ye&&!se&&i){let r=i.recovery;if(r.type!=="native")return r}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??K?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(se)return se;let n=Xe();if(n)return Promise.resolve(n);let r=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??K?.operationId??null,f=()=>({type:"recover",operationId:r,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let N=i?.recovery;return Promise.resolve(N&&N.type!=="native"&&N.type!=="cancel"?N:f())}let ne=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(N=>N.operation==="close");if(v&&!(ne||K&&e.client.view?.status==="closed")||x||Re||Ie||M.active||!i&&!K&&!ne)return Promise.resolve(f());let ge=i,Z=(async()=>{try{if(!K&&ne){let m=await e.client.retry();return await me(e.client.view??m.run),f()}if(!K){let m=await ge.prepareFallback();if(m.type!=="native")return m;if(e.client.hasDurableJournal!==!0)return f();K=m}let N=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(N.length){let m=N.find(H=>H.operation==="close");if(!m||!X||m.requestId!==X.requestId)return f();let j=await e.client.retry();un(j),await me(e.client.view??j.run)}else{let m=e.client.view,j=m?.paywall;if(!m||!j||j.selectionGeneration===void 0||(j.quote?.operationId??null)!==K.operationId||K.operationId!==null&&j.canReselect!==!0)return f();let H=j.selectionGeneration,te=await e.client.get();await me(e.client.view??te.run);let oe=e.client.view,ie=oe?.paywall;if(!oe||!ie||!["running","waiting"].includes(oe.status)||oe.stopped||oe.id!==m.id||oe.nodeId!==m.nodeId||oe.visit!==m.visit||ie.receiptId!==j.receiptId||ie.selectionGeneration!==H||(ie.quote?.operationId??null)!==K.operationId||K.operationId!==null&&ie.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return f();let ee=be();X={runId:oe.id,operationId:K.operationId,revision:ee.revision,requestId:ee.requestId,nodeId:oe.nodeId,visit:oe.visit,receiptId:ie.receiptId,selectionGeneration:H,acknowledged:!1},await Pe(ee)}let G=Xe();return G?(ae(),G):f()}catch(N){return ue(N),f()}})();se=Z;let we=()=>{se===Z&&(se=null)};return Z.then(we,we),Z},review:M.open,exitReview:M.exit,get unappliedDrafts(){return M.drafts}}}function Vt(t,y,w){return zn(t,y,w)}export{Bn as a,Mn as b,zn as c,Vt as d};
@@ -0,0 +1 @@
1
+ import{p as n,s as t}from"./chunk-JPHYIUIR.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
@@ -1 +1 @@
1
- import{e as rn}from"./chunk-EBXWLW4D.js";import{h as ue,i as se,r as nn,s as pe}from"./chunk-5M536ISX.js";import{c as Be,d as Ke,e as J,l as en}from"./chunk-2GMWNOOE.js";import{$ as U,D as Ye,R as Qe,W as Ze,X as We,Y as $,Z as Xe,_ as de,a as q,b as je,c as Me,d as qe,e as G,f as Ge,g as Ue,i as X,w as ee,x as ze,z as Je}from"./chunk-XZMM34BS.js";import{b as on}from"./chunk-26YREQNF.js";import{b as ne}from"./chunk-MTKM26F7.js";import{a as W}from"./chunk-S67P7ZQ6.js";import{D as Te,L as ae,U as D,V as De,W as Le,ja as $e,ka as le,la as He,ma as ce,t as Oe,z as Ae}from"./chunk-TJMODHSS.js";import{a as f}from"./chunk-S4X6YX5D.js";import{h as V}from"./chunk-2ZPCWVFU.js";import{b as tn}from"./chunk-AEERSTTW.js";import{b as n}from"./chunk-ZGBSTK22.js";import{c as _e,d as ke,e as Ve,f as z}from"./chunk-5OJVM7Q4.js";import{a as Pe,b as Ne}from"./chunk-QENDBHBQ.js";function an(e){return En({...e,namespace:"commands",identity:[e.runToken]})}function En(e){let t,u,r=()=>new f("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let d=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??tn).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",d));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,o=>o.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function p(d){try{let a=await i;return await u.request(a,{mode:"exclusive"},()=>d(a))}catch(a){throw a instanceof f?a:r()}}function c(d){let a=t.getItem(d);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let o=JSON.parse(a);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw r();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(c),write:(d,a)=>p(o=>{if(c(o).revision!==d)return null;if(!Number.isSafeInteger(d+1))throw r();let y=JSON.stringify({revision:d+1,entry:a});if(y.length>1048576)throw r();return t.setItem(o,y),d+1})}}var un=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var L=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Cn=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Pn=n.discriminatedUnion("type",[Ye,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:L.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:Ze,openIn:We}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:L})]),Nn={id:L,presentation:Te,outputs:n.array(L).max(250),inputs:ce,values:n.record(n.string(),D).optional(),offeringKey:q.optional(),capabilities:Oe,customerData:Ae,dataCursors:n.record(L,$e.nullable())},On=n.strictObject({...Nn,content:n.strictObject({type:n.literal("document"),document:ae})}),me=n.strictObject({id:n.uuid(),source:un,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:L,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Cn,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:le,parameters:He,variables:n.record(n.string(),D),output:D.nullable(),screen:On.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([nn,pe]),quote:ue.nullable(),operation:se.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Pn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),An=n.strictObject({scope:V,run:me,settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),operationId:n.uuid().nullable(),receiptId:n.uuid().nullable().optional()}).optional(),purchase:n.strictObject({receiptId:n.uuid(),quote:ue.nullable(),operation:se.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:L,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:L,visit:n.number().int().nonnegative(),document:ae,answers:le,inputs:ce,values:n.record(n.string(),D).optional()}).nullable(),coupons:n.array(n.strictObject({grantId:n.uuid(),status:n.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:n.string().nullable()})).max(100),purchases:n.array(n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),status:n.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:n.uuid().optional()}),sn=An.extend({run:me.extend({paywall:me.shape.paywall.unwrap().extend({resolution:pe}).nullable()})});var ln="X-Indiana-Server-Key";var H=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function fe(e,t,u){let r={},i,p,c,d="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let o=e.cases.findIndex(g=>ke(t.attributes??{},g.condition,t.savedGroups??{}));d=o<0?"default":`case:${o}`,a=o<0?e.default:e.cases[o].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new H("Required GB Feature is unavailable");i=z(e.featureKey,t),c=i.value,Object.assign(r,G(e,{value:c})),a=e.next;break;case"split":{let o=u[e.experimentId];if(!o)throw new H("Required GB Experiment is unavailable");if(p=Ve(o,t),c=p.value,d=p.inExperiment&&!p.passthrough&&typeof c=="string"?c:"notParticipating",a=d==="notParticipating"?e.notParticipating:e.routes[d],!a)throw new H("Experiment Variation has no published route");break}case"offering":{let o=e.configuration.source==="fixed"?e.configuration.versionId:z(e.configuration.featureKey,t).value;c={type:"offering_version",id:n.uuid().parse(o)},Object.assign(r,G(e,{value:c})),a=e.next;break}case"coupon":case"coupons":c=e.type==="coupons"?e.couponIds.map(o=>({type:"reward",id:o})):{type:"reward",id:e.couponId},Object.assign(r,G(e,{value:c})),a=e.next;break}return{port:d,target:a,projections:r,...c===void 0?{}:{value:c},...i?{feature:i}:{},...p?{experiment:p}:{}}}function cn(e,t,u){n.uuid().parse(e),n.number().int().nonnegative().parse(t);let r=Pe(Ne(new TextEncoder().encode(JSON.stringify([e,t,u])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var Tn=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),_n=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(Tn).max(200).default([]),iam:ze.optional(),renderGuard:ee.optional()}),ge=_n.omit({variation:!0,description:!0,iam:!0}),kn=Be.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20)}),dn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(kn).max(100),savedGroups:Ke});var Y=n.string().regex(/^[a-f0-9]{64}$/),jt=n.strictObject({iam:Y,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),Vn=n.strictObject({release:Y,render:ee,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),Mt=n.strictObject({scope:V.extend({environmentId:n.uuid()}),release:Y,validatedAt:n.iso.datetime({offset:!0}),validUntil:n.iso.datetime({offset:!0}),entries:n.array(n.strictObject({id:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),event:n.enum(["screen_enter","button_click"]),target:Vn})).max(4e3)}),qt=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:Y,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Gt=n.strictObject({scope:V,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Ut=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Dn=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),ye=n.strictObject({operation:n.literal("page_experiments"),release:Y,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(W).optional()}),pn=n.strictObject({scope:V,runId:n.uuid(),assignments:n.array(Dn.extend({receiptId:n.uuid()})).max(100),payload:dn});var B=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fn=n.strictObject({entry:B,nodes:n.array(n.strictObject({id:B,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),B),writes:n.record(q,q),resources:n.strictObject({screenId:B.optional(),paywallVersionId:n.uuid().optional(),couponId:n.uuid().optional(),couponIds:n.array(n.uuid()).max(20).optional(),experimentId:n.uuid().optional(),featureKey:n.string().optional(),offeringVersionId:n.uuid().optional()})})).min(1).max(500)}),mn={scope:V,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:fn},te=n.discriminatedUnion("evaluationMode",[n.strictObject({...mn,evaluationMode:n.literal("local"),growth:J,conditions:n.record(B,n.array(n.strictObject({condition:Le,port:n.string()})))}),n.strictObject({...mn,evaluationMode:n.literal("remote")})]),Ln=te.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(q,Me),outputSchema:je,terminals:n.record(B,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Qe.nullable()}))})});function jn(e){return fn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let p=e.screens.find(c=>c.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,c)=>{u[`case:${c}`]=p.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let p of["success","cancel","unavailable","failure"])u[p]=t[p];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ve(e){let t=de.parse(e.document),u=e.evaluationMode==="local"?J.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:u?.expiresAt??null,topology:jn(t)};return te.parse(e.evaluationMode==="remote"?r:{...r,growth:en(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((p,c)=>({condition:p.condition,port:`case:${c}`}))]))})}function Wt(e){let t=ve(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=de.parse(e.document);return Ln.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var he=32,Mn=522240;function we(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var qn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),Ie=n.record(n.string(),D),Gn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:$.shape.schemaVersion,kind:$.shape.kind,selector:$.shape.selector,contract:$.shape.contract}),context:Ie,removed:n.array(n.string()).max(100),attributes:Ie,removedAttributes:n.array(n.string()).max(100),result:Xe,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),or=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:qn,context:Ie,steps:n.array(Gn).min(1).max(he)}).refine(e=>X(e)<=Mn,"Segment exceeds its byte budget");var Un=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Q(e){return Array.isArray(e)?e.some(Q):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Q(u):!Un.test(t))}function gn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(d=>d.id===t.screenId&&d.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(d=>Q(d.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(d=>d.id===t.screenId):null]);for(let[d,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${d}`)||p.includes(JSON.stringify(d))))return"customer_required";if(t.type==="split"){let d=u.experiments?.[t.experimentId];if((d?.hashAttribute??"id")!=="funnelParticipantId"||Q(d?.condition)||d?.parentConditions?.length)return"customer_experiment_required"}let c=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return c&&u.features?.[c]?.rules?.some(d=>(d.hashAttribute??"id")!=="funnelParticipantId"||Q(d.condition)||d.parentConditions?.length)?"customer_experiment_required":null}var be=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},re=(e,t)=>new be(e,t),Bn=e=>({experiments:e.experiments,features:e.features});function xe(e,t=re){let u=new Map(e.topology.nodes.map(c=>[c.id,c])),r=_e(e.growth.savedGroups),i=Bn(e.growth);function p(c,d){if(!Object.hasOwn(e.growth.features,c))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return z(c,d).value}return{nodes:u,savedGroups:r,features:i.features,feature:p,evaluate(c,d){let a=u.get(c);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let o,g;if(a.type==="condition"){let v=e.conditions[a.id];if(!v)throw t("INVALID_RESPONSE","Local condition rules are unavailable");o=fe({id:a.id,name:a.id,type:"condition",cases:v.map(I=>({condition:I.condition,target:a.outputs[I.port]})),default:a.outputs.default},d,i.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,d),o="next"}else if(a.type==="split"){if(!(a.resources.experimentId?e.growth.experiments[a.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let I=fe({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},d,i.experiments);g=I.value,o=I.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,d),o=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[o]??(o==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:c,port:o,target:y,...g===void 0?{}:{value:g}}}}}function vr(e,t,u,r=re){return Re(e,r)(t,u)}function Re(e,t){let u=te.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let p=xe(u,t);return(c,d)=>(i(),Kn(p,c,d))}function Kn(e,t,u){let r=De.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:p,onExperimentViewed:c}=u,d={attributes:r,...i?{saveStickyBucketAssignmentDoc:a=>i(structuredClone(a))}:{},...p?{onFeatureUsage:(a,o)=>p(a,structuredClone(o))}:{},...c?{onExperimentViewed:(a,o)=>c(structuredClone(a),structuredClone(o))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,d)}function Ir(e,t,u,r=re){return yn(Re(e,r),t,u)}function yn(e,t,u){let r=[],i=[],p=[],c=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(d){let a=r.findIndex(y=>y.next.attributeName===d.attributeName&&y.next.attributeValue===d.attributeValue),o=d.attributeName+"||"+d.attributeValue,g={expected:u.sticky[o]??null,next:d};a<0?r.push(g):r[a]=g},onExperimentViewed(d,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&i.push(D.parse({key:d.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(d,a){p.push(D.parse({feature:d,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:c.port,...c.value===void 0?{}:{value:c.value},sticky:r,exposures:i,features:p}}function vn(e,t,u,r=re){let i=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),c=structuredClone(u.variables),d=structuredClone(i.sticky),a=[],o=u.nodeId,g=u.visit,y=!1,v,I=O=>gn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),b=O=>(v??=Re(e,r),yn(v,O,{attributes:Je({declarations:t.variables,attributes:i.attributes,parameters:u.parameters,answers:u.answers,results:c,savedGroups:{}}),sticky:d}));for(let O=0;O<he;O++){let s=p.get(o);if(!s||!we(s)||I(s))break;if(g>=t.execution.maxTransitions&&(g>t.execution.maxTransitions||s.type!=="end"&&s.type!=="output")){if(!a.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let m,x;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")m=b(s.id),s.type==="offering"&&(m.value={type:"offering_version",id:String(m.value)}),s.type==="condition"?x=m.port==="default"?s.default:s.cases[Number(m.port.slice(5))]?.target:s.type==="split"?x=m.port==="notParticipating"?s.notParticipating:s.routes[m.port]:(s.type==="feature"||s.type==="offering")&&(x=s.next);else if(m={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(x=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(m.value={type:"offering_version",id:s.configuration.versionId},x=s.next),s.type==="end"||s.type==="output"){let P=s.type==="end"?s.output:s.value;if(m=P?.type==="feature"?b(s.id):{...m,port:"value",value:P?.type==="literal"?P.value:P?.type==="variable"?Ue({source:"variable",key:P.key,...P.path?{path:P.path}:{}},{declarations:t.variables,answers:u.answers,results:c,parameters:u.parameters,attributes:i.attributes,savedGroups:{}}):null},P&&(m.value===void 0||!qe(t.outputSchema,m.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let N=[...a,{nodeId:o,result:m}];if(X({steps:N})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:o,result:m}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let P=s.type==="coupons"?s.couponIds.map(M=>({type:"reward",id:M})):s.type==="coupon"?{type:"reward",id:s.couponId}:m.value;if(P===void 0)throw r("INVALID_RESPONSE","Node output is missing");let k=G(s,{value:P});Ge(t.variables,s,k),Object.assign(c,k)}for(let P of m.sticky)d[`${P.next.attributeName}||${P.next.attributeValue}`]=structuredClone(P.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");o=x,g++}let _=p.get(o);return{steps:a,...!y&&_&&(!we(_)||I(_))?{boundary:{nodeId:o,visit:g}}:{}}}function In(e,t){let u=sn.safeParse(t);if(!u.success)throw new f("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new f("SCOPE_MISMATCH","Funnel scope changed");return r}var Se=(e,t)=>new f(e,t);function Fr(e){return xe(e,Se)}var zn=3,Jn=2e3;function $n(e){return e instanceof TypeError||e instanceof f&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Hn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===zn||!$n(u))throw u;await new Promise(r=>setTimeout(r,t*Jn))}}async function Fe(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new f("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new f("SCOPE_MISMATCH","Evaluation environment changed");let i=null,p;if(u)try{let c=await e.funnel(t.source.id,t.source.versionId);p=c.manifest.generation,i=Yn(e,t,c)}catch{i=null}return p??=e.snapshot?.generation??(await Hn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:i}}function Yn(e,t,u){let r=t.instruction;if(r?.type!=="evaluate_segment"||!u.growth||u.control.evaluationMode!=="local"||u.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:p,...c}=u.growth,d=ve({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:u.document,payload:J.parse(c)}),a=Qn(d,u.document,{...t,...r}),o=a.steps.at(-1),g=a.boundary??(o?.result.port==="value"?{nodeId:o.nodeId,visit:t.visit+a.steps.length-1}:null);return g?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:g.nodeId,visit:g.visit,terminal:!a.boundary}:null}function Qn(e,t,u){return vn(e,t,u,Se)}var hn=U.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new f("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),wn=n.strictObject({schemaVersion:n.literal(1),scope:V,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:hn.optional(),closeCommand:hn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),A=()=>new f("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),oe=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Z(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function bn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),i=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new f("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:wn.parse(a.entry)}}function c(a){let o=i.then(a);return i=o.catch(()=>{}),o}async function d(a){for(let o=0;o<4;o++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(oe(g.entry,y)){t=g.revision;return}let v=await e.write(g.revision,y);if(v!==null){if(!Number.isSafeInteger(v)||v<=g.revision)throw A();t=v;return}}throw A()}return{bind(a){let o=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==o)throw A();u=o},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let o=wn.parse(a),g=o.command;return!g||u!==null&&r(o)!==u?Promise.reject(A()):(u??=r(o),c(()=>d((y,v)=>{if(y&&!oe(r(y),r(o)))throw A();if(y&&o.processBindingIds){for(let[I,b]of Object.entries(o.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,I)&&y.processBindingIds[I]!==b)throw A();y={...y,processBindingIds:{...y.processBindingIds,...o.processBindingIds}}}if(!y){if(v!==t&&g.operation!=="close")throw A();return o}if(!y.command)return{...y,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&y.command.operation!=="close"){if(y.command.requestId===g.requestId||y.closeCommand&&!oe(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!oe(y.command,g))throw A();return y})))},observePurchase(a,o,g,y){return c(()=>d((v,I)=>{if(!v&&I!==t||v&&r(v)!==r({...a,schemaVersion:1}))throw A();if(v?.purchase&&v.purchase.generation>o.generation)return Z(v,y);if(v?.purchase&&v.purchase.generation===o.generation&&v.purchase.operationId!==o.operationId)throw A();return g?!v?.purchase||v.purchase.operationId!==o.operationId?Z(v,y):Z(v.command?{...v,purchase:void 0}:null,y):Z({schemaVersion:1,...a,...v,purchase:o},y)}))},settle(a){return c(()=>d(o=>Z(o,a)))}}}function jr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function ie(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,p)=>ie(i,t[p]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([i,p])=>Object.hasOwn(t,i)&&ie(p,Reflect.get(t,i)))}function xn(e,t){let u=t&&{...t},r=null,i=0,p=-1,c=0,d=new AbortController;function a(){c++,d.abort(new f("IDENTITY_CHANGED","Run identity changed")),d=new AbortController}let o=!1,g,y=0,v=new Set;return{get scope(){return u},bindScope(I){if(u&&(u.projectId!==I.projectId||u.environment!==I.environment))throw new f("SCOPE_MISMATCH","Run scope changed");u??={...I}},get view(){return r},get currentView(){return p===c?r:null},get viewAgeMs(){return r&&p===c?performance.now()-i:void 0},get generation(){return c},get signal(){return d.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(I,b="Run identity changed during the request"){if(I!==c||o)throw new f("IDENTITY_CHANGED",b)},assertRun(I){if(r&&(I.id!==r.id||I.source.type!==r.source.type||I.source.id!==r.source.id||I.source.versionId!==r.source.versionId||I.locale!==r.locale||!ie(I.parameters,r.parameters)))throw new f("INVALID_RESPONSE","Run version changed");if(e&&I.source.id!==e)throw new f("INVALID_RESPONSE","Run belongs to another Funnel")},publish(I,b,_,O,s){if(!(I.operation==="review"&&r&&r!==_&&b.run.revision<=r.revision)&&!(r&&b.run.revision===r.revision&&O!==void 0&&O<y)&&(I.operation==="review"&&!b.run.stopped&&["running","waiting"].includes(b.run.status)&&r&&p===c&&b.run.nodeId===r.nodeId&&b.run.visit===r.visit&&b.run.revision===r.revision&&(b.run.screen=r.screen,(r.paywall?.quote?.operationId===b.review?.activeOperationId||!r.paywall?.quote&&b.review?.activeOperationId===null)&&(b.run.paywall=r.paywall)),!(r?.paywall&&b.run.paywall&&r.paywall.receiptId===b.run.paywall.receiptId&&(b.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||b.run.revision>=r.revision)r=b.run,i=performance.now(),p=c;else if(!s)return;if(r&&p===c)for(let m of v)try{m(structuredClone(r))}catch{}}},identify(I){if(o)throw new f("IDENTITY_CHANGED","Controller was reset");if(!W.test(I))throw new f("INVALID_TOKEN","Customer credential required");a(),g=I},subscribe(I){return v.add(I),()=>v.delete(I)},reset(){o||(o=!0,a(),g=void 0,r=null,v.clear())}}}var Ee=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function zr(e,t,u="A server API key is required"){if(typeof window<"u")throw new f("SERVER_ONLY",t);if(!Ee.test(e))throw new f("INVALID_TOKEN",u)}function Jr(e){let t=ne(e);return t.identify(e.apiKey),t}function Rn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&["apple","google"].includes(t.provider)?"native":t?.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new f("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function j(e){let{customerToken:t,...u}=e;return u}var Zn=e=>!(e instanceof f&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof f)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Sn({journal:e,state:t,call:u,processIdentity:r}){let i=null,p=null,c=!1,d={command:null,close:null},a=new Set,o,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new f("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(x=>x&&!Object.hasOwn(s.processBindingIds??{},x.requestId)))throw new f("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new f("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=s.purchase,c=s.closed===!0,!s.command)return;let m=s.command;i=m.operation==="close"?null:m,p=m.operation==="close"?m:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(c=!0);for(let x of[i,p])x&&a.add(x.requestId)}):Promise.resolve();y.catch(()=>{});async function v(s){e&&await y;let m=t.generation;if(e){if(!t.view||!t.scope)throw new f("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:j(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(m!==t.generation||i!==s&&p!==s)throw new f("IDENTITY_CHANGED","Run changed before command dispatch");let x=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(N){throw m===t.generation&&(i===s||p===s)&&!x&&!Zn(N)&&(e&&await e.settle(s.requestId),m===t.generation&&O(s)),N}}function I(s){let m=U.parse(s);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new f("INVALID_REQUEST","Mutation required");if(c&&m.operation!=="close"){if(i?.requestId===m.requestId)return _(m.requestId);throw new f("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(m.operation==="close"){if(i?.requestId===m.requestId)throw new f("INVALID_REQUEST","Close requires its own request identity");if(c=!0,p&&JSON.stringify(j(p))!==JSON.stringify(j(m)))throw new f("COMMAND_PENDING","Retry the original Close");return p??=m,d.close?d.close:b(p,"close")}if(i){if(JSON.stringify(j(i))!==JSON.stringify(j(m)))throw new f("COMMAND_PENDING","Retry the original command before sending another");if(d.command)return d.command}else i=m;return b(i,"command")}function b(s,m){let x=v(s);d[m]=x;let N=()=>{d[m]===x&&(d[m]=null)};return x.then(N,N),x}function _(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||i!==s&&p!==s?!1:(i===s&&(i=null),p===s&&(p=null),a.delete(s.requestId),!i&&!p&&(g=null),!0)}return{ready:y,get pending(){return i},get closing(){return p},get closeRequested(){return c},get inFlight(){return d.command},get closeFlight(){return d.close},get purchase(){return o},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new f("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,m,x,N){let P=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,k=P&&m.settlement?.state==="settled"&&m.run.pendingRequest?.requestId!==P&&(s.operation==="get"||!c||s.operation==="close"||!["running","waiting"].includes(m.run.status))?P:void 0,M=i?.requestId===k?i:p?.requestId===k?p:void 0;e?.bind({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId});let l=m.run.paywall,h=l??m.purchase,E=h?.operation,F=m.settlement&&(!l||l.purchaseRequestId===m.settlement.requestId)&&(!o||o.operationId===m.settlement.operationId)?m.settlement:void 0,R=E?.operationId??h?.quote?.operationId??F?.operationId,S=h?.receiptId??F?.receiptId,w=l?.selectionGeneration??o?.generation??0;if(e&&R&&S&&s.operation!=="review"&&(!t.view||m.run.revision>=t.view.revision)&&(N===void 0||N>=t.readSequence)&&(!o||w>=o.generation)){let C={receiptId:S,operationId:R,generation:w},T=on(E,h?.canReselect===!0);await e.observePurchase({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId},C,T,k),t.assertCurrent(x),(!o||C.generation>=o.generation)&&(N===void 0||N>=t.readSequence)&&(T?o?.operationId===C.operationId&&(o=void 0):o=C)}else e&&k&&await e.settle(k);return t.assertCurrent(x),k?O(M):!1},stop(){c=!0},submit:I,settle:_,reset(){c=!0,i=null,p=null,o=void 0,g=null,d.close=null,a.clear(),d.command=null}}}function Wn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new f("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new f("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Ee.test(e.serverKey)))throw new f("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new f("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=ne({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),i=xn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(b),c=null,d=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?an(e):void 0),a=d&&bn(d),o=Sn({journal:a,state:i,call:_,processIdentity:e.process}),g=0,y=new Map;function v(){g++,y.clear(),t=void 0}async function I(l){let h=l.operation==="resume"?o.pending?.operation==="resume"?null:o.pending:l;if(u&&l.operation==="resume"&&!h&&l.requestId!==e.customerRun?.startRequestId)throw new f("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(h?.operation==="submit"&&h.input.type==="paywall_confirm"){let C=i.view?.paywall;Rn(u,C?.quote?.operationId===h.input.operationId?C.quote:void 0)}if(e.process)return e.process.request(l);let E=i.generation;i.assertCurrent(E);let F=performance.now()+(e.timeoutMs??35e3),R=i.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let C=i.signal,T,K=()=>{},Fn=new Promise((Xn,Ce)=>{K=()=>Ce(C.reason),C.addEventListener("abort",K,{once:!0}),T=setTimeout(()=>Ce(new f("TIMEOUT","Longplay request timed out")),Math.max(1,F-performance.now()))});try{R=await Promise.race([Promise.resolve().then(()=>(i.assertCurrent(E),e.session.access())),Fn])}finally{clearTimeout(T),C.removeEventListener("abort",K)}}i.assertCurrent(E);let S={...l,...R?{customerToken:R}:{}},w=l.operation==="page_experiments"?ye.parse(S):U.parse(S);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!R)throw new f("IDENTITY_CHANGED","Original recovery Customer changed");let C={...w};return"customerToken"in C&&delete C.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:C},R,{timeoutMs:Math.max(1,F-performance.now())})}return r.requestWithCredential("funnels",w,e.runToken,{headers:e.serverKey&&!R?{[ln]:e.serverKey}:void 0,timeoutMs:Math.max(1,F-performance.now())})}function b(){v(),p?.(),i.reset(),o.reset(),c=null,r.dispose()}async function _(l,h){let E=t;t=void 0;let F=i.generation,R=()=>i.assertCurrent(F);a&&await o.ready,R();let S=i.view,w=In(e,E!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?E:await I(l));if(l.operation==="review"&&!w.review)throw new f("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&w.run.id!==e.customerRun.runId)throw new f("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&w.purchase&&(w.purchase.receiptId!==l.purchase.receiptId||(w.purchase.operation?.operationId??w.purchase.quote?.operationId)!==l.purchase.operationId))throw new f("INVALID_RESPONSE","The requested original purchase changed");if(R(),w.runToken&&w.runToken!==e.runToken)throw new f("INVALID_RESPONSE","Run credential changed");let C=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(C&&w.settlement?.requestId!==C)throw new f("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(w),i.assertRun(w.run),i.bindScope(w.scope);let T=await o.observe(l,w,F,h);return(!i.view||w.run.revision>=i.view.revision)&&(h===void 0||h>=i.readSequence)&&(await e.onAcceptedResponse?.(w),R()),!w.run.stopped&&["running","waiting"].includes(w.run.status)&&l.operation==="get"&&l.settlementRequestId||(R(),["running","waiting"].includes(w.run.status)||o.stop(),i.publish(l,w,S,h,T)),w}function O(l){let h=i.generation;v();let E=l(),F=()=>{i.generation===h&&v()};return E.then(F,F),E}let s=l=>O(()=>o.submit(l)),m=null,x=new WeakMap;function N(l){let h=x.get(l);if(h)return h;let E=k(l);return x.set(l,E),E}let P=!1;async function k(l){let h=await l;if(h.run.instruction?.type!=="evaluate_segment")return h;if(m)return m;P=!0;let E=i.generation,F=(async()=>{for(let R=0;R<32&&h.run.instruction?.type==="evaluate_segment";R++){if(o.pending||o.closeRequested)return h;let S=h.run;if(h.run.instruction?.type==="evaluate_segment"){let{advance:C}=await Fe(e.configuration,S,{predict:!1});if(E!==i.generation)throw new f("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return h;if(i.view&&(i.view.revision!==S.revision||i.view.visit!==S.visit||i.view.nodeId!==S.nodeId))return _({operation:"get"});let T=!0;Fe(e.configuration,S).then(({prediction:K})=>{T&&E===i.generation&&!o.closeRequested&&i.view?.id===S.id&&!i.view.stopped&&i.view.nodeId===S.nodeId&&i.view.visit===S.visit&&i.view.revision===S.revision&&(c=K)}).catch(()=>{});try{h=await s({operation:"commit_segment",requestId:cn(S.id,S.visit,`segment:${S.revision}`),nodeId:S.nodeId,visit:S.visit,revision:S.revision,...C})}finally{T=!1,c=null}}}return h})();m=F;try{return await F}finally{m===F&&(m=null)}}let M={get configuration(){return P?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=i.currentView;return l?structuredClone(l):null},get viewAgeMs(){return i.viewAgeMs},get pendingCommand(){let l=o.closing??o.pending;return l?structuredClone(j(l)):null},get pendingCommands(){return[o.pending,o.closing].filter(l=>l!==null).map(l=>structuredClone(j(l)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=i.view;return c&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===c.runId&&l.nodeId===c.from.nodeId&&l.visit===c.from.visit&&l.revision===c.from.revision&&!o.closeRequested?structuredClone(c):null},settle:(...l)=>O(()=>o.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return rn(e,l)},async pageExperiments(l,h=[]){let E=i.generation;i.assertCurrent(E);let F=i.view?.id;if(!F)throw new f("INVALID_REQUEST","Read the Run before its page experiments");let R=pn.parse(await I(ye.parse({operation:"page_experiments",release:l,usedReceiptIds:h})));if(i.assertCurrent(E),R.runId!==F||R.scope.projectId!==i.scope?.projectId||R.scope.environment!==i.scope?.environment)throw new f("SCOPE_MISMATCH","Page experiment Run changed");return R},review(l){return _({operation:"review",...l?{receiptId:l}:{}},i.nextRead())},async get(l,h){let E=i.generation;l=l&&structuredClone(l),h=h&&{...h},a&&await o.ready,i.assertCurrent(E),h??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let F=JSON.stringify([i.generation,g,l??null,h??null]),R=y.get(F);if(R)return R.then(T=>structuredClone(T));let S=i.nextRead(),w=N(_({operation:"get",...l?{data:l}:{},...h?{purchase:h}:{}},S));y.set(F,w);let C=()=>{y.get(F)===w&&y.delete(F)};return w.then(C,C),w.then(T=>structuredClone(T))},resume(l=i.view?.pendingRequest?.requestId){return l?o.closeRequested?M.settle(l):o.pending?.requestId===l?N(s(o.pending)):N(s({operation:"resume",requestId:l})):Promise.reject(new f("INVALID_REQUEST","No interrupted command is available"))},submit(l){return N(s(l))},retry(){return o.closeFlight?o.closeFlight:o.closing?s(o.closing):o.closeRequested&&o.pending?M.settle(o.pending.requestId):o.inFlight?N(o.inFlight):o.pending?N(s(o.pending)):Promise.reject(new f("INVALID_REQUEST","No command is pending"))},identify(l){let h=i.customerToken?void 0:t;v(),i.identify(l),t=h,c=null,r.reset()},get identitySignal(){return i.signal},subscribe:i.subscribe,reset:b};return M}function go(e,t){return Wn({...e,runToken:"",initialResponse:t})}export{cn as a,un as b,Pn as c,me as d,An as e,sn as f,Vn as g,Mt as h,qt as i,Gt as j,ye as k,pn as l,te as m,Ln as n,Wt as o,vr as p,Ir as q,In as r,Se as s,Fr as t,Qn as u,wn as v,Z as w,an as x,En as y,jr as z,ie as A,Ee as B,zr as C,Jr as D,Rn as E,Wn as F,go as G};
1
+ import{e as rn}from"./chunk-PKY55SBA.js";import{h as ue,i as se,r as nn,s as pe}from"./chunk-UWAZDSWO.js";import{c as Be,d as Ke,e as J,l as en}from"./chunk-TNN4S6VO.js";import{$ as U,D as Ye,R as Qe,W as Ze,X as We,Y as $,Z as Xe,_ as de,a as q,b as je,c as Me,d as qe,e as G,f as Ge,g as Ue,i as X,w as ee,x as ze,z as Je}from"./chunk-2JTMXZ5M.js";import{b as on}from"./chunk-KAXKYBSI.js";import{b as ne}from"./chunk-YBX2LLRG.js";import{a as W}from"./chunk-TLGKBSXC.js";import{D as Te,L as ae,U as D,V as De,W as Le,ja as $e,ka as le,la as He,ma as ce,t as Oe,z as Ae}from"./chunk-4WBIACS2.js";import{a as f}from"./chunk-7EPE2PUN.js";import{h as V}from"./chunk-VC2H3LFP.js";import{b as tn}from"./chunk-5X6WAPH3.js";import{b as n}from"./chunk-7GD2UTBU.js";import{c as _e,d as ke,e as Ve,f as z}from"./chunk-O4KXODTJ.js";import{a as Pe,b as Ne}from"./chunk-CILM5XMH.js";function an(e){return En({...e,namespace:"commands",identity:[e.runToken]})}function En(e){let t,u,r=()=>new f("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let d=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??tn).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",d));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,o=>o.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function p(d){try{let a=await i;return await u.request(a,{mode:"exclusive"},()=>d(a))}catch(a){throw a instanceof f?a:r()}}function c(d){let a=t.getItem(d);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let o=JSON.parse(a);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw r();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(c),write:(d,a)=>p(o=>{if(c(o).revision!==d)return null;if(!Number.isSafeInteger(d+1))throw r();let y=JSON.stringify({revision:d+1,entry:a});if(y.length>1048576)throw r();return t.setItem(o,y),d+1})}}var un=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var L=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Cn=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Pn=n.discriminatedUnion("type",[Ye,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:L.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:Ze,openIn:We}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:L})]),Nn={id:L,presentation:Te,outputs:n.array(L).max(250),inputs:ce,values:n.record(n.string(),D).optional(),offeringKey:q.optional(),capabilities:Oe,customerData:Ae,dataCursors:n.record(L,$e.nullable())},On=n.strictObject({...Nn,content:n.strictObject({type:n.literal("document"),document:ae})}),me=n.strictObject({id:n.uuid(),source:un,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:L,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Cn,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:le,parameters:He,variables:n.record(n.string(),D),output:D.nullable(),screen:On.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([nn,pe]),quote:ue.nullable(),operation:se.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Pn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),An=n.strictObject({scope:V,run:me,settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),operationId:n.uuid().nullable(),receiptId:n.uuid().nullable().optional()}).optional(),purchase:n.strictObject({receiptId:n.uuid(),quote:ue.nullable(),operation:se.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:L,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:L,visit:n.number().int().nonnegative(),document:ae,answers:le,inputs:ce,values:n.record(n.string(),D).optional()}).nullable(),coupons:n.array(n.strictObject({grantId:n.uuid(),status:n.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:n.string().nullable()})).max(100),purchases:n.array(n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),status:n.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:n.uuid().optional()}),sn=An.extend({run:me.extend({paywall:me.shape.paywall.unwrap().extend({resolution:pe}).nullable()})});var ln="X-Indiana-Server-Key";var H=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function fe(e,t,u){let r={},i,p,c,d="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let o=e.cases.findIndex(g=>ke(t.attributes??{},g.condition,t.savedGroups??{}));d=o<0?"default":`case:${o}`,a=o<0?e.default:e.cases[o].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new H("Required GB Feature is unavailable");i=z(e.featureKey,t),c=i.value,Object.assign(r,G(e,{value:c})),a=e.next;break;case"split":{let o=u[e.experimentId];if(!o)throw new H("Required GB Experiment is unavailable");if(p=Ve(o,t),c=p.value,d=p.inExperiment&&!p.passthrough&&typeof c=="string"?c:"notParticipating",a=d==="notParticipating"?e.notParticipating:e.routes[d],!a)throw new H("Experiment Variation has no published route");break}case"offering":{let o=e.configuration.source==="fixed"?e.configuration.versionId:z(e.configuration.featureKey,t).value;c={type:"offering_version",id:n.uuid().parse(o)},Object.assign(r,G(e,{value:c})),a=e.next;break}case"coupon":case"coupons":c=e.type==="coupons"?e.couponIds.map(o=>({type:"reward",id:o})):{type:"reward",id:e.couponId},Object.assign(r,G(e,{value:c})),a=e.next;break}return{port:d,target:a,projections:r,...c===void 0?{}:{value:c},...i?{feature:i}:{},...p?{experiment:p}:{}}}function cn(e,t,u){n.uuid().parse(e),n.number().int().nonnegative().parse(t);let r=Pe(Ne(new TextEncoder().encode(JSON.stringify([e,t,u])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var Tn=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),_n=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(Tn).max(200).default([]),iam:ze.optional(),renderGuard:ee.optional()}),ge=_n.omit({variation:!0,description:!0,iam:!0}),kn=Be.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20)}),dn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(kn).max(100),savedGroups:Ke});var Y=n.string().regex(/^[a-f0-9]{64}$/),jt=n.strictObject({iam:Y,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),Vn=n.strictObject({release:Y,render:ee,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),Mt=n.strictObject({scope:V.extend({environmentId:n.uuid()}),release:Y,validatedAt:n.iso.datetime({offset:!0}),validUntil:n.iso.datetime({offset:!0}),entries:n.array(n.strictObject({id:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),event:n.enum(["screen_enter","button_click"]),target:Vn})).max(4e3)}),qt=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:Y,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Gt=n.strictObject({scope:V,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Ut=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Dn=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),ye=n.strictObject({operation:n.literal("page_experiments"),release:Y,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(W).optional()}),pn=n.strictObject({scope:V,runId:n.uuid(),assignments:n.array(Dn.extend({receiptId:n.uuid()})).max(100),payload:dn});var B=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fn=n.strictObject({entry:B,nodes:n.array(n.strictObject({id:B,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),B),writes:n.record(q,q),resources:n.strictObject({screenId:B.optional(),paywallVersionId:n.uuid().optional(),couponId:n.uuid().optional(),couponIds:n.array(n.uuid()).max(20).optional(),experimentId:n.uuid().optional(),featureKey:n.string().optional(),offeringVersionId:n.uuid().optional()})})).min(1).max(500)}),mn={scope:V,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:fn},te=n.discriminatedUnion("evaluationMode",[n.strictObject({...mn,evaluationMode:n.literal("local"),growth:J,conditions:n.record(B,n.array(n.strictObject({condition:Le,port:n.string()})))}),n.strictObject({...mn,evaluationMode:n.literal("remote")})]),Ln=te.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(q,Me),outputSchema:je,terminals:n.record(B,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Qe.nullable()}))})});function jn(e){return fn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let p=e.screens.find(c=>c.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,c)=>{u[`case:${c}`]=p.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let p of["success","cancel","unavailable","failure"])u[p]=t[p];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ve(e){let t=de.parse(e.document),u=e.evaluationMode==="local"?J.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:u?.expiresAt??null,topology:jn(t)};return te.parse(e.evaluationMode==="remote"?r:{...r,growth:en(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((p,c)=>({condition:p.condition,port:`case:${c}`}))]))})}function Wt(e){let t=ve(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=de.parse(e.document);return Ln.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var he=32,Mn=522240;function we(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var qn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),Ie=n.record(n.string(),D),Gn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:$.shape.schemaVersion,kind:$.shape.kind,selector:$.shape.selector,contract:$.shape.contract}),context:Ie,removed:n.array(n.string()).max(100),attributes:Ie,removedAttributes:n.array(n.string()).max(100),result:Xe,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),or=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:qn,context:Ie,steps:n.array(Gn).min(1).max(he)}).refine(e=>X(e)<=Mn,"Segment exceeds its byte budget");var Un=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Q(e){return Array.isArray(e)?e.some(Q):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Q(u):!Un.test(t))}function gn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(d=>d.id===t.screenId&&d.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(d=>Q(d.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(d=>d.id===t.screenId):null]);for(let[d,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${d}`)||p.includes(JSON.stringify(d))))return"customer_required";if(t.type==="split"){let d=u.experiments?.[t.experimentId];if((d?.hashAttribute??"id")!=="funnelParticipantId"||Q(d?.condition)||d?.parentConditions?.length)return"customer_experiment_required"}let c=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return c&&u.features?.[c]?.rules?.some(d=>(d.hashAttribute??"id")!=="funnelParticipantId"||Q(d.condition)||d.parentConditions?.length)?"customer_experiment_required":null}var be=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},re=(e,t)=>new be(e,t),Bn=e=>({experiments:e.experiments,features:e.features});function xe(e,t=re){let u=new Map(e.topology.nodes.map(c=>[c.id,c])),r=_e(e.growth.savedGroups),i=Bn(e.growth);function p(c,d){if(!Object.hasOwn(e.growth.features,c))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return z(c,d).value}return{nodes:u,savedGroups:r,features:i.features,feature:p,evaluate(c,d){let a=u.get(c);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let o,g;if(a.type==="condition"){let v=e.conditions[a.id];if(!v)throw t("INVALID_RESPONSE","Local condition rules are unavailable");o=fe({id:a.id,name:a.id,type:"condition",cases:v.map(I=>({condition:I.condition,target:a.outputs[I.port]})),default:a.outputs.default},d,i.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,d),o="next"}else if(a.type==="split"){if(!(a.resources.experimentId?e.growth.experiments[a.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let I=fe({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},d,i.experiments);g=I.value,o=I.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,d),o=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[o]??(o==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:c,port:o,target:y,...g===void 0?{}:{value:g}}}}}function vr(e,t,u,r=re){return Re(e,r)(t,u)}function Re(e,t){let u=te.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let p=xe(u,t);return(c,d)=>(i(),Kn(p,c,d))}function Kn(e,t,u){let r=De.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:p,onExperimentViewed:c}=u,d={attributes:r,...i?{saveStickyBucketAssignmentDoc:a=>i(structuredClone(a))}:{},...p?{onFeatureUsage:(a,o)=>p(a,structuredClone(o))}:{},...c?{onExperimentViewed:(a,o)=>c(structuredClone(a),structuredClone(o))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,d)}function Ir(e,t,u,r=re){return yn(Re(e,r),t,u)}function yn(e,t,u){let r=[],i=[],p=[],c=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(d){let a=r.findIndex(y=>y.next.attributeName===d.attributeName&&y.next.attributeValue===d.attributeValue),o=d.attributeName+"||"+d.attributeValue,g={expected:u.sticky[o]??null,next:d};a<0?r.push(g):r[a]=g},onExperimentViewed(d,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&i.push(D.parse({key:d.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(d,a){p.push(D.parse({feature:d,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:c.port,...c.value===void 0?{}:{value:c.value},sticky:r,exposures:i,features:p}}function vn(e,t,u,r=re){let i=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),c=structuredClone(u.variables),d=structuredClone(i.sticky),a=[],o=u.nodeId,g=u.visit,y=!1,v,I=O=>gn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),b=O=>(v??=Re(e,r),yn(v,O,{attributes:Je({declarations:t.variables,attributes:i.attributes,parameters:u.parameters,answers:u.answers,results:c,savedGroups:{}}),sticky:d}));for(let O=0;O<he;O++){let s=p.get(o);if(!s||!we(s)||I(s))break;if(g>=t.execution.maxTransitions&&(g>t.execution.maxTransitions||s.type!=="end"&&s.type!=="output")){if(!a.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let m,x;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")m=b(s.id),s.type==="offering"&&(m.value={type:"offering_version",id:String(m.value)}),s.type==="condition"?x=m.port==="default"?s.default:s.cases[Number(m.port.slice(5))]?.target:s.type==="split"?x=m.port==="notParticipating"?s.notParticipating:s.routes[m.port]:(s.type==="feature"||s.type==="offering")&&(x=s.next);else if(m={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(x=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(m.value={type:"offering_version",id:s.configuration.versionId},x=s.next),s.type==="end"||s.type==="output"){let P=s.type==="end"?s.output:s.value;if(m=P?.type==="feature"?b(s.id):{...m,port:"value",value:P?.type==="literal"?P.value:P?.type==="variable"?Ue({source:"variable",key:P.key,...P.path?{path:P.path}:{}},{declarations:t.variables,answers:u.answers,results:c,parameters:u.parameters,attributes:i.attributes,savedGroups:{}}):null},P&&(m.value===void 0||!qe(t.outputSchema,m.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let N=[...a,{nodeId:o,result:m}];if(X({steps:N})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:o,result:m}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let P=s.type==="coupons"?s.couponIds.map(M=>({type:"reward",id:M})):s.type==="coupon"?{type:"reward",id:s.couponId}:m.value;if(P===void 0)throw r("INVALID_RESPONSE","Node output is missing");let k=G(s,{value:P});Ge(t.variables,s,k),Object.assign(c,k)}for(let P of m.sticky)d[`${P.next.attributeName}||${P.next.attributeValue}`]=structuredClone(P.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");o=x,g++}let _=p.get(o);return{steps:a,...!y&&_&&(!we(_)||I(_))?{boundary:{nodeId:o,visit:g}}:{}}}function In(e,t){let u=sn.safeParse(t);if(!u.success)throw new f("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new f("SCOPE_MISMATCH","Funnel scope changed");return r}var Se=(e,t)=>new f(e,t);function Fr(e){return xe(e,Se)}var zn=3,Jn=2e3;function $n(e){return e instanceof TypeError||e instanceof f&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Hn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===zn||!$n(u))throw u;await new Promise(r=>setTimeout(r,t*Jn))}}async function Fe(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new f("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new f("SCOPE_MISMATCH","Evaluation environment changed");let i=null,p;if(u)try{let c=await e.funnel(t.source.id,t.source.versionId);p=c.manifest.generation,i=Yn(e,t,c)}catch{i=null}return p??=e.snapshot?.generation??(await Hn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:i}}function Yn(e,t,u){let r=t.instruction;if(r?.type!=="evaluate_segment"||!u.growth||u.control.evaluationMode!=="local"||u.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:p,...c}=u.growth,d=ve({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:u.document,payload:J.parse(c)}),a=Qn(d,u.document,{...t,...r}),o=a.steps.at(-1),g=a.boundary??(o?.result.port==="value"?{nodeId:o.nodeId,visit:t.visit+a.steps.length-1}:null);return g?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:g.nodeId,visit:g.visit,terminal:!a.boundary}:null}function Qn(e,t,u){return vn(e,t,u,Se)}var hn=U.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new f("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),wn=n.strictObject({schemaVersion:n.literal(1),scope:V,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:hn.optional(),closeCommand:hn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),A=()=>new f("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),oe=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Z(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function bn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),i=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new f("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:wn.parse(a.entry)}}function c(a){let o=i.then(a);return i=o.catch(()=>{}),o}async function d(a){for(let o=0;o<4;o++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(oe(g.entry,y)){t=g.revision;return}let v=await e.write(g.revision,y);if(v!==null){if(!Number.isSafeInteger(v)||v<=g.revision)throw A();t=v;return}}throw A()}return{bind(a){let o=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==o)throw A();u=o},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let o=wn.parse(a),g=o.command;return!g||u!==null&&r(o)!==u?Promise.reject(A()):(u??=r(o),c(()=>d((y,v)=>{if(y&&!oe(r(y),r(o)))throw A();if(y&&o.processBindingIds){for(let[I,b]of Object.entries(o.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,I)&&y.processBindingIds[I]!==b)throw A();y={...y,processBindingIds:{...y.processBindingIds,...o.processBindingIds}}}if(!y){if(v!==t&&g.operation!=="close")throw A();return o}if(!y.command)return{...y,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&y.command.operation!=="close"){if(y.command.requestId===g.requestId||y.closeCommand&&!oe(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!oe(y.command,g))throw A();return y})))},observePurchase(a,o,g,y){return c(()=>d((v,I)=>{if(!v&&I!==t||v&&r(v)!==r({...a,schemaVersion:1}))throw A();if(v?.purchase&&v.purchase.generation>o.generation)return Z(v,y);if(v?.purchase&&v.purchase.generation===o.generation&&v.purchase.operationId!==o.operationId)throw A();return g?!v?.purchase||v.purchase.operationId!==o.operationId?Z(v,y):Z(v.command?{...v,purchase:void 0}:null,y):Z({schemaVersion:1,...a,...v,purchase:o},y)}))},settle(a){return c(()=>d(o=>Z(o,a)))}}}function jr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function ie(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,p)=>ie(i,t[p]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([i,p])=>Object.hasOwn(t,i)&&ie(p,Reflect.get(t,i)))}function xn(e,t){let u=t&&{...t},r=null,i=0,p=-1,c=0,d=new AbortController;function a(){c++,d.abort(new f("IDENTITY_CHANGED","Run identity changed")),d=new AbortController}let o=!1,g,y=0,v=new Set;return{get scope(){return u},bindScope(I){if(u&&(u.projectId!==I.projectId||u.environment!==I.environment))throw new f("SCOPE_MISMATCH","Run scope changed");u??={...I}},get view(){return r},get currentView(){return p===c?r:null},get viewAgeMs(){return r&&p===c?performance.now()-i:void 0},get generation(){return c},get signal(){return d.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(I,b="Run identity changed during the request"){if(I!==c||o)throw new f("IDENTITY_CHANGED",b)},assertRun(I){if(r&&(I.id!==r.id||I.source.type!==r.source.type||I.source.id!==r.source.id||I.source.versionId!==r.source.versionId||I.locale!==r.locale||!ie(I.parameters,r.parameters)))throw new f("INVALID_RESPONSE","Run version changed");if(e&&I.source.id!==e)throw new f("INVALID_RESPONSE","Run belongs to another Funnel")},publish(I,b,_,O,s){if(!(I.operation==="review"&&r&&r!==_&&b.run.revision<=r.revision)&&!(r&&b.run.revision===r.revision&&O!==void 0&&O<y)&&(I.operation==="review"&&!b.run.stopped&&["running","waiting"].includes(b.run.status)&&r&&p===c&&b.run.nodeId===r.nodeId&&b.run.visit===r.visit&&b.run.revision===r.revision&&(b.run.screen=r.screen,(r.paywall?.quote?.operationId===b.review?.activeOperationId||!r.paywall?.quote&&b.review?.activeOperationId===null)&&(b.run.paywall=r.paywall)),!(r?.paywall&&b.run.paywall&&r.paywall.receiptId===b.run.paywall.receiptId&&(b.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||b.run.revision>=r.revision)r=b.run,i=performance.now(),p=c;else if(!s)return;if(r&&p===c)for(let m of v)try{m(structuredClone(r))}catch{}}},identify(I){if(o)throw new f("IDENTITY_CHANGED","Controller was reset");if(!W.test(I))throw new f("INVALID_TOKEN","Customer credential required");a(),g=I},subscribe(I){return v.add(I),()=>v.delete(I)},reset(){o||(o=!0,a(),g=void 0,r=null,v.clear())}}}var Ee=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function zr(e,t,u="A server API key is required"){if(typeof window<"u")throw new f("SERVER_ONLY",t);if(!Ee.test(e))throw new f("INVALID_TOKEN",u)}function Jr(e){let t=ne(e);return t.identify(e.apiKey),t}function Rn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&["apple","google"].includes(t.provider)?"native":t?.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new f("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function j(e){let{customerToken:t,...u}=e;return u}var Zn=e=>!(e instanceof f&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof f)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Sn({journal:e,state:t,call:u,processIdentity:r}){let i=null,p=null,c=!1,d={command:null,close:null},a=new Set,o,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new f("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(x=>x&&!Object.hasOwn(s.processBindingIds??{},x.requestId)))throw new f("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new f("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=s.purchase,c=s.closed===!0,!s.command)return;let m=s.command;i=m.operation==="close"?null:m,p=m.operation==="close"?m:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(c=!0);for(let x of[i,p])x&&a.add(x.requestId)}):Promise.resolve();y.catch(()=>{});async function v(s){e&&await y;let m=t.generation;if(e){if(!t.view||!t.scope)throw new f("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:j(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(m!==t.generation||i!==s&&p!==s)throw new f("IDENTITY_CHANGED","Run changed before command dispatch");let x=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(N){throw m===t.generation&&(i===s||p===s)&&!x&&!Zn(N)&&(e&&await e.settle(s.requestId),m===t.generation&&O(s)),N}}function I(s){let m=U.parse(s);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new f("INVALID_REQUEST","Mutation required");if(c&&m.operation!=="close"){if(i?.requestId===m.requestId)return _(m.requestId);throw new f("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(m.operation==="close"){if(i?.requestId===m.requestId)throw new f("INVALID_REQUEST","Close requires its own request identity");if(c=!0,p&&JSON.stringify(j(p))!==JSON.stringify(j(m)))throw new f("COMMAND_PENDING","Retry the original Close");return p??=m,d.close?d.close:b(p,"close")}if(i){if(JSON.stringify(j(i))!==JSON.stringify(j(m)))throw new f("COMMAND_PENDING","Retry the original command before sending another");if(d.command)return d.command}else i=m;return b(i,"command")}function b(s,m){let x=v(s);d[m]=x;let N=()=>{d[m]===x&&(d[m]=null)};return x.then(N,N),x}function _(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||i!==s&&p!==s?!1:(i===s&&(i=null),p===s&&(p=null),a.delete(s.requestId),!i&&!p&&(g=null),!0)}return{ready:y,get pending(){return i},get closing(){return p},get closeRequested(){return c},get inFlight(){return d.command},get closeFlight(){return d.close},get purchase(){return o},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new f("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,m,x,N){let P=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,k=P&&m.settlement?.state==="settled"&&m.run.pendingRequest?.requestId!==P&&(s.operation==="get"||!c||s.operation==="close"||!["running","waiting"].includes(m.run.status))?P:void 0,M=i?.requestId===k?i:p?.requestId===k?p:void 0;e?.bind({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId});let l=m.run.paywall,h=l??m.purchase,E=h?.operation,F=m.settlement&&(!l||l.purchaseRequestId===m.settlement.requestId)&&(!o||o.operationId===m.settlement.operationId)?m.settlement:void 0,R=E?.operationId??h?.quote?.operationId??F?.operationId,S=h?.receiptId??F?.receiptId,w=l?.selectionGeneration??o?.generation??0;if(e&&R&&S&&s.operation!=="review"&&(!t.view||m.run.revision>=t.view.revision)&&(N===void 0||N>=t.readSequence)&&(!o||w>=o.generation)){let C={receiptId:S,operationId:R,generation:w},T=on(E,h?.canReselect===!0);await e.observePurchase({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId},C,T,k),t.assertCurrent(x),(!o||C.generation>=o.generation)&&(N===void 0||N>=t.readSequence)&&(T?o?.operationId===C.operationId&&(o=void 0):o=C)}else e&&k&&await e.settle(k);return t.assertCurrent(x),k?O(M):!1},stop(){c=!0},submit:I,settle:_,reset(){c=!0,i=null,p=null,o=void 0,g=null,d.close=null,a.clear(),d.command=null}}}function Wn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new f("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new f("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Ee.test(e.serverKey)))throw new f("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new f("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=ne({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),i=xn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(b),c=null,d=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?an(e):void 0),a=d&&bn(d),o=Sn({journal:a,state:i,call:_,processIdentity:e.process}),g=0,y=new Map;function v(){g++,y.clear(),t=void 0}async function I(l){let h=l.operation==="resume"?o.pending?.operation==="resume"?null:o.pending:l;if(u&&l.operation==="resume"&&!h&&l.requestId!==e.customerRun?.startRequestId)throw new f("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(h?.operation==="submit"&&h.input.type==="paywall_confirm"){let C=i.view?.paywall;Rn(u,C?.quote?.operationId===h.input.operationId?C.quote:void 0)}if(e.process)return e.process.request(l);let E=i.generation;i.assertCurrent(E);let F=performance.now()+(e.timeoutMs??35e3),R=i.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let C=i.signal,T,K=()=>{},Fn=new Promise((Xn,Ce)=>{K=()=>Ce(C.reason),C.addEventListener("abort",K,{once:!0}),T=setTimeout(()=>Ce(new f("TIMEOUT","The request timed out")),Math.max(1,F-performance.now()))});try{R=await Promise.race([Promise.resolve().then(()=>(i.assertCurrent(E),e.session.access())),Fn])}finally{clearTimeout(T),C.removeEventListener("abort",K)}}i.assertCurrent(E);let S={...l,...R?{customerToken:R}:{}},w=l.operation==="page_experiments"?ye.parse(S):U.parse(S);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!R)throw new f("IDENTITY_CHANGED","Original recovery Customer changed");let C={...w};return"customerToken"in C&&delete C.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:C},R,{timeoutMs:Math.max(1,F-performance.now())})}return r.requestWithCredential("funnels",w,e.runToken,{headers:e.serverKey&&!R?{[ln]:e.serverKey}:void 0,timeoutMs:Math.max(1,F-performance.now())})}function b(){v(),p?.(),i.reset(),o.reset(),c=null,r.dispose()}async function _(l,h){let E=t;t=void 0;let F=i.generation,R=()=>i.assertCurrent(F);a&&await o.ready,R();let S=i.view,w=In(e,E!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?E:await I(l));if(l.operation==="review"&&!w.review)throw new f("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&w.run.id!==e.customerRun.runId)throw new f("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&w.purchase&&(w.purchase.receiptId!==l.purchase.receiptId||(w.purchase.operation?.operationId??w.purchase.quote?.operationId)!==l.purchase.operationId))throw new f("INVALID_RESPONSE","The requested original purchase changed");if(R(),w.runToken&&w.runToken!==e.runToken)throw new f("INVALID_RESPONSE","Run credential changed");let C=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(C&&w.settlement?.requestId!==C)throw new f("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(w),i.assertRun(w.run),i.bindScope(w.scope);let T=await o.observe(l,w,F,h);return(!i.view||w.run.revision>=i.view.revision)&&(h===void 0||h>=i.readSequence)&&(await e.onAcceptedResponse?.(w),R()),!w.run.stopped&&["running","waiting"].includes(w.run.status)&&l.operation==="get"&&l.settlementRequestId||(R(),["running","waiting"].includes(w.run.status)||o.stop(),i.publish(l,w,S,h,T)),w}function O(l){let h=i.generation;v();let E=l(),F=()=>{i.generation===h&&v()};return E.then(F,F),E}let s=l=>O(()=>o.submit(l)),m=null,x=new WeakMap;function N(l){let h=x.get(l);if(h)return h;let E=k(l);return x.set(l,E),E}let P=!1;async function k(l){let h=await l;if(h.run.instruction?.type!=="evaluate_segment")return h;if(m)return m;P=!0;let E=i.generation,F=(async()=>{for(let R=0;R<32&&h.run.instruction?.type==="evaluate_segment";R++){if(o.pending||o.closeRequested)return h;let S=h.run;if(h.run.instruction?.type==="evaluate_segment"){let{advance:C}=await Fe(e.configuration,S,{predict:!1});if(E!==i.generation)throw new f("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return h;if(i.view&&(i.view.revision!==S.revision||i.view.visit!==S.visit||i.view.nodeId!==S.nodeId))return _({operation:"get"});let T=!0;Fe(e.configuration,S).then(({prediction:K})=>{T&&E===i.generation&&!o.closeRequested&&i.view?.id===S.id&&!i.view.stopped&&i.view.nodeId===S.nodeId&&i.view.visit===S.visit&&i.view.revision===S.revision&&(c=K)}).catch(()=>{});try{h=await s({operation:"commit_segment",requestId:cn(S.id,S.visit,`segment:${S.revision}`),nodeId:S.nodeId,visit:S.visit,revision:S.revision,...C})}finally{T=!1,c=null}}}return h})();m=F;try{return await F}finally{m===F&&(m=null)}}let M={get configuration(){return P?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=i.currentView;return l?structuredClone(l):null},get viewAgeMs(){return i.viewAgeMs},get pendingCommand(){let l=o.closing??o.pending;return l?structuredClone(j(l)):null},get pendingCommands(){return[o.pending,o.closing].filter(l=>l!==null).map(l=>structuredClone(j(l)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=i.view;return c&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===c.runId&&l.nodeId===c.from.nodeId&&l.visit===c.from.visit&&l.revision===c.from.revision&&!o.closeRequested?structuredClone(c):null},settle:(...l)=>O(()=>o.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return rn(e,l)},async pageExperiments(l,h=[]){let E=i.generation;i.assertCurrent(E);let F=i.view?.id;if(!F)throw new f("INVALID_REQUEST","Read the Run before its page experiments");let R=pn.parse(await I(ye.parse({operation:"page_experiments",release:l,usedReceiptIds:h})));if(i.assertCurrent(E),R.runId!==F||R.scope.projectId!==i.scope?.projectId||R.scope.environment!==i.scope?.environment)throw new f("SCOPE_MISMATCH","Page experiment Run changed");return R},review(l){return _({operation:"review",...l?{receiptId:l}:{}},i.nextRead())},async get(l,h){let E=i.generation;l=l&&structuredClone(l),h=h&&{...h},a&&await o.ready,i.assertCurrent(E),h??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let F=JSON.stringify([i.generation,g,l??null,h??null]),R=y.get(F);if(R)return R.then(T=>structuredClone(T));let S=i.nextRead(),w=N(_({operation:"get",...l?{data:l}:{},...h?{purchase:h}:{}},S));y.set(F,w);let C=()=>{y.get(F)===w&&y.delete(F)};return w.then(C,C),w.then(T=>structuredClone(T))},resume(l=i.view?.pendingRequest?.requestId){return l?o.closeRequested?M.settle(l):o.pending?.requestId===l?N(s(o.pending)):N(s({operation:"resume",requestId:l})):Promise.reject(new f("INVALID_REQUEST","No interrupted command is available"))},submit(l){return N(s(l))},retry(){return o.closeFlight?o.closeFlight:o.closing?s(o.closing):o.closeRequested&&o.pending?M.settle(o.pending.requestId):o.inFlight?N(o.inFlight):o.pending?N(s(o.pending)):Promise.reject(new f("INVALID_REQUEST","No command is pending"))},identify(l){let h=i.customerToken?void 0:t;v(),i.identify(l),t=h,c=null,r.reset()},get identitySignal(){return i.signal},subscribe:i.subscribe,reset:b};return M}function go(e,t){return Wn({...e,runToken:"",initialResponse:t})}export{cn as a,un as b,Pn as c,me as d,An as e,sn as f,Vn as g,Mt as h,qt as i,Gt as j,ye as k,pn as l,te as m,Ln as n,Wt as o,vr as p,Ir as q,In as r,Se as s,Fr as t,Qn as u,wn as v,Z as w,an as x,En as y,jr as z,ie as A,Ee as B,zr as C,Jr as D,Rn as E,Wn as F,go as G};
@@ -0,0 +1 @@
1
+ import{a as c}from"./chunk-7EPE2PUN.js";var u={none:0,sm:4,md:8,lg:14,full:9999},f={system:"system-ui,sans-serif",serif:"Georgia,serif",rounded:"ui-rounded,system-ui,sans-serif",mono:"ui-monospace,monospace"},g={primary:"#172033",background:"#FFFFFF",text:"#172033",radius:"md",font:"system"};function p(e){let[n,i,r]=[1,3,5].map(t=>{let o=Number.parseInt(e.slice(t,t+2),16)/255;return o<=.03928?o/12.92:((o+.055)/1.055)**2.4});return .2126*n+.7152*i+.0722*r}function y(e,n=!0){let i=p(e.primary),r=(i+.05)/.05>1.05/(i+.05)?"#111318":"#FFFFFF",t=`color-mix(in srgb, ${e.text} 22%, ${e.background})`,o=`${u[e.radius]}px`,s=`appearance:none;margin:0;min-height:44px;padding:10px 18px;border:0;border-radius:${o};font:inherit;font-size:15px;font-weight:600;line-height:1.25;cursor:pointer;touch-action:manipulation`;return{root:`width:100%;box-sizing:border-box;${n?`background:${e.background};`:""}color:${e.text};font:14px/1.5 ${f[e.font]}`,controls:"display:flex;gap:12px;padding:0 20px 12px;align-items:center;flex-wrap:wrap",pinned:`position:sticky;bottom:0;z-index:1;box-sizing:border-box;padding-top:12px;background:${e.background};border-top:1px solid ${t}`,bar:`display:flex;gap:8px;padding:12px 16px;align-items:center;flex-wrap:wrap;border-top:1px solid ${t}`,message:"flex:1 1 200px;min-width:0;margin:0;font-size:13px",status:"margin:0;font-size:13px;opacity:.72",alert:`flex:1 1 200px;min-width:0;margin:0;font-size:13px;font-weight:500;color:${p(e.background)>.4?"#B42318":"#FDA29B"}`,panel:`flex:1 0 100%;box-sizing:border-box;display:flex;flex-direction:column;gap:8px;padding:16px;border:1px solid ${t};border-radius:${o}`,summary:"margin:0;font-size:15px;font-weight:600",terms:"display:flex;flex-direction:column;gap:4px;font-size:13px;opacity:.72",actions:"display:flex;gap:8px;flex-wrap:wrap;margin-top:4px",primary:`${s};background:${e.primary};color:${r}`,secondary:`${s};background:transparent;color:${e.text};box-shadow:inset 0 0 0 1px ${t}`,link:`${s};background:transparent;color:${e.text};opacity:.72;font-weight:500`,stage:"display:flex;justify-content:center;padding:24px 20px",history:"display:flex;flex-direction:column;gap:12px;padding:20px",historyTitle:"margin:0;padding-inline-end:40px;font-size:17px;font-weight:600;line-height:1.3",historyNote:"margin:0;font-size:13px;opacity:.72",historyPages:"display:flex;gap:8px;flex-wrap:wrap;margin:0;padding:0;list-style:none",historyPage:`border:1px solid ${t};border-radius:${o};overflow:hidden`,historyRecords:`display:flex;flex-direction:column;gap:4px;margin:0;padding:12px 0 0;list-style:none;font-size:13px;border-top:1px solid ${t}`,focus:e.text}}function b(e){e.style.opacity=e.disabled?".55":"",e.style.cursor=e.disabled?"not-allowed":"pointer"}function h(e,n){e.addEventListener("focus",()=>{let i=!0;try{i=e.matches(":focus-visible")}catch{}i&&(e.style.outline=`2px solid ${n()}`,e.style.outlineOffset="2px")}),e.addEventListener("blur",()=>{e.style.outline="",e.style.outlineOffset=""})}var x={en:{network:"Connection problem. Check your network and try again.",timeout:"This is taking longer than expected. Try again.",other:"Something went wrong. Try again."},zh:{network:"\u7F51\u7EDC\u8FDE\u63A5\u5F02\u5E38\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u540E\u91CD\u8BD5\u3002",timeout:"\u54CD\u5E94\u65F6\u95F4\u8FC7\u957F\uFF0C\u8BF7\u91CD\u8BD5\u3002",other:"\u51FA\u4E86\u70B9\u95EE\u9898\uFF0C\u8BF7\u91CD\u8BD5\u3002"}};function k(e,n){let i=x[n?"zh":"en"],r=e instanceof c?e.code:void 0;return r==="NETWORK_ERROR"?i.network:r==="TIMEOUT"?i.timeout:i.other}function T(e){let n=!1,i,r,t=()=>{clearTimeout(i),i=void 0};function o(){if(t(),n)return;let a=e.document.visibilityState==="hidden"?e.hiddenDelay?.():e.delay();a!==void 0&&(i=setTimeout(()=>{s().catch(()=>{})},a))}function s(){if(n)return Promise.resolve();if(r)return r;t();let a=Promise.resolve().then(()=>n?void 0:e.run());r=a;let l=()=>{r===a&&(r=void 0),o()};return a.then(l,l),a}let d=()=>{e.document.visibilityState==="hidden"?o():s().catch(()=>{})};return e.document.addEventListener("visibilitychange",d),{schedule:o,refresh:s,destroy(){n=!0,t(),e.document.removeEventListener("visibilitychange",d)}}}function E(e,n,i){return new Promise(r=>{let t,o=()=>{clearTimeout(t),n.removeEventListener("visibilitychange",d),i.removeEventListener("abort",o),r()},s=()=>{clearTimeout(t),t=setTimeout(o,n.visibilityState==="hidden"?Math.max(e,3e4):e)},d=()=>{n.visibilityState==="visible"?o():s()};n.addEventListener("visibilitychange",d),i.addEventListener("abort",o,{once:!0}),s(),i.aborted&&o()})}var m={zh:{pending:"\u5904\u7406\u4E2D",complete:"\u5DF2\u5B8C\u6210",cancelled:"\u5DF2\u53D6\u6D88",failed:"\u5931\u8D25",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"},en:{pending:"Processing",complete:"Completed",cancelled:"Cancelled",failed:"Failed",unknown:"Status unconfirmed"}};function z(e,n){return m[n?"zh":"en"][e]}export{g as a,y as b,b as c,h as d,k as e,T as f,E as g,z as h};
@@ -1 +1 @@
1
- import{a as c}from"./chunk-S4X6YX5D.js";function d(t){let{quote:r,operation:e,requestId:i}=t,o={type:"recover",operationId:e?.operationId??r?.operationId??null,requestId:i};if(t.destroyed||t.pending)return o;if(!e)return r?{type:"cancel",operationId:r.operationId}:o;let n=e.merchantExecution;if(n?.type==="purchase"){if(["succeeded","not_required"].includes(n.paymentStatus))return!["applied","not_applicable"].includes(n.fulfillmentStatus)||e.problem?.phase==="fulfillment"||n.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:e.operationId}:{type:n.recordingStatus==="accepted"&&e.status==="complete"&&!e.problem&&!n.problem?"complete":"recording",operationId:e.operationId};if(e.status==="pending"&&e.checkoutUrl&&n.checkoutUrl===e.checkoutUrl&&n.checkoutExpiresAt&&Date.parse(n.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(n.paymentStatus))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl}}if(e.executor==="indiana"&&e.status==="pending"&&e.checkoutUrl&&!e.problem&&!e.nativePurchase&&(!r||Date.parse(r.expiresAt)>Date.now()))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl};let p=[e.problem,n?.problem],s=p.every(l=>!l||l.phase==="execution"&&l.reason!=="RESULT_UNKNOWN");return!p.some(Boolean)&&e.status==="complete"&&e.executor!=="merchant"?{type:"complete",operationId:e.operationId}:s&&t.canReselect!==!1&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"?!e.confirmedAt&&(e.status==="cancelled"||!e.quoteFinalized):!n&&!e.quoteFinalized||n?.type==="purchase"&&["failed","expired"].includes(n.paymentStatus)&&n.fulfillmentStatus==="not_applicable"&&n.recordingStatus==="accepted")?{type:"native",operationId:e.operationId}:e.status==="pending"&&s&&!e.quoteFinalized&&!n&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase?{type:"cancel",operationId:e.operationId}:o}function f(t,r=!0){if(!t)return!1;let e=d({quote:t.quote??null,operation:t,requestId:null,pending:!1,destroyed:!1,canReselect:r});return e.type==="complete"||e.type==="native"}function u(t){return t.recovery??{type:"recover",operationId:t.operation?.operationId??t.quote?.operationId??null,requestId:null}}async function y(t){let r=u(t);if(r.type==="recover"&&t.quote)try{await t.read(),r=u(t)}catch{return r}if(r.type!=="cancel"&&!(r.type==="recover"&&t.pendingCancellation))return r;try{await t.cancel();let e=u(t);return e.type==="cancel"?{type:"recover",operationId:r.operationId,requestId:null}:e}catch{let e=u(t);return e.type==="recover"?e:{type:"recover",operationId:r.operationId,requestId:null}}}function m(t,r){let e=structuredClone(t);for(let[i,a]of Object.entries(e.plans)){let o=r.plans[i];!o||o.versionId!==a.versionId||(o.amountMinor!==void 0&&(a.amountMinor=o.amountMinor),o.interval!==void 0&&(a.interval=o.interval),o.intervalCount!==void 0&&(a.intervalCount=o.intervalCount),o.prepaid!==void 0&&(a.prepaid=structuredClone(o.prepaid)))}return e}function b(t,r){let e=i=>"document"in i?i.offering.id:i.content.offeringVersionId;return t.id===r.id&&e(t)===e(r)&&t.content?.artifact.sha256===r.content?.artifact.sha256}function S(t,r,e){if(t.operationId!==r.operationId||r.currency!==void 0&&t.currency!==r.currency)throw new c("INVALID_RESPONSE",e)}function v(t,r,e){let i=Object.fromEntries((t.lines[0]?.prepaid??[]).map(a=>[a.internal_feature_id,a.quantity]));if(r.featureQuantities&&(Object.keys(i).length!==Object.keys(r.featureQuantities).length||Object.entries(r.featureQuantities).some(([a,o])=>i[a]!==o)))throw new c("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(t.lines.length!==1||t.lines[0].productVersionId!==r.productVersionId||r.currency!==void 0&&t.currency!==r.currency||r.provider!==void 0&&t.provider!==r.provider&&!(r.provider==="stripe"&&t.provider==="merchant"&&t.execution?.provider==="merchant"))throw new c("INVALID_RESPONSE",e)}function g(t,r,e=!1){if(!t||t.operationId!==r?.operationId)return r;let i=t.merchantExecution,a=r.merchantExecution;return i&&(!a||Date.parse(a.updatedAt)<Date.parse(i.updatedAt))||t.status==="complete"&&r.status!=="complete"||t.status!=="pending"&&(r.status==="pending"||e&&r.status!=="complete")?t:r}export{d as a,f as b,u as c,y as d,m as e,b as f,S as g,v as h,g as i};
1
+ import{a as c}from"./chunk-7EPE2PUN.js";function d(t){let{quote:r,operation:e,requestId:i}=t,o={type:"recover",operationId:e?.operationId??r?.operationId??null,requestId:i};if(t.destroyed||t.pending)return o;if(!e)return r?{type:"cancel",operationId:r.operationId}:o;let n=e.merchantExecution;if(n?.type==="purchase"){if(["succeeded","not_required"].includes(n.paymentStatus))return!["applied","not_applicable"].includes(n.fulfillmentStatus)||e.problem?.phase==="fulfillment"||n.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:e.operationId}:{type:n.recordingStatus==="accepted"&&e.status==="complete"&&!e.problem&&!n.problem?"complete":"recording",operationId:e.operationId};if(e.status==="pending"&&e.checkoutUrl&&n.checkoutUrl===e.checkoutUrl&&n.checkoutExpiresAt&&Date.parse(n.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(n.paymentStatus))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl}}if(e.executor==="indiana"&&e.status==="pending"&&e.checkoutUrl&&!e.problem&&!e.nativePurchase&&(!r||Date.parse(r.expiresAt)>Date.now()))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl};let p=[e.problem,n?.problem],s=p.every(u=>!u||u.phase==="execution"&&u.reason!=="RESULT_UNKNOWN");return!p.some(Boolean)&&e.status==="complete"&&e.executor!=="merchant"?{type:"complete",operationId:e.operationId}:s&&t.canReselect!==!1&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"?!e.confirmedAt&&(e.status==="cancelled"||!e.quoteFinalized):!n&&!e.quoteFinalized||n?.type==="purchase"&&["failed","expired"].includes(n.paymentStatus)&&n.fulfillmentStatus==="not_applicable"&&n.recordingStatus==="accepted")?{type:"native",operationId:e.operationId}:e.status==="pending"&&s&&!e.quoteFinalized&&!n&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase?{type:"cancel",operationId:e.operationId}:o}function f(t,r=!0){if(!t)return!1;let e=d({quote:t.quote??null,operation:t,requestId:null,pending:!1,destroyed:!1,canReselect:r});return e.type==="complete"||e.type==="native"}function l(t){return t.recovery??{type:"recover",operationId:t.operation?.operationId??t.quote?.operationId??null,requestId:null}}async function y(t){let r=l(t);if(r.type==="recover"&&t.quote)try{await t.read(),r=l(t)}catch{return r}if(r.type!=="cancel"&&!(r.type==="recover"&&t.pendingCancellation))return r;try{await t.cancel();let e=l(t);return e.type==="cancel"?{type:"recover",operationId:r.operationId,requestId:null}:e}catch{let e=l(t);return e.type==="recover"?e:{type:"recover",operationId:r.operationId,requestId:null}}}function m(t,r){let e=structuredClone(t);for(let[i,a]of Object.entries(e.plans)){let o=r.plans[i];!o||o.versionId!==a.versionId||(o.amountMinor!==void 0&&(a.amountMinor=o.amountMinor),o.interval!==void 0&&(a.interval=o.interval),o.intervalCount!==void 0&&(a.intervalCount=o.intervalCount),o.prepaid!==void 0&&(a.prepaid=structuredClone(o.prepaid)))}return e}function b(t,r){let e=i=>"document"in i?i.offering.id:i.content.offeringVersionId;return t.id===r.id&&e(t)===e(r)&&t.content?.artifact.sha256===r.content?.artifact.sha256}function S(t,r,e){if(t.operationId!==r.operationId||r.currency!==void 0&&t.currency!==r.currency)throw new c("INVALID_RESPONSE",e)}function v(t,r,e){let i=Object.fromEntries((t.lines[0]?.prepaid??[]).map(a=>[a.internal_feature_id,a.quantity]));if(r.featureQuantities&&(Object.keys(i).length!==Object.keys(r.featureQuantities).length||Object.entries(r.featureQuantities).some(([a,o])=>i[a]!==o)))throw new c("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(t.lines.length!==1||t.lines[0].productVersionId!==r.productVersionId||r.currency!==void 0&&t.currency!==r.currency||r.provider!==void 0&&t.provider!==r.provider&&!(r.provider==="stripe"&&t.provider==="merchant"&&t.execution?.provider==="merchant"))throw new c("INVALID_RESPONSE",e)}function g(t,r,e=!1){if(!t||t.operationId!==r?.operationId)return r;let i=t.merchantExecution,a=r.merchantExecution;return i&&(!a||Date.parse(a.updatedAt)<Date.parse(i.updatedAt))||t.status==="complete"&&r.status!=="complete"||t.status!=="pending"&&(r.status==="pending"||e&&r.status!=="complete")?t:r}function w(t){return t.screen.actions.some(r=>r.properties.closeControl==="content"&&t.buttons[r.id]?.type==="close")}export{d as a,f as b,l as c,y as d,m as e,b as f,S as g,v as h,g as i,w as j};
@@ -1 +1 @@
1
- import{b as e}from"./chunk-ZGBSTK22.js";var r=e.number().int().min(1).max(Number.MAX_SAFE_INTEGER),m=e.enum(["unknown","denied","provisional","granted"]),d=e.enum(["ios","android"]),i=e.strictObject({installationId:e.uuid(),publicKey:e.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:e.iso.datetime({offset:!0}),signature:e.string().regex(/^[A-Za-z0-9_-]{86}$/)}),a=e.string().regex(/^[a-f0-9]{64}$/),p=i.extend({sequence:r,platform:d,credentialDigest:a}),f=i.extend({credentialDigest:a}),x=i.extend({sequence:r,platform:d}),l=i.extend({sequence:r,credentialDigest:a,connectionId:e.uuid().nullable(),kind:e.enum(["fcm_token","apns_token"]).nullable(),token:e.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:m}),g=l,b=l.extend({challenge:e.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),S=e.strictObject({requested:e.literal(!0),expiresAt:e.iso.datetime({offset:!0})}),A=e.strictObject({installationId:e.uuid(),bound:e.boolean(),identitySeq:r,bindingGeneration:r,addressSeq:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:e.uuid().nullable(),addressStatus:e.enum(["active","invalid"]).nullable(),permission:m}),I=e.strictObject({channel:e.enum(["email","sms","voice","push"]),state:e.enum(["unknown","allowed","denied"]),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:e.iso.datetime({offset:!0}).nullable()}),P=e.strictObject({state:e.enum(["allowed","denied"]),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function y(s,c,t){let n=["indiana_push_v1",s,c.projectId,c.environment,t.installationId,t.publicKey,t.issuedAt];s==="bind"?n.push(t.sequence,t.platform,t.credentialDigest):s==="detach"?n.push(t.sequence,t.platform):s==="read"?n.push(t.credentialDigest):n.push(t.sequence,t.credentialDigest,t.connectionId,t.kind,t.token,t.permission),s==="recovery_confirm"&&n.push(t.challenge);let u=JSON.stringify(n);if([...u].some(o=>o.charCodeAt(0)>127))throw new Error("Push proof fields must be ASCII");return Uint8Array.from(u,o=>o.charCodeAt(0))}export{p as a,f as b,x as c,l as d,g as e,b as f,S as g,A as h,I as i,y as j};
1
+ import{b as e}from"./chunk-7GD2UTBU.js";var r=e.number().int().min(1).max(Number.MAX_SAFE_INTEGER),m=e.enum(["unknown","denied","provisional","granted"]),d=e.enum(["ios","android"]),i=e.strictObject({installationId:e.uuid(),publicKey:e.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:e.iso.datetime({offset:!0}),signature:e.string().regex(/^[A-Za-z0-9_-]{86}$/)}),a=e.string().regex(/^[a-f0-9]{64}$/),p=i.extend({sequence:r,platform:d,credentialDigest:a}),f=i.extend({credentialDigest:a}),x=i.extend({sequence:r,platform:d}),l=i.extend({sequence:r,credentialDigest:a,connectionId:e.uuid().nullable(),kind:e.enum(["fcm_token","apns_token"]).nullable(),token:e.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:m}),g=l,b=l.extend({challenge:e.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),S=e.strictObject({requested:e.literal(!0),expiresAt:e.iso.datetime({offset:!0})}),A=e.strictObject({installationId:e.uuid(),bound:e.boolean(),identitySeq:r,bindingGeneration:r,addressSeq:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:e.uuid().nullable(),addressStatus:e.enum(["active","invalid"]).nullable(),permission:m}),I=e.strictObject({channel:e.enum(["email","sms","voice","push"]),state:e.enum(["unknown","allowed","denied"]),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:e.iso.datetime({offset:!0}).nullable()}),P=e.strictObject({state:e.enum(["allowed","denied"]),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function y(s,c,t){let n=["indiana_push_v1",s,c.projectId,c.environment,t.installationId,t.publicKey,t.issuedAt];s==="bind"?n.push(t.sequence,t.platform,t.credentialDigest):s==="detach"?n.push(t.sequence,t.platform):s==="read"?n.push(t.credentialDigest):n.push(t.sequence,t.credentialDigest,t.connectionId,t.kind,t.token,t.permission),s==="recovery_confirm"&&n.push(t.challenge);let u=JSON.stringify(n);if([...u].some(o=>o.charCodeAt(0)>127))throw new Error("Push proof fields must be ASCII");return Uint8Array.from(u,o=>o.charCodeAt(0))}export{p as a,f as b,x as c,l as d,g as e,b as f,S as g,A as h,I as i,y as j};
@@ -1 +1 @@
1
- import{b as Ie}from"./chunk-WCKOWAIL.js";import{a as Q}from"./chunk-2TQEJ6GM.js";import{A as Se,E as z,G as Pe,d as pe,f as k,k as me,v as we,w as ge,y as ye}from"./chunk-D4CDG535.js";import{$ as N}from"./chunk-XZMM34BS.js";import{a as B,i as J}from"./chunk-26YREQNF.js";import{b as he}from"./chunk-MTKM26F7.js";import{a as c}from"./chunk-S4X6YX5D.js";import{h as G}from"./chunk-2ZPCWVFU.js";import{b as fe}from"./chunk-AEERSTTW.js";import{b as r}from"./chunk-ZGBSTK22.js";import{a as oe}from"./chunk-DSPLGTQI.js";var g=N.options,Ae=r.discriminatedUnion("operation",[g[1].omit({customerToken:!0}),g[2].omit({customerToken:!0}),g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0}),g[8].omit({customerToken:!0}),me.omit({customerToken:!0})]),je=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),Me=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume"]),start:r.strictObject({requestId:g[0].shape.requestId,funnelId:g[0].shape.funnelId,locale:g[0].shape.locale,parameters:g[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:je}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0})]).optional()}).refine(o=>!o.command||o.requestId===o.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:Ae})]),ae=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:k.shape.run.shape.status}),K={scope:G,customerId:r.uuid()},Ce=r.discriminatedUnion("outcome",[r.strictObject({...K,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...K,outcome:r.literal("resolved"),target:ae,view:k.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((o,d)=>{o.outcome==="resolved"&&(o.access.type==="customer"!=(o.view!==null)||o.view&&(o.view.id!==o.target.runId||o.view.source.id!==o.target.funnelId||o.view.source.versionId!==o.target.versionId||o.view.status!==o.target.status||o.view.runExpiresAt!==o.target.runExpiresAt||o.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Re=r.strictObject({...K,target:ae,view:k.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:k.shape.purchase.unwrap().nullable()}).superRefine((o,d)=>{let p=o.settlement;(p.acceptance==="accepted"!=(p.receiptPhase!==null)||p.acceptance==="accepted"&&p.basis!=="receipt"||p.acceptance==="unknown"&&(p.state!=="unknown"||p.basis!=="none")||p.acceptance!=="accepted"&&(p.operationId!==null||p.receiptId!==null)||p.acceptance==="not_accepted"&&(p.state!=="settled"||!["run_terminal","position_advanced"].includes(p.basis))||o.purchase&&(o.purchase.receiptId!==p.receiptId||o.purchase.operation&&o.purchase.operation.operationId!==p.operationId||o.purchase.quote&&o.purchase.quote.operationId!==p.operationId)||o.view&&(o.view.id!==o.target.runId||o.view.source.id!==o.target.funnelId||o.view.source.versionId!==o.target.versionId||o.view.status!==o.target.status||o.view.runExpiresAt!==o.target.runExpiresAt||o.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ee=r.strictObject({...K,target:ae,purchase:k.shape.purchase.unwrap()}).superRefine((o,d)=>{(!o.purchase.operation||typeof o.purchase.canReselect!="boolean"||o.purchase.quote&&o.purchase.quote.operationId!==o.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})});var Ne=N.options[0].refine(o=>!o.customer&&!o.customerData),ke=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),ve=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:G,customerId:r.uuid(),sessionId:r.uuid(),start:Ne,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:pe.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ke).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:we.nullable()})});function be(o){return ye({...o,namespace:"purchases",identity:[o.scope.projectId,o.scope.environment,o.customerId]})}function Oe(o){let d=new URL(o.baseUrl??fe).href,p=()=>new c("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function E(){o.assertCurrent();try{let y=await o.storage.read();if(o.assertCurrent(),!Number.isSafeInteger(y.revision)||y.revision<0)throw p();let a=y.entry===null?null:ve.parse(y.entry);if(a&&(a.baseUrl!==d||a.customerId!==o.customerId||a.scope.projectId!==o.scope.projectId||a.scope.environment!==o.scope.environment))throw new c("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(a?.journal.entry&&(a.journal.entry.scope.projectId!==a.scope.projectId||a.journal.entry.scope.environment!==a.scope.environment||a.journal.entry.funnelId!==a.start.funnelId||a.journal.entry.runId!==a.run?.id||a.journal.entry.versionId!==a.run?.versionId)||a?.operationCommand&&!a.purchases.some(R=>R.operationId===a.operationCommand?.operationId))throw p();return{revision:y.revision,entry:a}}catch(y){throw y instanceof c?y:p()}}async function Y(y){for(let a=0;a<8;a++){let R=await E(),b=y(structuredClone(R.entry));if(JSON.stringify(b)===JSON.stringify(R.entry))return b;b&&ve.parse(b),o.assertCurrent();let v;try{v=await o.storage.write(R.revision,b)}catch{throw p()}if(o.assertCurrent(),v!==null){if(!Number.isSafeInteger(v)||v<=R.revision)throw p();return b}}throw new c("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:E,update:Y,baseUrl:d}}function Te(o){let d=o.purchases.find(p=>p.type==="checkout");if(!o.actions.includes("continue_checkout")||d?.type!=="checkout")throw new c("PURCHASE_PENDING","No single resumable Checkout is confirmed");return d.checkoutUrl}function pn(o){let d={...o,scope:{...o.scope},executionPolicy:structuredClone(o.executionPolicy)},p=d.session.snapshot();if(!p)throw new c("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:E,sessionId:Y}=p,y=!1,a=null,R,b=null,v=!1,q,U,D,O={mode:"idle",status:"idle",actions:["start"],purchases:[]},I=new Map,j=new Map,ie=new AbortController,H=new Set,W=he(d),se=Ie(W.request);function L(e){return{code:e instanceof c?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof c&&e.status!==void 0?{status:e.status}:{}}}function P(){if(y||d.session.snapshot()?.customerId!==E)throw new c("IDENTITY_CHANGED","The original purchase Customer changed")}let w=Oe({...d,customerId:E,assertCurrent:P,storage:d.storage??be({baseUrl:d.baseUrl,scope:d.scope,customerId:E})}),Fe=d.session.subscribeIdentity(ue);function ue(){y||(y=!0,clearTimeout(D),ie.abort(new c("IDENTITY_CHANGED","Purchase consumer was destroyed")),Fe(),a?.reset(),a=null,b=null,W.dispose(),H.clear(),I.clear(),j.clear())}function C(e){P();let n=JSON.stringify(e)!==JSON.stringify(O);O=e,clearTimeout(D),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(D=setTimeout(()=>{T().catch(()=>{})},5e3)),n&&oe(d.onRecovery,structuredClone(e));for(let t of n?H:[]){if(y)break;oe(t,structuredClone(e))}return structuredClone(e)}function h(e){if(P(),!e||e.start.requestId!==R)throw new c("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function F(e){let n=[...e.purchases],t=e.journal.entry?.purchase;return t&&!n.some(u=>u.operationId===t.operationId)&&n.push({receiptId:t.receiptId,operationId:t.operationId,terminal:null}),n}function M(e){return e.run&&!["running","waiting"].includes(e.run.status)&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&F(e).every(n=>n.terminal!==null)}function _(e,n){let t=e.journal.entry?.command??e.journal.entry?.closeCommand,u=F(e).map(S=>{let re=I.get(S.operationId);return S.terminal&&!re?{type:S.terminal,operationId:S.operationId}:B({quote:re?.quote??null,operation:re??null,requestId:t?.requestId??null,pending:!1,destroyed:!1,canReselect:j.get(S.operationId)===!0})}),l=u.filter(S=>!["complete","native"].includes(S.type)),i=l[0],s=l.length===1&&i?.operationId?I.get(i.operationId):void 0;if(s&&(i?.type==="checkout"||i?.type==="cancel"))try{z({allowed:e.allowed.filter(S=>d.executionPolicy.allowed.includes(S))},s.quote)}catch(S){return{mode:n,status:"blocked",actions:["refresh",...n==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:u,error:L(S)}}let m;if(n==="operation"&&!t&&i?.type==="cancel"&&s?.quote&&!s.problem&&!s.confirmedAt)try{z({allowed:e.allowed.filter(S=>d.executionPolicy.allowed.includes(S))},s.quote),Date.parse(s.quote.expiresAt)>Date.now()&&(m={operationId:s.operationId,quote:s.quote})}catch{}let f=u.length>0&&l.length===0,x=M(e)||n==="operation"&&f&&!t&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":t||e.operationCommand||i&&i.type!=="cancel"||n==="operation"&&!m?"waiting_result":"ready";return{mode:n,status:x,purchases:u,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...M(e)?["start"]:[],...n==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...l.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function $(e){let n=B({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&j.get(e.operationId)===!0});return n.type==="complete"||n.type==="native"?n.type:null}function X(e){if(!e.operation)return;let n={...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}};if(n.merchantExecution&&n.merchantExecution.customerId!==E)throw new c("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let t=J(I.get(n.operationId)??null,n);I.set(n.operationId,t),t===n&&j.set(n.operationId,e.canReselect===!0)}async function qe(e){P();for(let t of[e.purchase,e.run.paywall])t&&X(t);let n=await w.update(t=>{if(h(t),t.run&&(t.run.id!==e.run.id||t.run.versionId!==e.run.source.versionId))throw new c("SCOPE_MISMATCH","The original purchase Run changed");let u=F(t);for(let l of[e.purchase,e.run.paywall]){let i=l?.operation?.operationId??l?.quote?.operationId;if(!l||!i)continue;let s=u.find(f=>f.operationId===i);if(s&&s.receiptId!==l.receiptId)throw new c("INVALID_RESPONSE","The original purchase Receipt changed");let m=$(I.get(i));s?s.terminal??=m:u.push({receiptId:l.receiptId,operationId:i,terminal:m})}return{...t,purchases:u,run:t.run&&(t.run.revision>e.run.revision||!["running","waiting"].includes(t.run.status)&&["running","waiting"].includes(e.run.status))?t.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});h(n),n.run&&!["running","waiting"].includes(n.run.status)&&F(n).some(t=>!t.terminal)&&(n=await Z(n,!n.journal.entry?.command&&!n.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(t=>!!t)))),h(n),C(_(n,"run"))}function _e(){return{async read(){let{entry:e}=await w.read();return h(e),structuredClone(e.journal)},async write(e,n){let t=null;return await w.update(u=>{if(h(u),u.operationCommand&&n?.command&&n.command.operation!=="close")throw new c("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return t=null,u.journal.revision!==e?u:(t=e+1,{...u,journal:{revision:t,entry:n}})}),t}}}async function Z(e,n=!1,t=new Set){h(e);let u=F(e);for(let i of u){if(i.terminal)continue;let s=t.has(i.operationId)?I.get(i.operationId):void 0;if(s??=await ce(e,i),P(),s.operationId!==i.operationId)throw new c("INVALID_RESPONSE","Original Operation changed");if(s.merchantExecution&&s.merchantExecution.customerId!==E)throw new c("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(n&&!e.operationCommand&&B({quote:s.quote??null,operation:s,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){if({operation:s}=await se.attach({operationId:i.operationId,intent:"cancel"}),P(),s.operationId!==i.operationId)throw new c("INVALID_RESPONSE","Original cancellation Operation changed");s=await ce(e,i)}I.set(i.operationId,J(I.get(i.operationId)??null,s))}let l=await w.update(i=>{h(i);let s=i.operationCommand&&I.get(i.operationCommand.operationId);return{...i,...s&&(s.confirmedAt||s.merchantExecution||s.status!=="pending")?{operationCommand:void 0}:{},purchases:F(i).map(m=>({...m,terminal:m.terminal??$(I.get(m.operationId))}))}});return h(l),l}async function ee(e){P();let n=await W.request("funnels",e);return P(),n}async function ce(e,n){let t=Q(Ee,await ee({operation:"recover_purchase",runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:n.receiptId,operationId:n.operationId}}));if(ne(e,t),t.purchase.receiptId!==n.receiptId||t.purchase.operation?.operationId!==n.operationId)throw new c("INVALID_RESPONSE","Original purchase reference changed");return X(t.purchase),I.get(n.operationId)}async function le(e){for(let n of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!n)continue;let t=Q(Re,await ee({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:n.requestId,...n.operation==="resume"?{}:{command:n}}));if(ne(e,t),t.settlement.requestId!==n.requestId)throw new c("INVALID_RESPONSE","Original command settlement changed");t.purchase&&X(t.purchase);let u=await w.update(l=>{h(l);let i=F(l),{receiptId:s,operationId:m}=t.settlement;if(s&&m){let x=i.find(S=>S.operationId===m);if(x&&x.receiptId!==s)throw new c("INVALID_RESPONSE","Original Receipt changed");x||i.push({receiptId:s,operationId:m,terminal:$(I.get(m))})}let f=t.settlement.state==="settled"?ge(l.journal.entry,n.requestId):l.journal.entry;return{...l,purchases:i,journal:f===l.journal.entry?l.journal:{revision:l.journal.revision+1,entry:f}}});h(u),e=u}return e}function ne(e,n){if(n.customerId!==E||n.scope.projectId!==d.scope.projectId||n.scope.environment!==d.scope.environment||n.target.funnelId!==e.start.funnelId||n.target.startRequestId!==e.start.requestId||e.run&&(n.target.runId!==e.run.id||n.target.versionId!==e.run.versionId))throw new c("SCOPE_MISMATCH","The original recovery binding changed")}async function te(e,n){if(h(e),e.run&&(e=await le(e)),!F(e).length&&M(e))return C(_(e,"operation"));if(!F(e).length)return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(n)});v=!0;let t=await Z(e);return C(_(t,"operation"))}async function V(e,n=!1,t=!0){if(R=e.start.requestId,b=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!a){let u=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:n?"resume":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},l;try{l=await ee(u)}catch(f){if(!e.run&&f instanceof c&&(f.status===void 0||f.status>=500))return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:O.purchases,error:L(f)});throw f}let i=Q(Ce,l);if(i.customerId!==E||i.scope.projectId!==d.scope.projectId||i.scope.environment!==d.scope.environment)throw new c("SCOPE_MISMATCH","Recovery Customer or environment changed");if(i.outcome==="unknown")return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:O.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});ne(e,i);let s=await w.update(f=>(h(f),{...f,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??f.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(h(s),e=s,i.access.type==="operation_only")return te(e,new c("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await le(e);let m=i.view;if(m.locale!==e.start.locale||!Se(m.parameters,e.start.parameters))throw new c("INVALID_RESPONSE","The original Start input changed");a=Pe({...d,customerRun:{runId:i.target.runId,customerId:E,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(f=>d.executionPolicy.allowed.includes(f))},funnelCommandStorage:_e(),onAcceptedResponse:qe},{scope:i.scope,run:m})}try{await a.get(),a.view?.pendingRequest?.requestId===e.start.requestId&&!a.pendingCommands?.length&&await a.resume(a.view.pendingRequest.requestId);for(let l of a.pendingCommands??[])l.operation!=="close"&&await a.settle?.(l.requestId);a.pendingCommands?.length&&await a.retry(),P();let u=(await w.read()).entry;return h(u),C(_(u,"run"))}catch(u){if(P(),t&&u instanceof c&&(u.status===401||u.status===409&&u.reason==="STATE_CHANGED")){a.reset(),a=null;let l=(await w.read()).entry;return h(l),V(l,!1,!1)}throw u}}function A(e,n="read"){if(P(),q)return n==="read"||n===U?q:q.then(()=>A(e,n),()=>A(e,n));clearTimeout(D);let t=e().catch(u=>{throw y||C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:O.purchases,error:L(u)}),u});return q=t,U=n,t.then(()=>{q===t&&(q=void 0,U=void 0)},()=>{q===t&&(q=void 0,U=void 0)}),t}function T(){return A(async()=>{let{entry:e}=await w.read();return e?(R&&e.start.requestId!==R&&(a?.reset(),a=null,I.clear(),j.clear()),v&&R===e.start.requestId?te(e,O.error):V(e)):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}async function de(){let e=await T();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:A(async()=>{let n=(await w.read()).entry;if(h(n),!v){if(!a?.view?.paywall?.quote)throw new c("PURCHASE_PENDING","Read the original quote before confirming");let s=a.view.paywall.operation;if(s?.confirmedAt||s?.merchantExecution||s&&s.status!=="pending")return C(_(n,"run"));if(a.pendingCommands?.length)await a.retry();else{let f=a.view;await a.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:f.nodeId,visit:f.visit,revision:f.revision,input:{type:"paywall_confirm",operationId:f.paywall.quote.operationId}})}let m=(await w.read()).entry;return h(m),C(_(m,"run"))}let t=n.operationCommand?.operationId??O.confirmation?.operationId,u=t&&I.get(t);if(!t||!u||n.journal.entry?.command||n.journal.entry?.closeCommand)throw new c("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");z({allowed:n.allowed.filter(s=>d.executionPolicy.allowed.includes(s))},u.quote),await w.update(s=>{if(h(s),s.journal.entry?.command||s.journal.entry?.closeCommand||s.operationCommand&&s.operationCommand.operationId!==t)throw new c("PURCHASE_PENDING","Another original command is pending");return{...s,operationCommand:{operationId:t,intent:"confirm"}}});let l=await se.attach({operationId:t,intent:"confirm"});if(P(),l.operation.operationId!==t)throw new c("INVALID_RESPONSE","Original confirmation Operation changed");I.set(t,J(u,l.operation));let i=(await w.read()).entry;return h(i),C(_(await Z(i,!1,new Set([t])),"operation"))},"confirm")}return{get controller(){return a},get recovery(){return structuredClone(O)},get attempt(){return P(),structuredClone(b)},get identitySignal(){return ie.signal},start(e){let n=N.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(n.operation!=="start"||n.customer||n.customerData)throw new c("INVALID_REQUEST","A Customer-owned Funnel start is required");return A(async()=>{let t=await w.update(u=>{if(u&&!M(u)){if(u.start.funnelId!==n.funnelId)throw new c("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return u}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:E,sessionId:Y,start:n,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!t)throw new c("PURCHASE_STORAGE_INVALID","Original start was not retained");return R!==t.start.requestId&&(a?.reset(),a=null,I.clear(),j.clear(),v=!1),v?te(t,O.error):V(t,!0)},`start:${n.funnelId}`)},refresh:T,confirm:de,retry:()=>v?de():A(async()=>{let{entry:e}=await w.read();return e?V(e,!0):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return a?.view?A(async()=>{if(!a?.view)throw new c("PURCHASE_PENDING","Recover the original Run before closing");if(a.pendingCommands?.find(t=>t.operation==="close"))await a.retry();else if(["running","waiting"].includes(a.view.status)){let t=a.view;await a.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision})}let n=(await w.read()).entry;return h(n),C(_(n,"run"))},"close"):T()},async continueCheckout(e){let n=await T();P(),await e(Te(n))},subscribe(e){return H.add(e),()=>{H.delete(e)}},destroy:ue}}export{be as a,Te as b,pn as c};
1
+ import{b as Ie}from"./chunk-PQJJ5BSY.js";import{a as Q}from"./chunk-6QJRT23Q.js";import{A as Se,E as z,G as Pe,d as pe,f as k,k as me,v as we,w as ge,y as ye}from"./chunk-JPHYIUIR.js";import{$ as N}from"./chunk-2JTMXZ5M.js";import{a as B,i as J}from"./chunk-KAXKYBSI.js";import{b as he}from"./chunk-YBX2LLRG.js";import{a as c}from"./chunk-7EPE2PUN.js";import{h as G}from"./chunk-VC2H3LFP.js";import{b as fe}from"./chunk-5X6WAPH3.js";import{b as r}from"./chunk-7GD2UTBU.js";import{a as oe}from"./chunk-DSPLGTQI.js";var g=N.options,Ae=r.discriminatedUnion("operation",[g[1].omit({customerToken:!0}),g[2].omit({customerToken:!0}),g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0}),g[8].omit({customerToken:!0}),me.omit({customerToken:!0})]),je=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),Me=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume"]),start:r.strictObject({requestId:g[0].shape.requestId,funnelId:g[0].shape.funnelId,locale:g[0].shape.locale,parameters:g[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:je}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0})]).optional()}).refine(o=>!o.command||o.requestId===o.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:Ae})]),ae=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:k.shape.run.shape.status}),K={scope:G,customerId:r.uuid()},Ce=r.discriminatedUnion("outcome",[r.strictObject({...K,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...K,outcome:r.literal("resolved"),target:ae,view:k.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((o,d)=>{o.outcome==="resolved"&&(o.access.type==="customer"!=(o.view!==null)||o.view&&(o.view.id!==o.target.runId||o.view.source.id!==o.target.funnelId||o.view.source.versionId!==o.target.versionId||o.view.status!==o.target.status||o.view.runExpiresAt!==o.target.runExpiresAt||o.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Re=r.strictObject({...K,target:ae,view:k.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:k.shape.purchase.unwrap().nullable()}).superRefine((o,d)=>{let p=o.settlement;(p.acceptance==="accepted"!=(p.receiptPhase!==null)||p.acceptance==="accepted"&&p.basis!=="receipt"||p.acceptance==="unknown"&&(p.state!=="unknown"||p.basis!=="none")||p.acceptance!=="accepted"&&(p.operationId!==null||p.receiptId!==null)||p.acceptance==="not_accepted"&&(p.state!=="settled"||!["run_terminal","position_advanced"].includes(p.basis))||o.purchase&&(o.purchase.receiptId!==p.receiptId||o.purchase.operation&&o.purchase.operation.operationId!==p.operationId||o.purchase.quote&&o.purchase.quote.operationId!==p.operationId)||o.view&&(o.view.id!==o.target.runId||o.view.source.id!==o.target.funnelId||o.view.source.versionId!==o.target.versionId||o.view.status!==o.target.status||o.view.runExpiresAt!==o.target.runExpiresAt||o.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ee=r.strictObject({...K,target:ae,purchase:k.shape.purchase.unwrap()}).superRefine((o,d)=>{(!o.purchase.operation||typeof o.purchase.canReselect!="boolean"||o.purchase.quote&&o.purchase.quote.operationId!==o.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})});var Ne=N.options[0].refine(o=>!o.customer&&!o.customerData),ke=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),ve=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:G,customerId:r.uuid(),sessionId:r.uuid(),start:Ne,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:pe.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ke).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:we.nullable()})});function be(o){return ye({...o,namespace:"purchases",identity:[o.scope.projectId,o.scope.environment,o.customerId]})}function Oe(o){let d=new URL(o.baseUrl??fe).href,p=()=>new c("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function E(){o.assertCurrent();try{let y=await o.storage.read();if(o.assertCurrent(),!Number.isSafeInteger(y.revision)||y.revision<0)throw p();let a=y.entry===null?null:ve.parse(y.entry);if(a&&(a.baseUrl!==d||a.customerId!==o.customerId||a.scope.projectId!==o.scope.projectId||a.scope.environment!==o.scope.environment))throw new c("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(a?.journal.entry&&(a.journal.entry.scope.projectId!==a.scope.projectId||a.journal.entry.scope.environment!==a.scope.environment||a.journal.entry.funnelId!==a.start.funnelId||a.journal.entry.runId!==a.run?.id||a.journal.entry.versionId!==a.run?.versionId)||a?.operationCommand&&!a.purchases.some(R=>R.operationId===a.operationCommand?.operationId))throw p();return{revision:y.revision,entry:a}}catch(y){throw y instanceof c?y:p()}}async function Y(y){for(let a=0;a<8;a++){let R=await E(),b=y(structuredClone(R.entry));if(JSON.stringify(b)===JSON.stringify(R.entry))return b;b&&ve.parse(b),o.assertCurrent();let v;try{v=await o.storage.write(R.revision,b)}catch{throw p()}if(o.assertCurrent(),v!==null){if(!Number.isSafeInteger(v)||v<=R.revision)throw p();return b}}throw new c("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:E,update:Y,baseUrl:d}}function Te(o){let d=o.purchases.find(p=>p.type==="checkout");if(!o.actions.includes("continue_checkout")||d?.type!=="checkout")throw new c("PURCHASE_PENDING","No single resumable Checkout is confirmed");return d.checkoutUrl}function pn(o){let d={...o,scope:{...o.scope},executionPolicy:structuredClone(o.executionPolicy)},p=d.session.snapshot();if(!p)throw new c("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:E,sessionId:Y}=p,y=!1,a=null,R,b=null,v=!1,q,U,D,O={mode:"idle",status:"idle",actions:["start"],purchases:[]},I=new Map,j=new Map,ie=new AbortController,H=new Set,W=he(d),se=Ie(W.request);function L(e){return{code:e instanceof c?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof c&&e.status!==void 0?{status:e.status}:{}}}function P(){if(y||d.session.snapshot()?.customerId!==E)throw new c("IDENTITY_CHANGED","The original purchase Customer changed")}let w=Oe({...d,customerId:E,assertCurrent:P,storage:d.storage??be({baseUrl:d.baseUrl,scope:d.scope,customerId:E})}),Fe=d.session.subscribeIdentity(ue);function ue(){y||(y=!0,clearTimeout(D),ie.abort(new c("IDENTITY_CHANGED","Purchase consumer was destroyed")),Fe(),a?.reset(),a=null,b=null,W.dispose(),H.clear(),I.clear(),j.clear())}function C(e){P();let n=JSON.stringify(e)!==JSON.stringify(O);O=e,clearTimeout(D),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(D=setTimeout(()=>{T().catch(()=>{})},5e3)),n&&oe(d.onRecovery,structuredClone(e));for(let t of n?H:[]){if(y)break;oe(t,structuredClone(e))}return structuredClone(e)}function h(e){if(P(),!e||e.start.requestId!==R)throw new c("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function F(e){let n=[...e.purchases],t=e.journal.entry?.purchase;return t&&!n.some(u=>u.operationId===t.operationId)&&n.push({receiptId:t.receiptId,operationId:t.operationId,terminal:null}),n}function M(e){return e.run&&!["running","waiting"].includes(e.run.status)&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&F(e).every(n=>n.terminal!==null)}function _(e,n){let t=e.journal.entry?.command??e.journal.entry?.closeCommand,u=F(e).map(S=>{let re=I.get(S.operationId);return S.terminal&&!re?{type:S.terminal,operationId:S.operationId}:B({quote:re?.quote??null,operation:re??null,requestId:t?.requestId??null,pending:!1,destroyed:!1,canReselect:j.get(S.operationId)===!0})}),l=u.filter(S=>!["complete","native"].includes(S.type)),i=l[0],s=l.length===1&&i?.operationId?I.get(i.operationId):void 0;if(s&&(i?.type==="checkout"||i?.type==="cancel"))try{z({allowed:e.allowed.filter(S=>d.executionPolicy.allowed.includes(S))},s.quote)}catch(S){return{mode:n,status:"blocked",actions:["refresh",...n==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:u,error:L(S)}}let m;if(n==="operation"&&!t&&i?.type==="cancel"&&s?.quote&&!s.problem&&!s.confirmedAt)try{z({allowed:e.allowed.filter(S=>d.executionPolicy.allowed.includes(S))},s.quote),Date.parse(s.quote.expiresAt)>Date.now()&&(m={operationId:s.operationId,quote:s.quote})}catch{}let f=u.length>0&&l.length===0,x=M(e)||n==="operation"&&f&&!t&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":t||e.operationCommand||i&&i.type!=="cancel"||n==="operation"&&!m?"waiting_result":"ready";return{mode:n,status:x,purchases:u,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...M(e)?["start"]:[],...n==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...l.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function $(e){let n=B({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&j.get(e.operationId)===!0});return n.type==="complete"||n.type==="native"?n.type:null}function X(e){if(!e.operation)return;let n={...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}};if(n.merchantExecution&&n.merchantExecution.customerId!==E)throw new c("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let t=J(I.get(n.operationId)??null,n);I.set(n.operationId,t),t===n&&j.set(n.operationId,e.canReselect===!0)}async function qe(e){P();for(let t of[e.purchase,e.run.paywall])t&&X(t);let n=await w.update(t=>{if(h(t),t.run&&(t.run.id!==e.run.id||t.run.versionId!==e.run.source.versionId))throw new c("SCOPE_MISMATCH","The original purchase Run changed");let u=F(t);for(let l of[e.purchase,e.run.paywall]){let i=l?.operation?.operationId??l?.quote?.operationId;if(!l||!i)continue;let s=u.find(f=>f.operationId===i);if(s&&s.receiptId!==l.receiptId)throw new c("INVALID_RESPONSE","The original purchase Receipt changed");let m=$(I.get(i));s?s.terminal??=m:u.push({receiptId:l.receiptId,operationId:i,terminal:m})}return{...t,purchases:u,run:t.run&&(t.run.revision>e.run.revision||!["running","waiting"].includes(t.run.status)&&["running","waiting"].includes(e.run.status))?t.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});h(n),n.run&&!["running","waiting"].includes(n.run.status)&&F(n).some(t=>!t.terminal)&&(n=await Z(n,!n.journal.entry?.command&&!n.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(t=>!!t)))),h(n),C(_(n,"run"))}function _e(){return{async read(){let{entry:e}=await w.read();return h(e),structuredClone(e.journal)},async write(e,n){let t=null;return await w.update(u=>{if(h(u),u.operationCommand&&n?.command&&n.command.operation!=="close")throw new c("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return t=null,u.journal.revision!==e?u:(t=e+1,{...u,journal:{revision:t,entry:n}})}),t}}}async function Z(e,n=!1,t=new Set){h(e);let u=F(e);for(let i of u){if(i.terminal)continue;let s=t.has(i.operationId)?I.get(i.operationId):void 0;if(s??=await ce(e,i),P(),s.operationId!==i.operationId)throw new c("INVALID_RESPONSE","Original Operation changed");if(s.merchantExecution&&s.merchantExecution.customerId!==E)throw new c("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(n&&!e.operationCommand&&B({quote:s.quote??null,operation:s,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){if({operation:s}=await se.attach({operationId:i.operationId,intent:"cancel"}),P(),s.operationId!==i.operationId)throw new c("INVALID_RESPONSE","Original cancellation Operation changed");s=await ce(e,i)}I.set(i.operationId,J(I.get(i.operationId)??null,s))}let l=await w.update(i=>{h(i);let s=i.operationCommand&&I.get(i.operationCommand.operationId);return{...i,...s&&(s.confirmedAt||s.merchantExecution||s.status!=="pending")?{operationCommand:void 0}:{},purchases:F(i).map(m=>({...m,terminal:m.terminal??$(I.get(m.operationId))}))}});return h(l),l}async function ee(e){P();let n=await W.request("funnels",e);return P(),n}async function ce(e,n){let t=Q(Ee,await ee({operation:"recover_purchase",runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:n.receiptId,operationId:n.operationId}}));if(ne(e,t),t.purchase.receiptId!==n.receiptId||t.purchase.operation?.operationId!==n.operationId)throw new c("INVALID_RESPONSE","Original purchase reference changed");return X(t.purchase),I.get(n.operationId)}async function le(e){for(let n of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!n)continue;let t=Q(Re,await ee({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:n.requestId,...n.operation==="resume"?{}:{command:n}}));if(ne(e,t),t.settlement.requestId!==n.requestId)throw new c("INVALID_RESPONSE","Original command settlement changed");t.purchase&&X(t.purchase);let u=await w.update(l=>{h(l);let i=F(l),{receiptId:s,operationId:m}=t.settlement;if(s&&m){let x=i.find(S=>S.operationId===m);if(x&&x.receiptId!==s)throw new c("INVALID_RESPONSE","Original Receipt changed");x||i.push({receiptId:s,operationId:m,terminal:$(I.get(m))})}let f=t.settlement.state==="settled"?ge(l.journal.entry,n.requestId):l.journal.entry;return{...l,purchases:i,journal:f===l.journal.entry?l.journal:{revision:l.journal.revision+1,entry:f}}});h(u),e=u}return e}function ne(e,n){if(n.customerId!==E||n.scope.projectId!==d.scope.projectId||n.scope.environment!==d.scope.environment||n.target.funnelId!==e.start.funnelId||n.target.startRequestId!==e.start.requestId||e.run&&(n.target.runId!==e.run.id||n.target.versionId!==e.run.versionId))throw new c("SCOPE_MISMATCH","The original recovery binding changed")}async function te(e,n){if(h(e),e.run&&(e=await le(e)),!F(e).length&&M(e))return C(_(e,"operation"));if(!F(e).length)return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(n)});v=!0;let t=await Z(e);return C(_(t,"operation"))}async function V(e,n=!1,t=!0){if(R=e.start.requestId,b=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!a){let u=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:n?"resume":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},l;try{l=await ee(u)}catch(f){if(!e.run&&f instanceof c&&(f.status===void 0||f.status>=500))return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:O.purchases,error:L(f)});throw f}let i=Q(Ce,l);if(i.customerId!==E||i.scope.projectId!==d.scope.projectId||i.scope.environment!==d.scope.environment)throw new c("SCOPE_MISMATCH","Recovery Customer or environment changed");if(i.outcome==="unknown")return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:O.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});ne(e,i);let s=await w.update(f=>(h(f),{...f,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??f.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(h(s),e=s,i.access.type==="operation_only")return te(e,new c("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await le(e);let m=i.view;if(m.locale!==e.start.locale||!Se(m.parameters,e.start.parameters))throw new c("INVALID_RESPONSE","The original Start input changed");a=Pe({...d,customerRun:{runId:i.target.runId,customerId:E,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(f=>d.executionPolicy.allowed.includes(f))},funnelCommandStorage:_e(),onAcceptedResponse:qe},{scope:i.scope,run:m})}try{await a.get(),a.view?.pendingRequest?.requestId===e.start.requestId&&!a.pendingCommands?.length&&await a.resume(a.view.pendingRequest.requestId);for(let l of a.pendingCommands??[])l.operation!=="close"&&await a.settle?.(l.requestId);a.pendingCommands?.length&&await a.retry(),P();let u=(await w.read()).entry;return h(u),C(_(u,"run"))}catch(u){if(P(),t&&u instanceof c&&(u.status===401||u.status===409&&u.reason==="STATE_CHANGED")){a.reset(),a=null;let l=(await w.read()).entry;return h(l),V(l,!1,!1)}throw u}}function A(e,n="read"){if(P(),q)return n==="read"||n===U?q:q.then(()=>A(e,n),()=>A(e,n));clearTimeout(D);let t=e().catch(u=>{throw y||C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:O.purchases,error:L(u)}),u});return q=t,U=n,t.then(()=>{q===t&&(q=void 0,U=void 0)},()=>{q===t&&(q=void 0,U=void 0)}),t}function T(){return A(async()=>{let{entry:e}=await w.read();return e?(R&&e.start.requestId!==R&&(a?.reset(),a=null,I.clear(),j.clear()),v&&R===e.start.requestId?te(e,O.error):V(e)):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}async function de(){let e=await T();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:A(async()=>{let n=(await w.read()).entry;if(h(n),!v){if(!a?.view?.paywall?.quote)throw new c("PURCHASE_PENDING","Read the original quote before confirming");let s=a.view.paywall.operation;if(s?.confirmedAt||s?.merchantExecution||s&&s.status!=="pending")return C(_(n,"run"));if(a.pendingCommands?.length)await a.retry();else{let f=a.view;await a.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:f.nodeId,visit:f.visit,revision:f.revision,input:{type:"paywall_confirm",operationId:f.paywall.quote.operationId}})}let m=(await w.read()).entry;return h(m),C(_(m,"run"))}let t=n.operationCommand?.operationId??O.confirmation?.operationId,u=t&&I.get(t);if(!t||!u||n.journal.entry?.command||n.journal.entry?.closeCommand)throw new c("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");z({allowed:n.allowed.filter(s=>d.executionPolicy.allowed.includes(s))},u.quote),await w.update(s=>{if(h(s),s.journal.entry?.command||s.journal.entry?.closeCommand||s.operationCommand&&s.operationCommand.operationId!==t)throw new c("PURCHASE_PENDING","Another original command is pending");return{...s,operationCommand:{operationId:t,intent:"confirm"}}});let l=await se.attach({operationId:t,intent:"confirm"});if(P(),l.operation.operationId!==t)throw new c("INVALID_RESPONSE","Original confirmation Operation changed");I.set(t,J(u,l.operation));let i=(await w.read()).entry;return h(i),C(_(await Z(i,!1,new Set([t])),"operation"))},"confirm")}return{get controller(){return a},get recovery(){return structuredClone(O)},get attempt(){return P(),structuredClone(b)},get identitySignal(){return ie.signal},start(e){let n=N.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(n.operation!=="start"||n.customer||n.customerData)throw new c("INVALID_REQUEST","A Customer-owned Funnel start is required");return A(async()=>{let t=await w.update(u=>{if(u&&!M(u)){if(u.start.funnelId!==n.funnelId)throw new c("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return u}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:E,sessionId:Y,start:n,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!t)throw new c("PURCHASE_STORAGE_INVALID","Original start was not retained");return R!==t.start.requestId&&(a?.reset(),a=null,I.clear(),j.clear(),v=!1),v?te(t,O.error):V(t,!0)},`start:${n.funnelId}`)},refresh:T,confirm:de,retry:()=>v?de():A(async()=>{let{entry:e}=await w.read();return e?V(e,!0):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return a?.view?A(async()=>{if(!a?.view)throw new c("PURCHASE_PENDING","Recover the original Run before closing");if(a.pendingCommands?.find(t=>t.operation==="close"))await a.retry();else if(["running","waiting"].includes(a.view.status)){let t=a.view;await a.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision})}let n=(await w.read()).entry;return h(n),C(_(n,"run"))},"close"):T()},async continueCheckout(e){let n=await T();P(),await e(Te(n))},subscribe(e){return H.add(e),()=>{H.delete(e)}},destroy:ue}}export{be as a,Te as b,pn as c};