@tinkerlandai/longplay-sdk 0.10.41 → 0.10.43

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 (94) hide show
  1. package/CHANGELOG.md +16 -3
  2. package/README.md +1 -0
  3. package/dist/check-response-OIBVUP72.js +1 -0
  4. package/dist/{chunk-P6XQC7GG.js → chunk-22LQSRYH.js} +1 -1
  5. package/dist/{chunk-OEONV3JY.js → chunk-2PVQUPBN.js} +1 -1
  6. package/dist/{chunk-EECTJHI6.js → chunk-3SXPCVIP.js} +1 -1
  7. package/dist/chunk-3XMBILUJ.js +1 -0
  8. package/dist/{chunk-MYDMOAKX.js → chunk-5JRBCW6V.js} +1 -1
  9. package/dist/{chunk-VJHURKRY.js → chunk-5TJISOWN.js} +1 -1
  10. package/dist/{chunk-S4P4UUUF.js → chunk-6XRXHFM6.js} +1 -1
  11. package/dist/{chunk-KINNES62.js → chunk-7MYS52FL.js} +1 -1
  12. package/dist/{chunk-2RUJXZCO.js → chunk-7X65GNKZ.js} +1 -1
  13. package/dist/{chunk-W35FZWGG.js → chunk-AQONMY2H.js} +1 -1
  14. package/dist/{chunk-5PNH2FPI.js → chunk-ASL7TJFU.js} +1 -1
  15. package/dist/{chunk-H26F3IOI.js → chunk-AV2WZSII.js} +1 -1
  16. package/dist/chunk-B4AELNLE.js +1 -0
  17. package/dist/{chunk-CQRSMCCG.js → chunk-C4NG6RVA.js} +1 -1
  18. package/dist/{chunk-NFY7DKVJ.js → chunk-CALDEF4M.js} +1 -1
  19. package/dist/{chunk-24Z3THUR.js → chunk-CSLTAXC7.js} +1 -1
  20. package/dist/{chunk-HGH2X6QM.js → chunk-CWD36SJO.js} +1 -1
  21. package/dist/{chunk-OAAS5LJY.js → chunk-DCZWNTG2.js} +1 -1
  22. package/dist/{chunk-GXADA7OV.js → chunk-DGZCD3AY.js} +1 -1
  23. package/dist/chunk-DPVYEOD6.js +1 -0
  24. package/dist/{chunk-VWRQBQZD.js → chunk-FMSHIKMI.js} +1 -1
  25. package/dist/{chunk-SYHMHKFQ.js → chunk-FTGRTYBL.js} +1 -1
  26. package/dist/{chunk-EOPKOAR5.js → chunk-HLCDAU5A.js} +1 -1
  27. package/dist/{chunk-EJSDOSP5.js → chunk-HTXB2WVI.js} +1 -1
  28. package/dist/chunk-IT5DIE6G.js +1 -0
  29. package/dist/{chunk-7IVLNV5H.js → chunk-KP4QI4RX.js} +1 -1
  30. package/dist/{chunk-26UXCYBP.js → chunk-LSVTH3TS.js} +1 -1
  31. package/dist/{chunk-DPEMW2FO.js → chunk-LZ3OJYBY.js} +1 -1
  32. package/dist/{chunk-QJMM37CB.js → chunk-MEDW4N3F.js} +1 -1
  33. package/dist/{chunk-2LERKK7O.js → chunk-MPD3UIY4.js} +1 -1
  34. package/dist/{chunk-Y2HXKANG.js → chunk-MWICFZUF.js} +1 -1
  35. package/dist/{chunk-EON4IKWR.js → chunk-NVF54BDR.js} +1 -1
  36. package/dist/{chunk-AQQJPP3P.js → chunk-P6TNBX2S.js} +1 -1
  37. package/dist/{chunk-6EBS6MLW.js → chunk-PBZSOTKZ.js} +1 -1
  38. package/dist/{chunk-2XF34Q6D.js → chunk-PG5UESZB.js} +1 -1
  39. package/dist/{chunk-756SIMZF.js → chunk-Q23JDNYJ.js} +1 -1
  40. package/dist/{chunk-RQTYIUWP.js → chunk-RDUKCMST.js} +1 -1
  41. package/dist/{chunk-6STWY5GX.js → chunk-RJY5CUTB.js} +1 -1
  42. package/dist/{chunk-FTVNGN6Z.js → chunk-RMRZSF5C.js} +1 -1
  43. package/dist/chunk-S7A3IBAF.js +10 -0
  44. package/dist/chunk-SSRQGIGB.js +1 -0
  45. package/dist/{chunk-2LUVO7GM.js → chunk-T43HTIQX.js} +1 -1
  46. package/dist/{chunk-G6CWZBT5.js → chunk-TL67SYPH.js} +1 -1
  47. package/dist/{chunk-O3HLNU6T.js → chunk-UJMP7AMY.js} +1 -1
  48. package/dist/{chunk-TGPZJ5A7.js → chunk-V65FSNYO.js} +1 -1
  49. package/dist/{chunk-2P2YSNYU.js → chunk-X4UTTXOU.js} +1 -1
  50. package/dist/{chunk-W3J2SIPY.js → chunk-XZEZFWFD.js} +1 -1
  51. package/dist/chunk-YVAQLTHJ.js +1 -0
  52. package/dist/{content-XYUJFGY2.js → content-FZOT5NDI.js} +1 -1
  53. package/dist/funnel-host-purchase-6GV67OIA.js +1 -0
  54. package/dist/funnel-paywall-prerender-OA3QN2VI.js +1 -0
  55. package/dist/funnel-route-prediction-XGCMCIKA.js +1 -0
  56. package/dist/funnel-route-source-O76QSUYU.js +1 -0
  57. package/dist/funnel-runtime-host-NU36AKUF.js +1 -0
  58. package/dist/index.js +1 -1
  59. package/dist/merchant-bridge-contracts-FB63H7NE.js +1 -0
  60. package/dist/native-shell.js +1 -1
  61. package/dist/openrouter.js +1 -1
  62. package/dist/operation-contracts-YSFIINLK.js +1 -0
  63. package/dist/page.js +1 -1
  64. package/dist/paywall-GLXO4HN7.js +1 -0
  65. package/dist/paywall-content-IF2LKXDF.js +1 -0
  66. package/dist/paywall-session-YDG3FDOP.js +1 -0
  67. package/dist/popup.js +1 -1
  68. package/dist/react-native.js +1 -1
  69. package/dist/screen-renderer-RDXKWHYE.js +1 -0
  70. package/dist/server.js +1 -1
  71. package/dist/{visual-dom-7YYJQ2ZI.js → visual-dom-IN6DRNX3.js} +1 -1
  72. package/dist/visual.js +1 -1
  73. package/package.json +1 -1
  74. package/dist/check-response-SR3PDVGE.js +0 -1
  75. package/dist/chunk-4B4RB36N.js +0 -1
  76. package/dist/chunk-6OVMC5BT.js +0 -1
  77. package/dist/chunk-ANXK3B5B.js +0 -1
  78. package/dist/chunk-BWRRZ2NW.js +0 -1
  79. package/dist/chunk-H7AHDGVU.js +0 -10
  80. package/dist/chunk-PYLX3WF6.js +0 -1
  81. package/dist/funnel-host-purchase-BNS3242X.js +0 -1
  82. package/dist/funnel-paywall-prerender-DDQI3GAZ.js +0 -1
  83. package/dist/funnel-route-prediction-BT5ZWU54.js +0 -1
  84. package/dist/funnel-route-source-7ZJMZRID.js +0 -1
  85. package/dist/funnel-runtime-host-3SSDNG24.js +0 -1
  86. package/dist/merchant-bridge-contracts-YU53UKUN.js +0 -1
  87. package/dist/operation-contracts-GEIGP23I.js +0 -1
  88. package/dist/paywall-YZAEI7TF.js +0 -1
  89. package/dist/paywall-content-QBSB5NA7.js +0 -1
  90. package/dist/paywall-session-MHBAZLS7.js +0 -1
  91. package/dist/screen-renderer-SEJG7A2C.js +0 -1
  92. /package/dist/{chunk-2ULWP26K.js → chunk-GPJF3T43.js} +0 -0
  93. /package/dist/{chunk-4PGYQ2TI.js → chunk-RA7GZ67U.js} +0 -0
  94. /package/dist/{chunk-PBBREFS5.js → chunk-WPFTSHP2.js} +0 -0
