@tinkerlandai/longplay-sdk 0.10.54 → 0.10.55

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 (104) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +1 -0
  3. package/README.zh-CN.md +2 -0
  4. package/dist/check-response-SGAJJZM3.js +1 -0
  5. package/dist/{chunk-JXWZS4UM.js → chunk-3BZTDD2U.js} +1 -1
  6. package/dist/{chunk-73UFNVEP.js → chunk-3HT7SVBF.js} +1 -1
  7. package/dist/{chunk-36VNAOG6.js → chunk-3NWMQ33E.js} +1 -1
  8. package/dist/{chunk-SK5JZ7HA.js → chunk-3QWERHSB.js} +2 -2
  9. package/dist/{chunk-6HKQILBV.js → chunk-4AXCP6YL.js} +1 -1
  10. package/dist/{chunk-YMRWDMIL.js → chunk-5NVSHZHH.js} +1 -1
  11. package/dist/{chunk-RJT764B2.js → chunk-5ONJ4ZQH.js} +1 -1
  12. package/dist/{chunk-NL7AXMUA.js → chunk-5ZTKQAJV.js} +1 -1
  13. package/dist/{chunk-ZQY7OYHM.js → chunk-6P3WCGPY.js} +1 -1
  14. package/dist/{chunk-M4P6TGBU.js → chunk-7IHAPLCS.js} +1 -1
  15. package/dist/{chunk-PB34FLPJ.js → chunk-7L6F7FSH.js} +1 -1
  16. package/dist/{chunk-LFMAFY3P.js → chunk-7MXSO2FW.js} +1 -1
  17. package/dist/{chunk-PPXVRQAG.js → chunk-AZKU5JQD.js} +1 -1
  18. package/dist/{chunk-MZRDAMFQ.js → chunk-DN4OYE4E.js} +1 -1
  19. package/dist/{chunk-OZK47BUU.js → chunk-DNQLSWIX.js} +1 -1
  20. package/dist/chunk-ESQVXEKB.js +10 -0
  21. package/dist/{chunk-ANJPFGFN.js → chunk-ET6CBBLH.js} +1 -1
  22. package/dist/chunk-GLIZTWEO.js +1 -0
  23. package/dist/{chunk-RRZZUIFM.js → chunk-GP7T4WEY.js} +1 -1
  24. package/dist/{chunk-CAE4KIZN.js → chunk-GTMK4JF3.js} +1 -1
  25. package/dist/{chunk-DXLBEXC6.js → chunk-HI6Y7XJ2.js} +1 -1
  26. package/dist/{chunk-LOBZ45T3.js → chunk-HXDNGCPJ.js} +1 -1
  27. package/dist/{chunk-L64BS65O.js → chunk-IVWTAVT3.js} +1 -1
  28. package/dist/{chunk-NNJVMJUG.js → chunk-IZTD33WJ.js} +1 -1
  29. package/dist/{chunk-IN32NWRI.js → chunk-J4GRBKUH.js} +1 -1
  30. package/dist/{chunk-HMJTABQ5.js → chunk-JDGH5QJP.js} +2 -2
  31. package/dist/chunk-JO27764K.js +1 -0
  32. package/dist/{chunk-R2L227PQ.js → chunk-JPPEUS4P.js} +1 -1
  33. package/dist/{chunk-JCI5PGY3.js → chunk-KDHWO4RP.js} +1 -1
  34. package/dist/{chunk-XHZH3E4G.js → chunk-KJTRF35F.js} +1 -1
  35. package/dist/{chunk-66TY4EFN.js → chunk-LKZELSFX.js} +1 -1
  36. package/dist/chunk-LNWK2TH6.js +1 -0
  37. package/dist/{chunk-LBDLWHBY.js → chunk-M774BXNR.js} +1 -1
  38. package/dist/{chunk-TS26DZNO.js → chunk-MEOMDJZI.js} +1 -1
  39. package/dist/{chunk-PVMGYRGE.js → chunk-MKMYNK4K.js} +1 -1
  40. package/dist/{chunk-BKBWGPNR.js → chunk-MSM3WAM5.js} +1 -1
  41. package/dist/{chunk-JJIP6BZL.js → chunk-OO2GQESM.js} +1 -1
  42. package/dist/{chunk-ADTZEBQF.js → chunk-QK2Y2ZEZ.js} +1 -1
  43. package/dist/{chunk-OV46DXRX.js → chunk-QYEQNDQD.js} +1 -1
  44. package/dist/{chunk-C4NXQMSO.js → chunk-RG2JNNXL.js} +1 -1
  45. package/dist/{chunk-EACC667P.js → chunk-RSG74B3M.js} +1 -1
  46. package/dist/{chunk-GGZG56GR.js → chunk-RSO5KO7S.js} +1 -1
  47. package/dist/{chunk-QGKROSRD.js → chunk-RVBX3X7P.js} +1 -1
  48. package/dist/{chunk-WE55LJEN.js → chunk-TZ4IC4US.js} +1 -1
  49. package/dist/chunk-UCYTLZPQ.js +1 -0
  50. package/dist/{chunk-J4RM5GQP.js → chunk-UHPMOLMW.js} +1 -1
  51. package/dist/{chunk-R4BYUK7S.js → chunk-VBX3OPEE.js} +1 -1
  52. package/dist/{chunk-BX2MSRA4.js → chunk-VKY4K4KH.js} +1 -1
  53. package/dist/chunk-XHKGJGCZ.js +1 -0
  54. package/dist/{chunk-CJUODAOF.js → chunk-XRNBVBAA.js} +1 -1
  55. package/dist/{content-A4SPKH7N.js → content-PZUD5TVQ.js} +1 -1
  56. package/dist/funnel-host-purchase-Q6P2YDVI.js +1 -0
  57. package/dist/funnel-host-recovery-paywall-5EQRYS7M.js +1 -0
  58. package/dist/funnel-paywall-prerender-T4BYKZCR.js +1 -0
  59. package/dist/funnel-route-prediction-GIG2G525.js +1 -0
  60. package/dist/funnel-route-source-HXE7AGDB.js +1 -0
  61. package/dist/funnel-runtime-host-UFKTZW2N.js +1 -0
  62. package/dist/index.d.ts +5 -3
  63. package/dist/index.js +1 -1
  64. package/dist/merchant-bridge-contracts-A3HCEH4C.js +1 -0
  65. package/dist/native-shell.js +1 -1
  66. package/dist/openrouter.js +1 -1
  67. package/dist/operation-contracts-5YSN3IKV.js +1 -0
  68. package/dist/page.js +1 -1
  69. package/dist/paywall-XR5QXRMH.js +1 -0
  70. package/dist/paywall-content-UASETG4Y.js +1 -0
  71. package/dist/paywall-session-FH7UX2GO.js +1 -0
  72. package/dist/popup.d.ts +2 -2
  73. package/dist/popup.js +1 -1
  74. package/dist/{presentation-loading-sMyRJ21g.d.ts → presentation-loading-CjljfuJq.d.ts} +1 -0
  75. package/dist/react-native.js +1 -1
  76. package/dist/screen-renderer-4OBUAKRB.js +1 -0
  77. package/dist/server.js +1 -1
  78. package/dist/{visual-dom-MH3JDJHJ.js → visual-dom-EG5K4MQZ.js} +1 -1
  79. package/dist/visual.js +1 -1
  80. package/package.json +1 -1
  81. package/dist/check-response-MJHH5FWT.js +0 -1
  82. package/dist/chunk-MRL7XUBV.js +0 -1
  83. package/dist/chunk-OJDO7546.js +0 -1
  84. package/dist/chunk-QAGK2SLZ.js +0 -1
  85. package/dist/chunk-S2MSRPR2.js +0 -1
  86. package/dist/chunk-UEKKQHUZ.js +0 -10
  87. package/dist/chunk-ZEU56NVY.js +0 -1
  88. package/dist/funnel-host-purchase-V2TIWGCQ.js +0 -1
  89. package/dist/funnel-host-recovery-paywall-DWKTPDLY.js +0 -1
  90. package/dist/funnel-paywall-prerender-DD7LQXDJ.js +0 -1
  91. package/dist/funnel-route-prediction-ICGW4DPX.js +0 -1
  92. package/dist/funnel-route-source-64LTJZXN.js +0 -1
  93. package/dist/funnel-runtime-host-JG3OAYZ6.js +0 -1
  94. package/dist/merchant-bridge-contracts-DEDEIYNU.js +0 -1
  95. package/dist/operation-contracts-RHJJI5NO.js +0 -1
  96. package/dist/paywall-NM4HMYMK.js +0 -1
  97. package/dist/paywall-content-T2FGNRBR.js +0 -1
  98. package/dist/paywall-session-BAUWSWWR.js +0 -1
  99. package/dist/screen-renderer-CMFJVI36.js +0 -1
  100. /package/dist/{chunk-SK5JZ7HA.js.LEGAL.txt → chunk-3QWERHSB.js.LEGAL.txt} +0 -0
  101. /package/dist/{chunk-5YBTU4KS.js → chunk-ADCYMD2M.js} +0 -0
  102. /package/dist/{chunk-VJIONC4S.js → chunk-AZKM26EX.js} +0 -0
  103. /package/dist/{chunk-HMJTABQ5.js.LEGAL.txt → chunk-JDGH5QJP.js.LEGAL.txt} +0 -0
  104. /package/dist/{chunk-DLRCJF6U.js → chunk-NCKIG4QS.js} +0 -0
