@tinkerlandai/longplay-sdk 0.10.69 → 0.10.70

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 (88) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/check-response-NKWICRAW.js +1 -0
  3. package/dist/{chunk-NEW77IDA.js → chunk-2CK6XBGN.js} +1 -1
  4. package/dist/{chunk-DXNTXCSI.js → chunk-35CGFRWR.js} +1 -1
  5. package/dist/{chunk-ZRU7WONE.js → chunk-46FG3J5X.js} +1 -1
  6. package/dist/{chunk-2ZMIM4MO.js → chunk-5DWUXPEL.js} +1 -1
  7. package/dist/{chunk-Q4GG33R5.js → chunk-5JUUTENA.js} +1 -1
  8. package/dist/{chunk-UIR5CBCC.js → chunk-65IMHQSS.js} +1 -1
  9. package/dist/chunk-6E7CXGVN.js +1 -0
  10. package/dist/{chunk-5U7LC2NL.js → chunk-6FL4QVU5.js} +1 -1
  11. package/dist/{chunk-WVTKVQLZ.js → chunk-7AWA6PKI.js} +1 -1
  12. package/dist/{chunk-RMR64P6V.js → chunk-AME3L7BT.js} +1 -1
  13. package/dist/chunk-ASJZKRCY.js +1 -0
  14. package/dist/{chunk-BGCCW5QX.js → chunk-BFU25JPT.js} +2 -2
  15. package/dist/{chunk-DZYMD4MJ.js → chunk-CEDCYLLH.js} +1 -1
  16. package/dist/{chunk-KJTHMRSH.js → chunk-CETHPZ2K.js} +1 -1
  17. package/dist/{chunk-MT4OQFDI.js → chunk-CNWG4S72.js} +1 -1
  18. package/dist/{chunk-44ZJPQM6.js → chunk-DDAP4VXQ.js} +1 -1
  19. package/dist/{chunk-EJSTRCBQ.js → chunk-F3WIZE6M.js} +1 -1
  20. package/dist/{chunk-6GY2YT3U.js → chunk-FEOTHBMD.js} +1 -1
  21. package/dist/{chunk-TFPLIX5E.js → chunk-FOBN6LEV.js} +1 -1
  22. package/dist/{chunk-G3YIPDT6.js → chunk-GRC6NWQH.js} +1 -1
  23. package/dist/{chunk-2SSOV3OG.js → chunk-H3LTDAI5.js} +1 -1
  24. package/dist/{chunk-6C3ARFEL.js → chunk-HV7LI2JU.js} +1 -1
  25. package/dist/{chunk-5NCQOJR2.js → chunk-LN54XCEF.js} +1 -1
  26. package/dist/{chunk-CQ5EQNQA.js → chunk-LS55FUZZ.js} +1 -1
  27. package/dist/{chunk-ULED3B5P.js → chunk-M5V62FLG.js} +1 -1
  28. package/dist/{chunk-NNJ7W4KY.js → chunk-MJ5FVEM6.js} +1 -1
  29. package/dist/{chunk-GBUGEL6M.js → chunk-NDXHLKAC.js} +1 -1
  30. package/dist/{chunk-VMYLTNDS.js → chunk-NPFQD4WY.js} +1 -1
  31. package/dist/{chunk-3NV6NBQB.js → chunk-O6ZYZM6E.js} +1 -1
  32. package/dist/{chunk-CWBBW6QS.js → chunk-O7QCWT4T.js} +1 -1
  33. package/dist/{chunk-YDPF2ZZW.js → chunk-OLRWD7DF.js} +1 -1
  34. package/dist/{chunk-JW4MSBYN.js → chunk-ORIC64LN.js} +1 -1
  35. package/dist/{chunk-26QYDE7V.js → chunk-POPGX22M.js} +1 -1
  36. package/dist/{chunk-QTXHF27F.js → chunk-QTVVVOJZ.js} +1 -1
  37. package/dist/{chunk-EQ64JD4L.js → chunk-REPLGJ4W.js} +1 -1
  38. package/dist/{chunk-57ZXT7AS.js → chunk-RWZZAFR7.js} +1 -1
  39. package/dist/{chunk-LUVTP4VU.js → chunk-RYCZEVTK.js} +1 -1
  40. package/dist/{chunk-5MOJUGMA.js → chunk-T4UKYSRF.js} +1 -1
  41. package/dist/{chunk-LBYMDTGD.js → chunk-U63XQGMP.js} +1 -1
  42. package/dist/{chunk-ST7XO45I.js → chunk-URSBR2ZU.js} +1 -1
  43. package/dist/{chunk-USH4WN6W.js → chunk-VF6PR4HV.js} +1 -1
  44. package/dist/{chunk-ECUGL7AO.js → chunk-VSWF46OO.js} +1 -1
  45. package/dist/{chunk-T5SCW4IA.js → chunk-WU7M7ZZZ.js} +1 -1
  46. package/dist/{chunk-SGOVJD5P.js → chunk-XPWU4XOF.js} +1 -1
  47. package/dist/chunk-XQWYYXWZ.js +1 -0
  48. package/dist/{chunk-TYJWRPJY.js → chunk-XT25VURZ.js} +1 -1
  49. package/dist/{chunk-UFTKCFNI.js → chunk-YLZEADRF.js} +1 -1
  50. package/dist/{content-66BI72XB.js → content-JMJYZQAJ.js} +1 -1
  51. package/dist/{funnel-host-purchase-YPAWZLXP.js → funnel-host-purchase-2T5X2VHD.js} +1 -1
  52. package/dist/{funnel-host-recovery-paywall-KHBGMNS5.js → funnel-host-recovery-paywall-KRG22QX7.js} +1 -1
  53. package/dist/{funnel-paywall-copies-A76T5V7B.js → funnel-paywall-copies-RUUXK6MC.js} +1 -1
  54. package/dist/funnel-paywall-prerender-VDMHERHO.js +1 -0
  55. package/dist/funnel-route-prediction-UIF45MJM.js +1 -0
  56. package/dist/funnel-route-source-YLUKLBOY.js +1 -0
  57. package/dist/funnel-runtime-host-N75NI5NS.js +1 -0
  58. package/dist/index.js +1 -1
  59. package/dist/merchant-bridge-contracts-SCRRFZIX.js +1 -0
  60. package/dist/native-shell.js +1 -1
  61. package/dist/openrouter.js +1 -1
  62. package/dist/operation-contracts-MBTMAKH2.js +1 -0
  63. package/dist/page.js +1 -1
  64. package/dist/paywall-Z6F2GGOB.js +1 -0
  65. package/dist/paywall-content-SRZPUYGX.js +1 -0
  66. package/dist/paywall-session-MGNQ2JOG.js +1 -0
  67. package/dist/popup.js +1 -1
  68. package/dist/react-native.js +1 -1
  69. package/dist/screen-renderer-POUJYMIZ.js +1 -0
  70. package/dist/server.js +1 -1
  71. package/dist/visual.js +1 -1
  72. package/package.json +1 -1
  73. package/dist/check-response-754GDUOJ.js +0 -1
  74. package/dist/chunk-2BSDXKQS.js +0 -1
  75. package/dist/chunk-F5ABUGHD.js +0 -1
  76. package/dist/chunk-JAH62B6J.js +0 -1
  77. package/dist/funnel-paywall-prerender-PNJXR4VC.js +0 -1
  78. package/dist/funnel-route-prediction-KFUCAJLL.js +0 -1
  79. package/dist/funnel-route-source-WEYKNM2C.js +0 -1
  80. package/dist/funnel-runtime-host-RWU52BJ7.js +0 -1
  81. package/dist/merchant-bridge-contracts-RWNJHBTR.js +0 -1
  82. package/dist/operation-contracts-NNWS467N.js +0 -1
  83. package/dist/paywall-BSY67NQL.js +0 -1
  84. package/dist/paywall-content-RAB5S6KB.js +0 -1
  85. package/dist/paywall-session-CRIGHMOQ.js +0 -1
  86. package/dist/screen-renderer-H3FBGJZB.js +0 -1
  87. /package/dist/{chunk-BGCCW5QX.js.LEGAL.txt → chunk-BFU25JPT.js.LEGAL.txt} +0 -0
  88. /package/dist/{chunk-S7NHVERO.js → chunk-HI6KTEQA.js} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.70
4
+
5
+ - A Funnel shown in a dialog keeps its size while a click is processed: the footer no longer opens a "Processing" bar under the screen, so a popup does not grow a dark band before its next step (for example its Paywall) appears. The status stays in the footer's status region for assistive technology; a Back or History control, a wait, an error or an inline Funnel still shows the footer as before
6
+
3
7
  ## 0.10.69
4
8
 
