@tinkerlandai/longplay-sdk 0.10.34 → 0.10.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +49 -2
  3. package/README.zh-CN.md +20 -3
  4. package/dist/check-response-GZZRWBEA.js +1 -0
  5. package/dist/chunk-2FE4FTPH.js +1 -0
  6. package/dist/chunk-3NCMYTNG.js +1 -0
  7. package/dist/chunk-44U3FOBB.js +1 -0
  8. package/dist/chunk-56BYGPQ6.js +1 -0
  9. package/dist/chunk-73NP72FV.js +1 -0
  10. package/dist/{chunk-7VRZYSTR.js → chunk-BLVBUN2R.js} +1 -1
  11. package/dist/chunk-BOVN2BE3.js +1 -0
  12. package/dist/chunk-BQRS7Y4K.js +1 -0
  13. package/dist/chunk-CIP5SQ5Y.js +1 -0
  14. package/dist/chunk-CKKIB2HC.js +1 -0
  15. package/dist/chunk-EM3MGDPG.js +1 -0
  16. package/dist/chunk-ETK6GC5P.js +1 -0
  17. package/dist/chunk-EUTWY7A2.js +1 -0
  18. package/dist/{chunk-TYY3MUTF.js → chunk-FMDC6N4W.js} +1 -1
  19. package/dist/chunk-GZRRVHYK.js +1 -0
  20. package/dist/{chunk-MIBRUDIS.js → chunk-KE26KWIU.js} +1 -1
  21. package/dist/{chunk-I6TSQQ5N.js → chunk-KPDHY76A.js} +1 -1
  22. package/dist/{chunk-FYQXSGRT.js → chunk-LF2UIJYD.js} +1 -1
  23. package/dist/{chunk-UWLEGMWX.js → chunk-MSK3VZ3A.js} +1 -1
  24. package/dist/{chunk-X4W22IH6.js → chunk-OX7PA64E.js} +1 -1
  25. package/dist/chunk-PUR5CYWX.js +1 -0
  26. package/dist/{chunk-7NELM6EH.js → chunk-RML52BOR.js} +1 -1
  27. package/dist/chunk-RNEF4MZW.js +1 -0
  28. package/dist/chunk-SFHIFCXG.js +1 -0
  29. package/dist/{chunk-HQITRRHF.js → chunk-SXBM3DWK.js} +1 -1
  30. package/dist/chunk-TAFALMQN.js +1 -0
  31. package/dist/chunk-TJGIT5CU.js +1 -0
  32. package/dist/{chunk-6T575JKD.js → chunk-TLZP7BW6.js} +1 -1
  33. package/dist/chunk-TOTRALYQ.js +10 -0
  34. package/dist/chunk-U4RSRFZY.js +1 -0
  35. package/dist/chunk-UVRT4MY6.js +1 -0
  36. package/dist/chunk-V7MMTILA.js +1 -0
  37. package/dist/chunk-V7PFLFHE.js +1 -0
  38. package/dist/{chunk-BXPXJARS.js → chunk-VEX2FOFZ.js} +1 -1
  39. package/dist/chunk-W32FI2A2.js +1 -0
  40. package/dist/chunk-W6OQTXLL.js +1 -0
  41. package/dist/{chunk-EQPEUPMG.js → chunk-WZR2XCSJ.js} +1 -1
  42. package/dist/{chunk-U6UHASIB.js → chunk-XUGEOELU.js} +1 -1
  43. package/dist/chunk-YVXLCQGM.js +1 -0
  44. package/dist/content-AJDTSI7A.js +1 -0
  45. package/dist/funnel-host-purchase-Z7FCJ5CX.js +1 -0
  46. package/dist/{funnel-local-client-BeGBvi3z.d.ts → funnel-local-client-Dz1dTgES.d.ts} +22 -22
  47. package/dist/funnel-paywall-prerender-QHCUZZY3.js +1 -0
  48. package/dist/{funnel-process-client-C6QKDZun.d.ts → funnel-process-client-D6qjStm2.d.ts} +1 -1
  49. package/dist/funnel-runtime-host-UKSOOA4H.js +1 -0
  50. package/dist/index.d.ts +192 -58
  51. package/dist/index.js +1 -1
  52. package/dist/merchant-bridge-contracts-EAE4HQE4.js +1 -0
  53. package/dist/native-shell.js +1 -1
  54. package/dist/openrouter.js +1 -1
  55. package/dist/operation-contracts-HS4M2UXN.js +1 -0
  56. package/dist/page.js +1 -1
  57. package/dist/paywall-VYUBYBUI.js +1 -0
  58. package/dist/paywall-content-YQAVSO2T.js +1 -0
  59. package/dist/paywall-session-E5V42XUT.js +1 -0
  60. package/dist/popup.d.ts +18 -0
  61. package/dist/popup.js +1 -1
  62. package/dist/react-native.d.ts +4 -4
  63. package/dist/react-native.js +1 -1
  64. package/dist/screen-renderer-R5GH7XLV.js +1 -0
  65. package/dist/server.d.ts +2 -2
  66. package/dist/server.js +2 -2
  67. package/dist/visual.js +1 -1
  68. package/package.json +1 -1
  69. package/dist/chunk-3JJYWRA3.js +0 -1
  70. package/dist/chunk-4WZVC4TM.js +0 -1
  71. package/dist/chunk-5JWMP4YD.js +0 -1
  72. package/dist/chunk-EHDHWYVJ.js +0 -1
  73. package/dist/chunk-ERJP2GBD.js +0 -1
  74. package/dist/chunk-ILEDKSRQ.js +0 -1
  75. package/dist/chunk-ITGERPCJ.js +0 -1
  76. package/dist/chunk-N7YXDSQL.js +0 -1
  77. package/dist/chunk-NAZU3EEJ.js +0 -1
  78. package/dist/chunk-QBA3B4YK.js +0 -1
  79. package/dist/chunk-R23IGK5U.js +0 -1
  80. package/dist/chunk-R4FDIYMN.js +0 -1
  81. package/dist/chunk-RKPAIF6U.js +0 -1
  82. package/dist/chunk-SCC3O2RD.js +0 -1
  83. package/dist/chunk-TDSATEGE.js +0 -10
  84. package/dist/chunk-THMGTRXP.js +0 -1
  85. package/dist/chunk-WKIR2EQG.js +0 -1
  86. package/dist/chunk-WTVLNUMS.js +0 -1
  87. package/dist/content-ORU4ODJQ.js +0 -1
  88. package/dist/funnel-host-purchase-BEFE3N3E.js +0 -1
  89. package/dist/funnel-runtime-host-V6TYIDX3.js +0 -1
  90. package/dist/merchant-bridge-contracts-ZUQ6SGXZ.js +0 -1
  91. package/dist/operation-contracts-443N2P3A.js +0 -1
  92. package/dist/paywall-HO4PS472.js +0 -1
  93. package/dist/paywall-session-MZXFOPTR.js +0 -1
  94. package/dist/screen-renderer-W7ZGBFIR.js +0 -1