@@ -1 +1 @@
1
- import"./chunk-IN32NWRI.js";import"./chunk-ANJPFGFN.js";import"./chunk-TS26DZNO.js";import"./chunk-L64BS65O.js";import{a as i}from"./chunk-WE55LJEN.js";import"./chunk-OZK47BUU.js";import"./chunk-LBDLWHBY.js";import{b as A}from"./chunk-5YBTU4KS.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-J4GRBKUH.js";import"./chunk-ET6CBBLH.js";import"./chunk-MEOMDJZI.js";import"./chunk-IVWTAVT3.js";import{a as i}from"./chunk-TZ4IC4US.js";import"./chunk-DNQLSWIX.js";import"./chunk-M774BXNR.js";import{b as A}from"./chunk-ADCYMD2M.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-3BZTDD2U.js";import"./chunk-5NVSHZHH.js";import"./chunk-XRNBVBAA.js";import"./chunk-4AXCP6YL.js";import"./chunk-RSG74B3M.js";import"./chunk-VKY4K4KH.js";import"./chunk-UHPMOLMW.js";import"./chunk-7IHAPLCS.js";import"./chunk-RSO5KO7S.js";import"./chunk-5ZTKQAJV.js";import"./chunk-VILB5M4X.js";import"./chunk-ET6CBBLH.js";import"./chunk-IVWTAVT3.js";import"./chunk-RVBX3X7P.js";import"./chunk-GP7T4WEY.js";import"./chunk-5ONJ4ZQH.js";import"./chunk-MSM3WAM5.js";import"./chunk-IZTD33WJ.js";import"./chunk-DNQLSWIX.js";import"./chunk-ADCYMD2M.js";import"./chunk-JDGH5QJP.js";import"./chunk-NCKIG4QS.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-SK5JZ7HA.js";import"./chunk-R2L227PQ.js";import"./chunk-3VUPVXAV.js";import"./chunk-LBDLWHBY.js";import"./chunk-DSPLGTQI.js";import"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.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-3QWERHSB.js";import"./chunk-JPPEUS4P.js";import"./chunk-3VUPVXAV.js";import"./chunk-M774BXNR.js";import"./chunk-DSPLGTQI.js";import"./chunk-JDGH5QJP.js";import"./chunk-NCKIG4QS.js";import"./chunk-WOT6VMZA.js";export{f as createPageExperiments,o as mergeQueryStrings,r as pageAttributes,e as readPayload};
@@ -0,0 +1 @@
1
+ import{a}from"./chunk-JO27764K.js";import"./chunk-HI6Y7XJ2.js";import"./chunk-W32FI2A2.js";import"./chunk-LNWK2TH6.js";import"./chunk-QK2Y2ZEZ.js";import"./chunk-QYEQNDQD.js";import"./chunk-7IHAPLCS.js";import"./chunk-RSO5KO7S.js";import"./chunk-5ZTKQAJV.js";import"./chunk-VILB5M4X.js";import"./chunk-MEOMDJZI.js";import"./chunk-IVWTAVT3.js";import"./chunk-RVBX3X7P.js";import"./chunk-GP7T4WEY.js";import"./chunk-5ONJ4ZQH.js";import"./chunk-MSM3WAM5.js";import"./chunk-IZTD33WJ.js";import"./chunk-TZ4IC4US.js";import"./chunk-DNQLSWIX.js";import"./chunk-M774BXNR.js";import"./chunk-ADCYMD2M.js";import"./chunk-DSPLGTQI.js";import"./chunk-JDGH5QJP.js";import"./chunk-NCKIG4QS.js";import"./chunk-WOT6VMZA.js";export{a as showPaywall};
@@ -0,0 +1 @@
1
+ import{b as a}from"./chunk-7MXSO2FW.js";import"./chunk-4AXCP6YL.js";import"./chunk-RSG74B3M.js";import"./chunk-VKY4K4KH.js";import"./chunk-UHPMOLMW.js";import"./chunk-7IHAPLCS.js";import"./chunk-RSO5KO7S.js";import"./chunk-5ZTKQAJV.js";import"./chunk-VILB5M4X.js";import"./chunk-MEOMDJZI.js";import"./chunk-IVWTAVT3.js";import"./chunk-RVBX3X7P.js";import"./chunk-GP7T4WEY.js";import"./chunk-5ONJ4ZQH.js";import"./chunk-MSM3WAM5.js";import"./chunk-IZTD33WJ.js";import"./chunk-TZ4IC4US.js";import"./chunk-DNQLSWIX.js";import"./chunk-3VUPVXAV.js";import"./chunk-M774BXNR.js";import"./chunk-ADCYMD2M.js";import"./chunk-JDGH5QJP.js";import"./chunk-NCKIG4QS.js";import"./chunk-WOT6VMZA.js";export{a as readPaywallContent};
@@ -0,0 +1 @@
1
+ import{a}from"./chunk-6P3WCGPY.js";import"./chunk-3BZTDD2U.js";import"./chunk-5NVSHZHH.js";import"./chunk-GTMK4JF3.js";import"./chunk-XRNBVBAA.js";import"./chunk-KJTRF35F.js";import"./chunk-7MXSO2FW.js";import"./chunk-4AXCP6YL.js";import"./chunk-RSG74B3M.js";import"./chunk-VKY4K4KH.js";import"./chunk-UHPMOLMW.js";import"./chunk-QK2Y2ZEZ.js";import"./chunk-QYEQNDQD.js";import"./chunk-7IHAPLCS.js";import"./chunk-RSO5KO7S.js";import"./chunk-5ZTKQAJV.js";import"./chunk-VILB5M4X.js";import"./chunk-ET6CBBLH.js";import"./chunk-MEOMDJZI.js";import"./chunk-IVWTAVT3.js";import"./chunk-RVBX3X7P.js";import"./chunk-GP7T4WEY.js";import"./chunk-5ONJ4ZQH.js";import"./chunk-MSM3WAM5.js";import"./chunk-IZTD33WJ.js";import"./chunk-TZ4IC4US.js";import"./chunk-DNQLSWIX.js";import"./chunk-3VUPVXAV.js";import"./chunk-M774BXNR.js";import"./chunk-ADCYMD2M.js";import"./chunk-DSPLGTQI.js";import"./chunk-JDGH5QJP.js";import"./chunk-NCKIG4QS.js";import"./chunk-WOT6VMZA.js";export{a as createPaywallSession};
package/dist/popup.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { e as CustomerPageData, a as SurfaceData, P as PresentationLoadingOptions, L as LoadingLayout, f as ScreenParameters, g as ScreenRendererInput, S as ScreenAnswers, C as CustomerDataIntent } from './presentation-loading-sMyRJ21g.js';
2
- export { d as PresentationState } from './presentation-loading-sMyRJ21g.js';
1
+ import { e as CustomerPageData, a as SurfaceData, P as PresentationLoadingOptions, L as LoadingLayout, f as ScreenParameters, g as ScreenRendererInput, S as ScreenAnswers, C as CustomerDataIntent } from './presentation-loading-CjljfuJq.js';
2
+ export { d as PresentationState } from './presentation-loading-CjljfuJq.js';
3
3
  import { b as ScreenAction, c as ScreenNode, d as ScreenInteractivity, e as ScreenDocument } from './screen-D2bUmJ4M.js';
4
4
  import { O as Offer, a as OfferUnavailableReason } from './coupon-kfkIVf9n.js';
