@tinkerlandai/longplay-sdk 0.10.42 → 0.10.43

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