@@ -1 +1 @@
1
- import"./chunk-HQITRRHF.js";import"./chunk-5HJYR6Z4.js";import"./chunk-WTVLNUMS.js";import"./chunk-VYFSRHXM.js";import{a as i}from"./chunk-X4W22IH6.js";import"./chunk-R4FDIYMN.js";import"./chunk-WKIR2EQG.js";import{b as A}from"./chunk-VF6QMMEA.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-SXBM3DWK.js";import"./chunk-5HJYR6Z4.js";import"./chunk-56BYGPQ6.js";import"./chunk-VYFSRHXM.js";import"./chunk-TJGIT5CU.js";import{a as i}from"./chunk-OX7PA64E.js";import"./chunk-V7MMTILA.js";import"./chunk-EM3MGDPG.js";import{b as A}from"./chunk-VF6QMMEA.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-44U3FOBB.js";import"./chunk-WZR2XCSJ.js";import"./chunk-7MNJH5GB.js";import"./chunk-CIP5SQ5Y.js";import"./chunk-CKKIB2HC.js";import"./chunk-BOVN2BE3.js";import"./chunk-PUR5CYWX.js";import"./chunk-TAFALMQN.js";import"./chunk-ZGCKQWQ5.js";import"./chunk-VEX2FOFZ.js";import"./chunk-5HJYR6Z4.js";import"./chunk-VYFSRHXM.js";import"./chunk-BQRS7Y4K.js";import"./chunk-U4RSRFZY.js";import"./chunk-KE26KWIU.js";import"./chunk-TJGIT5CU.js";import"./chunk-V7MMTILA.js";import"./chunk-VF6QMMEA.js";import"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.js";import"./chunk-WOT6VMZA.js";export{o as apiOperations};
package/dist/page.js CHANGED
@@ -1 +1 @@
1
- import{d as o,e as r,f as e,g as f}from"./chunk-TYY3MUTF.js";import"./chunk-6T575JKD.js";import"./chunk-3VUPVXAV.js";import"./chunk-WKIR2EQG.js";import"./chunk-DSPLGTQI.js";import"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.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-FMDC6N4W.js";import"./chunk-TLZP7BW6.js";import"./chunk-3VUPVXAV.js";import"./chunk-EM3MGDPG.js";import"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.js";import"./chunk-DSPLGTQI.js";import"./chunk-WOT6VMZA.js";export{f as createPageExperiments,o as mergeQueryStrings,r as pageAttributes,e as readPayload};
@@ -0,0 +1 @@
1
+ import{a as gt,c as vt,d as Fe,f as Ct,i as Pt}from"./chunk-SFHIFCXG.js";import{b as Be}from"./chunk-W32FI2A2.js";import{d as pt,e as mt,f as ht,h as je,i as Ae,j as yt,k as wt,l as bt}from"./chunk-XUGEOELU.js";import{a as ct,c as Ve,d as lt,e as ut}from"./chunk-3NCMYTNG.js";import{b as ne}from"./chunk-VEX2FOFZ.js";import{b as He,d as dt,g as ft}from"./chunk-V7PFLFHE.js";import"./chunk-56BYGPQ6.js";import"./chunk-VYFSRHXM.js";import{ba as ye,da as we}from"./chunk-BQRS7Y4K.js";import{c as ce,j as he}from"./chunk-U4RSRFZY.js";import{c as $e}from"./chunk-KE26KWIU.js";import"./chunk-TJGIT5CU.js";import{a as v}from"./chunk-OX7PA64E.js";import"./chunk-V7MMTILA.js";import"./chunk-EM3MGDPG.js";import"./chunk-VF6QMMEA.js";import"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.js";import{a as j}from"./chunk-DSPLGTQI.js";import"./chunk-WOT6VMZA.js";async function kt(T,a,A){if(a.status!=="complete")throw new v("INVALID_RESPONSE","A verified completed purchase is required");let g=T?he.parse(T):null;if(await A.onComplete?.(a),!g||!A.check)return;let D=he.parse(await A.check());if(D.internal_feature_id!==g.internal_feature_id||D.quantity!==g.quantity||g.observation!==void 0&&(D.observation===void 0||D.observation.requirementDigest!==g.observation.requirementDigest||D.observation.authority!==g.observation.authority||$e(D.observation.subject)!==$e(g.observation.subject)))throw new v("INVALID_RESPONSE","The access requirement changed");D.allowed&&await A.onAccessGranted?.(D)}function Qe(T){return Object.entries(T.document.buttons).filter(([,a])=>a.type==="checkout"&&a.product.type==="fixed"&&!ne(a.product,{},T.capabilities)).map(([a])=>a)}function Et(T,a){let A=a.lines[0];if(a.lines.length!==1||!A)return;let g=A.productVersionId,{screen:D,buttons:F}=T.document,E=new Map((A.prepaid??[]).map(d=>[d.internal_feature_id,d.quantity]));function Q(d,f){if(d.hidden)return!1;if(d.type==="plan_picker"&&T.capabilities.pickers[d.id]?.options.includes(g))return f[d.id]=g,!0;if(d.type==="quantity_picker"){let V=E.get(d.internalFeatureId);return V!==void 0&&(!d.bind?.plan||d.bind.plan===g)&&(f[d.id]=V),!1}if(d.type==="button"&&d.action){let V=F[d.action];return V?.type==="checkout"&&V.product.type==="fixed"&&V.product.productVersionId===g}if(d.type!=="stack")return!1;let $=d.interaction,r=d.bind?.plan===g;for(let[V,p]of d.children.entries()){let J={},R=Q(p,J);if($?.type==="toggle"||$?.type==="tabs"){if(!R)continue;return f[d.id]=$.type==="toggle"?V===0:p.id,Object.assign(f,J),!0}Object.assign(f,J),R&&(r=!0,$?.type==="select"&&$.purpose==="product"&&$.pickerId&&p.type==="stack"&&p.bind?.plan===g&&(f[d.id]=p.id,f[$.pickerId]=g))}return r}for(let d of D.pages){let f={__page:d.id};if(Q(d.root,f))return f}}async function dn(T,a,A){let g=a.focusAtReveal?()=>{}:je(T.ownerDocument),D=()=>{E.finish("dismissed"),g()},F=()=>D(),E=yt(T,a,"paywall",()=>{D(),j(a.onDismiss)},gt);a.signal?.throwIfAborted(),a.signal?.addEventListener("abort",F,{once:!0});let Q=null,d,f,$;try{if(E.start(!0,a.loadingDocument?.screen.strings.defaultLocale,a.loadingDocument??null),E.cancelled)throw new DOMException("Presentation cancelled","AbortError");if(Q=a.check?he.parse(await E.wait(a.check(),Ae)):null,Q?.allowed)return E.finish("skipped"),a.signal?.removeEventListener("abort",F),g(),await a.onAccessGranted?.(Q),{check:Q,host:null};let[e,t]=await Promise.allSettled([E.wait(import("./screen-renderer-R5GH7XLV.js")),E.wait(a.start().then(i=>(E.cancelled&&i.destroy(),i)),Ae)]);if(e.status==="rejected")throw t.status==="fulfilled"&&t.value.destroy(),e.reason;if(t.status==="rejected")throw t.reason;$=e.value,d=t.value,a.signal?.throwIfAborted(),d.signal?.throwIfAborted(),d.signal?.addEventListener("abort",F,{once:!0});let n=d.view??await E.wait(d.refresh(),Ae);if(!n)throw new v("INVALID_RESPONSE","Paywall presentation is missing");d.signal?.throwIfAborted(),f=n}catch(e){throw E.finish("error",e),a.signal?.removeEventListener("abort",F),d?.signal?.removeEventListener("abort",F),d?.destroy(),g(),e}let r=d,{mountScreenPreview:V}=$,p=T.ownerDocument,J=new AbortController,R=p.createElement("section"),re=p.createElement("div"),G=p.createElement("div"),l=p.createElement("p"),y=p.createElement("button"),C=p.createElement("button"),x=p.createElement("dialog"),s=f.document.screen.strings.defaultLocale.startsWith("zh"),xt=s?"\u6B63\u5728\u5904\u7406\u2026":"Processing\u2026",It=s?"\u6B63\u5728\u51C6\u5907\u62A5\u4EF7\u2026":"Preparing your price\u2026",O=vt(f.document.screen.theme);R.dataset.indianaPaywall="",R.setAttribute("aria-label",f.document.name),R.style.cssText=O.root,G.style.cssText=O.controls,l.style.cssText=O.message,l.setAttribute("role","status"),C.style.cssText=O.link,C.textContent=s?"\u5173\u95ED":"Close",y.style.cssText=O.secondary,y.textContent=s?"\u91CD\u8BD5":"Retry",y.hidden=!0,G.append(l,y,C),R.append(re,G);let Ge=()=>{let e=K??G,t=[...e.children].every(i=>i===l?!l.textContent:i.hidden),n=[...e.children].some(i=>i===C?!1:i===l?!!l.textContent:!i.hidden);e.style.cssText=t?O.controls.replace(/padding:[^;]+/,"padding:0"):n?`${O.controls};${O.pinned}`:O.controls,Oe()},We=typeof MutationObserver>"u"?void 0:new MutationObserver(Ge);We?.observe(R,{attributes:!0,attributeFilter:["hidden"],characterData:!0,childList:!0,subtree:!0});let be=f.document.presentation,At=Object.entries(f.document.buttons).filter(([,e])=>e.type==="close").map(([e])=>e),U,ze,Re=!1,Ye=JSON.stringify(f.capabilities),Je=e=>Z&&!ue?Object.entries(e.document.buttons).filter(([,t])=>t.type==="checkout").map(([t])=>t):Qe(e);function Se(e){if(h)return;f=e;let t=JSON.stringify(e.capabilities);t!==Ye&&(U?.updateCapabilities(e.capabilities,Je(e)),Ye=t),Tt(e),de()}let P,Te=0;function Oe(){let e=p.defaultView;if(!P?.responsive||!e)return;let t=K??G,n=e.innerHeight-(P.type==="modal"?32:0);t.style.maxHeight=`${Math.max(1,n)}px`,t.style.overflowY="auto",t.style.flexShrink="0",Te=Math.max(1,n-t.getBoundingClientRect().height),U?.resizeViewport?.(Te,e.innerWidth)}let h=!1,Z=!1,k=null,ge=!1,Ke=!1,ee=!1,De,Ne=!1,W,K;function Rt(){return Z||h||W||Ne?{type:"recover",operationId:r.operation?.operationId??r.quote?.operationId??null,requestId:null}:Ve(r)}let I=()=>!h&&!ge&&!W&&a.canInteract?.()!==!1,ie=!1,m=null,z=null,te=()=>a.checkoutNavigation==="after_confirmation"&&!!(a.terminateCheckout||a.resumeCheckout),le={},ue,H=null;function de(){if(!te()||!U?.updateCheckoutControls)return;let e=r.quote,t=!H&&!!e&&!!r.operation&&M(r.operation).type==="checkout",n=Object.entries(f.document.buttons).flatMap(([i,o])=>o.type==="checkout"?[{actionId:i,policy:o}]:[]);U.updateCheckoutControls({actions:n.map(({actionId:i})=>i),resume:t?n.filter(({policy:i})=>Pe(e,f,i.product,le)).map(({actionId:i})=>i):[],resumeLabel:s?"\u7EE7\u7EED\u4ED8\u6B3E":"Continue checkout",busy:ue})}function Xe(){z?.remove(),z=null}async function _e(){if(H)return;if(a.resumeCheckout&&r.operation){await a.resumeCheckout(r.operation.operationId);return}let e=await r.read();if(M(e).type!=="checkout")return N(e,!1);I()&&(ve.delete(e.operationId),await ke(e))}function Ze(){l.textContent=s?"\u6682\u65F6\u65E0\u6CD5\u6253\u5F00\u4ED8\u6B3E\u9875\u9762\u3002\u8BF7\u91CD\u8BD5\u3002":"Couldn\u2019t open checkout. Try again.",y.hidden=!0}async function et(e=!1){let t=H;if(!t)return;y.hidden=!0;let n=Date.now()+2e4;for(;I();){let i=await r.read();if(i.operationId!==t.operationId)throw new v("PURCHASE_PENDING","The original Checkout changed");if(!I())break;let o=M(i);if(o.type==="native"){H=null,Xe(),k=t.selection,ie=!1,await pe();return}if(o.type==="complete"||o.type==="fulfillment"||o.type==="recording"){H=null,await N(i,!1);return}if(e&&o.type==="checkout"){e=!1;try{await a.terminateCheckout(t.operationId)}catch(u){j(a.onError,u)}}if(Date.now()>=n)break;await Be(1e3,p,J.signal)}h||Ze()}async function St(e,t){H={operationId:e,selection:t};let n=!1;try{await a.terminateCheckout(e)}catch(i){if(i instanceof v&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(i.code)){H=null,l.textContent=s?"\u8BF7\u7EE7\u7EED\u539F\u8BA2\u5355\uFF0C\u6216\u7B49\u5F85\u5B83\u8FC7\u671F\u540E\u518D\u66F4\u6362\u65B9\u6848\u3002":"Continue your original checkout, or wait for it to expire before changing plans.",j(a.onError,i);return}n=i instanceof v&&(i.status??0)>=500,j(a.onError,i)}I()&&await et(n)}function Tt(e){Z||k||r.quote||r.operation||(l.textContent=Object.values(e.capabilities.plans).some(t=>t.available)?"":s?"\u5F53\u524D\u8D26\u53F7\u6682\u65E0\u53EF\u8D2D\u4E70\u7684\u65B9\u6848\u3002":"No plans are currently available for this account.")}let ve=new Map,Ce=!1;function Pe(e,t,n,i){let o=e.lines.length===1?e.lines[0]:void 0,u=ne(n,i,t.capabilities);if(!o||!u||o.productVersionId!==u)return!1;let _;try{_=we(t.document.screen,u,i,t.capabilities)}catch{return!1}let b=Object.fromEntries((o.prepaid??[]).map(Y=>[Y.internal_feature_id,Y.quantity]));return[...new Set([...Object.keys(_),...Object.keys(b)])].every(Y=>(_[Y]??0)===(b[Y]??0))}let M=e=>ct({quote:r.quote,operation:e,requestId:null,pending:!1,destroyed:h,canReselect:r.canReselect});async function ke(e){let t=e.merchantExecution;if(!(!I()||!e.checkoutUrl||a.checkoutNavigation==="after_confirmation"&&M(e).type!=="checkout"||t?.type==="purchase"&&!["not_started","pending"].includes(t.paymentStatus)||ve.get(e.operationId)===e.checkoutUrl)){ve.set(e.operationId,e.checkoutUrl);try{a.onCheckoutUrl?await a.onCheckoutUrl(e.checkoutUrl):p.defaultView?.location.assign(e.checkoutUrl)}catch(n){throw ve.delete(e.operationId),n}}}let X=(e,t=!1)=>{if(e instanceof He)m=null,l.textContent=e.customerMessage(s);else if(t){let n=e instanceof v?e.code:void 0;n==="CAPABILITY_UNAVAILABLE"||n==="NOT_CONFIGURED"?(m=null,l.textContent=s?"\u6682\u65F6\u65E0\u6CD5\u4E3A\u6B64\u5957\u9910\u62A5\u4EF7\uFF0C\u4ED8\u6B3E\u5C1A\u672A\u5F00\u59CB\u3002":"Pricing for this plan is unavailable. Payment hasn\u2019t started."):r.canReselect===!0&&!k?l.textContent=s?"\u672A\u80FD\u53D6\u5F97\u62A5\u4EF7\uFF0C\u4ED8\u6B3E\u5C1A\u672A\u5F00\u59CB\u3002\u8BF7\u91CD\u65B0\u9009\u62E9\u5957\u9910\u3002":"We couldn\u2019t prepare your price. Payment hasn\u2019t started. Choose a plan again.":n==="COMMAND_PENDING"?l.textContent=s?"\u4ECD\u5728\u51C6\u5907\u62A5\u4EF7\uFF0C\u8BF7\u91CD\u8BD5\u4EE5\u67E5\u770B\u7ED3\u679C\u3002":"Your price is still being prepared. Retry to check the result.":l.textContent=s?"\u672A\u80FD\u53D6\u5F97\u62A5\u4EF7\uFF0C\u4ED8\u6B3E\u5C1A\u672A\u5F00\u59CB\u3002\u8BF7\u91CD\u8BD5\u3002":"We couldn\u2019t prepare your price. Payment hasn\u2019t started. Try again."}else l.textContent=e instanceof v&&(e.code==="NETWORK_ERROR"||e.code==="TIMEOUT")?Ct(e,s):e instanceof v?e.message:s?"\u64CD\u4F5C\u672A\u5B8C\u6210\uFF0C\u8BF7\u91CD\u8BD5\u3002":"This action couldn\u2019t be completed. Try again.";y.hidden=m===null,t&&!P?.responsive&&l.scrollIntoView?.({block:"nearest"}),j(t&&A?.quoteError?A.quoteError:a.onError,e)},Ee=new WeakMap;function xe(e){Z=e,y.disabled=e,U?.updateCapabilities?.(f.capabilities,Je(f));for(let t of z?.querySelectorAll("button")??[])e?(Ee.set(t,t.disabled),t.disabled=!0):Ee.has(t)&&(t.disabled=Ee.get(t),Ee.delete(t)),Fe(t)}function Le(){l.textContent=s?"\u6682\u65F6\u65E0\u6CD5\u64CD\u4F5C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"This action is unavailable right now. Try again in a moment."}async function Ot(e){if(a.beforeAction)try{await a.beforeAction()}catch(t){throw t instanceof He?(k=null,ie=!1,m=null):m=e,t}}async function L(e,t){if(Z||h)return;if(!I()){Le();return}let n=e===pe,i=n?It:xt,o=te()&&t!==void 0;ue=o?t:void 0,xe(!0),de(),y.hidden=!0,l.textContent=o?"":i;try{if((e!==_e||!a.resumeCheckout)&&await Ot(e),h)return;if(!I()){m=e,y.hidden=!1,Le();return}await e()}catch(u){h||X(u,n&&!o)}finally{ue=void 0,xe(!1),de(),l.textContent===i&&(l.textContent="")}}async function Dt(e){await kt(Q,e,a)}function tt(e){return Ve(r).type==="recording"||M(e).type==="recording"}function nt(e){let t=e.merchantTerms,n=t?.subscriptionTerms?.items??[],i=t?t.totalMinor:e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),o=t?n.length===1&&n[0]?.amountMinor===i&&n[0]:e.lines.length===1&&e.lines[0]?.catalogAmountMinor===i&&e.lines[0],u=i===null?ce(t.subtotalMinor-t.discountMinor,e.currency)+(s?" + \u5F85\u786E\u8BA4\u7A0E\u8D39":" + tax confirmed at checkout"):ce(i,e.currency)+(o?ye(o.interval,s?"zh-CN":"en",o.intervalCount??1):""),_=e.lines.map(b=>b.productName).join(", ");return{label:_?`${_} \xB7 ${u}`:u,recurring:o}}async function N(e,t=a.checkoutNavigation!=="after_confirmation"){if(h)return;if(!I()){m=async()=>N(await r.read()),y.hidden=!1;return}if(l.textContent=Pt(e.status,s),tt(e)){let o=e.merchantExecution?.type==="purchase"&&e.merchantExecution.recordingStatus==="failed";l.textContent=o?s?"\u4ED8\u6B3E\u548C\u5546\u6237\u5904\u7406\u5DF2\u5B8C\u6210\uFF0C\u4F46\u4EA4\u6613\u8BB0\u5F55\u5931\u8D25\u3002\u8BF7\u8054\u7CFB\u5546\u6237\u4FEE\u590D\uFF0C\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"Payment and fulfillment succeeded, but recording failed. Contact the merchant to repair this purchase; do not buy again.":s?"\u4ED8\u6B3E\u548C\u5546\u6237\u5904\u7406\u5DF2\u5B8C\u6210\uFF0C\u6B63\u5728\u786E\u8BA4\u4EA4\u6613\u8BB0\u5F55\u3002\u8BF7\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"Payment and merchant fulfillment are complete. Recording is pending confirmation; do not purchase again.",y.textContent=s?"\u67E5\u8BE2\u8BB0\u5F55":"Check recording",m=async()=>N(await r.read()),y.hidden=!1;return}if(e.problem){let o=e.problem;m=fe,y.textContent=s?"\u68C0\u67E5\u5E76\u6062\u590D\u539F\u64CD\u4F5C":"Check and recover original purchase",X(new v(o.code,o.reason==="RESULT_UNKNOWN"?s?"\u4ED8\u6B3E\u7ED3\u679C\u5C1A\u672A\u786E\u5B9A\uFF0C\u8BF7\u6062\u590D\u539F\u64CD\u4F5C\uFF0C\u6682\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"The payment result is unknown. Recover the original purchase before buying again.":o.phase==="fulfillment"?s?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u5546\u6237\u6743\u76CA\u5904\u7406\u9700\u8981\u6838\u5BF9\u3002":"Payment was recorded. Access fulfillment needs attention.":o.code==="CAPABILITY_UNAVAILABLE"?s?"\u5546\u6237\u5C1A\u4E0D\u652F\u6301\u672C\u6B21\u8D2D\u4E70\u6240\u9700\u7684\u5B8C\u6574\u80FD\u529B\uFF0C\u8BF7\u5904\u7406\u540E\u6062\u590D\u539F\u64CD\u4F5C\u3002":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":o.code==="NOT_CONFIGURED"?s?"\u4ED8\u6B3E\u670D\u52A1\u8FDE\u63A5\u9700\u8981\u5904\u7406\uFF0C\u8BF7\u8054\u7CFB\u5546\u6237\u540E\u6062\u590D\u539F\u64CD\u4F5C\u3002":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":s?"\u539F\u8D2D\u4E70\u64CD\u4F5C\u9700\u8981\u5904\u7406\uFF0C\u8BF7\u67E5\u8BE2\u6216\u6062\u590D\u6B64\u64CD\u4F5C\u3002":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,o));return}if(e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(l.textContent=s?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u6B63\u5728\u7B49\u5F85\u5546\u6237\u5B8C\u6210\u5904\u7406\u3002":"Payment was recorded. Waiting for merchant fulfillment."),e.status==="complete"){m=null,await Dt(e);return}if(e.status!=="pending"){if(r.canReselect===!1){l.textContent=s?"\u6B63\u5728\u6838\u5BF9\u539F\u8D2D\u4E70\u7ED3\u679C":"Checking the original purchase result",y.textContent=s?"\u67E5\u8BE2\u7ED3\u679C":"Check result",m=async()=>N(await r.read()),y.hidden=!1;return}e.status==="cancelled"?l.textContent=s?"\u8FD9\u7B14\u8D2D\u4E70\u5DF2\u53D6\u6D88\uFF0C\u53EF\u4EE5\u91CD\u65B0\u9009\u62E9\u65B9\u6848\u3002":"This purchase was cancelled. Choose a plan to start again.":e.status==="failed"&&(l.textContent=s?"\u8FD9\u7B14\u8D2D\u4E70\u672A\u80FD\u5B8C\u6210\uFF0C\u53EF\u4EE5\u91CD\u65B0\u9009\u62E9\u65B9\u6848\u3002":"This purchase didn\u2019t go through. Choose a plan to try again."),y.textContent=s?"\u91CD\u8BD5":"Retry",m=null,k=null;return}if(!t&&M(e).type==="checkout"){if(H){Ze();return}if(te()){l.textContent="",Ce=!1,m=null,de();return}let o=r.quote,u=o?.operationId===e.operationId?nt(o).label:"";l.textContent=Ce?u?s?`${u} \u5C1A\u672A\u4ED8\u6B3E\u3002\u518D\u6B21\u9009\u62E9\u8BE5\u65B9\u6848\u5373\u53EF\u7EE7\u7EED\u4ED8\u6B3E\u3002`:`${u} is still unpaid. Choose it again to continue paying.`:s?"\u4E4B\u524D\u7684\u8D2D\u4E70\u5C1A\u672A\u4ED8\u6B3E\u3002\u518D\u6B21\u9009\u62E9\u8BE5\u65B9\u6848\u5373\u53EF\u7EE7\u7EED\u4ED8\u6B3E\u3002":"Your earlier purchase is still unpaid. Choose that plan again to continue paying.":"",Ce=!1,m=null;return}await ke(e);let n=Date.now()+6e5,i=2e3;Re=!0,j(a.onObservationChange,!0);try{for(;!h&&Date.now()<n;){if(await Be(i,p,J.signal),h)return;if(!I()){m=async()=>N(await r.read()),y.hidden=!1;return}let o=await r.read();if(!t&&M(o).type==="checkout"){await N(o,!1);return}if(!o.problem&&o.status==="pending"&&await ke(o),o.status!=="pending"||o.problem||tt(o)){await N(o);return}i=Math.min(i*1.5,3e4)}}finally{Re=!1,j(a.onObservationChange,!1)}m=async()=>N(await r.read()),y.hidden=!1}async function Ue(e=!1){let t=await r.read();if(h)return;if(!I()){m=()=>Ue(e),y.hidden=!1;return}let n=r.quote;if(n&&dt(t,{operationId:n.operationId,currency:n.currency},"The original purchase operation changed"),n&&t.status==="pending"&&t.quoteFinalized===!1&&!t.confirmedAt&&!t.checkoutUrl&&!t.nativePurchase&&!t.merchantExecution&&!t.problem&&!r.pendingCancellation){rt(n);return}await N(t,e||void 0)}async function fe(){Xe(),m=fe;let e=await r.confirm();if(!I()){m=fe,y.hidden=!1;return}if(e.problem){await N(e);return}if(e.status==="pending"){if(e.checkoutUrl)await ke(e);else if(e.execution&&e.execution.provider!=="merchant"||e.nativePurchase){if(!a.onPurchase)throw new v("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await a.onPurchase({operation:e,signal:J.signal})}}m=async()=>N(await r.read()),await N(e,!0)}function rt(e){z?.remove();let t=!(Date.parse(e.expiresAt)>Date.now());l.textContent=t?s?"\u6B64\u62A5\u4EF7\u5DF2\u8FC7\u671F\u3002\u8BF7\u5148\u53D6\u6D88\uFF0C\u518D\u91CD\u65B0\u9009\u62E9\u3002":"This quote has expired. Cancel it, then choose again.":"";let n=p.createElement("div"),i=p.createElement("button"),o=p.createElement("button"),u=p.createElement("div"),_=p.createElement("p"),b=e.merchantTerms,oe=s?"zh-CN":"en",Y=b?.subscriptionTerms?.items??[],me=b?b.subscriptionTerms?.trial?.days:e.lines.find(c=>c.trial)?.trial?.days,se=me===void 0?null:b?b.totalMinor:e.charge?e.charge.totalMinor:e.lines.every(c=>c.trial)?0:null,it=(c,w)=>s?`${w} \u5929\u8BD5\u7528\u7ED3\u675F\u540E ${c}`:`Then ${c} after the ${w}-day trial`,{label:Nt,recurring:at}=nt(e),_t=e.lines.map(c=>c.productName).join(", "),ot=se===null?"":`${s?"\u4ECA\u5929\u5E94\u4ED8":"Due today"} ${ce(se,e.currency)}`;_.textContent=ot?[_t,ot].filter(Boolean).join(" \xB7 "):Nt,i.textContent=s?"\u786E\u8BA4\u8D2D\u4E70":"Confirm purchase",i.disabled=t,o.textContent=s?"\u53D6\u6D88":"Cancel",n.style.cssText=O.panel,_.style.cssText=O.summary,u.style.cssText=O.actions,i.style.cssText=O.primary,o.style.cssText=O.secondary,Fe(i),i.onclick=()=>{L(fe)};let st=async()=>{let c=await r.cancel();h||(n.remove(),z=null,await N(c))};o.onclick=()=>{m=st,L(st)};let q=p.createElement("div");if(q.style.cssText=O.terms,b){for(let w of Y){if(se===null&&w===at)continue;let S=p.createElement("p"),B=ce(w.amountMinor,e.currency)+ye(w.interval,oe,w.intervalCount);S.textContent=se!==null&&me!==void 0?it(B,me):B,q.append(S)}let c=b.subscriptionTerms?.trial;if(c){let w=p.createElement("p");w.textContent=s?`\u8BD5\u7528 ${c.days} \u5929\uFF1B${c.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${c.days}; ${c.cardRequired?"a payment method is required":"no payment method is required"}`,q.append(w)}for(let w of[...b.expectedEffects.map(S=>S.description),...b.requiredConsents.map(S=>S.summary)]){let S=p.createElement("p");S.textContent=w,q.append(S)}}else{for(let c of e.lines){if(se!==null||c!==at){let w=p.createElement("p"),S=`${ce(c.catalogAmountMinor,e.currency)}${ye(c.interval,oe,c.intervalCount??1)}`;w.textContent=se!==null&&c.trial?(e.lines.length>1?`${c.productName} \xB7 `:"")+it(S,c.trial.days):`${c.productName} \xB7 ${S}`,q.append(w)}for(let w of c.prepaid??[]){let S=p.createElement("p"),B=r.view?.capabilities.plans[c.productVersionId]?.prepaid?.find(Lt=>Lt.internalFeatureId===w.internal_feature_id);S.textContent=`${B?.name??w.internal_feature_id} \xB7 ${w.quantity} ${s?"\u4EFD":"packs"} \xD7 ${w.terms.units}`,B&&(S.textContent+=ye(B.reset==="week"||B.reset==="month"||B.reset==="year"?B.reset:"one_time",oe,B.resetCount)),q.append(S)}if(c.trial){let w=p.createElement("p");w.textContent=s?`\u8BD5\u7528 ${c.trial.days} \u5929\uFF1B${c.trial.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${c.trial.days}; ${c.trial.cardRequired?"a payment method is required":"no payment method is required"}`,q.append(w)}}if(!e.charge){let c=p.createElement("p");c.textContent=s?"\u76EE\u5F55\u4EF7\u683C\uFF1B\u6700\u7EC8\u91D1\u989D\u4EE5\u7ED3\u8D26\u65F6\u7A0E\u8D39\u548C\u8BD5\u7528\u89C4\u5219\u4E3A\u51C6\u3002":"Catalog price; the final charge depends on checkout taxes and trial terms.",q.append(c)}}for(let c of q.children)c.style.margin="0";u.append(i,o),n.append(_,...q.childElementCount?[q]:[],u),G.prepend(n),P?.responsive||n.scrollIntoView?.({block:"nearest"}),i.focus({preventScroll:!0}),z=n,m=null}async function pe(){if(!k)return;if(m=pe,!ie){let n=r.view,i=n?.document.buttons[k.actionId],o=n&&i?.type==="checkout"?ne(i.product,k.selection,n.capabilities):null;if(!n||!o)throw new v("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");let u=await a.resolveOfferId?.({actionId:k.actionId,productVersionId:o,featureQuantities:we(n.document.screen,o,k.selection,n.capabilities)});if(h)return;u!==void 0&&(k.offerId=u),ie=!0}if(!I()){y.hidden=!1;return}let e;try{e=await r.preview(k)}catch(n){throw r.canReselect===!0&&(k=null,ie=!1,m=null),n}if(h)return;let t=e.merchantTerms;if(a.confirmOnHostedCheckout&&I()&&e.provider==="merchant"&&e.billingSubscriptionId===null&&t?.request.action==="purchase"&&t.request.mode==="subscription"&&t.subscriptionTerms?.trial===null&&t.requiredConsents.length===0&&Date.parse(e.expiresAt)>Date.now()){let n=ue?"":s?"\u6B63\u5728\u6253\u5F00\u6536\u94F6\u53F0\u2026":"Opening checkout\u2026";l.textContent=n;try{await fe()}catch(i){h||X(i)}finally{l.textContent===n&&(l.textContent="")}return}rt(e)}function ae(e="destroy"){h||(h=!0,a.signal?.removeEventListener("abort",F),r.signal?.removeEventListener("abort",F),E.finish("dismissed"),ze?.(),J.abort(),We?.disconnect(),P?.destroy(),U?.destroy(),r.destroy(),x.open&&x.close(),x.remove(),R.remove(),g(),e==="dismiss"&&j(a.onDismiss))}D=ae;async function Ie(){if(!ee||h||ge||W==="closing"||!W&&!I())return;if(!A){ae("dismiss");return}let e=p.createElement("p");e.setAttribute("role","status"),e.textContent=s?"\u6B63\u5728\u5173\u95ED\u2026":"Closing\u2026",K||(K=p.createElement("div"),K.style.cssText=G.style.cssText,G.replaceWith(K),re.inert=!0),C.hidden=!1,K.replaceChildren(e,C),W="closing",C.setAttribute("aria-disabled","true"),C.focus({preventScroll:!0});try{await A.dismiss()}catch(t){h||j(a.onError,t)}h||(W="retry",e.textContent=s?"\u672A\u80FD\u786E\u8BA4\u5173\u95ED\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not confirm closure. Try again.",C.textContent=s?"\u91CD\u8BD5\u5173\u95ED":"Retry closing",C.removeAttribute("aria-label"),C.removeAttribute("aria-disabled"))}C.onclick=()=>{Ie()},x.addEventListener("cancel",e=>{e.preventDefault(),Ie()}),y.onclick=()=>{m&&L(m)};function Me(e){E.finish("error",e),ae()}function qe(){if(!(!Ke||ee||h||ge||P&&!I()))try{let e=t=>{a.focusAtReveal&&(g=je(p)),U?.setHidden?.(!1),De?.(),P&&(x.showModal(),P.responsive&&x.focus({preventScroll:!0}),!t&&a.loading!=="host"&&mt(x,P.type,P.responsive)),ee=!0};A?A.present(()=>E.present(()=>e(!0))):E.present(e)}catch(e){Me(e),X(e)}}try{be.type==="inline"?(Ge(),De=bt(R,T),T.append(R)):(x.setAttribute("aria-label",f.document.name),C.textContent="\xD7",C.setAttribute("aria-label",s?"\u5173\u95ED":"Close"),ht(C,f.document.screen.theme),C.hidden=ft(f.document),x.append(C,R),T.append(x),P=pt(x,{...f.document.screen,presentation:be},Oe),P.latch(),P.responsive&&(R.style.display="flex",R.style.flexDirection="column",R.style.maxHeight="100%",re.style.overflow="clip",re.style.minHeight="0"),De=wt(x)),U=V(re,{mode:"live",rendererUrl:r.webViewUrl,title:f.document.name,closeActions:At,onAuthoredClose(n){W||h||(C.hidden=n)},hostPresentation:()=>P?.type??be.type,reportContentHeight:P?.responsive,onResize:n=>{if(!P?.responsive)return;let i=Math.min(n,Te);re.style.height=`${i}px`,P.setContentHeight(i+(K??G).getBoundingClientRect().height)},onSelection(n){le=n,de()},onAction(n,i={}){if(!ee||h||W)return;let o=r.view,u=o?.document.buttons[n];if(!u)return;if(u.type==="close"&&A&&a.resumeCheckout&&r.operation&&lt(M(r.operation))){Ie();return}if(Z)return;if(!I()){Le();return}if(u.type==="close"){L(async()=>{await a.onAction?.(n),ae(a.onAction?"action":"dismiss")});return}if(u.type==="action"){m=async()=>{if(u.action.type==="event"){if(!a.onEvent)throw new v("EVENT_HANDLER_REQUIRED","Provide the event handler");await a.onEvent(u.action.event)}else a.onOpenUrl?await a.onOpenUrl(u.action.url):p.defaultView?.location.assign(u.action.url);await a.onAction?.(n),m=null},L(m);return}if(a.allowNewPurchase===!1){te()&&o&&r.quote&&r.operation&&M(r.operation).type==="checkout"&&Pe(r.quote,o,u.product,i)?L(_e,n):l.textContent=s?"\u5F53\u524D\u53EA\u80FD\u7EE7\u7EED\u539F\u8BA2\u5355\u3002":"Only your original checkout is available.";return}if(z&&r.canReselect===!1){l.textContent=s?"\u8BF7\u5148\u786E\u8BA4\u6216\u53D6\u6D88\u5F53\u524D\u8D2D\u4E70\u3002":"Confirm or cancel the current purchase first.",P?.responsive||z.scrollIntoView?.({block:"nearest"}),z.querySelector("button")?.focus({preventScroll:!0});return}if(te()&&H){H.selection.actionId===n&&L(()=>et(!0),n);return}if(te()&&a.terminateCheckout&&o&&r.quote&&r.operation&&r.canReselect===!1&&M(r.operation).type==="checkout"){if(Pe(r.quote,o,u.product,i)){L(_e,n);return}let b=ne(u.product,i,o.capabilities);try{if(!b)throw new v("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");we(o.document.screen,b,i,o.capabilities)}catch(me){X(me);return}let oe=r.operation.operationId,Y={actionId:n,requestId:crypto.randomUUID(),selection:structuredClone(i)};L(()=>St(oe,Y),n);return}if((r.quote||k)&&r.canReselect===!1){let b=!!o&&!!r.quote&&Pe(r.quote,o,u.product,i);Ce=!!r.quote&&!b,m=r.quote?()=>Ue(b):pe,L(m);return}let _=o&&ne(u.product,i,o.capabilities);if(!o||!_){X(new v("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(a.onPurchaseIntent){m=null,L(async()=>{let b={actionId:n,productVersionId:_,selection:structuredClone(i),featureQuantities:we(o.document.screen,_,i,o.capabilities)};Ne=!0,await a.onPurchaseIntent(b)});return}if(k&&k.actionId!==n){X(new v("COMMAND_PENDING","Finish the current purchase"));return}k||(k={requestId:crypto.randomUUID(),actionId:n,selection:structuredClone(i)},ie=!1),L(pe,n)},onEscape:()=>{Ie()},onError:n=>{let i=new Error(n);!ee&&!h&&Me(i),X(i)},onRendered:n=>{n&&x.setAttribute("aria-label",n),Ke=!0,qe()}}),U.setHidden?.(!0),Oe();let e=te()&&!!r.quote&&!!r.operation&&M(r.operation).type==="checkout";le=e?Et(f,r.quote)??{}:{},U.update(f.document.screen,f.document.screen.strings.defaultLocale,{capabilities:f.capabilities,unavailableActions:Qe(f),serverInput:{bindings:[],answers:{}},...Object.keys(le).length?{selection:le}:{}}),ze=r.subscribe?.(Se),Se(r.view??f),await E.wait(U.ready);let t=r.operation;!e&&(r.quote||t&&(t.confirmedAt||t.checkoutUrl||t.status==="complete"))&&(m=()=>Ue(),L(m))}catch(e){throw Me(e),e}return{check:Q,host:{get observing(){return Re},get recovery(){return Rt()},async prepareFallback(){if(Z||h||W||Ne)return{type:"recover",operationId:r.operation?.operationId??r.quote?.operationId??null,requestId:null};xe(!0);try{let e=await ut(r);return e.type==="native"&&ae(),e}finally{xe(!1)}},setSuspended(e){ge=e,R.hidden=e,e&&x.open?x.close():!e&&!ee?qe():!e&&!h&&ee&&be.type!=="inline"&&!x.open&&x.showModal()},destroy:ae,refresh:async()=>{if(!I()){if(r.view)return r.view;throw new v("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await r.refresh();return Se(e),qe(),e}}}}export{dn as showPaywall};
@@ -0,0 +1 @@
1
+ import{b as a}from"./chunk-W6OQTXLL.js";import"./chunk-BOVN2BE3.js";import"./chunk-PUR5CYWX.js";import"./chunk-TAFALMQN.js";import"./chunk-ZGCKQWQ5.js";import"./chunk-VEX2FOFZ.js";import"./chunk-56BYGPQ6.js";import"./chunk-VYFSRHXM.js";import"./chunk-BQRS7Y4K.js";import"./chunk-U4RSRFZY.js";import"./chunk-KE26KWIU.js";import"./chunk-TJGIT5CU.js";import"./chunk-OX7PA64E.js";import"./chunk-V7MMTILA.js";import"./chunk-3VUPVXAV.js";import"./chunk-EM3MGDPG.js";import"./chunk-VF6QMMEA.js";import"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.js";import"./chunk-WOT6VMZA.js";export{a as readPaywallContent};
@@ -0,0 +1 @@
1
+ import{a}from"./chunk-GZRRVHYK.js";import"./chunk-44U3FOBB.js";import"./chunk-WZR2XCSJ.js";import"./chunk-EUTWY7A2.js";import"./chunk-7MNJH5GB.js";import"./chunk-CIP5SQ5Y.js";import"./chunk-LF2UIJYD.js";import"./chunk-CKKIB2HC.js";import"./chunk-W6OQTXLL.js";import"./chunk-BOVN2BE3.js";import"./chunk-PUR5CYWX.js";import"./chunk-TAFALMQN.js";import"./chunk-ZGCKQWQ5.js";import"./chunk-3NCMYTNG.js";import"./chunk-VEX2FOFZ.js";import"./chunk-V7PFLFHE.js";import"./chunk-5HJYR6Z4.js";import"./chunk-56BYGPQ6.js";import"./chunk-VYFSRHXM.js";import"./chunk-BQRS7Y4K.js";import"./chunk-U4RSRFZY.js";import"./chunk-KE26KWIU.js";import"./chunk-TJGIT5CU.js";import"./chunk-OX7PA64E.js";import"./chunk-V7MMTILA.js";import"./chunk-3VUPVXAV.js";import"./chunk-EM3MGDPG.js";import"./chunk-VF6QMMEA.js";import"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.js";import"./chunk-DSPLGTQI.js";import"./chunk-WOT6VMZA.js";export{a as createPaywallSession};
package/dist/popup.d.ts CHANGED
@@ -49,6 +49,17 @@ type ScreenNodeRect = {
49
49
  width: number;
50
50
  height: number;
51
51
  };
52
+ /**
53
+ * Live purchase buttons the host is driving: `resume` actions read `resumeLabel` (the original
54
+ * Checkout continues) and the `busy` action spins while every listed action is held.
55
+ */
56
+ type CheckoutControls = {
57
+ type: "checkout-controls";
58
+ actions: readonly string[];
59
+ resume: readonly string[];
60
+ resumeLabel: string;
61
+ busy?: string;
62
+ };
52
63
  /** Editor shortcuts typed while focus is inside the canvas; the host owns their meaning. */
53
64
  type RendererEditorKey = {
54
65
  key: string;
@@ -144,9 +155,16 @@ type ScreenPreviewHandle = {
144
155
  reset?: boolean;
145
156
  }): void;
146
157
  updateCustomerData(data: CustomerPageData): void;
158
+ /** Live purchase buttons: the original Checkout's label and the in-button progress. */
159
+ updateCheckoutControls(controls: Omit<CheckoutControls, "type">): void;
147
160
  updateCapabilities(data: SurfaceData, unavailableActions?: readonly string[]): void;
148
161
  /** Resize the visible viewport without replacing the document or interaction state. */
149
162
  resizeViewport(height: number, width?: number): void;
163
+ /**
164
+ * A staging host keeps the frame rendered but unseen: its motion waits until
165
+ * it is shown again. Frames that predate this message keep animating.
166
+ */
167
+ setHidden(hidden: boolean): void;
150
168
  /** 编辑模式下的悬停与选中描边。 */
151
169
  highlight(hoverId: string | null, selectedId: string | null): void;
152
170
  destroy(): void;
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-TDSATEGE.js";import"./chunk-U6UHASIB.js";import"./chunk-N7YXDSQL.js";import"./chunk-MIBRUDIS.js";import"./chunk-X4W22IH6.js";import"./chunk-R4FDIYMN.js";import"./chunk-VF6QMMEA.js";import"./chunk-DSPLGTQI.js";import"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.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-TOTRALYQ.js";import"./chunk-XUGEOELU.js";import"./chunk-BQRS7Y4K.js";import"./chunk-U4RSRFZY.js";import"./chunk-KE26KWIU.js";import"./chunk-TJGIT5CU.js";import"./chunk-OX7PA64E.js";import"./chunk-V7MMTILA.js";import"./chunk-VF6QMMEA.js";import"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.js";import"./chunk-DSPLGTQI.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,7 +1,7 @@
1
- import { f as createCustomerClient, d as createFunnelClient } from './funnel-process-client-C6QKDZun.js';
2
- export { F as FunnelProcessAdapter, a as FunnelProcessOptions, c as createFunnelProcess } from './funnel-process-client-C6QKDZun.js';
3
- import { I as IndianaOptions, d as SessionCredentials, E as Scope, z as createFunnelRunController, v as PaywallStartInput, j as createPaywallSession } from './funnel-local-client-BeGBvi3z.js';
4
- export { c as FunnelCommandStorage, F as FunnelRunController, r as LocalFunnelClientOptions, t as LongplayError, u as PaywallPurchaseInput, P as PaywallSession, w as PushHost, x as PushJournal, y as createFeatureClient, A as createLocalFunnelClient } from './funnel-local-client-BeGBvi3z.js';
1
+ import { f as createCustomerClient, d as createFunnelClient } from './funnel-process-client-D6qjStm2.js';
2
+ export { F as FunnelProcessAdapter, a as FunnelProcessOptions, c as createFunnelProcess } from './funnel-process-client-D6qjStm2.js';
3
+ import { I as IndianaOptions, b as SessionCredentials, G as Scope, A as createFunnelRunController, w as PaywallStartInput, k as createPaywallSession } from './funnel-local-client-Dz1dTgES.js';
4
+ export { F as FunnelCommandStorage, f as FunnelRunController, t as LocalFunnelClientOptions, u as LongplayError, v as PaywallPurchaseInput, P as PaywallSession, x as PushHost, y as PushJournal, z as createFeatureClient, B as createLocalFunnelClient } from './funnel-local-client-Dz1dTgES.js';
5
5
  import { z } from 'zod';
6
6
  import { J as JsonValue } from './growth-rules-B4YYy64R.js';
7
7
  export { C as ConfigurationStorage, b as ConfigurationSyncOptions, c as createConfigurationSync } from './configuration-sync-DdTRUv7A.js';
@@ -1 +1 @@
1
- import{b as S,c as E,d as T}from"./chunk-7NELM6EH.js";import"./chunk-I6TSQQ5N.js";import{a as A}from"./chunk-ERJP2GBD.js";import{e as P}from"./chunk-ILEDKSRQ.js";import"./chunk-EQPEUPMG.js";import{h as b,i as x,k as L}from"./chunk-7VRZYSTR.js";import"./chunk-FYQXSGRT.js";import"./chunk-7MNJH5GB.js";import{F as C}from"./chunk-QBA3B4YK.js";import"./chunk-ITGERPCJ.js";import"./chunk-THMGTRXP.js";import"./chunk-NAZU3EEJ.js";import"./chunk-SCC3O2RD.js";import"./chunk-R23IGK5U.js";import"./chunk-ZGCKQWQ5.js";import"./chunk-EHDHWYVJ.js";import"./chunk-BXPXJARS.js";import"./chunk-5HJYR6Z4.js";import"./chunk-WTVLNUMS.js";import"./chunk-VYFSRHXM.js";import"./chunk-N7YXDSQL.js";import"./chunk-MIBRUDIS.js";import{a as r}from"./chunk-X4W22IH6.js";import{h as R}from"./chunk-R4FDIYMN.js";import"./chunk-3VUPVXAV.js";import"./chunk-WKIR2EQG.js";import"./chunk-VF6QMMEA.js";import"./chunk-DSPLGTQI.js";import"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.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-RML52BOR.js";import"./chunk-KPDHY76A.js";import{a as A}from"./chunk-GZRRVHYK.js";import{e as P}from"./chunk-44U3FOBB.js";import"./chunk-WZR2XCSJ.js";import{h as b,i as x,k as L}from"./chunk-BLVBUN2R.js";import{F as C}from"./chunk-2FE4FTPH.js";import"./chunk-EUTWY7A2.js";import"./chunk-7MNJH5GB.js";import"./chunk-CIP5SQ5Y.js";import"./chunk-LF2UIJYD.js";import"./chunk-CKKIB2HC.js";import"./chunk-W6OQTXLL.js";import"./chunk-BOVN2BE3.js";import"./chunk-PUR5CYWX.js";import"./chunk-TAFALMQN.js";import"./chunk-ZGCKQWQ5.js";import"./chunk-3NCMYTNG.js";import"./chunk-VEX2FOFZ.js";import"./chunk-V7PFLFHE.js";import"./chunk-5HJYR6Z4.js";import"./chunk-56BYGPQ6.js";import"./chunk-VYFSRHXM.js";import"./chunk-BQRS7Y4K.js";import"./chunk-U4RSRFZY.js";import"./chunk-KE26KWIU.js";import{b as R}from"./chunk-TJGIT5CU.js";import{a as r}from"./chunk-OX7PA64E.js";import"./chunk-V7MMTILA.js";import"./chunk-3VUPVXAV.js";import"./chunk-EM3MGDPG.js";import"./chunk-VF6QMMEA.js";import"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.js";import"./chunk-DSPLGTQI.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-TOTRALYQ.js";import"./chunk-XUGEOELU.js";import"./chunk-BQRS7Y4K.js";import"./chunk-U4RSRFZY.js";import"./chunk-KE26KWIU.js";import"./chunk-TJGIT5CU.js";import"./chunk-OX7PA64E.js";import"./chunk-V7MMTILA.js";import"./chunk-VF6QMMEA.js";import"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.js";import"./chunk-DSPLGTQI.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,6 +1,6 @@
1
1
  import { F as FoundationApi, I as InvoiceModeParams } from './api-Do-6AyWa.js';
2
- import { O as IndianaServerOptions, t as IndianaError, Q as FunnelProcessSuppression, T as FunnelProcessCommand, J as FunnelProcessResponse, C as CustomerSession, H as FunnelProcessOpenInput, M as FunnelProcessMutation, v as PaywallStartInput, P as PaywallSession, l as FeatureClientOptions, R as RemoteFeatureResult } from './funnel-local-client-BeGBvi3z.js';
3
- export { k as FeatureClient, g as FunnelStartInput, L as LocalFunnelClient, r as LocalFunnelClientOptions, y as createFeatureClient, U as createFunnelStartClient, A as createLocalFunnelClient } from './funnel-local-client-BeGBvi3z.js';
2
+ import { Q as IndianaServerOptions, u as IndianaError, T as FunnelProcessSuppression, U as FunnelProcessCommand, K as FunnelProcessResponse, C as CustomerSession, J as FunnelProcessOpenInput, N as FunnelProcessMutation, w as PaywallStartInput, P as PaywallSession, m as FeatureClientOptions, R as RemoteFeatureResult } from './funnel-local-client-Dz1dTgES.js';
3
+ export { l as FeatureClient, a as FunnelStartInput, L as LocalFunnelClient, t as LocalFunnelClientOptions, z as createFeatureClient, V as createFunnelStartClient, B as createLocalFunnelClient } from './funnel-local-client-Dz1dTgES.js';
4
4
  import * as zod from 'zod';
5
5
  import { z } from 'zod';
6
6
  import { S as StackNode } from './screen-CGCJ46b1.js';
package/dist/server.js CHANGED
@@ -1,6 +1,6 @@
1
- import{a as pn}from"./chunk-5JWMP4YD.js";import{a as I}from"./chunk-UWLEGMWX.js";import{a as fn,b as hn,c as gn,d as yn}from"./chunk-HQITRRHF.js";import{a as xt}from"./chunk-ERJP2GBD.js";import{a as Ue,b as Ve,c as qe,d as He,e as m}from"./chunk-ILEDKSRQ.js";import"./chunk-EQPEUPMG.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-7VRZYSTR.js";import{a as Et,b as _e}from"./chunk-FYQXSGRT.js";import"./chunk-7MNJH5GB.js";import{A as Tt,C as V,D as N,a as Oe,e as ft,f as ht,l as gt,m as z,n as St,q as Ct,r as Rt,s as bt,t as At,u as Ot,z as pe}from"./chunk-QBA3B4YK.js";import{c as f}from"./chunk-ITGERPCJ.js";import"./chunk-THMGTRXP.js";import{e as at}from"./chunk-NAZU3EEJ.js";import{A as tt,B as Se,C as ie,E as se,F as Ce,K as j,M as ce,N as nt,P as Ee,Q as rt,R as ot,d as Ge,e as je,h as we,p as ze,q as Ke,s as an,t as sn,w as cn,x as X,y as W,z as oe}from"./chunk-SCC3O2RD.js";import{A as Re,B as st,C as ct,H as ut,I as dt,J as be,K as Ae,S as pt,T as de,U as Z,V as lt,_ as mt,d as ve,f as Ze,g as et,u as q,z as it}from"./chunk-R23IGK5U.js";import"./chunk-ZGCKQWQ5.js";import"./chunk-EHDHWYVJ.js";import"./chunk-BXPXJARS.js";import"./chunk-5HJYR6Z4.js";import"./chunk-WTVLNUMS.js";import{a as Ne,b as Le}from"./chunk-VYFSRHXM.js";import{V as Xe,Y as We,la as ue,n as un,p as $e,q as Qe,r as Je}from"./chunk-N7YXDSQL.js";import{c as Ie}from"./chunk-MIBRUDIS.js";import{a as c}from"./chunk-X4W22IH6.js";import{h as Y}from"./chunk-R4FDIYMN.js";import"./chunk-3VUPVXAV.js";import"./chunk-WKIR2EQG.js";import{b as u}from"./chunk-VF6QMMEA.js";import"./chunk-DSPLGTQI.js";import{a as Ye}from"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.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-UVRT4MY6.js";import{a as I}from"./chunk-MSK3VZ3A.js";import{a as fn,b as hn,c as gn,d as yn}from"./chunk-SXBM3DWK.js";import{a as xt}from"./chunk-GZRRVHYK.js";import{a as Ue,b as Ve,c as qe,d as He,e as m}from"./chunk-44U3FOBB.js";import"./chunk-WZR2XCSJ.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-BLVBUN2R.js";import{A as Tt,C as V,D as N,a as Oe,e as ft,f as ht,l as gt,m as z,n as St,q as Ct,r as Rt,s as bt,t as At,u as Ot,z as pe}from"./chunk-2FE4FTPH.js";import{c as h}from"./chunk-EUTWY7A2.js";import"./chunk-7MNJH5GB.js";import"./chunk-CIP5SQ5Y.js";import{a as Et,b as _e}from"./chunk-LF2UIJYD.js";import{A as tt,B as Se,C as ie,E as se,F as Ce,K as j,M as ce,N as nt,P as Ee,Q as rt,R as ot,d as Ge,e as je,h as we,p as ze,q as Ke,s as an,t as sn,w as cn,x as X,y as W,z as oe}from"./chunk-CKKIB2HC.js";import"./chunk-W6OQTXLL.js";import"./chunk-BOVN2BE3.js";import{e as at}from"./chunk-PUR5CYWX.js";import{A as Re,B as st,C as ct,H as ut,I as dt,J as be,K as Ae,S as pt,T as de,U as Z,V as lt,_ as mt,d as ve,f as Ze,g as et,u as q,z as it}from"./chunk-TAFALMQN.js";import"./chunk-ZGCKQWQ5.js";import"./chunk-3NCMYTNG.js";import"./chunk-VEX2FOFZ.js";import"./chunk-V7PFLFHE.js";import"./chunk-5HJYR6Z4.js";import"./chunk-56BYGPQ6.js";import{a as Ne,b as Le}from"./chunk-VYFSRHXM.js";import{I as Xe,L as We,_ as ue}from"./chunk-BQRS7Y4K.js";import{i as un,k as $e,l as Qe,m as Je}from"./chunk-U4RSRFZY.js";import{c as Ie}from"./chunk-KE26KWIU.js";import{b as Y}from"./chunk-TJGIT5CU.js";import{a as c}from"./chunk-OX7PA64E.js";import"./chunk-V7MMTILA.js";import"./chunk-3VUPVXAV.js";import"./chunk-EM3MGDPG.js";import{b as u}from"./chunk-VF6QMMEA.js";import{a as Ye}from"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.js";import"./chunk-DSPLGTQI.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}
5
5
  ${t}
6
- ${e}`)}async function Nt(e){let n=ie.parse(e);return crypto.subtle.importKey("raw",Dt(n.signingSecret),{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}async function te(e,n,t,o=Date.now(),r=X){let a=String(Math.floor(o/1e3)),s=new Uint8Array(await crypto.subtle.sign("HMAC",await Nt(n),Ft(e,t,a,r))),l=btoa(String.fromCharCode(...s)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");return{[Q]:n.keyId,[Pt]:`t=${a},v1=${l}`}}async function ne(e,n,t,o,r=Date.now(),a=X){try{if(n.get(Q)!==t.keyId)return!1;let s=/^t=([0-9]{1,12}),v1=([A-Za-z0-9_-]{43})$/.exec(n.get(Pt)??"");return!s||Math.abs(r/1e3-Number(s[1]))>300?!1:await crypto.subtle.verify("HMAC",await Nt(t),Dt(s[2]),Ft(e,o,s[1],a))}catch{return!1}}var Lt=u.strictObject({operation:u.literal("renew_run"),runId:u.uuid(),customerId:u.uuid()}),le=ft.refine(e=>!!e.runToken,"Renewal returns a credential"),Ut=ht.refine(e=>!!e.runToken,"Renewal returns a credential");var Pe=u.discriminatedUnion("operation",[u.strictObject({operation:u.literal("campaign_decide"),...pt}).refine(be,Ae),u.strictObject({operation:u.literal("campaign_start"),funnelId:u.uuid(),requestId:u.uuid(),customer:ut,customerData:dt.optional(),locale:u.string().min(1).max(35),parameters:ue,cooldownSeconds:u.number().int().min(1).max(2592e3)}).refine(be,Ae)]),Sn=u.union([u.strictObject({scope:Y,suppressed:u.literal(!0),reason:u.enum(["frequency","in_progress"]),retryAt:u.iso.datetime({offset:!0})}),le]),Vt=u.union([Sn.options[0],Ut]);var qt=u.discriminatedUnion("provider",[u.strictObject({provider:u.literal("apple"),orderId:u.uuid(),receiptId:u.uuid(),signedTransaction:u.string().min(1).max(131072)}),u.strictObject({provider:u.literal("google"),orderId:u.uuid(),receiptId:u.uuid(),purchaseToken:u.string().min(1).max(16384)})]),Ht=u.strictObject({orderId:u.uuid(),receiptId:u.uuid(),transactionIds:u.array(u.string().min(1).max(255)).min(1).max(50),membership:u.boolean()});var Gt=u.strictObject({operation:u.literal("native_receipt"),requestId:u.uuid(),customerToken:u.string().regex(Ne),orderId:u.uuid(),receiptId:u.uuid(),nativeEvidence:qt.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),jt=u.strictObject({scope:Y,requestId:u.uuid(),orderId:u.uuid(),receiptId:u.uuid(),orderStatus:u.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:u.boolean(),nativeCompletion:Ht.optional()});var zt=u.strictObject({document:mt,configuration:z.options[0]});function me(e){return{async getCustomer(n){let t=m.getCustomer;return f(e,t,n,{request:"Invalid customer lookup",response:"Invalid customer response"})},async listCustomers(n={}){let t=m.listCustomers;return f(e,t,n,{request:"Invalid customer filters",response:"Invalid customer response"})},async updateCustomer(n){let t=m.updateCustomer;return f(e,t,n,{request:"Invalid customer patch",response:"Invalid customer response"})},async createGuestCustomer(n){let t=m.createGuestCustomer;return f(e,t,n)},async resumeGuestSession(n){let t=m.resumeGuestSession;return f(e,t,n)},async claimGuestCustomer(n){let t=m.claimGuestCustomer;return f(e,t,n)},async revokeCustomerSessions(n){let t=m.revokeSessions;return f(e,t,n)},async createCustomerSession(n){return f(e,m.createSession,{customerId:n},{request:"A customer ID is required",response:"Invalid customer session response"})},async getOrCreateCustomer(n){return f(e,m.createCustomer,n,{request:"Invalid customer input",response:"Invalid customer response"})}}}function Kt(e){return{async checkEntitlement(n){let t=m.checkEntitlement,o=t.request.parse(n),r=await f(e,t,o,I);return Et(o.requirement,r.check,o.customerId,r.scope),r},async readHoldings(n){let t=m.readHoldings;return f(e,t,n,I)},async readSeats(n){let t=m.readSeats;return f(e,t,n,I)},async manageSeat(n){let t=m.manageSeat;return f(e,t,n,I)}}}function $t(e){return{async readAiPricing(n){let t=m.readAiPricing;return f(e,t,n,I)},async readUsage(n){let t=m.readUsage;return f(e,t,n,I)},async setUsage(n){let t=m.setUsage;return f(e,t,n,I)},async manageBalanceGrant(n){let t=m.manageBalanceGrant;return f(e,t,n,I)},async readBalanceSource(n){let t=m.readBalanceSource;return f(e,t,n,I)},async adjustBalance(n){let t=m.adjustBalance;return f(e,t,n,I)},async listBalanceGrants(n){let t=m.listBalanceGrants;return f(e,t,n,I)},async manageBillingLimits(n){let t=m.manageBillingLimits;return f(e,t,n,I)},async manageUsageEntity(n){let t=m.manageUsageEntity;return f(e,t,n,I)},async readUsageAnalytics(n){let t=m.readUsageAnalytics;return f(e,t,n,I)},async readCreditAnalytics(n){let t=m.readCreditAnalytics;return f(e,t,n,I)},async submitUsageBatch(n){let t=m.submitUsageBatch;return f(e,t,n,I)},async readUsageBatch(n){let t=m.readUsageBatch;return f(e,t,n,I)},async readLedger(n){let t=m.readLedger;return f(e,t,n,I)},async readCreditStatement(n){let t=m.readCreditStatement;return f(e,t,n,I)},async quoteBalance(n){let t=m.quoteBalance;return f(e,t,n,I)},async trackUsage(n){let t=m.trackUsage;return f(e,t,n,I)},async mutateBalance(n){let t=m.mutateBalance;return f(e,t,n,I)}}}function Qt(e){return{async listInvoiceTemplates(n={}){let t=m.listInvoiceTemplates;return f(e,t,n,I)},async previewInvoice(n){let t=m.previewInvoice;return f(e,t,n,I)},async createInvoice(n){let t=m.createInvoice;return f(e,t,n,I)},async prepareBillingAdjustment(n){let t=m.prepareBillingAdjustment;return f(e,t,n,I)},async manageInvoice(n){let t=m.manageInvoice;return f(e,t,n,I)},async readInvoiceOperation(n){let t=m.readInvoiceOperation;return f(e,t,n,I)},async listInvoices(n){let t=m.listInvoices;return f(e,t,n,I)},async getInvoice(n){let t=m.getInvoice;return f(e,t,n,I)},async setupPayment(n){let t=m.setupPayment;return f(e,t,n,I)},async readPaymentSetup(n){let t=m.readPaymentSetup;return f(e,t,n,I)},async readBillingInvoice(n){let t=m.readBillingInvoice;return f(e,t,n,I)},async previewRefund(n){let t=m.previewRefund;return f(e,t,n,I)},async refund(n){let t=m.refund;return f(e,t,n,I)},async readRefund(n){let t=m.readRefund;return f(e,t,n,I)}}}function Jt(e){return{async previewSubscriptionBatch(n){let t=m.previewSubscriptionBatch;return f(e,t,n,I)},async confirmSubscriptionBatch(n){let t=m.confirmSubscriptionBatch;return f(e,t,n,I)},async readSubscriptionBatch(n){let t=m.readSubscriptionBatch;return f(e,t,n,I)},async abandonSubscriptionBatch(n){let t=m.abandonSubscriptionBatch;return f(e,t,n,I)},async manageSubscriptionTrial(n){let t=m.manageSubscriptionTrial;return f(e,t,n,I)},async readSubscriptionTrial(n){let t=m.readSubscriptionTrial;return f(e,t,n,I)},async listSubscriptions(n){let t=m.listSubscriptions;return f(e,t,n,I)},async listPurchases(n){let t=m.listPurchases;return f(e,t,n,I)},async listSubscriptionConflicts(n){let t=m.listSubscriptionConflicts;return f(e,t,n,I)},async retrySubscriptionConflict(n){let t=m.retrySubscriptionConflict;return f(e,t,n,I)},async previewUpdate(n){let t=m.previewUpdate;return f(e,t,n,I)},async update(n){let t=m.update;return f(e,t,n,I)},async readSubscriptionUpdate(n){let t=m.readSubscriptionUpdate;return f(e,t,n,I)},async restoreNativePurchase(n){let t=m.restoreNativePurchase;return f(e,t,n,I)},async verifySubscriptions(n){let t=m.verifySubscriptions;return f(e,t,n,I)},async previewAttach(n){let t=m.previewAttach;return f(e,t,n,I)},async recordMerchantEvent(n){return f(e,m.recordMerchantEvent,n,{request:"Invalid merchant event",parseResponse:I})},async attach(n){let t=m.attach;return f(e,t,n,I)},async readSubscriptionOperation(n){let t=m.readSubscriptionOperation;return f(e,t,n,I)}}}function Yt(e){return{async grantModelBenefit(n){return f(e,m.grantModelBenefit,n,{request:"Invalid model benefit grant",response:"Invalid model benefit response"})},async readModelBenefit(n){return f(e,m.readModelBenefit,n,{request:"Invalid model benefit operation",response:"Invalid model benefit response"})},async grantOffer(n){let t=m.grantOffer;return f(e,{...t,request:t.request.refine(o=>!!o.customerId)},{...n,requestId:n.requestId??crypto.randomUUID()},{request:"Invalid offer grant",response:"Invalid offer response"})}}}function Xt(e){return{...Kt(e),...$t(e),...Qt(e),...Jt(e),...Yt(e)}}function Wt(e){return{async getFeatures(n={}){let t=m.getFeatures;return f(e,t,n,I)},async evaluateFeatures(n){let t=m.evaluateFeatures;return f(e,t,n,I)}}}function Zt(e){return{async trackEvents(n){let t=m.trackEvents;return f(e,t,n,I)}}}function en(e){return{async resolveContent(n){let t=m.resolveContent;return f(e,t,n,I)},async resolvePaywall(n){let t=m.resolvePaywall,o=t.request.parse(n),r=await f(e,t,o,I);return _e(o,r.paywall.check,r.scope),r},async resolveOffering(n){let t=m.resolveOffering,o=t.request.parse(n),r=await f(e,t,o,I);return _e(o,r.check,r.scope),r}}}function Cn(e){V(e.apiKey,"Secret API keys must stay on your backend");let t=N(e).request;return{async sendMessage(o){let r=m.sendMessage;return r.response.parse(await t(r.path,r.request.parse(o)))},async readMessage(o){let r=m.readMessage;return r.response.parse(await t(r.path,r.request.parse(o)))},...me(t),...Xt(t),...Wt(t),...Zt(t),...en(t)}}function De(){if(typeof window<"u")throw new c("SERVER_ONLY","Guest identity is issued by your backend");let e=crypto.getRandomValues(new Uint8Array(32));return"gg_gc_"+btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}var tn=()=>new c("CONFLICT","Process synchronization is in progress",425),L=()=>new c("CONFLICT","This process belongs to a different account",409,void 0,{reason:"CUSTOMER_BINDING_CONFLICT"}),En=(e,n)=>JSON.stringify(e)===JSON.stringify(n),fe=class extends c{constructor(t){super("CONFLICT","Funnel entry is suppressed",409,void 0,{reason:t.reason==="in_progress"?"OPERATION_IN_PROGRESS":"STATE_CHANGED",recovery:"check_availability"});this.result=t}result};function Rn(e){if(V(e.apiKey,"Funnel process identity belongs to your backend"),e.session)throw new c("INVALID_CONFIGURATION","The process adapter owns its credential lifecycle");let n=N(e),t=me(n.request),o=`longplay:process:${e.scope.projectId}:${e.scope.environment}:`;async function r(g){let i=await e.resolveUser(g);if(i!==null&&(typeof i?.externalUserId!="string"||!i.externalUserId||i.externalUserId!==i.externalUserId.trim()||i.externalUserId.startsWith("gg_guest_")))throw new c("INVALID_RESPONSE","The merchant identity resolver returned an invalid subject");return i}async function a(g){let i=await e.resolveContext(g);if(i?.confirmed!==!0||!i.processKey||!i.guestKey)throw new c("INVALID_CONFIGURATION","A confirmed durable process handle is required");return{process:o+"run:"+i.processKey,guest:o+"guest:"+i.guestKey}}async function s(g,i){for(let w=0;w<8;w++){let R=await e.store.read(g),C=i(R?structuredClone(R.value):null);if(R&&En(R.value,C)||await e.store.compareAndSwap(g,R?.revision??null,C))return C}throw tn()}async function l(g){let i=await e.store.read(g);if(!i)throw new c("NOT_FOUND","Open the process before continuing",404);return i.value}async function p(g){let i=await l(g);for(let w of i.revocations??[])await t.revokeCustomerSessions(w),await s(g,R=>{if(!R)throw L();return R.revocations=R.revocations?.filter(C=>C.sessionId!==w.sessionId),R})}async function v(g,i){let w=Te.parse(g);return i?n.requestWithCredential("funnel-processes",w,i):n.request("funnel-processes",w)}function E(g,i){if(i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment||g.run&&(g.run.id!==i.run.id||g.run.source.versionId!==i.run.source.versionId||g.run.source.id!==i.run.source.id||g.run.runExpiresAt!==i.run.runExpiresAt||g.run.identity.startedAs!==i.run.identity.startedAs||g.run.identity.participantId!==i.run.identity.participantId||g.run.identity.binding&&g.run.identity.binding.id!==i.run.identity.binding?.id)||g.runToken&&i.runToken&&g.runToken!==i.runToken)throw new c("INVALID_RESPONSE","Process identity or Run changed")}async function b(g,i,w){return s(g,R=>{if(!R)throw new c("NOT_FOUND","Process handle is missing",404);return E(R,i),(!R.run||i.run.revision>=R.run.revision)&&(R.run=i.run),R.runToken??=i.runToken,w!==void 0&&(R.target=w),R})}async function d(g,i){if(i.detached)throw new c("UNAUTHENTICATED","The process is detached",401);let w=i.run?.identity.binding?.customerId??i.run?.identity.participantId;if(!w)throw new c("INVALID_RESPONSE","Process participant is missing");if(i.session?.customerId===w&&Date.parse(i.session.expiresAt)>Date.now()+3e4)return i.session;let R={id:crypto.randomUUID(),until:Date.now()+(e.timeoutMs??35e3)+5e3},C=await s(g,O=>{if(!O||O.detached||O.run?.id!==i.run?.id)throw L();if(O.sessionLease&&O.sessionLease.until>Date.now())throw tn();return O.sessionLease=R,O}),A;try{if(C.session?.customerId===w&&Date.parse(C.session.refreshExpiresAt)>Date.now())try{if(A=Le.parse(await n.requestWithCredential("customer-sessions/refresh",{},C.session.refreshToken)),A.sessionId!==C.session.sessionId)throw new c("INVALID_RESPONSE","Refresh changed the logical session")}catch(M){if(!(M instanceof c)||M.status!==401)throw M}if(A??=C.run?.identity.binding?await t.createCustomerSession(w):await t.resumeGuestSession({guestToken:C.guest.token}),A.customerId!==w)throw new c("INVALID_RESPONSE","Session Customer changed");let O=A;return await s(g,M=>{if(!M||M.detached||M.sessionLease?.id!==R.id||M.run?.identity.binding?.id!==i.run?.identity.binding?.id)throw new c("CONFLICT","Process identity changed during session issuance",409,void 0,{reason:"IDENTITY_CONTEXT_CHANGED",recovery:"reload_state"});return M.session=O,delete M.sessionLease,M}),A}catch(O){throw A&&A.sessionId!==C.session?.sessionId&&await t.revokeCustomerSessions({customerId:A.customerId,sessionId:A.sessionId}).catch(()=>{}),await s(g,M=>{if(!M)throw L();return M.sessionLease?.id===R.id&&delete M.sessionLease,M}).catch(()=>{}),O}}let h;async function y(){if(h??=vt.parse(await v({contract:q,operation:"describe"})),h.scope.projectId!==e.scope.projectId||h.scope.environment!==e.scope.environment)throw L();return h}async function S(g,i,w=!1){let R=await r(g),C=await l(i);if(C.issuingKeyId!==(await y()).keyId)throw new c("INVALID_CONFIGURATION","Restore this process with its original issuing Server Key");if(!C.runToken||!C.run)throw new c("CONFLICT","Recover the original start first",425);if(C.detached){if(!w)throw new c("UNAUTHENTICATED","Explicitly restore the process after sign-in",401);if(C.run.identity.binding&&(!R||C.target&&C.target!==R.externalUserId))throw L();await p(i),C=await s(i,A=>{if(!A||A.run?.id!==C.run?.id)throw L();return delete A.detached,A})}if(!C.runToken||!C.run)throw new c("INVALID_RESPONSE","Process identity is missing");if(C.run.identity.binding){if(R&&!C.target){let A=xe.parse(await v({contract:q,operation:"binding_status",runToken:C.runToken,requestId:C.bindingIntent?.requestId??C.start.requestId,externalUserId:R.externalUserId}));if(A.state!=="bound"||A.binding.id!==C.run.identity.binding.id)throw L();C=await s(i,O=>{if(!O)throw L();return O.target=R.externalUserId,O})}if(!R||C.target!==R.externalUserId)throw L()}else if(R){if(!C.guest)throw L();C=await s(i,O=>{if(!O||O.bindingIntent&&O.bindingIntent.externalUserId!==R.externalUserId)throw L();return O.bindingIntent??={requestId:crypto.randomUUID(),externalUserId:R.externalUserId},O});let A=C.bindingIntent;try{let O=wt.parse(await v({contract:q,operation:"bind_customer",...A,runToken:C.runToken,guestToken:C.guest.token,claimRequestId:C.guest.claimRequestId,expectedBindingId:null}));C=await b(i,O,R.externalUserId)}catch(O){let M=xe.parse(await v({contract:q,operation:"binding_status",...A,runToken:C.runToken,guestToken:C.guest.token}));if(M.state!=="bound")throw O;C=await s(i,F=>{if(!F?.run||F.run.id!==M.binding.runId)throw L();return F.run.identity.binding={id:M.binding.id,customerId:M.binding.customerId,acceptedAt:M.binding.acceptedAt},F.target=R.externalUserId,F})}}return{state:C,session:await d(i,C)}}async function k(g,i,w,R){try{return await R(w)}catch(C){if(!(C instanceof c)||C.status!==401)throw C;return await s(i,A=>{if(!A||A.detached)throw C;return A.session?.accessToken===w.session.accessToken&&(A.session.expiresAt=new Date(0).toISOString()),A}),R(await S(g,i))}}async function D(g,i,w=!1){let R=await a(g),C=await S(g,R.process,w),A=ae.parse(await k(g,R.process,C,O=>v({...i,customerToken:O.session.accessToken},O.state.runToken)));return await b(R.process,A),A}return{async open(g,i){i=It.parse(i);let w=await a(g),R=await y(),C=w.guest+":"+R.keyId,A=await e.store.read(w.process);if(!A){let B=await r(g),T,_,P;if(B)T={type:"customer",customer:{type:"externalUserId",value:B.externalUserId}};else{let H=await e.store.read(C);if(H)try{P=await t.resumeGuestSession({guestToken:H.value.token}),_=H.value}catch(U){if(!(U instanceof c)||U.status!==401)throw U}let G={token:De(),claimRequestId:crypto.randomUUID()};_=await s(C,U=>_??(U&&U.token!==H?.value.token?U:G)),T={type:"guest",guestToken:_.token}}await s(w.process,H=>H??{issuingKeyId:R.keyId,start:Te.parse({...i,contract:q,requestId:crypto.randomUUID(),source:T}),..._?{guest:_}:{},...B?{target:B.externalUserId}:{},...P?{session:P}:{}}),A=await e.store.read(w.process)}let O=A.value;if(O.issuingKeyId!==R.keyId)throw new c("INVALID_CONFIGURATION","Restore the original issuing Server Key before retrying this start");if(O.start.funnelId!==i.funnelId||O.start.operation!==i.operation)throw new c("CONFLICT","This handle already owns another process",409);if(!O.runToken){if(O.start.source.type==="customer"){let P=await r(g);if(!P||P.externalUserId!==O.target)throw L()}let B=await v(O.start),T=yt.safeParse(B);if(T.success)throw new fe(T.data);let _=ae.parse(B);if(!_.runToken)throw new c("INVALID_RESPONSE","Process credential is missing");O=await b(w.process,_)}let M=await S(g,w.process,!0),F=ae.parse(await k(g,w.process,M,B=>v({contract:q,operation:"get",customerToken:B.session.accessToken},B.state.runToken)));return await b(w.process,F),{...F,runToken:O.runToken}},async syncIdentity(g){return D(g,{contract:q,operation:"get",customerToken:""},!0)},async get(g,i={}){return D(g,{...i,contract:q,operation:"get",customerToken:""})},async review(g,i){return D(g,{contract:q,operation:"review",customerToken:"",...i?{receiptId:i}:{}})},async command(g,i,w){let R=await a(g),C=await S(g,R.process),A=ae.parse(await k(g,R.process,C,O=>v({contract:q,operation:"command",command:i,identity:{bindingId:w},customerToken:O.session.accessToken},O.state.runToken)));return await b(R.process,A),A},async pageExperiments(g,i,w=[]){let R=await a(g),C=await S(g,R.process);return gt.parse(await k(g,R.process,C,A=>v({contract:q,operation:"page_experiments",release:i,usedReceiptIds:w,customerToken:A.session.accessToken},A.state.runToken)))},async detach(g){let i=await a(g);await s(i.process,w=>{if(!w)throw L();return w.session&&!w.revocations?.some(R=>R.sessionId===w.session.sessionId)&&(w.revocations??=[]).push({customerId:w.session.customerId,sessionId:w.session.sessionId}),w.detached=!0,delete w.session,delete w.sessionLease,w}),await p(i.process)},destroy(){n.dispose()}}}async function bn(e,n){V(e.apiKey,"Renewal requires your backend");let t=N(e),o=le.parse(Rt(e,await t.request("funnels",Lt.parse({...n,operation:"renew_run"}))));if(o.run.id!==n.runId)throw new c("INVALID_RESPONSE","Run renewal identity changed");return o}function nn(e){let n=At(e),t=l=>{throw new c("INVALID_RESPONSE",l)};n.nodes.size!==e.topology.nodes.length&&t("Duplicate local node identity"),n.nodes.get(e.topology.entry)?.type!=="entry"&&t("A local Funnel must start at Entry");let o=new Set(["entry","condition","feature","split","end","output"]);for(let l of n.nodes.values()){if(!o.has(l.type))throw new c("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(l.type==="entry"&&l.id!==e.topology.entry&&t("Unexpected Entry node"),["entry","feature"].includes(l.type)&&!l.outputs.next&&t("Local next exit is unavailable"),l.type==="feature"){let p=l.resources.featureKey;(!p||!Object.hasOwn(e.evaluation.variables,l.writes.value)||!Object.hasOwn(n.features,p))&&t("Local Feature definition or declaration is unavailable")}if(l.type==="condition"){let p=e.conditions[l.id];(!p||!l.outputs.default||p.some((v,E)=>v.port!==`case:${E}`||!l.outputs[v.port]))&&t("Local Condition exits are unavailable")}if(l.type==="split"&&(!l.resources.experimentId||!Object.hasOwn(e.growth.experiments,l.resources.experimentId)||!l.outputs.notParticipating)&&t("Local Experiment definition or exit is unavailable"),l.type==="end"||l.type==="output"){let p=e.evaluation.terminals[l.id];if(!p)throw new c("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(l.outputs).length&&t("A terminal cannot have outgoing edges"),p.output?.type==="feature"&&!Object.hasOwn(n.features,p.output.featureKey)&&t("Terminal Feature definition is unavailable")}for(let p of Object.values(l.outputs))n.nodes.has(p)||t("Local target is unavailable")}let r=new Set,a=new Set;function s(l){if(a.has(l)&&t("Local graph contains a cycle"),!r.has(l)){a.add(l);for(let p of Object.values(n.nodes.get(l).outputs))s(p);a.delete(l),r.add(l)}}return s(e.topology.entry),r.size!==n.nodes.size&&t("Local graph contains unreachable nodes"),{evaluate(l){let p={},v=l.context;v.features=n.features,v.savedGroups=n.savedGroups;let E=()=>{v.attributes=it({declarations:e.evaluation.variables,attributes:l.attributes,parameters:l.parameters,answers:{},results:p,savedGroups:n.savedGroups})};E();let b=e.topology.entry,d=0;for(;;){let h=n.nodes.get(b);if(h.type==="end"||h.type==="output"){let y=e.evaluation.terminals[b],S=y.output,k=S?.type==="feature"?n.feature(S.featureKey,v):S?.type==="variable"?et({source:"variable",key:S.key,...S.path?{path:S.path}:{}},{declarations:e.evaluation.variables,answers:{},results:p,parameters:l.parameters,attributes:l.attributes,savedGroups:n.savedGroups}):S?.value??null;return ve(e.evaluation.outputSchema,k)||t("Local output does not match its declaration"),{outcome:y.outcome,value:k}}if(d++>=e.evaluation.maxTransitions)throw new c("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(h.type==="entry")b=h.outputs.next;else{let y=n.evaluate(b,v);if(h.type==="feature"){let S=h.writes.value,k=y.value??null;ve(e.evaluation.variables[S],k)||t("Local Feature value does not match its declaration"),Ze(e.evaluation.variables,{writes:h.writes},{[S]:k}),p[S]=k,E()}b=y.target}}}}}function rn(e,n,t){let o=Xe.parse(e.attributes);if(["parameters","answers","results"].some(g=>Object.hasOwn(o,g)))throw new c("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let r=ue.parse(e.parameters??{}),a=u.record(u.string(),We).parse(e.stickyBucketAssignmentDocs??{});for(let[g,i]of Object.entries(a))if(g!==`${i.attributeName}||${i.attributeValue}`||!Object.hasOwn(o,i.attributeName)||Ye(o[i.attributeName])!==i.attributeValue)throw new c("INVALID_REQUEST","Sticky document identity does not match this session");let s=e.saveStickyBucketAssignmentDoc,l=e.onFeatureUsage,p=e.onExperimentViewed,v=e.onError,E=new Map,b=new Set,d={},h=Promise.resolve();function y(g){let i=h.then(()=>(t(),g()));return h=i.catch(()=>{}),i}function S(g){try{v?.(g)}catch{}}function k(g){try{let i=g();i&&typeof i.catch=="function"&&i.catch(S)}catch(i){S(i)}}async function D(){for(let[g,i]of E){if(t(),s)try{await s(structuredClone(i))}catch{throw new c("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}t(),E.delete(g)}}return{evaluate(g={}){let i=g.track===!0;return y(async()=>{let w=await n();t(w);let R=new Set(b),C={...d},A=new Map,O=[],M={stickyBucketAssignmentDocs:structuredClone(a),saveStickyBucketAssignmentDoc(T){A.set(`${T.attributeName}||${T.attributeValue}`,structuredClone(T))},...i?{trackedExperiments:R,trackedFeatureUsage:C,onExperimentViewed(T,_){let P=structuredClone(T),H=structuredClone(_);p&&O.push(()=>p(structuredClone(P),structuredClone(H)))},onFeatureUsage(T,_){let P=structuredClone(_);l&&O.push(()=>l(T,structuredClone(P)))}}:{}},F=w.program.evaluate({attributes:o,parameters:r,context:M});t(w);for(let[T,_]of A)a[T]=_,E.set(T,_);await D(),t(w),i&&(b=R,d=C);for(let T of O)k(T);let B=w.configuration;return structuredClone({evaluationMode:"local",scope:B.scope,funnelId:B.funnelId,versionId:B.versionId,evaluationRevision:B.evaluationRevision,generation:B.growth.generation,...F})})},flush:()=>y(D),get stickyBucketAssignmentDocs(){return t(),structuredClone(a)}}}var An=6e4;function he(e){if(typeof window<"u")throw new c("SERVER_ONLY","Local Funnel sessions run on your backend");let n=Y.parse(e.scope),t=e.funnelId,o=e.load,r,a,s,l=0,p=b=>Date.now()>=b.expiresAt;async function v(){if(a)return a;let b=l;r=void 0;let d=(async()=>{let h=await o();if(b!==l)throw new c("IDENTITY_CHANGED","Local evaluator was reset");if(h&&typeof h=="object"&&"evaluationMode"in h&&h.evaluationMode==="remote")throw I(z,h),new c("EVALUATION_MODE","This Funnel requires remote decide");let y=I(St,h);if(b!==l)throw new c("IDENTITY_CHANGED","Local evaluator was reset");if(y.scope.projectId!==n.projectId||y.scope.environment!==n.environment||y.funnelId!==t)throw new c("SCOPE_MISMATCH","Local configuration scope changed");if(y.growth.scope.projectId!==n.projectId||y.growth.scope.environment!==n.environment||y.growth.expiresAt!==y.expiresAt)throw new c("INVALID_RESPONSE","GB configuration scope or expiry changed");let S=Math.min(Date.now()+An,y.expiresAt?Date.parse(y.expiresAt):1/0);if(Date.now()>=S)throw new c("CONFIGURATION_EXPIRED","Refresh expired local rules");let k=JSON.stringify([n.projectId,n.environment,t,y.versionId,y.evaluationRevision,y.growth.generation]),D=[y.topology,y.conditions,y.evaluation,y.growth.features,y.growth.experiments,y.growth.savedGroups];if(s?.key===k&&!Tt(s.body,D))throw new c("INVALID_RESPONSE","Immutable local configuration identity changed");return s?.key!==k&&(s={key:k,body:D,program:nn(y)}),r={key:k,configuration:y,expiresAt:S,program:s.program},r})();a=d;try{return await d}finally{a===d&&(a=void 0)}}function E(){return a??(r&&!p(r)?Promise.resolve(r):v())}return{session(b){let d=l;return rn(b,E,h=>{if(e.assertUsable?.(),d!==l)throw new c("IDENTITY_CHANGED","Local evaluator was reset");if(h&&(p(h)||r?.key!==h.key))throw new c("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await v()).configuration)},reset(){l++,r=void 0,a=void 0,s=void 0}}}function On(e,n){let t=e.snapshot?.generation,o=he({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n,load:()=>e.localFunnel(n),assertUsable:()=>e.assertFunnel(n)}),r=e.subscribe(()=>{let s=e.snapshot?.generation;e.fresh&&s!==t&&(t=s,o.refresh().catch(()=>{}))}),a=o.session;return Object.assign(o,{session(s){let l=a(s),p=l.evaluate;return Object.assign(l,{async evaluate(...v){return e.fresh||await e.refresh(),p(...v)}})},destroy(){r(),o.reset()}})}function Tn(e){if(typeof window<"u")throw new c("SERVER_ONLY","Secret API keys must stay on the backend");return{start:n=>xt(e,n)}}var re=class extends c{constructor(t,o){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,o);this.decisionId=t;this.decisionRequestId=o}decisionId;decisionRequestId};async function ge(e,n,t,o){let{decisionId:r,requestId:a}=e,s=e,l=250,p=0;for(;;){if(s.decisionId!==r||s.requestId!==a||s.decision&&!pe(s.decision,n))throw new c("INVALID_RESPONSE","Decision request or customer changed");if(s.decision)return s.decision;if(s.status==="failed")throw new c("DECISION_FAILED","Decision execution failed",503,a);if(Date.now()>=t)throw new re(r,a);if(await new Promise(v=>setTimeout(v,Math.min(Math.max(l,p-Date.now()),t-Date.now()))),Date.now()>=t)throw new re(r,a);l=Math.min(1e3,l*2);try{s=await o(r,t)}catch(v){if(v instanceof c&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(v.code)){p=Date.now()+(v.retryAfterSeconds??0)*1e3;continue}throw v}}}function Fe(e){if("remoteEval"in e)throw new c("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");V(e.apiKey,"Funnel decisions are requested by your backend");let n,t,o=new Map;async function r(p,v){let E=p;E.status!=="pending"&&o.delete(E.decisionId);for(let b=0;b<32&&E.evaluation;b++){let d=E.evaluation;if(d.runId!==E.decisionId)throw new c("INVALID_RESPONSE","Local evaluation Run changed");let h=o.get(E.decisionId);if(!h&&d.type==="evaluate_segment"){let S=zt.parse(await a({operation:"segment_configuration",funnelId:e.funnelId,versionId:d.versionId},v));if(S.configuration.scope.projectId!==e.scope.projectId||S.configuration.scope.environment!==e.scope.environment||S.configuration.funnelId!==e.funnelId||S.configuration.versionId!==d.versionId||S.configuration.evaluationRevision!==d.policyRevision)throw new c("SCOPE_MISMATCH","Original decision segment configuration changed");if(o.size>=128)throw new c("COMMAND_PENDING","Reconcile outstanding decisions first");h={operation:"commit_decision_segment",decisionId:E.decisionId,requestId:Oe(E.decisionId,d.visit,`segment:${d.revision}`),nodeId:d.nodeId,visit:d.visit,revision:d.revision,policyRevision:d.policyRevision,generation:S.configuration.growth.generation,...Ot(S.configuration,S.document,d)},o.set(E.decisionId,h)}if(!h){if(d.type!=="evaluate")throw new c("INVALID_RESPONSE","Unknown decision instruction");if((!t||t.versionId!==d.versionId||t.evaluationRevision!==d.policyRevision||t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())&&(t=z.parse(await a({operation:"configuration",funnelId:e.funnelId,versionId:d.versionId},v))),t.scope.projectId!==e.scope.projectId||t.scope.environment!==e.scope.environment||t.funnelId!==e.funnelId)throw new c("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(t.evaluationMode!=="local"||t.versionId!==d.versionId||t.evaluationRevision!==d.policyRevision)throw new c("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(o.size>=128)throw new c("COMMAND_PENDING","Reconcile outstanding Local decisions first");h={operation:"evaluate_decision",decisionId:E.decisionId,requestId:Oe(E.decisionId,d.visit,"evaluation"),nodeId:d.nodeId,visit:d.visit,revision:d.revision,receiptId:d.receiptId,policyRevision:d.policyRevision,generation:t.growth.generation,result:Ct(t,d.nodeId,d,bt)},o.set(E.decisionId,h)}let y=Z.parse(await a(h,v));if(y.decisionId!==p.decisionId||y.requestId!==p.requestId)throw new c("INVALID_RESPONSE","Decision identity changed during local evaluation");o.delete(E.decisionId),E=y}return E}async function a(p,v,E=!1){return N({...e,fetch:(d,h)=>{let y=new Headers(h?.headers);return y.set("Accept-Encoding","identity"),E&&y.set("Prefer","respond-async"),(e.fetch??globalThis.fetch)(d,{...h,headers:y})},timeoutMs:Math.min(e.timeoutMs??1e4,v?Math.max(1,v-Date.now()):12e4)}).request("funnels",p)}async function s(p,v){let E=Z.parse(await a(de.parse({operation:"read_decision",decisionId:p}),v));if(E.decisionId!==p)throw new c("INVALID_RESPONSE","Decision identity changed");return r(E,v)}async function l(p,v,E=!1){let b=de.options[0].parse({...p,operation:"decide",funnelId:e.funnelId}),d;try{d=Z.parse(await a(b,v,E))}catch(h){throw h instanceof c&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(h.code)?new c("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",h.status,p.requestId):h}if(d.requestId!==p.requestId||d.decision&&!pe(d.decision,b.customer))throw new c("INVALID_RESPONSE","Decision request or customer changed");return{response:await r(d,v),customer:b.customer}}return{local(){return n??=he({scope:e.scope,funnelId:e.funnelId,load:()=>a({operation:"local_configuration",funnelId:e.funnelId})})},async configuration(){let p=z.parse(await a({operation:"configuration",funnelId:e.funnelId}));if(p.scope.projectId!==e.scope.projectId||p.scope.environment!==e.scope.environment||p.funnelId!==e.funnelId)throw new c("SCOPE_MISMATCH","Configuration scope changed");return p},features(p={}){return Me({...p,scope:e.scope,load:async()=>at.parse(await a({operation:"feature_config",funnelId:e.funnelId}))})},read:p=>s(p),async submit(p){return(await l(p,void 0,!0)).response},async decide(p){let v=Date.now()+3e4,E=await l(p,v);return ge(E.response,E.customer,v,s)},async reportUsed(p){let v=lt.parse(await a(de.parse({...p,operation:"report_used"})));if(v.decisionId!==p.decisionId||v.eventId!==p.eventId)throw new c("INVALID_RESPONSE","Usage receipt identity changed");return v}}}function xn(e){V(e.apiKey,"Native receipts are verified by your backend","Server API key required");let n=N({...e,timeoutMs:e.timeoutMs??35e3});return{async recover(t){let o=Gt.parse(t);if(o.orderId!==o.receiptId)throw new c("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let r=o.nativeEvidence,a={requestId:o.requestId,customerToken:o.customerToken,purchaseIntentId:o.orderId,...r===null?{intent:"read"}:r.provider==="apple"?{provider:"apple",signedTransaction:r.signedTransaction}:{provider:"google",purchaseToken:r.purchaseToken}},s=m.restoreNativePurchase.response.parse(await n.request(m.restoreNativePurchase.path,a));if(s.operation.requestId!==o.requestId||s.operation.purchaseIntentId!==o.orderId)throw new c("INVALID_RESPONSE","Native receipt request identity changed");let l=jt.parse({scope:s.scope,requestId:o.requestId,orderId:s.operation.orderId,receiptId:s.operation.orderId,orderStatus:s.operation.status,refunded:s.operation.refunded,...s.operation.completion===null?{}:{nativeCompletion:{orderId:s.operation.orderId,receiptId:s.operation.orderId,...s.operation.completion}}});if(l.requestId!==o.requestId||l.orderId!==o.orderId||l.receiptId!==o.receiptId||l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment)throw new c("INVALID_RESPONSE","Current order receipt scope changed");return l}}}var J=u.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function _n(e,n){let t=J.parse(e.inputTokens.total),o=J.parse(e.outputTokens.total),r=J.parse(e.inputTokens.cacheRead??0),a=J.parse(e.inputTokens.cacheWrite??0),s=J.parse(e.outputTokens.reasoning??0);if(r+a>t||s>o||e.inputTokens.noCache!==void 0&&J.parse(e.inputTokens.noCache)!==t-r-a||e.outputTokens.text!==void 0&&J.parse(e.outputTokens.text)!==o-s)throw new c("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:t-r-a,cache_read:r,cache_write:a,output:n==="output"?o:o-s,reasoning:n==="separate"?s:0,input_audio:0,output_audio:0}}function Mn(e){if(typeof window<"u")throw new c("SERVER_ONLY","AI usage belongs on the trusted backend");if(!e.modelId||!["output","separate"].includes(e.reasoning))throw new c("INVALID_REQUEST","Model ID and reasoning pricing are required");async function n(o){await e.persist({context:o,modelId:e.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function t(o,r){let a={context:o,modelId:e.modelId,usage:r,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(a);let s=e.mapTokens?e.mapTokens(r):_n(r,e.reasoning),l=await e.pricing.quoteTokens({modelId:e.modelId,tokens:s});await e.persist({...a,tokens:s,quote:l,phase:"quoted"});let p=await e.pricing.trackTokens(e.client,{...o,quote:l});if(!p.receipt.accepted)throw new c("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await e.persist({...a,tokens:s,quote:l,receipt:p,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:o}){let r=await e.context(),a;try{a=await o()}catch(s){throw await n(r),s}return await t(r,a.usage),a},async wrapStream({doStream:o}){let r=await e.context(),a;try{a=await o()}catch(E){throw await n(r),E}let s=!1,l=!1,p=a.stream.getReader();async function v(){s||l||(l=!0,await n(r))}return{...a,stream:new ReadableStream({async pull(E){try{let{value:b,done:d}=await p.read();if(d){if(!s)throw await v(),new c("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");E.close();return}if(b.type==="finish"){if(s)throw new c("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");s=!0,await t(r,b.usage)}E.enqueue(b)}catch(b){try{await v()}finally{E.error(b),await p.cancel(b)}}},async cancel(E){try{await v()}finally{await p.cancel(E)}}})}}}}function kn(e){V(e.apiKey,"Funnel receipts are sent by your backend");let n=N(e);return{async signal(t){let o=Re.parse({...t,operation:"signal"}),r=st.parse(await n.request("funnels",o));if(r.runId!==t.runId||r.eventId!==t.eventId||r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new c("INVALID_RESPONSE","Receipt identity changed");return r},async readResults(t){let o=Re.parse({operation:"read_results",runId:t}),r=ct.parse(await n.request("funnels",o));if(r.runId!==t||r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new c("INVALID_RESPONSE","Result identity changed");return r}}}function Bn(e){if("remoteEval"in e)throw new c("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");V(e.apiKey,"Campaign entry requires your backend");let n=N({...e,timeoutMs:e.timeoutMs??35e3});return{async decide(t){let o=Date.now()+(e.timeoutMs??3e4),r=Pe.parse({...t,funnelId:e.funnelId,operation:"campaign_decide"}),a=N({...e,timeoutMs:Math.min(e.timeoutMs??35e3,Math.max(1,o-Date.now()))}),s=Z.parse(await a.request("funnels",r));if(s.scope.projectId!==e.scope.projectId||s.scope.environment!==e.scope.environment)throw new c("SCOPE_MISMATCH","Campaign scope changed");return ge(s,r.customer,o,(l,p)=>Fe({...e,timeoutMs:Math.min(e.timeoutMs??1e4,Math.max(1,p-Date.now()))}).read(l))},async start(t){let o=Pe.parse({...t,funnelId:e.funnelId,operation:"campaign_start"}),r=Vt.parse(await n.request("funnels",o));if(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new c("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in r)&&(r.run.source.id!==e.funnelId||!r.customerId||o.customer.type==="id"&&r.customerId!==o.customer.value))throw new c("INVALID_RESPONSE","Campaign Funnel or Customer changed");return r}}}var x=class extends Error{constructor(t,o=409,r=!1,a="fix_request"){super(t);this.code=t;this.status=o;this.retryable=r;this.recovery=a}code;status;retryable;recovery};function Pn(e){if(typeof window<"u")throw new Error("Merchant bridge credentials require a trusted server");let n=se.parse(e.manifest),t={projectId:n.projectId,environmentId:n.environmentId,environment:n.environment},o=n.capabilities.some(r=>["purchases","subscription_changes","refunds","operation_status"].includes(r));for(let[r,a]of Object.entries(Se))if(a.command&&n.capabilities.includes(r)&&!(r==="catalog"&&n.catalog==="static")&&!e.handlers[a.command])throw new Error(`Missing merchant command handler: ${a.command}`);if(o&&(!e.resolveOperationAuthority||!e.handlers["operation.read"]||!n.capabilities.includes("operation_status")))throw new Error("Merchant operations require fresh Longplay authority and an operation lookup handler");return async function(a){let s=crypto.randomUUID(),l="bridge.ping",p,v=async(E,b,d=!1)=>{let h=JSON.stringify({bridgeVersion:X,requestId:s,command:l,scope:t,[d?"error":"data"]:E});if(new TextEncoder().encode(h).byteLength>262144)throw new Error("Merchant response exceeds limit");return new Response(h,{status:b,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store","X-Request-Id":s,...p?await te(h,p,"response"):{}}})};try{if(a.headers.get("X-Indiana-Merchant-Bridge-Version")!==String(X)||a.method!=="POST"||new URL(a.url).pathname!==W)throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",400);if(!/^application\/json(?:\s*;|$)/i.test(a.headers.get("Content-Type")??""))throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",400);let E=a.body?.getReader();if(!E)throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",400);let b=new TextDecoder("utf-8",{fatal:!0}),d="",h=0;try{for(;;){let _=await E.read();if(_.done)break;if(h+=_.value.byteLength,h>16384)throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",413);d+=b.decode(_.value,{stream:!0})}d+=b.decode()}finally{await E.cancel().catch(()=>{}),E.releaseLock()}let y=ot.safeParse(JSON.parse(d));if(!y.success)throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",400);let S=y.data;if(s=S.requestId,l=S.command,Object.keys(t).some(_=>S.scope[_]!==t[_]))throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);let k=S.command==="bridge.ping"||S.command==="bridge.describe",D=S.command==="catalog.read";if((k||D||a.headers.has(Q))&&(p=e.authentication.find(_=>_.keyId===a.headers.get(Q)),!p||!await ne(d,a.headers,p,"request")))throw p=void 0,new x("MERCHANT_BRIDGE_AUTHENTICATION_FAILED",401);if(S.command==="bridge.ping")return v(Ee["bridge.ping"].parse(S.data),200);if(S.command==="bridge.describe")return v(n,200);let g=Object.entries(Se).find(([,_])=>_.command===S.command);if(!g||!n.capabilities.includes(g[0]))throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let i=e.handlers[S.command];if(!i)throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);if(!D&&a.headers.has("Cookie")&&(a.headers.get("Origin")!==new URL(a.url).origin||["cross-site","same-site"].includes(a.headers.get("Sec-Fetch-Site")??"")))throw new x("MERCHANT_BRIDGE_FORBIDDEN",403);let w=D?{kind:"service"}:await e.authorize(a,S),R=w.kind,C=["purchase.execute","subscription.change","refund.execute"].includes(S.command),A=C||S.command==="operation.read";if(!(A&&p!==void 0&&R==="service")&&(S.command==="refund.execute"?R!=="administrator":!D&&R!=="user"))throw new x("MERCHANT_BRIDGE_FORBIDDEN",403);if(w.kind==="user"&&["purchase.execute","operation.read","subscription.change","customer.commerce.read","presentation.report"].includes(S.command)&&!u.uuid().safeParse(w.customerId).success)throw new x("MERCHANT_BRIDGE_UNAUTHENTICATED",401);let M=i,F=Ee[S.command].parse(S.data),B={request:a,command:S.command,scope:t,principal:w},T;if(A){let _=j.parse(F);if(w.kind==="user"&&w.customerId!==_.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!e.resolveOperationAuthority)throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let P=ce.parse(await e.resolveOperationAuthority(_,B));if(P.operationId!==_.operationId||P.customerId!==_.customerId||Object.keys(t).some(G=>P.scope[G]!==t[G]))throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);B.authority=P;let H=S.command==="purchase.execute"?"purchase":S.command==="subscription.change"?"subscription_change":S.command==="refund.execute"?"refund":P.instruction.type;if(P.instruction.type!==H)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!C)T=we.parse(await M(F,B));else{if(P.confirmedAt===null)throw new x("MERCHANT_BRIDGE_OPERATION_NOT_CONFIRMED",409);let G=we.parse(await e.handlers["operation.read"](_,{...B,command:"operation.read"}));if(G.operationId!==_.operationId||G.customerId!==_.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(G.lookup==="found")T=G.execution;else{if(!P.initialExecutionAllowed)throw new x("MERCHANT_BRIDGE_RECOVERY_REQUIRED",409,!1,"recover_operation");if(Date.parse(P.instruction.expiresAt)<=Date.now())throw new x("MERCHANT_BRIDGE_OPERATION_EXPIRED",409,!1,"reload_state");if(!n.capabilities.includes("billing_records")||je(P.instruction).some(U=>!n.billingEvents.some(on=>on===U))||Ge(P.instruction).some(U=>!n.profiles.includes(U)))throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");try{T=nt.parse(await M(F,B))}catch(U){throw U instanceof x?U:new x("MERCHANT_BRIDGE_RESULT_UNKNOWN",503,!1,"recover_operation")}}if(T.type!==H)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}}else T=rt[S.command].parse(await M(F,B));if(w.kind==="user"){if("nativeUserId"in T&&T.nativeUserId!==w.nativeUserId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("customerId"in T&&T.customerId!==w.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("session"in T&&w.customerId&&T.session.customerId!==w.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("presentation"in T&&T.presentation&&w.customerId&&T.presentation.customerId!==w.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}if("operationId"in T&&(T.operationId!==j.parse(S.data).operationId||T.customerId!==j.parse(S.data).customerId))throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return v(T,C&&("paymentStatus"in T&&["pending","unknown"].includes(T.paymentStatus)||"status"in T&&["pending","unknown","scheduled"].includes(T.status))?202:200)}catch(E){let b=E instanceof x?E:E instanceof SyntaxError?new x("MERCHANT_BRIDGE_INVALID_REQUEST",400):new x("MERCHANT_BRIDGE_INVALID_RESPONSE",500);return v({code:b.code,message:b.code,retryable:b.retryable,recovery:b.recovery},b.status,!0)}}}function Dn(e){return async(n,t)=>{let o=()=>e.readSubscriptionOperation(n),r=()=>e.readSubscriptionUpdate(n),a=()=>e.readRefund(n),s=t.command==="purchase.execute"?[o]:t.command==="subscription.change"?[r]:t.command==="refund.execute"?[a]:[o,r,a];for(let l of s)try{let p=await l(),v="authority"in p.operation?p.operation.authority:void 0;if(!v)throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");let E=ce.parse(v);if(E.customerId!==n.customerId||E.operationId!==n.operationId||Object.keys(t.scope).some(b=>E.scope[b]!==t.scope[b]))throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return E}catch(p){if(t.command==="operation.read"&&p instanceof c&&p.code==="NOT_FOUND")continue;throw p}throw new x("MERCHANT_BRIDGE_OPERATION_NOT_FOUND",404,!1,"reload_state")}}function Fn(e){if(typeof window<"u")throw new Error("Merchant protocol credentials require a trusted server");let n=ke.parse(e.manifest),t=ie.parse(e.authentication),o={projectId:n.projectId,environmentId:n.environmentId,environment:n.environment},r=e.now??Date.now,a=d=>{throw new c("INVALID_RESPONSE",d)},s=(d,h)=>Ie(d)===Ie(h);function l(d){new TextEncoder().encode(d).byteLength>262144&&a("Merchant protocol body exceeds limit");try{return JSON.parse(d)}catch{return a("Invalid merchant protocol JSON")}}function p(d){let h=kt.parse(d);return s(h.scope,o)||a("Merchant protocol scope mismatch"),h.command==="requirement.check"&&(n.capabilities.includes("requirement_checks")||a("Merchant Check capability unavailable"),s(h.data.subject.scope,o)||a("Merchant Check subject crosses scope")),h.command==="operation.prepare"&&(!n.capabilities.includes("preparations")||!s(h.data.request.subject.scope,o))&&a("Merchant preparation capability unavailable"),h}function v(d){if(d.command!=="operation.prepare")return;let h=d.data;return(!s(h.request.subject.scope,o)||!h.preparationAllowed||Date.parse(h.requestedAt)>r()||Date.parse(h.request.expiresAt)<=r()||!n.preparationActions.includes(h.request.action))&&a("Merchant preparation requires fresh scoped authority"),h}function E(d,h){let y=Bt(d.command).parse(h);if((y.requestId!==d.requestId||!s(y.scope,o))&&a("Merchant reply correlation mismatch"),"error"in y)return y;if(d.command==="bridge.ping"&&"challenge"in y.data&&y.data.challenge!==d.data.challenge&&a("Merchant ping challenge mismatch"),d.command==="bridge.describe"&&"bridgeVersion"in y.data&&!s({projectId:y.data.projectId,environmentId:y.data.environmentId,environment:y.data.environment},o)&&a("Merchant declaration crosses scope"),d.command==="requirement.check"&&"observation"in y.data&&(!s(y.data.observation.subject,d.data.subject)||!Je(d.data.requirement,y.data)||!n.checkKinds.includes(y.data.kind))&&a("Merchant Check changed the original requirement or subject"),d.command==="operation.prepare"&&"quoteTermsDigest"in y.data){let S=v(d);(!s(y.data.request,S.request)||Date.parse(y.data.expiresAt)<=r()||Date.parse(y.data.observedAt)<Date.parse(S.requestedAt)||Date.parse(y.data.observedAt)>r())&&a("Merchant quote changed its authorized request or validity")}return y}let b=async d=>{let h=JSON.stringify(d);return l(h),{body:h,headers:new Headers({"Content-Type":"application/json","Cache-Control":"private, no-store",[oe]:"4",...await te(h,t,"response",r(),4)})}};return{version:4,path:W,async encodeRequest(d,h){let y=p({bridgeVersion:4,requestId:crypto.randomUUID(),scope:o,command:d,data:h});v(y);let S=JSON.stringify(y);l(S);let k=new Headers({"Content-Type":"application/json",[oe]:"4",...await te(S,t,"request",r(),4)});return{body:S,headers:k,async readResponse(D,g){l(D),(g.get(oe)!=="4"||!await ne(D,g,t,"response",r(),4))&&a("Merchant response authentication failed");let i=E(y,l(D));if("error"in i)throw new ye(i.error);return i.data}}},async decodeRequest(d,h){l(d),(h.get(oe)!=="4"||h.get(Q)!==t.keyId||!await ne(d,h,t,"request",r(),4))&&a("Merchant request authentication failed");let y=p(l(d));return v(y),y},async encodeResponse(d,h){let y=p(d),S=E(y,{...y,data:h});return b(S)},async encodeError(d,h){let y=p(d),{data:S,...k}=y;return b(E(y,{...k,error:Be.parse(h)}))}}}var ye=class extends Error{constructor(t){super(t.message);this.problem=t}problem};export{re as FunnelDecisionTimeoutError,fe as FunnelProcessEntrySuppressedError,c as LongplayError,x as MerchantBridgeHandlerError,ye as MerchantBridgeProtocolError,fn as aiPriceSnapshotSchema,hn as aiTokenQuoteSchema,gn as createAiPricing,Mn as createAiUsageMiddleware,dn as createConfigurationSync,yn as createConfiguredAiPricing,Me as createFeatureClient,Bn as createFunnelCampaignClient,Fe as createFunnelDecisionClient,he as createFunnelLocalEvaluator,kn as createFunnelOrchestrationClient,Rn as createFunnelProcessAdapter,ln as createFunnelStartClient,De as createGuestToken,mn as createLocalFunnelClient,Cn as createLongplayServer,Dn as createMerchantBridgeAuthorityResolver,Pn as createMerchantBridgeHandler,Fn as createMerchantBridgeProtocol,xn as createNativeReceiptClient,Tn as createPaywallStartClient,On as createSynchronizedFunnelLocalEvaluator,un as entitlementRequirementDigest,pn as evaluateFunnelNode,cn as merchantConfirmationMatchesTerms,an as merchantPreparationRequestDigest,sn as merchantQuoteTermsDigest,bn as renewFunnelRun,te as signMerchantBridgeMessage,ne as verifyMerchantBridgeMessage};
6
+ ${e}`)}async function Nt(e){let n=ie.parse(e);return crypto.subtle.importKey("raw",Dt(n.signingSecret),{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}async function te(e,n,t,o=Date.now(),r=X){let a=String(Math.floor(o/1e3)),s=new Uint8Array(await crypto.subtle.sign("HMAC",await Nt(n),Ft(e,t,a,r))),l=btoa(String.fromCharCode(...s)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");return{[Q]:n.keyId,[Pt]:`t=${a},v1=${l}`}}async function ne(e,n,t,o,r=Date.now(),a=X){try{if(n.get(Q)!==t.keyId)return!1;let s=/^t=([0-9]{1,12}),v1=([A-Za-z0-9_-]{43})$/.exec(n.get(Pt)??"");return!s||Math.abs(r/1e3-Number(s[1]))>300?!1:await crypto.subtle.verify("HMAC",await Nt(t),Dt(s[2]),Ft(e,o,s[1],a))}catch{return!1}}var Lt=u.strictObject({operation:u.literal("renew_run"),runId:u.uuid(),customerId:u.uuid()}),le=ft.refine(e=>!!e.runToken,"Renewal returns a credential"),Ut=ht.refine(e=>!!e.runToken,"Renewal returns a credential");var Pe=u.discriminatedUnion("operation",[u.strictObject({operation:u.literal("campaign_decide"),...pt}).refine(be,Ae),u.strictObject({operation:u.literal("campaign_start"),funnelId:u.uuid(),requestId:u.uuid(),customer:ut,customerData:dt.optional(),locale:u.string().min(1).max(35),parameters:ue,cooldownSeconds:u.number().int().min(1).max(2592e3)}).refine(be,Ae)]),Sn=u.union([u.strictObject({scope:Y,suppressed:u.literal(!0),reason:u.enum(["frequency","in_progress"]),retryAt:u.iso.datetime({offset:!0})}),le]),Vt=u.union([Sn.options[0],Ut]);var qt=u.discriminatedUnion("provider",[u.strictObject({provider:u.literal("apple"),orderId:u.uuid(),receiptId:u.uuid(),signedTransaction:u.string().min(1).max(131072)}),u.strictObject({provider:u.literal("google"),orderId:u.uuid(),receiptId:u.uuid(),purchaseToken:u.string().min(1).max(16384)})]),Ht=u.strictObject({orderId:u.uuid(),receiptId:u.uuid(),transactionIds:u.array(u.string().min(1).max(255)).min(1).max(50),membership:u.boolean()});var Gt=u.strictObject({operation:u.literal("native_receipt"),requestId:u.uuid(),customerToken:u.string().regex(Ne),orderId:u.uuid(),receiptId:u.uuid(),nativeEvidence:qt.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),jt=u.strictObject({scope:Y,requestId:u.uuid(),orderId:u.uuid(),receiptId:u.uuid(),orderStatus:u.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:u.boolean(),nativeCompletion:Ht.optional()});var zt=u.strictObject({document:mt,configuration:z.options[0]});function me(e){return{async getCustomer(n){let t=m.getCustomer;return h(e,t,n,{request:"Invalid customer lookup",response:"Invalid customer response"})},async listCustomers(n={}){let t=m.listCustomers;return h(e,t,n,{request:"Invalid customer filters",response:"Invalid customer response"})},async updateCustomer(n){let t=m.updateCustomer;return h(e,t,n,{request:"Invalid customer patch",response:"Invalid customer response"})},async createGuestCustomer(n){let t=m.createGuestCustomer;return h(e,t,n)},async resumeGuestSession(n){let t=m.resumeGuestSession;return h(e,t,n)},async claimGuestCustomer(n){let t=m.claimGuestCustomer;return h(e,t,n)},async revokeCustomerSessions(n){let t=m.revokeSessions;return h(e,t,n)},async createCustomerSession(n){return h(e,m.createSession,{customerId:n},{request:"A customer ID is required",response:"Invalid customer session response"})},async getOrCreateCustomer(n){return h(e,m.createCustomer,n,{request:"Invalid customer input",response:"Invalid customer response"})}}}function Kt(e){return{async checkEntitlement(n){let t=m.checkEntitlement,o=t.request.parse(n),r=await h(e,t,o,I);return Et(o.requirement,r.check,o.customerId,r.scope),r},async readHoldings(n){let t=m.readHoldings;return h(e,t,n,I)},async readSeats(n){let t=m.readSeats;return h(e,t,n,I)},async manageSeat(n){let t=m.manageSeat;return h(e,t,n,I)}}}function $t(e){return{async readAiPricing(n){let t=m.readAiPricing;return h(e,t,n,I)},async readUsage(n){let t=m.readUsage;return h(e,t,n,I)},async setUsage(n){let t=m.setUsage;return h(e,t,n,I)},async manageBalanceGrant(n){let t=m.manageBalanceGrant;return h(e,t,n,I)},async readBalanceSource(n){let t=m.readBalanceSource;return h(e,t,n,I)},async adjustBalance(n){let t=m.adjustBalance;return h(e,t,n,I)},async listBalanceGrants(n){let t=m.listBalanceGrants;return h(e,t,n,I)},async manageBillingLimits(n){let t=m.manageBillingLimits;return h(e,t,n,I)},async manageUsageEntity(n){let t=m.manageUsageEntity;return h(e,t,n,I)},async readUsageAnalytics(n){let t=m.readUsageAnalytics;return h(e,t,n,I)},async readCreditAnalytics(n){let t=m.readCreditAnalytics;return h(e,t,n,I)},async submitUsageBatch(n){let t=m.submitUsageBatch;return h(e,t,n,I)},async readUsageBatch(n){let t=m.readUsageBatch;return h(e,t,n,I)},async readLedger(n){let t=m.readLedger;return h(e,t,n,I)},async readCreditStatement(n){let t=m.readCreditStatement;return h(e,t,n,I)},async quoteBalance(n){let t=m.quoteBalance;return h(e,t,n,I)},async trackUsage(n){let t=m.trackUsage;return h(e,t,n,I)},async mutateBalance(n){let t=m.mutateBalance;return h(e,t,n,I)}}}function Qt(e){return{async listInvoiceTemplates(n={}){let t=m.listInvoiceTemplates;return h(e,t,n,I)},async previewInvoice(n){let t=m.previewInvoice;return h(e,t,n,I)},async createInvoice(n){let t=m.createInvoice;return h(e,t,n,I)},async prepareBillingAdjustment(n){let t=m.prepareBillingAdjustment;return h(e,t,n,I)},async manageInvoice(n){let t=m.manageInvoice;return h(e,t,n,I)},async readInvoiceOperation(n){let t=m.readInvoiceOperation;return h(e,t,n,I)},async listInvoices(n){let t=m.listInvoices;return h(e,t,n,I)},async getInvoice(n){let t=m.getInvoice;return h(e,t,n,I)},async setupPayment(n){let t=m.setupPayment;return h(e,t,n,I)},async readPaymentSetup(n){let t=m.readPaymentSetup;return h(e,t,n,I)},async readBillingInvoice(n){let t=m.readBillingInvoice;return h(e,t,n,I)},async previewRefund(n){let t=m.previewRefund;return h(e,t,n,I)},async refund(n){let t=m.refund;return h(e,t,n,I)},async readRefund(n){let t=m.readRefund;return h(e,t,n,I)}}}function Jt(e){return{async previewSubscriptionBatch(n){let t=m.previewSubscriptionBatch;return h(e,t,n,I)},async confirmSubscriptionBatch(n){let t=m.confirmSubscriptionBatch;return h(e,t,n,I)},async readSubscriptionBatch(n){let t=m.readSubscriptionBatch;return h(e,t,n,I)},async abandonSubscriptionBatch(n){let t=m.abandonSubscriptionBatch;return h(e,t,n,I)},async manageSubscriptionTrial(n){let t=m.manageSubscriptionTrial;return h(e,t,n,I)},async readSubscriptionTrial(n){let t=m.readSubscriptionTrial;return h(e,t,n,I)},async listSubscriptions(n){let t=m.listSubscriptions;return h(e,t,n,I)},async listPurchases(n){let t=m.listPurchases;return h(e,t,n,I)},async listSubscriptionConflicts(n){let t=m.listSubscriptionConflicts;return h(e,t,n,I)},async retrySubscriptionConflict(n){let t=m.retrySubscriptionConflict;return h(e,t,n,I)},async previewUpdate(n){let t=m.previewUpdate;return h(e,t,n,I)},async update(n){let t=m.update;return h(e,t,n,I)},async readSubscriptionUpdate(n){let t=m.readSubscriptionUpdate;return h(e,t,n,I)},async restoreNativePurchase(n){let t=m.restoreNativePurchase;return h(e,t,n,I)},async verifySubscriptions(n){let t=m.verifySubscriptions;return h(e,t,n,I)},async previewAttach(n){let t=m.previewAttach;return h(e,t,n,I)},async recordMerchantEvent(n){return h(e,m.recordMerchantEvent,n,{request:"Invalid merchant event",parseResponse:I})},async attach(n){let t=m.attach;return h(e,t,n,I)},async readSubscriptionOperation(n){let t=m.readSubscriptionOperation;return h(e,t,n,I)}}}function Yt(e){return{async grantModelBenefit(n){return h(e,m.grantModelBenefit,n,{request:"Invalid model benefit grant",response:"Invalid model benefit response"})},async readModelBenefit(n){return h(e,m.readModelBenefit,n,{request:"Invalid model benefit operation",response:"Invalid model benefit response"})},async grantOffer(n){let t=m.grantOffer;return h(e,{...t,request:t.request.refine(o=>!!o.customerId)},{...n,requestId:n.requestId??crypto.randomUUID()},{request:"Invalid offer grant",response:"Invalid offer response"})}}}function Xt(e){return{...Kt(e),...$t(e),...Qt(e),...Jt(e),...Yt(e)}}function Wt(e){return{async getFeatures(n={}){let t=m.getFeatures;return h(e,t,n,I)},async evaluateFeatures(n){let t=m.evaluateFeatures;return h(e,t,n,I)}}}function Zt(e){return{async trackEvents(n){let t=m.trackEvents;return h(e,t,n,I)}}}function en(e){return{async resolveContent(n){let t=m.resolveContent;return h(e,t,n,I)},async resolvePaywall(n){let t=m.resolvePaywall,o=t.request.parse(n),r=await h(e,t,o,I);return _e(o,r.paywall.check,r.scope),r},async resolveOffering(n){let t=m.resolveOffering,o=t.request.parse(n),r=await h(e,t,o,I);return _e(o,r.check,r.scope),r}}}function Cn(e){V(e.apiKey,"Secret API keys must stay on your backend");let t=N(e).request;return{async sendMessage(o){let r=m.sendMessage;return r.response.parse(await t(r.path,r.request.parse(o)))},async readMessage(o){let r=m.readMessage;return r.response.parse(await t(r.path,r.request.parse(o)))},...me(t),...Xt(t),...Wt(t),...Zt(t),...en(t)}}function De(){if(typeof window<"u")throw new c("SERVER_ONLY","Guest identity is issued by your backend");let e=crypto.getRandomValues(new Uint8Array(32));return"gg_gc_"+btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}var tn=()=>new c("CONFLICT","Process synchronization is in progress",425),L=()=>new c("CONFLICT","This process belongs to a different account",409,void 0,{reason:"CUSTOMER_BINDING_CONFLICT"}),En=(e,n)=>JSON.stringify(e)===JSON.stringify(n),fe=class extends c{constructor(t){super("CONFLICT","Funnel entry is suppressed",409,void 0,{reason:t.reason==="in_progress"?"OPERATION_IN_PROGRESS":"STATE_CHANGED",recovery:"check_availability"});this.result=t}result};function Rn(e){if(V(e.apiKey,"Funnel process identity belongs to your backend"),e.session)throw new c("INVALID_CONFIGURATION","The process adapter owns its credential lifecycle");let n=N(e),t=me(n.request),o=`longplay:process:${e.scope.projectId}:${e.scope.environment}:`;async function r(g){let i=await e.resolveUser(g);if(i!==null&&(typeof i?.externalUserId!="string"||!i.externalUserId||i.externalUserId!==i.externalUserId.trim()||i.externalUserId.startsWith("gg_guest_")))throw new c("INVALID_RESPONSE","The merchant identity resolver returned an invalid subject");return i}async function a(g){let i=await e.resolveContext(g);if(i?.confirmed!==!0||!i.processKey||!i.guestKey)throw new c("INVALID_CONFIGURATION","A confirmed durable process handle is required");return{process:o+"run:"+i.processKey,guest:o+"guest:"+i.guestKey}}async function s(g,i){for(let w=0;w<8;w++){let R=await e.store.read(g),C=i(R?structuredClone(R.value):null);if(R&&En(R.value,C)||await e.store.compareAndSwap(g,R?.revision??null,C))return C}throw tn()}async function l(g){let i=await e.store.read(g);if(!i)throw new c("NOT_FOUND","Open the process before continuing",404);return i.value}async function p(g){let i=await l(g);for(let w of i.revocations??[])await t.revokeCustomerSessions(w),await s(g,R=>{if(!R)throw L();return R.revocations=R.revocations?.filter(C=>C.sessionId!==w.sessionId),R})}async function v(g,i){let w=Te.parse(g);return i?n.requestWithCredential("funnel-processes",w,i):n.request("funnel-processes",w)}function E(g,i){if(i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment||g.run&&(g.run.id!==i.run.id||g.run.source.versionId!==i.run.source.versionId||g.run.source.id!==i.run.source.id||g.run.runExpiresAt!==i.run.runExpiresAt||g.run.identity.startedAs!==i.run.identity.startedAs||g.run.identity.participantId!==i.run.identity.participantId||g.run.identity.binding&&g.run.identity.binding.id!==i.run.identity.binding?.id)||g.runToken&&i.runToken&&g.runToken!==i.runToken)throw new c("INVALID_RESPONSE","Process identity or Run changed")}async function b(g,i,w){return s(g,R=>{if(!R)throw new c("NOT_FOUND","Process handle is missing",404);return E(R,i),(!R.run||i.run.revision>=R.run.revision)&&(R.run=i.run),R.runToken??=i.runToken,w!==void 0&&(R.target=w),R})}async function d(g,i){if(i.detached)throw new c("UNAUTHENTICATED","The process is detached",401);let w=i.run?.identity.binding?.customerId??i.run?.identity.participantId;if(!w)throw new c("INVALID_RESPONSE","Process participant is missing");if(i.session?.customerId===w&&Date.parse(i.session.expiresAt)>Date.now()+3e4)return i.session;let R={id:crypto.randomUUID(),until:Date.now()+(e.timeoutMs??35e3)+5e3},C=await s(g,O=>{if(!O||O.detached||O.run?.id!==i.run?.id)throw L();if(O.sessionLease&&O.sessionLease.until>Date.now())throw tn();return O.sessionLease=R,O}),A;try{if(C.session?.customerId===w&&Date.parse(C.session.refreshExpiresAt)>Date.now())try{if(A=Le.parse(await n.requestWithCredential("customer-sessions/refresh",{},C.session.refreshToken)),A.sessionId!==C.session.sessionId)throw new c("INVALID_RESPONSE","Refresh changed the logical session")}catch(M){if(!(M instanceof c)||M.status!==401)throw M}if(A??=C.run?.identity.binding?await t.createCustomerSession(w):await t.resumeGuestSession({guestToken:C.guest.token}),A.customerId!==w)throw new c("INVALID_RESPONSE","Session Customer changed");let O=A;return await s(g,M=>{if(!M||M.detached||M.sessionLease?.id!==R.id||M.run?.identity.binding?.id!==i.run?.identity.binding?.id)throw new c("CONFLICT","Process identity changed during session issuance",409,void 0,{reason:"IDENTITY_CONTEXT_CHANGED",recovery:"reload_state"});return M.session=O,delete M.sessionLease,M}),A}catch(O){throw A&&A.sessionId!==C.session?.sessionId&&await t.revokeCustomerSessions({customerId:A.customerId,sessionId:A.sessionId}).catch(()=>{}),await s(g,M=>{if(!M)throw L();return M.sessionLease?.id===R.id&&delete M.sessionLease,M}).catch(()=>{}),O}}let f;async function y(){if(f??=vt.parse(await v({contract:q,operation:"describe"})),f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment)throw L();return f}async function S(g,i,w=!1){let R=await r(g),C=await l(i);if(C.issuingKeyId!==(await y()).keyId)throw new c("INVALID_CONFIGURATION","Restore this process with its original issuing Server Key");if(!C.runToken||!C.run)throw new c("CONFLICT","Recover the original start first",425);if(C.detached){if(!w)throw new c("UNAUTHENTICATED","Explicitly restore the process after sign-in",401);if(C.run.identity.binding&&(!R||C.target&&C.target!==R.externalUserId))throw L();await p(i),C=await s(i,A=>{if(!A||A.run?.id!==C.run?.id)throw L();return delete A.detached,A})}if(!C.runToken||!C.run)throw new c("INVALID_RESPONSE","Process identity is missing");if(C.run.identity.binding){if(R&&!C.target){let A=xe.parse(await v({contract:q,operation:"binding_status",runToken:C.runToken,requestId:C.bindingIntent?.requestId??C.start.requestId,externalUserId:R.externalUserId}));if(A.state!=="bound"||A.binding.id!==C.run.identity.binding.id)throw L();C=await s(i,O=>{if(!O)throw L();return O.target=R.externalUserId,O})}if(!R||C.target!==R.externalUserId)throw L()}else if(R){if(!C.guest)throw L();C=await s(i,O=>{if(!O||O.bindingIntent&&O.bindingIntent.externalUserId!==R.externalUserId)throw L();return O.bindingIntent??={requestId:crypto.randomUUID(),externalUserId:R.externalUserId},O});let A=C.bindingIntent;try{let O=wt.parse(await v({contract:q,operation:"bind_customer",...A,runToken:C.runToken,guestToken:C.guest.token,claimRequestId:C.guest.claimRequestId,expectedBindingId:null}));C=await b(i,O,R.externalUserId)}catch(O){let M=xe.parse(await v({contract:q,operation:"binding_status",...A,runToken:C.runToken,guestToken:C.guest.token}));if(M.state!=="bound")throw O;C=await s(i,F=>{if(!F?.run||F.run.id!==M.binding.runId)throw L();return F.run.identity.binding={id:M.binding.id,customerId:M.binding.customerId,acceptedAt:M.binding.acceptedAt},F.target=R.externalUserId,F})}}return{state:C,session:await d(i,C)}}async function k(g,i,w,R){try{return await R(w)}catch(C){if(!(C instanceof c)||C.status!==401)throw C;return await s(i,A=>{if(!A||A.detached)throw C;return A.session?.accessToken===w.session.accessToken&&(A.session.expiresAt=new Date(0).toISOString()),A}),R(await S(g,i))}}async function D(g,i,w=!1){let R=await a(g),C=await S(g,R.process,w),A=ae.parse(await k(g,R.process,C,O=>v({...i,customerToken:O.session.accessToken},O.state.runToken)));return await b(R.process,A),A}return{async open(g,i){i=It.parse(i);let w=await a(g),R=await y(),C=w.guest+":"+R.keyId,A=await e.store.read(w.process);if(!A){let B=await r(g),T,_,P;if(B)T={type:"customer",customer:{type:"externalUserId",value:B.externalUserId}};else{let H=await e.store.read(C);if(H)try{P=await t.resumeGuestSession({guestToken:H.value.token}),_=H.value}catch(U){if(!(U instanceof c)||U.status!==401)throw U}let G={token:De(),claimRequestId:crypto.randomUUID()};_=await s(C,U=>_??(U&&U.token!==H?.value.token?U:G)),T={type:"guest",guestToken:_.token}}await s(w.process,H=>H??{issuingKeyId:R.keyId,start:Te.parse({...i,contract:q,requestId:crypto.randomUUID(),source:T}),..._?{guest:_}:{},...B?{target:B.externalUserId}:{},...P?{session:P}:{}}),A=await e.store.read(w.process)}let O=A.value;if(O.issuingKeyId!==R.keyId)throw new c("INVALID_CONFIGURATION","Restore the original issuing Server Key before retrying this start");if(O.start.funnelId!==i.funnelId||O.start.operation!==i.operation)throw new c("CONFLICT","This handle already owns another process",409);if(!O.runToken){if(O.start.source.type==="customer"){let P=await r(g);if(!P||P.externalUserId!==O.target)throw L()}let B=await v(O.start),T=yt.safeParse(B);if(T.success)throw new fe(T.data);let _=ae.parse(B);if(!_.runToken)throw new c("INVALID_RESPONSE","Process credential is missing");O=await b(w.process,_)}let M=await S(g,w.process,!0),F=ae.parse(await k(g,w.process,M,B=>v({contract:q,operation:"get",customerToken:B.session.accessToken},B.state.runToken)));return await b(w.process,F),{...F,runToken:O.runToken}},async syncIdentity(g){return D(g,{contract:q,operation:"get",customerToken:""},!0)},async get(g,i={}){return D(g,{...i,contract:q,operation:"get",customerToken:""})},async review(g,i){return D(g,{contract:q,operation:"review",customerToken:"",...i?{receiptId:i}:{}})},async command(g,i,w){let R=await a(g),C=await S(g,R.process),A=ae.parse(await k(g,R.process,C,O=>v({contract:q,operation:"command",command:i,identity:{bindingId:w},customerToken:O.session.accessToken},O.state.runToken)));return await b(R.process,A),A},async pageExperiments(g,i,w=[]){let R=await a(g),C=await S(g,R.process);return gt.parse(await k(g,R.process,C,A=>v({contract:q,operation:"page_experiments",release:i,usedReceiptIds:w,customerToken:A.session.accessToken},A.state.runToken)))},async detach(g){let i=await a(g);await s(i.process,w=>{if(!w)throw L();return w.session&&!w.revocations?.some(R=>R.sessionId===w.session.sessionId)&&(w.revocations??=[]).push({customerId:w.session.customerId,sessionId:w.session.sessionId}),w.detached=!0,delete w.session,delete w.sessionLease,w}),await p(i.process)},destroy(){n.dispose()}}}async function bn(e,n){V(e.apiKey,"Renewal requires your backend");let t=N(e),o=le.parse(Rt(e,await t.request("funnels",Lt.parse({...n,operation:"renew_run"}))));if(o.run.id!==n.runId)throw new c("INVALID_RESPONSE","Run renewal identity changed");return o}function nn(e){let n=At(e),t=l=>{throw new c("INVALID_RESPONSE",l)};n.nodes.size!==e.topology.nodes.length&&t("Duplicate local node identity"),n.nodes.get(e.topology.entry)?.type!=="entry"&&t("A local Funnel must start at Entry");let o=new Set(["entry","condition","feature","split","end","output"]);for(let l of n.nodes.values()){if(!o.has(l.type))throw new c("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(l.type==="entry"&&l.id!==e.topology.entry&&t("Unexpected Entry node"),["entry","feature"].includes(l.type)&&!l.outputs.next&&t("Local next exit is unavailable"),l.type==="feature"){let p=l.resources.featureKey;(!p||!Object.hasOwn(e.evaluation.variables,l.writes.value)||!Object.hasOwn(n.features,p))&&t("Local Feature definition or declaration is unavailable")}if(l.type==="condition"){let p=e.conditions[l.id];(!p||!l.outputs.default||p.some((v,E)=>v.port!==`case:${E}`||!l.outputs[v.port]))&&t("Local Condition exits are unavailable")}if(l.type==="split"&&(!l.resources.experimentId||!Object.hasOwn(e.growth.experiments,l.resources.experimentId)||!l.outputs.notParticipating)&&t("Local Experiment definition or exit is unavailable"),l.type==="end"||l.type==="output"){let p=e.evaluation.terminals[l.id];if(!p)throw new c("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(l.outputs).length&&t("A terminal cannot have outgoing edges"),p.output?.type==="feature"&&!Object.hasOwn(n.features,p.output.featureKey)&&t("Terminal Feature definition is unavailable")}for(let p of Object.values(l.outputs))n.nodes.has(p)||t("Local target is unavailable")}let r=new Set,a=new Set;function s(l){if(a.has(l)&&t("Local graph contains a cycle"),!r.has(l)){a.add(l);for(let p of Object.values(n.nodes.get(l).outputs))s(p);a.delete(l),r.add(l)}}return s(e.topology.entry),r.size!==n.nodes.size&&t("Local graph contains unreachable nodes"),{evaluate(l){let p={},v=l.context;v.features=n.features,v.savedGroups=n.savedGroups;let E=()=>{v.attributes=it({declarations:e.evaluation.variables,attributes:l.attributes,parameters:l.parameters,answers:{},results:p,savedGroups:n.savedGroups})};E();let b=e.topology.entry,d=0;for(;;){let f=n.nodes.get(b);if(f.type==="end"||f.type==="output"){let y=e.evaluation.terminals[b],S=y.output,k=S?.type==="feature"?n.feature(S.featureKey,v):S?.type==="variable"?et({source:"variable",key:S.key,...S.path?{path:S.path}:{}},{declarations:e.evaluation.variables,answers:{},results:p,parameters:l.parameters,attributes:l.attributes,savedGroups:n.savedGroups}):S?.value??null;return ve(e.evaluation.outputSchema,k)||t("Local output does not match its declaration"),{outcome:y.outcome,value:k}}if(d++>=e.evaluation.maxTransitions)throw new c("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(f.type==="entry")b=f.outputs.next;else{let y=n.evaluate(b,v);if(f.type==="feature"){let S=f.writes.value,k=y.value??null;ve(e.evaluation.variables[S],k)||t("Local Feature value does not match its declaration"),Ze(e.evaluation.variables,{writes:f.writes},{[S]:k}),p[S]=k,E()}b=y.target}}}}}function rn(e,n,t){let o=Xe.parse(e.attributes);if(["parameters","answers","results"].some(g=>Object.hasOwn(o,g)))throw new c("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let r=ue.parse(e.parameters??{}),a=u.record(u.string(),We).parse(e.stickyBucketAssignmentDocs??{});for(let[g,i]of Object.entries(a))if(g!==`${i.attributeName}||${i.attributeValue}`||!Object.hasOwn(o,i.attributeName)||Ye(o[i.attributeName])!==i.attributeValue)throw new c("INVALID_REQUEST","Sticky document identity does not match this session");let s=e.saveStickyBucketAssignmentDoc,l=e.onFeatureUsage,p=e.onExperimentViewed,v=e.onError,E=new Map,b=new Set,d={},f=Promise.resolve();function y(g){let i=f.then(()=>(t(),g()));return f=i.catch(()=>{}),i}function S(g){try{v?.(g)}catch{}}function k(g){try{let i=g();i&&typeof i.catch=="function"&&i.catch(S)}catch(i){S(i)}}async function D(){for(let[g,i]of E){if(t(),s)try{await s(structuredClone(i))}catch{throw new c("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}t(),E.delete(g)}}return{evaluate(g={}){let i=g.track===!0;return y(async()=>{let w=await n();t(w);let R=new Set(b),C={...d},A=new Map,O=[],M={stickyBucketAssignmentDocs:structuredClone(a),saveStickyBucketAssignmentDoc(T){A.set(`${T.attributeName}||${T.attributeValue}`,structuredClone(T))},...i?{trackedExperiments:R,trackedFeatureUsage:C,onExperimentViewed(T,_){let P=structuredClone(T),H=structuredClone(_);p&&O.push(()=>p(structuredClone(P),structuredClone(H)))},onFeatureUsage(T,_){let P=structuredClone(_);l&&O.push(()=>l(T,structuredClone(P)))}}:{}},F=w.program.evaluate({attributes:o,parameters:r,context:M});t(w);for(let[T,_]of A)a[T]=_,E.set(T,_);await D(),t(w),i&&(b=R,d=C);for(let T of O)k(T);let B=w.configuration;return structuredClone({evaluationMode:"local",scope:B.scope,funnelId:B.funnelId,versionId:B.versionId,evaluationRevision:B.evaluationRevision,generation:B.growth.generation,...F})})},flush:()=>y(D),get stickyBucketAssignmentDocs(){return t(),structuredClone(a)}}}var An=6e4;function he(e){if(typeof window<"u")throw new c("SERVER_ONLY","Local Funnel sessions run on your backend");let n=Y.parse(e.scope),t=e.funnelId,o=e.load,r,a,s,l=0,p=b=>Date.now()>=b.expiresAt;async function v(){if(a)return a;let b=l;r=void 0;let d=(async()=>{let f=await o();if(b!==l)throw new c("IDENTITY_CHANGED","Local evaluator was reset");if(f&&typeof f=="object"&&"evaluationMode"in f&&f.evaluationMode==="remote")throw I(z,f),new c("EVALUATION_MODE","This Funnel requires remote decide");let y=I(St,f);if(b!==l)throw new c("IDENTITY_CHANGED","Local evaluator was reset");if(y.scope.projectId!==n.projectId||y.scope.environment!==n.environment||y.funnelId!==t)throw new c("SCOPE_MISMATCH","Local configuration scope changed");if(y.growth.scope.projectId!==n.projectId||y.growth.scope.environment!==n.environment||y.growth.expiresAt!==y.expiresAt)throw new c("INVALID_RESPONSE","GB configuration scope or expiry changed");let S=Math.min(Date.now()+An,y.expiresAt?Date.parse(y.expiresAt):1/0);if(Date.now()>=S)throw new c("CONFIGURATION_EXPIRED","Refresh expired local rules");let k=JSON.stringify([n.projectId,n.environment,t,y.versionId,y.evaluationRevision,y.growth.generation]),D=[y.topology,y.conditions,y.evaluation,y.growth.features,y.growth.experiments,y.growth.savedGroups];if(s?.key===k&&!Tt(s.body,D))throw new c("INVALID_RESPONSE","Immutable local configuration identity changed");return s?.key!==k&&(s={key:k,body:D,program:nn(y)}),r={key:k,configuration:y,expiresAt:S,program:s.program},r})();a=d;try{return await d}finally{a===d&&(a=void 0)}}function E(){return a??(r&&!p(r)?Promise.resolve(r):v())}return{session(b){let d=l;return rn(b,E,f=>{if(e.assertUsable?.(),d!==l)throw new c("IDENTITY_CHANGED","Local evaluator was reset");if(f&&(p(f)||r?.key!==f.key))throw new c("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await v()).configuration)},reset(){l++,r=void 0,a=void 0,s=void 0}}}function On(e,n){let t=e.snapshot?.generation,o=he({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n,load:()=>e.localFunnel(n),assertUsable:()=>e.assertFunnel(n)}),r=e.subscribe(()=>{let s=e.snapshot?.generation;e.fresh&&s!==t&&(t=s,o.refresh().catch(()=>{}))}),a=o.session;return Object.assign(o,{session(s){let l=a(s),p=l.evaluate;return Object.assign(l,{async evaluate(...v){return e.fresh||await e.refresh(),p(...v)}})},destroy(){r(),o.reset()}})}function Tn(e){if(typeof window<"u")throw new c("SERVER_ONLY","Secret API keys must stay on the backend");return{start:n=>xt(e,n)}}var re=class extends c{constructor(t,o){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,o);this.decisionId=t;this.decisionRequestId=o}decisionId;decisionRequestId};async function ge(e,n,t,o){let{decisionId:r,requestId:a}=e,s=e,l=250,p=0;for(;;){if(s.decisionId!==r||s.requestId!==a||s.decision&&!pe(s.decision,n))throw new c("INVALID_RESPONSE","Decision request or customer changed");if(s.decision)return s.decision;if(s.status==="failed")throw new c("DECISION_FAILED","Decision execution failed",503,a);if(Date.now()>=t)throw new re(r,a);if(await new Promise(v=>setTimeout(v,Math.min(Math.max(l,p-Date.now()),t-Date.now()))),Date.now()>=t)throw new re(r,a);l=Math.min(1e3,l*2);try{s=await o(r,t)}catch(v){if(v instanceof c&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(v.code)){p=Date.now()+(v.retryAfterSeconds??0)*1e3;continue}throw v}}}function Fe(e){if("remoteEval"in e)throw new c("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");V(e.apiKey,"Funnel decisions are requested by your backend");let n,t,o=new Map;async function r(p,v){let E=p;E.status!=="pending"&&o.delete(E.decisionId);for(let b=0;b<32&&E.evaluation;b++){let d=E.evaluation;if(d.runId!==E.decisionId)throw new c("INVALID_RESPONSE","Local evaluation Run changed");let f=o.get(E.decisionId);if(!f&&d.type==="evaluate_segment"){let S=zt.parse(await a({operation:"segment_configuration",funnelId:e.funnelId,versionId:d.versionId},v));if(S.configuration.scope.projectId!==e.scope.projectId||S.configuration.scope.environment!==e.scope.environment||S.configuration.funnelId!==e.funnelId||S.configuration.versionId!==d.versionId||S.configuration.evaluationRevision!==d.policyRevision)throw new c("SCOPE_MISMATCH","Original decision segment configuration changed");if(o.size>=128)throw new c("COMMAND_PENDING","Reconcile outstanding decisions first");f={operation:"commit_decision_segment",decisionId:E.decisionId,requestId:Oe(E.decisionId,d.visit,`segment:${d.revision}`),nodeId:d.nodeId,visit:d.visit,revision:d.revision,policyRevision:d.policyRevision,generation:S.configuration.growth.generation,...Ot(S.configuration,S.document,d)},o.set(E.decisionId,f)}if(!f){if(d.type!=="evaluate")throw new c("INVALID_RESPONSE","Unknown decision instruction");if((!t||t.versionId!==d.versionId||t.evaluationRevision!==d.policyRevision||t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())&&(t=z.parse(await a({operation:"configuration",funnelId:e.funnelId,versionId:d.versionId},v))),t.scope.projectId!==e.scope.projectId||t.scope.environment!==e.scope.environment||t.funnelId!==e.funnelId)throw new c("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(t.evaluationMode!=="local"||t.versionId!==d.versionId||t.evaluationRevision!==d.policyRevision)throw new c("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(o.size>=128)throw new c("COMMAND_PENDING","Reconcile outstanding Local decisions first");f={operation:"evaluate_decision",decisionId:E.decisionId,requestId:Oe(E.decisionId,d.visit,"evaluation"),nodeId:d.nodeId,visit:d.visit,revision:d.revision,receiptId:d.receiptId,policyRevision:d.policyRevision,generation:t.growth.generation,result:Ct(t,d.nodeId,d,bt)},o.set(E.decisionId,f)}let y=Z.parse(await a(f,v));if(y.decisionId!==p.decisionId||y.requestId!==p.requestId)throw new c("INVALID_RESPONSE","Decision identity changed during local evaluation");o.delete(E.decisionId),E=y}return E}async function a(p,v,E=!1){return N({...e,fetch:(d,f)=>{let y=new Headers(f?.headers);return y.set("Accept-Encoding","identity"),E&&y.set("Prefer","respond-async"),(e.fetch??globalThis.fetch)(d,{...f,headers:y})},timeoutMs:Math.min(e.timeoutMs??1e4,v?Math.max(1,v-Date.now()):12e4)}).request("funnels",p)}async function s(p,v){let E=Z.parse(await a(de.parse({operation:"read_decision",decisionId:p}),v));if(E.decisionId!==p)throw new c("INVALID_RESPONSE","Decision identity changed");return r(E,v)}async function l(p,v,E=!1){let b=de.options[0].parse({...p,operation:"decide",funnelId:e.funnelId}),d;try{d=Z.parse(await a(b,v,E))}catch(f){throw f instanceof c&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(f.code)?new c("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",f.status,p.requestId):f}if(d.requestId!==p.requestId||d.decision&&!pe(d.decision,b.customer))throw new c("INVALID_RESPONSE","Decision request or customer changed");return{response:await r(d,v),customer:b.customer}}return{local(){return n??=he({scope:e.scope,funnelId:e.funnelId,load:()=>a({operation:"local_configuration",funnelId:e.funnelId})})},async configuration(){let p=z.parse(await a({operation:"configuration",funnelId:e.funnelId}));if(p.scope.projectId!==e.scope.projectId||p.scope.environment!==e.scope.environment||p.funnelId!==e.funnelId)throw new c("SCOPE_MISMATCH","Configuration scope changed");return p},features(p={}){return Me({...p,scope:e.scope,load:async()=>at.parse(await a({operation:"feature_config",funnelId:e.funnelId}))})},read:p=>s(p),async submit(p){return(await l(p,void 0,!0)).response},async decide(p){let v=Date.now()+3e4,E=await l(p,v);return ge(E.response,E.customer,v,s)},async reportUsed(p){let v=lt.parse(await a(de.parse({...p,operation:"report_used"})));if(v.decisionId!==p.decisionId||v.eventId!==p.eventId)throw new c("INVALID_RESPONSE","Usage receipt identity changed");return v}}}function xn(e){V(e.apiKey,"Native receipts are verified by your backend","Server API key required");let n=N({...e,timeoutMs:e.timeoutMs??35e3});return{async recover(t){let o=Gt.parse(t);if(o.orderId!==o.receiptId)throw new c("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let r=o.nativeEvidence,a={requestId:o.requestId,customerToken:o.customerToken,purchaseIntentId:o.orderId,...r===null?{intent:"read"}:r.provider==="apple"?{provider:"apple",signedTransaction:r.signedTransaction}:{provider:"google",purchaseToken:r.purchaseToken}},s=m.restoreNativePurchase.response.parse(await n.request(m.restoreNativePurchase.path,a));if(s.operation.requestId!==o.requestId||s.operation.purchaseIntentId!==o.orderId)throw new c("INVALID_RESPONSE","Native receipt request identity changed");let l=jt.parse({scope:s.scope,requestId:o.requestId,orderId:s.operation.orderId,receiptId:s.operation.orderId,orderStatus:s.operation.status,refunded:s.operation.refunded,...s.operation.completion===null?{}:{nativeCompletion:{orderId:s.operation.orderId,receiptId:s.operation.orderId,...s.operation.completion}}});if(l.requestId!==o.requestId||l.orderId!==o.orderId||l.receiptId!==o.receiptId||l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment)throw new c("INVALID_RESPONSE","Current order receipt scope changed");return l}}}var J=u.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function _n(e,n){let t=J.parse(e.inputTokens.total),o=J.parse(e.outputTokens.total),r=J.parse(e.inputTokens.cacheRead??0),a=J.parse(e.inputTokens.cacheWrite??0),s=J.parse(e.outputTokens.reasoning??0);if(r+a>t||s>o||e.inputTokens.noCache!==void 0&&J.parse(e.inputTokens.noCache)!==t-r-a||e.outputTokens.text!==void 0&&J.parse(e.outputTokens.text)!==o-s)throw new c("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:t-r-a,cache_read:r,cache_write:a,output:n==="output"?o:o-s,reasoning:n==="separate"?s:0,input_audio:0,output_audio:0}}function Mn(e){if(typeof window<"u")throw new c("SERVER_ONLY","AI usage belongs on the trusted backend");if(!e.modelId||!["output","separate"].includes(e.reasoning))throw new c("INVALID_REQUEST","Model ID and reasoning pricing are required");async function n(o){await e.persist({context:o,modelId:e.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function t(o,r){let a={context:o,modelId:e.modelId,usage:r,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(a);let s=e.mapTokens?e.mapTokens(r):_n(r,e.reasoning),l=await e.pricing.quoteTokens({modelId:e.modelId,tokens:s});await e.persist({...a,tokens:s,quote:l,phase:"quoted"});let p=await e.pricing.trackTokens(e.client,{...o,quote:l});if(!p.receipt.accepted)throw new c("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await e.persist({...a,tokens:s,quote:l,receipt:p,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:o}){let r=await e.context(),a;try{a=await o()}catch(s){throw await n(r),s}return await t(r,a.usage),a},async wrapStream({doStream:o}){let r=await e.context(),a;try{a=await o()}catch(E){throw await n(r),E}let s=!1,l=!1,p=a.stream.getReader();async function v(){s||l||(l=!0,await n(r))}return{...a,stream:new ReadableStream({async pull(E){try{let{value:b,done:d}=await p.read();if(d){if(!s)throw await v(),new c("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");E.close();return}if(b.type==="finish"){if(s)throw new c("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");s=!0,await t(r,b.usage)}E.enqueue(b)}catch(b){try{await v()}finally{E.error(b),await p.cancel(b)}}},async cancel(E){try{await v()}finally{await p.cancel(E)}}})}}}}function kn(e){V(e.apiKey,"Funnel receipts are sent by your backend");let n=N(e);return{async signal(t){let o=Re.parse({...t,operation:"signal"}),r=st.parse(await n.request("funnels",o));if(r.runId!==t.runId||r.eventId!==t.eventId||r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new c("INVALID_RESPONSE","Receipt identity changed");return r},async readResults(t){let o=Re.parse({operation:"read_results",runId:t}),r=ct.parse(await n.request("funnels",o));if(r.runId!==t||r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new c("INVALID_RESPONSE","Result identity changed");return r}}}function Bn(e){if("remoteEval"in e)throw new c("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");V(e.apiKey,"Campaign entry requires your backend");let n=N({...e,timeoutMs:e.timeoutMs??35e3});return{async decide(t){let o=Date.now()+(e.timeoutMs??3e4),r=Pe.parse({...t,funnelId:e.funnelId,operation:"campaign_decide"}),a=N({...e,timeoutMs:Math.min(e.timeoutMs??35e3,Math.max(1,o-Date.now()))}),s=Z.parse(await a.request("funnels",r));if(s.scope.projectId!==e.scope.projectId||s.scope.environment!==e.scope.environment)throw new c("SCOPE_MISMATCH","Campaign scope changed");return ge(s,r.customer,o,(l,p)=>Fe({...e,timeoutMs:Math.min(e.timeoutMs??1e4,Math.max(1,p-Date.now()))}).read(l))},async start(t){let o=Pe.parse({...t,funnelId:e.funnelId,operation:"campaign_start"}),r=Vt.parse(await n.request("funnels",o));if(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new c("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in r)&&(r.run.source.id!==e.funnelId||!r.customerId||o.customer.type==="id"&&r.customerId!==o.customer.value))throw new c("INVALID_RESPONSE","Campaign Funnel or Customer changed");return r}}}var x=class extends Error{constructor(t,o=409,r=!1,a="fix_request"){super(t);this.code=t;this.status=o;this.retryable=r;this.recovery=a}code;status;retryable;recovery};function Pn(e){if(typeof window<"u")throw new Error("Merchant bridge credentials require a trusted server");let n=se.parse(e.manifest),t={projectId:n.projectId,environmentId:n.environmentId,environment:n.environment},o=n.capabilities.some(r=>["purchases","subscription_changes","refunds","operation_status"].includes(r));for(let[r,a]of Object.entries(Se))if(a.command&&n.capabilities.includes(r)&&!(r==="catalog"&&n.catalog==="static")&&!e.handlers[a.command])throw new Error(`Missing merchant command handler: ${a.command}`);if(o&&(!e.resolveOperationAuthority||!e.handlers["operation.read"]||!n.capabilities.includes("operation_status")))throw new Error("Merchant operations require fresh Longplay authority and an operation lookup handler");return async function(a){let s=crypto.randomUUID(),l="bridge.ping",p,v=async(E,b,d=!1)=>{let f=JSON.stringify({bridgeVersion:X,requestId:s,command:l,scope:t,[d?"error":"data"]:E});if(new TextEncoder().encode(f).byteLength>262144)throw new Error("Merchant response exceeds limit");return new Response(f,{status:b,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store","X-Request-Id":s,...p?await te(f,p,"response"):{}}})};try{if(a.headers.get("X-Indiana-Merchant-Bridge-Version")!==String(X)||a.method!=="POST"||new URL(a.url).pathname!==W)throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",400);if(!/^application\/json(?:\s*;|$)/i.test(a.headers.get("Content-Type")??""))throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",400);let E=a.body?.getReader();if(!E)throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",400);let b=new TextDecoder("utf-8",{fatal:!0}),d="",f=0;try{for(;;){let _=await E.read();if(_.done)break;if(f+=_.value.byteLength,f>16384)throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",413);d+=b.decode(_.value,{stream:!0})}d+=b.decode()}finally{await E.cancel().catch(()=>{}),E.releaseLock()}let y=ot.safeParse(JSON.parse(d));if(!y.success)throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",400);let S=y.data;if(s=S.requestId,l=S.command,Object.keys(t).some(_=>S.scope[_]!==t[_]))throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);let k=S.command==="bridge.ping"||S.command==="bridge.describe",D=S.command==="catalog.read";if((k||D||a.headers.has(Q))&&(p=e.authentication.find(_=>_.keyId===a.headers.get(Q)),!p||!await ne(d,a.headers,p,"request")))throw p=void 0,new x("MERCHANT_BRIDGE_AUTHENTICATION_FAILED",401);if(S.command==="bridge.ping")return v(Ee["bridge.ping"].parse(S.data),200);if(S.command==="bridge.describe")return v(n,200);let g=Object.entries(Se).find(([,_])=>_.command===S.command);if(!g||!n.capabilities.includes(g[0]))throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let i=e.handlers[S.command];if(!i)throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);if(!D&&a.headers.has("Cookie")&&(a.headers.get("Origin")!==new URL(a.url).origin||["cross-site","same-site"].includes(a.headers.get("Sec-Fetch-Site")??"")))throw new x("MERCHANT_BRIDGE_FORBIDDEN",403);let w=D?{kind:"service"}:await e.authorize(a,S),R=w.kind,C=["purchase.execute","subscription.change","refund.execute"].includes(S.command),A=C||S.command==="operation.read";if(!(A&&p!==void 0&&R==="service")&&(S.command==="refund.execute"?R!=="administrator":!D&&R!=="user"))throw new x("MERCHANT_BRIDGE_FORBIDDEN",403);if(w.kind==="user"&&["purchase.execute","operation.read","subscription.change","customer.commerce.read","presentation.report"].includes(S.command)&&!u.uuid().safeParse(w.customerId).success)throw new x("MERCHANT_BRIDGE_UNAUTHENTICATED",401);let M=i,F=Ee[S.command].parse(S.data),B={request:a,command:S.command,scope:t,principal:w},T;if(A){let _=j.parse(F);if(w.kind==="user"&&w.customerId!==_.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!e.resolveOperationAuthority)throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let P=ce.parse(await e.resolveOperationAuthority(_,B));if(P.operationId!==_.operationId||P.customerId!==_.customerId||Object.keys(t).some(G=>P.scope[G]!==t[G]))throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);B.authority=P;let H=S.command==="purchase.execute"?"purchase":S.command==="subscription.change"?"subscription_change":S.command==="refund.execute"?"refund":P.instruction.type;if(P.instruction.type!==H)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!C)T=we.parse(await M(F,B));else{if(P.confirmedAt===null)throw new x("MERCHANT_BRIDGE_OPERATION_NOT_CONFIRMED",409);let G=we.parse(await e.handlers["operation.read"](_,{...B,command:"operation.read"}));if(G.operationId!==_.operationId||G.customerId!==_.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(G.lookup==="found")T=G.execution;else{if(!P.initialExecutionAllowed)throw new x("MERCHANT_BRIDGE_RECOVERY_REQUIRED",409,!1,"recover_operation");if(Date.parse(P.instruction.expiresAt)<=Date.now())throw new x("MERCHANT_BRIDGE_OPERATION_EXPIRED",409,!1,"reload_state");if(!n.capabilities.includes("billing_records")||je(P.instruction).some(U=>!n.billingEvents.some(on=>on===U))||Ge(P.instruction).some(U=>!n.profiles.includes(U)))throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");try{T=nt.parse(await M(F,B))}catch(U){throw U instanceof x?U:new x("MERCHANT_BRIDGE_RESULT_UNKNOWN",503,!1,"recover_operation")}}if(T.type!==H)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}}else T=rt[S.command].parse(await M(F,B));if(w.kind==="user"){if("nativeUserId"in T&&T.nativeUserId!==w.nativeUserId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("customerId"in T&&T.customerId!==w.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("session"in T&&w.customerId&&T.session.customerId!==w.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("presentation"in T&&T.presentation&&w.customerId&&T.presentation.customerId!==w.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}if("operationId"in T&&(T.operationId!==j.parse(S.data).operationId||T.customerId!==j.parse(S.data).customerId))throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return v(T,C&&("paymentStatus"in T&&["pending","unknown"].includes(T.paymentStatus)||"status"in T&&["pending","unknown","scheduled"].includes(T.status))?202:200)}catch(E){let b=E instanceof x?E:E instanceof SyntaxError?new x("MERCHANT_BRIDGE_INVALID_REQUEST",400):new x("MERCHANT_BRIDGE_INVALID_RESPONSE",500);return v({code:b.code,message:b.code,retryable:b.retryable,recovery:b.recovery},b.status,!0)}}}function Dn(e){return async(n,t)=>{let o=()=>e.readSubscriptionOperation(n),r=()=>e.readSubscriptionUpdate(n),a=()=>e.readRefund(n),s=t.command==="purchase.execute"?[o]:t.command==="subscription.change"?[r]:t.command==="refund.execute"?[a]:[o,r,a];for(let l of s)try{let p=await l(),v="authority"in p.operation?p.operation.authority:void 0;if(!v)throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");let E=ce.parse(v);if(E.customerId!==n.customerId||E.operationId!==n.operationId||Object.keys(t.scope).some(b=>E.scope[b]!==t.scope[b]))throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return E}catch(p){if(t.command==="operation.read"&&p instanceof c&&p.code==="NOT_FOUND")continue;throw p}throw new x("MERCHANT_BRIDGE_OPERATION_NOT_FOUND",404,!1,"reload_state")}}function Fn(e){if(typeof window<"u")throw new Error("Merchant protocol credentials require a trusted server");let n=ke.parse(e.manifest),t=ie.parse(e.authentication),o={projectId:n.projectId,environmentId:n.environmentId,environment:n.environment},r=e.now??Date.now,a=d=>{throw new c("INVALID_RESPONSE",d)},s=(d,f)=>Ie(d)===Ie(f);function l(d){new TextEncoder().encode(d).byteLength>262144&&a("Merchant protocol body exceeds limit");try{return JSON.parse(d)}catch{return a("Invalid merchant protocol JSON")}}function p(d){let f=kt.parse(d);return s(f.scope,o)||a("Merchant protocol scope mismatch"),f.command==="requirement.check"&&(n.capabilities.includes("requirement_checks")||a("Merchant Check capability unavailable"),s(f.data.subject.scope,o)||a("Merchant Check subject crosses scope")),f.command==="operation.prepare"&&(!n.capabilities.includes("preparations")||!s(f.data.request.subject.scope,o))&&a("Merchant preparation capability unavailable"),f.command==="purchase.terminate"&&!n.capabilities.includes("checkout_termination")&&a("Checkout termination capability unavailable"),f}function v(d){if(d.command!=="operation.prepare")return;let f=d.data;return(!s(f.request.subject.scope,o)||!f.preparationAllowed||Date.parse(f.requestedAt)>r()||Date.parse(f.request.expiresAt)<=r()||!n.preparationActions.includes(f.request.action))&&a("Merchant preparation requires fresh scoped authority"),f}function E(d,f){let y=Bt(d.command).parse(f);if((y.requestId!==d.requestId||!s(y.scope,o))&&a("Merchant reply correlation mismatch"),"error"in y)return y;if(d.command==="purchase.terminate"&&"outcome"in y.data&&(y.data.operationId!==d.data.operationId||y.data.customerId!==d.data.customerId)&&a("Checkout termination changed the original operation"),d.command==="bridge.ping"&&"challenge"in y.data&&y.data.challenge!==d.data.challenge&&a("Merchant ping challenge mismatch"),d.command==="bridge.describe"&&"bridgeVersion"in y.data&&!s({projectId:y.data.projectId,environmentId:y.data.environmentId,environment:y.data.environment},o)&&a("Merchant declaration crosses scope"),d.command==="requirement.check"&&"observation"in y.data&&(!s(y.data.observation.subject,d.data.subject)||!Je(d.data.requirement,y.data)||!n.checkKinds.includes(y.data.kind))&&a("Merchant Check changed the original requirement or subject"),d.command==="operation.prepare"&&"quoteTermsDigest"in y.data){let S=v(d);(!s(y.data.request,S.request)||Date.parse(y.data.expiresAt)<=r()||Date.parse(y.data.observedAt)<Date.parse(S.requestedAt)||Date.parse(y.data.observedAt)>r())&&a("Merchant quote changed its authorized request or validity")}return y}let b=async d=>{let f=JSON.stringify(d);return l(f),{body:f,headers:new Headers({"Content-Type":"application/json","Cache-Control":"private, no-store",[oe]:"4",...await te(f,t,"response",r(),4)})}};return{version:4,path:W,async encodeRequest(d,f){let y=p({bridgeVersion:4,requestId:crypto.randomUUID(),scope:o,command:d,data:f});v(y);let S=JSON.stringify(y);l(S);let k=new Headers({"Content-Type":"application/json",[oe]:"4",...await te(S,t,"request",r(),4)});return{body:S,headers:k,async readResponse(D,g){l(D),(g.get(oe)!=="4"||!await ne(D,g,t,"response",r(),4))&&a("Merchant response authentication failed");let i=E(y,l(D));if("error"in i)throw new ye(i.error);return i.data}}},async decodeRequest(d,f){l(d),(f.get(oe)!=="4"||f.get(Q)!==t.keyId||!await ne(d,f,t,"request",r(),4))&&a("Merchant request authentication failed");let y=p(l(d));return v(y),y},async encodeResponse(d,f){let y=p(d),S=E(y,{...y,data:f});return b(S)},async encodeError(d,f){let y=p(d),{data:S,...k}=y;return b(E(y,{...k,error:Be.parse(f)}))}}}var ye=class extends Error{constructor(t){super(t.message);this.problem=t}problem};export{re as FunnelDecisionTimeoutError,fe as FunnelProcessEntrySuppressedError,c as LongplayError,x as MerchantBridgeHandlerError,ye as MerchantBridgeProtocolError,fn as aiPriceSnapshotSchema,hn as aiTokenQuoteSchema,gn as createAiPricing,Mn as createAiUsageMiddleware,dn as createConfigurationSync,yn as createConfiguredAiPricing,Me as createFeatureClient,Bn as createFunnelCampaignClient,Fe as createFunnelDecisionClient,he as createFunnelLocalEvaluator,kn as createFunnelOrchestrationClient,Rn as createFunnelProcessAdapter,ln as createFunnelStartClient,De as createGuestToken,mn as createLocalFunnelClient,Cn as createLongplayServer,Dn as createMerchantBridgeAuthorityResolver,Pn as createMerchantBridgeHandler,Fn as createMerchantBridgeProtocol,xn as createNativeReceiptClient,Tn as createPaywallStartClient,On as createSynchronizedFunnelLocalEvaluator,un as entitlementRequirementDigest,pn as evaluateFunnelNode,cn as merchantConfirmationMatchesTerms,an as merchantPreparationRequestDigest,sn as merchantQuoteTermsDigest,bn as renewFunnelRun,te as signMerchantBridgeMessage,ne as verifyMerchantBridgeMessage};