@tinkerlandai/longplay-sdk 0.10.58 → 0.10.60

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 (114) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +2 -1
  3. package/README.zh-CN.md +2 -1
  4. package/dist/{ai-usage-DBcYB8ix.d.ts → ai-usage-DM3jAubK.d.ts} +1 -1
  5. package/dist/{api-1Tplv-7M.d.ts → api-KIp0I50M.d.ts} +21 -21
  6. package/dist/check-response-K56UEZ6E.js +1 -0
  7. package/dist/{chunk-ZG3EYP5L.js → chunk-2KM537QH.js} +1 -1
  8. package/dist/{chunk-GCTD4RXV.js → chunk-2RFI2DEV.js} +1 -1
  9. package/dist/{chunk-KXA4JHFW.js → chunk-32AEJKJW.js} +1 -1
  10. package/dist/{chunk-XQAGF6SQ.js → chunk-45PGU2HW.js} +1 -1
  11. package/dist/{chunk-P2JQEGYV.js → chunk-4OODZM64.js} +1 -1
  12. package/dist/{chunk-YJ2IOBHW.js → chunk-4SI4SQ3C.js} +1 -1
  13. package/dist/{chunk-4VZCPOVE.js → chunk-5LNX7MHO.js} +1 -1
  14. package/dist/chunk-5MRSFLQA.js +1 -0
  15. package/dist/{chunk-AIRW6CZ7.js → chunk-5QVMWM2X.js} +1 -1
  16. package/dist/chunk-6TETQL5Z.js +1 -0
  17. package/dist/{chunk-LDNDI6G3.js → chunk-77O2O552.js} +1 -1
  18. package/dist/{chunk-4UOJT46E.js → chunk-7GIP3RNR.js} +1 -1
  19. package/dist/{chunk-RXEYS3X5.js → chunk-7STWC4L4.js} +1 -1
  20. package/dist/{chunk-EHYW66EH.js → chunk-BJW4AXFL.js} +1 -1
  21. package/dist/{chunk-227Z7LU4.js → chunk-C3HZCZVJ.js} +1 -1
  22. package/dist/{chunk-YIHMOK6T.js → chunk-DBYRJ4QV.js} +1 -1
  23. package/dist/{chunk-NQZ23AGQ.js → chunk-EB7MIZ4T.js} +1 -1
  24. package/dist/{chunk-G2JC7G3R.js → chunk-EE6QNOCL.js} +1 -1
  25. package/dist/{chunk-PZTFSADV.js → chunk-EKUDMQXT.js} +1 -1
  26. package/dist/{chunk-T7AK4QLG.js → chunk-FQMZY5VP.js} +1 -1
  27. package/dist/{chunk-6VWVBQFR.js → chunk-HUYKZH3H.js} +1 -1
  28. package/dist/{chunk-EP2L4VTS.js → chunk-IM5OXTEH.js} +1 -1
  29. package/dist/{chunk-4BHGHPI5.js → chunk-J4JJZN24.js} +1 -1
  30. package/dist/{chunk-GIX2F53I.js → chunk-JBSJ3JU2.js} +1 -1
  31. package/dist/{chunk-6HNCADWS.js → chunk-JEDRJAJ5.js} +1 -1
  32. package/dist/chunk-KBST6VBH.js +1 -0
  33. package/dist/{chunk-2PY7INHO.js → chunk-KTWKDR5L.js} +1 -1
  34. package/dist/{chunk-46MFVWRW.js → chunk-MB2U2GWJ.js} +1 -1
  35. package/dist/{chunk-NFZUVZJP.js → chunk-NAFHQVSX.js} +1 -1
  36. package/dist/{chunk-NPKNI2UD.js → chunk-NDNHTG5B.js} +1 -1
  37. package/dist/{chunk-XQJW2RXY.js → chunk-PGLBFTRK.js} +1 -1
  38. package/dist/{chunk-D26ZQC46.js → chunk-PJHTN5NJ.js} +1 -1
  39. package/dist/chunk-QJPH7AFI.js +1 -0
  40. package/dist/chunk-QXDLOPZK.js +1 -0
  41. package/dist/{chunk-PYTI77BV.js → chunk-R4CYPCBI.js} +1 -1
  42. package/dist/{chunk-LB2ZRTRA.js → chunk-RIEWU4MN.js} +1 -1
  43. package/dist/{chunk-GLVCBJL5.js → chunk-RUGB7NAN.js} +1 -1
  44. package/dist/chunk-S24PK62Y.js +1 -0
  45. package/dist/chunk-S3QZOIUO.js +1 -0
  46. package/dist/{chunk-IJQFSZQG.js → chunk-S55446VK.js} +1 -1
  47. package/dist/{chunk-QA3LXFSK.js → chunk-S5RM3VO6.js} +1 -1
  48. package/dist/chunk-TBXHEGSY.js +1 -0
  49. package/dist/{chunk-Y2DUFDPV.js → chunk-TK3WOD2O.js} +1 -1
  50. package/dist/{chunk-WILVPHE6.js → chunk-UM5R4RNN.js} +2 -2
  51. package/dist/{chunk-RSKDG2VD.js → chunk-VNYUL3PV.js} +1 -1
  52. package/dist/{chunk-LTWU7HH5.js → chunk-VXDVMAS6.js} +1 -1
  53. package/dist/{chunk-XBF44N3Z.js → chunk-XCFAKO23.js} +1 -1
  54. package/dist/{chunk-RB2SBQMM.js → chunk-XZLGDFZ4.js} +1 -1
  55. package/dist/{chunk-XH2JMWC6.js → chunk-ZCJEXNJD.js} +1 -1
  56. package/dist/{chunk-NTYIQ5YC.js → chunk-ZRGL2CAP.js} +1 -1
  57. package/dist/{configuration-sync-DeWWW5za.d.ts → configuration-sync-Dad8B5Pv.d.ts} +3 -3
  58. package/dist/content-IFXC4OBS.js +1 -0
  59. package/dist/funnel-host-purchase-NS7FJH2F.js +1 -0
  60. package/dist/funnel-host-recovery-paywall-R4QGRGIJ.js +1 -0
  61. package/dist/{funnel-local-client-Fxsyl7rh.d.ts → funnel-local-client-Cb9jJGpo.d.ts} +53 -53
  62. package/dist/funnel-paywall-copies-U3JIYQJ5.js +1 -0
  63. package/dist/funnel-paywall-prerender-5NVQIQIV.js +1 -0
  64. package/dist/{funnel-process-client-D9saqPse.d.ts → funnel-process-client-DE650LzB.d.ts} +28 -28
  65. package/dist/funnel-route-prediction-XYWNKGQZ.js +1 -0
  66. package/dist/funnel-route-source-4ZVBFNYV.js +1 -0
  67. package/dist/funnel-runtime-host-6VL6UAF5.js +1 -0
  68. package/dist/index.d.ts +805 -13
  69. package/dist/index.js +1 -1
  70. package/dist/merchant-bridge-contracts-IZ7ARRRO.js +1 -0
  71. package/dist/native-shell.js +1 -1
  72. package/dist/openrouter.d.ts +3 -3
  73. package/dist/openrouter.js +1 -1
  74. package/dist/operation-contracts-6RQ33K66.js +1 -0
  75. package/dist/page.d.ts +2 -2
  76. package/dist/page.js +1 -1
  77. package/dist/paywall-47DXK7WR.js +1 -0
  78. package/dist/paywall-content-MNMF4QKA.js +1 -0
  79. package/dist/paywall-session-APGD7FZ5.js +1 -0
  80. package/dist/popup.d.ts +23 -3
  81. package/dist/popup.js +1 -1
  82. package/dist/{presentation-loading-CjljfuJq.d.ts → presentation-loading-B8W6a9WB.d.ts} +10 -46
  83. package/dist/react-native.d.ts +7 -7
  84. package/dist/react-native.js +1 -1
  85. package/dist/screen-renderer-3YO6EUWD.js +1 -0
  86. package/dist/server.d.ts +10 -10
  87. package/dist/server.js +1 -1
  88. package/dist/visual.js +1 -1
  89. package/package.json +1 -1
  90. package/dist/check-response-EYOK5EU5.js +0 -1
  91. package/dist/chunk-6PVQF4FJ.js +0 -1
  92. package/dist/chunk-6UQ7BKSR.js +0 -1
  93. package/dist/chunk-F4E42S54.js +0 -1
  94. package/dist/chunk-HIH6IEV7.js +0 -1
  95. package/dist/chunk-QY5TS3OY.js +0 -1
  96. package/dist/chunk-UB5SVEM6.js +0 -1
  97. package/dist/chunk-XFOU4DZG.js +0 -1
  98. package/dist/content-2SRJS3E3.js +0 -1
  99. package/dist/funnel-host-purchase-PBCM5VL5.js +0 -1
  100. package/dist/funnel-host-recovery-paywall-7Z4VOQCV.js +0 -1
  101. package/dist/funnel-paywall-prerender-4J5EFPFQ.js +0 -1
  102. package/dist/funnel-route-prediction-4CW6WOJY.js +0 -1
  103. package/dist/funnel-route-source-UM5O7FJS.js +0 -1
  104. package/dist/funnel-runtime-host-F6B7XCVB.js +0 -1
  105. package/dist/merchant-bridge-contracts-YVMAYBE2.js +0 -1
  106. package/dist/operation-contracts-WX2HYHD5.js +0 -1
  107. package/dist/paywall-PWWDHKVH.js +0 -1
  108. package/dist/paywall-content-DSZJWOTF.js +0 -1
  109. package/dist/paywall-session-OOXP3SRE.js +0 -1
  110. package/dist/screen-renderer-WZFPWLB5.js +0 -1
  111. package/dist/{chunk-COMZFFUA.js → chunk-PZTWDJHN.js} +0 -0
  112. package/dist/{chunk-WILVPHE6.js.LEGAL.txt → chunk-UM5R4RNN.js.LEGAL.txt} +0 -0
  113. package/dist/{funnel-node-evaluation-CRRTh1je.d.ts → funnel-node-evaluation-COIh1hKs.d.ts} +3 -3
  114. package/dist/{screen-D2bUmJ4M.d.ts → screen-Pv_pViF6.d.ts} +21 -21