5
5
  import { WindowLike } from 'dompurify';
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-UEKKQHUZ.js";import"./chunk-QAGK2SLZ.js";import"./chunk-QGKROSRD.js";import"./chunk-RRZZUIFM.js";import"./chunk-RJT764B2.js";import"./chunk-BKBWGPNR.js";import"./chunk-NNJVMJUG.js";import"./chunk-WE55LJEN.js";import"./chunk-OZK47BUU.js";import"./chunk-5YBTU4KS.js";import"./chunk-DSPLGTQI.js";import"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.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-ESQVXEKB.js";import"./chunk-LNWK2TH6.js";import"./chunk-RVBX3X7P.js";import"./chunk-GP7T4WEY.js";import"./chunk-5ONJ4ZQH.js";import"./chunk-MSM3WAM5.js";import"./chunk-IZTD33WJ.js";import"./chunk-TZ4IC4US.js";import"./chunk-DNQLSWIX.js";import"./chunk-ADCYMD2M.js";import"./chunk-DSPLGTQI.js";import"./chunk-JDGH5QJP.js";import"./chunk-NCKIG4QS.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};
@@ -1019,6 +1019,7 @@ type LoadingLayout = {
1019
1019
 
1020
1020
  type RetainedPurchaseDialog = {
1021
1021
  dialog: HTMLDialogElement;
1022
+ content?: HTMLElement;
1022
1023
  release(): void;
1023
1024
  };
1024
1025
 
@@ -1 +1 @@
1
- import{b as S,c as E,d as T}from"./chunk-PPXVRQAG.js";import"./chunk-PVMGYRGE.js";import{a as A}from"./chunk-ZQY7OYHM.js";import{e as P}from"./chunk-JXWZS4UM.js";import"./chunk-YMRWDMIL.js";import{h as b,i as x,k as L}from"./chunk-PB34FLPJ.js";import{E as C}from"./chunk-MZRDAMFQ.js";import"./chunk-73UFNVEP.js";import"./chunk-CAE4KIZN.js";import"./chunk-CJUODAOF.js";import"./chunk-XHZH3E4G.js";import"./chunk-LFMAFY3P.js";import"./chunk-6HKQILBV.js";import"./chunk-EACC667P.js";import"./chunk-BX2MSRA4.js";import"./chunk-LOBZ45T3.js";import"./chunk-J4RM5GQP.js";import"./chunk-ADTZEBQF.js";import"./chunk-OV46DXRX.js";import"./chunk-M4P6TGBU.js";import"./chunk-GGZG56GR.js";import"./chunk-NL7AXMUA.js";import"./chunk-VILB5M4X.js";import"./chunk-ANJPFGFN.js";import"./chunk-TS26DZNO.js";import"./chunk-L64BS65O.js";import"./chunk-QGKROSRD.js";import"./chunk-RRZZUIFM.js";import"./chunk-RJT764B2.js";import"./chunk-BKBWGPNR.js";import"./chunk-NNJVMJUG.js";import{a as r}from"./chunk-WE55LJEN.js";import{h as R}from"./chunk-OZK47BUU.js";import"./chunk-3VUPVXAV.js";import"./chunk-LBDLWHBY.js";import"./chunk-5YBTU4KS.js";import"./chunk-DSPLGTQI.js";import"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.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-AZKU5JQD.js";import"./chunk-MKMYNK4K.js";import{a as A}from"./chunk-6P3WCGPY.js";import{e as P}from"./chunk-3BZTDD2U.js";import"./chunk-5NVSHZHH.js";import{h as b,i as x,k as L}from"./chunk-7L6F7FSH.js";import{E as C}from"./chunk-DN4OYE4E.js";import"./chunk-3HT7SVBF.js";import"./chunk-GTMK4JF3.js";import"./chunk-XRNBVBAA.js";import"./chunk-KJTRF35F.js";import"./chunk-7MXSO2FW.js";import"./chunk-4AXCP6YL.js";import"./chunk-RSG74B3M.js";import"./chunk-VKY4K4KH.js";import"./chunk-HXDNGCPJ.js";import"./chunk-UHPMOLMW.js";import"./chunk-QK2Y2ZEZ.js";import"./chunk-QYEQNDQD.js";import"./chunk-7IHAPLCS.js";import"./chunk-RSO5KO7S.js";import"./chunk-5ZTKQAJV.js";import"./chunk-VILB5M4X.js";import"./chunk-ET6CBBLH.js";import"./chunk-MEOMDJZI.js";import"./chunk-IVWTAVT3.js";import"./chunk-RVBX3X7P.js";import"./chunk-GP7T4WEY.js";import"./chunk-5ONJ4ZQH.js";import"./chunk-MSM3WAM5.js";import"./chunk-IZTD33WJ.js";import{a as r}from"./chunk-TZ4IC4US.js";import{h as R}from"./chunk-DNQLSWIX.js";import"./chunk-3VUPVXAV.js";import"./chunk-M774BXNR.js";import"./chunk-ADCYMD2M.js";import"./chunk-DSPLGTQI.js";import"./chunk-JDGH5QJP.js";import"./chunk-NCKIG4QS.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-ESQVXEKB.js";import"./chunk-LNWK2TH6.js";import"./chunk-RVBX3X7P.js";import"./chunk-GP7T4WEY.js";import"./chunk-5ONJ4ZQH.js";import"./chunk-MSM3WAM5.js";import"./chunk-IZTD33WJ.js";import"./chunk-TZ4IC4US.js";import"./chunk-DNQLSWIX.js";import"./chunk-ADCYMD2M.js";import"./chunk-DSPLGTQI.js";import"./chunk-JDGH5QJP.js";import"./chunk-NCKIG4QS.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-MRL7XUBV.js";import{a as I}from"./chunk-36VNAOG6.js";import{a as fn,b as hn,c as gn,d as yn}from"./chunk-IN32NWRI.js";import{a as xt}from"./chunk-ZQY7OYHM.js";import{a as Ue,b as Ve,c as qe,d as He,e as m}from"./chunk-JXWZS4UM.js";import"./chunk-YMRWDMIL.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-PB34FLPJ.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-MZRDAMFQ.js";import"./chunk-73UFNVEP.js";import{c as h}from"./chunk-CAE4KIZN.js";import"./chunk-CJUODAOF.js";import{a as Et,b as _e}from"./chunk-XHZH3E4G.js";import"./chunk-LFMAFY3P.js";import"./chunk-6HKQILBV.js";import{e as at}from"./chunk-EACC667P.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-BX2MSRA4.js";import{b as Oe}from"./chunk-LOBZ45T3.js";import{e as ve,i as Ze,l as it}from"./chunk-J4RM5GQP.js";import"./chunk-ADTZEBQF.js";import"./chunk-OV46DXRX.js";import"./chunk-M4P6TGBU.js";import"./chunk-GGZG56GR.js";import{A as W,B as oe,C as tt,D as Se,E as ie,G as se,H as Ce,M as j,O as ce,P as nt,R as Ee,S as rt,T as ot,f as Ge,g as je,j as we,r as ze,s as Ke,u as an,v as sn,y as cn,z as X}from"./chunk-NL7AXMUA.js";import"./chunk-VILB5M4X.js";import"./chunk-ANJPFGFN.js";import"./chunk-TS26DZNO.js";import{a as Ne,b as Le}from"./chunk-L64BS65O.js";import{o as ue}from"./chunk-QGKROSRD.js";import"./chunk-RRZZUIFM.js";import{i as un,k as $e,l as Qe,m as Je}from"./chunk-RJT764B2.js";import{c as Ie}from"./chunk-BKBWGPNR.js";import{e as Xe,h as We}from"./chunk-NNJVMJUG.js";import{a as c}from"./chunk-WE55LJEN.js";import{h as Y}from"./chunk-OZK47BUU.js";import"./chunk-3VUPVXAV.js";import"./chunk-LBDLWHBY.js";import{b as u}from"./chunk-5YBTU4KS.js";import"./chunk-DSPLGTQI.js";import{a as Ye}from"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.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-XHKGJGCZ.js";import{a as I}from"./chunk-3NWMQ33E.js";import{a as fn,b as hn,c as gn,d as yn}from"./chunk-J4GRBKUH.js";import{a as xt}from"./chunk-6P3WCGPY.js";import{a as Ue,b as Ve,c as qe,d as He,e as m}from"./chunk-3BZTDD2U.js";import"./chunk-5NVSHZHH.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-7L6F7FSH.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-DN4OYE4E.js";import"./chunk-3HT7SVBF.js";import{c as h}from"./chunk-GTMK4JF3.js";import"./chunk-XRNBVBAA.js";import{a as Et,b as _e}from"./chunk-KJTRF35F.js";import"./chunk-7MXSO2FW.js";import"./chunk-4AXCP6YL.js";import{e as at}from"./chunk-RSG74B3M.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-VKY4K4KH.js";import{b as Oe}from"./chunk-HXDNGCPJ.js";import{e as ve,i as Ze,l as it}from"./chunk-UHPMOLMW.js";import"./chunk-QK2Y2ZEZ.js";import"./chunk-QYEQNDQD.js";import"./chunk-7IHAPLCS.js";import"./chunk-RSO5KO7S.js";import{A as W,B as oe,C as tt,D as Se,E as ie,G as se,H as Ce,M as j,O as ce,P as nt,R as Ee,S as rt,T as ot,f as Ge,g as je,j as we,r as ze,s as Ke,u as an,v as sn,y as cn,z as X}from"./chunk-5ZTKQAJV.js";import"./chunk-VILB5M4X.js";import"./chunk-ET6CBBLH.js";import"./chunk-MEOMDJZI.js";import{a as Ne,b as Le}from"./chunk-IVWTAVT3.js";import{o as ue}from"./chunk-RVBX3X7P.js";import"./chunk-GP7T4WEY.js";import{i as un,k as $e,l as Qe,m as Je}from"./chunk-5ONJ4ZQH.js";import{c as Ie}from"./chunk-MSM3WAM5.js";import{e as Xe,h as We}from"./chunk-IZTD33WJ.js";import{a as c}from"./chunk-TZ4IC4US.js";import{h as Y}from"./chunk-DNQLSWIX.js";import"./chunk-3VUPVXAV.js";import"./chunk-M774BXNR.js";import{b as u}from"./chunk-ADCYMD2M.js";import"./chunk-DSPLGTQI.js";import{a as Ye}from"./chunk-JDGH5QJP.js";import"./chunk-NCKIG4QS.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-VJIONC4S.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-AZKM26EX.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-VJIONC4S.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-SK5JZ7HA.js";import{a as re,b as ae,c as se,d as oe}from"./chunk-R2L227PQ.js";import"./chunk-3VUPVXAV.js";import"./chunk-LBDLWHBY.js";import{b as o}from"./chunk-5YBTU4KS.js";import"./chunk-DSPLGTQI.js";import{c as te,e as ie,g as M}from"./chunk-HMJTABQ5.js";import"./chunk-DLRCJF6U.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-AZKM26EX.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-3QWERHSB.js";import{a as re,b as ae,c as se,d as oe}from"./chunk-JPPEUS4P.js";import"./chunk-3VUPVXAV.js";import"./chunk-M774BXNR.js";import{b as o}from"./chunk-ADCYMD2M.js";import"./chunk-DSPLGTQI.js";import{c as te,e as ie,g as M}from"./chunk-JDGH5QJP.js";import"./chunk-NCKIG4QS.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.54",
3
+ "version": "0.10.55",
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-XHZH3E4G.js";import"./chunk-RJT764B2.js";import"./chunk-BKBWGPNR.js";import"./chunk-WE55LJEN.js";import"./chunk-OZK47BUU.js";import"./chunk-5YBTU4KS.js";import"./chunk-DLRCJF6U.js";import"./chunk-WOT6VMZA.js";export{a as validateEntitlementCheck,b as validateResourceCheck};
@@ -1 +0,0 @@
1
- import{o as n,r as t}from"./chunk-MZRDAMFQ.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
@@ -1 +0,0 @@
1
- import{a as fn,c as pn,d as xt,f as At,g as mn,k as hn}from"./chunk-DXLBEXC6.js";import{b as et}from"./chunk-W32FI2A2.js";import{d as on,e as sn,f as ln,h as It,i as tt,j as cn,k as un,l as dn}from"./chunk-QAGK2SLZ.js";import{a as tn,c as Pt,d as nn,e as rn}from"./chunk-ADTZEBQF.js";import{a as Ze,b as ne,d as kt,f as Et,j as an}from"./chunk-OV46DXRX.js";import{b as ve}from"./chunk-M4P6TGBU.js";import{B as N,C as Xe,D as je,E as Oe,y as en}from"./chunk-GGZG56GR.js";import{r as Te,t as Ne}from"./chunk-QGKROSRD.js";import{i as Zt}from"./chunk-RRZZUIFM.js";import{c as he,j as Be}from"./chunk-RJT764B2.js";import{c as vt}from"./chunk-BKBWGPNR.js";import{a as k}from"./chunk-WE55LJEN.js";import{a as q}from"./chunk-DSPLGTQI.js";async function yn(V,i,E){if(!je(i))throw new k("INVALID_RESPONSE","A verified completed purchase is required");let O=V?Be.parse(V):null;if(await E.onComplete?.(i),!O||!E.check)return;let B=Be.parse(await E.check());if(B.internal_feature_id!==O.internal_feature_id||B.quantity!==O.quantity||O.observation!==void 0&&(B.observation===void 0||B.observation.requirementDigest!==O.observation.requirementDigest||B.observation.authority!==O.observation.authority||vt(B.observation.subject)!==vt(O.observation.subject)))throw new k("INVALID_RESPONSE","The access requirement changed");B.allowed&&await E.onAccessGranted?.(B)}function wn(V){return Object.entries(V.document.buttons).filter(([,i])=>i.type==="checkout"&&i.product.type==="fixed"&&!ve(i.product,{},V.capabilities)).map(([i])=>i)}function gn(V,i){let E=N(i)?void 0:i.lines[0];if(!N(i)&&(i.lines.length!==1||!E))return;let O=N(i)?i.productVersionId:E.productVersionId,{screen:B,buttons:re}=V.document,D=new Map(N(i)?Object.entries(i.featureQuantities??{}):(E?.prepaid??[]).map(g=>[g.internal_feature_id,g.quantity]));function ie(g,c){if(g.hidden)return!1;if(g.type==="plan_picker"&&V.capabilities.pickers[g.id]?.options.includes(O))return c[g.id]=O,!0;if(g.type==="quantity_picker"){let ee=D.get(g.internalFeatureId);return ee!==void 0&&(!g.bind?.plan||g.bind.plan===O)&&(c[g.id]=ee),!1}if(g.type==="button"&&g.action){let ee=re[g.action];return ee?.type==="checkout"&&ee.product.type==="fixed"&&ee.product.productVersionId===O}if(g.type!=="stack")return!1;let Z=g.interaction,a=g.bind?.plan===O;for(let[ee,p]of g.children.entries()){let ae={},U=ie(p,ae);if(Z?.type==="toggle"||Z?.type==="tabs"){if(!U)continue;return c[g.id]=Z.type==="toggle"?ee===0:p.id,Object.assign(c,ae),!0}Object.assign(c,ae),U&&(a=!0,Z?.type==="select"&&Z.purpose==="product"&&Z.pickerId&&p.type==="stack"&&p.bind?.plan===O&&(c[g.id]=p.id,c[Z.pickerId]=O))}return a}for(let g of B.pages){let c={__page:g.id};if(ie(g.root,c))return c}}async function ir(V,i,E){let O=i.focusAtReveal?()=>{}:It(V.ownerDocument),B=()=>{D.finish("dismissed"),O()},re=()=>B(),D=cn(V,i,"paywall",()=>{B(),q(i.onDismiss)},fn);i.signal?.throwIfAborted(),i.signal?.addEventListener("abort",re,{once:!0});let ie=null,g,c,Z;try{if(D.start(!0,i.loadingDocument?.screen.strings.defaultLocale,i.loadingDocument??null),D.cancelled)throw new DOMException("Presentation cancelled","AbortError");if(ie=i.check?Be.parse(await D.wait(i.check(),tt)):null,ie?.allowed)return D.finish("skipped"),i.signal?.removeEventListener("abort",re),O(),await i.onAccessGranted?.(ie),{check:ie,host:null};let[e,t]=await Promise.allSettled([D.wait(import("./screen-renderer-CMFJVI36.js")),D.wait(i.start().then(r=>(D.cancelled&&r.destroy(),r)),tt)]);if(e.status==="rejected")throw t.status==="fulfilled"&&t.value.destroy(),e.reason;if(t.status==="rejected")throw t.reason;Z=e.value,g=t.value,i.signal?.throwIfAborted(),g.signal?.throwIfAborted(),g.signal?.addEventListener("abort",re,{once:!0});let n=g.view??await D.wait(g.refresh(),tt);if(!n)throw new k("INVALID_RESPONSE","Paywall presentation is missing");g.signal?.throwIfAborted(),c=n}catch(e){throw D.finish("error",e),E?.retainedDialog?.release(),i.signal?.removeEventListener("abort",re),g?.signal?.removeEventListener("abort",re),g?.destroy(),O(),e}let a=g,{mountScreenPreview:ee}=Z,p=V.ownerDocument,ae=new AbortController,U=p.createElement("section"),de=p.createElement("div"),te=p.createElement("div"),nt=i.mountControls,J=nt?p.createElement("div"):void 0,d=p.createElement("p"),w=p.createElement("button"),oe=p.createElement("button"),T=p.createElement("button"),Pe=E?.retainedDialog,I=Pe?.dialog??p.createElement("dialog"),rt=a.locale||c.document.screen.strings.defaultLocale,o=rt.toLowerCase().startsWith("zh"),bn=o?"正在处理…":"Processing…",Cn=o?"正在准备报价…":"Preparing your price…",M=pn(c.document.screen.theme);U.dataset.indianaPaywall="",U.setAttribute("aria-label",c.document.name),U.style.cssText=M.root,te.style.cssText=M.controls,d.style.cssText=M.message,d.setAttribute("role","status"),T.style.cssText=M.link,T.textContent=o?"关闭":"Close",w.style.cssText=M.secondary,w.textContent=o?"重试":"Retry",w.hidden=!0,oe.type="button",oe.style.cssText=M.primary,oe.textContent=o?"继续付款":"Continue payment",oe.hidden=!0,te.append(d,oe,w,T),J&&(J.style.cssText="flex:1 0 100%;min-width:0",J.hidden=!0,te.prepend(J)),U.append(de,te);let it=()=>{if(J){let r=!J.childElementCount&&!J.textContent?.trim();J.hidden!==r&&(J.hidden=r)}let e=pe??te,t=[...e.children].every(r=>r===d?!d.textContent:r.hidden),n=[...e.children].some(r=>r===T?!1:r===d?!!d.textContent:!r.hidden);e.style.cssText=t?M.controls.replace(/padding:[^;]+/,"padding:0"):n?`${M.controls};${M.pinned}`:M.controls,ot()},Rt=typeof MutationObserver>"u"?void 0:new MutationObserver(it);Rt?.observe(U,{attributes:!0,attributeFilter:["hidden"],characterData:!0,childList:!0,subtree:!0});let Fe=Pe&&c.document.presentation.type==="inline"?{type:"modal",size:"md"}:c.document.presentation,vn=Object.entries(c.document.buttons).filter(([,e])=>e.type==="close").map(([e])=>e),$,St,De=!1,Ot=JSON.stringify(c.capabilities),j;function ye(e){let t=wn(e);if(j||fe&&!ue||G&&C)return Ue(e).map(({actionId:r})=>r);if(dt()||!C&&Ge())return t;let n=C?_t(e):Mt(e);return[...new Set([...t,...Ue(e).map(({actionId:r})=>r).filter(r=>!n.includes(r))])]}function Le(e){if(b)return;let t=c.id!==e.id;c=e;let n=JSON.stringify(e.capabilities);if(t||n!==Ot){let r=!P&&!a.quote&&!a.operation?Ze(e,W,Nt):W;t||JSON.stringify(r)!==JSON.stringify(W)?(W=r,$?.update(e.document.screen,rt,{capabilities:ne(e),unavailableActions:ye(e),serverInput:{bindings:[],answers:{}},selection:W})):$?.updateCapabilities(ne(e),ye(e)),Ot=n}kn(e),ge()}let L,at=0;function ot(){let e=p.defaultView;if(!L?.responsive||!e)return;let t=pe??te,n=e.innerHeight-(L.type==="modal"?32:0);t.style.maxHeight=`${Math.max(1,n)}px`,t.style.overflowY="auto",t.style.flexShrink="0",at=Math.max(1,n-t.getBoundingClientRect().height),$?.resizeViewport?.(at,e.innerWidth)}let b=!1,fe=!1,P=null,st,qe=!1,Tt=!1,we=!1,lt,ct=!1,se,pe;function Pn(){return fe||b||se||ct?{type:"recover",operationId:a.operation?.operationId??a.quote?.operationId??null,requestId:null}:Pt(a)}let x=()=>!b&&!qe&&!se&&i.canInteract?.()!==!1,z,ke=!1,Ee=!1,u=null,le=null,We="",ce=()=>i.checkoutNavigation==="after_confirmation"&&!!(i.terminateCheckout||i.resumeCheckout),W={},Nt=new Set,ue,C;function ut(e){return!!e&&N(e)&&e.timing==="immediate"&&e.execution.provider==="merchant"}let Dt=o?"正在确认付款…":"Confirming payment…",G=null,Lt=!1,Ge=()=>i.allowNewPurchase!==!1||Lt;function Ue(e){return Object.entries(e.document.buttons).flatMap(([t,n])=>n.type==="checkout"?[{actionId:t,policy:n}]:[])}function Ut(e){let t=C?.quote;return t?Ue(e).filter(({actionId:n,policy:r})=>Ie(t,e,n,r.product,W)).map(({actionId:n})=>n):[]}function _t(e){return C?.phase==="payment"?Ut(e):[]}function dt(){return C?.phase==="payment"&&(Ge()||!!i.prepareUpgradeReplacement)&&ce()&&!!i.terminateCheckout&&!!a.operation&&A(a.operation).type==="checkout"}function Mt(e){let t=a.quote;return!ce()||G||!t||!a.operation||A(a.operation).type!=="checkout"?[]:Ue(e).filter(({actionId:n,policy:r})=>Ie(t,e,n,r.product,W)).map(({actionId:n})=>n)}function ge(){let e=j?[]:C?_t(c):Mt(c),t=i.allowNewPurchase===!1&&!!a.operation&&A(a.operation).type==="checkout";if(oe.hidden=!!j||(C?C.phase!=="payment":!t)||e.length>0,!ce()&&!C||!$?.updateCheckoutControls)return;let n=!j&&C?.phase==="checking"?ue:void 0;$.updateCheckoutControls({actions:Ue(c).map(({actionId:r})=>r),resume:n?[n]:e,resumeLabel:n?Dt:o?"继续付款":C?"Continue payment":"Continue checkout",busy:ue})}function Vt(){le?.remove(),le=null}async function ze(){if(G)return;if(i.resumeCheckout&&a.operation){await i.resumeCheckout(a.operation.operationId);return}let e=await a.read();if(A(e).type!=="checkout")return H(e,!1);x()&&(_e.delete(e.operationId),await Me(e))}function $t(){d.textContent=o?"暂时无法打开付款页面。请重试。":"Couldn’t open checkout. Try again.",w.hidden=!0}async function ft(e=!1){let t=G;if(!t)return;C&&(u=()=>ft(),w.textContent=o?"查询状态":"Check status"),w.hidden=!0;let n=Date.now()+2e4;for(;x();){let r=await a.read();if(r.operationId!==t.operationId)throw new k("PURCHASE_PENDING","The original Checkout changed");if(!x())break;let l=A(r);if(l.type==="native"){if(C&&!Ge()&&i.prepareUpgradeReplacement){let m=await i.prepareUpgradeReplacement(t.operationId,t.intent);if(!x())return;Lt=!0,Le(m)}G=null,C&&xe(C.quote),Vt(),P=t.selection,z=t.coupon,ke=!1,Ee=!1,await Qe();return}if(l.type==="complete"||l.type==="fulfillment"||l.type==="recording"){G=null,C?await be(C.quote,r):await H(r,!1);return}if(e&&l.type==="checkout"){e=!1;try{await i.terminateCheckout(t.operationId)}catch(m){q(i.onError,m)}}if(Date.now()>=n){C&&l.type==="checkout"&&(G=null,await be(C.quote,r));break}await et(1e3,p,ae.signal)}!G||b||(C?(d.textContent=o?"仍在核对原升级单,暂时无法更换套餐。":"We’re still checking the original upgrade before changing plans.",w.hidden=!1):$t())}async function Qt(e,t,n,r){if(u=()=>Qt(e,t,n,r),await i.beforeCheckoutReplacement?.(structuredClone(r)),!x())return;let l=a.operation;if(l?.operationId!==e||A(l).type!=="checkout"){u=null,l&&await H(l,!1);return}G={operationId:e,selection:t,coupon:n,intent:r},C&&(d.textContent=o?"正在切换套餐…":"Changing plan…",w.hidden=!0);let m=!1;try{await i.terminateCheckout(e)}catch(s){if(s instanceof k&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(s.code)){G=null,C&&(u=Ke,w.textContent=o?"查询状态":"Check status",w.hidden=!1),d.textContent=o?"请继续原订单,或等待它过期后再更换方案。":"Continue your original checkout, or wait for it to expire before changing plans.",q(i.onError,s);return}m=s instanceof k&&(s.status??0)>=500,q(i.onError,s)}x()&&await ft(m)}function pt(e,t,n,r,l){let m=ne(e).checkoutCoupons?.[t],s=m?m.products[n]:i.claimCoupon&&l?Zt(e.capabilities,l,r):void 0;return s?.couponId&&s.planVersionId===n?{id:s.couponId,offerId:s.offerId}:void 0}function kn(e){fe||P||a.quote||a.operation||We&&d.textContent===We||(d.textContent=Object.values(e.capabilities.plans).some(t=>t.available)?"":o?"当前账号暂无可购买的方案。":"No plans are currently available for this account.")}let _e=new Map,Ye=!1;function Ie(e,t,n,r,l,m){let s=N(e),h=!s&&e.lines.length===1?e.lines[0]:void 0,f=ve(r,l,t.capabilities);if(!f||f!==(s?e.productVersionId:h?.productVersionId))return!1;let R=pt(t,n,f,l,m),Y;try{Y=Ne(t.document.screen,f,l,t.capabilities)}catch{return!1}if(s){let K=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return Object.keys(Y).length===Object.keys(e.featureQuantities??{}).length&&Object.entries(Y).every(([Se,Ct])=>e.featureQuantities?.[Se]===Ct)&&(!R||K?.couponId===R.id&&(!R.offerId||K.grantId===R.offerId))}if((R||ne(t).checkoutCoupons?.[n])&&(R?.id??null)!==(e.discount?.couponId??null))return!1;let X=Object.fromEntries((h?.prepaid??[]).map(K=>[K.internal_feature_id,K.quantity]));return[...new Set([...Object.keys(Y),...Object.keys(X)])].every(K=>(Y[K]??0)===(X[K]??0))}let A=e=>tn({quote:a.quote,operation:e,requestId:null,pending:!1,destroyed:b,canReselect:a.canReselect});async function Me(e){let t=e.merchantExecution,n=A(e),r=n.type==="checkout"?n.checkoutUrl:e.checkoutUrl;if(!(!x()||!r||Xe(e)&&n.type!=="checkout"||i.checkoutNavigation==="after_confirmation"&&n.type!=="checkout"||t?.type==="purchase"&&!["not_started","pending"].includes(t.paymentStatus)||_e.get(e.operationId)===r)){_e.set(e.operationId,r);try{i.onCheckoutUrl?await i.onCheckoutUrl(r):p.defaultView?.location.assign(r)}catch(l){throw _e.delete(e.operationId),l}}}let me=(e,t=!1)=>{if(e instanceof kt)u=null,d.textContent=e.customerMessage(o);else if(mn(e))u=null,d.textContent=t?o?"当前无法在此购买,付款尚未开始。请联系商户。":"Purchases aren’t available here right now. Payment hasn’t started. Contact the merchant for help.":At(e,o);else if(t){let n=e instanceof k?e.code:void 0;n==="CAPABILITY_UNAVAILABLE"||n==="NOT_CONFIGURED"?(u=null,d.textContent=o?"暂时无法为此套餐报价,付款尚未开始。":"Pricing for this plan is unavailable. Payment hasn’t started."):a.canReselect===!0&&!P?d.textContent=o?"未能取得报价,付款尚未开始。请重新选择套餐。":"We couldn’t prepare your price. Payment hasn’t started. Choose a plan again.":n==="COMMAND_PENDING"?d.textContent=o?"仍在准备报价,请重试以查看结果。":"Your price is still being prepared. Retry to check the result.":d.textContent=o?"未能取得报价,付款尚未开始。请重试。":"We couldn’t prepare your price. Payment hasn’t started. Try again."}else d.textContent=e instanceof k&&(e.code==="NETWORK_ERROR"||e.code==="TIMEOUT")?At(e,o):e instanceof k?e.message:o?"操作未完成,请重试。":"This action couldn’t be completed. Try again.";w.hidden=u===null,We=d.textContent,t&&ue===void 0&&!L?.responsive&&d.scrollIntoView?.({block:"nearest"}),q(t&&E?.quoteError?E.quoteError:i.onError,e)},Ve=new WeakMap;function $e(e){fe=e,w.disabled=e,oe.disabled=e,$?.updateCapabilities?.(ne(c),ye(c));for(let t of le?.querySelectorAll("button")??[])e?(Ve.has(t)||Ve.set(t,t.disabled),t.disabled=!0):Ve.has(t)&&(t.disabled=Ve.get(t),Ve.delete(t)),xt(t)}function Ht(){j&&(d.textContent=j.message,w.textContent=o?"重试":"Retry",w.disabled=!1,w.hidden=!j.retry,oe.disabled=!0)}function mt(){d.textContent=o?"暂时无法操作,请稍后重试。":"This action is unavailable right now. Try again in a moment."}async function En(e){if(i.beforeAction)try{await i.beforeAction()}catch(t){throw t instanceof kt?(P=null,ke=!1,Ee=!1,u=null):u=e,t}}async function Q(e,t){if(fe||b||j)return;if(!x()){mt();return}let n=e===Qe,r=n?Cn:bn,l=ce()&&t!==void 0;ue=l?t:void 0,$e(!0),ge(),w.hidden=!0,d.textContent=l?"":r;try{if(e!==wt&&e!==Ke&&e!==ht&&e!==Ke&&(e!==ze||!i.resumeCheckout)&&await En(e),b||j)return;if(!x()){u=e,w.hidden=!1,mt();return}await e()}catch(m){b||me(m,n)}finally{ue=void 0,$e(!1),ge(),j?Ht():d.textContent===r&&(d.textContent="")}}async function Bt(e){await yn(ie,e,i)}function xe(e,t){C=t?{quote:e,phase:t}:void 0,t==="checking"?(ue??=P?.actionId??Ut(c)[0],d.textContent=Dt,u=Ke,w.textContent=o?"查询状态":"Check status",w.hidden=!0):ue=void 0,$?.updateCapabilities(ne(c),ye(c)),ge()}function jt(e){return e instanceof k&&(e.code==="COMMAND_PENDING"||e.reason==="RESULT_UNKNOWN"||e.code==="NETWORK_ERROR"||e.code==="TIMEOUT"||e.status===429||(e.status??0)>=500)}function Ft(e,t){Et(e,{...t,featureQuantities:t.featureQuantities??{}},"Purchase operation changed")}async function Ke(){C&&await be(C.quote)}async function be(e,t){xe(e,"checking"),We="";let n=1e3;De=!0,q(i.onObservationChange,!0);try{for(let r=t;x();r=void 0){if(!r){try{r=await a.read()}catch(l){if(!jt(l))throw l}if(!x())return}if(r){Ft(r,e);let l=A(r);if(l.type==="checkout"){xe(e,"payment"),d.textContent=o?"请先完成原订单的付款。":"Finish paying for this upgrade.",w.hidden=!1;return}if(l.type==="complete"){xe(e,"complete"),u=null;let m=c.capabilities.plans[e.productVersionId]?.name,s=e.merchantTerms?.subscriptionTerms?.items,h=s?.length===1?s[0].interval:void 0,f=h==="year"?o?"年付":"annual billing":h==="month"?o?"月付":"monthly billing":null;d.textContent=m?o?`已升级到 ${m}${f?" "+f:""}。`:`Upgraded to ${m}${f?" ("+f+")":""}.`:o?"已成功升级。":"Plan upgraded.",await Bt(r);return}if(l.type==="native"&&!Oe(r)){xe(e),P=null,u=null,d.textContent=o?"付款未完成,请重新选择套餐。":"Payment failed. Choose a plan to start again.",w.textContent=o?"重试":"Retry";return}if(r.problem&&!["RESULT_UNKNOWN","STATE_CHANGED"].includes(r.problem.reason??""))throw new k(r.problem.code,o?"暂时无法完成升级。":"The upgrade needs attention.",void 0,void 0,r.problem)}await et(n,p,ae.signal),n=Math.min(n*1.5,15e3)}}finally{De=!1,q(i.onObservationChange,!1)}}async function ht(){let e=C?.quote;if(!e)return;let t=await a.read();if(Ft(t,e),A(t).type!=="checkout")return be(e,t);if(i.resumeCheckout){await i.resumeCheckout(t.operationId);return}_e.delete(t.operationId),await Me(t)}function qt(e){return Pt(a).type==="recording"||A(e).type==="recording"}function Wt(e){let t=e.merchantTerms,n=t?.subscriptionTerms?.items??[],r=t?t.totalMinor:N(e)?e.totalMinor:e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),l=t?n.length===1&&n[0]?.amountMinor===r&&n[0]:!N(e)&&e.lines.length===1&&e.lines[0]?.catalogAmountMinor===r&&e.lines[0],m=r===null?he(t.subtotalMinor-t.discountMinor,e.currency)+(o?" + 待确认税费":" + tax confirmed at checkout"):he(r,e.currency)+(l?Te(l.interval,o?"zh-CN":"en",l.intervalCount??1):""),s=N(e)?a.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(h=>h.productName).join(", ");return{label:s?`${s} · ${m}`:m,recurring:l}}async function H(e,t=i.checkoutNavigation!=="after_confirmation"){if(b)return;if(!x()){u=async()=>H(await a.read()),w.hidden=!1;return}let n=e.quote??a.quote;if(ut(n)&&(e.confirmedAt||e.merchantExecution))return be(n,e);if(d.textContent=hn(e.status,o),qt(e)){let f=e.merchantExecution?.recordingStatus==="failed";d.textContent=f?o?"付款和商户处理已完成,但交易记录失败。请联系商户修复,勿重复购买。":"Payment and fulfillment succeeded, but recording failed. Contact the merchant to repair this purchase; do not buy again.":o?"付款和商户处理已完成,正在确认交易记录。请勿重复购买。":"Payment and merchant fulfillment are complete. Recording is pending confirmation; do not purchase again.",w.textContent=o?"查询记录":"Check recording",u=async()=>H(await a.read()),w.hidden=!1;return}if(e.problem&&A(e).type!=="native"){let f=e.problem;u=Ae,w.textContent=o?"检查并恢复原操作":"Check and recover original purchase",me(new k(f.code,f.reason==="RESULT_UNKNOWN"?o?"付款结果尚未确定,请恢复原操作,暂勿重复购买。":"The payment result is unknown. Recover the original purchase before buying again.":f.phase==="fulfillment"?o?"付款已记录,商户权益处理需要核对。":"Payment was recorded. Access fulfillment needs attention.":f.code==="CAPABILITY_UNAVAILABLE"?o?"商户尚不支持本次购买所需的完整能力,请处理后恢复原操作。":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":f.code==="NOT_CONFIGURED"?o?"付款服务连接需要处理,请联系商户后恢复原操作。":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":o?"原购买操作需要处理,请查询或恢复此操作。":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,f));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)&&(d.textContent=o?"付款已记录,正在等待商户完成处理。":"Payment was recorded. Waiting for merchant fulfillment."),je(e)&&A(e).type==="complete"){u=null,await Bt(e);return}if(!Oe(e)&&A(e).type!=="fulfillment"){if(a.canReselect===!1){d.textContent=o?"正在核对原购买结果":"Checking the original purchase result",w.textContent=o?"查询结果":"Check result",u=async()=>H(await a.read()),w.hidden=!1;return}e.status==="cancelled"?d.textContent=o?"这笔购买已取消,可以重新选择方案。":"This purchase was cancelled. Choose a plan to start again.":e.status==="failed"&&(d.textContent=o?"这笔购买未能完成,可以重新选择方案。":"This purchase didn’t go through. Choose a plan to try again."),w.textContent=o?"重试":"Retry",u=null,P=null;return}if(!t&&A(e).type==="checkout"){if(G){$t();return}if(ce()){d.textContent="",Ye=!1,i.allowNewPurchase===!1?Gt():u=null,$?.updateCapabilities?.(ne(c),ye(c)),ge();return}let f=a.quote,R=f?.operationId===e.operationId?Wt(f).label:"";d.textContent=Ye?R?o?`${R} 尚未付款。再次选择该方案即可继续付款。`:`${R} is still unpaid. Choose it again to continue paying.`:o?"之前的购买尚未付款。再次选择该方案即可继续付款。":"Your earlier purchase is still unpaid. Choose that plan again to continue paying.":"",Ye=!1,u=null;return}await Me(e);let r=Date.now(),l=r+6e5,m=2e3,s=A(e).type!=="checkout",h=()=>s&&Date.now()-r<15e3;De=!0,q(i.onObservationChange,!0);try{for(;!b&&Date.now()<l;){if(await et(h()?700:m,p,ae.signal),b)return;if(!x()){u=async()=>H(await a.read()),w.hidden=!1;return}let f=await a.read();if(A(f).type==="checkout"&&(s=!1),!t&&A(f).type==="checkout"){await H(f,!1);return}if(!f.problem&&Oe(f)&&await Me(f),!Oe(f)||f.problem||qt(f)){await H(f);return}h()||(m=Math.min(m*1.5,3e4))}}finally{De=!1,q(i.onObservationChange,!1)}u=async()=>H(await a.read()),w.hidden=!1}async function yt(e=!1){let t=await a.read();if(b)return;if(!x()){u=()=>yt(e),w.hidden=!1;return}let n=a.quote;if(n&&Et(t,{operationId:n.operationId,currency:n.currency},"The original purchase operation changed"),n&&(Xe(t)?["prepared","quoted"].includes(t.status):t.status==="pending")&&(Xe(t)||t.quoteFinalized===!1)&&!t.confirmedAt&&!t.checkoutUrl&&!("nativePurchase"in t&&t.nativePurchase)&&!t.merchantExecution&&!t.problem&&!a.pendingCancellation){if(i.purchaseConfirmation!=="paywall"){e?await Ae():u=null;return}setTimeout(zt,0,n);return}await H(t,e||void 0)}function Gt(){u=wt,w.textContent=o?"查询状态":"Check status",w.hidden=!1}async function wt(){await yt()}async function Ae(){if(a.quote&&!(Date.parse(a.quote.expiresAt)>Date.now()))throw new k("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");Vt();let e=a.quote;if(ut(e)){xe(e,"checking");let n;try{n=await a.confirm()}catch(r){if(!jt(r))throw r;return be(e)}return be(e,n)}u=Ae;let t=await a.confirm();if(!x()){u=Ae,w.hidden=!1;return}if(t.problem){await H(t);return}if(Oe(t)){if(A(t).type==="checkout")await Me(t);else if(t.execution&&t.execution.provider!=="merchant"||"nativePurchase"in t&&t.nativePurchase){if(!i.onPurchase)throw new k("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await i.onPurchase({operation:t,signal:ae.signal})}}u=async()=>H(await a.read()),await H(t,!0)}function zt(e){if(b)return;le?.remove();let t=!(Date.parse(e.expiresAt)>Date.now());d.textContent=t?o?"此报价已过期。请先取消,再重新选择。":"This quote has expired. Cancel it, then choose again.":"";let n=p.createElement("div"),r=p.createElement("button"),l=p.createElement("button"),m=p.createElement("div"),s=p.createElement("p"),h=e.merchantTerms,f=o?"zh-CN":"en",R=h?.subscriptionTerms?.items??[],Y=h?h.subscriptionTerms?.trial?.days:N(e)?void 0:e.lines.find(y=>y.trial)?.trial?.days,X=N(e)?h?h.totalMinor:e.totalMinor:Y===void 0?null:h?h.totalMinor:e.charge?e.charge.totalMinor:e.lines.every(y=>y.trial)?0:null,Re=(y,v)=>o?`${v} 天试用结束后 ${y}`:`Then ${y} after the ${v}-day trial`,{label:K,recurring:Se}=Wt(e),Ct=N(e)?a.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(y=>y.productName).join(", "),Jt=X===null?"":`${o?"今天应付":"Due today"} ${he(X,e.currency)}`;s.textContent=Jt?[Ct,Jt].filter(Boolean).join(" · "):K,r.textContent=N(e)?o?"确认变更":"Confirm change":o?"确认购买":"Confirm purchase",r.disabled=t,l.textContent=o?"取消":"Cancel",n.style.cssText=M.panel,s.style.cssText=M.summary,m.style.cssText=M.actions,r.style.cssText=M.primary,l.style.cssText=M.secondary,xt(r),r.onclick=()=>{Q(Ae)};let Xt=async()=>{let y=await a.cancel();b||(n.remove(),le=null,await H(y))};l.onclick=()=>{u=Xt,Q(Xt)};let F=p.createElement("div");if(F.style.cssText=M.terms,N(e)){for(let[v,S]of Object.entries(e.featureQuantities??{})){let _=a.view?.capabilities.plans[e.productVersionId]?.prepaid?.find(In=>In.internalFeatureId===v),Je=p.createElement("p");Je.textContent=`${_?.name??v} · ${S} ${o?"份":"packs"}${_?` × ${_.terms.units}`:""}`,F.append(Je)}for(let[v,S]of[[o?"原订阅抵扣":"Unused subscription credit",e.creditMinor],[o?"新套餐费用":"New plan charge",e.debitMinor],[o?"优惠减免":"Offer savings",h?.discountMinor??e.discountMinor],[o?"税费":"Tax",h?h.taxMinor:e.taxMinor]]){let _=p.createElement("p");_.textContent=`${v}: ${S===null?o?"结账时确认":"Confirmed at checkout":he(S,e.currency)}`,F.append(_)}let y=p.createElement("p");y.textContent=`${o?"生效时间":"Effective"}: ${e.effectiveAt}`,F.append(y)}if(h){for(let v of R){if(X===null&&v===Se)continue;let S=p.createElement("p"),_=he(v.amountMinor,e.currency)+Te(v.interval,f,v.intervalCount);S.textContent=X!==null&&Y!==void 0?Re(_,Y):_,v.amountAfterOfferMinor!==void 0&&(S.textContent+=` · ${o?"优惠结束后":"After the offer"} ${he(v.amountAfterOfferMinor,e.currency)}${Te(v.interval,f,v.intervalCount)}`),F.append(S)}let y=h.subscriptionTerms?.trial;if(y){let v=p.createElement("p");v.textContent=o?`试用 ${y.days} 天;${y.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${y.days}; ${y.cardRequired?"a payment method is required":"no payment method is required"}`,F.append(v)}for(let v of[...h.expectedEffects.map(S=>S.description),...h.requiredConsents.map(S=>S.summary)]){let S=p.createElement("p");S.textContent=v,F.append(S)}}else if(!N(e)){for(let y of e.lines){if(X!==null||y!==Se){let v=p.createElement("p"),S=`${he(y.catalogAmountMinor,e.currency)}${Te(y.interval,f,y.intervalCount??1)}`;v.textContent=X!==null&&y.trial?(e.lines.length>1?`${y.productName} · `:"")+Re(S,y.trial.days):`${y.productName} · ${S}`,F.append(v)}for(let v of y.prepaid??[]){let S=p.createElement("p"),_=a.view?.capabilities.plans[y.productVersionId]?.prepaid?.find(Je=>Je.internalFeatureId===v.internal_feature_id);S.textContent=`${_?.name??v.internal_feature_id} · ${v.quantity} ${o?"份":"packs"} × ${v.terms.units}`,_&&(S.textContent+=Te(_.reset==="week"||_.reset==="month"||_.reset==="year"?_.reset:"one_time",f,_.resetCount)),F.append(S)}if(y.trial){let v=p.createElement("p");v.textContent=o?`试用 ${y.trial.days} 天;${y.trial.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${y.trial.days}; ${y.trial.cardRequired?"a payment method is required":"no payment method is required"}`,F.append(v)}}if(!e.charge){let y=p.createElement("p");y.textContent=o?"目录价格;最终金额以结账时税费和试用规则为准。":"Catalog price; the final charge depends on checkout taxes and trial terms.",F.append(y)}}for(let y of F.children)y.style.margin="0";m.append(r,l),n.append(s,...F.childElementCount?[F]:[],m),te.prepend(n),L?.responsive||n.scrollIntoView?.({block:"nearest"}),r.focus({preventScroll:!0}),le=n,fe&&$e(!0),u=null}async function Qe(){if(!P)return;if(u=Qe,!ke){let n=a.view,r=n?.document.buttons[P.actionId],l=n&&r?.type==="checkout"?ve(r.product,P.selection,n.capabilities):null;if(!n||!l)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");if(!Ee){let s=await i.resolveSubscriptionChange?.({actionId:P.actionId,productVersionId:l,featureQuantities:Ne(n.document.screen,l,P.selection,n.capabilities)});if(b)return;s!==void 0&&(P.subscriptionChange=en.parse(s)),Ee=!0}let m=z?.offerId;if(z&&!m){if(!i.claimCoupon)throw new k("CAPABILITY_UNAVAILABLE","Coupon claiming is unavailable");let{offer:s}=await i.claimCoupon(z.id,P.requestId);if(b)return;if(!s||s.couponId!==z.id||s.status!=="issued"||!(Date.parse(s.expiresAt)>Date.now()))throw P=null,z=void 0,u=async()=>{Le(await a.refresh()),u=null},new k("COUPON_UNAVAILABLE","This Coupon is no longer available for this purchase");m=s.id}if(!z&&!n.document.screen.actions.some(s=>s.id===P?.actionId&&typeof s.properties.couponBinding=="string")&&(m=await i.resolveOfferId?.({actionId:P.actionId,productVersionId:l,featureQuantities:Ne(n.document.screen,l,P.selection,n.capabilities)})),b)return;m!==void 0&&(P.offerId=m),ke=!0}if(!x()){w.hidden=!1;return}let e;try{e=await a.preview(P)}catch(n){throw a.canReselect===!0&&(P=null,ke=!1,Ee=!1,z=void 0,u=null),n}if(z&&(N(e)?(()=>{let n=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return n?.couponId!==z.id||n.grantId!==P.offerId})():e.discount?.couponId!==z.id||e.discount.offerId!==P.offerId))throw new k("INVALID_RESPONSE","The quote did not apply the Coupon selected on this Paywall");if(b)return;let t=e.merchantTerms;if(i.purchaseConfirmation!=="paywall"||i.confirmOnHostedCheckout&&x()&&!N(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()){if(!x()){w.hidden=!1;return}if(!(Date.parse(e.expiresAt)>Date.now()))throw new k("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");let n=ue?"":o?"正在打开收银台…":"Opening checkout…";d.textContent=n;try{await Ae()}catch(r){b||me(r)}finally{d.textContent===n&&(d.textContent="")}return}zt(e)}function Ce(e="destroy",t=!1){if(b)return;b=!0;let n=st;st=void 0,q(n),i.signal?.removeEventListener("abort",re),a.signal?.removeEventListener("abort",re),D.finish("dismissed"),St?.(),ae.abort(),Rt?.disconnect(),$?.destroy(),a.destroy(),I.removeEventListener("cancel",Kt),T.remove(),U.remove(),t||Yt(),e==="dismiss"&&q(i.onDismiss)}function Yt(){if(L?.destroy(),Pe){Pe.release();return}I.open&&I.close(),I.remove(),O()}B=Ce;async function He(){if(!we||b||qe||se==="closing"||!se&&!x())return;if(!E){Ce("dismiss");return}let e=p.createElement("p");e.setAttribute("role","status"),e.textContent=o?"正在关闭…":"Closing…",pe||(pe=p.createElement("div"),pe.style.cssText=te.style.cssText,te.replaceWith(pe),de.inert=!0),T.hidden=!1,pe.replaceChildren(e,T),se="closing",T.setAttribute("aria-disabled","true"),T.focus({preventScroll:!0});try{await E.dismiss()}catch(t){b||q(i.onError,t)}b||(se="retry",e.textContent=o?"未能确认关闭,请重试。":"Could not confirm closure. Try again.",T.textContent=o?"重试关闭":"Retry closing",T.removeAttribute("aria-label"),T.removeAttribute("aria-disabled"))}T.onclick=()=>{He()};function Kt(e){e.preventDefault(),He()}I.addEventListener("cancel",Kt),oe.onclick=()=>{Q(C?ht:ze)},w.onclick=()=>{if(j){j.retry?.();return}u&&Q(u)};function gt(e){D.finish("error",e),Ce()}function bt(){if(!(!Tt||we||b||qe||L&&!x()))try{let e=t=>{i.focusAtReveal&&(O=It(p)),$?.setHidden?.(!1),lt?.(),L&&(I.open||I.showModal(),L.responsive&&I.focus({preventScroll:!0}),!t&&i.loading!=="host"&&sn(I,L.type,L.responsive)),t&&i.loading!=="host"&&typeof de.animate=="function"&&!p.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches&&de.animate([{opacity:.55},{opacity:1}],{duration:160,easing:"ease-out"}),we=!0};E?E.present(t=>D.present(n=>e(t??n))):D.present(e)}catch(e){gt(e),me(e)}}try{if(Fe.type==="inline"?(it(),lt=dn(U,V),V.append(U)):(I.setAttribute("aria-label",c.document.name),T.textContent="×",T.setAttribute("aria-label",o?"关闭":"Close"),ln(T,c.document.screen.theme),T.hidden=an(c.document),(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&E?.retainedContent?E.retainedContent.append(T,U):I.replaceChildren(T,U),Pe||V.append(I),L=on(I,{...c.document.screen,presentation:Fe},ot),L.latch(),L.responsive&&(U.style.display="flex",U.style.flexDirection="column",U.style.maxHeight="100%",de.style.overflow="clip",de.style.minHeight="0"),Pe||(lt=un(I))),nt&&J){let n=nt(J);if(typeof n=="function"&&(b?q(n):st=n),b)throw new DOMException("Presentation cancelled","AbortError");it()}$=ee(de,{mode:"live",loadingLayout:()=>D.getLoadingLayout?.()??E?.loadingLayout?.(),rendererUrl:"bundled",title:c.document.name,closeActions:vn,onAuthoredClose(n){se||b||(T.hidden=n)},hostPresentation:()=>L?.type??Fe.type,reportContentHeight:L?.responsive,onResize:n=>{if(!L?.responsive)return;let r=Math.min(n,at);de.style.height=`${r}px`,L.setContentHeight(r+(pe??te).getBoundingClientRect().height)},onSelection(n){for(let[r,l]of Object.entries(n))typeof l=="number"&&typeof W[r]=="number"&&W[r]!==l&&Nt.add(r);W=n,ge()},onAction(n,r={},l,m){if(!we||b||se)return;let s=a.view,h=s?.document.buttons[n];if(!h)return;if(j){h.type==="close"&&He();return}if(h.type==="close"&&E&&i.resumeCheckout&&a.operation&&nn(A(a.operation))){He();return}if(fe)return;if(!x()){mt();return}if(h.type==="close"){Q(async()=>{E?.closeAction?await E.closeAction(n):await i.onAction?.(n),Ce(i.onAction?"action":"dismiss")});return}if(h.type==="action"){u=async()=>{if(h.action.type==="event"){if(!i.onEvent)throw new k("EVENT_HANDLER_REQUIRED","Provide the event handler");await i.onEvent(h.action.event)}else i.onOpenUrl?await i.onOpenUrl(h.action.url):p.defaultView?.location.assign(h.action.url);await i.onAction?.(n),u=null},Q(u);return}if(ce()&&G){G.selection.actionId===n&&Q(()=>ft(!0),n);return}if(C){if(C.phase==="payment"&&s&&Ie(C.quote,s,n,h.product,r,m)){Q(ht,n);return}if(!dt())return}if(!Ge()&&!dt()){ce()&&s&&a.quote&&a.operation&&A(a.operation).type==="checkout"&&Ie(a.quote,s,n,h.product,r,m)?Q(ze,n):d.textContent=o?"当前只能继续原订单。":"Only your original checkout is available.";return}if(le&&a.canReselect===!1){d.textContent=o?"请先确认或取消当前购买。":"Confirm or cancel the current purchase first.",L?.responsive||le.scrollIntoView?.({block:"nearest"}),le.querySelector("button")?.focus({preventScroll:!0});return}if(ce()&&i.terminateCheckout&&s&&a.quote&&a.operation&&a.canReselect===!1&&A(a.operation).type==="checkout"){if(Ie(a.quote,s,n,h.product,r,m)){Q(ze,n);return}let R=ve(h.product,r,s.capabilities),Y;try{if(!R)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");Y=Ne(s.document.screen,R,r,s.capabilities)}catch(Se){me(Se);return}let X=a.operation.operationId,Re={actionId:n,requestId:crypto.randomUUID(),selection:structuredClone(r)},K=pt(s,n,R,r,m);Q(()=>Qt(X,Re,K,{actionId:n,productVersionId:R,selection:Re.selection,featureQuantities:Y}),n);return}if((a.quote||P)&&a.canReselect===!1){let R=!!s&&!!a.quote&&Ie(a.quote,s,n,h.product,r,m);Ye=!!a.quote&&!R,u=a.quote?()=>yt(R):Qe,Q(u);return}let f=s&&ve(h.product,r,s.capabilities);if(!s||!f){me(new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(i.onPurchaseIntent){u=null,Q(async()=>{let R={actionId:n,productVersionId:f,selection:structuredClone(r),featureQuantities:Ne(s.document.screen,f,r,s.capabilities)};ct=!0,await i.onPurchaseIntent(R)});return}if(P&&P.actionId!==n){me(new k("COMMAND_PENDING","Finish the current purchase"));return}P||(z=pt(s,n,f,r,m),P={requestId:crypto.randomUUID(),actionId:n,selection:structuredClone(r)},ke=!1,Ee=!1),Q(Qe,n)},onEscape:()=>{He()},onError:n=>{let r=new Error(n);!we&&!b&&gt(r),me(r)},onRendered:n=>{n&&I.setAttribute("aria-label",n),Tt=!0,bt()}}),$.setHidden?.(!0),ot();let e=ce()&&!!a.quote&&!!a.operation&&A(a.operation).type==="checkout";W=a.quote?gn(c,a.quote)??Ze(c,{}):Ze(c,{}),$.update(c.document.screen,rt,{capabilities:ne(c),unavailableActions:ye(c),serverInput:{bindings:[],answers:{}},...Object.keys(W).length?{selection:W}:{}}),St=a.subscribe?.(Le),Le(a.view??c),await D.wait($.ready);let t=a.operation;(!e||ut(a.quote))&&(a.quote||t&&(t.confirmedAt||t.checkoutUrl||je(t)))?(u=wt,Q(u)):e&&i.allowNewPurchase===!1&&Gt()}catch(e){throw gt(e),e}return{check:ie,host:{get currentResolution(){return c},setPurchaseRecovery(e,t){j={message:e,retry:t},$?.updateCapabilities?.(ne(c),ye(c)),ge(),Ht()},get subscriptionUpgradeActive(){return C!==void 0},get observing(){return De},get recovery(){return Pn()},async prepareFallback(){if(fe||b||se||ct)return{type:"recover",operationId:a.operation?.operationId??a.quote?.operationId??null,requestId:null};$e(!0);try{let e=await rn(a);return e.type==="native"&&Ce(),e}finally{$e(!1)}},setSuspended(e){qe=e,U.hidden=e,e&&I.open?I.close():!e&&!we?bt():!e&&!b&&we&&Fe.type!=="inline"&&!I.open&&I.showModal()},destroy:Ce,retainPurchaseDialog(){if(!(b||!I.open||!I.isConnected))return Ce("destroy",!0),{dialog:I,release:Yt}},refresh:async()=>{if(!x()){if(a.view)return a.view;throw new k("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await a.refresh();return Le(e),bt(),e}}}}export{ir as a};
@@ -1 +0,0 @@
1
- import{c as $}from"./chunk-NNJVMJUG.js";import{a as z}from"./chunk-DSPLGTQI.js";var G={sm:420,md:640,lg:900},F=767;function Pe(e,n,i=()=>!0,c="Close"){let t=e.ownerDocument.defaultView,r=e.ownerDocument.createElement("button");r.type="button",r.setAttribute("aria-label",c),r.style.cssText="position:absolute;inset:0 48px auto;z-index:2;height:24px;border:0;padding:0;background:transparent;touch-action:none;cursor:grab";let d=e.ownerDocument.createElement("span");d.style.cssText="display:block;width:36px;height:4px;border-radius:4px;margin:8px auto 12px;background:currentColor;opacity:.22;pointer-events:none",r.append(d),e.prepend(r);let l,s=0,a=!1,p=()=>{r.hidden=e.dataset.presentation!=="sheet",r.setAttribute("aria-disabled",String(!i()))},b=o=>{p(),!(r.hidden||!i()||o.button!==0)&&(l={y:o.clientY,time:Date.now(),id:o.pointerId},s=0,a=!1,r.setPointerCapture?.(o.pointerId))},y=o=>{!l||o.pointerId!==l.id||(s=Math.max(0,o.clientY-l.y),e.style.transform=`translateY(${s}px)`)},v=o=>{if(!l||o.pointerId!==l.id)return;let g=Math.max(1,Date.now()-l.time),P=o.type!=="pointercancel"&&i()&&(s>120||s>40&&s/g>.5);a=s>6,l=void 0,r.releasePointerCapture?.(o.pointerId),e.style.transform="",P?n():s&&typeof e.animate=="function"&&!t?.matchMedia?.("(prefers-reduced-motion: reduce)").matches&&e.animate([{transform:`translateY(${s}px)`},{transform:"none"}],{duration:200,easing:"cubic-bezier(.2,.8,.2,1)"}),s=0},m=()=>{if(a){a=!1;return}!l&&s===0&&i()&&n()};r.addEventListener("pointerdown",b),r.addEventListener("pointermove",y),r.addEventListener("pointerup",v),r.addEventListener("pointercancel",v),r.addEventListener("click",m);let L=typeof MutationObserver=="function"?new MutationObserver(p):void 0;return L?.observe(e,{attributes:!0,attributeFilter:["data-presentation"]}),t?.addEventListener("resize",p),p(),()=>{L?.disconnect(),t?.removeEventListener("resize",p),r.remove(),e.style.transform=""}}function q(e,n,i=!1){return(e.type==="modal"||e.type==="sheet")&&e.mobile&&i&&n<=F?e.mobile:e.type}function j(e,n,i){let c=e.ownerDocument.defaultView,t=n.presentation,r;if((t.type==="modal"||t.type==="sheet")&&t.backdrop){let o=`lp-backdrop-${crypto.randomUUID()}`,g={none:"transparent",scrim:"#f2f2f2cc",dim:"#0006","strong-dim":"#000000bf",blur:"#0006"};e.dataset.indianaBackdrop=o,r=e.ownerDocument.createElement("style"),r.textContent=`dialog[data-indiana-backdrop="${o}"]::backdrop{background:${g[t.backdrop]};backdrop-filter:${t.backdrop==="blur"?"blur(16px)":"none"}}`,e.append(r)}let d=n.pages?.[0]?.root.style?.shape,l=d?.type==="pill"?"9999px":d?.type==="rect"?typeof d.radius=="number"?`${d.radius}px`:[d.radius.topLeft,d.radius.topRight,d.radius.bottomRight,d.radius.bottomLeft].map(o=>`${o}px`).join(" "):void 0,s=(t.type==="modal"||t.type==="sheet")&&(t.desktopWidth!==void 0||t.mobile!==void 0||t.type==="modal"&&t.position!==void 0),a=t.type,p,b,y=!1,v=o=>{y||!Number.isFinite(o)||o<0||(b=o,a!=="fullscreen"&&a!=="inline"&&(e.style.height=`min(${Math.max(o,40)}px, calc(100dvh - ${a==="sheet"?0:32}px))`))},m=()=>{if(!y&&(a=p??q(t,c?.innerWidth??1024,c?.matchMedia?.("(pointer: coarse)").matches===!0),e.dataset.presentation=a,!(!s||t.type!=="modal"&&t.type!=="sheet"))){if(e.style.boxSizing="border-box",e.style.padding="0",e.style.border="0",e.style.overflow="hidden",e.style.outline="none",e.tabIndex=-1,e.style.background=n.theme.background,e.style.color=n.theme.text,a==="fullscreen")e.style.width="100vw",e.style.height="100dvh",e.style.maxWidth="100vw",e.style.maxHeight="100dvh",e.style.margin="0",e.style.borderRadius="0";else{let o=t.mobile==="sheet"&&a==="sheet",g=t.desktopWidth,P=c?.innerWidth??1024;e.style.width=o?`${P}px`:g?`${Math.min(g.max,Math.max(P*g.viewport/100,g.min))}px`:`${$[t.size]}px`,e.style.maxWidth=`${Math.max(0,P-(a==="sheet"?0:32))}px`,e.style.maxHeight=a==="sheet"?"100dvh":"calc(100dvh - 32px)",e.style.margin=a==="sheet"?"auto auto 0":t.type==="modal"&&t.position==="top"?"16px auto auto":t.type==="modal"&&t.position==="bottom"?"auto auto 16px":"auto",e.style.borderRadius=l??(a==="sheet"?"16px 16px 0 0":"24px"),e.style.height="",b!==void 0&&v(b)}i?.(a)}},L=s?[c?.matchMedia?.(`(max-width: ${F}px)`),c?.matchMedia?.("(pointer: coarse)")].filter(o=>o!==void 0):[];if(s){c?.addEventListener("resize",m);for(let o of L)o.addEventListener?o.addEventListener("change",m):o.addListener?.(m)}return m(),{responsive:s,get type(){return a},latch(){y||p!==void 0||(m(),p=a)},setContentHeight:v,destroy(){if(!y){y=!0,r?.remove(),delete e.dataset.indianaBackdrop,c?.removeEventListener("resize",m);for(let o of L)o.removeEventListener?o.removeEventListener("change",m):o.removeListener?.(m)}}}}function Se(e,n,i){let{presentation:c}=n,t="size"in c?`${G[c.size]}px`:"100vw";return e.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${t}`,j(e,n,i)}function Le(e,n,i=!1){let c=e.ownerDocument.defaultView;if(typeof e.animate!="function"||c?.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;let t=i?{duration:300,easing:"cubic-bezier(0.23, 1, 0.32, 1)"}:{duration:240,easing:"cubic-bezier(0.2, 0.8, 0.2, 1)"};e.animate(n==="sheet"?[{transform:"translateY(100%)"},{transform:"none"}]:n==="modal"?[{opacity:0,transform:i?"translateY(12px) scale(0.96)":"translateY(8px) scale(0.98)"},{opacity:1,transform:"none"}]:[{opacity:0},{opacity:1}],t);try{e.animate([{opacity:0},{opacity:1}],{...t,pseudoElement:"::backdrop"})}catch{}}function V(e,n){e.style.cssText=["position:absolute","z-index:1","top:calc(4px + env(safe-area-inset-top, 0px))","inset-inline-end:calc(4px + env(safe-area-inset-right, 0px))","width:44px","height:44px","padding:0","border:0","border-radius:50%","font:400 20px/1 system-ui,sans-serif","cursor:pointer","touch-action:manipulation"].join(";"),e.style.background=`radial-gradient(circle, ${n.background} 0 15px, color-mix(in srgb, ${n.text} 22%, ${n.background}) 15px 16px, transparent 16.5px)`,e.style.color=n.text}var O=new WeakMap;function Te(e,n){return O.set(e,n),()=>O.delete(e)}function B(e){let n=e.defaultView?.HTMLElement,i=e.activeElement;for(let t=0;t<16&&i?.shadowRoot?.activeElement;t++)i=i.shadowRoot.activeElement;let c=i?O.get(i)?.():void 0;return()=>{!i?.isConnected||!n||!(i instanceof n)||(i.focus({preventScroll:!0}),c?.())}}var Re=15e3;function He(e,n,i,c,t){let r=e.ownerDocument,d=new AbortController,l=!1,s=!1,a,p,b,y,v,m;function L(){clearTimeout(m),m=void 0,b?.(),b=void 0,a?.tagName==="DIALOG"&&a.close?.(),a?.remove(),a=void 0,p=void 0,v=void 0}function o(u,w){s||(s=!0,L(),(u==="dismissed"||u==="error")&&d.abort(w??new DOMException("Presentation cancelled","AbortError")),!(!l&&u!=="ready")&&z(n.onPresentationState,u==="error"?{surface:i,state:u,error:w}:{surface:i,state:u}))}let g=c,P=()=>{s||g()};return{setDismissHandler(u){g=u},get active(){return l&&!s},get cancelled(){return d.signal.aborted},getLoadingLayout(){return b?.getLayout?.()},retainPurchaseDialog(){return p?.()},setPurchaseRecovery(u,w){y={message:u,retry:w},v?.()},start(u,w,x){if(l||s)return;l=!0;let C=()=>{if(!s&&n.loading!=="host"){let D=(w??r.documentElement.lang)||"en",M=u&&x?.presentation?.type!=="inline",T=x!==void 0,h=r.createElement(M?"dialog":"div");a=h,h.dataset.longplayLoading=i;let R=D.startsWith("zh"),W=T?R?"正在加载套餐":"Loading plans":R?"正在加载":"Loading",N=x?.screen.theme??{background:"Canvas",text:"CanvasText"};h.setAttribute("aria-label",W);let S=r.createElement("div");S.setAttribute("role","status");let I=r.createElement("div");I.setAttribute("aria-hidden","true"),T?(S.style.cssText="padding:calc(24px + env(safe-area-inset-top, 0px)) 24px 16px;padding-inline-end:68px;font:650 20px/1.3 system-ui,sans-serif;letter-spacing:-.015em",x||(S.style.paddingBlockEnd="24px")):S.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)",S.textContent=W;let k=r.createElement("button");k.type="button",k.textContent=R?"重试":"Retry",k.style.cssText="margin:0 24px 20px;padding:8px 16px",k.onclick=()=>y?.retry?.(),v=()=>{y&&(S.textContent=y.message,y.retry?S.after(k):k.remove())};let E=r.createElement("button");E.type="button",E.textContent="×",E.setAttribute("aria-label",R?"取消加载":"Cancel loading"),V(E,N),T&&(E.style.borderRadius="50%",E.style.top="calc(15px + env(safe-area-inset-top, 0px))",E.style.insetInlineEnd="calc(15px + env(safe-area-inset-right, 0px))"),E.addEventListener("click",P);let _=f=>{f.preventDefault(),P()};h.addEventListener("cancel",_);let H=r.createElement("style");H.textContent="[data-longplay-loading] > button:focus-visible{outline:2px solid currentColor;outline-offset:-2px}",h.append(S,I,E,H),v(),e.append(h);let A=()=>{if(!s&&M){let f=h,Y=B(r);f.showModal?f.showModal():f.open=!0,E.focus({preventScroll:!0}),p=()=>{if(!f.open||!f.isConnected)return;let U=b;return b=void 0,a=void 0,p=void 0,delete f.dataset.longplayLoading,f.removeAttribute("aria-label"),f.style.padding="0",f.removeEventListener("cancel",_),S.remove(),I.remove(),E.remove(),H.remove(),k.remove(),v=void 0,{dialog:f,release(){U?.(),f.close?.(),f.remove(),Y()}}}}};x&&t?(b=t(h,I,x,D),A()):T?(h.style.cssText=M?"padding:0;border:0;border-radius:24px;background:Canvas;color:CanvasText;width:min(420px,calc(100vw - 32px))":"position:relative;background:Canvas;color:CanvasText;width:100%",A()):(X(h,I,M,i),A())}};x!==void 0&&n.loading!=="host"?m=setTimeout(C,120):C(),z(n.onPresentationState,{surface:i,state:"loading",dismiss:P})},present(u){if(s)return;let w=!!a;L(),u(w),o("ready")},dismiss:P,finish:o,async wait(u,w){let x=d.signal,C,D,M=new Promise((T,h)=>{D=()=>h(x.reason),x.aborted?D():x.addEventListener("abort",D,{once:!0}),w!==void 0&&(C=setTimeout(()=>h(new Error("Presentation data timed out")),w))});try{let T=await Promise.race([M,u]);return x.throwIfAborted(),T}finally{x.removeEventListener("abort",D),clearTimeout(C)}}}}function X(e,n,i,c){e.style.cssText="position:relative;box-sizing:border-box;background:Canvas;color:CanvasText;padding:24px 48px 24px 24px;"+(i?"position:fixed;width:min(480px,calc(100% - 32px));border:0;border-radius:16px;max-height:calc(100dvh - 32px)":"width:100%"),n.style.cssText="display:grid;gap:12px";let t=c==="banner"?[["72%",12],["44%",10]]:[["46%",20],["84%",12],["65%",12],["100%",64]];for(let[r,d]of t){let l=e.ownerDocument.createElement("div");l.style.cssText=`width:${r};height:${d}px;background:currentColor;opacity:.11;border-radius:6px`,n.append(l)}}function J(e){let n={display:"block",position:"fixed",top:"0",left:"0",opacity:"0",pointerEvents:"none",zIndex:"-1"},i=Object.keys(n).map(r=>{let d=r,l=e.style[d];return e.style[d]=n[d],[d,l]}),c=e.inert??!1,t=e.getAttribute("aria-hidden");return e.inert=!0,e.setAttribute("aria-hidden","true"),()=>{for(let[r,d]of i)e.style[r]=d;e.inert=c,t===null?e.removeAttribute("aria-hidden"):e.setAttribute("aria-hidden",t)}}function $e(e,n){let i=e.style.width;e.style.width=`${n.getBoundingClientRect().width||n.ownerDocument.defaultView?.innerWidth||800}px`;let c=J(e);return()=>{c(),e.style.width=i}}export{Pe as a,q as b,j as c,Se as d,Le as e,V as f,Te as g,B as h,Re as i,He as j,J as k,$e as l};
@@ -1 +0,0 @@
1
- import{a as we,b as ge}from"./chunk-JJIP6BZL.js";import{d as ye,e as Q}from"./chunk-OV46DXRX.js";import{a as pe}from"./chunk-WE55LJEN.js";import{a as v}from"./chunk-DSPLGTQI.js";var Ae=5*6e4,Ee=15e3,he=new WeakMap;function He(i){return he.get(i)}var C=i=>Array.isArray(i)?i.map(C):i&&typeof i=="object"?Object.fromEntries(Object.keys(i).sort().map(n=>[n,C(i[n])])):i,k=(i,n)=>JSON.stringify(C(i))===JSON.stringify(C(n)),me=i=>JSON.stringify(C([i.funnelId,i.locale??null,i.parameters??{}])),Re=["onObservationChange","onPurchase","onCheckoutUrl","resumeCheckout","allowNewPurchase","checkoutNavigation","terminateCheckout","beforeCheckoutReplacement","purchaseConfirmation","confirmOnHostedCheckout","resolveOfferId","resolveSubscriptionChange","onOpenUrl","onEvent","onAction","onComplete","onError"];function Oe(i,n){let Y=e=>structuredClone({funnelId:e.funnelId,locale:e.locale,parameters:e.parameters}),w,Z="",ee=n.start instanceof Promise?void 0:Y(n.start),L=e=>e?.parameters?.commerce,ne=Promise.resolve(n.start).then(e=>e?Y(e):void 0),N=n.maxAgeMs??Ae,ae=new AbortController,p=AbortSignal.any([ae.signal,n.client.identitySignal,...n.signal?[n.signal]:[]]),M=()=>t("released","aborted"),r="preparing",re,_,q=()=>{},V=0,m=null,g=null,h=null,u=null,P,x,te=new Map,f=null,D=new Set,S=new Map,T,oe=new Promise(e=>T=e),j,be=new Promise(e=>j=e);function H(e,a){r!==e&&(r=e,re=a,v(n.onState,e))}function Pe(){p.removeEventListener("abort",M),O(),g?.destroy(),g=null,m?.remove(),m=null,h=null}function t(e,a){["adopted","unavailable","released","closed"].includes(r)||(H(e,a),Pe(),T(!1),j(null))}let J=e=>`error:${e?.code??e?.name??"unknown"}`,U=i.ownerDocument.defaultView,A=!0,le=null,I=!1,ve=e=>e.storageArea===U?.localStorage&&(e.key===null||e.key.startsWith("indiana.funnel.purchases.")),ie=e=>{ve(e)&&F()},Se=n.client.subscribe(()=>F());function O(){A&&(A=!1,U?.removeEventListener("storage",ie),Se(),q())}let G=()=>A&&(r==="ready"||r==="preparing");function W(e){(r==="ready"||r==="preparing")&&t("unavailable",e)}function F(){if(r==="ready"&&Date.now()-V>=N)return O();I=!0,le??=(async()=>{for(;I&&w&&G();){I=!1;try{await n.client.retained()==="pending"&&W("purchase_pending")}catch(e){p.aborted?t("released","aborted"):W(J(e))}}})().finally(()=>{le=null,I&&w&&G()&&F()})}U?.addEventListener("storage",ie),p.addEventListener("abort",M,{once:!0});let se=n.client.findPurchase();se.catch(()=>{});let E;function K(e){let a=JSON.stringify(C(e)),o=te.get(a);return o||(o=n.client.readPaywall({paywallVersionId:E?.paywallVersionId??n.paywallVersionId??u?.id,...E?.paywallVersionId||n.paywallVersionId||u?{}:{paywallId:E?.paywallId??n.paywallId},...e}),te.set(a,o)),o}function B(e){let a=Object.values(e.capabilities.plans);return!(Object.values(e.document.buttons).some(c=>c.type==="checkout")&&a.length===0)&&!a.some(c=>!c.available)}function ce(e,a){if(u&&!Q(e,u))return t("unavailable","paywall_changed"),!1;u=e,x=a;for(let o of S.keys())v(o,structuredClone(e));return!0}async function R(){let e=await be;if(!e)throw new pe("PURCHASE_PENDING","The purchase did not start; open it again");return e}let Ie={get view(){return f?f.view:u},get signal(){return f?.signal??n.client.identitySignal},get quote(){return f?.quote??null},get operation(){return f?.operation??null},webViewUrl:"bundled",get canReselect(){return f?.canReselect},get recovery(){return f?.recovery},get pendingCancellation(){return f?.pendingCancellation},subscribe(e){return S.set(e,f?.subscribe?.(e)??(()=>{})),()=>{S.get(e)?.(),S.delete(e)}},refresh:async()=>f?f.refresh():structuredClone(u),preview:async e=>(await R()).preview(e),confirm:async()=>(await R()).confirm(),cancel:async()=>(await R()).cancel(),read:async()=>(await R()).read(),destroy(){f?.destroy()}},s={options:{},handoff:{}},de={loading:"host",focusAtReveal:!0,signal:n.client.identitySignal,start:async()=>Ie,canInteract:()=>s.options.canInteract?s.options.canInteract():!["unavailable","released","closed"].includes(r),async beforeAction(){let e=r!=="adopted",a=u?.capabilities,o=await R();if(e&&!k(o.view?.capabilities,a))throw new ye;await s.options.beforeAction?.()}};for(let e of Re)Object.defineProperty(de,e,{enumerable:!0,get:()=>s.options[e]});function X(){r!=="preparing"||!h||!g||!w||!k(x?.commerce,L(w))||x?.locale!==w.locale||(H("ready"),T(!0))}let ue={loadingLayout:()=>s.handoff.loadingLayout?.(),present(e){if(s.handoff.present)return s.handoff.present(e);r==="preparing"&&(h=e,V=Date.now(),X())},async dismiss(){if(s.handoff.dismiss)return s.handoff.dismiss();t("closed");for(let e of[...D])v(e)},async closeAction(e){if(s.handoff.closeAction)return s.handoff.closeAction(e);s.options.onAction?await s.options.onAction(e):await ue.dismiss()},quoteError(e){s.handoff.quoteError?s.handoff.quoteError(e):v(s.options.onError,e)}};async function Ce(){if(n.paywallVersionId||n.paywallId)return{paywallVersionId:n.paywallVersionId,paywallId:n.paywallId};let e=n.configuration;if(!e)return t("unavailable","paywall_missing"),null;let a=await Promise.resolve(n.start).catch(()=>null);if(!a||r!=="preparing")return null;let o=()=>we(e,{funnelId:a.funnelId,customerId:n.client.customerId,parameters:a.parameters??{}});if(_=await o(),r!=="preparing")return null;let c=_;if(c.type!=="paywall")return t("unavailable",ge(c)??"route"),null;let l=!1;return q=e.subscribe(()=>{l||!G()||(l=!0,o().then(d=>{!(d.type==="unavailable"&&!["funnel_stopped","route_unavailable"].includes(d.reason))&&(d.type!=="paywall"||d.paywallVersionId!==c.paywallVersionId)&&W("route_changed")}).finally(()=>l=!1))}),A||q(),{paywallVersionId:c.paywallVersionId}}(async()=>{try{let[{showPaywall:e},a]=await Promise.all([import("./paywall-NM4HMYMK.js"),Ce()]);if(p.throwIfAborted(),r!=="preparing"||!a)return;let o=n.commerce??L(ee),c=n.locale??ee?.locale;if(!o)return t("unavailable","commerce_missing");if(!c)return t("unavailable","locale_missing");E=a;let l={commerce:o,locale:c},d=await K(l);if(p.throwIfAborted(),r!=="preparing"||(!B(d)&&n.start instanceof Promise&&!P&&await ne,P&&!k(l,P)&&(l=P,d=await K(l)),p.throwIfAborted(),r!=="preparing"))return;if(!B(d))return t("unavailable","plan_unavailable");if(!ce(d,l))return;m=i.ownerDocument.createElement("div"),i.append(m);let b=setTimeout(()=>r==="preparing"&&t("unavailable","timeout"),Ee);oe.then(()=>clearTimeout(b));let y=await e(m,de,ue);if(!y.host||p.aborted||r!=="preparing"){y.host?.destroy(),t(p.aborted?"released":"unavailable","error");return}g=y.host,X()}catch(e){t(p.aborted?"released":"unavailable",J(e))}})(),ne.then(async e=>{if(!e)return t("unavailable","gated");let a=e,o=L(a),c=n.commerce??o;if(!k(o&&{...o,intent:void 0},c&&{...c,intent:void 0})||n.locale!==void 0&&a.locale!==n.locale)return t("unavailable","start_mismatch");if(!o)return t("unavailable","commerce_missing");P={commerce:o,locale:a.locale};try{let l=await se,d=l==="pending"?"purchase_pending":l==="found"?"original_purchase":l==="blocked"?"purchase_blocked":void 0;if(d)return t("unavailable",d);if(r!=="preparing")return;if(A&&(I=!1,await n.client.retained()==="pending"))return t("unavailable","purchase_pending");if(E||n.paywallId||n.paywallVersionId||u){let b=await K(P);if(p.throwIfAborted(),r!=="preparing")return;if(u){if(!B(b))return t("unavailable","plan_unavailable");if(!ce(b,P))return}}}catch(l){return t(p.aborted?"released":"unavailable",J(l))}r==="preparing"&&(w=a,Z=me(a),X(),I&&F())},()=>t("unavailable","gated"));let fe={get state(){return r},get reason(){return re},ready:oe,get start(){return w},get prediction(){return _?structuredClone(_):void 0},matches:e=>!!w&&me(e)===Z,open(){if(r==="preparing")return"pending";if(r!=="ready"||!h)return!1;if(Date.now()-V>=N)return t("unavailable","expired"),!1;let e=h;return h=null,O(),H("shown"),e(),"shown"},destroy(){ae.abort()}};return he.set(fe,{onClose(e){return r==="closed"?(v(e),()=>{}):(D.add(e),()=>{D.delete(e)})},claim(){O()},async adopt(e,a){let o=e.paywall?.resolution,c=e.paywall&&!e.paywall.quote&&!e.paywall.operation&&!e.paywall.purchaseRequestId&&!(e.paywall.selectionGeneration??0);if(r!=="shown"||!g||!u||!o||!c||e.source.id!==w?.funnelId||e.locale!==w?.locale||!k(e.parameters??{},w?.parameters??{})||!["running","waiting"].includes(e.status)||!Q(o,u))return null;let l;try{l=await a.start()}catch{return null}if(r!=="shown"||!g)return l.destroy(),null;f=l,s.options=a.options,s.handoff=a.handoff;for(let[y]of S)S.set(y,l.subscribe?.(y)??(()=>{})),l.view&&v(y,structuredClone(l.view));p.removeEventListener("abort",M),H("adopted"),j(l),D.clear();let d=g,b=m;return g=null,m=null,h=null,new Proxy(d,{get(y,$){return $==="destroy"?()=>{y.destroy(),b?.remove()}:$==="retainPurchaseDialog"?()=>{let z=y.retainPurchaseDialog();if(z)return{dialog:z.dialog,release(){z.release(),b?.remove()}}}:Reflect.get(y,$,y)}})},retainPurchaseDialog(){if(r!=="shown")return;let e=g?.retainPurchaseDialog();if(!e)return;let a=m;return g=null,m=null,t("released"),{dialog:e.dialog,release(){e.release(),a?.remove()}}},get modal(){return u?.document.presentation.type!=="inline"},get revealable(){return r==="ready"&&!!h&&Date.now()-V<N},release(){t("released")}}),fe}export{Ae as a,He as b,Oe as c};