5
9
  - A purchase client whose device kept only a Start that never reached Longplay (no Run, purchase or command) no longer reports `blocked` with `RESULT_UNKNOWN` on every `refresh()`. The lookup forgets that Start and returns `idle` with `start`, so a host that treats `blocked` as an unfinished purchase stops asking the Customer to check an earlier purchase that does not exist. Explicit `retry()` before a refresh still resumes the retained Start with its original input
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunk-XPWU4XOF.js";import"./chunk-POPGX22M.js";import"./chunk-CEDCYLLH.js";import"./chunk-46FG3J5X.js";import"./chunk-FOBN6LEV.js";import"./chunk-HI6KTEQA.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{a as validateEntitlementCheck,b as validateResourceCheck};
@@ -1 +1 @@
1
- import{a,b as o,c as i}from"./chunk-T5SCW4IA.js";import{a as p}from"./chunk-ZRU7WONE.js";function c(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new p("INVALID_REQUEST","Customer requests use the verified session identity")}function I(e){return{async previewUpdate(t){t=a(t),c(t);let r=await o(e,"previewUpdate");return i(e,r,t)},async update(t){t=a(t),c(t);let r=await o(e,"update");return i(e,r,t)},async readSubscriptionUpdate(t){t=a(t),c(t);let r=await o(e,"readSubscriptionUpdate");return i(e,r,t)},async restoreNativePurchase(t){t=a(t),c(t);let r=await o(e,"restoreNativePurchase");return i(e,r,t)},async previewAttach(t){t=a(t),c(t);let r=await o(e,"previewAttach");return i(e,r,t)},async attach(t){t=a(t),c(t);let r=await o(e,"attach");return i(e,r,t)},async readSubscriptionOperation(t){t=a(t),c(t);let r=await o(e,"readSubscriptionOperation");return i(e,r,t)}}}export{c as a,I as b};
1
+ import{a,b as o,c as i}from"./chunk-WU7M7ZZZ.js";import{a as p}from"./chunk-46FG3J5X.js";function c(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new p("INVALID_REQUEST","Customer requests use the verified session identity")}function I(e){return{async previewUpdate(t){t=a(t),c(t);let r=await o(e,"previewUpdate");return i(e,r,t)},async update(t){t=a(t),c(t);let r=await o(e,"update");return i(e,r,t)},async readSubscriptionUpdate(t){t=a(t),c(t);let r=await o(e,"readSubscriptionUpdate");return i(e,r,t)},async restoreNativePurchase(t){t=a(t),c(t);let r=await o(e,"restoreNativePurchase");return i(e,r,t)},async previewAttach(t){t=a(t),c(t);let r=await o(e,"previewAttach");return i(e,r,t)},async attach(t){t=a(t),c(t);let r=await o(e,"attach");return i(e,r,t)},async readSubscriptionOperation(t){t=a(t),c(t);let r=await o(e,"readSubscriptionOperation");return i(e,r,t)}}}export{c as a,I as b};
@@ -1 +1 @@
1
- import{h as c}from"./chunk-44ZJPQM6.js";import{b as p}from"./chunk-S7NHVERO.js";import{d as x,e as y,f as g}from"./chunk-VPT5MFDG.js";import{a as m,b as d}from"./chunk-CILM5XMH.js";var u=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function F(e,t,f){let i={},l,s,n,o="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let r=e.cases.findIndex(b=>x(t.attributes??{},b.condition,t.savedGroups??{}));o=r<0?"default":`case:${r}`,a=r<0?e.default:e.cases[r].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new u("Required GB Feature is unavailable");l=g(e.featureKey,t),n=l.value,Object.assign(i,c(e,{value:n})),a=e.next;break;case"split":{let r=f[e.experimentId];if(!r)throw new u("Required GB Experiment is unavailable");if(s=y(r,t),n=s.value,o=s.inExperiment&&!s.passthrough&&typeof n=="string"?n:"notParticipating",a=o==="notParticipating"?e.notParticipating:e.routes[o],!a)throw new u("Experiment Variation has no published route");break}case"offering":{let r=e.configuration.source==="fixed"?e.configuration.versionId:g(e.configuration.featureKey,t).value;n={type:"offering_version",id:p.uuid().parse(r)},Object.assign(i,c(e,{value:n})),a=e.next;break}case"coupon":case"coupons":n=e.type==="coupons"?e.couponIds.map(r=>({type:"reward",id:r})):{type:"reward",id:e.couponId},Object.assign(i,c(e,{value:n})),a=e.next;break}return{port:o,target:a,projections:i,...n===void 0?{}:{value:n},...l?{feature:l}:{},...s?{experiment:s}:{}}}function E(e,t,f){p.uuid().parse(e),p.number().int().nonnegative().parse(t);let i=m(d(new TextEncoder().encode(JSON.stringify([e,t,f])))).slice(0,32);return`${i.slice(0,8)}-${i.slice(8,12)}-5${i.slice(13,16)}-a${i.slice(17,20)}-${i.slice(20)}`}export{F as a,E as b};
1
+ import{h as c}from"./chunk-DDAP4VXQ.js";import{b as p}from"./chunk-HI6KTEQA.js";import{d as x,e as y,f as g}from"./chunk-VPT5MFDG.js";import{a as m,b as d}from"./chunk-CILM5XMH.js";var u=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function F(e,t,f){let i={},l,s,n,o="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let r=e.cases.findIndex(b=>x(t.attributes??{},b.condition,t.savedGroups??{}));o=r<0?"default":`case:${r}`,a=r<0?e.default:e.cases[r].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new u("Required GB Feature is unavailable");l=g(e.featureKey,t),n=l.value,Object.assign(i,c(e,{value:n})),a=e.next;break;case"split":{let r=f[e.experimentId];if(!r)throw new u("Required GB Experiment is unavailable");if(s=y(r,t),n=s.value,o=s.inExperiment&&!s.passthrough&&typeof n=="string"?n:"notParticipating",a=o==="notParticipating"?e.notParticipating:e.routes[o],!a)throw new u("Experiment Variation has no published route");break}case"offering":{let r=e.configuration.source==="fixed"?e.configuration.versionId:g(e.configuration.featureKey,t).value;n={type:"offering_version",id:p.uuid().parse(r)},Object.assign(i,c(e,{value:n})),a=e.next;break}case"coupon":case"coupons":n=e.type==="coupons"?e.couponIds.map(r=>({type:"reward",id:r})):{type:"reward",id:e.couponId},Object.assign(i,c(e,{value:n})),a=e.next;break}return{port:o,target:a,projections:i,...n===void 0?{}:{value:n},...l?{feature:l}:{},...s?{experiment:s}:{}}}function E(e,t,f){p.uuid().parse(e),p.number().int().nonnegative().parse(t);let i=m(d(new TextEncoder().encode(JSON.stringify([e,t,f])))).slice(0,32);return`${i.slice(0,8)}-${i.slice(8,12)}-5${i.slice(13,16)}-a${i.slice(17,20)}-${i.slice(20)}`}export{F as a,E as b};
@@ -1 +1 @@
1
- import{f as o}from"./chunk-TFPLIX5E.js";var n=class extends Error{constructor(t,s,y,i,r){super(s);this.code=t;this.status=y;this.requestId=i;this.name="IndianaError",this.reason=r?.reason;let e=o(t,y??0,{...r,retryAfter:r?.retryAfterSeconds===void 0?void 0:String(r.retryAfterSeconds)});this.retryable=e.retryable,this.recovery=e.recovery,this.retryAfterSeconds=e.retryAfterSeconds}code;status;requestId;commandRequestId;retryable;recovery;retryAfterSeconds;reason};export{n as a};
1
+ import{f as o}from"./chunk-FOBN6LEV.js";var n=class extends Error{constructor(t,s,y,i,r){super(s);this.code=t;this.status=y;this.requestId=i;this.name="IndianaError",this.reason=r?.reason;let e=o(t,y??0,{...r,retryAfter:r?.retryAfterSeconds===void 0?void 0:String(r.retryAfterSeconds)});this.retryable=e.retryable,this.recovery=e.recovery,this.retryAfterSeconds=e.retryAfterSeconds}code;status;requestId;commandRequestId;retryable;recovery;retryAfterSeconds;reason};export{n as a};
@@ -1 +1 @@
1
- import{d as t}from"./chunk-RMR64P6V.js";async function u(e,n){try{let{route:r}=await e.funnelRoute(n.funnelId),a=t(r,{customerId:n.customerId,parameters:n.parameters??{}});return{funnelId:n.funnelId,...a}}catch(r){return{funnelId:n.funnelId,type:"unavailable",reason:r?.code?.toLowerCase()??"error",path:[]}}}function l(e){switch(e.type){case"paywall":return null;case"screen":return`first_screen_${e.surface}`;case"external_page":return"first_screen_external_page";case"end":return`route_end_${e.outcome}`;case"unknown":return`route_unknown_${e.reason}`;case"unavailable":return e.reason.startsWith("route_")?e.reason:`route_${e.reason}`}}async function s(e,n){if(n.type!=="paywall")return null;try{let{document:r}=await e.paywall(n.paywallId,n.paywallVersionId);return{presentation:r.presentation,screen:r.screen,buttons:r.buttons}}catch{return null}}export{u as a,l as b,s as c};
1
+ import{d as t}from"./chunk-AME3L7BT.js";async function u(e,n){try{let{route:r}=await e.funnelRoute(n.funnelId),a=t(r,{customerId:n.customerId,parameters:n.parameters??{}});return{funnelId:n.funnelId,...a}}catch(r){return{funnelId:n.funnelId,type:"unavailable",reason:r?.code?.toLowerCase()??"error",path:[]}}}function l(e){switch(e.type){case"paywall":return null;case"screen":return`first_screen_${e.surface}`;case"external_page":return"first_screen_external_page";case"end":return`route_end_${e.outcome}`;case"unknown":return`route_unknown_${e.reason}`;case"unavailable":return e.reason.startsWith("route_")?e.reason:`route_${e.reason}`}}async function s(e,n){if(n.type!=="paywall")return null;try{let{document:r}=await e.paywall(n.paywallId,n.paywallVersionId);return{presentation:r.presentation,screen:r.screen,buttons:r.buttons}}catch{return null}}export{u as a,l as b,s as c};
@@ -1 +1 @@
1
- import{k as c}from"./chunk-EJSTRCBQ.js";import{b as r}from"./chunk-S7NHVERO.js";var s=r.strictObject({items:r.array(r.strictObject({productVersionId:r.string().min(1).max(200),label:r.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:r.string().min(1).max(200).nullable(),grouping:c.optional()});function p(e,t,n){let i=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof i!="string"||!Object.values(n.plans).some(o=>o.versionId===i&&o.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(i)||!n.pickers[e.pickerId]?.options.includes(i))?null:i}export{s as a,p as b};
1
+ import{k as c}from"./chunk-F3WIZE6M.js";import{b as r}from"./chunk-HI6KTEQA.js";var s=r.strictObject({items:r.array(r.strictObject({productVersionId:r.string().min(1).max(200),label:r.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:r.string().min(1).max(200).nullable(),grouping:c.optional()});function p(e,t,n){let i=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof i!="string"||!Object.values(n.plans).some(o=>o.versionId===i&&o.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(i)||!n.pickers[e.pickerId]?.options.includes(i))?null:i}export{s as a,p as b};
@@ -1 +1 @@
1
- import{a as tn}from"./chunk-EQ64JD4L.js";import{b as rn}from"./chunk-LBYMDTGD.js";import{b as nn}from"./chunk-ST7XO45I.js";import{d as We,e as ce}from"./chunk-ULED3B5P.js";import{c as qe,d as je,e as K,l as Ze}from"./chunk-ECUGL7AO.js";import{A as Je,F as He,G as Qe,H as z,I as Ye,J as le,K as G,a as Me,c as Y,g as Z,h as Ge,i as Ue,m as $e}from"./chunk-3NV6NBQB.js";import{A as ie,B as ae,z as oe}from"./chunk-WVTKVQLZ.js";import{a as de,b as Xe}from"./chunk-DXNTXCSI.js";import{a as j,b as _e,c as ke,e as De,h as Ve,i as Le,l as Be}from"./chunk-44ZJPQM6.js";import{b as W}from"./chunk-MT4OQFDI.js";import{a as Q}from"./chunk-KJTHMRSH.js";import{m as Ke,n as ue,o as ze,p as se}from"./chunk-JW4MSBYN.js";import{g as Ee,m as Ce,w as re}from"./chunk-EJSTRCBQ.js";import{b as Pe,d as L,e as Ae,f as Te}from"./chunk-LUVTP4VU.js";import{a as m}from"./chunk-ZRU7WONE.js";import{h as V}from"./chunk-TFPLIX5E.js";import{a as en}from"./chunk-5MRSFLQA.js";import{b as n}from"./chunk-S7NHVERO.js";import{a as on}from"./chunk-DSPLGTQI.js";import{c as Ne,f as Oe}from"./chunk-VPT5MFDG.js";function an(e){return Fn({...e,namespace:"commands",identity:[e.runToken]})}function Fn(e){let t,u,r=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),o=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let c=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??en).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",c));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,i=>i.toString(16).padStart(2,"0")).join("")});o.catch(()=>{});async function p(c){try{let a=await o;return await u.request(a,{mode:"exclusive"},()=>c(a))}catch(a){throw a instanceof m?a:r()}}function d(c){let a=t.getItem(c);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let i=JSON.parse(a);if(!i||typeof i!="object"||!("revision"in i)||!("entry"in i)||!Number.isSafeInteger(i.revision)||Number(i.revision)<0)throw r();return{revision:Number(i.revision),entry:i.entry}}return{read:()=>p(d),write:(c,a)=>p(i=>{if(d(i).revision!==c)return null;if(!Number.isSafeInteger(c+1))throw r();let y=JSON.stringify({revision:c+1,entry:a});if(y.length>1048576)throw r();return t.setItem(i,y),c+1})}}var un=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var M=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),En=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Cn=n.discriminatedUnion("type",[$e,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:M.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:He,openIn:Qe}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:M})]),Pn={id:M,presentation:Pe,outputs:n.array(M).max(250),inputs:se,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Ee,customerData:Ce,dataCursors:n.record(M,Ke.nullable())},Nn=n.strictObject({...Pn,content:n.strictObject({type:n.literal("document"),document:re})}),pe=n.strictObject({id:n.uuid(),source:un,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:M,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:En,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:ue,parameters:ze,variables:n.record(n.string(),L),output:L.nullable(),screen:Nn.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([We,ce]),quote:oe.nullable(),operation:ie.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Cn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),On=n.strictObject({scope:V,run:pe,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:oe.nullable(),operation:ie.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative(),document:re,answers:ue,inputs:se,values:n.record(n.string(),L).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=On.extend({run:pe.extend({paywall:pe.shape.paywall.unwrap().extend({resolution:ce}).nullable()})});var ln="X-Indiana-Server-Key";var An=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()}),Tn=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(An).max(200).default([]),iam:Ge.optional(),renderGuard:Z.optional()}),me=Tn.omit({variation:!0,description:!0,iam:!0}),_n=qe.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([me,me]).rest(me).refine(e=>e.length<=20)}),cn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(_n).max(100),savedGroups:je});var $=n.string().regex(/^[a-f0-9]{64}$/),Tt=n.strictObject({iam:$,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),kn=n.strictObject({release:$,render:Z,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),_t=n.strictObject({scope:V.extend({environmentId:n.uuid()}),release:$,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"]),delivery:Ue.optional(),target:kn})).max(4e3)}),kt=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:$,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Dt=n.strictObject({scope:V,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Vt=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)}),fe=n.strictObject({operation:n.literal("page_experiments"),release:$,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(Q).optional()}),dn=n.strictObject({scope:V,runId:n.uuid(),assignments:n.array(Dn.extend({receiptId:n.uuid()})).max(100),payload:cn});var U=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),mn=n.strictObject({entry:U,nodes:n.array(n.strictObject({id:U,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),U),writes:n.record(j,j),resources:n.strictObject({screenId:U.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)}),pn={scope:V,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:mn},X=n.discriminatedUnion("evaluationMode",[n.strictObject({...pn,evaluationMode:n.literal("local"),growth:K,conditions:n.record(U,n.array(n.strictObject({condition:Te,port:n.string()})))}),n.strictObject({...pn,evaluationMode:n.literal("remote")})]),Vn=X.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,ke),outputSchema:_e,terminals:n.record(U,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Je.nullable()}))})});function Ln(e){return mn.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(d=>d.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,d)=>{u[`case:${d}`]=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 o=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return o?.type==="feature"&&(r.featureKey=o.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 ge(e){let t=le.parse(e.document),u=e.evaluationMode==="local"?K.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:Ln(t)};return X.parse(e.evaluationMode==="remote"?r:{...r,growth:Ze(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(o=>o.type==="condition").map(o=>[o.id,o.cases.map((p,d)=>({condition:p.condition,port:`case:${d}`}))]))})}function $t(e){let t=ge(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=le.parse(e.document);return Vn.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let o=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:o&&o.type!=="literal"&&o.type!=="feature"&&o.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:o??null}]]}))}})}var Ie=32,Mn=522240;function ve(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()}),ye=n.record(n.string(),L),jn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:z.shape.schemaVersion,kind:z.shape.kind,selector:z.shape.selector,contract:z.shape.contract}),context:ye,removed:n.array(n.string()).max(100),attributes:ye,removedAttributes:n.array(n.string()).max(100),result:Ye,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()})}),Wt=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:qn,context:ye,steps:n.array(jn).min(1).max(Ie)}).refine(e=>Y(e)<=Mn,"Segment exceeds its byte budget");var Gn=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function J(e){return Array.isArray(e)?e.some(J):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&J(u):!Gn.test(t))}function fn(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(c=>c.id===t.screenId&&c.type==="paywall")))return"customer_required";let o=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(o&&["bundle","selection","offering"].includes(o.type)||t.type==="condition"&&t.cases.some(c=>J(c.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(c=>c.id===t.screenId):null]);for(let[c,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${c}`)||p.includes(JSON.stringify(c))))return"customer_required";if(t.type==="split"){let c=u.experiments?.[t.experimentId];if((c?.hashAttribute??"id")!=="funnelParticipantId"||J(c?.condition)||c?.parentConditions?.length)return"customer_experiment_required"}let d=t.type==="feature"?t.featureKey:o?.type==="feature"?o.featureKey:void 0;return d&&u.features?.[d]?.rules?.some(c=>(c.hashAttribute??"id")!=="funnelParticipantId"||J(c.condition)||c.parentConditions?.length)?"customer_experiment_required":null}var he=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},ee=(e,t)=>new he(e,t),Un=e=>({experiments:e.experiments,features:e.features});function we(e,t=ee){let u=new Map(e.topology.nodes.map(d=>[d.id,d])),r=Ne(e.growth.savedGroups),o=Un(e.growth);function p(d,c){if(!Object.hasOwn(e.growth.features,d))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Oe(d,c).value}return{nodes:u,savedGroups:r,features:o.features,feature:p,evaluate(d,c){let a=u.get(d);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let i,g;if(a.type==="condition"){let v=e.conditions[a.id];if(!v)throw t("INVALID_RESPONSE","Local condition rules are unavailable");i=de({id:a.id,name:a.id,type:"condition",cases:v.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},c,o.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,c),i="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 h=de({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},c,o.experiments);g=h.value,i=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,c),i=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[i]??(i==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:d,port:i,target:y,...g===void 0?{}:{value:g}}}}}function dr(e,t,u,r=ee){return be(e,r)(t,u)}function be(e,t){let u=X.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,o=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};o();let p=we(u,t);return(d,c)=>(o(),Bn(p,d,c))}function Bn(e,t,u){let r=Ae.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:o,onFeatureUsage:p,onExperimentViewed:d}=u,c={attributes:r,...o?{saveStickyBucketAssignmentDoc:a=>o(structuredClone(a))}:{},...p?{onFeatureUsage:(a,i)=>p(a,structuredClone(i))}:{},...d?{onExperimentViewed:(a,i)=>d(structuredClone(a),structuredClone(i))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,c)}function pr(e,t,u,r=ee){return gn(be(e,r),t,u)}function gn(e,t,u){let r=[],o=[],p=[],d=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(c){let a=r.findIndex(y=>y.next.attributeName===c.attributeName&&y.next.attributeValue===c.attributeValue),i=c.attributeName+"||"+c.attributeValue,g={expected:u.sticky[i]??null,next:c};a<0?r.push(g):r[a]=g},onExperimentViewed(c,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&o.push(L.parse({key:c.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(c,a){p.push(L.parse({feature:c,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:d.port,...d.value===void 0?{}:{value:d.value},sticky:r,exposures:o,features:p}}function yn(e,t,u,r=ee){let o=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),d=structuredClone(u.variables),c=structuredClone(o.sticky),a=[],i=u.nodeId,g=u.visit,y=!1,v,h=O=>fn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},o.attributes.funnelCustomerBound===!0),R=O=>(v??=be(e,r),gn(v,O,{attributes:Be({declarations:t.variables,attributes:o.attributes,parameters:u.parameters,answers:u.answers,results:d,savedGroups:{}}),sticky:c}));for(let O=0;O<Ie;O++){let s=p.get(i);if(!s||!ve(s)||h(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 f,w;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")f=R(s.id),s.type==="offering"&&(f.value={type:"offering_version",id:String(f.value)}),s.type==="condition"?w=f.port==="default"?s.default:s.cases[Number(f.port.slice(5))]?.target:s.type==="split"?w=f.port==="notParticipating"?s.notParticipating:s.routes[f.port]:(s.type==="feature"||s.type==="offering")&&(w=s.next);else if(f={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(w=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(f.value={type:"offering_version",id:s.configuration.versionId},w=s.next),s.type==="end"||s.type==="output"){let x=s.type==="end"?s.output:s.value;if(f=x?.type==="feature"?R(s.id):{...f,port:"value",value:x?.type==="literal"?x.value:x?.type==="variable"?Me({source:"variable",key:x.key,...x.path?{path:x.path}:{}},{declarations:t.variables,answers:u.answers,results:d,parameters:u.parameters,attributes:o.attributes,savedGroups:{}}):null},x&&(f.value===void 0||!De(t.outputSchema,f.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let N=[...a,{nodeId:i,result:f}];if(Y({steps:N})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:i,result:f}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let x=s.type==="coupons"?s.couponIds.map(D=>({type:"reward",id:D})):s.type==="coupon"?{type:"reward",id:s.couponId}:f.value;if(x===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=Ve(s,{value:x});Le(t.variables,s,_),Object.assign(d,_)}for(let x of f.sticky)c[`${x.next.attributeName}||${x.next.attributeValue}`]=structuredClone(x.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!w)throw r("INVALID_RESPONSE","Local pure exit is unavailable");i=w,g++}let T=p.get(i);return{steps:a,...!y&&T&&(!ve(T)||h(T))?{boundary:{nodeId:i,visit:g}}:{}}}function In(e,t){let u=sn.safeParse(t);if(!u.success)throw new m("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 m("SCOPE_MISMATCH","Funnel scope changed");return r}var xe=(e,t)=>new m(e,t);function hr(e){return we(e,xe)}var Kn=3,zn=2e3;function $n(e){return e instanceof TypeError||e instanceof m&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Jn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===Kn||!$n(u))throw u;await new Promise(r=>setTimeout(r,t*zn))}}async function Re(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 m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let o=null,p;if(u)try{let d=await e.funnel(t.source.id,t.source.versionId);p=d.manifest.generation,o=Hn(e,t,d)}catch{o=null}return p??=e.snapshot?.generation??(await Jn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:o}}function Hn(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:o,remoteFeatures:p,...d}=u.growth,c=ge({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:K.parse(d)}),a=Qn(c,u.document,{...t,...r}),i=a.steps.at(-1),g=a.boundary??(i?.result.port==="value"?{nodeId:i.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 yn(e,t,u,xe)}var vn=G.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 m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),hn=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:vn.optional(),closeCommand:vn.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 m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),ne=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function H(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 wn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),o=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:hn.parse(a.entry)}}function d(a){let i=o.then(a);return o=i.catch(()=>{}),i}async function c(a){for(let i=0;i<4;i++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(ne(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 i=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==i)throw A();u=i},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let i=hn.parse(a),g=i.command;return!g||u!==null&&r(i)!==u?Promise.reject(A()):(u??=r(i),d(()=>c((y,v)=>{if(y&&!ne(r(y),r(i)))throw A();if(y&&i.processBindingIds){for(let[h,R]of Object.entries(i.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==R)throw A();y={...y,processBindingIds:{...y.processBindingIds,...i.processBindingIds}}}if(!y){if(v!==t&&g.operation!=="close")throw A();return i}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&&!ne(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!ne(y.command,g))throw A();return y})))},observePurchase(a,i,g,y){return d(()=>c((v,h)=>{if(!v&&h!==t||v&&r(v)!==r({...a,schemaVersion:1}))throw A();if(v?.purchase&&v.purchase.generation>i.generation)return H(v,y);if(v?.purchase&&v.purchase.generation===i.generation&&v.purchase.operationId!==i.operationId)throw A();return g?!v?.purchase||v.purchase.operationId!==i.operationId?H(v,y):H(v.command?{...v,purchase:void 0}:null,y):H({schemaVersion:1,...a,...v,purchase:i},y)}))},settle(a){return d(()=>c(i=>H(i,a)))}}}function Tr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function te(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((o,p)=>te(o,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(([o,p])=>Object.hasOwn(t,o)&&te(p,Reflect.get(t,o)))}function bn(e,t){let u=t&&{...t},r=null,o=0,p=-1,d=0,c=new AbortController;function a(){d++,c.abort(new m("IDENTITY_CHANGED","Run identity changed")),c=new AbortController}let i=!1,g,y=0,v=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new m("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return p===d?r:null},get viewAgeMs(){return r&&p===d?performance.now()-o:void 0},get generation(){return d},get signal(){return c.signal},get disposed(){return i},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,R="Run identity changed during the request"){if(h!==d||i)throw new m("IDENTITY_CHANGED",R)},assertRun(h){if(r&&(h.id!==r.id||h.source.type!==r.source.type||h.source.id!==r.source.id||h.source.versionId!==r.source.versionId||h.locale!==r.locale||!te(h.parameters,r.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,R,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&R.run.revision<=r.revision)&&!(r&&R.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!R.run.stopped&&["running","waiting"].includes(R.run.status)&&r&&p===d&&R.run.nodeId===r.nodeId&&R.run.visit===r.visit&&R.run.revision===r.revision&&(R.run.screen=r.screen,(r.paywall?.quote?.operationId===R.review?.activeOperationId||!r.paywall?.quote&&R.review?.activeOperationId===null)&&(R.run.paywall=r.paywall)),!(r?.paywall&&R.run.paywall&&r.paywall.receiptId===R.run.paywall.receiptId&&(R.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||R.run.revision>=r.revision)r=R.run,o=performance.now(),p=d;else if(!s)return;if(r&&p===d)for(let f of v)try{f(structuredClone(r))}catch{}}},identify(h){if(i)throw new m("IDENTITY_CHANGED","Controller was reset");if(!Q.test(h))throw new m("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return v.add(h),()=>v.delete(h)},reset(){i||(i=!0,a(),g=void 0,r=null,v.clear())}}}var Se=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function qr(e,t,u="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",t);if(!Se.test(e))throw new m("INVALID_TOKEN",u)}function jr(e){let t=W(e);return t.identify(e.apiKey),t}function xn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&!ae(t)&&["apple","google"].includes(t.provider)?"native":t&&!ae(t)&&t.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new m("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function q(e){let{customerToken:t,...u}=e;return u}var Yn=e=>!(e instanceof m&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Rn({journal:e,state:t,call:u,processIdentity:r}){let o=null,p=null,d=!1,c={command:null,close:null},a=new Set,i,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(w=>w&&!Object.hasOwn(s.processBindingIds??{},w.requestId)))throw new m("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 m("SCOPE_MISMATCH","Pending command belongs to another scope");if(i=s.purchase,d=s.closed===!0,!s.command)return;let f=s.command;o=f.operation==="close"?null:f,p=f.operation==="close"?f:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(d=!0);for(let w of[o,p])w&&a.add(w.requestId)}):Promise.resolve();y.catch(()=>{});async function v(s,f){e&&await y;let w=t.generation;if(e){if(!t.view||!t.scope)throw new m("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:q(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(w!==t.generation||o!==s&&p!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");if(e&&on(f),t.assertCurrent(w),o!==s&&p!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let N=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(x){let _=s.operation==="submit"&&s.input.type==="paywall_quote",D=!N&&!Yn(x),l=!1;if(_&&D&&w===t.generation&&o===s&&x instanceof m&&x.status!==void 0){let I=await T(s.requestId).catch(()=>{});l=I?.settlement?.state==="unknown"&&I.settlement.operationId===null}throw w===t.generation&&(o===s||p===s)&&D&&(!_||!(x instanceof m)||x.status===void 0||l)&&(e&&await e.settle(s.requestId),w===t.generation&&O(s)),x}}function h(s,f){let w=G.parse(s);if(w.operation==="start"||w.operation==="get"||w.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(d&&w.operation!=="close"){if(o?.requestId===w.requestId)return T(w.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(w.operation==="close"){if(o?.requestId===w.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(d=!0,p&&JSON.stringify(q(p))!==JSON.stringify(q(w)))throw new m("COMMAND_PENDING","Retry the original Close");return p??=w,c.close?c.close:R(p,"close",f)}if(o){if(JSON.stringify(q(o))!==JSON.stringify(q(w)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(c.command)return c.command}else o=w;return R(o,"command",f)}function R(s,f,w){let N=v(s,w);c[f]=N;let x=()=>{c[f]===N&&(c[f]=null)};return N.then(x,x),N}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||o!==s&&p!==s?!1:(o===s&&(o=null),p===s&&(p=null),a.delete(s.requestId),!o&&!p&&(g=null),!0)}return{ready:y,get pending(){return o},get closing(){return p},get closeRequested(){return d},get inFlight(){return c.command},get closeFlight(){return c.close},get purchase(){return i},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,f,w,N){let x=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=x&&f.settlement?.state==="settled"&&f.run.pendingRequest?.requestId!==x&&(s.operation==="get"||!d||s.operation==="close"||!["running","waiting"].includes(f.run.status))?x:void 0,D=o?.requestId===_?o:p?.requestId===_?p:void 0;e?.bind({scope:f.scope,runId:f.run.id,funnelId:f.run.source.id,versionId:f.run.source.versionId});let l=f.run.paywall,I=l??f.purchase,C=I?.operation,E=f.settlement&&(!l||l.purchaseRequestId===f.settlement.requestId)&&(!i||i.operationId===f.settlement.operationId)?f.settlement:void 0,S=C?.operationId??I?.quote?.operationId??E?.operationId,F=I?.receiptId??E?.receiptId,b=l?.selectionGeneration??i?.generation??0;if(e&&S&&F&&s.operation!=="review"&&(!t.view||f.run.revision>=t.view.revision)&&(N===void 0||N>=t.readSequence)&&(!i||b>=i.generation)){let P={receiptId:F,operationId:S,generation:b},k=rn(C,I?.canReselect===!0);await e.observePurchase({scope:f.scope,runId:f.run.id,funnelId:f.run.source.id,versionId:f.run.source.versionId},P,k,_),t.assertCurrent(w),(!i||P.generation>=i.generation)&&(N===void 0||N>=t.readSequence)&&(k?i?.operationId===P.operationId&&(i=void 0):i=P)}else e&&_&&await e.settle(_);return t.assertCurrent(w),_?O(D):!1},stop(){d=!0},submit:h,settle:T,reset(){d=!0,o=null,p=null,i=void 0,g=null,c.close=null,a.clear(),c.command=null}}}function Zn(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 m("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new m("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Se.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=W({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),o=bn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(R),d=null,c=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?an(e):void 0),a=c&&wn(c),i=Rn({journal:a,state:o,call:T,processIdentity:e.process}),g=0,y=new Map;function v(){g++,y.clear(),t=void 0}async function h(l){let I=l.operation==="resume"?i.pending?.operation==="resume"?null:i.pending:l;if(u&&l.operation==="resume"&&!I&&l.requestId!==e.customerRun?.startRequestId)throw new m("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(I?.operation==="submit"&&I.input.type==="paywall_confirm"){let P=o.view?.paywall;xn(u,P?.quote?.operationId===I.input.operationId?P.quote:void 0)}if(e.process)return e.process.request(l);let C=o.generation;o.assertCurrent(C);let E=performance.now()+(e.timeoutMs??35e3),S=o.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let P=o.signal,k,B=()=>{},Sn=new Promise((Wn,Fe)=>{B=()=>Fe(P.reason),P.addEventListener("abort",B,{once:!0}),k=setTimeout(()=>Fe(new m("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(o.assertCurrent(C),e.session.access())),Sn])}finally{clearTimeout(k),P.removeEventListener("abort",B)}}o.assertCurrent(C);let F={...l,...S?{customerToken:S}:{}},b=l.operation==="page_experiments"?fe.parse(F):G.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!S)throw new m("IDENTITY_CHANGED","Original recovery Customer changed");let P={...b};return"customerToken"in P&&delete P.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:P},S,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",b,e.runToken,{headers:e.serverKey&&!S?{[ln]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function R(){v(),p?.(),o.reset(),i.reset(),d=null,r.dispose()}async function T(l,I){let C=t;t=void 0;let E=o.generation,S=()=>o.assertCurrent(E);a&&await i.ready,S();let F=o.view,b=In(e,C!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?C:await h(l));if(l.operation==="review"&&!b.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&b.run.id!==e.customerRun.runId)throw new m("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&b.purchase&&(b.purchase.receiptId!==l.purchase.receiptId||(b.purchase.operation?.operationId??b.purchase.quote?.operationId)!==l.purchase.operationId))throw new m("INVALID_RESPONSE","The requested original purchase changed");if(S(),b.runToken&&b.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let P=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(P&&b.settlement?.requestId!==P)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");i.assertBinding(b),o.assertRun(b.run),o.bindScope(b.scope);let k=await i.observe(l,b,E,I);return(!o.view||b.run.revision>=o.view.revision)&&(I===void 0||I>=o.readSequence)&&(await e.onAcceptedResponse?.(b),S()),!b.run.stopped&&["running","waiting"].includes(b.run.status)&&l.operation==="get"&&l.settlementRequestId||(S(),["running","waiting"].includes(b.run.status)||i.stop(),o.publish(l,b,F,I,k)),b}function O(l){let I=o.generation;v();let C=l(),E=()=>{o.generation===I&&v()};return C.then(E,E),C}let s=(l,I)=>O(()=>i.submit(l,I)),f=null,w=new WeakMap;function N(l){let I=w.get(l);if(I)return I;let C=_(l);return w.set(l,C),C}let x=!1;async function _(l){let I=await l;if(I.run.instruction?.type!=="evaluate_segment")return I;if(f)return f;x=!0;let C=o.generation,E=(async()=>{for(let S=0;S<32&&I.run.instruction?.type==="evaluate_segment";S++){if(i.pending||i.closeRequested)return I;let F=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:P}=await Re(e.configuration,F,{predict:!1});if(C!==o.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(i.pending||i.closeRequested)return I;if(o.view&&(o.view.revision!==F.revision||o.view.visit!==F.visit||o.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Re(e.configuration,F).then(({prediction:B})=>{k&&C===o.generation&&!i.closeRequested&&o.view?.id===F.id&&!o.view.stopped&&o.view.nodeId===F.nodeId&&o.view.visit===F.visit&&o.view.revision===F.revision&&(d=B)}).catch(()=>{});try{I=await s({operation:"commit_segment",requestId:Xe(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...P})}finally{k=!1,d=null}}}return I})();f=E;try{return await E}finally{f===E&&(f=null)}}let D={get configuration(){return x?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=o.currentView;return l?structuredClone(l):null},get viewAgeMs(){return o.viewAgeMs},get pendingCommand(){let l=i.closing??i.pending;return l?structuredClone(q(l)):null},get pendingCommands(){return[i.pending,i.closing].filter(l=>l!==null).map(l=>structuredClone(q(l)))},get pendingPurchase(){return i.purchase?structuredClone(i.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=o.view;return d&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===d.runId&&l.nodeId===d.from.nodeId&&l.visit===d.from.visit&&l.revision===d.from.revision&&!i.closeRequested?structuredClone(d):null},settle:(...l)=>O(()=>i.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return nn(e,l)},async pageExperiments(l,I=[]){let C=o.generation;o.assertCurrent(C);let E=o.view?.id;if(!E)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let S=dn.parse(await h(fe.parse({operation:"page_experiments",release:l,usedReceiptIds:I})));if(o.assertCurrent(C),S.runId!==E||S.scope.projectId!==o.scope?.projectId||S.scope.environment!==o.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return S},review(l){return T({operation:"review",...l?{receiptId:l}:{}},o.nextRead())},async get(l,I){let C=o.generation;l=l&&structuredClone(l),I=I&&{...I},a&&await i.ready,o.assertCurrent(C),I??=i.purchase&&{receiptId:i.purchase.receiptId,operationId:i.purchase.operationId};let E=JSON.stringify([o.generation,g,l??null,I??null]),S=y.get(E);if(S)return S.then(k=>structuredClone(k));let F=o.nextRead(),b=N(T({operation:"get",...l?{data:l}:{},...I?{purchase:I}:{}},F));y.set(E,b);let P=()=>{y.get(E)===b&&y.delete(E)};return b.then(P,P),b.then(k=>structuredClone(k))},resume(l=o.view?.pendingRequest?.requestId){return l?i.closeRequested?D.settle(l):i.pending?.requestId===l?N(s(i.pending)):N(s({operation:"resume",requestId:l})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(l){return N(s(l))},async retry(){if(i.closeFlight)return i.closeFlight;if(i.closing)return s(i.closing);if(i.closeRequested&&i.pending)return D.settle(i.pending.requestId);if(i.inFlight)return N(i.inFlight);if(!i.pending)throw new m("INVALID_REQUEST","No command is pending");let l=i.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let I=o.generation;if(await D.settle(l.requestId),o.assertCurrent(I),!i.pending)return D.get();if(i.pending!==l||i.closeRequested)throw new m("COMMAND_PENDING","The original quote is being recovered")}return N(s(l))},identify(l){let I=o.customerToken?void 0:t;v(),o.identify(l),t=I,d=null,r.reset()},get identitySignal(){return o.signal},subscribe:o.subscribe,reset:R};return tn(D,(l,I)=>N(s(l,I))),D}function po(e,t){return Zn({...e,runToken:"",initialResponse:t})}export{un as a,Cn as b,pe as c,On as d,sn as e,kn as f,_t as g,kt as h,Dt as i,fe as j,dn as k,X as l,Vn as m,$t as n,dr as o,pr as p,In as q,xe as r,hr as s,Qn as t,hn as u,H as v,an as w,Fn as x,Tr as y,te as z,Se as A,qr as B,jr as C,xn as D,Zn as E,po as F};
1
+ import{a as tn}from"./chunk-REPLGJ4W.js";import{b as rn}from"./chunk-U63XQGMP.js";import{b as nn}from"./chunk-URSBR2ZU.js";import{d as We,e as ce}from"./chunk-M5V62FLG.js";import{c as qe,d as je,e as K,l as Ze}from"./chunk-VSWF46OO.js";import{A as Je,F as He,G as Qe,H as z,I as Ye,J as le,K as G,a as Me,c as Y,g as Z,h as Ge,i as Ue,m as $e}from"./chunk-O6ZYZM6E.js";import{A as ie,B as ae,z as oe}from"./chunk-7AWA6PKI.js";import{a as de,b as Xe}from"./chunk-35CGFRWR.js";import{a as j,b as _e,c as ke,e as De,h as Ve,i as Le,l as Be}from"./chunk-DDAP4VXQ.js";import{b as W}from"./chunk-CNWG4S72.js";import{a as Q}from"./chunk-CETHPZ2K.js";import{m as Ke,n as ue,o as ze,p as se}from"./chunk-ORIC64LN.js";import{g as Ee,m as Ce,w as re}from"./chunk-F3WIZE6M.js";import{b as Pe,d as L,e as Ae,f as Te}from"./chunk-RYCZEVTK.js";import{a as m}from"./chunk-46FG3J5X.js";import{h as V}from"./chunk-FOBN6LEV.js";import{a as en}from"./chunk-5MRSFLQA.js";import{b as n}from"./chunk-HI6KTEQA.js";import{a as on}from"./chunk-DSPLGTQI.js";import{c as Ne,f as Oe}from"./chunk-VPT5MFDG.js";function an(e){return Fn({...e,namespace:"commands",identity:[e.runToken]})}function Fn(e){let t,u,r=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),o=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let c=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??en).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",c));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,i=>i.toString(16).padStart(2,"0")).join("")});o.catch(()=>{});async function p(c){try{let a=await o;return await u.request(a,{mode:"exclusive"},()=>c(a))}catch(a){throw a instanceof m?a:r()}}function d(c){let a=t.getItem(c);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let i=JSON.parse(a);if(!i||typeof i!="object"||!("revision"in i)||!("entry"in i)||!Number.isSafeInteger(i.revision)||Number(i.revision)<0)throw r();return{revision:Number(i.revision),entry:i.entry}}return{read:()=>p(d),write:(c,a)=>p(i=>{if(d(i).revision!==c)return null;if(!Number.isSafeInteger(c+1))throw r();let y=JSON.stringify({revision:c+1,entry:a});if(y.length>1048576)throw r();return t.setItem(i,y),c+1})}}var un=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var M=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),En=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Cn=n.discriminatedUnion("type",[$e,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:M.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:He,openIn:Qe}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:M})]),Pn={id:M,presentation:Pe,outputs:n.array(M).max(250),inputs:se,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Ee,customerData:Ce,dataCursors:n.record(M,Ke.nullable())},Nn=n.strictObject({...Pn,content:n.strictObject({type:n.literal("document"),document:re})}),pe=n.strictObject({id:n.uuid(),source:un,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:M,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:En,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:ue,parameters:ze,variables:n.record(n.string(),L),output:L.nullable(),screen:Nn.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([We,ce]),quote:oe.nullable(),operation:ie.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Cn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),On=n.strictObject({scope:V,run:pe,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:oe.nullable(),operation:ie.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative(),document:re,answers:ue,inputs:se,values:n.record(n.string(),L).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=On.extend({run:pe.extend({paywall:pe.shape.paywall.unwrap().extend({resolution:ce}).nullable()})});var ln="X-Indiana-Server-Key";var An=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()}),Tn=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(An).max(200).default([]),iam:Ge.optional(),renderGuard:Z.optional()}),me=Tn.omit({variation:!0,description:!0,iam:!0}),_n=qe.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([me,me]).rest(me).refine(e=>e.length<=20)}),cn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(_n).max(100),savedGroups:je});var $=n.string().regex(/^[a-f0-9]{64}$/),Tt=n.strictObject({iam:$,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),kn=n.strictObject({release:$,render:Z,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),_t=n.strictObject({scope:V.extend({environmentId:n.uuid()}),release:$,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"]),delivery:Ue.optional(),target:kn})).max(4e3)}),kt=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:$,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Dt=n.strictObject({scope:V,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Vt=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)}),fe=n.strictObject({operation:n.literal("page_experiments"),release:$,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(Q).optional()}),dn=n.strictObject({scope:V,runId:n.uuid(),assignments:n.array(Dn.extend({receiptId:n.uuid()})).max(100),payload:cn});var U=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),mn=n.strictObject({entry:U,nodes:n.array(n.strictObject({id:U,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),U),writes:n.record(j,j),resources:n.strictObject({screenId:U.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)}),pn={scope:V,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:mn},X=n.discriminatedUnion("evaluationMode",[n.strictObject({...pn,evaluationMode:n.literal("local"),growth:K,conditions:n.record(U,n.array(n.strictObject({condition:Te,port:n.string()})))}),n.strictObject({...pn,evaluationMode:n.literal("remote")})]),Vn=X.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,ke),outputSchema:_e,terminals:n.record(U,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Je.nullable()}))})});function Ln(e){return mn.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(d=>d.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,d)=>{u[`case:${d}`]=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 o=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return o?.type==="feature"&&(r.featureKey=o.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 ge(e){let t=le.parse(e.document),u=e.evaluationMode==="local"?K.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:Ln(t)};return X.parse(e.evaluationMode==="remote"?r:{...r,growth:Ze(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(o=>o.type==="condition").map(o=>[o.id,o.cases.map((p,d)=>({condition:p.condition,port:`case:${d}`}))]))})}function $t(e){let t=ge(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=le.parse(e.document);return Vn.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let o=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:o&&o.type!=="literal"&&o.type!=="feature"&&o.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:o??null}]]}))}})}var Ie=32,Mn=522240;function ve(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()}),ye=n.record(n.string(),L),jn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:z.shape.schemaVersion,kind:z.shape.kind,selector:z.shape.selector,contract:z.shape.contract}),context:ye,removed:n.array(n.string()).max(100),attributes:ye,removedAttributes:n.array(n.string()).max(100),result:Ye,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()})}),Wt=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:qn,context:ye,steps:n.array(jn).min(1).max(Ie)}).refine(e=>Y(e)<=Mn,"Segment exceeds its byte budget");var Gn=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function J(e){return Array.isArray(e)?e.some(J):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&J(u):!Gn.test(t))}function fn(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(c=>c.id===t.screenId&&c.type==="paywall")))return"customer_required";let o=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(o&&["bundle","selection","offering"].includes(o.type)||t.type==="condition"&&t.cases.some(c=>J(c.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(c=>c.id===t.screenId):null]);for(let[c,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${c}`)||p.includes(JSON.stringify(c))))return"customer_required";if(t.type==="split"){let c=u.experiments?.[t.experimentId];if((c?.hashAttribute??"id")!=="funnelParticipantId"||J(c?.condition)||c?.parentConditions?.length)return"customer_experiment_required"}let d=t.type==="feature"?t.featureKey:o?.type==="feature"?o.featureKey:void 0;return d&&u.features?.[d]?.rules?.some(c=>(c.hashAttribute??"id")!=="funnelParticipantId"||J(c.condition)||c.parentConditions?.length)?"customer_experiment_required":null}var he=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},ee=(e,t)=>new he(e,t),Un=e=>({experiments:e.experiments,features:e.features});function we(e,t=ee){let u=new Map(e.topology.nodes.map(d=>[d.id,d])),r=Ne(e.growth.savedGroups),o=Un(e.growth);function p(d,c){if(!Object.hasOwn(e.growth.features,d))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Oe(d,c).value}return{nodes:u,savedGroups:r,features:o.features,feature:p,evaluate(d,c){let a=u.get(d);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let i,g;if(a.type==="condition"){let v=e.conditions[a.id];if(!v)throw t("INVALID_RESPONSE","Local condition rules are unavailable");i=de({id:a.id,name:a.id,type:"condition",cases:v.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},c,o.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,c),i="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 h=de({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},c,o.experiments);g=h.value,i=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,c),i=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[i]??(i==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:d,port:i,target:y,...g===void 0?{}:{value:g}}}}}function dr(e,t,u,r=ee){return be(e,r)(t,u)}function be(e,t){let u=X.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,o=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};o();let p=we(u,t);return(d,c)=>(o(),Bn(p,d,c))}function Bn(e,t,u){let r=Ae.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:o,onFeatureUsage:p,onExperimentViewed:d}=u,c={attributes:r,...o?{saveStickyBucketAssignmentDoc:a=>o(structuredClone(a))}:{},...p?{onFeatureUsage:(a,i)=>p(a,structuredClone(i))}:{},...d?{onExperimentViewed:(a,i)=>d(structuredClone(a),structuredClone(i))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,c)}function pr(e,t,u,r=ee){return gn(be(e,r),t,u)}function gn(e,t,u){let r=[],o=[],p=[],d=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(c){let a=r.findIndex(y=>y.next.attributeName===c.attributeName&&y.next.attributeValue===c.attributeValue),i=c.attributeName+"||"+c.attributeValue,g={expected:u.sticky[i]??null,next:c};a<0?r.push(g):r[a]=g},onExperimentViewed(c,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&o.push(L.parse({key:c.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(c,a){p.push(L.parse({feature:c,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:d.port,...d.value===void 0?{}:{value:d.value},sticky:r,exposures:o,features:p}}function yn(e,t,u,r=ee){let o=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),d=structuredClone(u.variables),c=structuredClone(o.sticky),a=[],i=u.nodeId,g=u.visit,y=!1,v,h=O=>fn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},o.attributes.funnelCustomerBound===!0),R=O=>(v??=be(e,r),gn(v,O,{attributes:Be({declarations:t.variables,attributes:o.attributes,parameters:u.parameters,answers:u.answers,results:d,savedGroups:{}}),sticky:c}));for(let O=0;O<Ie;O++){let s=p.get(i);if(!s||!ve(s)||h(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 f,w;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")f=R(s.id),s.type==="offering"&&(f.value={type:"offering_version",id:String(f.value)}),s.type==="condition"?w=f.port==="default"?s.default:s.cases[Number(f.port.slice(5))]?.target:s.type==="split"?w=f.port==="notParticipating"?s.notParticipating:s.routes[f.port]:(s.type==="feature"||s.type==="offering")&&(w=s.next);else if(f={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(w=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(f.value={type:"offering_version",id:s.configuration.versionId},w=s.next),s.type==="end"||s.type==="output"){let x=s.type==="end"?s.output:s.value;if(f=x?.type==="feature"?R(s.id):{...f,port:"value",value:x?.type==="literal"?x.value:x?.type==="variable"?Me({source:"variable",key:x.key,...x.path?{path:x.path}:{}},{declarations:t.variables,answers:u.answers,results:d,parameters:u.parameters,attributes:o.attributes,savedGroups:{}}):null},x&&(f.value===void 0||!De(t.outputSchema,f.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let N=[...a,{nodeId:i,result:f}];if(Y({steps:N})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:i,result:f}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let x=s.type==="coupons"?s.couponIds.map(D=>({type:"reward",id:D})):s.type==="coupon"?{type:"reward",id:s.couponId}:f.value;if(x===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=Ve(s,{value:x});Le(t.variables,s,_),Object.assign(d,_)}for(let x of f.sticky)c[`${x.next.attributeName}||${x.next.attributeValue}`]=structuredClone(x.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!w)throw r("INVALID_RESPONSE","Local pure exit is unavailable");i=w,g++}let T=p.get(i);return{steps:a,...!y&&T&&(!ve(T)||h(T))?{boundary:{nodeId:i,visit:g}}:{}}}function In(e,t){let u=sn.safeParse(t);if(!u.success)throw new m("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 m("SCOPE_MISMATCH","Funnel scope changed");return r}var xe=(e,t)=>new m(e,t);function hr(e){return we(e,xe)}var Kn=3,zn=2e3;function $n(e){return e instanceof TypeError||e instanceof m&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Jn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===Kn||!$n(u))throw u;await new Promise(r=>setTimeout(r,t*zn))}}async function Re(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 m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let o=null,p;if(u)try{let d=await e.funnel(t.source.id,t.source.versionId);p=d.manifest.generation,o=Hn(e,t,d)}catch{o=null}return p??=e.snapshot?.generation??(await Jn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:o}}function Hn(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:o,remoteFeatures:p,...d}=u.growth,c=ge({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:K.parse(d)}),a=Qn(c,u.document,{...t,...r}),i=a.steps.at(-1),g=a.boundary??(i?.result.port==="value"?{nodeId:i.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 yn(e,t,u,xe)}var vn=G.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 m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),hn=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:vn.optional(),closeCommand:vn.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 m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),ne=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function H(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 wn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),o=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:hn.parse(a.entry)}}function d(a){let i=o.then(a);return o=i.catch(()=>{}),i}async function c(a){for(let i=0;i<4;i++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(ne(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 i=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==i)throw A();u=i},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let i=hn.parse(a),g=i.command;return!g||u!==null&&r(i)!==u?Promise.reject(A()):(u??=r(i),d(()=>c((y,v)=>{if(y&&!ne(r(y),r(i)))throw A();if(y&&i.processBindingIds){for(let[h,R]of Object.entries(i.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==R)throw A();y={...y,processBindingIds:{...y.processBindingIds,...i.processBindingIds}}}if(!y){if(v!==t&&g.operation!=="close")throw A();return i}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&&!ne(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!ne(y.command,g))throw A();return y})))},observePurchase(a,i,g,y){return d(()=>c((v,h)=>{if(!v&&h!==t||v&&r(v)!==r({...a,schemaVersion:1}))throw A();if(v?.purchase&&v.purchase.generation>i.generation)return H(v,y);if(v?.purchase&&v.purchase.generation===i.generation&&v.purchase.operationId!==i.operationId)throw A();return g?!v?.purchase||v.purchase.operationId!==i.operationId?H(v,y):H(v.command?{...v,purchase:void 0}:null,y):H({schemaVersion:1,...a,...v,purchase:i},y)}))},settle(a){return d(()=>c(i=>H(i,a)))}}}function Tr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function te(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((o,p)=>te(o,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(([o,p])=>Object.hasOwn(t,o)&&te(p,Reflect.get(t,o)))}function bn(e,t){let u=t&&{...t},r=null,o=0,p=-1,d=0,c=new AbortController;function a(){d++,c.abort(new m("IDENTITY_CHANGED","Run identity changed")),c=new AbortController}let i=!1,g,y=0,v=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new m("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return p===d?r:null},get viewAgeMs(){return r&&p===d?performance.now()-o:void 0},get generation(){return d},get signal(){return c.signal},get disposed(){return i},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,R="Run identity changed during the request"){if(h!==d||i)throw new m("IDENTITY_CHANGED",R)},assertRun(h){if(r&&(h.id!==r.id||h.source.type!==r.source.type||h.source.id!==r.source.id||h.source.versionId!==r.source.versionId||h.locale!==r.locale||!te(h.parameters,r.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,R,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&R.run.revision<=r.revision)&&!(r&&R.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!R.run.stopped&&["running","waiting"].includes(R.run.status)&&r&&p===d&&R.run.nodeId===r.nodeId&&R.run.visit===r.visit&&R.run.revision===r.revision&&(R.run.screen=r.screen,(r.paywall?.quote?.operationId===R.review?.activeOperationId||!r.paywall?.quote&&R.review?.activeOperationId===null)&&(R.run.paywall=r.paywall)),!(r?.paywall&&R.run.paywall&&r.paywall.receiptId===R.run.paywall.receiptId&&(R.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||R.run.revision>=r.revision)r=R.run,o=performance.now(),p=d;else if(!s)return;if(r&&p===d)for(let f of v)try{f(structuredClone(r))}catch{}}},identify(h){if(i)throw new m("IDENTITY_CHANGED","Controller was reset");if(!Q.test(h))throw new m("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return v.add(h),()=>v.delete(h)},reset(){i||(i=!0,a(),g=void 0,r=null,v.clear())}}}var Se=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function qr(e,t,u="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",t);if(!Se.test(e))throw new m("INVALID_TOKEN",u)}function jr(e){let t=W(e);return t.identify(e.apiKey),t}function xn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&!ae(t)&&["apple","google"].includes(t.provider)?"native":t&&!ae(t)&&t.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new m("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function q(e){let{customerToken:t,...u}=e;return u}var Yn=e=>!(e instanceof m&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Rn({journal:e,state:t,call:u,processIdentity:r}){let o=null,p=null,d=!1,c={command:null,close:null},a=new Set,i,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(w=>w&&!Object.hasOwn(s.processBindingIds??{},w.requestId)))throw new m("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 m("SCOPE_MISMATCH","Pending command belongs to another scope");if(i=s.purchase,d=s.closed===!0,!s.command)return;let f=s.command;o=f.operation==="close"?null:f,p=f.operation==="close"?f:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(d=!0);for(let w of[o,p])w&&a.add(w.requestId)}):Promise.resolve();y.catch(()=>{});async function v(s,f){e&&await y;let w=t.generation;if(e){if(!t.view||!t.scope)throw new m("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:q(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(w!==t.generation||o!==s&&p!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");if(e&&on(f),t.assertCurrent(w),o!==s&&p!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let N=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(x){let _=s.operation==="submit"&&s.input.type==="paywall_quote",D=!N&&!Yn(x),l=!1;if(_&&D&&w===t.generation&&o===s&&x instanceof m&&x.status!==void 0){let I=await T(s.requestId).catch(()=>{});l=I?.settlement?.state==="unknown"&&I.settlement.operationId===null}throw w===t.generation&&(o===s||p===s)&&D&&(!_||!(x instanceof m)||x.status===void 0||l)&&(e&&await e.settle(s.requestId),w===t.generation&&O(s)),x}}function h(s,f){let w=G.parse(s);if(w.operation==="start"||w.operation==="get"||w.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(d&&w.operation!=="close"){if(o?.requestId===w.requestId)return T(w.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(w.operation==="close"){if(o?.requestId===w.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(d=!0,p&&JSON.stringify(q(p))!==JSON.stringify(q(w)))throw new m("COMMAND_PENDING","Retry the original Close");return p??=w,c.close?c.close:R(p,"close",f)}if(o){if(JSON.stringify(q(o))!==JSON.stringify(q(w)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(c.command)return c.command}else o=w;return R(o,"command",f)}function R(s,f,w){let N=v(s,w);c[f]=N;let x=()=>{c[f]===N&&(c[f]=null)};return N.then(x,x),N}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||o!==s&&p!==s?!1:(o===s&&(o=null),p===s&&(p=null),a.delete(s.requestId),!o&&!p&&(g=null),!0)}return{ready:y,get pending(){return o},get closing(){return p},get closeRequested(){return d},get inFlight(){return c.command},get closeFlight(){return c.close},get purchase(){return i},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,f,w,N){let x=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=x&&f.settlement?.state==="settled"&&f.run.pendingRequest?.requestId!==x&&(s.operation==="get"||!d||s.operation==="close"||!["running","waiting"].includes(f.run.status))?x:void 0,D=o?.requestId===_?o:p?.requestId===_?p:void 0;e?.bind({scope:f.scope,runId:f.run.id,funnelId:f.run.source.id,versionId:f.run.source.versionId});let l=f.run.paywall,I=l??f.purchase,C=I?.operation,E=f.settlement&&(!l||l.purchaseRequestId===f.settlement.requestId)&&(!i||i.operationId===f.settlement.operationId)?f.settlement:void 0,S=C?.operationId??I?.quote?.operationId??E?.operationId,F=I?.receiptId??E?.receiptId,b=l?.selectionGeneration??i?.generation??0;if(e&&S&&F&&s.operation!=="review"&&(!t.view||f.run.revision>=t.view.revision)&&(N===void 0||N>=t.readSequence)&&(!i||b>=i.generation)){let P={receiptId:F,operationId:S,generation:b},k=rn(C,I?.canReselect===!0);await e.observePurchase({scope:f.scope,runId:f.run.id,funnelId:f.run.source.id,versionId:f.run.source.versionId},P,k,_),t.assertCurrent(w),(!i||P.generation>=i.generation)&&(N===void 0||N>=t.readSequence)&&(k?i?.operationId===P.operationId&&(i=void 0):i=P)}else e&&_&&await e.settle(_);return t.assertCurrent(w),_?O(D):!1},stop(){d=!0},submit:h,settle:T,reset(){d=!0,o=null,p=null,i=void 0,g=null,c.close=null,a.clear(),c.command=null}}}function Zn(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 m("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new m("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Se.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=W({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),o=bn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(R),d=null,c=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?an(e):void 0),a=c&&wn(c),i=Rn({journal:a,state:o,call:T,processIdentity:e.process}),g=0,y=new Map;function v(){g++,y.clear(),t=void 0}async function h(l){let I=l.operation==="resume"?i.pending?.operation==="resume"?null:i.pending:l;if(u&&l.operation==="resume"&&!I&&l.requestId!==e.customerRun?.startRequestId)throw new m("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(I?.operation==="submit"&&I.input.type==="paywall_confirm"){let P=o.view?.paywall;xn(u,P?.quote?.operationId===I.input.operationId?P.quote:void 0)}if(e.process)return e.process.request(l);let C=o.generation;o.assertCurrent(C);let E=performance.now()+(e.timeoutMs??35e3),S=o.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let P=o.signal,k,B=()=>{},Sn=new Promise((Wn,Fe)=>{B=()=>Fe(P.reason),P.addEventListener("abort",B,{once:!0}),k=setTimeout(()=>Fe(new m("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(o.assertCurrent(C),e.session.access())),Sn])}finally{clearTimeout(k),P.removeEventListener("abort",B)}}o.assertCurrent(C);let F={...l,...S?{customerToken:S}:{}},b=l.operation==="page_experiments"?fe.parse(F):G.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!S)throw new m("IDENTITY_CHANGED","Original recovery Customer changed");let P={...b};return"customerToken"in P&&delete P.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:P},S,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",b,e.runToken,{headers:e.serverKey&&!S?{[ln]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function R(){v(),p?.(),o.reset(),i.reset(),d=null,r.dispose()}async function T(l,I){let C=t;t=void 0;let E=o.generation,S=()=>o.assertCurrent(E);a&&await i.ready,S();let F=o.view,b=In(e,C!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?C:await h(l));if(l.operation==="review"&&!b.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&b.run.id!==e.customerRun.runId)throw new m("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&b.purchase&&(b.purchase.receiptId!==l.purchase.receiptId||(b.purchase.operation?.operationId??b.purchase.quote?.operationId)!==l.purchase.operationId))throw new m("INVALID_RESPONSE","The requested original purchase changed");if(S(),b.runToken&&b.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let P=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(P&&b.settlement?.requestId!==P)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");i.assertBinding(b),o.assertRun(b.run),o.bindScope(b.scope);let k=await i.observe(l,b,E,I);return(!o.view||b.run.revision>=o.view.revision)&&(I===void 0||I>=o.readSequence)&&(await e.onAcceptedResponse?.(b),S()),!b.run.stopped&&["running","waiting"].includes(b.run.status)&&l.operation==="get"&&l.settlementRequestId||(S(),["running","waiting"].includes(b.run.status)||i.stop(),o.publish(l,b,F,I,k)),b}function O(l){let I=o.generation;v();let C=l(),E=()=>{o.generation===I&&v()};return C.then(E,E),C}let s=(l,I)=>O(()=>i.submit(l,I)),f=null,w=new WeakMap;function N(l){let I=w.get(l);if(I)return I;let C=_(l);return w.set(l,C),C}let x=!1;async function _(l){let I=await l;if(I.run.instruction?.type!=="evaluate_segment")return I;if(f)return f;x=!0;let C=o.generation,E=(async()=>{for(let S=0;S<32&&I.run.instruction?.type==="evaluate_segment";S++){if(i.pending||i.closeRequested)return I;let F=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:P}=await Re(e.configuration,F,{predict:!1});if(C!==o.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(i.pending||i.closeRequested)return I;if(o.view&&(o.view.revision!==F.revision||o.view.visit!==F.visit||o.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Re(e.configuration,F).then(({prediction:B})=>{k&&C===o.generation&&!i.closeRequested&&o.view?.id===F.id&&!o.view.stopped&&o.view.nodeId===F.nodeId&&o.view.visit===F.visit&&o.view.revision===F.revision&&(d=B)}).catch(()=>{});try{I=await s({operation:"commit_segment",requestId:Xe(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...P})}finally{k=!1,d=null}}}return I})();f=E;try{return await E}finally{f===E&&(f=null)}}let D={get configuration(){return x?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=o.currentView;return l?structuredClone(l):null},get viewAgeMs(){return o.viewAgeMs},get pendingCommand(){let l=i.closing??i.pending;return l?structuredClone(q(l)):null},get pendingCommands(){return[i.pending,i.closing].filter(l=>l!==null).map(l=>structuredClone(q(l)))},get pendingPurchase(){return i.purchase?structuredClone(i.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=o.view;return d&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===d.runId&&l.nodeId===d.from.nodeId&&l.visit===d.from.visit&&l.revision===d.from.revision&&!i.closeRequested?structuredClone(d):null},settle:(...l)=>O(()=>i.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return nn(e,l)},async pageExperiments(l,I=[]){let C=o.generation;o.assertCurrent(C);let E=o.view?.id;if(!E)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let S=dn.parse(await h(fe.parse({operation:"page_experiments",release:l,usedReceiptIds:I})));if(o.assertCurrent(C),S.runId!==E||S.scope.projectId!==o.scope?.projectId||S.scope.environment!==o.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return S},review(l){return T({operation:"review",...l?{receiptId:l}:{}},o.nextRead())},async get(l,I){let C=o.generation;l=l&&structuredClone(l),I=I&&{...I},a&&await i.ready,o.assertCurrent(C),I??=i.purchase&&{receiptId:i.purchase.receiptId,operationId:i.purchase.operationId};let E=JSON.stringify([o.generation,g,l??null,I??null]),S=y.get(E);if(S)return S.then(k=>structuredClone(k));let F=o.nextRead(),b=N(T({operation:"get",...l?{data:l}:{},...I?{purchase:I}:{}},F));y.set(E,b);let P=()=>{y.get(E)===b&&y.delete(E)};return b.then(P,P),b.then(k=>structuredClone(k))},resume(l=o.view?.pendingRequest?.requestId){return l?i.closeRequested?D.settle(l):i.pending?.requestId===l?N(s(i.pending)):N(s({operation:"resume",requestId:l})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(l){return N(s(l))},async retry(){if(i.closeFlight)return i.closeFlight;if(i.closing)return s(i.closing);if(i.closeRequested&&i.pending)return D.settle(i.pending.requestId);if(i.inFlight)return N(i.inFlight);if(!i.pending)throw new m("INVALID_REQUEST","No command is pending");let l=i.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let I=o.generation;if(await D.settle(l.requestId),o.assertCurrent(I),!i.pending)return D.get();if(i.pending!==l||i.closeRequested)throw new m("COMMAND_PENDING","The original quote is being recovered")}return N(s(l))},identify(l){let I=o.customerToken?void 0:t;v(),o.identify(l),t=I,d=null,r.reset()},get identitySignal(){return o.signal},subscribe:o.subscribe,reset:R};return tn(D,(l,I)=>N(s(l,I))),D}function po(e,t){return Zn({...e,runToken:"",initialResponse:t})}export{un as a,Cn as b,pe as c,On as d,sn as e,kn as f,_t as g,kt as h,Dt as i,fe as j,dn as k,X as l,Vn as m,$t as n,dr as o,pr as p,In as q,xe as r,hr as s,Qn as t,hn as u,H as v,an as w,Fn as x,Tr as y,te as z,Se as A,qr as B,jr as C,xn as D,Zn as E,po as F};
@@ -0,0 +1 @@
1
+ import{b as Qn}from"./chunk-6FL4QVU5.js";import{a as gn}from"./chunk-NPFQD4WY.js";import{a as Un,b as Mn,c as wn,d as yn,e as $e,f as xn,h as zn,i as Bn,j as Jn,k as Gn}from"./chunk-FEOTHBMD.js";import{a as Wn}from"./chunk-45PGU2HW.js";import{a as Hn}from"./chunk-W32FI2A2.js";import{c as Ln,e as Nn,f as _n,i as Vn,j as He,k as tn,l as $n,m as rn}from"./chunk-RWZZAFR7.js";import{b as On}from"./chunk-REPLGJ4W.js";import{a as mn,d as qn}from"./chunk-U63XQGMP.js";import{C as Sn}from"./chunk-F3WIZE6M.js";import{a as te}from"./chunk-46FG3J5X.js";import{a as be}from"./chunk-DSPLGTQI.js";function jn(i){let C=new Set,_=new Set,n=null;async function p(a,f){let L=!1;for(;!i.stopped&&i.key===a&&i.client.pendingCommand?.requestId===f;){if(!i.client.settle)throw new te("COMMAND_PENDING","The original display acknowledgement is still pending");await i.client.settle(f),L=!0,i.client.pendingCommand?.requestId===f&&await new Promise(S=>setTimeout(S,1500))}i.stopped||i.key!==a||(L&&await i.client.get(),!(i.stopped||i.key!==a)&&C.add(a))}function T(a,f){n=f;let L=()=>{n===f&&(n=null),_.delete(a)};return f.then(L,S=>{L(),i.busy||i.fail(S)}),f}function X(a){if(i.reviewing||C.has(a)||_.has(a)||i.stopped)return;_.add(a);let f=async()=>{if(i.reviewing||i.stopped||i.key!==a||C.has(a)){_.delete(a);return}if(i.busy||i.client.pendingCommand){setTimeout(()=>{f()},250);return}let L=(async()=>{if(i.staleRead){if(await i.staleRead,i.stopped||i.key!==a)return;if(i.client.pendingCommand){setTimeout(()=>{f()},250);return}}let S=i.client.view,de=i.expected(),U=de.requestId;try{await i.client.submit({operation:"shown",...de})}catch(o){if(!(o instanceof te)||o.code!=="CONFLICT"||o.status!==409||i.client.pendingCommand)throw o;await i.client.get();let u=i.client.view;if(i.stopped||i.reviewing||i.key!==a||!u||!S||u.id!==S.id||u.source.versionId!==S.source.versionId||u.nodeId!==de.nodeId||u.visit!==de.visit||u.revision<=de.revision||u.stopped||!u.screen&&(!u.paywall||u.paywall.receiptId!==S.paywall?.receiptId)||!["running","waiting"].includes(u.status)||i.client.pendingCommand)throw o;let P=i.expected();U=P.requestId,await i.client.submit({operation:"shown",...P})}await p(a,U)})();T(a,L)};f()}function g(){if(n)return n;let a=i.client.pendingCommand;if(a?.operation!=="shown")return null;let f=i.key;return _.add(f),T(f,(async()=>{await i.client.retry(),await p(f,a.requestId)})())}return{report:X,settled:g,get inFlight(){return n}}}function Yn(i){let C={},_=new Map;async function n(p){let T=i.client.view,X=T?.screen,g=X?.customerData.nodes[p.nodeId];if(i.stopped||i.busy||!T||!X||!g)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(p.action)){let o=i.document,u=o?Sn(o,p.nodeId):null,P=u?.type==="customer_data"?u.data.outputs?.[p.action]:void 0;P&&X.outputs.includes(P)?await i.perform(()=>i.client.submit({operation:"submit",...i.expected(),input:{type:"screen",output:P,answers:i.answers,selection:p.value?{[p.nodeId]:p.value}:{}}})):await i.onIntent?.(p,T);return}let f=p.action.startsWith("sources_")?g.resources.find(o=>o.key===p.value):null;if(p.action.startsWith("sources_")&&!f)throw new te("INVALID_REQUEST","Choose a current resource");let L=`${T.visit}:${p.nodeId}:${f?.key??""}`,S=_.get(L)??[null],U=C[p.nodeId]??{page:1,after:null,filter:"all",...f?{resourceKey:f.key}:{}};if(p.action==="filter"){let o=p.value;if(!o||!(g.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(o))throw new te("INVALID_REQUEST","Unknown data filter");U={page:1,after:null,filter:o},S.splice(0,S.length,null)}else if(p.action==="next"||p.action==="sources_next"){let o=f?.sources.at(-1),u=f?o?{kind:"ledger",cursor:{at:o.detail[0],id:o.id,type:"source"}}:null:X.dataCursors[p.nodeId];if(!u||!f&&!g.hasNext)return;S[U.page]=u,U={...U,page:U.page+1,after:u}}else if(p.action==="previous"||p.action==="sources_previous"){if(U.page<=1)return;U={...U,page:U.page-1,after:S[U.page-2]??null}}_.set(L,S),C={...C,[p.nodeId]:U},await i.perform(()=>i.client.get({nodeId:T.nodeId,visit:T.visit,revision:T.revision,components:C}))}return{get queries(){return C},intent:n,reset(){C={},_.clear()}}}function Xn(i){let{doc:C,holder:_,reviewHolder:n,mountScreenPreview:p}=i,T=!1,X,g=0,a=null,f="",L,S=new Map,de=u=>u?`${u.id}:${u.nodeId}:${u.visit}:${u.revision}:${u.paywall?.quote?.operationId??""}`:"";async function U(u){if(i.stopped||!i.client.review||T&&u===X&&L?.active)return;let P=!T||u!==X;T||(f=de(i.client.view),S.set(f,structuredClone(i.answers))),T=!0,X=u,_.hidden=!0,i.suspend(!0),n.hidden=!1;let c=++g;P&&(L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),L=tn(n,i.loadingOptions,"funnel",()=>{o()}));let A=P?L:void 0;try{if(A?.start(!1,i.client.view?.locale),c!==g||i.stopped)return;let N=i.client.review(u),j=await(A?.wait(N,He)??N);if(i.stopped||c!==g||!T)return;if(!j.review)throw new te("INVALID_RESPONSE","Historical projection is missing");a?.destroy(),a=null,A||n.replaceChildren();let M=C.createElement("div"),ye=A?rn(M,n):()=>{};n.append(M);let O=j.run.locale.startsWith("zh"),q=i.chrome;M.style.cssText=q.history;let R=C.createElement("p");R.textContent=O?"只读回看":"Read-only history",R.style.cssText=q.historyTitle,M.append(R);let Z=C.createElement("p");Z.style.cssText=q.historyNote,Z.textContent=j.review.pages.length?O?"选择一页查看当时的内容,回看不会改动任何信息。":"Choose a page to see it as it was. Nothing here can be changed.":O?"还没有可回看的页面。":"There are no earlier pages yet.",M.append(Z);let D=j.review.page?.receiptId,Ie=C.createElement("div");Ie.style.cssText=q.historyPages;for(let[E,x]of j.review.pages.entries()){let k=C.createElement("button");k.type="button",k.textContent=O?`第 ${E+1} 页`:`Page ${E+1}`;let J=D!==void 0&&x.receiptId===D;k.style.cssText=J?q.primary:q.secondary,J&&k.setAttribute("aria-current","page"),$e(k,()=>i.chrome.focus),k.onclick=()=>{U(x.receiptId)},Ie.append(k)}if(Ie.childElementCount&&M.append(Ie),j.review.page){let E=j.review.page,x=C.createElement("div");x.inert=!0,x.style.cssText=q.historyPage,M.append(x),a=p(x,{mode:"live",rendererUrl:i.client.webViewUrl,title:E.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{c===g&&!i.stopped&&A?.present(ye)},onError:J=>{if(c!==g||i.stopped)return;let Te=new Error(J);A?.finish("error",Te),a?.destroy(),a=null,M.remove(),i.fail(Te)},onEscape:()=>{o()}});let k=a;if(k.update(E.document,j.run.locale,{serverInput:{bindings:E.inputs,answers:E.answers,values:E.values}}),await k.ready,i.stopped||c!==g||!T)return}let Le=O?{issued:"已领取",reserved:"已预留",redeemed:"已使用",expired:"已过期",revoked:"已撤销",unknown:"状态待确认"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},ae=C.createElement("div");ae.style.cssText=q.historyRecords;for(let E of[...j.review.coupons.map((x,k)=>`${O?"优惠券":"Coupon"} ${k+1}: ${Le[x.status]}`),...j.review.purchases.map((x,k)=>`${O?"购买":"Purchase"} ${k+1}: ${Gn(x.status,O)}`)]){let x=C.createElement("p");x.textContent=E,x.style.margin="0",ae.append(x)}ae.childElementCount&&M.append(ae),j.review.page||A?.present(ye),i.client.view&&await i.enqueue(i.client.view)}catch(N){if(c!==g||i.stopped)return;A?.finish("error",N),a?.destroy(),a=null,n.replaceChildren(),i.fail(N)}}async function o(){if(!T||i.stopped||!i.client.review)return;let u=++g;L?.finish("dismissed");try{if(await i.client.review(),i.stopped||u!==g)return;T=!1,g++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,_.hidden=!1;let P=i.client.view;de(P)!==f?(S.set(f,structuredClone(i.answers)),i.resetScreen()):(S.delete(f),i.suspend(!1)),P&&await i.enqueue(P)}catch(P){if(u!==g||i.stopped)return;a?.destroy(),a=null,n.replaceChildren(),i.fail(P)}}return{get active(){return T},get receipt(){return X},open:U,exit:o,get drafts(){return new Map([...S].map(([u,P])=>[u,structuredClone(P)]))},stop(){T=!1,g++,L?.finish("dismissed"),a?.destroy(),a=null,n.replaceChildren(),n.hidden=!0,_.hidden=!1}}}var hn=5e3,it="position:absolute;width:1px;height:1px;margin:-1px;padding:0;border:0;overflow:hidden;clip-path:inset(50%);white-space:nowrap";async function rt(i,C,_){let n=C,p=n.prepared&&Qn(n.prepared),T=()=>{},X;function g(){n.prepared&&n.prepared.state!=="adopted"&&p?.release()}let a=()=>n.prepared?.state==="shown"&&!!p?.modal,f=n.client.identitySignal,L;try{L=await Promise.all([import("./screen-renderer-POUJYMIZ.js"),import("./paywall-Z6F2GGOB.js")]),n.signal?.throwIfAborted(),f?.throwIfAborted()}catch(e){throw g(),e}let[{mountScreenPreview:S},{showPaywall:de}]=L,U=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.appManifestRelease?Wn({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;U?.start();let o=i.ownerDocument,u=Vn(o),P=!1,c=o.createElement("section"),A=o.createElement("div"),N=o.createElement("div"),j=o.createElement("div"),M=o.createElement("button");j.hidden=!0,M.type="button";let ye=o.createElement("p"),O=o.createElement("p"),q=o.createElement("button"),R=o.createElement("button"),Z=o.createElement("button"),D=o.createElement("dialog"),Ie,Le=!1;c.dataset.indianaFunnel="",c.dataset.longplayCloseOwner="sdk",c.setAttribute("aria-busy","false"),ye.setAttribute("role","status"),O.setAttribute("role","alert"),O.hidden=!0,q.type=R.type=Z.type="button",N.append(q,M,ye,O,Z,R),c.append(A,j,N),i.append(c);let ae=Mn,E=wn(ae),x="",k=(o.documentElement.lang||"").startsWith("zh"),J,Te="",Me,vn=!1;for(let e of[q,M,Z,R])$e(e,()=>E.focus);function In(){let e=k?"关闭":"Close";R.parentElement===D?(R.textContent="×",R.setAttribute("aria-label",e),_n(R,ae)):(R.textContent=e,R.removeAttribute("aria-label"),R.style.cssText=E.link+";margin-inline-start:auto")}function xe(e){let t=e?.screen?.content.document.theme??ae,r=JSON.stringify([t.primary,t.background,t.text,t.radius,t.font,R.parentElement===D]);if(r===x)return;x=r,ae=t;let h=R.parentElement===D;E=wn(ae,h),c.style.cssText=E.root+";min-width:0"+(h?";display:flex;flex-direction:column;min-height:100%":""),N.style.cssText=E.bar+(h?";margin-top:auto":""),N.hidden&&(N.style.display="none"),q.style.cssText=M.style.cssText=E.secondary,Z.style.cssText=E.primary,ye.style.cssText=E.status,O.style.cssText=E.alert,In(),yn(q)}function Ce(){let e=R.parentElement===D,t=q.hidden&&M.hidden&&Z.hidden&&O.hidden&&(R.hidden||R.parentElement!==N),r=e&&vn&&t;N.hidden=t&&!ye.textContent,N.style.cssText=E.bar+(e?";margin-top:auto":"")+(r?`;${it}`:""),N.style.display=N.hidden?"none":"flex",J?.responsive&&Me!==void 0&&J.setContentHeight(Me+(r?0:N.getBoundingClientRect().height))}xe();let ue=null,v=null,ie=null,ge="",ne="",Pe=!1,ze="",on="",Be="",s=!1,Y=0,Je=!1,bn="",sn=null,an=Promise.resolve(),Cn=!n.client.view,Ne,ln=!1,F=_,Ge=n.hostPaywallTarget,Ae,_e,Qe="",We,re=!1,Re=null,pe=!1,je=()=>n.client.pendingCommand?.operation==="close",oe=null,V=null,dn=Hn({document:o,run:async()=>{(!v?.observing||n.client.pendingCommand)&&await cn()},delay:()=>{if(!se.pending&&!(s||!ie||!["running","waiting"].includes(ie.status)&&!n.client.pendingCommand)&&!(v?.observing&&!n.client.pendingCommand))return ie.pendingRequest||n.client.pendingCommand?1500:hn},hiddenDelay:()=>!s&&!se.pending&&n.client.pendingCommand?15e3:void 0}),z=null;function un(){return V&&n.client.hasDurableJournal===!0&&z?.acknowledged===!0&&z.operationId===V.operationId&&n.client.view?.id===z.runId&&n.client.view?.status==="closed"&&n.client.view.revision===z.revision+1&&!(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0))&&!n.client.pendingPurchase?V:null}function Pn(e){let t=e.run.paywall;if(z&&e.settlement?.requestId===z.requestId&&e.settlement.state==="settled"&&e.settlement.operationId===null&&e.run.id===z.runId&&e.run.status==="closed"&&!e.run.pendingRequest&&e.run.revision===z.revision+1&&e.run.nodeId===z.nodeId&&e.run.visit===z.visit&&t?.receiptId===z.receiptId&&t.selectionGeneration===z.selectionGeneration&&(t.quote?.operationId??null)===z.operationId&&(t.operation?.operationId??t.quote?.operationId??null)===z.operationId){let r=z.operationId===null&&t.selectionGeneration===0&&!t.quote&&!t.operation&&!t.purchaseRequestId,h=mn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect});(r||t.canReselect===!0&&h.type==="native")&&(z.acknowledged=!0)}}let Ee=null,Ue=new Set,fe={},De=!1,K=(e,t=null)=>{s||(e instanceof te&&e.status===409&&e.reason==="STATE_CHANGED"&&e.recovery==="recover_operation"&&dn.destroy(),Ee=t,De=!1,O.textContent=xn(e,k),O.hidden=!1,Z.hidden=n.client.pendingCommand===null,Ce(),be(n.onError,e))},se=On({client:n.client,document:o,conceal(){s||(me(),F?.finish("dismissed"),c.hidden=!0,P||(P=!0,u()))},async receive(e){s||await le(n.client.view??e.run)},failed(e){if(!s){if(!se.pending){pe=!1;let t=n.client.view;t&&le(t).then(()=>K(e),K);return}Ke(),c.parentElement!==i&&i.append(c),c.hidden=!1,q.hidden=M.hidden=R.hidden=!0,ye.textContent="",xe(),K(e,n.client.pendingCommand?.requestId??null)}}}),Rn=()=>{s||(Ee=null,O.textContent=Bn(k),O.hidden=!1,Z.hidden=!0,Ce())};function ke(){let e=n.client.view;if(!e)throw new te("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}let w=Xn({client:n.client,doc:o,holder:A,reviewHolder:j,mountScreenPreview:S,loadingOptions:n,get chrome(){return E},get stopped(){return s},get answers(){return fe},suspend(e){v?.setSuspended(e)},resetScreen(){ge="",ne="",ze=""},enqueue:le,fail:K}),Ve=jn({client:n.client,expected:ke,fail:K,get stopped(){return s},get reviewing(){return w.active},get key(){return ge},get busy(){return Y},get staleRead(){return sn}}),Ye=Yn({client:n.client,expected:ke,perform:Se,onIntent:n.onCustomerDataIntent,get stopped(){return s},get busy(){return Y},get document(){return ue?.document},get answers(){return fe}}),Xe=e=>`${e.id}:${e.nodeId}:${e.visit}`,Fe=e=>e&&(e.screen||e.paywall)?Xe(e):"";function he(){let e=n.client.view;q.disabled=!w.active&&(Y>0||!!n.client.pendingCommand||!e?.canBack||e.stopped||!["running","waiting"].includes(e.status)||!Fe(e)||ne!==Fe(e)),q.hidden=!w.active&&!e?.canBack,yn(q);let t=!!v&&!w.active;R.hidden=t&&!F?.active||Le&&!w.active,M.hidden=!n.client.review||!w.active&&!e?.canBack;let r=e?.locale.startsWith("zh");vn=!t&&(Y>0||!!e?.pendingRequest),ye.textContent=t?"":Y>0||e?.pendingRequest?r?"正在处理":"Processing":e?.instruction?.type==="wait"?r?"等待中":"Waiting":"",Ce()}async function En(e){if(!e)return;let t=n.client.view;await e;let r=n.client.view;if(!t||!r||r.id!==t.id||r.nodeId!==t.nodeId||r.visit!==t.visit||r.stopped||!["running","waiting"].includes(r.status))throw new te("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Se(e,t=!1,r){if(!((Y||pe||oe||V)&&!t||s||w.active&&!t)){Y++,c.setAttribute("aria-busy","true"),O.hidden=!0,Ee=null,De=!1,he();try{if(t||await En(Ve.inFlight),s)return;let h=await e();s||await le(n.client.view??h.run)}catch(h){r?.(h)&&n.client.pendingCommand===null?Rn():se.pending||K(h,n.client.pendingCommand?.requestId??null)}finally{Y=Math.max(0,Y-1),c.setAttribute("aria-busy",String(Y>0)),s||(Z.hidden=n.client.pendingCommand===null,he())}}}function Oe(){dn.schedule()}async function cn(){if(!(s||Je||Y)&&!se.pending){if(w.active){await w.open(w.receipt);return}Je=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let t=n.client.view,r=Ye.queries,h=await n.client.get(t?.screen&&Object.keys(r).length?{nodeId:t.nodeId,visit:t.visit,revision:t.revision,components:r}:void 0);De&&!s&&(De=!1,O.hidden=!0,Ce()),!s&&r===Ye.queries&&await le(n.client.view??h.run)}catch(e){K(e),De=!s}finally{Je=!1}}}function Ze(e,t,r){if(F?.active){let ee=F;return ee.setDismissHandler(()=>kn(ee)),ee}let h=tn(i,n,"funnel",()=>kn(h),Un);return F=h,h.start(e,t,r),h}function kn(e){s||re||(re=!0,e.finish("dismissed"),me(),c.hidden=!0,n.client.view?ve().finally(G):G())}function pn(){clearTimeout(We?.timeout),We=void 0}function me(e){Le=!1,pn(),Ae?.abort(),Ae=void 0,ue?.destroy(),ue=null,v?.destroy(),v=null,Ne=void 0,_e?.(),_e=void 0,D.open&&D.close();for(let t of Array.from(A.children))(!e||!t.contains(e))&&t.remove();A.style.cssText="",Me=void 0,ge="",ne="",Pe=!1,ze="",Be=""}function Tn(){let e=o.defaultView;J?.responsive&&e&&ue?.resizeViewport?.(e.innerHeight,e.innerWidth)}function Ke(){J?.destroy(),J=void 0,Te=""}function en(e){let t=e.screen?.presentation;if(!t||t.type==="inline"){D.open&&D.close(),Ke(),R.parentElement!==N&&N.append(R),c.parentElement!==i&&i.append(c);for(let ee of["flex","display","flex-direction","justify-content"])A.style.removeProperty(ee);xe(e),Ce();return}c.parentElement!==D&&(D.append(R,c),i.append(D)),A.style.flex="1 0 auto",A.style.display="flex",A.style.flexDirection="column",A.style.justifyContent="center",xe(e);let r=e.screen.content.document,h=JSON.stringify([t,x]);if(h!==Te){Ke(),Te=h;let ee={sm:420,md:640,lg:900},we="size"in t&&!t.backdrop?",0 0 0 100vmax #16142566":"";D.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${ae.background};color:${ae.text};`+(t.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ee[t.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${we};`+(t.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),J=Ln(D,{presentation:t,theme:r.theme,pages:r.pages},Tn),J.latch()}Ce(),D.setAttribute("aria-label",(Ie?.screen===e.screen?.content.document.name?Ie?.label:void 0)??ue?.document?.name??e.screen?.content.document.name??"Funnel")}async function Zn(e){if(s||re)return;if(se.observe(),se.pending){ie=e;return}if(pe&&(je()||["running","waiting"].includes(e.status))||(ie=e,Ee&&n.client.pendingCommand?.requestId!==Ee&&(O.hidden=!0,Ee=null),k=e.locale.startsWith("zh"),M.textContent=k?"回看":"History",q.textContent=w.active?k?"返回当前":"Return to current":k?"返回":"Back",In(),Z.textContent=k?"重试":"Retry",Z.hidden=n.client.pendingCommand===null,he(),bn!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(bn=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,be(n.onState,structuredClone(e))),s||re))return;if((!e.pendingRequest||pe&&e.status==="closed")&&["closed","ineligible","failed"].includes(e.status)){G();return}if(e.stopped&&a()){G();return}if(e.stopped||n.client.configurationReady===!1){w.stop(),g(),me(),F?.finish("skipped"),c.hidden=!0,Oe();return}if(c.hidden=!1,w.active){Oe();return}if(e.status==="completed"&&v?.subscriptionUpgradeActive){Oe();return}let t=Fe(e),r=n.client.view;if(r&&r.revision>e.revision&&Fe(r)!==t)return;let h=!e.instruction&&!e.pendingRequest&&e.nodeType==="screen"&&["running","waiting"].includes(e.status);t!==ge&&(ge&&F?.finish("dismissed"),me(),ge=t,fe={...e.answers},Ye.reset());let ee=Xe(e);if(Qe===ee){c.hidden=!0;return}if(h&&!t){c.hidden=!0;let I=n.prepared?.state==="shown"?null:Ze(!0,e.locale);!s&&!re&&We?.key!==ee&&(pn(),We={key:ee,timeout:setTimeout(()=>{let l=n.client.view;if(s||!I?.active&&n.prepared?.state!=="shown"||!l||Xe(l)!==ee)return;Qe=ee;let H=new Error("Funnel screen preparation timed out");I?.finish("error",H),g(),me(),K(H)},He)}),Oe();return}pn();let $=I=>{let l=n.client.view;return!s&&!re&&!Re&&!I.aborted&&n.client.configurationReady!==!1&&!!l&&!l.stopped&&!["closed","ineligible","failed"].includes(l.status)&&(Fe(l)===t||l.status==="completed"&&v?.subscriptionUpgradeActive===!0)},we=(I,l)=>{$(l)&&(Qe=t,F?.finish("error",I),me(),c.hidden=!0,K(I))};if(t||((e.instruction&&e.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(e.status))&&g(),en(e),e.instruction?.type!=="event"&&e.instruction?.type!=="open_url"&&F?.finish("skipped")),e.screen){ln=!0,Ge=void 0,g();let I=e.screen.content;if(!ue){let W=e.screen.presentation.type!=="inline",b=Ze(W,e.locale);if(s||re)return;let B=(Ae=new AbortController).signal;en(e),_e=W?$n(D):rn(c,i),ue=S(A,{mode:"live",closeActions:Array.from(new Set([...n.closeActions??[],...I.document.actions.filter(y=>y.type==="event"&&y.close).map(y=>y.id)])),onAuthoredClose(y){$(B)&&(Le=y,he())},rendererUrl:n.client.webViewUrl,title:I.document.name,...W?{hostPresentation:()=>J?.type??e.screen.presentation.type}:{},onResize:y=>{Me=y,J?.responsive&&J.setContentHeight(y+N.getBoundingClientRect().height)},onAction(y,d={},ce={}){if(w.active||!$(B)||ne!==t)return;fe={...fe,...ce};let fn=e.screen?.inputs??[],Fn=Object.fromEntries(fn.filter(({variable:qe})=>Object.hasOwn(fe,qe)).map(({variable:qe})=>[qe,fe[qe]]));if(Jn(fn,Fn).length){Rn();return}Se(()=>n.client.submit({operation:"submit",...ke(),input:{type:"screen",output:y,answers:Fn,selection:d}}),!1,qe=>zn(qe,fn))},onAnswers:y=>{w.active||!$(B)||ne!==t||(fe={...fe,...y})},onCustomerDataIntent:y=>{w.active||!$(B)||ne!==t||Ye.intent(y).catch(K)},onEscape:()=>{!$(B)||ne!==t||w.active||oe||V||ve()},onError:y=>{let d=new Error(y);ne===t?K(d):we(d,B)},onRendered:y=>{if(!(!$(B)||ne===t))try{b.present(d=>{_e?.(),_e=void 0,y&&(Ie={screen:I.document.name,label:y},D.setAttribute("aria-label",y)),W&&(D.showModal(),P=!1,J?.responsive&&D.focus({preventScroll:!0}),!d&&n.loading!=="host"&&Nn(D,J?.type??e.screen.presentation.type,J?.responsive)),ne=t,Pe=W,he()}),$(B)&&Ve.report(t)}catch(d){we(d,B)}}}),Tn()}let l={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:fe,values:e.screen.values}},H=JSON.stringify([I,e.locale,l.parameters,e.screen.inputs,e.screen.values]);if(H!==ze)ue.update(I.document,e.locale,l),ze=H,on=JSON.stringify(l.capabilities),Be=JSON.stringify(l.customerData);else{let W=JSON.stringify(l.capabilities);W!==on&&(ue.updateCapabilities(l.capabilities),on=W),JSON.stringify(l.customerData)!==Be&&(ue.updateCustomerData(l.customerData),Be=JSON.stringify(l.customerData))}let Q=ue;if(Q)try{await(F?.wait(Q.ready)??Q.ready)}catch(W){Ae&&we(W,Ae.signal)}}else if(e.paywall&&!v){ln=!0;let I=e.paywall.resolution,l="document"in I?I.document:null,H=p,Q=n.mountPaywallControls,W=null,b=(Ae=new AbortController).signal,B={loading:"host",signal:b,...Q&&{mountControls:d=>Q(d,e)},canInteract:()=>$(b)&&!w.active&&!oe&&!V,beforeAction:async()=>{Y++;try{await En(Ve.settled()),O.hidden=!0,Ee=null,De=!1,Ce()}finally{Y=Math.max(0,Y-1)}},start:async()=>{let d=await gn(n.client),ce=X;return X=void 0,d.view&&ce?.(d.view),d},onObservationChange:Oe,onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resumeCheckout:n.resumeCheckout,allowNewPurchase:n.allowNewPurchase,checkoutNavigation:n.checkoutNavigation,terminateCheckout:n.terminateCheckout,beforeCheckoutReplacement:n.beforeCheckoutReplacement,purchaseConfirmation:n.purchaseConfirmation,confirmOnHostedCheckout:n.confirmOnHostedCheckout,resolveOfferId:n.resolveOfferId,prepareSubscriptionChange:n.prepareSubscriptionChange,resolveSubscriptionChange:n.resolveSubscriptionChange,claimCoupon:n.claimCoupon,onEvent:n.onEvent,onOpenUrl:d=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:d,openIn:"same_window"}):o.defaultView?.location.assign(d),onAction:async d=>{if(w.active)return;let ce=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:d,answers:{}}});await le(n.client.view??ce.run)},onError:d=>{ne===t?K(d):we(d,b)}},y={quoteError:d=>be(n.onError,d),present(d){$(b)&&(W?.present(ce=>{d(ce),ne=t,Pe=y.retainedDialog?.dialog.open??!!A.querySelector("dialog[open]"),Pe&&(P=!1),he()}),$(b)&&Ve.report(t))},async closeAction(d){s||w.active||await se.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:d,answers:{}}})},async dismiss(){if(s||b.aborted||w.active||oe||V||!pe&&!$(b))return;pe=!0;let d=n.client.view;if(d?.status==="completed"&&v?.subscriptionUpgradeActive){Ue.add(`complete:${d.id}`),be(n.onComplete,structuredClone(d)),G();return}if((n.resumeCheckout||n.terminateCheckout)&&tt()){ie=n.client.view,G();return}await ve()}};if(H&&Q)g();else if(H){let d=await H.adopt(e,{options:B,handoff:y,start:()=>gn(n.client)});d&&$(b)&&!s?(en(e),v=d,Ne={runId:e.id,receiptId:e.paywall.receiptId},F?.active&&F.present(()=>{}),ne=t,Pe=H.modal,Pe&&(P=!1),he(),Ve.report(t),w.active&&v.setSuspended(!0)):(d?.destroy(),g(),X=ce=>p?.remember(ce))}if(s||re)return;if(!v){if(W=Ze(!0,e.locale,l),s||re)return;(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.loading==="host"&&Ge?.ownerDocument===o&&(y.hostPaywallTarget=Ge),Ge=void 0,en(e);let d=await de(A,B,y).catch(ce=>(we(ce,b),null));!$(b)&&!(pe&&!s&&!b.aborted)?d?.host?.destroy():d&&(v=d.host,v&&(Ne={runId:e.id,receiptId:e.paywall.receiptId}),v?.setSuspended(w.active))}}if(s||re)return;he();let m=e.instruction;if(m&&(m.type==="open_url"||m.type==="event")&&!Ue.has(m.receiptId)){let I=o.createElement("button");I.type="button",I.style.cssText=E.primary,$e(I,()=>E.focus),A.style.cssText=E.stage,I.textContent=m.type==="open_url"?`${k?"前往":"Continue to"} ${new URL(m.url).host}`:k?"继续":"Continue",I.onclick=()=>{let l=ke(),H=m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="new_window"?Kn(m.url):null;Se(async()=>{let Q="success";if(m.type==="open_url")if(n.onOpenUrl)try{Q=await n.onOpenUrl({receiptId:m.receiptId,url:m.url,openIn:m.openIn})===!1?"failed":"opened"}catch(b){be(n.onError,b),Q="failed"}else Q=m.openIn==="new_window"&&!H?"failed":"opened";if(m.type==="event"){if(!n.onEvent)throw new te("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(m.event)}if(s||n.client.view?.nodeId!==l.nodeId||n.client.view.visit!==l.visit)throw new te("PRECONDITION_FAILED","The client action visit changed");let W=await n.client.submit({operation:"submit",...l,input:{type:"client_action",receiptId:m.receiptId,outcome:Q}});return Ue.add(m.receiptId),m.type==="open_url"&&!n.onOpenUrl&&m.openIn==="same_window"&&o.defaultView?.location.assign(m.url),W})},F?.active?F.present(()=>A.replaceChildren(I)):A.replaceChildren(I)}!e.pendingRequest&&e.status==="completed"&&!Ue.has(`complete:${e.id}`)&&(Ue.add(`complete:${e.id}`),be(n.onComplete,structuredClone(e))),Oe()}function Kn(e){let t=o.defaultView?.open(e,"_blank")??null;return t&&(t.opener=null),t}function le(e){return he(),an=an.catch(()=>{}).then(async()=>{try{await Zn(e)}catch(t){throw F?.active&&(Qe=Xe(e),F.finish("error",t),me(),c.hidden=!0),t}}),an}let et=n.client.subscribe(e=>{if(!Cn){if(e.stopped&&(Pe||a())&&!pe){ie=e,G();return}!pe&&(e.stopped||n.client.configurationReady===!1||ge&&ne!==ge&&(Fe(e)!==ge||["closed","ineligible","failed"].includes(e.status)))&&(me(),F?.finish("dismissed"),c.hidden=!0),le(e).catch(K)}}),nt=n.client.subscribeError?.(e=>{se.pending||K(e)});function tt(){let e=n.client.view,t=e?.paywall;return!!t?.operation&&!!e&&["running","waiting"].includes(e.status)&&qn(mn({quote:t.quote,operation:t.operation,requestId:t.purchaseRequestId,pending:!1,destroyed:!1,canReselect:t.canReselect}))}function ve(e){if(Re)return Re;if(s||!e&&(oe||V))return Promise.resolve();let t=!e&&je();return!t&&n.client.view&&!["running","waiting"].includes(n.client.view.status)?(ie=n.client.view,G(),Promise.resolve()):(Re=Se(async()=>{let r=t?await n.client.retry():await(e?n.client.submit.bind(n.client):se.submit)({operation:"close",...e??ke()});return e&&Pn(r),r},!0).then(()=>{let r=n.client.view;r?.status==="closed"&&!je()&&(ie=r,G())}).finally(()=>{Re=null}),Re)}function G(){An()}function An(e){U?.destroy(),!s&&(s=!0,se.destroy(),T(),!ln&&(ie?.status==="ineligible"||ie?.status==="completed")&&p?.withhold(),g(),n.signal?.removeEventListener("abort",G),f?.removeEventListener("abort",G),F?.finish("dismissed"),dn.destroy(),et(),nt?.(),me(e),Ke(),w.stop(),D.remove(),!e||!c.contains(e)?c.remove():(N.remove(),j.remove()),!e&&!P&&u(),be(n.onDismiss,ie?structuredClone(ie):null))}q.onclick=()=>{if(!q.disabled){if(w.active){w.exit();return}Se(()=>n.client.submit({operation:"back",...ke()}))}},M.onclick=()=>{w.open()},R.onclick=()=>{F?.active?F.dismiss():oe||ve()},Z.onclick=()=>{se.pending?se.retry().catch(()=>{}):je()?ve():Se(()=>n.client.retry())},D.addEventListener("cancel",e=>{e.preventDefault(),F?.active?F.dismiss():oe||ve()}),n.signal?.addEventListener("abort",G,{once:!0}),f?.addEventListener("abort",G,{once:!0});let nn=!1;p&&(T=p.onClose(()=>{s||re||(re=!0,F?.finish("dismissed"),me(),c.hidden=!0,n.client.view?ve().finally(G):nn=!0)}));let Dn={destroy:G,refresh:cn,get recoveryPaywall(){if(v&&Ne)return{...Ne,view:v.currentResolution}},setPurchaseRecovery(e,t){return v?.setPurchaseRecovery(e,t),v!==null},retainPurchaseDialog(){let e=v?.retainPurchaseDialog();if(e)return v=null,An(e.dialog),{dialog:e.dialog,release(){e.release(),c.remove(),P||u()}}},get recovery(){let e=un();if(e)return e;if(!s&&!Y&&!pe&&!oe&&v){let t=v.recovery;if(t.type!=="native")return t}return{type:"recover",operationId:n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??V?.operationId??null,requestId:n.client.pendingCommand?.requestId??null}},prepareFallback(){if(oe)return oe;let e=un();if(e)return Promise.resolve(e);let t=n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??V?.operationId??null,r=()=>({type:"recover",operationId:t,requestId:n.client.pendingCommand?.requestId??null});if(n.client.hasDurableJournal!==!0){let m=v?.recovery;return Promise.resolve(m&&m.type!=="native"&&m.type!=="cancel"?m:r())}let h=(n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[])).some(m=>m.operation==="close");if(s&&!(h||V&&n.client.view?.status==="closed")||Y||Je||Re||w.active||!v&&!V&&!h)return Promise.resolve(r());let ee=v,$=(async()=>{try{if(!V&&h){let l=await n.client.retry();return await le(n.client.view??l.run),r()}if(!V){let l=await ee.prepareFallback();if(l.type!=="native")return l;if(n.client.hasDurableJournal!==!0)return r();V=l}let m=n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[]);if(m.length){let l=m.find(Q=>Q.operation==="close");if(!l||!z||l.requestId!==z.requestId)return r();let H=await n.client.retry();Pn(H),await le(n.client.view??H.run)}else{let l=n.client.view,H=l?.paywall;if(!l||!H||H.selectionGeneration===void 0||(H.quote?.operationId??null)!==V.operationId||V.operationId!==null&&H.canReselect!==!0)return r();let Q=H.selectionGeneration,W=await n.client.get();await le(n.client.view??W.run);let b=n.client.view,B=b?.paywall;if(!b||!B||!["running","waiting"].includes(b.status)||b.stopped||b.id!==l.id||b.nodeId!==l.nodeId||b.visit!==l.visit||B.receiptId!==H.receiptId||B.selectionGeneration!==Q||(B.quote?.operationId??null)!==V.operationId||V.operationId!==null&&B.canReselect!==!0||n.client.pendingPurchase||(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0)))return r();let y=ke();z={runId:b.id,operationId:V.operationId,revision:y.revision,requestId:y.requestId,nodeId:b.nodeId,visit:b.visit,receiptId:B.receiptId,selectionGeneration:Q,acknowledged:!1},await ve(y)}let I=un();return I?(G(),I):r()}catch(m){return K(m),r()}})();oe=$;let we=()=>{oe===$&&(oe=null)};return $.then(we,we),$},review:w.open,exitReview:w.exit,get unappliedDrafts(){return w.drafts}};try{let e=n.client.view;if(e)((n.client.viewAgeMs??hn)>=hn||e.instruction?.type==="evaluate_segment")&&(sn=cn().finally(()=>{sn=null})),await le(e);else{if(c.hidden=!0,s)throw new DOMException("Presentation cancelled","AbortError");let t=nn||n.prepared?.state==="shown"?null:Ze(n.client.view?.screen?.presentation.type!=="inline",n.client.view?.locale);if(s||re&&!nn)throw new DOMException("Presentation cancelled","AbortError");let r=n.client.get(),h=await(t?t.wait(r,He):ot(r,He));if(Cn=!1,nn)return s||await ve().finally(G),Dn;await le(n.client.view??h.run)}}catch(e){throw F?.finish("error",e),G(),e}return Dn}function ot(i,C){let _;return Promise.race([i,new Promise((n,p)=>{_=setTimeout(()=>p(new Error("Presentation data timed out")),C)})]).finally(()=>clearTimeout(_))}function Lt(i,C,_){return rt(i,C,_)}export{rt as a,Lt as b};
@@ -1 +1 @@
1
- import{a as fe,b as pe}from"./chunk-2ZMIM4MO.js";import{d as De,e as B}from"./chunk-CQ5EQNQA.js";import{a as Ve}from"./chunk-ZRU7WONE.js";import{a as C}from"./chunk-DSPLGTQI.js";var Te=5*6e4,je=15e3,Oe=new WeakMap;function Be(c){return Oe.get(c)}var A=c=>Array.isArray(c)?c.map(A):c&&typeof c=="object"?Object.fromEntries(Object.keys(c).sort().map(a=>[a,A(c[a])])):c,N=(c,a)=>JSON.stringify(A(c))===JSON.stringify(A(a)),X=c=>JSON.stringify(A([c.funnelId,c.locale??null,c.parameters??{}])),Je=["onObservationChange","onPurchase","onCheckoutUrl","resumeCheckout","allowNewPurchase","checkoutNavigation","terminateCheckout","beforeCheckoutReplacement","purchaseConfirmation","confirmOnHostedCheckout","resolveOfferId","prepareSubscriptionChange","resolveSubscriptionChange","onOpenUrl","onEvent","onAction","onComplete","onError"];function Xe(c,a){let we=e=>structuredClone({funnelId:e.funnelId,locale:e.locale,parameters:e.parameters}),m,x="",R=a.start instanceof Promise?void 0:we(a.start),$=e=>e?.parameters?.commerce,M=Promise.resolve(a.start).then(e=>e?we(e):void 0),z=a.maxAgeMs??Te,ye=new AbortController,w=AbortSignal.any([ye.signal,a.client.identitySignal,...a.signal?[a.signal]:[]]),Q=()=>d("released","aborted"),r="preparing",me,q,Y=()=>{},L=0,P=null,b=null,v=null,y=null,g,D,Z,ge=new Map,h=null,T=new Set,k=new Map,ee,he=new Promise(e=>ee=e),j,be=new Promise(e=>j=e),ne,He=new Promise(e=>ne=e);function J(e,n){r!==e&&(r=e,me=n,C(a.onState,e))}function Fe(){w.removeEventListener("abort",Q),U(),b?.destroy(),b=null,P?.remove(),P=null,v=null}function d(e,n){["adopted","unavailable","released","closed"].includes(r)||(J(e,n),Fe(),ee(!1),j(!1),ne(null))}function O(e){r!=="shown"&&d("unavailable",e)}let p,ae=!1,E=a.client.paywallCopies,te,Pe=new Promise(e=>te=e),re=!1;function ve(e){Pe.then(n=>{n&&E&&E.write(n,e).catch(()=>{})})}function Ie(e){Pe.then(async n=>{if(!n||!E)return;let t=await E.read(n);ae||t&&"presented"in t||await E.write(n,e)}).catch(()=>{})}let oe=e=>`error:${e?.code??e?.name??"unknown"}`,le=c.ownerDocument.defaultView,H=!0,Se=null,_=!1,Ne=e=>e.storageArea===le?.localStorage&&(e.key===null||e.key.startsWith("indiana.funnel.purchases.")),Ce=e=>{Ne(e)&&G()},xe=a.client.subscribe(()=>G());function U(){H&&(H=!1,le?.removeEventListener("storage",Ce),xe(),Y())}let ie=()=>H&&(r==="ready"||r==="preparing");function se(e){(r==="ready"||r==="preparing")&&d("unavailable",e)}function G(){if(r==="ready"&&Date.now()-L>=z)return U();_=!0,Se??=(async()=>{for(;_&&m&&ie();){_=!1;try{await a.client.retained()==="pending"&&se("purchase_pending")}catch(e){w.aborted?d("released","aborted"):se(oe(e))}}})().finally(()=>{Se=null,_&&m&&ie()&&G()})}le?.addEventListener("storage",Ce),w.addEventListener("abort",Q,{once:!0});let Ae=a.client.findPurchase();Ae.catch(()=>{});let W;function K(e){let n=W?.paywallVersionId??a.paywallVersionId??p?.resolution.id??y?.id,t=JSON.stringify(A([n??null,e])),l=ge.get(t);return l||(l=a.client.readPaywall({paywallVersionId:n,...n?{}:{paywallId:W?.paywallId??a.paywallId},...e}),ge.set(t,l)),l}function V(e,n){let t=Object.values(e.capabilities.plans),l=Object.values(e.document.buttons).some(i=>i.type==="checkout");return l&&t.length===0?!1:n.intent==="subscription_change"&&l?t.some(i=>i.available):t.every(i=>i.available)}function ce(e,n){if(y&&!B(e,y))return d("unavailable","paywall_changed"),!1;y=e,Z=n;for(let t of k.keys())C(t,structuredClone(e));return!0}function Re(e,n){if(!(!y||!["preparing","ready","shown"].includes(r))){if(!B(e,y))return O("paywall_changed");if(!V(e,n.commerce))return O("plan_unavailable");ce(e,n)}}async function F(){let e=await He;if(!e)throw new Ve("PURCHASE_PENDING","The purchase did not start; open it again");return e}let Me={get view(){return h?h.view:y},get signal(){return h?.signal??a.client.identitySignal},get quote(){return h?.quote??null},get operation(){return h?.operation??null},webViewUrl:"bundled",get canReselect(){return h?.canReselect},get recovery(){return h?.recovery},get pendingCancellation(){return h?.pendingCancellation},subscribe(e){return k.set(e,h?.subscribe?.(e)??(()=>{})),()=>{k.get(e)?.(),k.delete(e)}},refresh:async()=>h?h.refresh():structuredClone(y),preview:async e=>(await F()).preview(e),confirm:async()=>(await F()).confirm(),cancel:async()=>(await F()).cancel(),read:async()=>(await F()).read(),destroy(){h?.destroy()}},u={options:{},handoff:{}},ke={loading:"host",focusAtReveal:!0,signal:a.client.identitySignal,start:async()=>Me,canInteract:()=>u.options.canInteract?u.options.canInteract():!["unavailable","released","closed"].includes(r),async beforeAction(){let e=r!=="adopted",n=y?.capabilities,t=await F();if(e&&!N(t.view?.capabilities,n))throw new De;await u.options.beforeAction?.()}};for(let e of Je)Object.defineProperty(ke,e,{enumerable:!0,get:()=>u.options[e]});function de(){r!=="preparing"||!v||!b||!p&&(!m||!N(Z?.commerce,$(m))||Z?.locale!==m.locale)||(J("ready"),ee(!0))}let Ee={present(e){if(u.handoff.present)return u.handoff.present(e);r==="preparing"&&(v=e,L=Date.now(),de())},async dismiss(){if(u.handoff.dismiss)return u.handoff.dismiss();d("closed");for(let e of[...T])C(e)},async closeAction(e){if(u.handoff.closeAction)return u.handoff.closeAction(e);u.options.onAction?await u.options.onAction(e):await Ee.dismiss()},quoteError(e){u.handoff.quoteError?u.handoff.quoteError(e):C(u.options.onError,e)}};async function qe(){if(a.paywallVersionId||a.paywallId)return{paywallVersionId:a.paywallVersionId,paywallId:a.paywallId};let e=a.configuration;if(!e)return d("unavailable","paywall_missing"),null;let n=await Promise.resolve(a.start).catch(()=>null);if(!n||r!=="preparing")return null;let t=()=>fe(e,{funnelId:n.funnelId,customerId:a.client.customerId,parameters:n.parameters??{}});if(q=await t(),r!=="preparing")return null;let l=q;if(l.type!=="paywall")return d("unavailable",pe(l)??"route"),null;let i=!1;return Y=e.subscribe(()=>{i||!ie()||(i=!0,t().then(s=>{!(s.type==="unavailable"&&!["funnel_stopped","route_unavailable"].includes(s.reason))&&(s.type!=="paywall"||s.paywallVersionId!==l.paywallVersionId)&&se("route_changed")}).finally(()=>i=!1))}),H||Y(),{paywallVersionId:l.paywallVersionId}}(async()=>{try{let[{showPaywall:e},n]=await Promise.all([import("./paywall-BSY67NQL.js"),qe()]),t=a.commerce??$(R),l=a.locale??R?.locale,i=n&&t&&l?JSON.stringify(A([n.paywallVersionId??null,n.paywallId??null,{commerce:t,locale:l}])):null;if(te(i),w.throwIfAborted(),r!=="preparing"||!n)return;if(!t)return d("unavailable","commerce_missing");if(!l)return d("unavailable","locale_missing");W=n;let s={commerce:t,locale:l},f=i?await E?.read(i).catch(()=>null):null;if(re=!!f&&"presented"in f&&(!R||f.funnelId===R.funnelId),w.throwIfAborted(),r!=="preparing"||re)return;f&&!("presented"in f)&&(!R||f.funnelId===R.funnelId)&&V(f.resolution,f.context.commerce)&&(p=f),j(!!p);let o;if(p){let ue=p.context;s=ue,o=structuredClone(p.resolution),K(ue).then(Le=>Re(Le,ue),()=>{})}else o=await K(s);if(w.throwIfAborted(),r!=="preparing"||(!V(o,s.commerce)&&a.start instanceof Promise&&!g&&await M,!p&&g&&!N(s,g)&&(s=g,o=await K(s)),w.throwIfAborted(),r!=="preparing"))return;if(!V(o,s.commerce))return d("unavailable","plan_unavailable");if(!ce(o,s))return;P=c.ownerDocument.createElement("div"),c.append(P);let S=setTimeout(()=>r==="preparing"&&d("unavailable","timeout"),je);he.then(()=>clearTimeout(S));let I=await e(P,ke,Ee);if(!I.host||w.aborted||r!=="preparing"){I.host?.destroy(),d(w.aborted?"released":"unavailable","error");return}b=I.host,de()}catch(e){d(w.aborted?"released":"unavailable",oe(e))}finally{te(null),j(!1)}})(),M.then(async e=>{let n=s=>{Ie(null),O(s)};if(!e)return n("gated");let t=e,l=$(t),i=a.commerce??l;if(!N(l&&{...l,intent:void 0},i&&{...i,intent:void 0})||a.locale!==void 0&&t.locale!==a.locale)return n("start_mismatch");if(!l)return n("commerce_missing");g={commerce:l,locale:t.locale},D=t,p&&["preparing","ready","shown"].includes(r)&&(m=t,x=X(t));try{let s=await Ae,f=s==="pending"?"purchase_pending":s==="found"?"original_purchase":s==="blocked"?"purchase_blocked":void 0;if(f)return n(f);if(!["preparing","ready","shown"].includes(r))return;if(a.configuration&&(a.paywallId||a.paywallVersionId)){let o=await fe(a.configuration,{funnelId:t.funnelId,customerId:a.client.customerId,parameters:t.parameters??{}});w.throwIfAborted();let S=o.type==="unknown"||o.type==="unavailable"&&o.reason!=="funnel_stopped";if(o.type==="paywall"?p?o.paywallId!==p.resolution.paywallId:a.paywallVersionId?o.paywallVersionId!==a.paywallVersionId:o.paywallId!==a.paywallId:!S)return n(pe(o)??"route_changed")}if(H&&(_=!1,await a.client.retained()==="pending"))return n("purchase_pending");if(await be,re){m=t,x=X(t);return}if(W||a.paywallId||a.paywallVersionId||y){let o=await K(g);if(w.throwIfAborted(),Ie(V(o,g.commerce)?{savedAt:Date.now(),funnelId:t.funnelId,context:g,resolution:o}:null),p)Re(o,g);else{if(r!=="preparing")return;if(y){if(!V(o,g.commerce))return d("unavailable","plan_unavailable");if(!ce(o,g))return}}}}catch(s){return w.aborted?d("released","aborted"):O(oe(s))}["preparing","ready","shown"].includes(r)&&(m=t,x=X(t),de(),_&&G())},()=>O("gated"));let _e={get state(){return r},get reason(){return me},ready:he,local:be,get start(){return m},get prediction(){return q?structuredClone(q):void 0},matches:e=>m?X(e)===x:!!p&&e.funnelId===p.funnelId&&e.locale===p.context.locale,open(){if(r==="preparing")return"pending";if(r!=="ready"||!v)return!1;if(Date.now()-L>=z)return d("unavailable","expired"),!1;let e=v;return v=null,U(),J("shown"),e(),"shown"},destroy(){ye.abort()}};return Oe.set(_e,{onClose(e){return r==="closed"?(C(e),()=>{}):(T.add(e),()=>{T.delete(e)})},claim(){U()},remember(e){ae=!0;let n=structuredClone(e);M.then(()=>{!D||!g||ve({savedAt:Date.now(),funnelId:D.funnelId,context:g,resolution:n})},()=>{})},withhold(){ae=!0,M.then(()=>{D&&ve({savedAt:Date.now(),funnelId:D.funnelId,presented:"nothing"})},()=>{})},async adopt(e,n){let t=e.paywall?.resolution,l=e.paywall&&!e.paywall.quote&&!e.paywall.operation&&!e.paywall.purchaseRequestId&&!(e.paywall.selectionGeneration??0);if(r!=="shown"||!b||!y||!t||!l||e.source.id!==m?.funnelId||e.locale!==m?.locale||!N(e.parameters??{},m?.parameters??{})||!["running","waiting"].includes(e.status)||!B(t,y))return null;let i;try{i=await n.start()}catch{return null}if(r!=="shown"||!b)return i.destroy(),null;h=i,u.options=n.options,u.handoff=n.handoff;for(let[o]of k)k.set(o,i.subscribe?.(o)??(()=>{})),i.view&&C(o,structuredClone(i.view));w.removeEventListener("abort",Q),J("adopted"),ne(i),T.clear();let s=b,f=P;return b=null,P=null,v=null,new Proxy(s,{get(o,S){return S==="destroy"?()=>{o.destroy(),f?.remove()}:S==="retainPurchaseDialog"?()=>{let I=o.retainPurchaseDialog();if(I)return{dialog:I.dialog,release(){I.release(),f?.remove()}}}:Reflect.get(o,S,o)}})},retainPurchaseDialog(){if(r!=="shown")return;let e=b?.retainPurchaseDialog();if(!e)return;let n=P;return b=null,P=null,d("released"),{dialog:e.dialog,release(){e.release(),n?.remove()}}},get modal(){return y?.document.presentation.type!=="inline"},get revealable(){return r==="ready"&&!!v&&Date.now()-L<z},release(){d("released")}}),_e}export{Te as a,Be as b,Xe as c};
1
+ import{a as fe,b as pe}from"./chunk-5DWUXPEL.js";import{d as De,e as B}from"./chunk-LS55FUZZ.js";import{a as Ve}from"./chunk-46FG3J5X.js";import{a as C}from"./chunk-DSPLGTQI.js";var Te=5*6e4,je=15e3,Oe=new WeakMap;function Be(c){return Oe.get(c)}var A=c=>Array.isArray(c)?c.map(A):c&&typeof c=="object"?Object.fromEntries(Object.keys(c).sort().map(a=>[a,A(c[a])])):c,N=(c,a)=>JSON.stringify(A(c))===JSON.stringify(A(a)),X=c=>JSON.stringify(A([c.funnelId,c.locale??null,c.parameters??{}])),Je=["onObservationChange","onPurchase","onCheckoutUrl","resumeCheckout","allowNewPurchase","checkoutNavigation","terminateCheckout","beforeCheckoutReplacement","purchaseConfirmation","confirmOnHostedCheckout","resolveOfferId","prepareSubscriptionChange","resolveSubscriptionChange","onOpenUrl","onEvent","onAction","onComplete","onError"];function Xe(c,a){let we=e=>structuredClone({funnelId:e.funnelId,locale:e.locale,parameters:e.parameters}),m,x="",R=a.start instanceof Promise?void 0:we(a.start),$=e=>e?.parameters?.commerce,M=Promise.resolve(a.start).then(e=>e?we(e):void 0),z=a.maxAgeMs??Te,ye=new AbortController,w=AbortSignal.any([ye.signal,a.client.identitySignal,...a.signal?[a.signal]:[]]),Q=()=>d("released","aborted"),r="preparing",me,q,Y=()=>{},L=0,P=null,b=null,v=null,y=null,g,D,Z,ge=new Map,h=null,T=new Set,k=new Map,ee,he=new Promise(e=>ee=e),j,be=new Promise(e=>j=e),ne,He=new Promise(e=>ne=e);function J(e,n){r!==e&&(r=e,me=n,C(a.onState,e))}function Fe(){w.removeEventListener("abort",Q),U(),b?.destroy(),b=null,P?.remove(),P=null,v=null}function d(e,n){["adopted","unavailable","released","closed"].includes(r)||(J(e,n),Fe(),ee(!1),j(!1),ne(null))}function O(e){r!=="shown"&&d("unavailable",e)}let p,ae=!1,E=a.client.paywallCopies,te,Pe=new Promise(e=>te=e),re=!1;function ve(e){Pe.then(n=>{n&&E&&E.write(n,e).catch(()=>{})})}function Ie(e){Pe.then(async n=>{if(!n||!E)return;let t=await E.read(n);ae||t&&"presented"in t||await E.write(n,e)}).catch(()=>{})}let oe=e=>`error:${e?.code??e?.name??"unknown"}`,le=c.ownerDocument.defaultView,H=!0,Se=null,_=!1,Ne=e=>e.storageArea===le?.localStorage&&(e.key===null||e.key.startsWith("indiana.funnel.purchases.")),Ce=e=>{Ne(e)&&G()},xe=a.client.subscribe(()=>G());function U(){H&&(H=!1,le?.removeEventListener("storage",Ce),xe(),Y())}let ie=()=>H&&(r==="ready"||r==="preparing");function se(e){(r==="ready"||r==="preparing")&&d("unavailable",e)}function G(){if(r==="ready"&&Date.now()-L>=z)return U();_=!0,Se??=(async()=>{for(;_&&m&&ie();){_=!1;try{await a.client.retained()==="pending"&&se("purchase_pending")}catch(e){w.aborted?d("released","aborted"):se(oe(e))}}})().finally(()=>{Se=null,_&&m&&ie()&&G()})}le?.addEventListener("storage",Ce),w.addEventListener("abort",Q,{once:!0});let Ae=a.client.findPurchase();Ae.catch(()=>{});let W;function K(e){let n=W?.paywallVersionId??a.paywallVersionId??p?.resolution.id??y?.id,t=JSON.stringify(A([n??null,e])),l=ge.get(t);return l||(l=a.client.readPaywall({paywallVersionId:n,...n?{}:{paywallId:W?.paywallId??a.paywallId},...e}),ge.set(t,l)),l}function V(e,n){let t=Object.values(e.capabilities.plans),l=Object.values(e.document.buttons).some(i=>i.type==="checkout");return l&&t.length===0?!1:n.intent==="subscription_change"&&l?t.some(i=>i.available):t.every(i=>i.available)}function ce(e,n){if(y&&!B(e,y))return d("unavailable","paywall_changed"),!1;y=e,Z=n;for(let t of k.keys())C(t,structuredClone(e));return!0}function Re(e,n){if(!(!y||!["preparing","ready","shown"].includes(r))){if(!B(e,y))return O("paywall_changed");if(!V(e,n.commerce))return O("plan_unavailable");ce(e,n)}}async function F(){let e=await He;if(!e)throw new Ve("PURCHASE_PENDING","The purchase did not start; open it again");return e}let Me={get view(){return h?h.view:y},get signal(){return h?.signal??a.client.identitySignal},get quote(){return h?.quote??null},get operation(){return h?.operation??null},webViewUrl:"bundled",get canReselect(){return h?.canReselect},get recovery(){return h?.recovery},get pendingCancellation(){return h?.pendingCancellation},subscribe(e){return k.set(e,h?.subscribe?.(e)??(()=>{})),()=>{k.get(e)?.(),k.delete(e)}},refresh:async()=>h?h.refresh():structuredClone(y),preview:async e=>(await F()).preview(e),confirm:async()=>(await F()).confirm(),cancel:async()=>(await F()).cancel(),read:async()=>(await F()).read(),destroy(){h?.destroy()}},u={options:{},handoff:{}},ke={loading:"host",focusAtReveal:!0,signal:a.client.identitySignal,start:async()=>Me,canInteract:()=>u.options.canInteract?u.options.canInteract():!["unavailable","released","closed"].includes(r),async beforeAction(){let e=r!=="adopted",n=y?.capabilities,t=await F();if(e&&!N(t.view?.capabilities,n))throw new De;await u.options.beforeAction?.()}};for(let e of Je)Object.defineProperty(ke,e,{enumerable:!0,get:()=>u.options[e]});function de(){r!=="preparing"||!v||!b||!p&&(!m||!N(Z?.commerce,$(m))||Z?.locale!==m.locale)||(J("ready"),ee(!0))}let Ee={present(e){if(u.handoff.present)return u.handoff.present(e);r==="preparing"&&(v=e,L=Date.now(),de())},async dismiss(){if(u.handoff.dismiss)return u.handoff.dismiss();d("closed");for(let e of[...T])C(e)},async closeAction(e){if(u.handoff.closeAction)return u.handoff.closeAction(e);u.options.onAction?await u.options.onAction(e):await Ee.dismiss()},quoteError(e){u.handoff.quoteError?u.handoff.quoteError(e):C(u.options.onError,e)}};async function qe(){if(a.paywallVersionId||a.paywallId)return{paywallVersionId:a.paywallVersionId,paywallId:a.paywallId};let e=a.configuration;if(!e)return d("unavailable","paywall_missing"),null;let n=await Promise.resolve(a.start).catch(()=>null);if(!n||r!=="preparing")return null;let t=()=>fe(e,{funnelId:n.funnelId,customerId:a.client.customerId,parameters:n.parameters??{}});if(q=await t(),r!=="preparing")return null;let l=q;if(l.type!=="paywall")return d("unavailable",pe(l)??"route"),null;let i=!1;return Y=e.subscribe(()=>{i||!ie()||(i=!0,t().then(s=>{!(s.type==="unavailable"&&!["funnel_stopped","route_unavailable"].includes(s.reason))&&(s.type!=="paywall"||s.paywallVersionId!==l.paywallVersionId)&&se("route_changed")}).finally(()=>i=!1))}),H||Y(),{paywallVersionId:l.paywallVersionId}}(async()=>{try{let[{showPaywall:e},n]=await Promise.all([import("./paywall-Z6F2GGOB.js"),qe()]),t=a.commerce??$(R),l=a.locale??R?.locale,i=n&&t&&l?JSON.stringify(A([n.paywallVersionId??null,n.paywallId??null,{commerce:t,locale:l}])):null;if(te(i),w.throwIfAborted(),r!=="preparing"||!n)return;if(!t)return d("unavailable","commerce_missing");if(!l)return d("unavailable","locale_missing");W=n;let s={commerce:t,locale:l},f=i?await E?.read(i).catch(()=>null):null;if(re=!!f&&"presented"in f&&(!R||f.funnelId===R.funnelId),w.throwIfAborted(),r!=="preparing"||re)return;f&&!("presented"in f)&&(!R||f.funnelId===R.funnelId)&&V(f.resolution,f.context.commerce)&&(p=f),j(!!p);let o;if(p){let ue=p.context;s=ue,o=structuredClone(p.resolution),K(ue).then(Le=>Re(Le,ue),()=>{})}else o=await K(s);if(w.throwIfAborted(),r!=="preparing"||(!V(o,s.commerce)&&a.start instanceof Promise&&!g&&await M,!p&&g&&!N(s,g)&&(s=g,o=await K(s)),w.throwIfAborted(),r!=="preparing"))return;if(!V(o,s.commerce))return d("unavailable","plan_unavailable");if(!ce(o,s))return;P=c.ownerDocument.createElement("div"),c.append(P);let S=setTimeout(()=>r==="preparing"&&d("unavailable","timeout"),je);he.then(()=>clearTimeout(S));let I=await e(P,ke,Ee);if(!I.host||w.aborted||r!=="preparing"){I.host?.destroy(),d(w.aborted?"released":"unavailable","error");return}b=I.host,de()}catch(e){d(w.aborted?"released":"unavailable",oe(e))}finally{te(null),j(!1)}})(),M.then(async e=>{let n=s=>{Ie(null),O(s)};if(!e)return n("gated");let t=e,l=$(t),i=a.commerce??l;if(!N(l&&{...l,intent:void 0},i&&{...i,intent:void 0})||a.locale!==void 0&&t.locale!==a.locale)return n("start_mismatch");if(!l)return n("commerce_missing");g={commerce:l,locale:t.locale},D=t,p&&["preparing","ready","shown"].includes(r)&&(m=t,x=X(t));try{let s=await Ae,f=s==="pending"?"purchase_pending":s==="found"?"original_purchase":s==="blocked"?"purchase_blocked":void 0;if(f)return n(f);if(!["preparing","ready","shown"].includes(r))return;if(a.configuration&&(a.paywallId||a.paywallVersionId)){let o=await fe(a.configuration,{funnelId:t.funnelId,customerId:a.client.customerId,parameters:t.parameters??{}});w.throwIfAborted();let S=o.type==="unknown"||o.type==="unavailable"&&o.reason!=="funnel_stopped";if(o.type==="paywall"?p?o.paywallId!==p.resolution.paywallId:a.paywallVersionId?o.paywallVersionId!==a.paywallVersionId:o.paywallId!==a.paywallId:!S)return n(pe(o)??"route_changed")}if(H&&(_=!1,await a.client.retained()==="pending"))return n("purchase_pending");if(await be,re){m=t,x=X(t);return}if(W||a.paywallId||a.paywallVersionId||y){let o=await K(g);if(w.throwIfAborted(),Ie(V(o,g.commerce)?{savedAt:Date.now(),funnelId:t.funnelId,context:g,resolution:o}:null),p)Re(o,g);else{if(r!=="preparing")return;if(y){if(!V(o,g.commerce))return d("unavailable","plan_unavailable");if(!ce(o,g))return}}}}catch(s){return w.aborted?d("released","aborted"):O(oe(s))}["preparing","ready","shown"].includes(r)&&(m=t,x=X(t),de(),_&&G())},()=>O("gated"));let _e={get state(){return r},get reason(){return me},ready:he,local:be,get start(){return m},get prediction(){return q?structuredClone(q):void 0},matches:e=>m?X(e)===x:!!p&&e.funnelId===p.funnelId&&e.locale===p.context.locale,open(){if(r==="preparing")return"pending";if(r!=="ready"||!v)return!1;if(Date.now()-L>=z)return d("unavailable","expired"),!1;let e=v;return v=null,U(),J("shown"),e(),"shown"},destroy(){ye.abort()}};return Oe.set(_e,{onClose(e){return r==="closed"?(C(e),()=>{}):(T.add(e),()=>{T.delete(e)})},claim(){U()},remember(e){ae=!0;let n=structuredClone(e);M.then(()=>{!D||!g||ve({savedAt:Date.now(),funnelId:D.funnelId,context:g,resolution:n})},()=>{})},withhold(){ae=!0,M.then(()=>{D&&ve({savedAt:Date.now(),funnelId:D.funnelId,presented:"nothing"})},()=>{})},async adopt(e,n){let t=e.paywall?.resolution,l=e.paywall&&!e.paywall.quote&&!e.paywall.operation&&!e.paywall.purchaseRequestId&&!(e.paywall.selectionGeneration??0);if(r!=="shown"||!b||!y||!t||!l||e.source.id!==m?.funnelId||e.locale!==m?.locale||!N(e.parameters??{},m?.parameters??{})||!["running","waiting"].includes(e.status)||!B(t,y))return null;let i;try{i=await n.start()}catch{return null}if(r!=="shown"||!b)return i.destroy(),null;h=i,u.options=n.options,u.handoff=n.handoff;for(let[o]of k)k.set(o,i.subscribe?.(o)??(()=>{})),i.view&&C(o,structuredClone(i.view));w.removeEventListener("abort",Q),J("adopted"),ne(i),T.clear();let s=b,f=P;return b=null,P=null,v=null,new Proxy(s,{get(o,S){return S==="destroy"?()=>{o.destroy(),f?.remove()}:S==="retainPurchaseDialog"?()=>{let I=o.retainPurchaseDialog();if(I)return{dialog:I.dialog,release(){I.release(),f?.remove()}}}:Reflect.get(o,S,o)}})},retainPurchaseDialog(){if(r!=="shown")return;let e=b?.retainPurchaseDialog();if(!e)return;let n=P;return b=null,P=null,d("released"),{dialog:e.dialog,release(){e.release(),n?.remove()}}},get modal(){return y?.document.presentation.type!=="inline"},get revealable(){return r==="ready"&&!!v&&Date.now()-L<z},release(){d("released")}}),_e}export{Te as a,Be as b,Xe as c};