@@ -1,8 +1,8 @@
1
1
  import { OpenRouter } from '@openrouter/sdk';
2
2
  import { ChatUsage } from '@openrouter/sdk/models';
3
- import { F as FoundationApi } from './api-1Tplv-7M.js';
4
- import { c as createAiPricing, A as AiUsageContext, a as AiTokenUsage, b as AiTokenQuote } from './ai-usage-DBcYB8ix.js';
5
- import './screen-D2bUmJ4M.js';
3
+ import { F as FoundationApi } from './api-KIp0I50M.js';
4
+ import { c as createAiPricing, A as AiUsageContext, a as AiTokenUsage, b as AiTokenQuote } from './ai-usage-DM3jAubK.js';
5
+ import './screen-Pv_pViF6.js';
6
6
  import 'zod';
7
7
  import 'zod/v4';
8
8
  import '@ai-sdk/provider';
@@ -1 +1 @@
1
- import"./chunk-RXEYS3X5.js";import"./chunk-GCTD4RXV.js";import"./chunk-UB5SVEM6.js";import"./chunk-6VWVBQFR.js";import{a as i}from"./chunk-Y2DUFDPV.js";import"./chunk-LB2ZRTRA.js";import"./chunk-XFOU4DZG.js";import{b as A}from"./chunk-COMZFFUA.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-7STWC4L4.js";import"./chunk-2RFI2DEV.js";import"./chunk-QJPH7AFI.js";import"./chunk-HUYKZH3H.js";import{a as i}from"./chunk-TK3WOD2O.js";import"./chunk-RIEWU4MN.js";import"./chunk-S3QZOIUO.js";import"./chunk-5MRSFLQA.js";import{b as A}from"./chunk-PZTWDJHN.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-NAFHQVSX.js";import"./chunk-EE6QNOCL.js";import"./chunk-4SI4SQ3C.js";import"./chunk-BJW4AXFL.js";import"./chunk-32AEJKJW.js";import"./chunk-EKUDMQXT.js";import"./chunk-4OODZM64.js";import"./chunk-EB7MIZ4T.js";import"./chunk-S5RM3VO6.js";import"./chunk-DBYRJ4QV.js";import"./chunk-VILB5M4X.js";import"./chunk-2RFI2DEV.js";import"./chunk-HUYKZH3H.js";import"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import"./chunk-KTWKDR5L.js";import"./chunk-XCFAKO23.js";import"./chunk-FQMZY5VP.js";import"./chunk-RIEWU4MN.js";import"./chunk-PZTWDJHN.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{o as apiOperations};
package/dist/page.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { C as ConfigurationSync } from './configuration-sync-DeWWW5za.js';
1
+ import { C as ConfigurationSync } from './configuration-sync-Dad8B5Pv.js';
2
2
  import { J as JsonValue, R as Result } from './growth-rules-B4YYy64R.js';
3
3
  import { z } from 'zod';
4
- import './screen-D2bUmJ4M.js';
4
+ import './screen-Pv_pViF6.js';
5
5
 
6
6
  /** GET /api/v1/page-experiments/{environmentId}: page experiments and the saved groups they reference only. */