@@ -1 +1 @@
1
- import"./chunk-O3HLNU6T.js";import"./chunk-SYHMHKFQ.js";import"./chunk-2XF34Q6D.js";import"./chunk-26UXCYBP.js";import{a as i}from"./chunk-G6CWZBT5.js";import"./chunk-S4P4UUUF.js";import"./chunk-2LUVO7GM.js";import{b as A}from"./chunk-2ULWP26K.js";import"./chunk-WOT6VMZA.js";var c=A.number().int().min(0).max(1e9);function R(e,o){let a=c.parse(e.promptTokens),p=c.parse(e.completionTokens),s=c.parse(e.promptTokensDetails?.cachedTokens??0),t=c.parse(e.promptTokensDetails?.cacheWriteTokens??0),r=c.parse(e.promptTokensDetails?.audioTokens??0),l=c.parse(e.completionTokensDetails?.audioTokens??0),n=c.parse(e.completionTokensDetails?.reasoningTokens??0);if(c.parse(e.totalTokens)!==a+p||s+t+r>a||n+l>p||(e.promptTokensDetails?.videoTokens??0)>0)throw new i("AI_USAGE_UNAVAILABLE","Token pools must conserve usage; video needs an explicit token mapper");return{input:a-s-t-r,output:p-l-(o==="separate"?n:0),cache_read:s,cache_write:t,input_audio:r,output_audio:l,reasoning:o==="separate"?n:0}}function I(e){if(!Number.isFinite(e)||e<0)throw new i("AI_USAGE_UNAVAILABLE","Provider cost must be a nonnegative USD amount");let o=String(e),a=o.includes("e")?e.toFixed(18).replace(/0+$/,"").replace(/\.$/,""):o;if(!/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/.test(a)||Number(a)!==e)throw new i("AI_USAGE_UNAVAILABLE","Provider cost exceeds the supported precision");return a}async function f(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning)||!e.modelId||!e.generationId)throw new i("INVALID_REQUEST","Actual model, generation ID and reasoning pricing are required");let o={context:e.context,generationId:e.generationId,modelId:`openrouter/${e.modelId}`,usage:e.usage,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(o);let a=e.mapTokens?e.mapTokens(e.usage):R(e.usage,e.reasoning),p=e.usage.cost==null?void 0:I(e.usage.cost),s=e.quote??await e.pricing.quoteTokens({modelId:o.modelId,tokens:a});if(s.pricing.modelId!==o.modelId||Object.keys(a).some(l=>a[l]!==s.tokens[l]))throw new i("INVALID_REQUEST","Saved quote must match the provider model and token pools");await e.persist({...o,tokens:a,quote:s,phase:"quoted"});let t=await e.pricing.trackTokens(e.client,{...e.context,quote:s,providerCostUsd:p,generationId:e.generationId});if(!t.receipt.accepted)throw new i("AI_BALANCE_REJECTED","OpenRouter usage was saved but the balance request was rejected");let r={...o,tokens:a,quote:s,receipt:t,phase:"settled"};return await e.persist(r),r}function T(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning))throw new i("INVALID_REQUEST","Reasoning pricing is required");let o=e.openRouter.chat;async function a(t){if(!t.usage||!t.modelId||!t.generationId)throw new i("AI_USAGE_UNAVAILABLE","OpenRouter did not return final usage and the actual model");await f({...e,context:t.context,generationId:t.generationId,modelId:t.modelId.slice(11),usage:t.usage})}let p=async(t,r)=>{let n={context:await e.context(),generationId:null,modelId:null,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"},d;try{d=await o.send(t,r)}catch(g){throw await e.persist(n),g}if(!(d instanceof ReadableStream)){if(n={...n,generationId:d.id,modelId:d.model?`openrouter/${d.model}`:null,usage:d.usage??null},!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter omitted final accounting");return await a(n),d}let w=d.getReader(),m=!1;return new ReadableStream({async pull(g){try{let{value:u,done:k}=await w.read();if(k){if(m=!0,!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter stream ended without final accounting");await a(n),g.close();return}if(u.error)throw new i("AI_PROVIDER_ERROR",u.error.message);u.usage&&(n={...n,generationId:u.id,modelId:u.model?`openrouter/${u.model}`:null,usage:u.usage}),g.enqueue(u)}catch(u){m||(m=!0,await e.persist(n)),await w.cancel(u),g.error(u)}},async cancel(g){m||(m=!0,await e.persist(n)),await w.cancel(g)}})},s=new Proxy(o,{get(t,r){return r==="send"?p:Reflect.get(t,r,t)}});return new Proxy(e.openRouter,{get(t,r){return r==="chat"?s:Reflect.get(t,r,t)}})}export{T as createOpenRouterUsageClient,f as trackOpenRouterUsage};
1
+ import"./chunk-UJMP7AMY.js";import"./chunk-FTGRTYBL.js";import"./chunk-PG5UESZB.js";import"./chunk-LSVTH3TS.js";import{a as i}from"./chunk-TL67SYPH.js";import"./chunk-6XRXHFM6.js";import"./chunk-T43HTIQX.js";import{b as A}from"./chunk-GPJF3T43.js";import"./chunk-WOT6VMZA.js";var c=A.number().int().min(0).max(1e9);function R(e,o){let a=c.parse(e.promptTokens),p=c.parse(e.completionTokens),s=c.parse(e.promptTokensDetails?.cachedTokens??0),t=c.parse(e.promptTokensDetails?.cacheWriteTokens??0),r=c.parse(e.promptTokensDetails?.audioTokens??0),l=c.parse(e.completionTokensDetails?.audioTokens??0),n=c.parse(e.completionTokensDetails?.reasoningTokens??0);if(c.parse(e.totalTokens)!==a+p||s+t+r>a||n+l>p||(e.promptTokensDetails?.videoTokens??0)>0)throw new i("AI_USAGE_UNAVAILABLE","Token pools must conserve usage; video needs an explicit token mapper");return{input:a-s-t-r,output:p-l-(o==="separate"?n:0),cache_read:s,cache_write:t,input_audio:r,output_audio:l,reasoning:o==="separate"?n:0}}function I(e){if(!Number.isFinite(e)||e<0)throw new i("AI_USAGE_UNAVAILABLE","Provider cost must be a nonnegative USD amount");let o=String(e),a=o.includes("e")?e.toFixed(18).replace(/0+$/,"").replace(/\.$/,""):o;if(!/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/.test(a)||Number(a)!==e)throw new i("AI_USAGE_UNAVAILABLE","Provider cost exceeds the supported precision");return a}async function f(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning)||!e.modelId||!e.generationId)throw new i("INVALID_REQUEST","Actual model, generation ID and reasoning pricing are required");let o={context:e.context,generationId:e.generationId,modelId:`openrouter/${e.modelId}`,usage:e.usage,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(o);let a=e.mapTokens?e.mapTokens(e.usage):R(e.usage,e.reasoning),p=e.usage.cost==null?void 0:I(e.usage.cost),s=e.quote??await e.pricing.quoteTokens({modelId:o.modelId,tokens:a});if(s.pricing.modelId!==o.modelId||Object.keys(a).some(l=>a[l]!==s.tokens[l]))throw new i("INVALID_REQUEST","Saved quote must match the provider model and token pools");await e.persist({...o,tokens:a,quote:s,phase:"quoted"});let t=await e.pricing.trackTokens(e.client,{...e.context,quote:s,providerCostUsd:p,generationId:e.generationId});if(!t.receipt.accepted)throw new i("AI_BALANCE_REJECTED","OpenRouter usage was saved but the balance request was rejected");let r={...o,tokens:a,quote:s,receipt:t,phase:"settled"};return await e.persist(r),r}function T(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning))throw new i("INVALID_REQUEST","Reasoning pricing is required");let o=e.openRouter.chat;async function a(t){if(!t.usage||!t.modelId||!t.generationId)throw new i("AI_USAGE_UNAVAILABLE","OpenRouter did not return final usage and the actual model");await f({...e,context:t.context,generationId:t.generationId,modelId:t.modelId.slice(11),usage:t.usage})}let p=async(t,r)=>{let n={context:await e.context(),generationId:null,modelId:null,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"},d;try{d=await o.send(t,r)}catch(g){throw await e.persist(n),g}if(!(d instanceof ReadableStream)){if(n={...n,generationId:d.id,modelId:d.model?`openrouter/${d.model}`:null,usage:d.usage??null},!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter omitted final accounting");return await a(n),d}let w=d.getReader(),m=!1;return new ReadableStream({async pull(g){try{let{value:u,done:k}=await w.read();if(k){if(m=!0,!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter stream ended without final accounting");await a(n),g.close();return}if(u.error)throw new i("AI_PROVIDER_ERROR",u.error.message);u.usage&&(n={...n,generationId:u.id,modelId:u.model?`openrouter/${u.model}`:null,usage:u.usage}),g.enqueue(u)}catch(u){m||(m=!0,await e.persist(n)),await w.cancel(u),g.error(u)}},async cancel(g){m||(m=!0,await e.persist(n)),await w.cancel(g)}})},s=new Proxy(o,{get(t,r){return r==="send"?p:Reflect.get(t,r,t)}});return new Proxy(e.openRouter,{get(t,r){return r==="chat"?s:Reflect.get(t,r,t)}})}export{T as createOpenRouterUsageClient,f as trackOpenRouterUsage};
@@ -0,0 +1 @@
1
+ import{e as o}from"./chunk-MEDW4N3F.js";import"./chunk-LZ3OJYBY.js";import"./chunk-AV2WZSII.js";import"./chunk-PBZSOTKZ.js";import"./chunk-HLCDAU5A.js";import"./chunk-DCZWNTG2.js";import"./chunk-ASL7TJFU.js";import"./chunk-RDUKCMST.js";import"./chunk-KP4QI4RX.js";import"./chunk-5TJISOWN.js";import"./chunk-VILB5M4X.js";import"./chunk-FTGRTYBL.js";import"./chunk-LSVTH3TS.js";import"./chunk-7MYS52FL.js";import"./chunk-MWICFZUF.js";import"./chunk-CWD36SJO.js";import"./chunk-5JRBCW6V.js";import"./chunk-3SXPCVIP.js";import"./chunk-6XRXHFM6.js";import"./chunk-GPJF3T43.js";import"./chunk-C4NG6RVA.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";export{o as apiOperations};
package/dist/page.js CHANGED
@@ -1 +1 @@
1
- import{d as o,e as r,f as e,g as f}from"./chunk-OEONV3JY.js";import"./chunk-2P2YSNYU.js";import"./chunk-3VUPVXAV.js";import"./chunk-2LUVO7GM.js";import"./chunk-DSPLGTQI.js";import"./chunk-CQRSMCCG.js";import"./chunk-PBBREFS5.js";import"./chunk-WOT6VMZA.js";export{f as createPageExperiments,o as mergeQueryStrings,r as pageAttributes,e as readPayload};
1
+ import{d as o,e as r,f as e,g as f}from"./chunk-2PVQUPBN.js";import"./chunk-X4UTTXOU.js";import"./chunk-3VUPVXAV.js";import"./chunk-T43HTIQX.js";import"./chunk-DSPLGTQI.js";import"./chunk-C4NG6RVA.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";export{f as createPageExperiments,o as mergeQueryStrings,r as pageAttributes,e as readPayload};
@@ -0,0 +1 @@
1
+ import{a as Qt,c as jt,d as pt,f as mt,g as Bt,k as Ft}from"./chunk-HTXB2WVI.js";import{b as dt}from"./chunk-W32FI2A2.js";import{d as _t,e as Mt,f as Ut,h as ft,i as qe,j as $t,k as Vt,l as Ht}from"./chunk-P6TNBX2S.js";import{a as Tt,c as lt,d as St,e as Dt}from"./chunk-B4AELNLE.js";import{a as Fe,b as me,d as ut,f as Nt,j as Lt}from"./chunk-AQONMY2H.js";import{b as ue}from"./chunk-RDUKCMST.js";import{B as A,C as Be,D as Re,E as Oe,y as Ot}from"./chunk-KP4QI4RX.js";import"./chunk-5TJISOWN.js";import"./chunk-VILB5M4X.js";import"./chunk-PG5UESZB.js";import"./chunk-LSVTH3TS.js";import{r as be,t as pe}from"./chunk-7MYS52FL.js";import{i as Rt}from"./chunk-MWICFZUF.js";import{c as le,j as Ae}from"./chunk-CWD36SJO.js";import{c as ct}from"./chunk-5JRBCW6V.js";import"./chunk-3SXPCVIP.js";import{a as P}from"./chunk-TL67SYPH.js";import"./chunk-6XRXHFM6.js";import"./chunk-T43HTIQX.js";import"./chunk-GPJF3T43.js";import{a as G}from"./chunk-DSPLGTQI.js";import"./chunk-C4NG6RVA.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";async function qt(_,a,E){if(!Re(a))throw new P("INVALID_RESPONSE","A verified completed purchase is required");let k=_?Ae.parse(_):null;if(await E.onComplete?.(a),!k||!E.check)return;let U=Ae.parse(await E.check());if(U.internal_feature_id!==k.internal_feature_id||U.quantity!==k.quantity||k.observation!==void 0&&(U.observation===void 0||U.observation.requirementDigest!==k.observation.requirementDigest||U.observation.authority!==k.observation.authority||ct(U.observation.subject)!==ct(k.observation.subject)))throw new P("INVALID_RESPONSE","The access requirement changed");U.allowed&&await E.onAccessGranted?.(U)}function ht(_){return Object.entries(_.document.buttons).filter(([,a])=>a.type==="checkout"&&a.product.type==="fixed"&&!ue(a.product,{},_.capabilities)).map(([a])=>a)}function Gt(_,a){let E=A(a)?void 0:a.lines[0];if(!A(a)&&(a.lines.length!==1||!E))return;let k=A(a)?a.productVersionId:E.productVersionId,{screen:U,buttons:X}=_.document,R=new Map(A(a)?Object.entries(a.featureQuantities??{}):(E?.prepaid??[]).map(h=>[h.internal_feature_id,h.quantity]));function Z(h,m){if(h.hidden)return!1;if(h.type==="plan_picker"&&_.capabilities.pickers[h.id]?.options.includes(k))return m[h.id]=k,!0;if(h.type==="quantity_picker"){let Y=R.get(h.internalFeatureId);return Y!==void 0&&(!h.bind?.plan||h.bind.plan===k)&&(m[h.id]=Y),!1}if(h.type==="button"&&h.action){let Y=X[h.action];return Y?.type==="checkout"&&Y.product.type==="fixed"&&Y.product.productVersionId===k}if(h.type!=="stack")return!1;let z=h.interaction,i=h.bind?.plan===k;for(let[Y,d]of h.children.entries()){let re={},N=Z(d,re);if(z?.type==="toggle"||z?.type==="tabs"){if(!N)continue;return m[h.id]=z.type==="toggle"?Y===0:d.id,Object.assign(m,re),!0}Object.assign(m,re),N&&(i=!0,z?.type==="select"&&z.purpose==="product"&&z.pickerId&&d.type==="stack"&&d.bind?.plan===k&&(m[h.id]=d.id,m[z.pickerId]=k))}return i}for(let h of U.pages){let m={__page:h.id};if(Z(h.root,m))return m}}async function _n(_,a,E){let k=a.focusAtReveal?()=>{}:ft(_.ownerDocument),U=()=>{R.finish("dismissed"),k()},X=()=>U(),R=$t(_,a,"paywall",()=>{U(),G(a.onDismiss)},Qt);a.signal?.throwIfAborted(),a.signal?.addEventListener("abort",X,{once:!0});let Z=null,h,m,z;try{if(R.start(!0,a.loadingDocument?.screen.strings.defaultLocale,a.loadingDocument??null),R.cancelled)throw new DOMException("Presentation cancelled","AbortError");if(Z=a.check?Ae.parse(await R.wait(a.check(),qe)):null,Z?.allowed)return R.finish("skipped"),a.signal?.removeEventListener("abort",X),k(),await a.onAccessGranted?.(Z),{check:Z,host:null};let[e,t]=await Promise.allSettled([R.wait(import("./screen-renderer-RDXKWHYE.js")),R.wait(a.start().then(r=>(R.cancelled&&r.destroy(),r)),qe)]);if(e.status==="rejected")throw t.status==="fulfilled"&&t.value.destroy(),e.reason;if(t.status==="rejected")throw t.reason;z=e.value,h=t.value,a.signal?.throwIfAborted(),h.signal?.throwIfAborted(),h.signal?.addEventListener("abort",X,{once:!0});let n=h.view??await R.wait(h.refresh(),qe);if(!n)throw new P("INVALID_RESPONSE","Paywall presentation is missing");h.signal?.throwIfAborted(),m=n}catch(e){throw R.finish("error",e),a.signal?.removeEventListener("abort",X),h?.signal?.removeEventListener("abort",X),h?.destroy(),k(),e}let i=h,{mountScreenPreview:Y}=z,d=_.ownerDocument,re=new AbortController,N=d.createElement("section"),he=d.createElement("div"),J=d.createElement("div"),Ge=a.mountControls,W=Ge?d.createElement("div"):void 0,f=d.createElement("p"),C=d.createElement("button"),x=d.createElement("button"),O=d.createElement("dialog"),We=i.locale||m.document.screen.strings.defaultLocale,o=We.toLowerCase().startsWith("zh"),Wt=o?"\u6B63\u5728\u5904\u7406\u2026":"Processing\u2026",zt=o?"\u6B63\u5728\u51C6\u5907\u62A5\u4EF7\u2026":"Preparing your price\u2026",M=jt(m.document.screen.theme);N.dataset.indianaPaywall="",N.setAttribute("aria-label",m.document.name),N.style.cssText=M.root,J.style.cssText=M.controls,f.style.cssText=M.message,f.setAttribute("role","status"),x.style.cssText=M.link,x.textContent=o?"\u5173\u95ED":"Close",C.style.cssText=M.secondary,C.textContent=o?"\u91CD\u8BD5":"Retry",C.hidden=!0,J.append(f,C,x),W&&(W.style.cssText="flex:1 0 100%;min-width:0",W.hidden=!0,J.prepend(W)),N.append(he,J);let ze=()=>{if(W){let r=!W.childElementCount&&!W.textContent?.trim();W.hidden!==r&&(W.hidden=r)}let e=ae??J,t=[...e.children].every(r=>r===f?!f.textContent:r.hidden),n=[...e.children].some(r=>r===x?!1:r===f?!!f.textContent:!r.hidden);e.style.cssText=t?M.controls.replace(/padding:[^;]+/,"padding:0"):n?`${M.controls};${M.pinned}`:M.controls,Xe()},yt=typeof MutationObserver>"u"?void 0:new MutationObserver(ze);yt?.observe(N,{attributes:!0,attributeFilter:["hidden"],characterData:!0,childList:!0,subtree:!0});let Te=m.document.presentation,Yt=Object.entries(m.document.buttons).filter(([,e])=>e.type==="close").map(([e])=>e),B,wt,Ye=!1,gt=JSON.stringify(m.capabilities),Je=e=>ie&&!Ce?Object.entries(e.document.buttons).filter(([,t])=>t.type==="checkout").map(([t])=>t):ht(e);function Se(e){if(w)return;m=e;let t=JSON.stringify(e.capabilities);if(t!==gt){let n=!b&&!i.quote&&!i.operation?Fe(e,q,Ct):q;JSON.stringify(n)!==JSON.stringify(q)?(q=n,B?.update(e.document.screen,We,{capabilities:me(e),unavailableActions:Je(e),serverInput:{bindings:[],answers:{}},selection:q})):B?.updateCapabilities(me(e),Je(e)),gt=t}Xt(e),ve()}let I,Ke=0;function Xe(){let e=d.defaultView;if(!I?.responsive||!e)return;let t=ae??J,n=e.innerHeight-(I.type==="modal"?32:0);t.style.maxHeight=`${Math.max(1,n)}px`,t.style.overflowY="auto",t.style.flexShrink="0",Ke=Math.max(1,n-t.getBoundingClientRect().height),B?.resizeViewport?.(Ke,e.innerWidth)}let w=!1,ie=!1,b=null,Ze,De=!1,bt=!1,de=!1,et,tt=!1,ee,ae;function Jt(){return ie||w||ee||tt?{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null}:lt(i)}let T=()=>!w&&!De&&!ee&&a.canInteract?.()!==!1,F,ye=!1,we=!1,p=null,te=null,nt="",fe=()=>a.checkoutNavigation==="after_confirmation"&&!!(a.terminateCheckout||a.resumeCheckout),q={},Ct=new Set,Ce,K=null;function ve(){if(!fe()||!B?.updateCheckoutControls)return;let e=i.quote,t=!K&&!!e&&!!i.operation&&S(i.operation).type==="checkout",n=Object.entries(m.document.buttons).flatMap(([r,c])=>c.type==="checkout"?[{actionId:r,policy:c}]:[]);B.updateCheckoutControls({actions:n.map(({actionId:r})=>r),resume:t?n.filter(({actionId:r,policy:c})=>Me(e,m,r,c.product,q)).map(({actionId:r})=>r):[],resumeLabel:o?"\u7EE7\u7EED\u4ED8\u6B3E":"Continue checkout",busy:Ce})}function vt(){te?.remove(),te=null}async function rt(){if(K)return;if(a.resumeCheckout&&i.operation){await a.resumeCheckout(i.operation.operationId);return}let e=await i.read();if(S(e).type!=="checkout")return $(e,!1);T()&&(Le.delete(e.operationId),await Ue(e))}function Pt(){f.textContent=o?"\u6682\u65F6\u65E0\u6CD5\u6253\u5F00\u4ED8\u6B3E\u9875\u9762\u3002\u8BF7\u91CD\u8BD5\u3002":"Couldn\u2019t open checkout. Try again.",C.hidden=!0}async function kt(e=!1){let t=K;if(!t)return;C.hidden=!0;let n=Date.now()+2e4;for(;T();){let r=await i.read();if(r.operationId!==t.operationId)throw new P("PURCHASE_PENDING","The original Checkout changed");if(!T())break;let c=S(r);if(c.type==="native"){K=null,vt(),b=t.selection,F=t.coupon,ye=!1,we=!1,await xe();return}if(c.type==="complete"||c.type==="fulfillment"||c.type==="recording"){K=null,await $(r,!1);return}if(e&&c.type==="checkout"){e=!1;try{await a.terminateCheckout(t.operationId)}catch(g){G(a.onError,g)}}if(Date.now()>=n)break;await dt(1e3,d,re.signal)}w||Pt()}async function Kt(e,t,n){K={operationId:e,selection:t,coupon:n};let r=!1;try{await a.terminateCheckout(e)}catch(c){if(c instanceof P&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(c.code)){K=null,f.textContent=o?"\u8BF7\u7EE7\u7EED\u539F\u8BA2\u5355\uFF0C\u6216\u7B49\u5F85\u5B83\u8FC7\u671F\u540E\u518D\u66F4\u6362\u65B9\u6848\u3002":"Continue your original checkout, or wait for it to expire before changing plans.",G(a.onError,c);return}r=c instanceof P&&(c.status??0)>=500,G(a.onError,c)}T()&&await kt(r)}function Ne(e,t,n,r,c){let g=me(e).checkoutCoupons?.[t],l=g?g.products[n]:a.claimCoupon&&c?Rt(e.capabilities,c,r):void 0;return l?.couponId&&l.planVersionId===n?{id:l.couponId,offerId:l.offerId}:void 0}function Xt(e){ie||b||i.quote||i.operation||nt&&f.textContent===nt||(f.textContent=Object.values(e.capabilities.plans).some(t=>t.available)?"":o?"\u5F53\u524D\u8D26\u53F7\u6682\u65E0\u53EF\u8D2D\u4E70\u7684\u65B9\u6848\u3002":"No plans are currently available for this account.")}let Le=new Map,_e=!1;function Me(e,t,n,r,c,g){if(A(e)){let H=ue(r,c,t.capabilities),ce=H&&Ne(t,n,H,c,g),Ie=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0),Ve=pe(t.document.screen,e.productVersionId,c,t.capabilities);return H===e.productVersionId&&Object.keys(Ve).length===Object.keys(e.featureQuantities??{}).length&&Object.entries(Ve).every(([He,Qe])=>e.featureQuantities?.[He]===Qe)&&(!ce||Ie?.couponId===ce.id&&(!ce.offerId||Ie.grantId===ce.offerId))}let l=e.lines.length===1?e.lines[0]:void 0,s=ue(r,c,t.capabilities);if(!l||!s||l.productVersionId!==s)return!1;let L=Ne(t,n,s,c,g);if((L||me(t).checkoutCoupons?.[n])&&(L?.id??null)!==(e.discount?.couponId??null))return!1;let V;try{V=pe(t.document.screen,s,c,t.capabilities)}catch{return!1}let se=Object.fromEntries((l.prepaid??[]).map(H=>[H.internal_feature_id,H.quantity]));return[...new Set([...Object.keys(V),...Object.keys(se)])].every(H=>(V[H]??0)===(se[H]??0))}let S=e=>Tt({quote:i.quote,operation:e,requestId:null,pending:!1,destroyed:w,canReselect:i.canReselect});async function Ue(e){let t=e.merchantExecution,n=S(e),r=n.type==="checkout"?n.checkoutUrl:e.checkoutUrl;if(!(!T()||!r||Be(e)&&n.type!=="checkout"||a.checkoutNavigation==="after_confirmation"&&n.type!=="checkout"||t?.type==="purchase"&&!["not_started","pending"].includes(t.paymentStatus)||Le.get(e.operationId)===r)){Le.set(e.operationId,r);try{a.onCheckoutUrl?await a.onCheckoutUrl(r):d.defaultView?.location.assign(r)}catch(c){throw Le.delete(e.operationId),c}}}let oe=(e,t=!1)=>{if(e instanceof ut)p=null,f.textContent=e.customerMessage(o);else if(Bt(e))p=null,f.textContent=t?o?"\u5F53\u524D\u65E0\u6CD5\u5728\u6B64\u8D2D\u4E70\uFF0C\u4ED8\u6B3E\u5C1A\u672A\u5F00\u59CB\u3002\u8BF7\u8054\u7CFB\u5546\u6237\u3002":"Purchases aren\u2019t available here right now. Payment hasn\u2019t started. Contact the merchant for help.":mt(e,o);else if(t){let n=e instanceof P?e.code:void 0;n==="CAPABILITY_UNAVAILABLE"||n==="NOT_CONFIGURED"?(p=null,f.textContent=o?"\u6682\u65F6\u65E0\u6CD5\u4E3A\u6B64\u5957\u9910\u62A5\u4EF7\uFF0C\u4ED8\u6B3E\u5C1A\u672A\u5F00\u59CB\u3002":"Pricing for this plan is unavailable. Payment hasn\u2019t started."):i.canReselect===!0&&!b?f.textContent=o?"\u672A\u80FD\u53D6\u5F97\u62A5\u4EF7\uFF0C\u4ED8\u6B3E\u5C1A\u672A\u5F00\u59CB\u3002\u8BF7\u91CD\u65B0\u9009\u62E9\u5957\u9910\u3002":"We couldn\u2019t prepare your price. Payment hasn\u2019t started. Choose a plan again.":n==="COMMAND_PENDING"?f.textContent=o?"\u4ECD\u5728\u51C6\u5907\u62A5\u4EF7\uFF0C\u8BF7\u91CD\u8BD5\u4EE5\u67E5\u770B\u7ED3\u679C\u3002":"Your price is still being prepared. Retry to check the result.":f.textContent=o?"\u672A\u80FD\u53D6\u5F97\u62A5\u4EF7\uFF0C\u4ED8\u6B3E\u5C1A\u672A\u5F00\u59CB\u3002\u8BF7\u91CD\u8BD5\u3002":"We couldn\u2019t prepare your price. Payment hasn\u2019t started. Try again."}else f.textContent=e instanceof P&&(e.code==="NETWORK_ERROR"||e.code==="TIMEOUT")?mt(e,o):e instanceof P?e.message:o?"\u64CD\u4F5C\u672A\u5B8C\u6210\uFF0C\u8BF7\u91CD\u8BD5\u3002":"This action couldn\u2019t be completed. Try again.";C.hidden=p===null,nt=f.textContent,t&&!I?.responsive&&f.scrollIntoView?.({block:"nearest"}),G(t&&E?.quoteError?E.quoteError:a.onError,e)},Pe=new WeakMap;function ke(e){ie=e,C.disabled=e,B?.updateCapabilities?.(me(m),Je(m));for(let t of te?.querySelectorAll("button")??[])e?(Pe.has(t)||Pe.set(t,t.disabled),t.disabled=!0):Pe.has(t)&&(t.disabled=Pe.get(t),Pe.delete(t)),pt(t)}function it(){f.textContent=o?"\u6682\u65F6\u65E0\u6CD5\u64CD\u4F5C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"This action is unavailable right now. Try again in a moment."}async function Zt(e){if(a.beforeAction)try{await a.beforeAction()}catch(t){throw t instanceof ut?(b=null,ye=!1,we=!1,p=null):p=e,t}}async function j(e,t){if(ie||w)return;if(!T()){it();return}let n=e===xe,r=n?zt:Wt,c=fe()&&t!==void 0;Ce=c?t:void 0,ke(!0),ve(),C.hidden=!0,f.textContent=c?"":r;try{if(e!==It&&(e!==rt||!a.resumeCheckout)&&await Zt(e),w)return;if(!T()){p=e,C.hidden=!1,it();return}await e()}catch(g){w||oe(g,n&&!c)}finally{Ce=void 0,ke(!1),ve(),f.textContent===r&&(f.textContent="")}}async function en(e){await qt(Z,e,a)}function Et(e){return lt(i).type==="recording"||S(e).type==="recording"}function xt(e){let t=e.merchantTerms,n=t?.subscriptionTerms?.items??[],r=t?t.totalMinor:A(e)?e.totalMinor:e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),c=t?n.length===1&&n[0]?.amountMinor===r&&n[0]:!A(e)&&e.lines.length===1&&e.lines[0]?.catalogAmountMinor===r&&e.lines[0],g=r===null?le(t.subtotalMinor-t.discountMinor,e.currency)+(o?" + \u5F85\u786E\u8BA4\u7A0E\u8D39":" + tax confirmed at checkout"):le(r,e.currency)+(c?be(c.interval,o?"zh-CN":"en",c.intervalCount??1):""),l=A(e)?i.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(s=>s.productName).join(", ");return{label:l?`${l} \xB7 ${g}`:g,recurring:c}}async function $(e,t=a.checkoutNavigation!=="after_confirmation"){if(w)return;if(!T()){p=async()=>$(await i.read()),C.hidden=!1;return}if(f.textContent=Ft(e.status,o),Et(e)){let s=e.merchantExecution?.recordingStatus==="failed";f.textContent=s?o?"\u4ED8\u6B3E\u548C\u5546\u6237\u5904\u7406\u5DF2\u5B8C\u6210\uFF0C\u4F46\u4EA4\u6613\u8BB0\u5F55\u5931\u8D25\u3002\u8BF7\u8054\u7CFB\u5546\u6237\u4FEE\u590D\uFF0C\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"Payment and fulfillment succeeded, but recording failed. Contact the merchant to repair this purchase; do not buy again.":o?"\u4ED8\u6B3E\u548C\u5546\u6237\u5904\u7406\u5DF2\u5B8C\u6210\uFF0C\u6B63\u5728\u786E\u8BA4\u4EA4\u6613\u8BB0\u5F55\u3002\u8BF7\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"Payment and merchant fulfillment are complete. Recording is pending confirmation; do not purchase again.",C.textContent=o?"\u67E5\u8BE2\u8BB0\u5F55":"Check recording",p=async()=>$(await i.read()),C.hidden=!1;return}if(e.problem&&S(e).type!=="native"){let s=e.problem;p=Ee,C.textContent=o?"\u68C0\u67E5\u5E76\u6062\u590D\u539F\u64CD\u4F5C":"Check and recover original purchase",oe(new P(s.code,s.reason==="RESULT_UNKNOWN"?o?"\u4ED8\u6B3E\u7ED3\u679C\u5C1A\u672A\u786E\u5B9A\uFF0C\u8BF7\u6062\u590D\u539F\u64CD\u4F5C\uFF0C\u6682\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"The payment result is unknown. Recover the original purchase before buying again.":s.phase==="fulfillment"?o?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u5546\u6237\u6743\u76CA\u5904\u7406\u9700\u8981\u6838\u5BF9\u3002":"Payment was recorded. Access fulfillment needs attention.":s.code==="CAPABILITY_UNAVAILABLE"?o?"\u5546\u6237\u5C1A\u4E0D\u652F\u6301\u672C\u6B21\u8D2D\u4E70\u6240\u9700\u7684\u5B8C\u6574\u80FD\u529B\uFF0C\u8BF7\u5904\u7406\u540E\u6062\u590D\u539F\u64CD\u4F5C\u3002":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":s.code==="NOT_CONFIGURED"?o?"\u4ED8\u6B3E\u670D\u52A1\u8FDE\u63A5\u9700\u8981\u5904\u7406\uFF0C\u8BF7\u8054\u7CFB\u5546\u6237\u540E\u6062\u590D\u539F\u64CD\u4F5C\u3002":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":o?"\u539F\u8D2D\u4E70\u64CD\u4F5C\u9700\u8981\u5904\u7406\uFF0C\u8BF7\u67E5\u8BE2\u6216\u6062\u590D\u6B64\u64CD\u4F5C\u3002":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,s));return}if((e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"||e.merchantExecution?.type==="subscription_change"&&e.merchantExecution.status==="applied")&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(f.textContent=o?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u6B63\u5728\u7B49\u5F85\u5546\u6237\u5B8C\u6210\u5904\u7406\u3002":"Payment was recorded. Waiting for merchant fulfillment."),Re(e)&&S(e).type==="complete"){p=null,await en(e);return}if(!Oe(e)&&S(e).type!=="fulfillment"){if(i.canReselect===!1){f.textContent=o?"\u6B63\u5728\u6838\u5BF9\u539F\u8D2D\u4E70\u7ED3\u679C":"Checking the original purchase result",C.textContent=o?"\u67E5\u8BE2\u7ED3\u679C":"Check result",p=async()=>$(await i.read()),C.hidden=!1;return}e.status==="cancelled"?f.textContent=o?"\u8FD9\u7B14\u8D2D\u4E70\u5DF2\u53D6\u6D88\uFF0C\u53EF\u4EE5\u91CD\u65B0\u9009\u62E9\u65B9\u6848\u3002":"This purchase was cancelled. Choose a plan to start again.":e.status==="failed"&&(f.textContent=o?"\u8FD9\u7B14\u8D2D\u4E70\u672A\u80FD\u5B8C\u6210\uFF0C\u53EF\u4EE5\u91CD\u65B0\u9009\u62E9\u65B9\u6848\u3002":"This purchase didn\u2019t go through. Choose a plan to try again."),C.textContent=o?"\u91CD\u8BD5":"Retry",p=null,b=null;return}if(!t&&S(e).type==="checkout"){if(K){Pt();return}if(fe()){f.textContent="",_e=!1,p=null,ve();return}let s=i.quote,L=s?.operationId===e.operationId?xt(s).label:"";f.textContent=_e?L?o?`${L} \u5C1A\u672A\u4ED8\u6B3E\u3002\u518D\u6B21\u9009\u62E9\u8BE5\u65B9\u6848\u5373\u53EF\u7EE7\u7EED\u4ED8\u6B3E\u3002`:`${L} is still unpaid. Choose it again to continue paying.`:o?"\u4E4B\u524D\u7684\u8D2D\u4E70\u5C1A\u672A\u4ED8\u6B3E\u3002\u518D\u6B21\u9009\u62E9\u8BE5\u65B9\u6848\u5373\u53EF\u7EE7\u7EED\u4ED8\u6B3E\u3002":"Your earlier purchase is still unpaid. Choose that plan again to continue paying.":"",_e=!1,p=null;return}await Ue(e);let n=Date.now(),r=n+6e5,c=2e3,g=S(e).type!=="checkout",l=()=>g&&Date.now()-n<15e3;Ye=!0,G(a.onObservationChange,!0);try{for(;!w&&Date.now()<r;){if(await dt(l()?700:c,d,re.signal),w)return;if(!T()){p=async()=>$(await i.read()),C.hidden=!1;return}let s=await i.read();if(S(s).type==="checkout"&&(g=!1),!t&&S(s).type==="checkout"){await $(s,!1);return}if(!s.problem&&Oe(s)&&await Ue(s),!Oe(s)||s.problem||Et(s)){await $(s);return}l()||(c=Math.min(c*1.5,3e4))}}finally{Ye=!1,G(a.onObservationChange,!1)}p=async()=>$(await i.read()),C.hidden=!1}async function at(e=!1){let t=await i.read();if(w)return;if(!T()){p=()=>at(e),C.hidden=!1;return}let n=i.quote;if(n&&Nt(t,{operationId:n.operationId,currency:n.currency},"The original purchase operation changed"),n&&(Be(t)?["prepared","quoted"].includes(t.status):t.status==="pending")&&(Be(t)||t.quoteFinalized===!1)&&!t.confirmedAt&&!t.checkoutUrl&&!("nativePurchase"in t&&t.nativePurchase)&&!t.merchantExecution&&!t.problem&&!i.pendingCancellation){At(n);return}await $(t,e||void 0)}async function It(){await at()}async function Ee(){vt(),p=Ee;let e=await i.confirm();if(!T()){p=Ee,C.hidden=!1;return}if(e.problem){await $(e);return}if(Oe(e)){if(S(e).type==="checkout")await Ue(e);else if(e.execution&&e.execution.provider!=="merchant"||"nativePurchase"in e&&e.nativePurchase){if(!a.onPurchase)throw new P("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await a.onPurchase({operation:e,signal:re.signal})}}p=async()=>$(await i.read()),await $(e,!0)}function At(e){te?.remove();let t=!(Date.parse(e.expiresAt)>Date.now());f.textContent=t?o?"\u6B64\u62A5\u4EF7\u5DF2\u8FC7\u671F\u3002\u8BF7\u5148\u53D6\u6D88\uFF0C\u518D\u91CD\u65B0\u9009\u62E9\u3002":"This quote has expired. Cancel it, then choose again.":"";let n=d.createElement("div"),r=d.createElement("button"),c=d.createElement("button"),g=d.createElement("div"),l=d.createElement("p"),s=e.merchantTerms,L=o?"zh-CN":"en",V=s?.subscriptionTerms?.items??[],se=s?s.subscriptionTerms?.trial?.days:A(e)?void 0:e.lines.find(u=>u.trial)?.trial?.days,ne=A(e)?s?s.totalMinor:e.totalMinor:se===void 0?null:s?s.totalMinor:e.charge?e.charge.totalMinor:e.lines.every(u=>u.trial)?0:null,H=(u,y)=>o?`${y} \u5929\u8BD5\u7528\u7ED3\u675F\u540E ${u}`:`Then ${u} after the ${y}-day trial`,{label:ce,recurring:Ie}=xt(e),Ve=A(e)?i.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(u=>u.productName).join(", "),He=ne===null?"":`${o?"\u4ECA\u5929\u5E94\u4ED8":"Due today"} ${le(ne,e.currency)}`;l.textContent=He?[Ve,He].filter(Boolean).join(" \xB7 "):ce,r.textContent=A(e)?o?"\u786E\u8BA4\u53D8\u66F4":"Confirm change":o?"\u786E\u8BA4\u8D2D\u4E70":"Confirm purchase",r.disabled=t,c.textContent=o?"\u53D6\u6D88":"Cancel",n.style.cssText=M.panel,l.style.cssText=M.summary,g.style.cssText=M.actions,r.style.cssText=M.primary,c.style.cssText=M.secondary,pt(r),r.onclick=()=>{j(Ee)};let Qe=async()=>{let u=await i.cancel();w||(n.remove(),te=null,await $(u))};c.onclick=()=>{p=Qe,j(Qe)};let Q=d.createElement("div");if(Q.style.cssText=M.terms,A(e)){for(let[y,v]of Object.entries(e.featureQuantities??{})){let D=i.view?.capabilities.plans[e.productVersionId]?.prepaid?.find(tn=>tn.internalFeatureId===y),je=d.createElement("p");je.textContent=`${D?.name??y} \xB7 ${v} ${o?"\u4EFD":"packs"}${D?` \xD7 ${D.terms.units}`:""}`,Q.append(je)}for(let[y,v]of[[o?"\u539F\u8BA2\u9605\u62B5\u6263":"Unused subscription credit",e.creditMinor],[o?"\u65B0\u5957\u9910\u8D39\u7528":"New plan charge",e.debitMinor],[o?"\u4F18\u60E0\u51CF\u514D":"Offer savings",s?.discountMinor??e.discountMinor],[o?"\u7A0E\u8D39":"Tax",s?s.taxMinor:e.taxMinor]]){let D=d.createElement("p");D.textContent=`${y}: ${v===null?o?"\u7ED3\u8D26\u65F6\u786E\u8BA4":"Confirmed at checkout":le(v,e.currency)}`,Q.append(D)}let u=d.createElement("p");u.textContent=`${o?"\u751F\u6548\u65F6\u95F4":"Effective"}: ${e.effectiveAt}`,Q.append(u)}if(s){for(let y of V){if(ne===null&&y===Ie)continue;let v=d.createElement("p"),D=le(y.amountMinor,e.currency)+be(y.interval,L,y.intervalCount);v.textContent=ne!==null&&se!==void 0?H(D,se):D,y.amountAfterOfferMinor!==void 0&&(v.textContent+=` \xB7 ${o?"\u4F18\u60E0\u7ED3\u675F\u540E":"After the offer"} ${le(y.amountAfterOfferMinor,e.currency)}${be(y.interval,L,y.intervalCount)}`),Q.append(v)}let u=s.subscriptionTerms?.trial;if(u){let y=d.createElement("p");y.textContent=o?`\u8BD5\u7528 ${u.days} \u5929\uFF1B${u.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${u.days}; ${u.cardRequired?"a payment method is required":"no payment method is required"}`,Q.append(y)}for(let y of[...s.expectedEffects.map(v=>v.description),...s.requiredConsents.map(v=>v.summary)]){let v=d.createElement("p");v.textContent=y,Q.append(v)}}else if(!A(e)){for(let u of e.lines){if(ne!==null||u!==Ie){let y=d.createElement("p"),v=`${le(u.catalogAmountMinor,e.currency)}${be(u.interval,L,u.intervalCount??1)}`;y.textContent=ne!==null&&u.trial?(e.lines.length>1?`${u.productName} \xB7 `:"")+H(v,u.trial.days):`${u.productName} \xB7 ${v}`,Q.append(y)}for(let y of u.prepaid??[]){let v=d.createElement("p"),D=i.view?.capabilities.plans[u.productVersionId]?.prepaid?.find(je=>je.internalFeatureId===y.internal_feature_id);v.textContent=`${D?.name??y.internal_feature_id} \xB7 ${y.quantity} ${o?"\u4EFD":"packs"} \xD7 ${y.terms.units}`,D&&(v.textContent+=be(D.reset==="week"||D.reset==="month"||D.reset==="year"?D.reset:"one_time",L,D.resetCount)),Q.append(v)}if(u.trial){let y=d.createElement("p");y.textContent=o?`\u8BD5\u7528 ${u.trial.days} \u5929\uFF1B${u.trial.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${u.trial.days}; ${u.trial.cardRequired?"a payment method is required":"no payment method is required"}`,Q.append(y)}}if(!e.charge){let u=d.createElement("p");u.textContent=o?"\u76EE\u5F55\u4EF7\u683C\uFF1B\u6700\u7EC8\u91D1\u989D\u4EE5\u7ED3\u8D26\u65F6\u7A0E\u8D39\u548C\u8BD5\u7528\u89C4\u5219\u4E3A\u51C6\u3002":"Catalog price; the final charge depends on checkout taxes and trial terms.",Q.append(u)}}for(let u of Q.children)u.style.margin="0";g.append(r,c),n.append(l,...Q.childElementCount?[Q]:[],g),J.prepend(n),I?.responsive||n.scrollIntoView?.({block:"nearest"}),r.focus({preventScroll:!0}),te=n,ie&&ke(!0),p=null}async function xe(){if(!b)return;if(p=xe,!ye){let n=i.view,r=n?.document.buttons[b.actionId],c=n&&r?.type==="checkout"?ue(r.product,b.selection,n.capabilities):null;if(!n||!c)throw new P("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");if(!we){let l=await a.resolveSubscriptionChange?.({actionId:b.actionId,productVersionId:c,featureQuantities:pe(n.document.screen,c,b.selection,n.capabilities)});if(w)return;l!==void 0&&(b.subscriptionChange=Ot.parse(l)),we=!0}let g=F?.offerId;if(F&&!g){if(!a.claimCoupon)throw new P("CAPABILITY_UNAVAILABLE","Coupon claiming is unavailable");let{offer:l}=await a.claimCoupon(F.id,b.requestId);if(w)return;if(!l||l.couponId!==F.id||l.status!=="issued"||!(Date.parse(l.expiresAt)>Date.now()))throw b=null,F=void 0,p=async()=>{Se(await i.refresh()),p=null},new P("COUPON_UNAVAILABLE","This Coupon is no longer available for this purchase");g=l.id}if(!F&&!n.document.screen.actions.some(l=>l.id===b?.actionId&&typeof l.properties.couponBinding=="string")&&(g=await a.resolveOfferId?.({actionId:b.actionId,productVersionId:c,featureQuantities:pe(n.document.screen,c,b.selection,n.capabilities)})),w)return;g!==void 0&&(b.offerId=g),ye=!0}if(!T()){C.hidden=!1;return}let e;try{e=await i.preview(b)}catch(n){throw i.canReselect===!0&&(b=null,ye=!1,we=!1,F=void 0,p=null),n}if(F&&(A(e)?(()=>{let n=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return n?.couponId!==F.id||n.grantId!==b.offerId})():e.discount?.couponId!==F.id||e.discount.offerId!==b.offerId))throw new P("INVALID_RESPONSE","The quote did not apply the Coupon selected on this Paywall");if(w)return;let t=e.merchantTerms;if(a.confirmOnHostedCheckout&&T()&&!A(e)&&e.provider==="merchant"&&e.billingSubscriptionId===null&&t?.request.action==="purchase"&&t.request.mode==="subscription"&&t.subscriptionTerms?.trial===null&&t.requiredConsents.length===0&&Date.parse(e.expiresAt)>Date.now()){let n=Ce?"":o?"\u6B63\u5728\u6253\u5F00\u6536\u94F6\u53F0\u2026":"Opening checkout\u2026";f.textContent=n;try{await Ee()}catch(r){w||oe(r)}finally{f.textContent===n&&(f.textContent="")}return}At(e)}function ge(e="destroy"){if(w)return;w=!0;let t=Ze;Ze=void 0,G(t),a.signal?.removeEventListener("abort",X),i.signal?.removeEventListener("abort",X),R.finish("dismissed"),wt?.(),re.abort(),yt?.disconnect(),I?.destroy(),B?.destroy(),i.destroy(),O.open&&O.close(),O.remove(),N.remove(),k(),e==="dismiss"&&G(a.onDismiss)}U=ge;async function $e(){if(!de||w||De||ee==="closing"||!ee&&!T())return;if(!E){ge("dismiss");return}let e=d.createElement("p");e.setAttribute("role","status"),e.textContent=o?"\u6B63\u5728\u5173\u95ED\u2026":"Closing\u2026",ae||(ae=d.createElement("div"),ae.style.cssText=J.style.cssText,J.replaceWith(ae),he.inert=!0),x.hidden=!1,ae.replaceChildren(e,x),ee="closing",x.setAttribute("aria-disabled","true"),x.focus({preventScroll:!0});try{await E.dismiss()}catch(t){w||G(a.onError,t)}w||(ee="retry",e.textContent=o?"\u672A\u80FD\u786E\u8BA4\u5173\u95ED\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not confirm closure. Try again.",x.textContent=o?"\u91CD\u8BD5\u5173\u95ED":"Retry closing",x.removeAttribute("aria-label"),x.removeAttribute("aria-disabled"))}x.onclick=()=>{$e()},O.addEventListener("cancel",e=>{e.preventDefault(),$e()}),C.onclick=()=>{p&&j(p)};function ot(e){R.finish("error",e),ge()}function st(){if(!(!bt||de||w||De||I&&!T()))try{let e=t=>{a.focusAtReveal&&(k=ft(d)),B?.setHidden?.(!1),et?.(),I&&(O.showModal(),I.responsive&&O.focus({preventScroll:!0}),!t&&a.loading!=="host"&&Mt(O,I.type,I.responsive)),de=!0};E?E.present(()=>R.present(()=>e(!0))):R.present(e)}catch(e){ot(e),oe(e)}}try{if(Te.type==="inline"?(ze(),et=Ht(N,_),_.append(N)):(O.setAttribute("aria-label",m.document.name),x.textContent="\xD7",x.setAttribute("aria-label",o?"\u5173\u95ED":"Close"),Ut(x,m.document.screen.theme),x.hidden=Lt(m.document),O.append(x,N),_.append(O),I=_t(O,{...m.document.screen,presentation:Te},Xe),I.latch(),I.responsive&&(N.style.display="flex",N.style.flexDirection="column",N.style.maxHeight="100%",he.style.overflow="clip",he.style.minHeight="0"),et=Vt(O)),Ge&&W){let n=Ge(W);if(typeof n=="function"&&(w?G(n):Ze=n),w)throw new DOMException("Presentation cancelled","AbortError");ze()}B=Y(he,{mode:"live",rendererUrl:i.webViewUrl,title:m.document.name,closeActions:Yt,onAuthoredClose(n){ee||w||(x.hidden=n)},hostPresentation:()=>I?.type??Te.type,reportContentHeight:I?.responsive,onResize:n=>{if(!I?.responsive)return;let r=Math.min(n,Ke);he.style.height=`${r}px`,I.setContentHeight(r+(ae??J).getBoundingClientRect().height)},onSelection(n){for(let[r,c]of Object.entries(n))typeof c=="number"&&typeof q[r]=="number"&&q[r]!==c&&Ct.add(r);q=n,ve()},onAction(n,r={},c,g){if(!de||w||ee)return;let l=i.view,s=l?.document.buttons[n];if(!s)return;if(s.type==="close"&&E&&a.resumeCheckout&&i.operation&&St(S(i.operation))){$e();return}if(ie)return;if(!T()){it();return}if(s.type==="close"){j(async()=>{E?.closeAction?await E.closeAction(n):await a.onAction?.(n),ge(a.onAction?"action":"dismiss")});return}if(s.type==="action"){p=async()=>{if(s.action.type==="event"){if(!a.onEvent)throw new P("EVENT_HANDLER_REQUIRED","Provide the event handler");await a.onEvent(s.action.event)}else a.onOpenUrl?await a.onOpenUrl(s.action.url):d.defaultView?.location.assign(s.action.url);await a.onAction?.(n),p=null},j(p);return}if(a.allowNewPurchase===!1){fe()&&l&&i.quote&&i.operation&&S(i.operation).type==="checkout"&&Me(i.quote,l,n,s.product,r,g)?j(rt,n):f.textContent=o?"\u5F53\u524D\u53EA\u80FD\u7EE7\u7EED\u539F\u8BA2\u5355\u3002":"Only your original checkout is available.";return}if(te&&i.canReselect===!1){f.textContent=o?"\u8BF7\u5148\u786E\u8BA4\u6216\u53D6\u6D88\u5F53\u524D\u8D2D\u4E70\u3002":"Confirm or cancel the current purchase first.",I?.responsive||te.scrollIntoView?.({block:"nearest"}),te.querySelector("button")?.focus({preventScroll:!0});return}if(fe()&&K){K.selection.actionId===n&&j(()=>kt(!0),n);return}if(fe()&&a.terminateCheckout&&l&&i.quote&&i.operation&&i.canReselect===!1&&S(i.operation).type==="checkout"){if(Me(i.quote,l,n,s.product,r,g)){j(rt,n);return}let V=ue(s.product,r,l.capabilities);try{if(!V)throw new P("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");pe(l.document.screen,V,r,l.capabilities)}catch(ce){oe(ce);return}let se=i.operation.operationId,ne={actionId:n,requestId:crypto.randomUUID(),selection:structuredClone(r)},H=Ne(l,n,V,r,g);j(()=>Kt(se,ne,H),n);return}if((i.quote||b)&&i.canReselect===!1){let V=!!l&&!!i.quote&&Me(i.quote,l,n,s.product,r,g);_e=!!i.quote&&!V,p=i.quote?()=>at(V):xe,j(p);return}let L=l&&ue(s.product,r,l.capabilities);if(!l||!L){oe(new P("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(a.onPurchaseIntent){p=null,j(async()=>{let V={actionId:n,productVersionId:L,selection:structuredClone(r),featureQuantities:pe(l.document.screen,L,r,l.capabilities)};tt=!0,await a.onPurchaseIntent(V)});return}if(b&&b.actionId!==n){oe(new P("COMMAND_PENDING","Finish the current purchase"));return}b||(F=Ne(l,n,L,r,g),b={requestId:crypto.randomUUID(),actionId:n,selection:structuredClone(r)},ye=!1,we=!1),j(xe,n)},onEscape:()=>{$e()},onError:n=>{let r=new Error(n);!de&&!w&&ot(r),oe(r)},onRendered:n=>{n&&O.setAttribute("aria-label",n),bt=!0,st()}}),B.setHidden?.(!0),Xe();let e=fe()&&!!i.quote&&!!i.operation&&S(i.operation).type==="checkout";q=i.quote?Gt(m,i.quote)??Fe(m,{}):Fe(m,{}),B.update(m.document.screen,We,{capabilities:me(m),unavailableActions:ht(m),serverInput:{bindings:[],answers:{}},...Object.keys(q).length?{selection:q}:{}}),wt=i.subscribe?.(Se),Se(i.view??m),await R.wait(B.ready);let t=i.operation;!e&&(i.quote||t&&(t.confirmedAt||t.checkoutUrl||Re(t)))&&(p=It,j(p))}catch(e){throw ot(e),e}return{check:Z,host:{get observing(){return Ye},get recovery(){return Jt()},async prepareFallback(){if(ie||w||ee||tt)return{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null};ke(!0);try{let e=await Dt(i);return e.type==="native"&&ge(),e}finally{ke(!1)}},setSuspended(e){De=e,N.hidden=e,e&&O.open?O.close():!e&&!de?st():!e&&!w&&de&&Te.type!=="inline"&&!O.open&&O.showModal()},destroy:ge,refresh:async()=>{if(!T()){if(i.view)return i.view;throw new P("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await i.refresh();return Se(e),st(),e}}}}export{_n as showPaywall};
@@ -0,0 +1 @@
1
+ import{b as a}from"./chunk-7X65GNKZ.js";import"./chunk-PBZSOTKZ.js";import"./chunk-HLCDAU5A.js";import"./chunk-DCZWNTG2.js";import"./chunk-ASL7TJFU.js";import"./chunk-RDUKCMST.js";import"./chunk-KP4QI4RX.js";import"./chunk-5TJISOWN.js";import"./chunk-VILB5M4X.js";import"./chunk-PG5UESZB.js";import"./chunk-LSVTH3TS.js";import"./chunk-7MYS52FL.js";import"./chunk-MWICFZUF.js";import"./chunk-CWD36SJO.js";import"./chunk-5JRBCW6V.js";import"./chunk-3SXPCVIP.js";import"./chunk-TL67SYPH.js";import"./chunk-6XRXHFM6.js";import"./chunk-3VUPVXAV.js";import"./chunk-T43HTIQX.js";import"./chunk-GPJF3T43.js";import"./chunk-C4NG6RVA.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";export{a as readPaywallContent};
@@ -0,0 +1 @@
1
+ import{a}from"./chunk-Q23JDNYJ.js";import"./chunk-MEDW4N3F.js";import"./chunk-LZ3OJYBY.js";import"./chunk-NVF54BDR.js";import"./chunk-AV2WZSII.js";import"./chunk-MPD3UIY4.js";import"./chunk-7X65GNKZ.js";import"./chunk-PBZSOTKZ.js";import"./chunk-HLCDAU5A.js";import"./chunk-DCZWNTG2.js";import"./chunk-ASL7TJFU.js";import"./chunk-B4AELNLE.js";import"./chunk-AQONMY2H.js";import"./chunk-RDUKCMST.js";import"./chunk-KP4QI4RX.js";import"./chunk-5TJISOWN.js";import"./chunk-VILB5M4X.js";import"./chunk-FTGRTYBL.js";import"./chunk-PG5UESZB.js";import"./chunk-LSVTH3TS.js";import"./chunk-7MYS52FL.js";import"./chunk-MWICFZUF.js";import"./chunk-CWD36SJO.js";import"./chunk-5JRBCW6V.js";import"./chunk-3SXPCVIP.js";import"./chunk-TL67SYPH.js";import"./chunk-6XRXHFM6.js";import"./chunk-3VUPVXAV.js";import"./chunk-T43HTIQX.js";import"./chunk-GPJF3T43.js";import"./chunk-DSPLGTQI.js";import"./chunk-C4NG6RVA.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";export{a as createPaywallSession};
package/dist/popup.js CHANGED
@@ -1 +1 @@
1
- import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a}from"./chunk-H7AHDGVU.js";import"./chunk-AQQJPP3P.js";import"./chunk-KINNES62.js";import"./chunk-Y2HXKANG.js";import"./chunk-HGH2X6QM.js";import"./chunk-MYDMOAKX.js";import"./chunk-EECTJHI6.js";import"./chunk-G6CWZBT5.js";import"./chunk-S4P4UUUF.js";import"./chunk-2ULWP26K.js";import"./chunk-DSPLGTQI.js";import"./chunk-CQRSMCCG.js";import"./chunk-PBBREFS5.js";import"./chunk-WOT6VMZA.js";export{p as formatCustomerDecimal,r as hostedRendererScript,o as hostedRendererShell,f as inspectCustomHtml,a as mountScreenPreview,x as preparePopup,m as prepareScreen,e as sanitizeCustomHtml,t as showPopup};
1
+ import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a}from"./chunk-S7A3IBAF.js";import"./chunk-P6TNBX2S.js";import"./chunk-7MYS52FL.js";import"./chunk-MWICFZUF.js";import"./chunk-CWD36SJO.js";import"./chunk-5JRBCW6V.js";import"./chunk-3SXPCVIP.js";import"./chunk-TL67SYPH.js";import"./chunk-6XRXHFM6.js";import"./chunk-GPJF3T43.js";import"./chunk-DSPLGTQI.js";import"./chunk-C4NG6RVA.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";export{p as formatCustomerDecimal,r as hostedRendererScript,o as hostedRendererShell,f as inspectCustomHtml,a as mountScreenPreview,x as preparePopup,m as prepareScreen,e as sanitizeCustomHtml,t as showPopup};
@@ -1 +1 @@
1
- import{b as S,c as E,d as T}from"./chunk-FTVNGN6Z.js";import"./chunk-6STWY5GX.js";import{a as A}from"./chunk-756SIMZF.js";import{e as P}from"./chunk-QJMM37CB.js";import"./chunk-DPEMW2FO.js";import{h as b,i as x,k as L}from"./chunk-P6XQC7GG.js";import{E as C}from"./chunk-4B4RB36N.js";import"./chunk-EON4IKWR.js";import"./chunk-H26F3IOI.js";import"./chunk-2LERKK7O.js";import"./chunk-2RUJXZCO.js";import"./chunk-6EBS6MLW.js";import"./chunk-EOPKOAR5.js";import"./chunk-OAAS5LJY.js";import"./chunk-NFY7DKVJ.js";import"./chunk-5PNH2FPI.js";import"./chunk-PYLX3WF6.js";import"./chunk-W35FZWGG.js";import"./chunk-RQTYIUWP.js";import"./chunk-7IVLNV5H.js";import"./chunk-VJHURKRY.js";import"./chunk-VILB5M4X.js";import"./chunk-SYHMHKFQ.js";import"./chunk-2XF34Q6D.js";import"./chunk-26UXCYBP.js";import"./chunk-KINNES62.js";import"./chunk-Y2HXKANG.js";import"./chunk-HGH2X6QM.js";import"./chunk-MYDMOAKX.js";import"./chunk-EECTJHI6.js";import{a as r}from"./chunk-G6CWZBT5.js";import{h as R}from"./chunk-S4P4UUUF.js";import"./chunk-3VUPVXAV.js";import"./chunk-2LUVO7GM.js";import"./chunk-2ULWP26K.js";import"./chunk-DSPLGTQI.js";import"./chunk-CQRSMCCG.js";import"./chunk-PBBREFS5.js";import"./chunk-WOT6VMZA.js";function k(t,d){let n,a=0,m=-1,l,i=!1,y=()=>{if(i)throw new r("CLOSED","Native host was destroyed");if(!t.nativeModule)throw new r("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return t.nativeModule},o=()=>new r("IDENTITY_CHANGED","Customer identity changed during the native operation"),h=d.subscribeIdentity(()=>{a++,m=-1;let e=a;n&&t.nativeModule&&n.then(c=>t.nativeModule.reset(c,e)).catch(()=>{})}),I=t.nativeEvents?.(e=>{!n||!t.nativeModule||typeof e?.requestId!="string"||(async()=>{let c=await n;if(e.instanceId!==c)return;if(e.kind==="credential"){let w=a,f=null;try{if(!i&&e.revision===w){let N=await d.access();!i&&a===w&&(f=N)}}finally{await t.nativeModule.provideCredential(c,e.requestId,f)}return}let s=!1,u=a;try{if(i||e.revision!==u||!t.onNativeAction)throw o();await t.onNativeAction(e.action),s=!i&&a===u}finally{await t.nativeModule.acknowledge(c,e.requestId,s)}})().catch(()=>{})});async function p(e,c={}){let s=y();if(d.snapshot()&&!t.nativeEvents)throw new r("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let u=a,w=await d.access();if(i||a!==u)throw o();if(!n){let v=s.create(JSON.stringify({baseUrl:t.baseUrl??"https://api.longplayai.com",scope:t.scope,timeout:(t.timeoutMs??15e3)/1e3,credentialEvents:!!t.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let f=await n;if(i||a!==u)throw o();if(m!==u){if(!l||l.epoch!==u){let O=(async()=>{if(await s.identify(f,JSON.stringify({revision:u,credentials:w})),i||a!==u)throw await s.reset(f,u),o();m=u})();l={epoch:u,task:O}}let v=l;try{await v.task}finally{l===v&&(l=void 0)}}let N=await s.invoke(f,e,JSON.stringify(c));if(i||a!==u)throw o();try{return JSON.parse(N)}catch{throw new r("INVALID_RESPONSE","Native host returned invalid JSON")}}async function g(e,c){let s=await p(e,c);if(!s||typeof s!="object"||Array.isArray(s)||s.status!=="complete"&&s.status!=="dismissed")throw new r("INVALID_RESPONSE","Native presentation returned an invalid result");return s}return{showFunnel(e){return g("showFunnel",{runToken:e})},showPaywall(e){return g("showPaywall",e)},showContent(e){return g("showContent",e)},purchaseSubscription(e,c){return p("purchaseSubscription",{operationId:e,accepted:c})},switchSubscription(e,c){return p("switchSubscription",{operationId:e,accepted:c})},restorePurchases(){return p("restorePurchases")},manageSubscriptions(e){return p("manageSubscriptions",e?{productId:e}:{})},async dismiss(){a++,m=-1,n&&await y().reset(await n,a)},async destroy(){i||(i=!0,a++,h(),I?.(),n&&t.nativeModule&&await t.nativeModule.destroy(await n))}}}var M=P.trackUsage.request.shape.command,U=P.trackUsage.response;function F(t){let d=R.parse(t.scope),n=S({...t,scope:d}),a={...t,scope:d,session:n.session},m=k(t,n.session),l=0,i=!1;n.subscribeIdentity(()=>{l++});let y=()=>{if(i)throw new r("CLOSED","SDK client was destroyed");let o=n.session.peek();if(!o)throw new r("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:m,async destroy(){i||(i=!0,l++,n.destroy(),await m.destroy())},funnel(){return E({...a,customerToken:y()})},resumeFunnel(o){return y(),C({...a,runToken:o})},paywall(o){return A(a,{...o,customerToken:y()})},async trackUsage(o){if(y(),!t.usageReporter)throw new r("INVALID_REQUEST","Configure your authenticated backend usageReporter");let h=M.parse(o),I=l,p;try{p=await t.usageReporter(h)}catch(e){throw I!==l?new r("IDENTITY_CHANGED","Customer identity changed during usage reporting"):e}if(I!==l)throw new r("IDENTITY_CHANGED","Customer identity changed during usage reporting");let g=U.parse(p);if(g.scope.projectId!==d.projectId||g.scope.environment!==d.environment)throw new r("INVALID_RESPONSE","Usage response scope differs");return g}}}export{r as LongplayError,x as createConfigurationSync,b as createFeatureClient,T as createFunnelProcess,L as createLocalFunnelClient,F as createLongplayReactNative};
1
+ import{b as S,c as E,d as T}from"./chunk-RMRZSF5C.js";import"./chunk-RJY5CUTB.js";import{a as A}from"./chunk-Q23JDNYJ.js";import{e as P}from"./chunk-MEDW4N3F.js";import"./chunk-LZ3OJYBY.js";import{h as b,i as x,k as L}from"./chunk-22LQSRYH.js";import{E as C}from"./chunk-DPVYEOD6.js";import"./chunk-IT5DIE6G.js";import"./chunk-NVF54BDR.js";import"./chunk-AV2WZSII.js";import"./chunk-MPD3UIY4.js";import"./chunk-7X65GNKZ.js";import"./chunk-PBZSOTKZ.js";import"./chunk-HLCDAU5A.js";import"./chunk-DCZWNTG2.js";import"./chunk-CALDEF4M.js";import"./chunk-ASL7TJFU.js";import"./chunk-B4AELNLE.js";import"./chunk-AQONMY2H.js";import"./chunk-RDUKCMST.js";import"./chunk-KP4QI4RX.js";import"./chunk-5TJISOWN.js";import"./chunk-VILB5M4X.js";import"./chunk-FTGRTYBL.js";import"./chunk-PG5UESZB.js";import"./chunk-LSVTH3TS.js";import"./chunk-7MYS52FL.js";import"./chunk-MWICFZUF.js";import"./chunk-CWD36SJO.js";import"./chunk-5JRBCW6V.js";import"./chunk-3SXPCVIP.js";import{a as r}from"./chunk-TL67SYPH.js";import{h as R}from"./chunk-6XRXHFM6.js";import"./chunk-3VUPVXAV.js";import"./chunk-T43HTIQX.js";import"./chunk-GPJF3T43.js";import"./chunk-DSPLGTQI.js";import"./chunk-C4NG6RVA.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";function k(t,d){let n,a=0,m=-1,l,i=!1,y=()=>{if(i)throw new r("CLOSED","Native host was destroyed");if(!t.nativeModule)throw new r("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return t.nativeModule},o=()=>new r("IDENTITY_CHANGED","Customer identity changed during the native operation"),h=d.subscribeIdentity(()=>{a++,m=-1;let e=a;n&&t.nativeModule&&n.then(c=>t.nativeModule.reset(c,e)).catch(()=>{})}),I=t.nativeEvents?.(e=>{!n||!t.nativeModule||typeof e?.requestId!="string"||(async()=>{let c=await n;if(e.instanceId!==c)return;if(e.kind==="credential"){let w=a,f=null;try{if(!i&&e.revision===w){let N=await d.access();!i&&a===w&&(f=N)}}finally{await t.nativeModule.provideCredential(c,e.requestId,f)}return}let s=!1,u=a;try{if(i||e.revision!==u||!t.onNativeAction)throw o();await t.onNativeAction(e.action),s=!i&&a===u}finally{await t.nativeModule.acknowledge(c,e.requestId,s)}})().catch(()=>{})});async function p(e,c={}){let s=y();if(d.snapshot()&&!t.nativeEvents)throw new r("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let u=a,w=await d.access();if(i||a!==u)throw o();if(!n){let v=s.create(JSON.stringify({baseUrl:t.baseUrl??"https://api.longplayai.com",scope:t.scope,timeout:(t.timeoutMs??15e3)/1e3,credentialEvents:!!t.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let f=await n;if(i||a!==u)throw o();if(m!==u){if(!l||l.epoch!==u){let O=(async()=>{if(await s.identify(f,JSON.stringify({revision:u,credentials:w})),i||a!==u)throw await s.reset(f,u),o();m=u})();l={epoch:u,task:O}}let v=l;try{await v.task}finally{l===v&&(l=void 0)}}let N=await s.invoke(f,e,JSON.stringify(c));if(i||a!==u)throw o();try{return JSON.parse(N)}catch{throw new r("INVALID_RESPONSE","Native host returned invalid JSON")}}async function g(e,c){let s=await p(e,c);if(!s||typeof s!="object"||Array.isArray(s)||s.status!=="complete"&&s.status!=="dismissed")throw new r("INVALID_RESPONSE","Native presentation returned an invalid result");return s}return{showFunnel(e){return g("showFunnel",{runToken:e})},showPaywall(e){return g("showPaywall",e)},showContent(e){return g("showContent",e)},purchaseSubscription(e,c){return p("purchaseSubscription",{operationId:e,accepted:c})},switchSubscription(e,c){return p("switchSubscription",{operationId:e,accepted:c})},restorePurchases(){return p("restorePurchases")},manageSubscriptions(e){return p("manageSubscriptions",e?{productId:e}:{})},async dismiss(){a++,m=-1,n&&await y().reset(await n,a)},async destroy(){i||(i=!0,a++,h(),I?.(),n&&t.nativeModule&&await t.nativeModule.destroy(await n))}}}var M=P.trackUsage.request.shape.command,U=P.trackUsage.response;function F(t){let d=R.parse(t.scope),n=S({...t,scope:d}),a={...t,scope:d,session:n.session},m=k(t,n.session),l=0,i=!1;n.subscribeIdentity(()=>{l++});let y=()=>{if(i)throw new r("CLOSED","SDK client was destroyed");let o=n.session.peek();if(!o)throw new r("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:m,async destroy(){i||(i=!0,l++,n.destroy(),await m.destroy())},funnel(){return E({...a,customerToken:y()})},resumeFunnel(o){return y(),C({...a,runToken:o})},paywall(o){return A(a,{...o,customerToken:y()})},async trackUsage(o){if(y(),!t.usageReporter)throw new r("INVALID_REQUEST","Configure your authenticated backend usageReporter");let h=M.parse(o),I=l,p;try{p=await t.usageReporter(h)}catch(e){throw I!==l?new r("IDENTITY_CHANGED","Customer identity changed during usage reporting"):e}if(I!==l)throw new r("IDENTITY_CHANGED","Customer identity changed during usage reporting");let g=U.parse(p);if(g.scope.projectId!==d.projectId||g.scope.environment!==d.environment)throw new r("INVALID_RESPONSE","Usage response scope differs");return g}}}export{r as LongplayError,x as createConfigurationSync,b as createFeatureClient,T as createFunnelProcess,L as createLocalFunnelClient,F as createLongplayReactNative};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f,g,h,i}from"./chunk-S7A3IBAF.js";import"./chunk-P6TNBX2S.js";import"./chunk-7MYS52FL.js";import"./chunk-MWICFZUF.js";import"./chunk-CWD36SJO.js";import"./chunk-5JRBCW6V.js";import"./chunk-3SXPCVIP.js";import"./chunk-TL67SYPH.js";import"./chunk-6XRXHFM6.js";import"./chunk-GPJF3T43.js";import"./chunk-DSPLGTQI.js";import"./chunk-C4NG6RVA.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";export{f as formatCustomerDecimal,b as hostedRendererScript,a as hostedRendererShell,d as inspectCustomHtml,i as mountScreenPreview,h as preparePopup,e as prepareScreen,c as sanitizeCustomHtml,g as showPopup};
package/dist/server.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as pn}from"./chunk-ANXK3B5B.js";import{a as I}from"./chunk-TGPZJ5A7.js";import{a as fn,b as hn,c as gn,d as yn}from"./chunk-O3HLNU6T.js";import{a as xt}from"./chunk-756SIMZF.js";import{a as Ue,b as Ve,c as qe,d as He,e as m}from"./chunk-QJMM37CB.js";import"./chunk-DPEMW2FO.js";import{a as Te,b as ae,c as yt,d as It,e as wt,f as xe,g as vt,h as Me,i as dn,j as ln,k as mn}from"./chunk-P6XQC7GG.js";import{B as V,C as N,d as ft,e as ht,k as gt,l as z,m as St,p as Ct,q as Rt,r as bt,s as At,t as Ot,y as pe,z as Tt}from"./chunk-4B4RB36N.js";import{c as h}from"./chunk-EON4IKWR.js";import"./chunk-H26F3IOI.js";import{a as Et,b as _e}from"./chunk-2LERKK7O.js";import"./chunk-2RUJXZCO.js";import"./chunk-6EBS6MLW.js";import{e as at}from"./chunk-EOPKOAR5.js";import{B as pt,C as de,D as Z,E as lt,J as mt,a as et,e as q,j as Re,k as st,l as ct,q as ut,r as dt,s as be,t as Ae}from"./chunk-OAAS5LJY.js";import{b as Oe}from"./chunk-NFY7DKVJ.js";import{e as ve,i as Ze,l as it}from"./chunk-5PNH2FPI.js";import"./chunk-PYLX3WF6.js";import"./chunk-W35FZWGG.js";import"./chunk-RQTYIUWP.js";import"./chunk-7IVLNV5H.js";import{A as oe,B as tt,C as Se,D as ie,F as se,G as Ce,L as j,N as ce,O as nt,Q as Ee,R as rt,S as ot,e as Ge,f as je,i as we,q as ze,r as Ke,t as an,u as sn,x as cn,y as X,z as W}from"./chunk-VJHURKRY.js";import"./chunk-VILB5M4X.js";import"./chunk-SYHMHKFQ.js";import"./chunk-2XF34Q6D.js";import{a as Ne,b as Le}from"./chunk-26UXCYBP.js";import{o as ue}from"./chunk-KINNES62.js";import"./chunk-Y2HXKANG.js";import{i as un,k as $e,l as Qe,m as Je}from"./chunk-HGH2X6QM.js";import{c as Ie}from"./chunk-MYDMOAKX.js";import{e as Xe,h as We}from"./chunk-EECTJHI6.js";import{a as c}from"./chunk-G6CWZBT5.js";import{h as Y}from"./chunk-S4P4UUUF.js";import"./chunk-3VUPVXAV.js";import"./chunk-2LUVO7GM.js";import{b as u}from"./chunk-2ULWP26K.js";import"./chunk-DSPLGTQI.js";import{a as Ye}from"./chunk-CQRSMCCG.js";import"./chunk-PBBREFS5.js";import"./chunk-WOT6VMZA.js";var _t=4,Mt=[...tt,"requirement_checks","native_offers","preparations","benefit_claims","authorizations","business_results","checkout_termination"],In=u.enum(Mt),ee=(e,n)=>u.array(e).max(n).refine(t=>new Set(t).size===t.length,"Declarations must be unique"),ke=u.strictObject({...se.shape,bridgeVersion:u.literal(_t),capabilities:ee(In,Mt.length),checkKinds:ee(u.enum(["access","metered","credit"]),3),preparationActions:ee(u.enum(["purchase","subscription_change","refund"]),3),authorizationKinds:ee(u.enum(["auto_topup"]),1),nextActionTypes:ee(u.enum(["redirect","authenticate"]),2),resultEvents:ee(u.enum(["benefit.claimed","authorization.updated"]),2)}).superRefine((e,n)=>{e.capabilities.includes("catalog")!==(e.catalog!=="none")&&n.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(e.capabilities.includes("billing_records")!==e.billingEvents.length>0||new Set(e.billingEvents).size!==e.billingEvents.length)&&n.addIssue({code:"custom",path:["billingEvents"],message:"Declare unique supported billing events"});let t=r=>e.capabilities.includes(r),o=(r,a)=>n.addIssue({code:"custom",path:[r],message:a});t("requirement_checks")!==e.checkKinds.length>0&&o("checkKinds","Declare the supported Check kinds"),t("preparations")!==e.preparationActions.length>0&&o("preparationActions","Declare the supported preparation actions"),t("authorizations")!==e.authorizationKinds.length>0&&o("authorizationKinds","Declare the supported authorization kinds"),t("business_results")!==e.resultEvents.length>0&&o("resultEvents","Declare the supported non-financial results");for(let[r,a,s]of[["purchases","purchase","purchase.completed"],["subscription_changes","subscription_change","subscription.change.completed"],["refunds","refund","refund.updated"]])t(r)&&(!t("operation_status")||!t("billing_records")||!t("preparations")||!e.preparationActions.includes(a)||!e.billingEvents.includes(s))&&o("capabilities",`${r} requires preparation, original lookup and its billing result`);t("purchases")&&!e.billingEvents.includes("purchase.closed")&&o("billingEvents","Purchase execution requires its terminal closure result"),t("checkout_termination")&&(!t("operation_status")||!t("billing_records")||!e.billingEvents.includes("purchase.closed"))&&o("capabilities","Checkout termination requires original lookup and purchase.closed"),t("subscription_changes")&&!e.billingEvents.includes("subscription.change.closed")&&o("billingEvents","Subscription change execution requires its terminal closure result");for(let[r,a]of[["benefit_claims","benefit.claimed"],["authorizations","authorization.updated"]])t(r)&&(!t("operation_status")||!t("business_results")||!e.resultEvents.includes(a))&&o("capabilities",`${r} requires original lookup and its non-financial result`)}),K={"bridge.ping":u.strictObject({challenge:u.uuid()}),"bridge.describe":u.strictObject({}),"requirement.check":$e,"operation.prepare":ze,"benefit.claim":Ue,"operation.read":qe,"purchase.terminate":j},wn={"bridge.ping":u.strictObject({challenge:u.uuid()}),"bridge.describe":ke,"requirement.check":Qe,"operation.prepare":Ke,"benefit.claim":Ve,"operation.read":He,"purchase.terminate":j.extend({outcome:u.enum(["requested","already_paid"])})},Gn=u.enum(["bridge.ping","bridge.describe","requirement.check","operation.prepare","benefit.claim","operation.read","purchase.terminate"]);function $(e,n){return u.strictObject({bridgeVersion:u.literal(_t),requestId:u.uuid(),scope:Ce,command:u.literal(e),data:n})}var kt=u.discriminatedUnion("command",[$("bridge.ping",K["bridge.ping"]),$("bridge.describe",K["bridge.describe"]),$("requirement.check",K["requirement.check"]),$("operation.prepare",K["operation.prepare"]),$("benefit.claim",K["benefit.claim"]),$("operation.read",K["operation.read"]),$("purchase.terminate",K["purchase.terminate"])]),Be=u.strictObject({code:u.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:u.string().min(1).max(500),retryable:u.boolean(),recovery:u.string().min(1).max(80),effect:u.enum(["none","unknown"])}).refine(e=>e.effect!=="unknown"||!e.retryable&&e.recovery==="recover_operation","Unknown effects require original-operation recovery");function Bt(e){let n={bridgeVersion:u.literal(4),requestId:u.uuid(),scope:Ce,command:u.literal(e)};return u.union([u.strictObject({...n,data:wn[e]}),u.strictObject({...n,error:Be})])}var Pt="X-Indiana-Bridge-Signature",Q="X-Indiana-Bridge-Key-Id";function vn(e){return new TextEncoder().encode(e)}function Dt(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),n=>n.charCodeAt(0))}function Ft(e,n,t,o){return vn(`indiana-merchant-bridge:${o}
1
+ import{a as pn}from"./chunk-3XMBILUJ.js";import{a as I}from"./chunk-V65FSNYO.js";import{a as fn,b as hn,c as gn,d as yn}from"./chunk-UJMP7AMY.js";import{a as xt}from"./chunk-Q23JDNYJ.js";import{a as Ue,b as Ve,c as qe,d as He,e as m}from"./chunk-MEDW4N3F.js";import"./chunk-LZ3OJYBY.js";import{a as Te,b as ae,c as yt,d as It,e as wt,f as xe,g as vt,h as Me,i as dn,j as ln,k as mn}from"./chunk-22LQSRYH.js";import{B as V,C as N,d as ft,e as ht,k as gt,l as z,m as St,p as Ct,q as Rt,r as bt,s as At,t as Ot,y as pe,z as Tt}from"./chunk-DPVYEOD6.js";import"./chunk-IT5DIE6G.js";import{c as h}from"./chunk-NVF54BDR.js";import"./chunk-AV2WZSII.js";import{a as Et,b as _e}from"./chunk-MPD3UIY4.js";import"./chunk-7X65GNKZ.js";import"./chunk-PBZSOTKZ.js";import{e as at}from"./chunk-HLCDAU5A.js";import{B as pt,C as de,D as Z,E as lt,J as mt,a as et,e as q,j as Re,k as st,l as ct,q as ut,r as dt,s as be,t as Ae}from"./chunk-DCZWNTG2.js";import{b as Oe}from"./chunk-CALDEF4M.js";import{e as ve,i as Ze,l as it}from"./chunk-ASL7TJFU.js";import"./chunk-B4AELNLE.js";import"./chunk-AQONMY2H.js";import"./chunk-RDUKCMST.js";import"./chunk-KP4QI4RX.js";import{A as oe,B as tt,C as Se,D as ie,F as se,G as Ce,L as j,N as ce,O as nt,Q as Ee,R as rt,S as ot,e as Ge,f as je,i as we,q as ze,r as Ke,t as an,u as sn,x as cn,y as X,z as W}from"./chunk-5TJISOWN.js";import"./chunk-VILB5M4X.js";import"./chunk-FTGRTYBL.js";import"./chunk-PG5UESZB.js";import{a as Ne,b as Le}from"./chunk-LSVTH3TS.js";import{o as ue}from"./chunk-7MYS52FL.js";import"./chunk-MWICFZUF.js";import{i as un,k as $e,l as Qe,m as Je}from"./chunk-CWD36SJO.js";import{c as Ie}from"./chunk-5JRBCW6V.js";import{e as Xe,h as We}from"./chunk-3SXPCVIP.js";import{a as c}from"./chunk-TL67SYPH.js";import{h as Y}from"./chunk-6XRXHFM6.js";import"./chunk-3VUPVXAV.js";import"./chunk-T43HTIQX.js";import{b as u}from"./chunk-GPJF3T43.js";import"./chunk-DSPLGTQI.js";import{a as Ye}from"./chunk-C4NG6RVA.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";var _t=4,Mt=[...tt,"requirement_checks","native_offers","preparations","benefit_claims","authorizations","business_results","checkout_termination"],In=u.enum(Mt),ee=(e,n)=>u.array(e).max(n).refine(t=>new Set(t).size===t.length,"Declarations must be unique"),ke=u.strictObject({...se.shape,bridgeVersion:u.literal(_t),capabilities:ee(In,Mt.length),checkKinds:ee(u.enum(["access","metered","credit"]),3),preparationActions:ee(u.enum(["purchase","subscription_change","refund"]),3),authorizationKinds:ee(u.enum(["auto_topup"]),1),nextActionTypes:ee(u.enum(["redirect","authenticate"]),2),resultEvents:ee(u.enum(["benefit.claimed","authorization.updated"]),2)}).superRefine((e,n)=>{e.capabilities.includes("catalog")!==(e.catalog!=="none")&&n.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(e.capabilities.includes("billing_records")!==e.billingEvents.length>0||new Set(e.billingEvents).size!==e.billingEvents.length)&&n.addIssue({code:"custom",path:["billingEvents"],message:"Declare unique supported billing events"});let t=r=>e.capabilities.includes(r),o=(r,a)=>n.addIssue({code:"custom",path:[r],message:a});t("requirement_checks")!==e.checkKinds.length>0&&o("checkKinds","Declare the supported Check kinds"),t("preparations")!==e.preparationActions.length>0&&o("preparationActions","Declare the supported preparation actions"),t("authorizations")!==e.authorizationKinds.length>0&&o("authorizationKinds","Declare the supported authorization kinds"),t("business_results")!==e.resultEvents.length>0&&o("resultEvents","Declare the supported non-financial results");for(let[r,a,s]of[["purchases","purchase","purchase.completed"],["subscription_changes","subscription_change","subscription.change.completed"],["refunds","refund","refund.updated"]])t(r)&&(!t("operation_status")||!t("billing_records")||!t("preparations")||!e.preparationActions.includes(a)||!e.billingEvents.includes(s))&&o("capabilities",`${r} requires preparation, original lookup and its billing result`);t("purchases")&&!e.billingEvents.includes("purchase.closed")&&o("billingEvents","Purchase execution requires its terminal closure result"),t("checkout_termination")&&(!t("operation_status")||!t("billing_records")||!e.billingEvents.includes("purchase.closed"))&&o("capabilities","Checkout termination requires original lookup and purchase.closed"),t("subscription_changes")&&!e.billingEvents.includes("subscription.change.closed")&&o("billingEvents","Subscription change execution requires its terminal closure result");for(let[r,a]of[["benefit_claims","benefit.claimed"],["authorizations","authorization.updated"]])t(r)&&(!t("operation_status")||!t("business_results")||!e.resultEvents.includes(a))&&o("capabilities",`${r} requires original lookup and its non-financial result`)}),K={"bridge.ping":u.strictObject({challenge:u.uuid()}),"bridge.describe":u.strictObject({}),"requirement.check":$e,"operation.prepare":ze,"benefit.claim":Ue,"operation.read":qe,"purchase.terminate":j},wn={"bridge.ping":u.strictObject({challenge:u.uuid()}),"bridge.describe":ke,"requirement.check":Qe,"operation.prepare":Ke,"benefit.claim":Ve,"operation.read":He,"purchase.terminate":j.extend({outcome:u.enum(["requested","already_paid"])})},Gn=u.enum(["bridge.ping","bridge.describe","requirement.check","operation.prepare","benefit.claim","operation.read","purchase.terminate"]);function $(e,n){return u.strictObject({bridgeVersion:u.literal(_t),requestId:u.uuid(),scope:Ce,command:u.literal(e),data:n})}var kt=u.discriminatedUnion("command",[$("bridge.ping",K["bridge.ping"]),$("bridge.describe",K["bridge.describe"]),$("requirement.check",K["requirement.check"]),$("operation.prepare",K["operation.prepare"]),$("benefit.claim",K["benefit.claim"]),$("operation.read",K["operation.read"]),$("purchase.terminate",K["purchase.terminate"])]),Be=u.strictObject({code:u.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:u.string().min(1).max(500),retryable:u.boolean(),recovery:u.string().min(1).max(80),effect:u.enum(["none","unknown"])}).refine(e=>e.effect!=="unknown"||!e.retryable&&e.recovery==="recover_operation","Unknown effects require original-operation recovery");function Bt(e){let n={bridgeVersion:u.literal(4),requestId:u.uuid(),scope:Ce,command:u.literal(e)};return u.union([u.strictObject({...n,data:wn[e]}),u.strictObject({...n,error:Be})])}var Pt="X-Indiana-Bridge-Signature",Q="X-Indiana-Bridge-Key-Id";function vn(e){return new TextEncoder().encode(e)}function Dt(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),n=>n.charCodeAt(0))}function Ft(e,n,t,o){return vn(`indiana-merchant-bridge:${o}
2
2
  ${n}
3
3
  POST
4
4
  ${W}
@@ -1 +1 @@
1
- import{b as a,c as b}from"./chunk-4PGYQ2TI.js";import"./chunk-J6KIN4RH.js";import"./chunk-WOT6VMZA.js";export{b as applyVisualVariation,a as safeVisualMutation};
1
+ import{b as a,c as b}from"./chunk-RA7GZ67U.js";import"./chunk-J6KIN4RH.js";import"./chunk-WOT6VMZA.js";export{b as applyVisualVariation,a as safeVisualMutation};
package/dist/visual.js CHANGED
@@ -1 +1 @@
1
- import{a as pe,c as fe}from"./chunk-4PGYQ2TI.js";import{b as le}from"./chunk-J6KIN4RH.js";import{a as Ve,b as ce,c as de,d as ue}from"./chunk-SLUA7ABW.js";import{a as J,b as F,c as ge,e as me}from"./chunk-OEONV3JY.js";import{a as re,b as ae,c as se,d as oe}from"./chunk-2P2YSNYU.js";import"./chunk-3VUPVXAV.js";import"./chunk-2LUVO7GM.js";import{b as o}from"./chunk-2ULWP26K.js";import"./chunk-DSPLGTQI.js";import{c as te,e as ie,g as M}from"./chunk-CQRSMCCG.js";import"./chunk-PBBREFS5.js";import"./chunk-WOT6VMZA.js";var K="indiana-visual-diagnostics-v1",Ae=o.strictObject({environmentId:o.string().uuid(),release:o.string().regex(/^[a-f0-9]{64}$/).nullable(),generation:o.string().regex(/^[a-f0-9]{64}$/).nullable(),publishedGeneration:o.string().regex(/^[a-f0-9]{64}$/).nullable(),checkedAt:o.string().datetime(),origin:o.string().url(),pathname:o.string().max(2048),urlMatches:o.boolean(),stopped:o.boolean(),rows:o.array(o.strictObject({changeId:o.string().regex(/^[a-f0-9]{64}$/),experimentKey:o.string().max(256),variationKey:o.string().max(256),inExperiment:o.boolean(),fingerprint:o.string().regex(/^[a-f0-9]{64}$/),status:o.enum(["inactive","waiting","partial","applied","mismatch","no_changes","unavailable","error"]),total:o.number().int().min(0).max(600),applied:o.number().int().min(0).max(600)})).max(100)});function ye(e){let l=n=>Array.isArray(n)?"["+n.map(l).join(",")+"]":n&&typeof n=="object"?"{"+Object.entries(n).filter(([,c])=>c!==void 0).sort(([c],[y])=>c.localeCompare(y)).map(([c,y])=>JSON.stringify(c)+":"+l(y)).join(",")+"}":JSON.stringify(n);return l({css:e.css,js:e.js,domMutations:e.domMutations,...e.renderGuard?{renderGuard:e.renderGuard}:{}})}function he(e){let l=new URL(e.baseUrl),n=l.origin==="https://api.longplayai.com"||l.origin==="https://api.dev.longplayai.com"?l.hostname.slice(4):void 0,c=e.origins??(n?[`https://console.${n}`]:[]),y=new Set(c.filter(t=>{try{let i=new URL(t);return i.origin===t&&(i.protocol==="https:"||i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname))}catch{return!1}})),v=!1,I=!1,k=0,T=async t=>{if(v||I||!t.source||!y.has(t.origin)||!t.data||typeof t.data!="object")return;let i=t.data;if(!(i.channel!==K||i.type!=="inspect"||i.environmentId!==e.environmentId||typeof i.nonce!="string"||!/^[a-f0-9-]{36}$/i.test(i.nonce)||typeof i.changeId!="string"||!/^[a-f0-9]{64}$/.test(i.changeId)||typeof i.url!="string"||i.url.length>2048||Date.now()-k<250)){try{if(new URL(i.url).origin!==location.origin)return}catch{return}I=!0,k=Date.now();try{let x=await e.inspect(i.changeId,i.url);!v&&x.rows.some(S=>S.changeId===i.changeId)&&t.source.postMessage({channel:K,type:"result",nonce:i.nonce,snapshot:x},t.origin)}finally{I=!1}}},u=t=>{T(t).catch(()=>{})};return window.addEventListener("message",u),()=>{v=!0,window.removeEventListener("message",u)}}var R=e=>!!e&&typeof e=="object"&&!Array.isArray(e),E=(e,l)=>typeof e=="string"&&e.length<=l,Ee=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function ke(e){if(!R(e)||!E(e.css??"",1e5)||!E(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let l=e.domMutations??[];for(let n of l)if(!R(n)||!E(n.selector,2048)||!n.selector||!Ee(n.attribute)||!["set","append","remove"].includes(String(n.action))||n.value!==void 0&&!E(n.value,5e4)||n.parentSelector!==void 0&&!E(n.parentSelector,2048)||n.insertBeforeSelector!==void 0&&!E(n.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:l,...e.renderGuard===void 0?{}:{renderGuard:le(e.renderGuard)}}}function q(e){if(!R(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!R(e.savedGroups))throw new Error("Invalid visual experiment payload");let l=e.experiments.map(n=>{if(!R(n)||!["key","changeId"].every(c=>typeof n[c]=="string"&&n[c])||!/^[a-f0-9]{64}$/.test(String(n.changeId))||["namespace","status","groups","url"].some(c=>Object.hasOwn(n,c))||n.hashVersion!==void 0&&n.hashVersion!==2||!Array.isArray(n.variations)||n.variations.length<2||n.variations.length>20||n.urlPatterns!==void 0&&!Array.isArray(n.urlPatterns))throw new Error("Invalid visual experiment");return{...n,variations:n.variations.map(ke)}});return{...e,experiments:l}}var ve=6e4;function qe(e){let l=se(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),c=F(n),y=F(n),v=`${l}/api/v1/visual-experiments/${e.environmentId}`,I=e.appManifestRelease?`${v}?iam=${e.appManifestRelease}`:v,k=re(e.deviceIdCookie??"indiana_did"),T=ae(),u=null,t=!1,i=!1,x="",S={...e.attributes??{}},G,B,D=0,H=-1/0,$,m=new Map,O=new Map,C=new Set,z=ge({endpoint:`${v}/events`,fetch:n,log:e.log,label:"Visual exposure"}),P=z.flush,W,b;function j(){clearTimeout(W),b?.remove(),b=void 0}function Y(s,d){let f=M(s,d);C.has(f)||e.trackExposures===!1||u?.trackExposures===!1||t||(C.add(f),z.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:k,...T?{sessionId:T}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:s.key,variationKey:d.key}))}function we(s){if(!u||t)return;let d=new Set,f={onExperimentViewed:(r,p)=>{d.add(M(r,p))},url:location.href,attributes:{...me(k,location),...S,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:te(u.savedGroups),log:e.log},h=new Set;for(let r of u.experiments){if(de(`${e.environmentId}:${r.key}`))continue;let p=r;try{let a=ie(p,f);if(O.set(r.changeId,a),!a.inExperiment)continue;h.add(r.changeId);let w=JSON.stringify([a.key,a.value]),U=m.get(r.changeId);if(U?.signature===w){d.has(M(p,a))&&s.push(()=>{U.applied()&&Y(p,a)});continue}m.get(r.changeId)?.revert(),m.delete(r.changeId);let A=fe(a.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(r.condition?.$and)&&r.condition.$and.some(g=>g!==null&&typeof g=="object"&&!Array.isArray(g)&&g.indianaAppManifestRelease===e.appManifestRelease),boundVariations:r.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{d.has(M(p,a))&&Y(p,a)},onError:g=>e.log?.("Visual experiment stopped",{experiment:r.key,changeId:r.changeId,variation:a.key,error:String(g)}),onTargetStatus:e.log?g=>e.log?.("Visual target status changed",{experiment:r.key,changeId:r.changeId,variation:a.key,...g}):void 0});m.set(r.changeId,{signature:w,revert:A.revert,applied:()=>A.applied,inspect:()=>A.inspect()})}catch(a){e.log?.("Skipping visual experiment",{experiment:r.key,error:String(a)})}}for(let[r,p]of m)h.has(r)||(p.revert(),m.delete(r));j()}let V=()=>{let s=[];pe(()=>we(s));for(let d of s)d()};async function _(){let s=++D,d;try{d=await c.read(I,J)}catch(h){if(t||s!==D)return!1;throw h}let f=q(d);if(f.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return t||s!==D?!1:(u=f,H=performance.now(),!0)}async function Q(){!await _()||t||(N(),V())}function L(){clearTimeout($),$=setTimeout(()=>{if(document.visibilityState==="hidden")return L();Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()})},ve)}let X=()=>{t||document.visibilityState==="hidden"||performance.now()-H<ve||(clearTimeout($),Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()}))},Ie=()=>{x!==location.href&&(x=location.href,V())},Z=()=>{P(!0)},N=()=>{G||t||(G=oe(Ie),addEventListener("pagehide",Z),x=location.href)};async function ee(s,d){let f=location.href,h=u,r=[],p=null;if(!t)try{let a=q(await y.read(I,J));a.environmentId===e.environmentId&&(p=a.generation)}catch{}for(let a of h?.experiments??[]){if(s&&a.changeId!==s)continue;let w=O.get(a.changeId);if(!w)continue;let U=new TextEncoder().encode(ye(w.value)),A=[...new Uint8Array(await crypto.subtle.digest("SHA-256",U))].map(be=>be.toString(16).padStart(2,"0")).join(""),g=m.get(a.changeId)?.inspect()??{status:"inactive",total:0,applied:0};r.push({changeId:a.changeId,experimentKey:a.key,variationKey:w.key,inExperiment:w.inExperiment,fingerprint:A,...g})}return{environmentId:e.environmentId,release:e.appManifestRelease??null,generation:h?.generation??null,publishedGeneration:p,checkedAt:new Date().toISOString(),origin:location.origin,pathname:location.pathname,urlMatches:location.href===f&&(!d||d===f)&&h===u,stopped:t,rows:r}}let ne,xe=ue(()=>{i&&!t&&V()});return{async start(){if(!(i||t)){i=!0,e.appManifestRelease&&(B=ce(e.appManifestRelease)),e.antiFlicker&&(b=document.createElement("style"),e.nonce&&(b.nonce=e.nonce),b.textContent="body { visibility: hidden !important }",document.head.append(b),W=setTimeout(j,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await _()||t)return;N(),V()}finally{j(),t||(L(),document.addEventListener("visibilitychange",X),ne=he({environmentId:e.environmentId,baseUrl:l,origins:e.diagnosticsOrigins,inspect:ee}))}}},async refresh(){t||await _()&&(i&&N(),V())},setAttributes(s){S={...s},V()},flush:()=>P(),getDiagnostics:ee,getResults(){return new Map(O)},get generation(){return u?.generation??null},destroy(){t=!0,clearTimeout($),document.removeEventListener("visibilitychange",X),xe(),ne?.(),D++,c.destroy(),y.destroy(),G?.(),B?.destroy(),removeEventListener("pagehide",Z),j();for(let s of m.values())s.revert();m.clear(),P(!0),u=null,O.clear(),C.clear(),S={}}}}export{qe as createVisualExperiments,Ve as loadAppManifestRelease};
1
+ import{a as pe,c as fe}from"./chunk-RA7GZ67U.js";import{b as le}from"./chunk-J6KIN4RH.js";import{a as Ve,b as ce,c as de,d as ue}from"./chunk-SLUA7ABW.js";import{a as J,b as F,c as ge,e as me}from"./chunk-2PVQUPBN.js";import{a as re,b as ae,c as se,d as oe}from"./chunk-X4UTTXOU.js";import"./chunk-3VUPVXAV.js";import"./chunk-T43HTIQX.js";import{b as o}from"./chunk-GPJF3T43.js";import"./chunk-DSPLGTQI.js";import{c as te,e as ie,g as M}from"./chunk-C4NG6RVA.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";var K="indiana-visual-diagnostics-v1",Ae=o.strictObject({environmentId:o.string().uuid(),release:o.string().regex(/^[a-f0-9]{64}$/).nullable(),generation:o.string().regex(/^[a-f0-9]{64}$/).nullable(),publishedGeneration:o.string().regex(/^[a-f0-9]{64}$/).nullable(),checkedAt:o.string().datetime(),origin:o.string().url(),pathname:o.string().max(2048),urlMatches:o.boolean(),stopped:o.boolean(),rows:o.array(o.strictObject({changeId:o.string().regex(/^[a-f0-9]{64}$/),experimentKey:o.string().max(256),variationKey:o.string().max(256),inExperiment:o.boolean(),fingerprint:o.string().regex(/^[a-f0-9]{64}$/),status:o.enum(["inactive","waiting","partial","applied","mismatch","no_changes","unavailable","error"]),total:o.number().int().min(0).max(600),applied:o.number().int().min(0).max(600)})).max(100)});function ye(e){let l=n=>Array.isArray(n)?"["+n.map(l).join(",")+"]":n&&typeof n=="object"?"{"+Object.entries(n).filter(([,c])=>c!==void 0).sort(([c],[y])=>c.localeCompare(y)).map(([c,y])=>JSON.stringify(c)+":"+l(y)).join(",")+"}":JSON.stringify(n);return l({css:e.css,js:e.js,domMutations:e.domMutations,...e.renderGuard?{renderGuard:e.renderGuard}:{}})}function he(e){let l=new URL(e.baseUrl),n=l.origin==="https://api.longplayai.com"||l.origin==="https://api.dev.longplayai.com"?l.hostname.slice(4):void 0,c=e.origins??(n?[`https://console.${n}`]:[]),y=new Set(c.filter(t=>{try{let i=new URL(t);return i.origin===t&&(i.protocol==="https:"||i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname))}catch{return!1}})),v=!1,I=!1,k=0,T=async t=>{if(v||I||!t.source||!y.has(t.origin)||!t.data||typeof t.data!="object")return;let i=t.data;if(!(i.channel!==K||i.type!=="inspect"||i.environmentId!==e.environmentId||typeof i.nonce!="string"||!/^[a-f0-9-]{36}$/i.test(i.nonce)||typeof i.changeId!="string"||!/^[a-f0-9]{64}$/.test(i.changeId)||typeof i.url!="string"||i.url.length>2048||Date.now()-k<250)){try{if(new URL(i.url).origin!==location.origin)return}catch{return}I=!0,k=Date.now();try{let x=await e.inspect(i.changeId,i.url);!v&&x.rows.some(S=>S.changeId===i.changeId)&&t.source.postMessage({channel:K,type:"result",nonce:i.nonce,snapshot:x},t.origin)}finally{I=!1}}},u=t=>{T(t).catch(()=>{})};return window.addEventListener("message",u),()=>{v=!0,window.removeEventListener("message",u)}}var R=e=>!!e&&typeof e=="object"&&!Array.isArray(e),E=(e,l)=>typeof e=="string"&&e.length<=l,Ee=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function ke(e){if(!R(e)||!E(e.css??"",1e5)||!E(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let l=e.domMutations??[];for(let n of l)if(!R(n)||!E(n.selector,2048)||!n.selector||!Ee(n.attribute)||!["set","append","remove"].includes(String(n.action))||n.value!==void 0&&!E(n.value,5e4)||n.parentSelector!==void 0&&!E(n.parentSelector,2048)||n.insertBeforeSelector!==void 0&&!E(n.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:l,...e.renderGuard===void 0?{}:{renderGuard:le(e.renderGuard)}}}function q(e){if(!R(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!R(e.savedGroups))throw new Error("Invalid visual experiment payload");let l=e.experiments.map(n=>{if(!R(n)||!["key","changeId"].every(c=>typeof n[c]=="string"&&n[c])||!/^[a-f0-9]{64}$/.test(String(n.changeId))||["namespace","status","groups","url"].some(c=>Object.hasOwn(n,c))||n.hashVersion!==void 0&&n.hashVersion!==2||!Array.isArray(n.variations)||n.variations.length<2||n.variations.length>20||n.urlPatterns!==void 0&&!Array.isArray(n.urlPatterns))throw new Error("Invalid visual experiment");return{...n,variations:n.variations.map(ke)}});return{...e,experiments:l}}var ve=6e4;function qe(e){let l=se(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),c=F(n),y=F(n),v=`${l}/api/v1/visual-experiments/${e.environmentId}`,I=e.appManifestRelease?`${v}?iam=${e.appManifestRelease}`:v,k=re(e.deviceIdCookie??"indiana_did"),T=ae(),u=null,t=!1,i=!1,x="",S={...e.attributes??{}},G,B,D=0,H=-1/0,$,m=new Map,O=new Map,C=new Set,z=ge({endpoint:`${v}/events`,fetch:n,log:e.log,label:"Visual exposure"}),P=z.flush,W,b;function j(){clearTimeout(W),b?.remove(),b=void 0}function Y(s,d){let f=M(s,d);C.has(f)||e.trackExposures===!1||u?.trackExposures===!1||t||(C.add(f),z.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:k,...T?{sessionId:T}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:s.key,variationKey:d.key}))}function we(s){if(!u||t)return;let d=new Set,f={onExperimentViewed:(r,p)=>{d.add(M(r,p))},url:location.href,attributes:{...me(k,location),...S,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:te(u.savedGroups),log:e.log},h=new Set;for(let r of u.experiments){if(de(`${e.environmentId}:${r.key}`))continue;let p=r;try{let a=ie(p,f);if(O.set(r.changeId,a),!a.inExperiment)continue;h.add(r.changeId);let w=JSON.stringify([a.key,a.value]),U=m.get(r.changeId);if(U?.signature===w){d.has(M(p,a))&&s.push(()=>{U.applied()&&Y(p,a)});continue}m.get(r.changeId)?.revert(),m.delete(r.changeId);let A=fe(a.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(r.condition?.$and)&&r.condition.$and.some(g=>g!==null&&typeof g=="object"&&!Array.isArray(g)&&g.indianaAppManifestRelease===e.appManifestRelease),boundVariations:r.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{d.has(M(p,a))&&Y(p,a)},onError:g=>e.log?.("Visual experiment stopped",{experiment:r.key,changeId:r.changeId,variation:a.key,error:String(g)}),onTargetStatus:e.log?g=>e.log?.("Visual target status changed",{experiment:r.key,changeId:r.changeId,variation:a.key,...g}):void 0});m.set(r.changeId,{signature:w,revert:A.revert,applied:()=>A.applied,inspect:()=>A.inspect()})}catch(a){e.log?.("Skipping visual experiment",{experiment:r.key,error:String(a)})}}for(let[r,p]of m)h.has(r)||(p.revert(),m.delete(r));j()}let V=()=>{let s=[];pe(()=>we(s));for(let d of s)d()};async function _(){let s=++D,d;try{d=await c.read(I,J)}catch(h){if(t||s!==D)return!1;throw h}let f=q(d);if(f.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return t||s!==D?!1:(u=f,H=performance.now(),!0)}async function Q(){!await _()||t||(N(),V())}function L(){clearTimeout($),$=setTimeout(()=>{if(document.visibilityState==="hidden")return L();Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()})},ve)}let X=()=>{t||document.visibilityState==="hidden"||performance.now()-H<ve||(clearTimeout($),Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()}))},Ie=()=>{x!==location.href&&(x=location.href,V())},Z=()=>{P(!0)},N=()=>{G||t||(G=oe(Ie),addEventListener("pagehide",Z),x=location.href)};async function ee(s,d){let f=location.href,h=u,r=[],p=null;if(!t)try{let a=q(await y.read(I,J));a.environmentId===e.environmentId&&(p=a.generation)}catch{}for(let a of h?.experiments??[]){if(s&&a.changeId!==s)continue;let w=O.get(a.changeId);if(!w)continue;let U=new TextEncoder().encode(ye(w.value)),A=[...new Uint8Array(await crypto.subtle.digest("SHA-256",U))].map(be=>be.toString(16).padStart(2,"0")).join(""),g=m.get(a.changeId)?.inspect()??{status:"inactive",total:0,applied:0};r.push({changeId:a.changeId,experimentKey:a.key,variationKey:w.key,inExperiment:w.inExperiment,fingerprint:A,...g})}return{environmentId:e.environmentId,release:e.appManifestRelease??null,generation:h?.generation??null,publishedGeneration:p,checkedAt:new Date().toISOString(),origin:location.origin,pathname:location.pathname,urlMatches:location.href===f&&(!d||d===f)&&h===u,stopped:t,rows:r}}let ne,xe=ue(()=>{i&&!t&&V()});return{async start(){if(!(i||t)){i=!0,e.appManifestRelease&&(B=ce(e.appManifestRelease)),e.antiFlicker&&(b=document.createElement("style"),e.nonce&&(b.nonce=e.nonce),b.textContent="body { visibility: hidden !important }",document.head.append(b),W=setTimeout(j,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await _()||t)return;N(),V()}finally{j(),t||(L(),document.addEventListener("visibilitychange",X),ne=he({environmentId:e.environmentId,baseUrl:l,origins:e.diagnosticsOrigins,inspect:ee}))}}},async refresh(){t||await _()&&(i&&N(),V())},setAttributes(s){S={...s},V()},flush:()=>P(),getDiagnostics:ee,getResults(){return new Map(O)},get generation(){return u?.generation??null},destroy(){t=!0,clearTimeout($),document.removeEventListener("visibilitychange",X),xe(),ne?.(),D++,c.destroy(),y.destroy(),G?.(),B?.destroy(),removeEventListener("pagehide",Z),j();for(let s of m.values())s.revert();m.clear(),P(!0),u=null,O.clear(),C.clear(),S={}}}}export{qe as createVisualExperiments,Ve as loadAppManifestRelease};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tinkerlandai/longplay-sdk",
3
- "version": "0.10.41",
3
+ "version": "0.10.43",
4
4
  "description": "Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- import{a,b}from"./chunk-2LERKK7O.js";import"./chunk-HGH2X6QM.js";import"./chunk-MYDMOAKX.js";import"./chunk-G6CWZBT5.js";import"./chunk-S4P4UUUF.js";import"./chunk-2ULWP26K.js";import"./chunk-PBBREFS5.js";import"./chunk-WOT6VMZA.js";export{a as validateEntitlementCheck,b as validateResourceCheck};
@@ -1 +0,0 @@
1
- import{b as nn}from"./chunk-2RUJXZCO.js";import{d as We,e as ce}from"./chunk-6EBS6MLW.js";import{c as qe,d as je,e as K,l as Ze}from"./chunk-EOPKOAR5.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-OAAS5LJY.js";import{a as de,b as Xe}from"./chunk-NFY7DKVJ.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-5PNH2FPI.js";import{b as tn}from"./chunk-PYLX3WF6.js";import{A as ie,B as ae,z as oe}from"./chunk-7IVLNV5H.js";import{b as W}from"./chunk-2XF34Q6D.js";import{a as Q}from"./chunk-26UXCYBP.js";import{m as Ke,n as ue,o as ze,p as se}from"./chunk-KINNES62.js";import{g as Ee,m as Ce,w as re}from"./chunk-Y2HXKANG.js";import{b as Pe,d as L,e as Ae,f as Te}from"./chunk-EECTJHI6.js";import{a as f}from"./chunk-G6CWZBT5.js";import{h as V}from"./chunk-S4P4UUUF.js";import{b as en}from"./chunk-2LUVO7GM.js";import{b as n}from"./chunk-2ULWP26K.js";import{c as Ne,f as Oe}from"./chunk-CQRSMCCG.js";function rn(e){return Sn({...e,namespace:"commands",identity:[e.runToken]})}function Sn(e){let t,u,r=()=>new f("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 m(c){try{let a=await o;return await u.request(a,{mode:"exclusive"},()=>c(a))}catch(a){throw a instanceof f?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:()=>m(d),write:(c,a)=>m(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 on=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}$/),Rn=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Fn=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})]),En={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())},Cn=n.strictObject({...En,content:n.strictObject({type:n.literal("document"),document:re})}),pe=n.strictObject({id:n.uuid(),source:on,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:Rn,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:Cn.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:Fn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),Pn=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()}),an=Pn.extend({run:pe.extend({paywall:pe.shape.paywall.unwrap().extend({resolution:ce}).nullable()})});var un="X-Indiana-Server-Key";var Nn=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()}),On=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(Nn).max(200).default([]),iam:Ge.optional(),renderGuard:Z.optional()}),me=On.omit({variation:!0,description:!0,iam:!0}),An=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)}),sn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(An).max(100),savedGroups:je});var $=n.string().regex(/^[a-f0-9]{64}$/),Ot=n.strictObject({iam:$,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),Tn=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()}),At=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:Tn})).max(4e3)}),Tt=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")}),_t=n.strictObject({scope:V,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),kt=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),_n=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()}),ln=n.strictObject({scope:V,runId:n.uuid(),assignments:n.array(_n.extend({receiptId:n.uuid()})).max(100),payload:sn});var U=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),dn=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)}),cn={scope:V,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:dn},X=n.discriminatedUnion("evaluationMode",[n.strictObject({...cn,evaluationMode:n.literal("local"),growth:K,conditions:n.record(U,n.array(n.strictObject({condition:Te,port:n.string()})))}),n.strictObject({...cn,evaluationMode:n.literal("remote")})]),kn=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 Dn(e){return dn.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 m=e.screens.find(d=>d.id===t.screenId);m?.type==="paywall"&&(r.paywallVersionId=m.paywallVersionId)}break;case"condition":t.cases.forEach((m,d)=>{u[`case:${d}`]=m.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 m of["success","cancel","unavailable","failure"])u[m]=t[m];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:Dn(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((m,d)=>({condition:m.condition,port:`case:${d}`}))]))})}function Kt(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 kn.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,Vn=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 Ln=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),Mn=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()})}),Yt=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:Ln,context:ye,steps:n.array(Mn).min(1).max(Ie)}).refine(e=>Y(e)<=Vn,"Segment exceeds its byte budget");var qn=/^(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):!qn.test(t))}function pn(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 m=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"&&(m.includes(`variables.${c}`)||m.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),jn=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=jn(e.growth);function m(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:m,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=m(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=m(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 lr(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 m=we(u,t);return(d,c)=>(o(),Gn(m,d,c))}function Gn(e,t,u){let r=Ae.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:o,onFeatureUsage:m,onExperimentViewed:d}=u,c={attributes:r,...o?{saveStickyBucketAssignmentDoc:a=>o(structuredClone(a))}:{},...m?{onFeatureUsage:(a,i)=>m(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 cr(e,t,u,r=ee){return mn(be(e,r),t,u)}function mn(e,t,u){let r=[],o=[],m=[],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){m.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:m}}function fn(e,t,u,r=ee){let o=u,m=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=>pn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},o.attributes.funnelCustomerBound===!0),b=O=>(v??=be(e,r),mn(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=m.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 p,x;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")p=b(s.id),s.type==="offering"&&(p.value={type:"offering_version",id:String(p.value)}),s.type==="condition"?x=p.port==="default"?s.default:s.cases[Number(p.port.slice(5))]?.target:s.type==="split"?x=p.port==="notParticipating"?s.notParticipating:s.routes[p.port]:(s.type==="feature"||s.type==="offering")&&(x=s.next);else if(p={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(x=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(p.value={type:"offering_version",id:s.configuration.versionId},x=s.next),s.type==="end"||s.type==="output"){let S=s.type==="end"?s.output:s.value;if(p=S?.type==="feature"?b(s.id):{...p,port:"value",value:S?.type==="literal"?S.value:S?.type==="variable"?Me({source:"variable",key:S.key,...S.path?{path:S.path}:{}},{declarations:t.variables,answers:u.answers,results:d,parameters:u.parameters,attributes:o.attributes,savedGroups:{}}):null},S&&(p.value===void 0||!De(t.outputSchema,p.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let C=[...a,{nodeId:i,result:p}];if(Y({steps:C})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:i,result:p}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let S=s.type==="coupons"?s.couponIds.map(D=>({type:"reward",id:D})):s.type==="coupon"?{type:"reward",id:s.couponId}:p.value;if(S===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=Ve(s,{value:S});Le(t.variables,s,_),Object.assign(d,_)}for(let S of p.sticky)c[`${S.next.attributeName}||${S.next.attributeValue}`]=structuredClone(S.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");i=x,g++}let T=m.get(i);return{steps:a,...!y&&T&&(!ve(T)||h(T))?{boundary:{nodeId:i,visit:g}}:{}}}function gn(e,t){let u=an.safeParse(t);if(!u.success)throw new f("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new f("SCOPE_MISMATCH","Funnel scope changed");return r}var xe=(e,t)=>new f(e,t);function Ir(e){return we(e,xe)}var Un=3,Bn=2e3;function Kn(e){return e instanceof TypeError||e instanceof f&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function zn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===Un||!Kn(u))throw u;await new Promise(r=>setTimeout(r,t*Bn))}}async function Se(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new f("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new f("SCOPE_MISMATCH","Evaluation environment changed");let o=null,m;if(u)try{let d=await e.funnel(t.source.id,t.source.versionId);m=d.manifest.generation,o=$n(e,t,d)}catch{o=null}return m??=e.snapshot?.generation??(await zn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:m},prediction:o}}function $n(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:m,...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=Jn(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 Jn(e,t,u){return fn(e,t,u,xe)}var yn=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 f("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),In=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:yn.optional(),closeCommand:yn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),A=()=>new f("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),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 vn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),o=Promise.resolve();async function m(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new f("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:In.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 m();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 m();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let i=In.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,b]of Object.entries(i.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==b)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 Or(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,m)=>te(o,t[m]));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,m])=>Object.hasOwn(t,o)&&te(m,Reflect.get(t,o)))}function hn(e,t){let u=t&&{...t},r=null,o=0,m=-1,d=0,c=new AbortController;function a(){d++,c.abort(new f("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 f("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return m===d?r:null},get viewAgeMs(){return r&&m===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,b="Run identity changed during the request"){if(h!==d||i)throw new f("IDENTITY_CHANGED",b)},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 f("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new f("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,b,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&b.run.revision<=r.revision)&&!(r&&b.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!b.run.stopped&&["running","waiting"].includes(b.run.status)&&r&&m===d&&b.run.nodeId===r.nodeId&&b.run.visit===r.visit&&b.run.revision===r.revision&&(b.run.screen=r.screen,(r.paywall?.quote?.operationId===b.review?.activeOperationId||!r.paywall?.quote&&b.review?.activeOperationId===null)&&(b.run.paywall=r.paywall)),!(r?.paywall&&b.run.paywall&&r.paywall.receiptId===b.run.paywall.receiptId&&(b.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||b.run.revision>=r.revision)r=b.run,o=performance.now(),m=d;else if(!s)return;if(r&&m===d)for(let p of v)try{p(structuredClone(r))}catch{}}},identify(h){if(i)throw new f("IDENTITY_CHANGED","Controller was reset");if(!Q.test(h))throw new f("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 Re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function Lr(e,t,u="A server API key is required"){if(typeof window<"u")throw new f("SERVER_ONLY",t);if(!Re.test(e))throw new f("INVALID_TOKEN",u)}function Mr(e){let t=W(e);return t.identify(e.apiKey),t}function wn(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 f("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function q(e){let{customerToken:t,...u}=e;return u}var Hn=e=>!(e instanceof f&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof f)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function bn({journal:e,state:t,call:u,processIdentity:r}){let o=null,m=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 f("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(x=>x&&!Object.hasOwn(s.processBindingIds??{},x.requestId)))throw new f("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new f("SCOPE_MISMATCH","Pending command belongs to another scope");if(i=s.purchase,d=s.closed===!0,!s.command)return;let p=s.command;o=p.operation==="close"?null:p,m=p.operation==="close"?p:s.closeCommand?.operation==="close"?s.closeCommand:null,m&&(d=!0);for(let x of[o,m])x&&a.add(x.requestId)}):Promise.resolve();y.catch(()=>{});async function v(s){e&&await y;let p=t.generation;if(e){if(!t.view||!t.scope)throw new f("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:q(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(p!==t.generation||o!==s&&m!==s)throw new f("IDENTITY_CHANGED","Run changed before command dispatch");let x=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(C){let S=s.operation==="submit"&&s.input.type==="paywall_quote",_=!x&&!Hn(C),D=!1;if(S&&_&&p===t.generation&&o===s&&C instanceof f&&C.status!==void 0){let l=await T(s.requestId).catch(()=>{});D=l?.settlement?.state==="unknown"&&l.settlement.operationId===null}throw p===t.generation&&(o===s||m===s)&&_&&(!S||!(C instanceof f)||C.status===void 0||D)&&(e&&await e.settle(s.requestId),p===t.generation&&O(s)),C}}function h(s){let p=G.parse(s);if(p.operation==="start"||p.operation==="get"||p.operation==="review")throw new f("INVALID_REQUEST","Mutation required");if(d&&p.operation!=="close"){if(o?.requestId===p.requestId)return T(p.requestId);throw new f("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(p.operation==="close"){if(o?.requestId===p.requestId)throw new f("INVALID_REQUEST","Close requires its own request identity");if(d=!0,m&&JSON.stringify(q(m))!==JSON.stringify(q(p)))throw new f("COMMAND_PENDING","Retry the original Close");return m??=p,c.close?c.close:b(m,"close")}if(o){if(JSON.stringify(q(o))!==JSON.stringify(q(p)))throw new f("COMMAND_PENDING","Retry the original command before sending another");if(c.command)return c.command}else o=p;return b(o,"command")}function b(s,p){let x=v(s);c[p]=x;let C=()=>{c[p]===x&&(c[p]=null)};return x.then(C,C),x}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||o!==s&&m!==s?!1:(o===s&&(o=null),m===s&&(m=null),a.delete(s.requestId),!o&&!m&&(g=null),!0)}return{ready:y,get pending(){return o},get closing(){return m},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 f("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,p,x,C){let S=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=S&&p.settlement?.state==="settled"&&p.run.pendingRequest?.requestId!==S&&(s.operation==="get"||!d||s.operation==="close"||!["running","waiting"].includes(p.run.status))?S:void 0,D=o?.requestId===_?o:m?.requestId===_?m:void 0;e?.bind({scope:p.scope,runId:p.run.id,funnelId:p.run.source.id,versionId:p.run.source.versionId});let l=p.run.paywall,I=l??p.purchase,P=I?.operation,E=p.settlement&&(!l||l.purchaseRequestId===p.settlement.requestId)&&(!i||i.operationId===p.settlement.operationId)?p.settlement:void 0,R=P?.operationId??I?.quote?.operationId??E?.operationId,F=I?.receiptId??E?.receiptId,w=l?.selectionGeneration??i?.generation??0;if(e&&R&&F&&s.operation!=="review"&&(!t.view||p.run.revision>=t.view.revision)&&(C===void 0||C>=t.readSequence)&&(!i||w>=i.generation)){let N={receiptId:F,operationId:R,generation:w},k=tn(P,I?.canReselect===!0);await e.observePurchase({scope:p.scope,runId:p.run.id,funnelId:p.run.source.id,versionId:p.run.source.versionId},N,k,_),t.assertCurrent(x),(!i||N.generation>=i.generation)&&(C===void 0||C>=t.readSequence)&&(k?i?.operationId===N.operationId&&(i=void 0):i=N)}else e&&_&&await e.settle(_);return t.assertCurrent(x),_?O(D):!1},stop(){d=!0},submit:h,settle:T,reset(){d=!0,o=null,m=null,i=void 0,g=null,c.close=null,a.clear(),c.command=null}}}function Qn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new f("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new f("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Re.test(e.serverKey)))throw new f("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new f("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=W({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),o=hn(e.funnelId,e.scope??e.configuration?.scope),m=e.session?.subscribeIdentity(b),d=null,c=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?rn(e):void 0),a=c&&vn(c),i=bn({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 f("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(I?.operation==="submit"&&I.input.type==="paywall_confirm"){let N=o.view?.paywall;wn(u,N?.quote?.operationId===I.input.operationId?N.quote:void 0)}if(e.process)return e.process.request(l);let P=o.generation;o.assertCurrent(P);let E=performance.now()+(e.timeoutMs??35e3),R=o.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let N=o.signal,k,B=()=>{},xn=new Promise((Yn,Fe)=>{B=()=>Fe(N.reason),N.addEventListener("abort",B,{once:!0}),k=setTimeout(()=>Fe(new f("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{R=await Promise.race([Promise.resolve().then(()=>(o.assertCurrent(P),e.session.access())),xn])}finally{clearTimeout(k),N.removeEventListener("abort",B)}}o.assertCurrent(P);let F={...l,...R?{customerToken:R}:{}},w=l.operation==="page_experiments"?fe.parse(F):G.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!R)throw new f("IDENTITY_CHANGED","Original recovery Customer changed");let N={...w};return"customerToken"in N&&delete N.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:N},R,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",w,e.runToken,{headers:e.serverKey&&!R?{[un]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function b(){v(),m?.(),o.reset(),i.reset(),d=null,r.dispose()}async function T(l,I){let P=t;t=void 0;let E=o.generation,R=()=>o.assertCurrent(E);a&&await i.ready,R();let F=o.view,w=gn(e,P!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?P:await h(l));if(l.operation==="review"&&!w.review)throw new f("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&w.run.id!==e.customerRun.runId)throw new f("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&w.purchase&&(w.purchase.receiptId!==l.purchase.receiptId||(w.purchase.operation?.operationId??w.purchase.quote?.operationId)!==l.purchase.operationId))throw new f("INVALID_RESPONSE","The requested original purchase changed");if(R(),w.runToken&&w.runToken!==e.runToken)throw new f("INVALID_RESPONSE","Run credential changed");let N=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(N&&w.settlement?.requestId!==N)throw new f("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");i.assertBinding(w),o.assertRun(w.run),o.bindScope(w.scope);let k=await i.observe(l,w,E,I);return(!o.view||w.run.revision>=o.view.revision)&&(I===void 0||I>=o.readSequence)&&(await e.onAcceptedResponse?.(w),R()),!w.run.stopped&&["running","waiting"].includes(w.run.status)&&l.operation==="get"&&l.settlementRequestId||(R(),["running","waiting"].includes(w.run.status)||i.stop(),o.publish(l,w,F,I,k)),w}function O(l){let I=o.generation;v();let P=l(),E=()=>{o.generation===I&&v()};return P.then(E,E),P}let s=l=>O(()=>i.submit(l)),p=null,x=new WeakMap;function C(l){let I=x.get(l);if(I)return I;let P=_(l);return x.set(l,P),P}let S=!1;async function _(l){let I=await l;if(I.run.instruction?.type!=="evaluate_segment")return I;if(p)return p;S=!0;let P=o.generation,E=(async()=>{for(let R=0;R<32&&I.run.instruction?.type==="evaluate_segment";R++){if(i.pending||i.closeRequested)return I;let F=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:N}=await Se(e.configuration,F,{predict:!1});if(P!==o.generation)throw new f("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;Se(e.configuration,F).then(({prediction:B})=>{k&&P===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,...N})}finally{k=!1,d=null}}}return I})();p=E;try{return await E}finally{p===E&&(p=null)}}let D={get configuration(){return S?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 P=o.generation;o.assertCurrent(P);let E=o.view?.id;if(!E)throw new f("INVALID_REQUEST","Read the Run before its page experiments");let R=ln.parse(await h(fe.parse({operation:"page_experiments",release:l,usedReceiptIds:I})));if(o.assertCurrent(P),R.runId!==E||R.scope.projectId!==o.scope?.projectId||R.scope.environment!==o.scope?.environment)throw new f("SCOPE_MISMATCH","Page experiment Run changed");return R},review(l){return T({operation:"review",...l?{receiptId:l}:{}},o.nextRead())},async get(l,I){let P=o.generation;l=l&&structuredClone(l),I=I&&{...I},a&&await i.ready,o.assertCurrent(P),I??=i.purchase&&{receiptId:i.purchase.receiptId,operationId:i.purchase.operationId};let E=JSON.stringify([o.generation,g,l??null,I??null]),R=y.get(E);if(R)return R.then(k=>structuredClone(k));let F=o.nextRead(),w=C(T({operation:"get",...l?{data:l}:{},...I?{purchase:I}:{}},F));y.set(E,w);let N=()=>{y.get(E)===w&&y.delete(E)};return w.then(N,N),w.then(k=>structuredClone(k))},resume(l=o.view?.pendingRequest?.requestId){return l?i.closeRequested?D.settle(l):i.pending?.requestId===l?C(s(i.pending)):C(s({operation:"resume",requestId:l})):Promise.reject(new f("INVALID_REQUEST","No interrupted command is available"))},submit(l){return C(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 C(i.inFlight);if(!i.pending)throw new f("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 f("COMMAND_PENDING","The original quote is being recovered")}return C(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:b};return D}function uo(e,t){return Qn({...e,runToken:"",initialResponse:t})}export{on as a,Fn as b,pe as c,Pn as d,an as e,Tn as f,At as g,Tt as h,_t as i,fe as j,ln as k,X as l,kn as m,Kt as n,lr as o,cr as p,gn as q,xe as r,Ir as s,Jn as t,In as u,H as v,rn as w,Sn as x,Or as y,te as z,Re as A,Lr as B,Mr as C,wn as D,Qn as E,uo as F};
@@ -1 +0,0 @@
1
- import{b as Wn}from"./chunk-BWRRZ2NW.js";import{a as xn,b as Gn,c as dn,d as cn,e as Ue,f as Qn,h as Jn,i as jn,j as zn,k as Bn}from"./chunk-EJSDOSP5.js";import{b as kn,c as Yn}from"./chunk-VWRQBQZD.js";import{a as Ln}from"./chunk-W32FI2A2.js";import{c as Hn,e as Vn,f as Un,h as Mn,i as Fe,j as Ze,k as $n,l as Ke}from"./chunk-AQQJPP3P.js";import{K as Xe}from"./chunk-OAAS5LJY.js";import{a as Ve,d as Tn}from"./chunk-PYLX3WF6.js";import{c as An,e as Sn,f as Nn,g as On,h as Fn,i as _n}from"./chunk-W35FZWGG.js";import{b as qn}from"./chunk-RQTYIUWP.js";import{B as un}from"./chunk-7IVLNV5H.js";import{w as Rn}from"./chunk-VJHURKRY.js";import{t as Dn}from"./chunk-KINNES62.js";import{C as En}from"./chunk-Y2HXKANG.js";import{a as m}from"./chunk-G6CWZBT5.js";import{a as Pe}from"./chunk-DSPLGTQI.js";async function pn(t){let{session:v,load:R}=st(t);try{return await R(),v}catch(e){throw v.destroy(),e}}function st(t){let v=t.view;if(!v?.paywall)throw new m("INVALID_REQUEST","The current node is not a Paywall");let R=v.paywall.receiptId,e=v.nodeId,y=v.visit,N=v.paywall.resolution,o=v.paywall,L="document"in N?{document:N.document,offering:N.offering,capabilities:N.capabilities}:null;function d(){let i=o.resolution;return"document"in i?i:L&&{...i,document:L.document,offering:L.offering,capabilities:An(i.capabilities,L.capabilities)}}function I(i){if(!Sn(i,N))throw new m("INVALID_RESPONSE","The pinned Paywall binding changed")}let E=!1,M=new Set,ne=null;function w(){let i=d();if(i&&!E)for(let l of M)Pe(l,structuredClone(i))}async function V(){F();let i=d();if(i)return structuredClone(i);if(!ne){let l=(async()=>{if("document"in o.resolution||!t.resolvePaywall)throw new m("INVALID_RESPONSE","Public Paywall reader is unavailable");let C=await kn(t,o.resolution);return F(),I(C),L={document:C.document,offering:C.offering,capabilities:C.capabilities},w(),d()})();ne=l;let a=()=>{ne===l&&(ne=null)};l.then(a,a)}return ne.then(l=>structuredClone(l))}let s=new AbortController,T=(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===y&&i.input.type==="paywall_quote")?.requestId??v.paywall.purchaseRequestId,W=0,J=null,Q=new Set,D=null,j=new Map;function A(i){if(i.purchase&&i.purchase.receiptId!==R)throw new m("INVALID_RESPONSE","Purchase receipt changed");let l=i.run.paywall;return i.purchase??(l?.receiptId===R?l:null)}function F(){if(E)throw new m("IDENTITY_CHANGED","Paywall presentation has closed")}function _(i,l,a){if(F(),l!==W||a!==void 0&&o.quote?.operationId!==a)return!1;let C=o.selectionGeneration??0,c=i.run.paywall;if(c?.receiptId===R){if((c.selectionGeneration??0)<(o.selectionGeneration??0))return!1;I(c.resolution)}let u=A(i),b=c?.receiptId===R&&(c.selectionGeneration??0)>C,P=b?u?.quote??null:u?.quote??o.quote,Z=u?.operation??(P?.operationId===o.quote?.operationId?o.operation:null);return o.quote&&P&&Fn(o.quote,P),P&&Z&&Nn(Z,{operationId:P.operationId,membershipId:un(P)?P.membershipId:null,...un(P)?{featureQuantities:P.featureQuantities??{}}:{}},"Purchase operation changed"),(b||P?.operationId!==o.quote?.operationId)&&(W++,c?.receiptId===R&&(T=c.purchaseRequestId)),c?.canReselect===!0&&c.purchaseRequestId===D&&!(t.pendingCommands??[t.pendingCommand]).some($=>$?.requestId===D)&&(D=null),o={...o,...c?.receiptId===R?c:{},...a!==void 0&&!b&&u?.canReselect!==void 0?{canReselect:u.canReselect}:{},quote:P,operation:_n(o.operation,Z,!0)},w(),!0}function pe(i,l,a){return new Promise((C,c)=>{let u=!1,b=()=>{clearTimeout(le),s.signal.removeEventListener("abort",$)},P=Ee=>{u||(u=!0,b(),C(Ee))},Z=Ee=>{u||(u=!0,b(),c(Ee))},$=()=>Z(new m("IDENTITY_CHANGED","Paywall presentation has closed")),le=setTimeout(()=>Z(new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a)),Math.max(0,l-Date.now()));s.signal.addEventListener("abort",$,{once:!0}),s.signal.aborted&&$(),i.then(P,Z)})}function Re(i){return new Promise(l=>{let a=()=>{clearTimeout(C),s.signal.removeEventListener("abort",a),l()},C=setTimeout(a,i);s.signal.addEventListener("abort",a,{once:!0}),s.signal.aborted&&a()})}function se(i,l){F();let a=j.get(i)??t.pendingCommands?.find(u=>u.requestId===i)??t.pendingCommand;if(a?.operation==="submit"&&a.requestId===i&&a.nodeId===e&&a.visit===y){l.type==="paywall_quote"&&a.input.type==="paywall_quote"&&a.input.predecessor&&!l.predecessor&&(l={...l,predecessor:a.input.predecessor});let u=Xe.parse(a),b=Xe.parse({...a,input:l});if(u.operation!=="submit"||b.operation!=="submit"||JSON.stringify(u.input)!==JSON.stringify(b.input))throw new m("CONFLICT","A purchase request cannot change its input");return j.set(i,u),u}let C=t.view;if(!C||C.nodeId!==e||C.visit!==y||C.paywall?.receiptId!==R)throw new m("PRECONDITION_FAILED","The Paywall visit has changed");let c=Xe.parse({operation:"submit",requestId:i,nodeId:e,visit:y,revision:C.revision,input:structuredClone(l)});if(c.operation!=="submit")throw new m("INVALID_REQUEST","A purchase submission is required");return j.set(i,c),c}async function te(i,l){F();let{requestId:a,input:C}=i,c=Date.now()+3e4;Q.add(a);try{let u=await pe(t.submit(i),c,a);for(;u.run.pendingRequest?.requestId===a&&Date.now()<c&&!E&&(await Re(Math.min(1e3,c-Date.now())),!(E||Date.now()>=c));)u=await pe(t.resume(a),c,a);if(E)throw new m("IDENTITY_CHANGED","Paywall presentation has closed");if(u.run.pendingRequest?.requestId===a)throw new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a);if(!_(u,l,C.type==="paywall_confirm"||C.type==="paywall_cancel"?C.operationId:void 0))throw new m("PRECONDITION_FAILED","The purchase selection has changed");D===a&&(D=null)}catch(u){if(D=a,C.type==="paywall_quote"&&t.settle&&!E&&u instanceof m&&u.status!==void 0&&![401,425].includes(u.status)&&!u.retryable&&u.recovery!=="recover_operation")try{if((await pe(t.settle(a),c,a)).settlement?.state==="settled"){let P=await pe(t.get(),c,a);_(P,l)&&P.run.paywall?.purchaseRequestId===a&&o.canReselect===!0&&j.delete(a)}}catch{}throw u instanceof m&&u.code==="COMMAND_PENDING"&&u.status===void 0&&j.delete(a),u}finally{Q.delete(a)}}async function we(i){if(!o.quote)throw new m("INVALID_REQUEST","A quoted purchase is required");let l=i==="confirm"?"paywall_confirm":"paywall_cancel",a=[...j.values(),...t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])].find(c=>c.operation==="submit"&&c.input.type===l&&"operationId"in c.input&&c.input.operationId===o.quote.operationId),C=a?.operation==="submit"&&a.input.type===l&&"operationId"in a.input&&a.input.operationId===o.quote.operationId?a.requestId:crypto.randomUUID();if(await te(se(C,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.quote.operationId,...i==="confirm"&&o.quote.merchantTerms?{merchantConfirmation:Rn(o.quote.merchantTerms)}:{}}),W),!o.operation)throw new m("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(o.operation)}let G={get view(){return structuredClone(d())},get quote(){return o.quote?structuredClone(o.quote):null},get operation(){return o.operation?structuredClone(o.operation):null},get webViewUrl(){return t.webViewUrl},get locale(){return t.view?.locale??v.locale},get canReselect(){return o.canReselect===!0&&D===null},get recovery(){let i=t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[]),l=t.pendingPurchase;if(l&&(l.receiptId!==R||l.operationId!==o.quote?.operationId))return{type:"recover",operationId:l.operationId,requestId:i[0]?.requestId??null};let a=Ve({quote:o.quote,operation:o.operation,requestId:i[0]?.requestId??D??T,pending:Q.size>0||i.length>0||D!==null,destroyed:E,canReselect:o.canReselect});return a.type==="recover"&&a.requestId===null&&!E&&t.hasDurableJournal===!0&&!o.quote&&!o.operation&&(o.selectionGeneration??0)===0&&!l&&!i.length&&!Q.size&&!T?{type:"native",operationId:null}:a},get pendingCancellation(){return!E&&(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===y&&i.input.type==="paywall_cancel"&&i.input.operationId===o.quote?.operationId)},subscribe(i){return E?()=>{}:(M.add(i),()=>M.delete(i))},async refresh(){F();let i=W,l=await t.get();if(_(l,i),l.run.paywall?.receiptId!==R)throw new m("PRECONDITION_FAILED","Paywall presentation has changed");return V()},preview(i){let l=d();if(!l)return Promise.reject(new m("PRECONDITION_FAILED","Load the Paywall presentation first"));if(T&&T!==i.requestId&&(J||o.canReselect!==!0))return Promise.reject(new m("COMMAND_PENDING","Retry the original purchase before starting another"));let a=l.document.buttons[i.actionId],C=a?.type==="checkout"?qn(a.product,i.selection,l.capabilities):null;if(!C)return Promise.reject(new m("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let c=Dn(l.document.screen,C,i.selection,l.capabilities),u=T!==i.requestId&&(o.selectionGeneration??0)>0?{operationId:o.quote?.operationId??null,generation:o.selectionGeneration??0}:void 0,b=t.view?.parameters.commerce;if(b&&typeof b=="object"&&!Array.isArray(b)&&b.intent==="subscription_change"&&!i.subscriptionChange)return Promise.reject(new m("INVALID_REQUEST","Choose the existing membership for this subscription change"));if(i.subscriptionChange&&i.nativeOffer)return Promise.reject(new m("INVALID_REQUEST","A web membership change cannot include a store offer"));if(u&&o.canReselect!==!0)return Promise.reject(new m("COMMAND_PENDING","Original purchase requires authoritative termination"));let P;try{P=se(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:C,...Object.keys(c).length?{featureQuantities:c}:{},...u?{predecessor:u}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{},...i.subscriptionChange?{subscriptionChange:i.subscriptionChange}:{}})}catch(le){return Promise.reject(le)}if(T===i.requestId&&J)return J;T!==i.requestId&&W++;let Z=W;T=i.requestId;let $=(async()=>{if(await te(P,Z),!o.quote)throw new m("INVALID_RESPONSE","The accepted quote is missing");return On(o.quote,{productVersionId:C,featureQuantities:c,subscriptionChange:i.subscriptionChange},"The selected purchase changed"),structuredClone(o.quote)})();return J=$,$.then(()=>{J===$&&(J=null)},le=>{J===$&&(J=null),T===i.requestId&&t.pendingCommand?.requestId!==i.requestId&&le instanceof m&&le.status!==void 0&&le.status<500&&![401,425].includes(le.status)&&(T=null)}),$},confirm:()=>we("confirm"),cancel:()=>we("cancel"),async read(){if(F(),!o.quote)throw new m("INVALID_REQUEST","A quoted purchase is required");let i=o.quote.operationId,l=W,a=t.pendingCommands?.find(P=>P.operation==="submit"&&(P.input.type==="paywall_confirm"||P.input.type==="paywall_cancel")&&P.input.operationId===i)??t.pendingCommand;a?.operation==="submit"&&(a.input.type==="paywall_confirm"||a.input.type==="paywall_cancel")&&a.input.operationId===i&&await t.settle?.(a.requestId);let C=await t.get(void 0,{receiptId:R,operationId:i});F();let c=A(C);if(c?.quote&&c.quote.operationId!==i||c?.operation&&c.operation.operationId!==i)throw new m("INVALID_RESPONSE","Purchase operation changed");let u=_(C,l,i),b=u?o.operation:c?.operation;if(!b)throw new m("INVALID_RESPONSE","The current purchase result is missing");return u&&Q.size===0&&!(t.pendingCommands?.length??(t.pendingCommand?1:0))&&(D=null),structuredClone(b)},destroy(){E=!0,S(),M.clear(),s.abort(),j.clear()}},S=t.subscribe(i=>{E||i.nodeId!==e||i.visit!==y||i.paywall?.receiptId!==R||(i.paywall.selectionGeneration??0)<(o.selectionGeneration??0)||(I(i.paywall.resolution),o={...o,resolution:i.paywall.resolution},w())});return{session:G,load:V}}function Xn(t){let v=new Set,R=new Set,e=null;async function y(d,I){let E=!1;for(;!t.stopped&&t.key===d&&t.client.pendingCommand?.requestId===I;){if(!t.client.settle)throw new m("COMMAND_PENDING","The original display acknowledgement is still pending");await t.client.settle(I),E=!0,t.client.pendingCommand?.requestId===I&&await new Promise(M=>setTimeout(M,1500))}t.stopped||t.key!==d||(E&&await t.client.get(),!(t.stopped||t.key!==d)&&v.add(d))}function N(d,I){e=I;let E=()=>{e===I&&(e=null),R.delete(d)};return I.then(E,M=>{E(),t.busy||t.fail(M)}),I}function o(d){if(t.reviewing||v.has(d)||R.has(d)||t.stopped)return;R.add(d);let I=async()=>{if(t.reviewing||t.stopped||t.key!==d||v.has(d)){R.delete(d);return}if(t.busy||t.client.pendingCommand){setTimeout(()=>{I()},250);return}let E=(async()=>{if(t.staleRead){if(await t.staleRead,t.stopped||t.key!==d)return;if(t.client.pendingCommand){setTimeout(()=>{I()},250);return}}let M=t.client.view,ne=t.expected(),w=ne.requestId;try{await t.client.submit({operation:"shown",...ne})}catch(V){if(!(V instanceof m)||V.code!=="CONFLICT"||V.status!==409||t.client.pendingCommand)throw V;await t.client.get();let s=t.client.view;if(t.stopped||t.reviewing||t.key!==d||!s||!M||s.id!==M.id||s.source.versionId!==M.source.versionId||s.nodeId!==ne.nodeId||s.visit!==ne.visit||s.revision<=ne.revision||s.stopped||!s.screen&&(!s.paywall||s.paywall.receiptId!==M.paywall?.receiptId)||!["running","waiting"].includes(s.status)||t.client.pendingCommand)throw V;let q=t.expected();w=q.requestId,await t.client.submit({operation:"shown",...q})}await y(d,w)})();N(d,E)};I()}function L(){if(e)return e;let d=t.client.pendingCommand;if(d?.operation!=="shown")return null;let I=t.key;return R.add(I),N(I,(async()=>{await t.client.retry(),await y(I,d.requestId)})())}return{report:o,settled:L,get inFlight(){return e}}}function Zn(t){let v={},R=new Map;async function e(y){let N=t.client.view,o=N?.screen,L=o?.customerData.nodes[y.nodeId];if(t.stopped||t.busy||!N||!o||!L)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(y.action)){let V=t.document,s=V?En(V,y.nodeId):null,q=s?.type==="customer_data"?s.data.outputs?.[y.action]:void 0;q&&o.outputs.includes(q)?await t.perform(()=>t.client.submit({operation:"submit",...t.expected(),input:{type:"screen",output:q,answers:t.answers,selection:y.value?{[y.nodeId]:y.value}:{}}})):await t.onIntent?.(y,N);return}let I=y.action.startsWith("sources_")?L.resources.find(V=>V.key===y.value):null;if(y.action.startsWith("sources_")&&!I)throw new m("INVALID_REQUEST","Choose a current resource");let E=`${N.visit}:${y.nodeId}:${I?.key??""}`,M=R.get(E)??[null],w=v[y.nodeId]??{page:1,after:null,filter:"all",...I?{resourceKey:I.key}:{}};if(y.action==="filter"){let V=y.value;if(!V||!(L.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(V))throw new m("INVALID_REQUEST","Unknown data filter");w={page:1,after:null,filter:V},M.splice(0,M.length,null)}else if(y.action==="next"||y.action==="sources_next"){let V=I?.sources.at(-1),s=I?V?{kind:"ledger",cursor:{at:V.detail[0],id:V.id,type:"source"}}:null:o.dataCursors[y.nodeId];if(!s||!I&&!L.hasNext)return;M[w.page]=s,w={...w,page:w.page+1,after:s}}else if(y.action==="previous"||y.action==="sources_previous"){if(w.page<=1)return;w={...w,page:w.page-1,after:M[w.page-2]??null}}R.set(E,M),v={...v,[y.nodeId]:w},await t.perform(()=>t.client.get({nodeId:N.nodeId,visit:N.visit,revision:N.revision,components:v}))}return{get queries(){return v},intent:e,reset(){v={},R.clear()}}}function Kn(t){let{doc:v,holder:R,reviewHolder:e,mountScreenPreview:y}=t,N=!1,o,L=0,d=null,I="",E,M=new Map,ne=s=>s?`${s.id}:${s.nodeId}:${s.visit}:${s.revision}:${s.paywall?.quote?.operationId??""}`:"";async function w(s){if(t.stopped||!t.client.review||N&&s===o&&E?.active)return;let q=!N||s!==o;N||(I=ne(t.client.view),M.set(I,structuredClone(t.answers))),N=!0,o=s,R.hidden=!0,t.suspend(!0),e.hidden=!1;let T=++L;q&&(E?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),E=Ze(e,t.loadingOptions,"funnel",()=>{V()}));let W=q?E:void 0;try{if(W?.start(!1,t.client.view?.locale),T!==L||t.stopped)return;let J=t.client.review(s),Q=await(W?.wait(J,Fe)??J);if(t.stopped||T!==L||!N)return;if(!Q.review)throw new m("INVALID_RESPONSE","Historical projection is missing");d?.destroy(),d=null,W||e.replaceChildren();let D=v.createElement("div"),j=W?Ke(D,e):()=>{};e.append(D);let A=Q.run.locale.startsWith("zh"),F=t.chrome;D.style.cssText=F.history;let _=v.createElement("p");_.textContent=A?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",_.style.cssText=F.historyTitle,D.append(_);let pe=v.createElement("p");pe.style.cssText=F.historyNote,pe.textContent=Q.review.pages.length?A?"\u9009\u62E9\u4E00\u9875\u67E5\u770B\u5F53\u65F6\u7684\u5185\u5BB9\uFF0C\u56DE\u770B\u4E0D\u4F1A\u6539\u52A8\u4EFB\u4F55\u4FE1\u606F\u3002":"Choose a page to see it as it was. Nothing here can be changed.":A?"\u8FD8\u6CA1\u6709\u53EF\u56DE\u770B\u7684\u9875\u9762\u3002":"There are no earlier pages yet.",D.append(pe);let Re=Q.review.page?.receiptId,se=v.createElement("div");se.style.cssText=F.historyPages;for(let[G,S]of Q.review.pages.entries()){let i=v.createElement("button");i.type="button",i.textContent=A?`\u7B2C ${G+1} \u9875`:`Page ${G+1}`;let l=Re!==void 0&&S.receiptId===Re;i.style.cssText=l?F.primary:F.secondary,l&&i.setAttribute("aria-current","page"),Ue(i,()=>t.chrome.focus),i.onclick=()=>{w(S.receiptId)},se.append(i)}if(se.childElementCount&&D.append(se),Q.review.page){let G=Q.review.page,S=v.createElement("div");S.inert=!0,S.style.cssText=F.historyPage,D.append(S),d=y(S,{mode:"live",rendererUrl:t.client.webViewUrl,title:G.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{T===L&&!t.stopped&&W?.present(j)},onError:l=>{if(T!==L||t.stopped)return;let a=new Error(l);W?.finish("error",a),d?.destroy(),d=null,D.remove(),t.fail(a)},onEscape:()=>{V()}});let i=d;if(i.update(G.document,Q.run.locale,{serverInput:{bindings:G.inputs,answers:G.answers,values:G.values}}),await i.ready,t.stopped||T!==L||!N)return}let te=A?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},we=v.createElement("div");we.style.cssText=F.historyRecords;for(let G of[...Q.review.coupons.map((S,i)=>`${A?"\u4F18\u60E0\u5238":"Coupon"} ${i+1}: ${te[S.status]}`),...Q.review.purchases.map((S,i)=>`${A?"\u8D2D\u4E70":"Purchase"} ${i+1}: ${Bn(S.status,A)}`)]){let S=v.createElement("p");S.textContent=G,S.style.margin="0",we.append(S)}we.childElementCount&&D.append(we),Q.review.page||W?.present(j),t.client.view&&await t.enqueue(t.client.view)}catch(J){if(T!==L||t.stopped)return;W?.finish("error",J),d?.destroy(),d=null,e.replaceChildren(),t.fail(J)}}async function V(){if(!N||t.stopped||!t.client.review)return;let s=++L;E?.finish("dismissed");try{if(await t.client.review(),t.stopped||s!==L)return;N=!1,L++,E?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),e.hidden=!0,R.hidden=!1;let q=t.client.view;ne(q)!==I?(M.set(I,structuredClone(t.answers)),t.resetScreen()):(M.delete(I),t.suspend(!1)),q&&await t.enqueue(q)}catch(q){if(s!==L||t.stopped)return;d?.destroy(),d=null,e.replaceChildren(),t.fail(q)}}return{get active(){return N},get receipt(){return o},open:w,exit:V,get drafts(){return new Map([...M].map(([s,q])=>[s,structuredClone(q)]))},stop(){N=!1,L++,E?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),e.hidden=!0,R.hidden=!1}}}var fn=5e3;async function at(t,v,R){let e=v,y=e.prepared&&Wn(e.prepared),N=()=>{};function o(){e.prepared&&e.prepared.state!=="adopted"&&y?.release()}let L=()=>e.prepared?.state==="shown"&&!!y?.modal,d=e.client.identitySignal,I;try{I=await Promise.all([import("./screen-renderer-SEJG7A2C.js"),import("./paywall-YZAEI7TF.js")]),e.signal?.throwIfAborted(),d?.throwIfAborted()}catch(n){throw o(),n}let[{mountScreenPreview:E},{showPaywall:M}]=I,ne=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&e.appManifestRelease?Yn({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;ne?.start();let w=t.ownerDocument,V=Mn(w),s=w.createElement("section"),q=w.createElement("div"),T=w.createElement("div"),W=w.createElement("div"),J=w.createElement("button");W.hidden=!0,J.type="button";let Q=w.createElement("p"),D=w.createElement("p"),j=w.createElement("button"),A=w.createElement("button"),F=w.createElement("button"),_=w.createElement("dialog"),pe,Re=!1;s.dataset.indianaFunnel="",s.dataset.longplayCloseOwner="sdk",s.setAttribute("aria-busy","false"),Q.setAttribute("role","status"),D.setAttribute("role","alert"),D.hidden=!0,j.type=A.type=F.type="button",T.append(j,J,Q,D,F,A),s.append(q,W,T),t.append(s);let se=Gn,te=dn(se),we="",G=(w.documentElement.lang||"").startsWith("zh"),S,i="",l;for(let n of[j,J,F,A])Ue(n,()=>te.focus);function a(){let n=G?"\u5173\u95ED":"Close";A.parentElement===_?(A.textContent="\xD7",A.setAttribute("aria-label",n),Un(A,se)):(A.textContent=n,A.removeAttribute("aria-label"),A.style.cssText=te.link+";margin-inline-start:auto")}function C(n){let r=n?.screen?.content.document.theme??se,p=JSON.stringify([r.primary,r.background,r.text,r.radius,r.font,A.parentElement===_]);if(p===we)return;we=p,se=r;let H=A.parentElement===_;te=dn(se,H),s.style.cssText=te.root+";min-width:0"+(H?";display:flex;flex-direction:column;min-height:100%":""),T.style.cssText=te.bar+(H?";margin-top:auto":""),T.hidden&&(T.style.display="none"),j.style.cssText=J.style.cssText=te.secondary,F.style.cssText=te.primary,Q.style.cssText=te.status,D.style.cssText=te.alert,a(),cn(j)}function c(){T.hidden=j.hidden&&J.hidden&&F.hidden&&D.hidden&&!Q.textContent&&(A.hidden||A.parentElement!==T),T.style.display=T.hidden?"none":"flex",S?.responsive&&l!==void 0&&S.setContentHeight(l+T.getBoundingClientRect().height)}C();let u=null,b=null,P=null,Z="",$="",le=!1,Ee="",en="",Me="",g=!1,ue=0,$e=!1,mn="",nn=null,tn=Promise.resolve(),wn=!e.client.view,z=R,Te,_e,xe="",Ge,de=!1,qe=null,ve=!1,Qe=()=>e.client.pendingCommand?.operation==="close",ce=null,Y=null,yn=Ln({document:w,run:async()=>{(!b?.observing||e.client.pendingCommand)&&await on()},delay:()=>{if(!(g||!P||!["running","waiting"].includes(P.status)&&!e.client.pendingCommand)&&!(b?.observing&&!e.client.pendingCommand))return P.pendingRequest||e.client.pendingCommand?1500:fn},hiddenDelay:()=>!g&&e.client.pendingCommand?15e3:void 0}),K=null;function rn(){return Y&&e.client.hasDurableJournal===!0&&K?.acknowledged===!0&&K.operationId===Y.operationId&&e.client.view?.id===K.runId&&e.client.view?.status==="closed"&&e.client.view.revision===K.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?Y:null}function hn(n){let r=n.run.paywall;if(K&&n.settlement?.requestId===K.requestId&&n.settlement.state==="settled"&&n.settlement.operationId===null&&n.run.id===K.runId&&n.run.status==="closed"&&!n.run.pendingRequest&&n.run.revision===K.revision+1&&n.run.nodeId===K.nodeId&&n.run.visit===K.visit&&r?.receiptId===K.receiptId&&r.selectionGeneration===K.selectionGeneration&&(r.quote?.operationId??null)===K.operationId&&(r.operation?.operationId??r.quote?.operationId??null)===K.operationId){let p=K.operationId===null&&r.selectionGeneration===0&&!r.quote&&!r.operation&&!r.purchaseRequestId,H=Ve({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect});(p||r.canReselect===!0&&H.type==="native")&&(K.acknowledged=!0)}}let De=null,Je=new Set,ye={},Ae=!1,fe=(n,r=null)=>{g||(De=r,Ae=!1,D.textContent=Qn(n,G),D.hidden=!1,F.hidden=e.client.pendingCommand===null,c(),Pe(e.onError,n))},gn=()=>{g||(De=null,D.textContent=jn(G),D.hidden=!1,F.hidden=!0,c())};function ke(){let n=e.client.view;if(!n)throw new m("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision}}let O=Kn({client:e.client,doc:w,holder:q,reviewHolder:W,mountScreenPreview:E,loadingOptions:e,get chrome(){return te},get stopped(){return g},get answers(){return ye},suspend(n){b?.setSuspended(n)},resetScreen(){Z="",$="",Ee=""},enqueue:he,fail:fe}),Le=Xn({client:e.client,expected:ke,fail:fe,get stopped(){return g},get reviewing(){return O.active},get key(){return Z},get busy(){return ue},get staleRead(){return nn}}),je=Zn({client:e.client,expected:ke,perform:Ne,onIntent:e.onCustomerDataIntent,get stopped(){return g},get busy(){return ue},get document(){return u?.document},get answers(){return ye}}),ze=n=>`${n.id}:${n.nodeId}:${n.visit}`,Se=n=>n&&(n.screen||n.paywall)?ze(n):"";function Ie(){let n=e.client.view;j.disabled=!O.active&&(ue>0||!!e.client.pendingCommand||!n?.canBack||n.stopped||!["running","waiting"].includes(n.status)||!Se(n)||$!==Se(n)),j.hidden=!O.active&&!n?.canBack,cn(j);let r=!!b&&!O.active;A.hidden=r&&!z?.active||Re&&!O.active,J.hidden=!e.client.review||!O.active&&!n?.canBack,r&&(Q.textContent=""),c()}async function vn(n){if(!n)return;let r=e.client.view;await n;let p=e.client.view;if(!r||!p||p.id!==r.id||p.nodeId!==r.nodeId||p.visit!==r.visit||p.stopped||!["running","waiting"].includes(p.status))throw new m("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Ne(n,r=!1,p){if(!((ue||ve||ce||Y)&&!r||g||O.active&&!r)){ue++,s.setAttribute("aria-busy","true"),D.hidden=!0,De=null,Ae=!1,Ie();try{if(r||await vn(Le.inFlight),g)return;let H=await n();g||await he(e.client.view??H.run)}catch(H){p?.(H)&&e.client.pendingCommand===null?gn():fe(H,e.client.pendingCommand?.requestId??null)}finally{ue=Math.max(0,ue-1),s.setAttribute("aria-busy",String(ue>0)),g||(F.hidden=e.client.pendingCommand===null,Ie())}}}function He(){yn.schedule()}async function on(){if(!(g||$e||ue)){if(O.active){await O.open(O.receipt);return}$e=!0;try{let n=e.client.pendingCommand;n&&e.client.settle&&await e.client.settle(n.requestId);let r=e.client.view,p=je.queries,H=await e.client.get(r?.screen&&Object.keys(p).length?{nodeId:r.nodeId,visit:r.visit,revision:r.revision,components:p}:void 0);Ae&&!g&&(Ae=!1,D.hidden=!0,c()),!g&&p===je.queries&&await he(e.client.view??H.run)}catch(n){fe(n),Ae=!g}finally{$e=!1}}}function Be(n,r,p){if(z?.active){let ae=z;return ae.setDismissHandler(()=>In(ae)),ae}let H=Ze(t,e,"funnel",()=>In(H),xn);return z=H,H.start(n,r,p),H}function In(n){g||de||(de=!0,n.finish("dismissed"),be(),s.hidden=!0,e.client.view?Ce().finally(ie):ie())}function sn(){clearTimeout(Ge?.timeout),Ge=void 0}function be(){Re=!1,sn(),Te?.abort(),Te=void 0,u?.destroy(),u=null,b?.destroy(),b=null,_e?.(),_e=void 0,_.open&&_.close(),q.replaceChildren(),q.style.cssText="",l=void 0,Z="",$="",le=!1,Ee="",Me=""}function bn(){let n=w.defaultView;S?.responsive&&n&&u?.resizeViewport?.(n.innerHeight,n.innerWidth)}function an(){S?.destroy(),S=void 0,i=""}function We(n){let r=n.screen?.presentation;if(!r||r.type==="inline"){_.open&&_.close(),an(),A.parentElement!==T&&T.append(A),s.parentElement!==t&&t.append(s);for(let ae of["flex","display","flex-direction","justify-content"])q.style.removeProperty(ae);C(n),c();return}s.parentElement!==_&&(_.append(A,s),t.append(_)),q.style.flex="1 0 auto",q.style.display="flex",q.style.flexDirection="column",q.style.justifyContent="center",C(n);let p=n.screen.content.document,H=JSON.stringify([r,we]);if(H!==i){an(),i=H;let ae={sm:420,md:640,lg:900},ge="size"in r&&!r.backdrop?",0 0 0 100vmax #16142566":"";_.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${se.background};color:${se.text};`+(r.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ae[r.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${ge};`+(r.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),S=Hn(_,{presentation:r,theme:p.theme,pages:p.pages},bn),S.latch()}c(),_.setAttribute("aria-label",(pe?.screen===n.screen?.content.document.name?pe?.label:void 0)??u?.document?.name??n.screen?.content.document.name??"Funnel")}async function et(n){if(g||de||ve&&(Qe()||["running","waiting"].includes(n.status))||(P=n,De&&e.client.pendingCommand?.requestId!==De&&(D.hidden=!0,De=null),G=n.locale.startsWith("zh"),J.textContent=G?"\u56DE\u770B":"History",j.textContent=O.active?G?"\u8FD4\u56DE\u5F53\u524D":"Return to current":G?"\u8FD4\u56DE":"Back",a(),F.textContent=G?"\u91CD\u8BD5":"Retry",F.hidden=e.client.pendingCommand===null,Q.textContent=n.pendingRequest?G?"\u6B63\u5728\u5904\u7406":"Processing":n.instruction?.type==="wait"?G?"\u7B49\u5F85\u4E2D":"Waiting":"",Ie(),mn!==`${n.revision}:${n.visit}:${n.status}:${n.stopped}`&&(mn=`${n.revision}:${n.visit}:${n.status}:${n.stopped}`,Pe(e.onState,structuredClone(n))),g||de))return;if((!n.pendingRequest||ve&&n.status==="closed")&&["closed","ineligible","failed"].includes(n.status)){ie();return}if(n.stopped&&L()){ie();return}if(n.stopped||e.client.configurationReady===!1){O.stop(),o(),be(),z?.finish("skipped"),s.hidden=!0,He();return}if(s.hidden=!1,O.active){He();return}let r=Se(n),p=e.client.view;if(p&&p.revision>n.revision&&Se(p)!==r)return;let H=!n.instruction&&!n.pendingRequest&&n.nodeType==="screen"&&["running","waiting"].includes(n.status);r!==Z&&(Z&&z?.finish("dismissed"),be(),Z=r,ye={...n.answers},je.reset());let ae=ze(n);if(xe===ae){s.hidden=!0;return}if(H&&!r){s.hidden=!0;let U=e.prepared?.state==="shown"?null:Be(!0,n.locale);!g&&!de&&Ge?.key!==ae&&(sn(),Ge={key:ae,timeout:setTimeout(()=>{let h=e.client.view;if(g||!U?.active&&e.prepared?.state!=="shown"||!h||ze(h)!==ae)return;xe=ae;let B=new Error("Funnel screen preparation timed out");U?.finish("error",B),o(),be(),fe(B)},Fe)}),He();return}sn();let X=U=>{let h=e.client.view;return!g&&!de&&!qe&&!U.aborted&&e.client.configurationReady!==!1&&!!h&&!h.stopped&&!["closed","ineligible","failed"].includes(h.status)&&Se(h)===r},ge=(U,h)=>{X(h)&&(xe=r,z?.finish("error",U),be(),s.hidden=!0,fe(U))};if(r||((n.instruction&&n.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(n.status))&&o(),We(n),n.instruction?.type!=="event"&&n.instruction?.type!=="open_url"&&z?.finish("skipped")),n.screen){o();let U=n.screen.content;if(!u){let x=n.screen.presentation.type!=="inline",re=Be(x,n.locale);if(g||de)return;let ee=(Te=new AbortController).signal;We(n),_e=x?$n(_):Ke(s,t),u=E(q,{mode:"live",closeActions:Array.from(new Set([...e.closeActions??[],...U.document.actions.filter(f=>f.type==="event"&&f.close).map(f=>f.id)])),onAuthoredClose(f){X(ee)&&(Re=f,Ie())},rendererUrl:e.client.webViewUrl,title:U.document.name,...x?{hostPresentation:()=>S?.type??n.screen.presentation.type}:{},onResize:f=>{l=f,S?.responsive&&S.setContentHeight(f+T.getBoundingClientRect().height)},onAction(f,me={},ot={}){if(O.active||!X(ee)||$!==r)return;ye={...ye,...ot};let ln=n.screen?.inputs??[],Pn=Object.fromEntries(ln.filter(({variable:Oe})=>Object.hasOwn(ye,Oe)).map(({variable:Oe})=>[Oe,ye[Oe]]));if(zn(ln,Pn).length){gn();return}Ne(()=>e.client.submit({operation:"submit",...ke(),input:{type:"screen",output:f,answers:Pn,selection:me}}),!1,Oe=>Jn(Oe,ln))},onAnswers:f=>{O.active||!X(ee)||$!==r||(ye={...ye,...f})},onCustomerDataIntent:f=>{O.active||!X(ee)||$!==r||je.intent(f).catch(fe)},onEscape:()=>{!X(ee)||$!==r||O.active||ce||Y||Ce()},onError:f=>{let me=new Error(f);$===r?fe(me):ge(me,ee)},onRendered:f=>{if(!(!X(ee)||$===r))try{re.present(me=>{_e?.(),_e=void 0,f&&(pe={screen:U.document.name,label:f},_.setAttribute("aria-label",f)),x&&(_.showModal(),S?.responsive&&_.focus({preventScroll:!0}),!me&&e.loading!=="host"&&Vn(_,S?.type??n.screen.presentation.type,S?.responsive)),$=r,le=x,Ie()}),X(ee)&&Le.report(r)}catch(me){ge(me,ee)}}}),bn()}let h={capabilities:n.screen.capabilities,customerData:n.screen.customerData,parameters:n.parameters,serverInput:{bindings:n.screen.inputs,answers:ye,values:n.screen.values}},B=JSON.stringify([U,n.locale,h.parameters,n.screen.inputs,n.screen.values]);if(B!==Ee)u.update(U.document,n.locale,h),Ee=B,en=JSON.stringify(h.capabilities),Me=JSON.stringify(h.customerData);else{let x=JSON.stringify(h.capabilities);x!==en&&(u.updateCapabilities(h.capabilities),en=x),JSON.stringify(h.customerData)!==Me&&(u.updateCustomerData(h.customerData),Me=JSON.stringify(h.customerData))}let oe=u;if(oe)try{await(z?.wait(oe.ready)??oe.ready)}catch(x){Te&&ge(x,Te.signal)}}else if(n.paywall&&!b){let U=n.paywall.resolution,h="document"in U?U.document:null,B=y,oe=null,x=(Te=new AbortController).signal,re={loading:"host",signal:x,canInteract:()=>X(x)&&!O.active&&!ce&&!Y,beforeAction:async()=>{ue++;try{await vn(Le.settled()),D.hidden=!0,De=null,Ae=!1,c()}finally{ue=Math.max(0,ue-1)}},start:()=>pn(e.client),onObservationChange:He,onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,resumeCheckout:e.resumeCheckout,allowNewPurchase:e.allowNewPurchase,checkoutNavigation:e.checkoutNavigation,terminateCheckout:e.terminateCheckout,confirmOnHostedCheckout:e.confirmOnHostedCheckout,resolveOfferId:e.resolveOfferId,resolveSubscriptionChange:e.resolveSubscriptionChange,claimCoupon:e.claimCoupon,onEvent:e.onEvent,onOpenUrl:f=>e.onOpenUrl?e.onOpenUrl({receiptId:n.paywall.receiptId,url:f,openIn:"same_window"}):w.defaultView?.location.assign(f),onAction:async f=>{if(O.active)return;let me=await e.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:e.client.view?.revision??n.revision,input:{type:"screen",output:f,answers:{}}});await he(e.client.view??me.run)},onError:f=>{$===r?fe(f):ge(f,x)}},ee={quoteError:f=>Pe(e.onError,f),present(f){X(x)&&(oe?.present(()=>{f(),$=r,le=!!q.querySelector("dialog[open]"),Ie()}),X(x)&&Le.report(r))},async dismiss(){if(!(g||x.aborted||O.active||ce||Y||!ve&&!X(x))){if(ve=!0,(e.resumeCheckout||e.terminateCheckout)&&rt()){P=e.client.view,ie();return}await Ce()}}};if(B){let f=await B.adopt(n,{options:re,handoff:ee,start:()=>pn(e.client)});f&&X(x)&&!g?(We(n),b=f,z?.active&&z.present(()=>{}),$=r,le=B.modal,Ie(),Le.report(r),O.active&&b.setSuspended(!0)):(f?.destroy(),o())}if(g||de)return;if(!b){if(oe=Be(!0,n.locale,h),g||de)return;We(n);let f=await M(q,re,ee).catch(me=>(ge(me,x),null));!X(x)&&!(ve&&!g&&!x.aborted)?f?.host?.destroy():f&&(b=f.host,b?.setSuspended(O.active))}}if(g||de)return;Ie();let k=n.instruction;if(k&&(k.type==="open_url"||k.type==="event")&&!Je.has(k.receiptId)){let U=w.createElement("button");U.type="button",U.style.cssText=te.primary,Ue(U,()=>te.focus),q.style.cssText=te.stage,U.textContent=k.type==="open_url"?`${G?"\u524D\u5F80":"Continue to"} ${new URL(k.url).host}`:G?"\u7EE7\u7EED":"Continue",U.onclick=()=>{let h=ke(),B=k.type==="open_url"&&!e.onOpenUrl&&k.openIn==="new_window"?nt(k.url):null;Ne(async()=>{let oe="success";if(k.type==="open_url")if(e.onOpenUrl)try{oe=await e.onOpenUrl({receiptId:k.receiptId,url:k.url,openIn:k.openIn})===!1?"failed":"opened"}catch(re){Pe(e.onError,re),oe="failed"}else oe=k.openIn==="new_window"&&!B?"failed":"opened";if(k.type==="event"){if(!e.onEvent)throw new m("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent(k.event)}if(g||e.client.view?.nodeId!==h.nodeId||e.client.view.visit!==h.visit)throw new m("PRECONDITION_FAILED","The client action visit changed");let x=await e.client.submit({operation:"submit",...h,input:{type:"client_action",receiptId:k.receiptId,outcome:oe}});return Je.add(k.receiptId),k.type==="open_url"&&!e.onOpenUrl&&k.openIn==="same_window"&&w.defaultView?.location.assign(k.url),x})},z?.active?z.present(()=>q.replaceChildren(U)):q.replaceChildren(U)}!n.pendingRequest&&n.status==="completed"&&!Je.has(`complete:${n.id}`)&&(Je.add(`complete:${n.id}`),Pe(e.onComplete,structuredClone(n))),He()}function nt(n){let r=w.defaultView?.open(n,"_blank")??null;return r&&(r.opener=null),r}function he(n){return Ie(),tn=tn.catch(()=>{}).then(async()=>{try{await et(n)}catch(r){throw z?.active&&(xe=ze(n),z.finish("error",r),be(),s.hidden=!0),r}}),tn}let tt=e.client.subscribe(n=>{if(!wn){if(n.stopped&&(le||L())&&!ve){P=n,ie();return}!ve&&(n.stopped||e.client.configurationReady===!1||Z&&$!==Z&&(Se(n)!==Z||["closed","ineligible","failed"].includes(n.status)))&&(be(),z?.finish("dismissed"),s.hidden=!0),he(n).catch(fe)}}),it=e.client.subscribeError?.(fe);function rt(){let n=e.client.view,r=n?.paywall;return!!r?.operation&&!!n&&["running","waiting"].includes(n.status)&&Tn(Ve({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect}))}function Ce(n){if(qe)return qe;if(g||!n&&(ce||Y))return Promise.resolve();let r=!n&&Qe();return!r&&e.client.view&&!["running","waiting"].includes(e.client.view.status)?(P=e.client.view,ie(),Promise.resolve()):(qe=Ne(async()=>{let p=r?await e.client.retry():await e.client.submit({operation:"close",...n??ke()});return n&&hn(p),p},!0).then(()=>{let p=e.client.view;p?.status==="closed"&&!Qe()&&(P=p,ie())}).finally(()=>{qe=null}),qe)}function ie(){ne?.destroy(),!g&&(g=!0,N(),o(),e.signal?.removeEventListener("abort",ie),d?.removeEventListener("abort",ie),z?.finish("dismissed"),yn.destroy(),tt(),it?.(),be(),an(),O.stop(),_.remove(),s.remove(),V(),Pe(e.onDismiss,P?structuredClone(P):null))}j.onclick=()=>{if(!j.disabled){if(O.active){O.exit();return}Ne(()=>e.client.submit({operation:"back",...ke()}))}},J.onclick=()=>{O.open()},A.onclick=()=>{z?.active?z.dismiss():ce||Ce()},F.onclick=()=>{Qe()?Ce():Ne(()=>e.client.retry())},_.addEventListener("cancel",n=>{n.preventDefault(),z?.active?z.dismiss():ce||Ce()}),e.signal?.addEventListener("abort",ie,{once:!0}),d?.addEventListener("abort",ie,{once:!0});let Ye=!1;y&&(N=y.onClose(()=>{g||de||(de=!0,z?.finish("dismissed"),be(),s.hidden=!0,e.client.view?Ce().finally(ie):Ye=!0)}));let Cn={destroy:ie,refresh:on,get recovery(){let n=rn();if(n)return n;if(!g&&!ue&&!ve&&!ce&&b){let r=b.recovery;if(r.type!=="native")return r}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??Y?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(ce)return ce;let n=rn();if(n)return Promise.resolve(n);let r=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??Y?.operationId??null,p=()=>({type:"recover",operationId:r,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let k=b?.recovery;return Promise.resolve(k&&k.type!=="native"&&k.type!=="cancel"?k:p())}let H=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(k=>k.operation==="close");if(g&&!(H||Y&&e.client.view?.status==="closed")||ue||$e||qe||O.active||!b&&!Y&&!H)return Promise.resolve(p());let ae=b,X=(async()=>{try{if(!Y&&H){let h=await e.client.retry();return await he(e.client.view??h.run),p()}if(!Y){let h=await ae.prepareFallback();if(h.type!=="native")return h;if(e.client.hasDurableJournal!==!0)return p();Y=h}let k=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(k.length){let h=k.find(oe=>oe.operation==="close");if(!h||!K||h.requestId!==K.requestId)return p();let B=await e.client.retry();hn(B),await he(e.client.view??B.run)}else{let h=e.client.view,B=h?.paywall;if(!h||!B||B.selectionGeneration===void 0||(B.quote?.operationId??null)!==Y.operationId||Y.operationId!==null&&B.canReselect!==!0)return p();let oe=B.selectionGeneration,x=await e.client.get();await he(e.client.view??x.run);let re=e.client.view,ee=re?.paywall;if(!re||!ee||!["running","waiting"].includes(re.status)||re.stopped||re.id!==h.id||re.nodeId!==h.nodeId||re.visit!==h.visit||ee.receiptId!==B.receiptId||ee.selectionGeneration!==oe||(ee.quote?.operationId??null)!==Y.operationId||Y.operationId!==null&&ee.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return p();let f=ke();K={runId:re.id,operationId:Y.operationId,revision:f.revision,requestId:f.requestId,nodeId:re.nodeId,visit:re.visit,receiptId:ee.receiptId,selectionGeneration:oe,acknowledged:!1},await Ce(f)}let U=rn();return U?(ie(),U):p()}catch(k){return fe(k),p()}})();ce=X;let ge=()=>{ce===X&&(ce=null)};return X.then(ge,ge),X},review:O.open,exitReview:O.exit,get unappliedDrafts(){return O.drafts}};try{let n=e.client.view;if(n)((e.client.viewAgeMs??fn)>=fn||n.instruction?.type==="evaluate_segment")&&(nn=on().finally(()=>{nn=null})),await he(n);else{if(s.hidden=!0,g)throw new DOMException("Presentation cancelled","AbortError");let r=Ye||e.prepared?.state==="shown"?null:Be(e.client.view?.screen?.presentation.type!=="inline",e.client.view?.locale);if(g||de&&!Ye)throw new DOMException("Presentation cancelled","AbortError");let p=e.client.get(),H=await(r?r.wait(p,Fe):lt(p,Fe));if(wn=!1,Ye)return g||await Ce().finally(ie),Cn;await he(e.client.view??H.run)}}catch(n){throw z?.finish("error",n),ie(),n}return Cn}function lt(t,v){let R;return Promise.race([t,new Promise((e,y)=>{R=setTimeout(()=>y(new Error("Presentation data timed out")),v)})]).finally(()=>clearTimeout(R))}function Bt(t,v,R){return at(t,v,R)}export{at as a,Bt as b};
@@ -1 +0,0 @@
1
- import{o as n,r as t}from"./chunk-4B4RB36N.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
@@ -1 +0,0 @@
1
- import{a as pe,b as ye}from"./chunk-24Z3THUR.js";import{d as fe,e as X}from"./chunk-W35FZWGG.js";import{a as de}from"./chunk-G6CWZBT5.js";import{a as P}from"./chunk-DSPLGTQI.js";var Ce=5*6e4,Ee=15e3,me=new WeakMap;function Ve(s){return me.get(s)}var C=s=>Array.isArray(s)?s.map(C):s&&typeof s=="object"?Object.fromEntries(Object.keys(s).sort().map(n=>[n,C(s[n])])):s,A=(s,n)=>JSON.stringify(C(s))===JSON.stringify(C(n)),we=s=>JSON.stringify(C([s.funnelId,s.locale??null,s.parameters??{}])),ke=["onObservationChange","onPurchase","onCheckoutUrl","resumeCheckout","allowNewPurchase","checkoutNavigation","terminateCheckout","confirmOnHostedCheckout","resolveOfferId","resolveSubscriptionChange","onOpenUrl","onEvent","onAction","onComplete","onError"];function Fe(s,n){let $=e=>structuredClone({funnelId:e.funnelId,locale:e.locale,parameters:e.parameters}),y,z="",Q=n.start instanceof Promise?void 0:$(n.start),N=e=>e?.parameters?.commerce,Y=Promise.resolve(n.start).then(e=>e?$(e):void 0),D=n.maxAgeMs??Ce,Z=new AbortController,f=AbortSignal.any([Z.signal,n.client.identitySignal,...n.signal?[n.signal]:[]]),M=()=>r("released","aborted"),t="preparing",ee,R,q=()=>{},_=0,b=null,m=null,g=null,p=null,h,x,ne=new Map,u=null,O=new Set,S=new Map,L,ae=new Promise(e=>L=e),T,ge=new Promise(e=>T=e);function V(e,a){t!==e&&(t=e,ee=a,P(n.onState,e))}function he(){f.removeEventListener("abort",M),F(),m?.destroy(),m=null,b?.remove(),b=null,g=null}function r(e,a){["adopted","unavailable","released","closed"].includes(t)||(V(e,a),he(),L(!1),T(null))}let j=e=>`error:${e?.code??e?.name??"unknown"}`,J=s.ownerDocument.defaultView,E=!0,te=null,I=!1,be=e=>e.storageArea===J?.localStorage&&(e.key===null||e.key.startsWith("indiana.funnel.purchases.")),re=e=>{be(e)&&H()},ve=n.client.subscribe(()=>H());function F(){E&&(E=!1,J?.removeEventListener("storage",re),ve(),q())}let U=()=>E&&(t==="ready"||t==="preparing");function G(e){(t==="ready"||t==="preparing")&&r("unavailable",e)}function H(){if(t==="ready"&&Date.now()-_>=D)return F();I=!0,te??=(async()=>{for(;I&&y&&U();){I=!1;try{await n.client.retained()==="pending"&&G("purchase_pending")}catch(e){f.aborted?r("released","aborted"):G(j(e))}}})().finally(()=>{te=null,I&&y&&U()&&H()})}J?.addEventListener("storage",re),f.addEventListener("abort",M,{once:!0});let oe=n.client.findPurchase();oe.catch(()=>{});async function W(e){let a=await se;if(!a)throw new Error("The first Paywall is unavailable");let l=JSON.stringify(C(e)),i=ne.get(l);return i||(i=n.client.readPaywall({paywallVersionId:p?.id??a.paywallVersionId,...a.paywallVersionId||p?{}:{paywallId:a.paywallId},...e}),ne.set(l,i)),i}function K(e){let a=Object.values(e.capabilities.plans);return!(Object.values(e.document.buttons).some(i=>i.type==="checkout")&&a.length===0)&&!a.some(i=>!i.available)}function le(e,a){if(p&&!X(e,p))return r("unavailable","paywall_changed"),!1;p=e,x=a;for(let l of S.keys())P(l,structuredClone(e));return!0}async function k(){let e=await ge;if(!e)throw new de("PURCHASE_PENDING","The purchase did not start; open it again");return e}let Pe={get view(){return u?u.view:p},get signal(){return u?.signal??n.client.identitySignal},get quote(){return u?.quote??null},get operation(){return u?.operation??null},webViewUrl:"bundled",get canReselect(){return u?.canReselect},get recovery(){return u?.recovery},get pendingCancellation(){return u?.pendingCancellation},subscribe(e){return S.set(e,u?.subscribe?.(e)??(()=>{})),()=>{S.get(e)?.(),S.delete(e)}},refresh:async()=>u?u.refresh():structuredClone(p),preview:async e=>(await k()).preview(e),confirm:async()=>(await k()).confirm(),cancel:async()=>(await k()).cancel(),read:async()=>(await k()).read(),destroy(){u?.destroy()}},d={options:{},handoff:{}},ie={loading:"host",focusAtReveal:!0,signal:n.client.identitySignal,start:async()=>Pe,canInteract:()=>d.options.canInteract?d.options.canInteract():!["unavailable","released","closed"].includes(t),async beforeAction(){let e=t!=="adopted",a=p?.capabilities,l=await k();if(e&&!A(l.view?.capabilities,a))throw new fe;await d.options.beforeAction?.()}};for(let e of ke)Object.defineProperty(ie,e,{enumerable:!0,get:()=>d.options[e]});function B(){t!=="preparing"||!g||!m||!y||!A(x?.commerce,N(y))||x?.locale!==y.locale||(V("ready"),L(!0))}let Se={present(e){if(d.handoff.present)return d.handoff.present(e);t==="preparing"&&(g=e,_=Date.now(),B())},async dismiss(){if(d.handoff.dismiss)return d.handoff.dismiss();r("closed");for(let e of[...O])P(e)},quoteError(e){d.handoff.quoteError?d.handoff.quoteError(e):P(d.options.onError,e)}};async function Ie(){if(n.paywallVersionId||n.paywallId)return{paywallVersionId:n.paywallVersionId,paywallId:n.paywallId};let e=n.configuration;if(!e)return r("unavailable","paywall_missing"),null;let a=await Promise.resolve(n.start).catch(()=>null);if(!a||t!=="preparing")return null;let l=()=>pe(e,{funnelId:a.funnelId,customerId:n.client.customerId,parameters:a.parameters??{}});if(R=await l(),t!=="preparing")return null;let i=R;if(i.type!=="paywall")return r("unavailable",ye(i)??"route"),null;let o=!1;return q=e.subscribe(()=>{o||!U()||(o=!0,l().then(c=>{!(c.type==="unavailable"&&!["funnel_stopped","route_unavailable"].includes(c.reason))&&(c.type!=="paywall"||c.paywallVersionId!==i.paywallVersionId)&&G("route_changed")}).finally(()=>o=!1))}),E||q(),{paywallVersionId:i.paywallVersionId}}let se=Ie();(async()=>{try{let[{showPaywall:e},a]=await Promise.all([import("./paywall-YZAEI7TF.js"),se]);if(f.throwIfAborted(),t!=="preparing"||!a)return;let l=n.commerce??N(Q),i=n.locale??Q?.locale;if(!l)return r("unavailable","commerce_missing");if(!i)return r("unavailable","locale_missing");let o=h??{commerce:l,locale:i},c=await W(o);if(f.throwIfAborted(),t!=="preparing"||(!K(c)&&n.start instanceof Promise&&!h&&await Y,h&&!A(o,h)&&(o=h,c=await W(o)),f.throwIfAborted(),t!=="preparing"))return;if(!K(c))return r("unavailable","plan_unavailable");if(!le(c,o))return;b=s.ownerDocument.createElement("div"),s.append(b);let v=setTimeout(()=>t==="preparing"&&r("unavailable","timeout"),Ee);ae.then(()=>clearTimeout(v));let w=await e(b,ie,Se);if(!w.host||f.aborted||t!=="preparing"){w.host?.destroy(),r(f.aborted?"released":"unavailable","error");return}m=w.host,B()}catch(e){r(f.aborted?"released":"unavailable",j(e))}})(),Y.then(async e=>{if(!e)return r("unavailable","gated");let a=e,l=N(a),i=n.commerce??l;if(!A(l&&{...l,intent:void 0},i&&{...i,intent:void 0})||n.locale!==void 0&&a.locale!==n.locale)return r("unavailable","start_mismatch");if(!l)return r("unavailable","commerce_missing");h={commerce:l,locale:a.locale};try{let o=await oe,c=o==="pending"?"purchase_pending":o==="found"?"original_purchase":o==="blocked"?"purchase_blocked":void 0;if(c)return r("unavailable",c);if(t!=="preparing")return;if(E&&(I=!1,await n.client.retained()==="pending"))return r("unavailable","purchase_pending");let v=await W(h);if(f.throwIfAborted(),t!=="preparing")return;if(p){if(!K(v))return r("unavailable","plan_unavailable");if(!le(v,h))return}}catch(o){return r(f.aborted?"released":"unavailable",j(o))}t==="preparing"&&(y=a,z=we(a),B(),I&&H())},()=>r("unavailable","gated"));let ce={get state(){return t},get reason(){return ee},ready:ae,get start(){return y},get prediction(){return R?structuredClone(R):void 0},matches:e=>!!y&&we(e)===z,open(){if(t==="preparing")return"pending";if(t!=="ready"||!g)return!1;if(Date.now()-_>=D)return r("unavailable","expired"),!1;let e=g;return g=null,F(),V("shown"),e(),"shown"},destroy(){Z.abort()}};return me.set(ce,{onClose(e){return t==="closed"?(P(e),()=>{}):(O.add(e),()=>{O.delete(e)})},claim(){F()},async adopt(e,a){let l=e.paywall?.resolution,i=e.paywall&&!e.paywall.quote&&!e.paywall.operation&&!e.paywall.purchaseRequestId&&!(e.paywall.selectionGeneration??0);if(t!=="shown"||!m||!p||!l||!i||e.source.id!==y?.funnelId||e.locale!==y?.locale||!A(e.parameters??{},y?.parameters??{})||!["running","waiting"].includes(e.status)||!X(l,p))return null;let o;try{o=await a.start()}catch{return null}if(t!=="shown"||!m)return o.destroy(),null;u=o,d.options=a.options,d.handoff=a.handoff;for(let[w]of S)S.set(w,o.subscribe?.(w)??(()=>{})),o.view&&P(w,structuredClone(o.view));f.removeEventListener("abort",M),V("adopted"),T(o),O.clear();let c=m,v=b;return m=null,b=null,g=null,new Proxy(c,{get(w,ue){return ue==="destroy"?()=>{w.destroy(),v?.remove()}:Reflect.get(w,ue,w)}})},get modal(){return p?.document.presentation.type!=="inline"},get revealable(){return t==="ready"&&!!g&&Date.now()-_<D},release(){r("released")}}),ce}export{Ce as a,Ve as b,Fe as c};