7
7
  declare const pageExperimentPayloadSchema: z.ZodObject<{
package/dist/page.js CHANGED
@@ -1 +1 @@
1
- import{d as o,e as r,f as e,g as f}from"./chunk-WILVPHE6.js";import"./chunk-46MFVWRW.js";import"./chunk-3VUPVXAV.js";import"./chunk-XFOU4DZG.js";import"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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-UM5R4RNN.js";import"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-S3QZOIUO.js";import"./chunk-5MRSFLQA.js";import"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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-XZLGDFZ4.js";import"./chunk-QXDLOPZK.js";import"./chunk-W32FI2A2.js";import"./chunk-IM5OXTEH.js";import"./chunk-NDNHTG5B.js";import"./chunk-5LNX7MHO.js";import"./chunk-4OODZM64.js";import"./chunk-EB7MIZ4T.js";import"./chunk-S5RM3VO6.js";import"./chunk-VILB5M4X.js";import"./chunk-QJPH7AFI.js";import"./chunk-HUYKZH3H.js";import"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import"./chunk-KTWKDR5L.js";import"./chunk-XCFAKO23.js";import"./chunk-FQMZY5VP.js";import"./chunk-TK3WOD2O.js";import"./chunk-RIEWU4MN.js";import"./chunk-S3QZOIUO.js";import"./chunk-5MRSFLQA.js";import"./chunk-PZTWDJHN.js";import"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{a as showPaywall};
@@ -0,0 +1 @@
1
+ import{b as a}from"./chunk-S55446VK.js";import"./chunk-BJW4AXFL.js";import"./chunk-32AEJKJW.js";import"./chunk-EKUDMQXT.js";import"./chunk-4OODZM64.js";import"./chunk-EB7MIZ4T.js";import"./chunk-S5RM3VO6.js";import"./chunk-DBYRJ4QV.js";import"./chunk-VILB5M4X.js";import"./chunk-QJPH7AFI.js";import"./chunk-HUYKZH3H.js";import"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import"./chunk-KTWKDR5L.js";import"./chunk-XCFAKO23.js";import"./chunk-FQMZY5VP.js";import"./chunk-TK3WOD2O.js";import"./chunk-RIEWU4MN.js";import"./chunk-3VUPVXAV.js";import"./chunk-S3QZOIUO.js";import"./chunk-5MRSFLQA.js";import"./chunk-PZTWDJHN.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{a as readPaywallContent};
@@ -0,0 +1 @@
1
+ import{a}from"./chunk-RUGB7NAN.js";import"./chunk-NAFHQVSX.js";import"./chunk-EE6QNOCL.js";import"./chunk-VNYUL3PV.js";import"./chunk-NDNHTG5B.js";import"./chunk-5LNX7MHO.js";import"./chunk-4SI4SQ3C.js";import"./chunk-C3HZCZVJ.js";import"./chunk-S55446VK.js";import"./chunk-BJW4AXFL.js";import"./chunk-32AEJKJW.js";import"./chunk-EKUDMQXT.js";import"./chunk-4OODZM64.js";import"./chunk-EB7MIZ4T.js";import"./chunk-S5RM3VO6.js";import"./chunk-DBYRJ4QV.js";import"./chunk-VILB5M4X.js";import"./chunk-2RFI2DEV.js";import"./chunk-QJPH7AFI.js";import"./chunk-HUYKZH3H.js";import"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import"./chunk-KTWKDR5L.js";import"./chunk-XCFAKO23.js";import"./chunk-FQMZY5VP.js";import"./chunk-TK3WOD2O.js";import"./chunk-RIEWU4MN.js";import"./chunk-3VUPVXAV.js";import"./chunk-S3QZOIUO.js";import"./chunk-5MRSFLQA.js";import"./chunk-PZTWDJHN.js";import"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{a as createPaywallSession};
package/dist/popup.d.ts CHANGED
@@ -1,7 +1,7 @@
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
- import { b as ScreenAction, c as ScreenNode, d as ScreenInteractivity, e as ScreenDocument } from './screen-D2bUmJ4M.js';
1
+ import { b as ScreenAction, c as ScreenNode, d as ScreenInteractivity, e as ScreenDocument } from './screen-Pv_pViF6.js';
4
2
  import { O as Offer, a as OfferUnavailableReason } from './coupon-kfkIVf9n.js';
3
+ import { e as CustomerPageData, a as SurfaceData, P as PresentationLoadingOptions, f as ScreenParameters, g as ScreenRendererInput, S as ScreenAnswers, C as CustomerDataIntent } from './presentation-loading-B8W6a9WB.js';
4
+ export { d as PresentationState } from './presentation-loading-B8W6a9WB.js';
5
5
  import { WindowLike } from 'dompurify';
6
6
  import 'zod';
7
7
 
@@ -26,6 +26,26 @@ type PopupEvent = {
26
26
  reason: OfferUnavailableReason | "error" | null;
27
27
  };
28
28
 
29
+ /** Display geometry only. It carries no Customer, pricing, purchase or selection data. */
30
+ type LoadingLayout = {
31
+ template: string;
32
+ width: number;
33
+ height: number;
34
+ cards: {
35
+ key: string;
36
+ group?: string;
37
+ x: number;
38
+ y: number;
39
+ width: number;
40
+ height: number;
41
+ }[];
42
+ scrolls: {
43
+ key: string;
44
+ left: number;
45
+ top: number;
46
+ }[];
47
+ };
48
+
29
49
  /**
30
50
  * Render the current ScreenDocument 4 into DOM.
31
51
  *
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-ZG3EYP5L.js";import"./chunk-EP2L4VTS.js";import"./chunk-LTWU7HH5.js";import"./chunk-NTYIQ5YC.js";import"./chunk-2PY7INHO.js";import"./chunk-XBF44N3Z.js";import"./chunk-T7AK4QLG.js";import"./chunk-Y2DUFDPV.js";import"./chunk-LB2ZRTRA.js";import"./chunk-COMZFFUA.js";import"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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-2KM537QH.js";import"./chunk-IM5OXTEH.js";import"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import"./chunk-KTWKDR5L.js";import"./chunk-XCFAKO23.js";import"./chunk-FQMZY5VP.js";import"./chunk-TK3WOD2O.js";import"./chunk-RIEWU4MN.js";import"./chunk-PZTWDJHN.js";import"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { S as StackNode, e as ScreenDocument } from './screen-D2bUmJ4M.js';
2
+ import { S as StackNode, e as ScreenDocument } from './screen-Pv_pViF6.js';
3
3
 
4
4
  declare const surfaceDataSchema: z.ZodObject<{
5
5
  paywall: z.ZodOptional<z.ZodObject<{
@@ -997,26 +997,6 @@ declare const publicPaywallSchema: z.ZodObject<{
997
997
  }, z.core.$strict>;
998
998
  type PublicPaywall = z.infer<typeof publicPaywallSchema>;
999
999
 
1000
- /** Display geometry only. It carries no Customer, pricing, purchase or selection data. */
1001
- type LoadingLayout = {
1002
- template: string;
1003
- width: number;
1004
- height: number;
1005
- cards: {
1006
- key: string;
1007
- group?: string;
1008
- x: number;
1009
- y: number;
1010
- width: number;
1011
- height: number;
1012
- }[];
1013
- scrolls: {
1014
- key: string;
1015
- left: number;
1016
- top: number;
1017
- }[];
1018
- };
1019
-
1020
1000
  type RetainedPurchaseDialog = {
1021
1001
  dialog: HTMLDialogElement;
1022
1002
  content?: HTMLElement;
@@ -1029,11 +1009,12 @@ type PaywallLoadingDocument = {
1029
1009
  screen: ScreenDocument;
1030
1010
  buttons?: PublicPaywall["buttons"];
1031
1011
  };
1032
- type PaywallLoadingView = (() => void) & {
1033
- getLayout?: () => LoadingLayout | undefined;
1034
- };
1035
- /** Keep authored geometry around the inert loading projection and its live handoff. */
1036
- declare function renderPaywallLoadingDocument(panel: HTMLElement, holder: HTMLElement, input: PaywallLoadingDocument, locale: string): PaywallLoadingView;
1012
+ type PaywallLoadingView = () => void;
1013
+ /**
1014
+ * The Paywall's authored geometry and colors around a light loading status. It draws plain DOM,
1015
+ * never a frame: the Paywall's own frame is the only one this presentation starts.
1016
+ */
1017
+ declare function renderPaywallLoadingDocument(panel: HTMLElement, holder: HTMLElement, input: PaywallLoadingDocument): PaywallLoadingView;
1037
1018
 
1038
1019
  type Surface = "page" | "popup" | "banner" | "paywall" | "funnel";
1039
1020
  type PresentationState = {
@@ -1056,27 +1037,10 @@ type PresentationLoadingOptions = {
1056
1037
  signal?: AbortSignal;
1057
1038
  };
1058
1039
  /** One loading cycle. No authored content or controls are exposed during it. */
1059
- declare function createPresentationLoading(container: HTMLElement | ShadowRoot, options: PresentationLoadingOptions, surface: Surface, onDismiss: () => void, renderPaywall?: typeof renderPaywallLoadingDocument): Omit<{
1060
- setDismissHandler(handler: () => void): void;
1061
- readonly active: boolean;
1062
- readonly cancelled: boolean;
1063
- getLoadingLayout(): LoadingLayout | undefined;
1064
- retainPurchaseDialog(): RetainedPurchaseDialog | undefined;
1065
- setPurchaseRecovery(message: string, retry?: () => void): void;
1066
- /** Null selects the Paywall loading status when its layout is unavailable. */
1067
- start(modal: boolean, locale?: string, paywall?: PaywallLoadingDocument | null): void;
1068
- /** Remove the placeholder and reveal in the same turn, before notifying the host. */
1069
- present(show: (hadPlaceholder: boolean) => void): void;
1070
- dismiss: () => void;
1071
- finish: (state: Exclude<PresentationState, {
1072
- state: "loading";
1073
- }>["state"], error?: unknown) => void;
1074
- wait<T>(work: Promise<T>, timeoutMs?: number): Promise<T>;
1075
- }, "getLoadingLayout"> & Partial<Pick<{
1040
+ declare function createPresentationLoading(container: HTMLElement | ShadowRoot, options: PresentationLoadingOptions, surface: Surface, onDismiss: () => void, renderPaywall?: typeof renderPaywallLoadingDocument): {
1076
1041
  setDismissHandler(handler: () => void): void;
1077
1042
  readonly active: boolean;
1078
1043
  readonly cancelled: boolean;
1079
- getLoadingLayout(): LoadingLayout | undefined;
1080
1044
  retainPurchaseDialog(): RetainedPurchaseDialog | undefined;
1081
1045
  setPurchaseRecovery(message: string, retry?: () => void): void;
1082
1046
  /** Null selects the Paywall loading status when its layout is unavailable. */
@@ -1088,6 +1052,6 @@ declare function createPresentationLoading(container: HTMLElement | ShadowRoot,
1088
1052
  state: "loading";
1089
1053
  }>["state"], error?: unknown) => void;
1090
1054
  wait<T>(work: Promise<T>, timeoutMs?: number): Promise<T>;
1091
- }, "getLoadingLayout">>;
1055
+ };
1092
1056
 
1093
- export { type CustomerDataIntent as C, type LoadingLayout as L, type PresentationLoadingOptions as P, type RetainedPurchaseDialog as R, type ScreenAnswers as S, type SurfaceData as a, type PaywallLoadingDocument as b, createPresentationLoading as c, type PresentationState as d, type CustomerPageData as e, type ScreenParameters as f, type ScreenRendererInput as g, screenInputBindingsSchema as s };
1057
+ export { type CustomerDataIntent as C, type PresentationLoadingOptions as P, type RetainedPurchaseDialog as R, type ScreenAnswers as S, type SurfaceData as a, type PaywallLoadingDocument as b, createPresentationLoading as c, type PresentationState as d, type CustomerPageData as e, type ScreenParameters as f, type ScreenRendererInput as g, screenInputBindingsSchema as s };
@@ -1,12 +1,12 @@
1
- import { f as createCustomerClient, d as createFunnelClient } from './funnel-process-client-D9saqPse.js';
2
- export { F as FunnelProcessAdapter, a as FunnelProcessOptions, c as createFunnelProcess } from './funnel-process-client-D9saqPse.js';
3
- import { I as IndianaOptions, S as SessionCredentials, N as Scope, B as createFunnelRunController, x as PaywallStartInput, l as createPaywallSession } from './funnel-local-client-Fxsyl7rh.js';
4
- export { F as FunnelCommandStorage, h as FunnelRunController, u as LocalFunnelClientOptions, v as LongplayError, w as PaywallPurchaseInput, P as PaywallSession, y as PushHost, z as PushJournal, A as createFeatureClient, D as createLocalFunnelClient } from './funnel-local-client-Fxsyl7rh.js';
1
+ import { f as createCustomerClient, d as createFunnelClient } from './funnel-process-client-DE650LzB.js';
2
+ export { F as FunnelProcessAdapter, a as FunnelProcessOptions, c as createFunnelProcess } from './funnel-process-client-DE650LzB.js';
3
+ import { I as IndianaOptions, S as SessionCredentials, N as Scope, B as createFunnelRunController, x as PaywallStartInput, l as createPaywallSession } from './funnel-local-client-Cb9jJGpo.js';
4
+ export { F as FunnelCommandStorage, h as FunnelRunController, u as LocalFunnelClientOptions, v as LongplayError, w as PaywallPurchaseInput, P as PaywallSession, y as PushHost, z as PushJournal, A as createFeatureClient, D as createLocalFunnelClient } from './funnel-local-client-Cb9jJGpo.js';
5
5
  import { z } from 'zod';
6
6
  import { J as JsonValue } from './growth-rules-B4YYy64R.js';
7
- export { a as ConfigurationStorage, b as ConfigurationSyncOptions, c as createConfigurationSync } from './configuration-sync-DeWWW5za.js';
8
- import './api-1Tplv-7M.js';
9
- import './screen-D2bUmJ4M.js';
7
+ export { a as ConfigurationStorage, b as ConfigurationSyncOptions, c as createConfigurationSync } from './configuration-sync-Dad8B5Pv.js';
8
+ import './api-KIp0I50M.js';
9
+ import './screen-Pv_pViF6.js';
10
10
  import 'zod/v4';
11
11
  import './coupon-kfkIVf9n.js';
12
12
 
@@ -1 +1 @@
1
- import{b as S,c as E,d as T}from"./chunk-4UOJT46E.js";import"./chunk-LDNDI6G3.js";import{a as A}from"./chunk-GLVCBJL5.js";import{e as P}from"./chunk-NFZUVZJP.js";import"./chunk-G2JC7G3R.js";import{h as b,i as x,k as L}from"./chunk-4BHGHPI5.js";import{E as C}from"./chunk-AIRW6CZ7.js";import"./chunk-XH2JMWC6.js";import"./chunk-RSKDG2VD.js";import"./chunk-YJ2IOBHW.js";import"./chunk-227Z7LU4.js";import"./chunk-IJQFSZQG.js";import"./chunk-EHYW66EH.js";import"./chunk-KXA4JHFW.js";import"./chunk-PZTFSADV.js";import"./chunk-6HNCADWS.js";import"./chunk-YIHMOK6T.js";import"./chunk-NPKNI2UD.js";import"./chunk-4VZCPOVE.js";import"./chunk-P2JQEGYV.js";import"./chunk-NQZ23AGQ.js";import"./chunk-QA3LXFSK.js";import"./chunk-VILB5M4X.js";import"./chunk-GCTD4RXV.js";import"./chunk-UB5SVEM6.js";import"./chunk-6VWVBQFR.js";import"./chunk-LTWU7HH5.js";import"./chunk-NTYIQ5YC.js";import"./chunk-2PY7INHO.js";import"./chunk-XBF44N3Z.js";import"./chunk-T7AK4QLG.js";import{a as r}from"./chunk-Y2DUFDPV.js";import{h as R}from"./chunk-LB2ZRTRA.js";import"./chunk-3VUPVXAV.js";import"./chunk-XFOU4DZG.js";import"./chunk-COMZFFUA.js";import"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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-7GIP3RNR.js";import"./chunk-77O2O552.js";import{a as A}from"./chunk-RUGB7NAN.js";import{e as P}from"./chunk-NAFHQVSX.js";import"./chunk-EE6QNOCL.js";import{h as b,i as x,k as L}from"./chunk-J4JJZN24.js";import{E as C}from"./chunk-5QVMWM2X.js";import"./chunk-ZCJEXNJD.js";import"./chunk-VNYUL3PV.js";import"./chunk-NDNHTG5B.js";import"./chunk-5LNX7MHO.js";import"./chunk-4SI4SQ3C.js";import"./chunk-C3HZCZVJ.js";import"./chunk-S55446VK.js";import"./chunk-BJW4AXFL.js";import"./chunk-32AEJKJW.js";import"./chunk-EKUDMQXT.js";import"./chunk-4OODZM64.js";import"./chunk-EB7MIZ4T.js";import"./chunk-S5RM3VO6.js";import"./chunk-JEDRJAJ5.js";import"./chunk-DBYRJ4QV.js";import"./chunk-VILB5M4X.js";import"./chunk-2RFI2DEV.js";import"./chunk-QJPH7AFI.js";import"./chunk-HUYKZH3H.js";import"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import"./chunk-KTWKDR5L.js";import"./chunk-XCFAKO23.js";import"./chunk-FQMZY5VP.js";import{a as r}from"./chunk-TK3WOD2O.js";import{h as R}from"./chunk-RIEWU4MN.js";import"./chunk-3VUPVXAV.js";import"./chunk-S3QZOIUO.js";import"./chunk-5MRSFLQA.js";import"./chunk-PZTWDJHN.js";import"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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-2KM537QH.js";import"./chunk-IM5OXTEH.js";import"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import"./chunk-KTWKDR5L.js";import"./chunk-XCFAKO23.js";import"./chunk-FQMZY5VP.js";import"./chunk-TK3WOD2O.js";import"./chunk-RIEWU4MN.js";import"./chunk-PZTWDJHN.js";import"./chunk-DSPLGTQI.js";import"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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.d.ts CHANGED
@@ -1,15 +1,15 @@
1
- import { F as FoundationApi, I as InvoiceModeParams } from './api-1Tplv-7M.js';
2
- import { X as IndianaServerOptions, v as IndianaError, Y as FunnelProcessSuppression, Z as FunnelProcessCommand, T as FunnelProcessResponse, C as CustomerSession, Q as FunnelProcessOpenInput, V as FunnelProcessMutation, x as PaywallStartInput, P as PaywallSession, n as FeatureClientOptions, R as RemoteFeatureResult } from './funnel-local-client-Fxsyl7rh.js';
3
- export { m as FeatureClient, d as FunnelStartInput, L as LocalFunnelClient, u as LocalFunnelClientOptions, A as createFeatureClient, _ as createFunnelStartClient, D as createLocalFunnelClient } from './funnel-local-client-Fxsyl7rh.js';
1
+ import { F as FoundationApi, I as InvoiceModeParams } from './api-KIp0I50M.js';
2
+ import { X as IndianaServerOptions, v as IndianaError, Y as FunnelProcessSuppression, Z as FunnelProcessCommand, T as FunnelProcessResponse, C as CustomerSession, Q as FunnelProcessOpenInput, V as FunnelProcessMutation, x as PaywallStartInput, P as PaywallSession, n as FeatureClientOptions, R as RemoteFeatureResult } from './funnel-local-client-Cb9jJGpo.js';
3
+ export { m as FeatureClient, d as FunnelStartInput, L as LocalFunnelClient, u as LocalFunnelClientOptions, A as createFeatureClient, _ as createFunnelStartClient, D as createLocalFunnelClient } from './funnel-local-client-Cb9jJGpo.js';
4
4
  import * as zod from 'zod';
5
5
  import { z } from 'zod';
6
- import { S as StackNode } from './screen-D2bUmJ4M.js';
7
- import { C as ConfigurationSync } from './configuration-sync-DeWWW5za.js';
8
- export { c as createConfigurationSync } from './configuration-sync-DeWWW5za.js';
6
+ import { S as StackNode } from './screen-Pv_pViF6.js';
7
+ import { C as ConfigurationSync } from './configuration-sync-Dad8B5Pv.js';
8
+ export { c as createConfigurationSync } from './configuration-sync-Dad8B5Pv.js';
9
9
  import { J as JsonValue, E as EvaluationContext, s as stickyAssignmentDocumentSchema, F as FeatureResult } from './growth-rules-B4YYy64R.js';
10
- import { d as FunnelLocalConfiguration, f as MerchantBridgeCommand, M as MerchantBridgeManifest, m as merchantBridgeOperationInputSchema } from './funnel-node-evaluation-CRRTh1je.js';
11
- export { F as FunnelNodeEvaluationContext, g as MerchantRequirementCheckInput, h as MerchantRequirementCheckResult, i as entitlementRequirementDigest, e as evaluateFunnelNode } from './funnel-node-evaluation-CRRTh1je.js';
12
- export { d as AiPricingOptions, b as AiTokenQuote, a as AiTokenUsage, A as AiUsageContext, e as AiUsageMiddlewareOptions, f as AiUsageRecord, g as aiPriceSnapshotSchema, h as aiTokenQuoteSchema, c as createAiPricing, i as createAiUsageMiddleware, j as createConfiguredAiPricing } from './ai-usage-DBcYB8ix.js';
10
+ import { d as FunnelLocalConfiguration, f as MerchantBridgeCommand, M as MerchantBridgeManifest, m as merchantBridgeOperationInputSchema } from './funnel-node-evaluation-COIh1hKs.js';
11
+ export { F as FunnelNodeEvaluationContext, g as MerchantRequirementCheckInput, h as MerchantRequirementCheckResult, i as entitlementRequirementDigest, e as evaluateFunnelNode } from './funnel-node-evaluation-COIh1hKs.js';
12
+ export { d as AiPricingOptions, b as AiTokenQuote, a as AiTokenUsage, A as AiUsageContext, e as AiUsageMiddlewareOptions, f as AiUsageRecord, g as aiPriceSnapshotSchema, h as aiTokenQuoteSchema, c as createAiPricing, i as createAiUsageMiddleware, j as createConfiguredAiPricing } from './ai-usage-DM3jAubK.js';
13
13
  import 'zod/v4';
14
14
  import '@ai-sdk/provider';
15
15
 
@@ -2105,8 +2105,8 @@ declare const merchantBridgeCommandOutputs: {
2105
2105
  productVersionId: z.ZodNullable<z.ZodUUID>;
2106
2106
  status: z.ZodEnum<{
2107
2107
  active: "active";
2108
- cancelled: "cancelled";
2109
2108
  trialing: "trialing";
2109
+ cancelled: "cancelled";
2110
2110
  expired: "expired";
2111
2111
  past_due: "past_due";
2112
2112
  }>;
package/dist/server.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as pn}from"./chunk-6PVQF4FJ.js";import{a as I}from"./chunk-D26ZQC46.js";import{a as fn,b as hn,c as gn,d as yn}from"./chunk-RXEYS3X5.js";import{a as xt}from"./chunk-GLVCBJL5.js";import{a as Ue,b as Ve,c as qe,d as He,e as m}from"./chunk-NFZUVZJP.js";import"./chunk-G2JC7G3R.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-4BHGHPI5.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-AIRW6CZ7.js";import"./chunk-XH2JMWC6.js";import{c as h}from"./chunk-RSKDG2VD.js";import"./chunk-YJ2IOBHW.js";import{a as Et,b as _e}from"./chunk-227Z7LU4.js";import"./chunk-IJQFSZQG.js";import"./chunk-EHYW66EH.js";import{e as at}from"./chunk-KXA4JHFW.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-PZTFSADV.js";import{b as Oe}from"./chunk-6HNCADWS.js";import{e as ve,i as Ze,l as it}from"./chunk-YIHMOK6T.js";import"./chunk-NPKNI2UD.js";import"./chunk-4VZCPOVE.js";import"./chunk-P2JQEGYV.js";import"./chunk-NQZ23AGQ.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-QA3LXFSK.js";import"./chunk-VILB5M4X.js";import"./chunk-GCTD4RXV.js";import"./chunk-UB5SVEM6.js";import{a as Ne,b as Le}from"./chunk-6VWVBQFR.js";import{o as ue}from"./chunk-LTWU7HH5.js";import"./chunk-NTYIQ5YC.js";import{i as un,k as $e,l as Qe,m as Je}from"./chunk-2PY7INHO.js";import{c as Ie}from"./chunk-XBF44N3Z.js";import{e as Xe,h as We}from"./chunk-T7AK4QLG.js";import{a as c}from"./chunk-Y2DUFDPV.js";import{h as Y}from"./chunk-LB2ZRTRA.js";import"./chunk-3VUPVXAV.js";import"./chunk-XFOU4DZG.js";import{b as u}from"./chunk-COMZFFUA.js";import"./chunk-DSPLGTQI.js";import{a as Ye}from"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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-KBST6VBH.js";import{a as I}from"./chunk-PJHTN5NJ.js";import{a as fn,b as hn,c as gn,d as yn}from"./chunk-7STWC4L4.js";import{a as xt}from"./chunk-RUGB7NAN.js";import{a as Ue,b as Ve,c as qe,d as He,e as m}from"./chunk-NAFHQVSX.js";import"./chunk-EE6QNOCL.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-J4JJZN24.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-5QVMWM2X.js";import"./chunk-ZCJEXNJD.js";import{c as h}from"./chunk-VNYUL3PV.js";import"./chunk-NDNHTG5B.js";import"./chunk-5LNX7MHO.js";import"./chunk-4SI4SQ3C.js";import{a as Et,b as _e}from"./chunk-C3HZCZVJ.js";import"./chunk-S55446VK.js";import"./chunk-BJW4AXFL.js";import{e as at}from"./chunk-32AEJKJW.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-EKUDMQXT.js";import"./chunk-4OODZM64.js";import"./chunk-EB7MIZ4T.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-S5RM3VO6.js";import{b as Oe}from"./chunk-JEDRJAJ5.js";import{e as ve,i as Ze,l as it}from"./chunk-DBYRJ4QV.js";import"./chunk-VILB5M4X.js";import"./chunk-2RFI2DEV.js";import"./chunk-QJPH7AFI.js";import{a as Ne,b as Le}from"./chunk-HUYKZH3H.js";import{o as ue}from"./chunk-VXDVMAS6.js";import"./chunk-ZRGL2CAP.js";import{i as un,k as $e,l as Qe,m as Je}from"./chunk-KTWKDR5L.js";import{c as Ie}from"./chunk-XCFAKO23.js";import{e as Xe,h as We}from"./chunk-FQMZY5VP.js";import{a as c}from"./chunk-TK3WOD2O.js";import{h as Y}from"./chunk-RIEWU4MN.js";import"./chunk-3VUPVXAV.js";import"./chunk-S3QZOIUO.js";import"./chunk-5MRSFLQA.js";import{b as u}from"./chunk-PZTWDJHN.js";import"./chunk-DSPLGTQI.js";import{a as Ye}from"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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}
package/dist/visual.js CHANGED
@@ -1 +1 @@
1
- import{a as pe,c as fe}from"./chunk-OJM6ORHE.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-WILVPHE6.js";import{a as re,b as ae,c as se,d as oe}from"./chunk-46MFVWRW.js";import"./chunk-3VUPVXAV.js";import"./chunk-XFOU4DZG.js";import{b as o}from"./chunk-COMZFFUA.js";import"./chunk-DSPLGTQI.js";import{c as te,e as ie,g as M}from"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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-OJM6ORHE.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-UM5R4RNN.js";import{a as re,b as ae,c as se,d as oe}from"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-S3QZOIUO.js";import"./chunk-5MRSFLQA.js";import{b as o}from"./chunk-PZTWDJHN.js";import"./chunk-DSPLGTQI.js";import{c as te,e as ie,g as M}from"./chunk-VPT5MFDG.js";import"./chunk-CILM5XMH.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.58",
3
+ "version": "0.10.60",
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-227Z7LU4.js";import"./chunk-2PY7INHO.js";import"./chunk-XBF44N3Z.js";import"./chunk-Y2DUFDPV.js";import"./chunk-LB2ZRTRA.js";import"./chunk-COMZFFUA.js";import"./chunk-CILM5XMH.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-AIRW6CZ7.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
@@ -1 +0,0 @@
1
- import{d as w}from"./chunk-EP2L4VTS.js";import{a as u}from"./chunk-Y2DUFDPV.js";function E(e,o,t,r){let{presentation:n,screen:i}=t,y=(i.pages.find(d=>d.id===i.initialPageId)??i.pages[0])?.theme??i.theme;o.inert=!0,o.style.cssText="width:100%;min-width:0;overflow:hidden";let m=!1,s,a,f=0,g=e.querySelector('[role="status"]'),v=g?.style.cssText??"",c=()=>{g&&(g.style.cssText=s?.getLoadingLayout?.()?"position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)":v)};function x(){let d=e.ownerDocument.defaultView;!a?.responsive||!d||(f=Math.max(1,d.innerHeight-(a.type==="modal"?32:0)),s?.resizeViewport(f,d.innerWidth))}return n.type!=="inline"&&(a=w(e,{...i,presentation:n,theme:{background:i.theme.background,text:i.theme.text}},x),a.latch()),e.style.background=y.background,e.style.color=y.text,a?(n.type==="fullscreen"||n.type==="sheet")&&(e.style.position="fixed"):e.style.position="relative",import("./screen-renderer-WZFPWLB5.js").then(({mountScreenPreview:d})=>{m||(s=d(o,{mode:"live",skeleton:!0,closeActions:Object.entries(t.buttons??{}).filter(([,l])=>l.type==="close").map(([l])=>l),hostPresentation:()=>a?.type??n.type,reportContentHeight:a?.responsive,onResize(l){if(c(),!a?.responsive)return;let h=Math.min(l,f);o.style.height=h+"px",a.setContentHeight(h)},onRendered:c,onError(){s?.destroy(),s=void 0,c()}}),x(),s.update({...i,presentation:n},r,{serverInput:{bindings:[],answers:{}}}))}).catch(()=>{s?.destroy(),s=void 0,c()}),Object.assign(()=>{m=!0,s?.destroy(),a?.destroy()},{getLayout:()=>s?.getLoadingLayout?.()})}var T={none:0,sm:4,md:8,lg:14,full:9999},$={system:"system-ui,sans-serif",serif:"Georgia,serif",rounded:"ui-rounded,system-ui,sans-serif",mono:"ui-monospace,monospace"},D={primary:"#172033",background:"#FFFFFF",text:"#172033",radius:"md",font:"system"};function b(e){let[o,t,r]=[1,3,5].map(n=>{let i=Number.parseInt(e.slice(n,n+2),16)/255;return i<=.03928?i/12.92:((i+.055)/1.055)**2.4});return .2126*o+.7152*t+.0722*r}function F(e,o=!0){let t=b(e.primary),r=(t+.05)/.05>1.05/(t+.05)?"#111318":"#FFFFFF",n=`color-mix(in srgb, ${e.text} 22%, ${e.background})`,i=`${T[e.radius]}px`,p=`appearance:none;margin:0;min-height:44px;padding:10px 18px;border:0;border-radius:${i};font:inherit;font-size:15px;font-weight:600;line-height:1.25;cursor:pointer;touch-action:manipulation`;return{root:`width:100%;box-sizing:border-box;${o?`background:${e.background};`:""}color:${e.text};font:14px/1.5 ${$[e.font]}`,controls:"display:flex;gap:12px;padding:0 20px 12px;align-items:center;flex-wrap:wrap",pinned:`position:sticky;bottom:0;z-index:1;box-sizing:border-box;padding-top:12px;background:${e.background};border-top:1px solid ${n}`,bar:`display:flex;gap:8px;padding:12px 16px;align-items:center;flex-wrap:wrap;border-top:1px solid ${n}`,message:"flex:1 1 200px;min-width:0;margin:0;font-size:13px",status:"margin:0;font-size:13px;opacity:.72",alert:`flex:1 1 200px;min-width:0;margin:0;font-size:13px;font-weight:500;color:${b(e.background)>.4?"#B42318":"#FDA29B"}`,panel:`flex:1 0 100%;box-sizing:border-box;display:flex;flex-direction:column;gap:8px;padding:16px;border:1px solid ${n};border-radius:${i}`,summary:"margin:0;font-size:15px;font-weight:600",terms:"display:flex;flex-direction:column;gap:4px;font-size:13px;opacity:.72",actions:"display:flex;gap:8px;flex-wrap:wrap;margin-top:4px",primary:`${p};background:${e.primary};color:${r}`,secondary:`${p};background:transparent;color:${e.text};box-shadow:inset 0 0 0 1px ${n}`,link:`${p};background:transparent;color:${e.text};opacity:.72;font-weight:500`,stage:"display:flex;justify-content:center;padding:24px 20px",history:"display:flex;flex-direction:column;gap:12px;padding:20px",historyTitle:"margin:0;padding-inline-end:40px;font-size:17px;font-weight:600;line-height:1.3",historyNote:"margin:0;font-size:13px;opacity:.72",historyPages:"display:flex;gap:8px;flex-wrap:wrap;margin:0;padding:0;list-style:none",historyPage:`border:1px solid ${n};border-radius:${i};overflow:hidden`,historyRecords:`display:flex;flex-direction:column;gap:4px;margin:0;padding:12px 0 0;list-style:none;font-size:13px;border-top:1px solid ${n}`,focus:e.text}}function S(e){e.style.opacity=e.disabled?".55":"",e.style.cursor=e.disabled?"not-allowed":"pointer"}function q(e,o){e.addEventListener("focus",()=>{let t=!0;try{t=e.matches(":focus-visible")}catch{}t&&(e.style.outline=`2px solid ${o()}`,e.style.outlineOffset="2px")}),e.addEventListener("blur",()=>{e.style.outline="",e.style.outlineOffset=""})}var k={en:{network:"Connection problem. Check your network and try again.",timeout:"This is taking longer than expected. Try again.",other:"Something went wrong. Try again.",required:"Answer the questions marked * to continue.",permission:"This isn’t available right now. Contact the merchant for help."},zh:{network:"网络连接异常,请检查网络后重试。",timeout:"响应时间过长,请重试。",other:"出了点问题,请重试。",required:"请先回答带 * 的问题。",permission:"当前无法完成此操作,请联系商户。"}};function O(e,o){let t=k[o?"zh":"en"],r=e instanceof u?e.code:void 0;return r==="NETWORK_ERROR"?t.network:r==="TIMEOUT"?t.timeout:L(e)?t.permission:t.other}function L(e){return e instanceof u&&(e.code==="FORBIDDEN"||e.recovery==="check_permissions")}function A(e,o){if(!(e instanceof u)||e.code!=="INVALID_REQUEST"||e.status===void 0||e.status>=500)return!1;let t=/^Required input: (.+)$/.exec(e.message)?.[1]?.trim();return t!==void 0&&o.some(r=>r.variable===t)}function I(e){return k[e?"zh":"en"].required}function C(e,o){return e.filter(({variable:t,required:r})=>{let n=o[t];return r&&(n==null||n===""||Array.isArray(n)&&n.length===0)})}var P={zh:{pending:"处理中",complete:"已完成",cancelled:"已取消",failed:"失败",unknown:"状态待确认",prepared:"报价待确认",quoted:"报价待确认",confirmed:"处理中",effective:"已生效",scheduled:"已安排续期变更"},en:{pending:"Processing",complete:"Completed",cancelled:"Cancelled",failed:"Failed",unknown:"Status unconfirmed",prepared:"Quote ready",quoted:"Quote ready",confirmed:"Processing",effective:"Effective",scheduled:"Scheduled for renewal"}};function V(e,o){return P[o?"zh":"en"][e]}export{E as a,D as b,F as c,S as d,q as e,O as f,L as g,A as h,I as i,C as j,V as k};
@@ -1 +0,0 @@
1
- import{b as De}from"./chunk-LDNDI6G3.js";import{a as $}from"./chunk-D26ZQC46.js";import{D as K,F as Ge,c as je,e as z,j as Te,u as Ve,v as He,x as Le,z as Me}from"./chunk-AIRW6CZ7.js";import{a as Ae,b as Fe,c as Ne}from"./chunk-RSKDG2VD.js";import{K as G}from"./chunk-PZTFSADV.js";import{a as se}from"./chunk-NPKNI2UD.js";import{i as ue}from"./chunk-4VZCPOVE.js";import{A as ae,B as ie,C as J,E as qe}from"./chunk-NQZ23AGQ.js";import{x as ye}from"./chunk-QA3LXFSK.js";import{b as xe}from"./chunk-UB5SVEM6.js";import{a as l}from"./chunk-Y2DUFDPV.js";import{h as oe}from"./chunk-LB2ZRTRA.js";import{b as Ue}from"./chunk-XFOU4DZG.js";import{b as r}from"./chunk-COMZFFUA.js";import{a as ge}from"./chunk-DSPLGTQI.js";var v=G.options,rt=r.discriminatedUnion("operation",[v[1].omit({customerToken:!0}),v[2].omit({customerToken:!0}),v[3].omit({customerToken:!0}),v[4].omit({customerToken:!0}),v[5].omit({customerToken:!0}),v[6].omit({customerToken:!0}),v[7].omit({customerToken:!0}),v[8].omit({customerToken:!0}),Te.omit({customerToken:!0})]),Pe=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),ft=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("find_purchase")}),r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume","start"]),start:r.strictObject({requestId:v[0].shape.requestId,funnelId:v[0].shape.funnelId,locale:v[0].shape.locale,parameters:v[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe,includePaywallVersion:r.literal(!0).optional()}),r.strictObject({operation:r.literal("terminate_checkout"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[v[3].omit({customerToken:!0}),v[4].omit({customerToken:!0}),v[5].omit({customerToken:!0}),v[6].omit({customerToken:!0}),v[7].omit({customerToken:!0})]).optional()}).refine(i=>!i.command||i.requestId===i.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:rt})]),ce=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:z.shape.run.shape.status}),H={scope:oe,customerId:r.uuid()},ze=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...H,outcome:r.literal("resolved"),target:ce,view:z.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((i,d)=>{i.outcome==="resolved"&&(i.access.type==="customer"!=(i.view!==null)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Qe=r.strictObject({...H,target:ce,view:z.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:z.shape.purchase.unwrap().nullable()}).superRefine((i,d)=>{let f=i.settlement;(f.acceptance==="accepted"!=(f.receiptPhase!==null)||f.acceptance==="accepted"&&f.basis!=="receipt"||f.acceptance==="unknown"&&(f.state!=="unknown"||f.basis!=="none")||f.acceptance!=="accepted"&&(f.operationId!==null||f.receiptId!==null)||f.acceptance==="not_accepted"&&(f.state!=="settled"||!["run_terminal","position_advanced"].includes(f.basis))||i.purchase&&(i.purchase.receiptId!==f.receiptId||i.purchase.operation&&i.purchase.operation.operationId!==f.operationId||i.purchase.quote&&i.purchase.quote.operationId!==f.operationId)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Be=r.strictObject({...H,target:ce,purchase:z.shape.purchase.unwrap(),paywallVersionId:r.uuid().optional()}).superRefine((i,d)=>{(!i.purchase.operation||typeof i.purchase.canReselect!="boolean"||i.purchase.quote&&i.purchase.quote.operationId!==i.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),Ye=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("none")}),r.strictObject({...H,outcome:r.literal("blocked")}),r.strictObject({...H,outcome:r.literal("found"),target:ce,start:r.strictObject({locale:v[0].shape.locale,parameters:v[0].shape.parameters}),purchase:Pe})]);var ot=G.options[0].refine(i=>!i.customer&&!i.customerData),at=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),Je=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:oe,customerId:r.uuid(),sessionId:r.uuid(),start:ot,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:je.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(at).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:Ve.nullable()})});function Ke(i){return Le({...i,namespace:"purchases",identity:[i.scope.projectId,i.scope.environment,i.customerId]})}function $e(i){let d=new URL(i.baseUrl??Ue).href,f=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function S(){i.assertCurrent();try{let C=await i.storage.read();if(i.assertCurrent(),!Number.isSafeInteger(C.revision)||C.revision<0)throw f();let c=C.entry===null?null:Je.parse(C.entry);if(c&&(c.baseUrl!==d||c.customerId!==i.customerId||c.scope.projectId!==i.scope.projectId||c.scope.environment!==i.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(c?.journal.entry&&(c.journal.entry.scope.projectId!==c.scope.projectId||c.journal.entry.scope.environment!==c.scope.environment||c.journal.entry.funnelId!==c.start.funnelId||c.journal.entry.runId!==c.run?.id||c.journal.entry.versionId!==c.run?.versionId)||c?.operationCommand&&!c.purchases.some(q=>q.operationId===c.operationCommand?.operationId))throw f();return{revision:C.revision,entry:c}}catch(C){throw C instanceof l?C:f()}}async function W(C){for(let c=0;c<8;c++){let q=await S(),O=C(structuredClone(q.entry));if(JSON.stringify(O)===JSON.stringify(q.entry))return O;O&&Je.parse(O),i.assertCurrent();let j;try{j=await i.storage.write(q.revision,O)}catch{throw f()}if(i.assertCurrent(),j!==null){if(!Number.isSafeInteger(j)||j<=q.revision)throw f();return O}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:S,update:W,baseUrl:d}}var it=5*6e4,st=2e3;function ut(i,d){let f=i.purchases.find(S=>S.type==="checkout");if(!i.actions.includes("continue_checkout")||f?.type!=="checkout"||d!==void 0&&f.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return f.checkoutUrl}function Lt(i){let d={...i,scope:{...i.scope},executionPolicy:structuredClone(i.executionPolicy)},f=d.session.snapshot();if(!f)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:S,sessionId:W}=f,C=!1,c=null,q,O,j=null,F=!1,T,X,Z,E={mode:"idle",status:"idle",actions:["start"],purchases:[]},g=new Map,ve=new Map,U=new Map,le=new AbortController,ee=new Set,Q=xe(d),te=De(Q.request);function B(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function P(){if(C||d.session.snapshot()?.customerId!==S)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let I=$e({...d,customerId:S,assertCurrent:P,storage:d.storage??Ke({baseUrl:d.baseUrl,scope:d.scope,customerId:S})}),We=d.session.subscribeIdentity(Re);function Re(){C||(C=!0,clearTimeout(Z),le.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),We(),c?.reset(),c=null,j=null,Q.dispose(),ee.clear(),g.clear(),U.clear())}function R(e){P();let t=JSON.stringify(e)!==JSON.stringify(E);E=e,clearTimeout(Z),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Z=setTimeout(()=>{M().catch(()=>{})},5e3)),t&&ge(d.onRecovery,structuredClone(e));for(let n of t?ee:[]){if(C)break;ge(n,structuredClone(e))}return structuredClone(e)}function y(e){if(P(),!e||e.start.requestId!==O)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function _(e){let t=[...e.purchases],n=e.journal.entry?.purchase;return n&&!t.some(o=>o.operationId===n.operationId)&&t.push({receiptId:n.receiptId,operationId:n.operationId,terminal:null}),t}function x(e){let t=_(e),n=F&&t.length>0&&t.every(o=>o.terminal==="native"&&D(g.get(o.operationId))==="native")&&t.some(o=>{let s=g.get(o.operationId);return!!s&&J(s)&&U.get(o.operationId)===!0});return e.run&&(n||!["running","waiting"].includes(e.run.status))&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&t.every(o=>o.terminal!==null)}function A(e,t){let n=e.journal.entry?.command??e.journal.entry?.closeCommand,o=_(e).map(w=>{let k=g.get(w.operationId);return w.terminal&&!k?{type:w.terminal,operationId:w.operationId}:se({quote:k?.quote??null,operation:k??null,requestId:n?.requestId??null,pending:!1,destroyed:!1,canReselect:U.get(w.operationId)===!0})}),s=o.filter(w=>!["complete","native"].includes(w.type)),u=s[0],a=s.length===1&&u?.operationId?g.get(u.operationId):void 0;if(a&&(u?.type==="checkout"||u?.type==="cancel"))try{K({allowed:e.allowed.filter(w=>d.executionPolicy.allowed.includes(w))},a.quote)}catch(w){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:B(w)}}let m;if(t==="operation"&&!n&&u?.type==="cancel"&&a?.quote&&!a.problem&&!a.confirmedAt)try{K({allowed:e.allowed.filter(w=>d.executionPolicy.allowed.includes(w))},a.quote),Date.parse(a.quote.expiresAt)>Date.now()&&(m={operationId:a.operationId,quote:a.quote})}catch{}let p=o.length>0&&s.length===0,h=x(e)||t==="operation"&&p&&!n&&!e.operationCommand?"complete":u?.type==="checkout"?"checkout":u?.type==="fulfillment"?"fulfillment":u?.type==="recording"?"recording":n||e.operationCommand||u&&u.type!=="cancel"||t==="operation"&&!m?"waiting_result":"ready";return{mode:t,status:h,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...x(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...s.length===1&&u?.type==="checkout"?["continue_checkout"]:[]]}}function D(e){let t=se({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&U.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function de(e){if(!e.operation)return;let t=ae.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let n=ue(g.get(t.operationId)??null,t);g.set(t.operationId,n),n===t&&U.set(t.operationId,e.canReselect===!0)}async function Xe(e){P();for(let n of[e.purchase,e.run.paywall])n&&de(n);let t=await I.update(n=>{if(y(n),n.run&&(n.run.id!==e.run.id||n.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=_(n);for(let s of[e.purchase,e.run.paywall]){let u=s?.operation?.operationId??s?.quote?.operationId;if(!s||!u)continue;let a=o.find(p=>p.operationId===u);if(a&&a.receiptId!==s.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=D(g.get(u));a?a.terminal??=m:o.push({receiptId:s.receiptId,operationId:u,terminal:m})}return{...n,purchases:o,run:n.run&&(n.run.revision>e.run.revision||!["running","waiting"].includes(n.run.status)&&["running","waiting"].includes(e.run.status))?n.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});y(t),t.run&&!["running","waiting"].includes(t.run.status)&&_(t).some(n=>!n.terminal)&&(t=await L(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(n=>!!n)))),y(t),R(A(t,"run"))}function Ze(){return{async read(){let{entry:e}=await I.read();return y(e),structuredClone(e.journal)},async write(e,t){let n=null;return await I.update(o=>{if(y(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return n=null,o.journal.revision!==e?o:(n=e+1,{...o,journal:{revision:n,entry:t}})}),n}}}async function L(e,t=!1,n=new Set){y(e);let o=_(e);for(let u of o){if(u.terminal)continue;let a=n.has(u.operationId)?g.get(u.operationId):void 0;if(a??=await V(e,u),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(a.merchantExecution&&a.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&se({quote:a.quote??null,operation:a,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let m=J(a)?await te.update({operationId:u.operationId,intent:"cancel"}):await te.attach({operationId:u.operationId,intent:"cancel"});if(a=ae.parse(m.operation),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");a=await V(e,u)}g.set(u.operationId,ue(g.get(u.operationId)??null,a))}let s=await I.update(u=>{y(u);let a=u.operationCommand&&g.get(u.operationCommand.operationId);return{...u,...a&&(a.confirmedAt||a.merchantExecution||!qe(a))?{operationCommand:void 0}:{},purchases:_(u).map(m=>({...m,terminal:m.terminal??D(g.get(m.operationId))}))}});return y(s),s}async function Y(e){P();let t=await Q.request("funnels",e);return P(),t}async function et(e){try{return await Y(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return Y({...e,intent:"resume"})}}async function tt(){let e=$(Ye,await Y({operation:"find_purchase"}));if(e.customerId!==S||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:n}=e;return await I.update(o=>o&&!x(o)?o:{schemaVersion:1,baseUrl:I.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...n,terminal:null}],journal:{revision:0,entry:null}}),"found"}let ne;function pe(e){let t=ne;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<it))return t.job;let n={at:Date.now(),job:tt().then(o=>(n.outcome=o,n.at=Date.now(),o),o=>{throw ne===n&&(ne=void 0),o})};return ne=n,n.job}async function V(e,t,n="recover_purchase",o=!1){let s=$(Be,await Y({operation:n,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId},...o?{includePaywallVersion:!0}:{}}));if(me(e,s),s.purchase.receiptId!==t.receiptId||s.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return de(s.purchase),o&&s.paywallVersionId&&ve.set(t.operationId,s.paywallVersionId),g.get(t.operationId)}async function Se(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let n=$(Qe,await Y({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(me(e,n),n.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");n.purchase&&de(n.purchase);let o=await I.update(s=>{y(s);let u=_(s),{receiptId:a,operationId:m}=n.settlement;if(a&&m){let h=u.find(w=>w.operationId===m);if(h&&h.receiptId!==a)throw new l("INVALID_RESPONSE","Original Receipt changed");h||u.push({receiptId:a,operationId:m,terminal:D(g.get(m))})}let p=n.settlement.state==="settled"?He(s.journal.entry,t.requestId):s.journal.entry;return{...s,purchases:u,journal:p===s.journal.entry?s.journal:{revision:s.journal.revision+1,entry:p}}});y(o),e=o}return e}function me(e,t){if(t.customerId!==S||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function fe(e,t){if(y(e),e.run&&(e=await Se(e)),!_(e).length&&x(e))return R(A(e,"operation"));if(!_(e).length)return R({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(t)});F=!0;let n=_(e);if(e.run&&["running","waiting"].includes(e.run.status)&&n.every(s=>s.terminal==="native"))for(let s of n)D(g.get(s.operationId))!=="native"&&await V(e,s);let o=await L(e);return R(A(o,"operation"))}async function re(e,t=!1,n=!0,o=!1){if(O=e.start.requestId,j=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!c){let s=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await et(s)}catch(h){if(!e.run&&h instanceof l&&(h.status===void 0||h.status>=500))return R({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:E.purchases,error:B(h)});throw h}let a=$(ze,u);if(a.customerId!==S||a.scope.projectId!==d.scope.projectId||a.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(a.outcome==="unknown")return R({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:E.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});me(e,a);let m=await I.update(h=>(y(h),{...h,run:{id:a.target.runId,versionId:a.target.versionId,status:a.target.status,revision:a.view?.revision??h.run?.revision??0,runExpiresAt:a.target.runExpiresAt}}));if(y(m),e=m,a.access.type==="operation_only")return fe(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Se(e);let p=a.view;if(p.locale!==e.start.locale||!Me(p.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");c=Ge({...d,customerRun:{runId:a.target.runId,customerId:S,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(h=>d.executionPolicy.allowed.includes(h))},funnelCommandStorage:Ze(),onAcceptedResponse:Xe},{scope:a.scope,run:p})}try{let s=o&&q?.controller===c?performance.now()-q.at:1/0;(s>=st||c.pendingCommands?.length||(c.viewAgeMs??0)<s)&&(q=void 0,await c.get(),q={controller:c,at:performance.now()}),c.view?.pendingRequest?.requestId===e.start.requestId&&!c.pendingCommands?.length&&await c.resume(c.view.pendingRequest.requestId);for(let a of c.pendingCommands??[])a.operation!=="close"&&await c.settle?.(a.requestId);c.pendingCommands?.length&&await c.retry(),P();let u=(await I.read()).entry;return y(u),R(A(u,"run"))}catch(s){if(P(),n&&s instanceof l&&(s.status===401||s.status===409&&s.reason==="STATE_CHANGED")){c.reset(),c=null;let u=(await I.read()).entry;return y(u),re(u,!1,!1,!1)}throw s}}function N(e,t="read",n){if(P(),T)return t==="read"||t===X?T:T.then(()=>N(e,t,n),()=>N(e,t,n));clearTimeout(Z);let o=e().catch(s=>{throw!C&&!n?.(s)&&R({mode:"blocked",status:"blocked",actions:["refresh"],purchases:E.purchases,error:B(s)}),s});return T=o,X=t,o.then(()=>{T===o&&(T=void 0,X=void 0)},()=>{T===o&&(T=void 0,X=void 0)}),o}function M(e){let t=e?.reuseRecentRead===!0;return N(async()=>{let{entry:n}=await I.read();if(!n||x(n)){if(await pe(!1)==="blocked")return Ce();({entry:n}=await I.read())}return n?(O&&n.start.requestId!==O&&(c?.reset(),c=null,g.clear(),U.clear(),F=!1),F&&O===n.start.requestId?fe(n,E.error):re(n,!1,!0,t)):R({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function Ce(){return R({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function Ee(){let e=await M();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:N(async()=>{let t=(await I.read()).entry;if(y(t),!F){if(!c?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=c.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(J(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return R(A(t,"run"));if(c.pendingCommands?.length)await c.retry();else{let w=c.view;await c.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:w.nodeId,visit:w.visit,revision:w.revision,input:{type:"paywall_confirm",operationId:w.paywall.quote.operationId,...w.paywall.quote.merchantTerms?{merchantConfirmation:ye(w.paywall.quote.merchantTerms)}:{}}})}let h=(await I.read()).entry;return y(h),R(A(h,"run"))}let n=t.operationCommand?.operationId??E.confirmation?.operationId,o=n&&g.get(n);if(!n||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");K({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await I.update(p=>{if(y(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==n)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:n,intent:"confirm"}}});let s={operationId:n,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:ye(o.quote.merchantTerms)}:{}},u=J(o)?await te.update(s):await te.attach(s),a=ae.parse(u.operation);if(P(),u.operation.operationId!==n)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");g.set(n,ue(o,a));let m=(await I.read()).entry;return y(m),R(A(await L(m,!1,new Set([n])),"operation"))},"confirm")}function nt(e){let t=e?.quote;return t&&ie(t)&&t.timing==="immediate"&&t.execution.provider==="merchant"&&(e.confirmedAt||e.merchantExecution)?t:null}function be(){if(E.mode!=="operation"||E.status==="blocked")return null;let e=E.purchases.filter(({type:n})=>n!=="complete"&&n!=="native"),t=e.length===1&&e[0]?.operationId;return t?nt(g.get(t)):null}async function Oe(){P();let{entry:e}=await I.read();return e?x(e)?"finished":"pending":"none"}return{get controller(){return c},get recovery(){return structuredClone(E)},get attempt(){return P(),structuredClone(j)},get identitySignal(){return le.signal},get customerId(){return S},retained:Oe,async findPurchase(){let e=await Oe();if(e==="pending")return e;let t=await pe(!0);return P(),t==="none"?e:t},async readPaywall(e){P();let t=Ae(e),[n,{readPaywallContent:o},{validateResourceCheck:s}]=await Promise.all([Fe(Q.request,"resolvePaywall"),import("./paywall-content-DSZJWOTF.js"),import("./check-response-EYOK5EU5.js")]);P();let u=n.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),a=await Ne(Q.request,n,u);s(u,a.paywall.check,a.scope);let m=await o(d,a.paywall);if(P(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},get canRestoreUpgradePaywall(){return be()!==null},recoverUpgradePaywall(){let e=be();return e?this.recoverPurchasePaywall(void 0,e.operationId):Promise.resolve(null)},async recoverPurchasePaywall(e,t){if(E.mode!=="operation"||E.status==="blocked")return null;let{entry:n}=await I.read();if(!n?.run)return null;y(n);let o=_(n),s=o.filter(b=>!b.terminal),u=o.filter(b=>b.terminal==="complete"),a=s.length===1?s[0]:s.length?void 0:u.find(b=>e&&e.runId===n.run?.id&&b.receiptId===e.receiptId)??(u.length===1?u[0]:void 0);if(!a||t&&a.operationId!==t)return null;let m=e?.runId===n.run.id&&e.receiptId===a.receiptId?e.view:void 0,p;try{p=await V(n,a,"recover_purchase",!0)}catch(b){if(!(b instanceof l&&b.status===400&&b.code==="INVALID_REQUEST"))throw b;if(!m)return null;p=await V(n,a)}let h=p.quote;if(!h||ie(h)&&(h.timing!=="immediate"||h.execution.provider!=="merchant")||!(p.confirmedAt||p.merchantExecution||p.checkoutUrl||D(p)==="complete"))return null;D(p)!=="complete"&&K({allowed:n.allowed.filter(b=>d.executionPolicy.allowed.includes(b))},h);let w=ve.get(a.operationId),k=n.start.parameters?.commerce,_e=n.start.locale??"en",he=m;if(w){if(typeof k!="object"||!k||!("provider"in k)||typeof k.provider!="string"||!("currency"in k)||typeof k.currency!="string")return null;he=await this.readPaywall({paywallVersionId:w,locale:_e,commerce:{provider:k.provider,currency:k.currency,...ie(h)?{intent:"subscription_change"}:{}}})}if(!he)return null;P();let ke=he,Ie=!1,we=async()=>{throw new l("PURCHASE_PENDING","Only the original purchase can be recovered")};return{signal:le.signal,view:ke,quote:h,locale:_e,get operation(){return p},get canReselect(){return U.get(a.operationId)===!0},async refresh(){return ke},preview:we,confirm:we,cancel:we,async read(){if(Ie)throw new DOMException("Purchase view closed","AbortError");p=await V(n,a);let b=await L(n,!1,new Set([a.operationId]));return Ie||R(A(b,"operation")),structuredClone(p)},destroy(){Ie=!0}}},start(e){let t=G.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return N(async()=>{let n=(await I.read()).entry;if((!n||x(n))&&await pe(!0)==="blocked")return Ce();let o=await I.update(s=>{if(s&&!x(s)){if(s.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return s}return{schemaVersion:1,baseUrl:I.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return O!==o.start.requestId&&(c?.reset(),c=null,g.clear(),U.clear(),F=!1),F?fe(o,E.error):re(o,!0,!0,!0)},`start:${t.funnelId}`)},refresh:M,confirm:Ee,retry:()=>F?Ee():N(async()=>{let{entry:e}=await I.read();return e?re(e,!0):R({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return c?.view?N(async()=>{if(!c?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(c.pendingCommands?.find(n=>n.operation==="close"))await c.retry();else if(["running","waiting"].includes(c.view.status)){let n=c.view;await c.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision})}let t=(await I.read()).entry;return y(t),R(A(t,"run"))},"close"):M()},async continueCheckout(e,t){let n=t?await N(async()=>{let{entry:o}=await I.read();if(y(o),!o.run||!_(o).some(u=>u.operationId===t&&!u.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let s=await L(o);return R(A(s,F?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await M();P(),await e(ut(n,t))},async terminateCheckout(e){let t=await M();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return N(async()=>{let{entry:o}=await I.read();y(o);let s=_(o).find(a=>a.operationId===e&&!a.terminal);if(!s||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await V(o,s,"terminate_checkout");let u=await L(o,!1,new Set([e]));return R(A(u,F?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return ee.add(e),()=>{ee.delete(e)}},destroy:Re}}export{Ke as a,ut as b,Lt as c};