@tinkerlandai/longplay-sdk 0.10.79 → 0.10.81
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.
- package/CHANGELOG.md +11 -0
- package/dist/{chunk-ZHVVJBT6.js → chunk-3P7M3WT7.js} +1 -1
- package/dist/{chunk-Z5JTYDD5.js → chunk-3ZOUIESZ.js} +1 -1
- package/dist/{chunk-GADT6JMW.js → chunk-7QPCNDIY.js} +1 -1
- package/dist/{chunk-BLXI5I3S.js → chunk-A6GBOXP2.js} +2 -2
- package/dist/{chunk-YQ2PQWHZ.js → chunk-BSC3VAYP.js} +1 -1
- package/dist/{chunk-5BPZUW6B.js → chunk-BT7IC765.js} +1 -1
- package/dist/{chunk-7KW3LCWQ.js → chunk-CKMSSBJM.js} +1 -1
- package/dist/{chunk-PGNIOWKY.js → chunk-FPJ3FE26.js} +1 -1
- package/dist/chunk-HHBDNW52.js +1 -0
- package/dist/{chunk-GB74QWAG.js → chunk-LXAOFLCO.js} +1 -1
- package/dist/{chunk-72UVQYXH.js → chunk-M5TCDVMJ.js} +1 -1
- package/dist/{chunk-I5ZXIKOT.js → chunk-ME6QTD5Y.js} +1 -1
- package/dist/{chunk-3WCIX4VH.js → chunk-OJZWFIG3.js} +1 -1
- package/dist/{chunk-PG5Q3B7Z.js → chunk-PP3FCEXY.js} +1 -1
- package/dist/{chunk-FFEJS4K3.js → chunk-S2S4ROGY.js} +1 -1
- package/dist/chunk-SVRKXSZR.js +1 -0
- package/dist/{chunk-GJPOVI7F.js → chunk-TGCVYHPW.js} +1 -1
- package/dist/chunk-TYDSAHJO.js +1 -0
- package/dist/{chunk-WU6HDOZM.js → chunk-UBRDRCJZ.js} +1 -1
- package/dist/chunk-V7QPMA2C.js +1 -0
- package/dist/{chunk-ORR47GDS.js → chunk-XLGNBPGF.js} +1 -1
- package/dist/{chunk-NS4YGWQP.js → chunk-ZTKPJTE4.js} +1 -1
- package/dist/{content-6MJOU3SX.js → content-VD374F7V.js} +1 -1
- package/dist/{funnel-host-purchase-526HVMXY.js → funnel-host-purchase-KVU6FBVO.js} +1 -1
- package/dist/{funnel-host-recovery-paywall-GRX7CLGF.js → funnel-host-recovery-paywall-X7HESLZM.js} +1 -1
- package/dist/{funnel-local-client-2Yx0Q_lF.d.ts → funnel-local-client-CsWyDEBw.d.ts} +57 -0
- package/dist/{funnel-paywall-copies-SKNQNABD.js → funnel-paywall-copies-LPOTYSTS.js} +1 -1
- package/dist/{funnel-paywall-prerender-GVHYSFWI.js → funnel-paywall-prerender-22AH6WEM.js} +1 -1
- package/dist/{funnel-process-client-BTusJtqx.d.ts → funnel-process-client-CVqSkdSl.d.ts} +1 -1
- package/dist/{funnel-runtime-host-4KBMPKBE.js → funnel-runtime-host-RHIDG6EF.js} +1 -1
- package/dist/index.d.ts +50 -6
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/{operation-contracts-3JEVPMO2.js → operation-contracts-YJM6772C.js} +1 -1
- package/dist/page.js +1 -1
- package/dist/{paywall-22EYVJAK.js → paywall-CMDMDGJ4.js} +1 -1
- package/dist/{paywall-content-XH344BMX.js → paywall-content-Z4LKDIO2.js} +1 -1
- package/dist/{paywall-session-TJ3X7NZA.js → paywall-session-JDJ4E4BO.js} +1 -1
- package/dist/react-native.d.ts +4 -4
- package/dist/react-native.js +1 -1
- package/dist/server.d.ts +2 -2
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-2WXUJGGZ.js +0 -1
- package/dist/chunk-PGKKIL6M.js +0 -1
- package/dist/chunk-SYFRWKJP.js +0 -1
- package/dist/chunk-XH6VXXCX.js +0 -1
- /package/dist/{chunk-BLXI5I3S.js.LEGAL.txt → chunk-A6GBOXP2.js.LEGAL.txt} +0 -0
package/dist/openrouter.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-Y6KA56V2.js";import"./chunk-SX7U2ONB.js";import"./chunk-
|
|
1
|
+
import"./chunk-Y6KA56V2.js";import"./chunk-SX7U2ONB.js";import"./chunk-OJZWFIG3.js";import"./chunk-KCUE2VFJ.js";import{a as i}from"./chunk-UGATOG2T.js";import"./chunk-LFR2LWYC.js";import"./chunk-3P7M3WT7.js";import"./chunk-5MRSFLQA.js";import{b as A}from"./chunk-W22ESUYY.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 +1 @@
|
|
|
1
|
-
import{e as o}from"./chunk-
|
|
1
|
+
import{e as o}from"./chunk-CKMSSBJM.js";import"./chunk-FPJ3FE26.js";import"./chunk-2OBXRQMW.js";import"./chunk-7QPCNDIY.js";import"./chunk-BT7IC765.js";import"./chunk-ME6QTD5Y.js";import"./chunk-6XRQR43F.js";import"./chunk-3532HSBP.js";import"./chunk-67WFVDTV.js";import"./chunk-6VVQWTHV.js";import"./chunk-VILB5M4X.js";import"./chunk-SX7U2ONB.js";import"./chunk-KCUE2VFJ.js";import"./chunk-Y3W5G4BF.js";import"./chunk-FYUMVOCV.js";import"./chunk-DUS5V65Z.js";import"./chunk-BOT6ZDLK.js";import"./chunk-A5WUQLAO.js";import"./chunk-LFR2LWYC.js";import"./chunk-W22ESUYY.js";import"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";export{o as apiOperations};
|
package/dist/page.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as o,e as r,f as e,g as f}from"./chunk-
|
|
1
|
+
import{d as o,e as r,f as e,g as f}from"./chunk-A6GBOXP2.js";import"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-3P7M3WT7.js";import"./chunk-5MRSFLQA.js";import"./chunk-DSPLGTQI.js";import"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";export{f as createPageExperiments,o as mergeQueryStrings,r as pageAttributes,e as readPayload};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a}from"./chunk-
|
|
1
|
+
import{a}from"./chunk-SVRKXSZR.js";import"./chunk-CHRNCOXJ.js";import"./chunk-W32FI2A2.js";import"./chunk-CO6HDNOC.js";import"./chunk-EQBJNU6R.js";import"./chunk-MOIVJERE.js";import"./chunk-6XRQR43F.js";import"./chunk-3532HSBP.js";import"./chunk-67WFVDTV.js";import"./chunk-VILB5M4X.js";import"./chunk-OJZWFIG3.js";import"./chunk-KCUE2VFJ.js";import"./chunk-Y3W5G4BF.js";import"./chunk-FYUMVOCV.js";import"./chunk-DUS5V65Z.js";import"./chunk-BOT6ZDLK.js";import"./chunk-A5WUQLAO.js";import"./chunk-UGATOG2T.js";import"./chunk-LFR2LWYC.js";import"./chunk-3P7M3WT7.js";import"./chunk-5MRSFLQA.js";import"./chunk-W22ESUYY.js";import"./chunk-DSPLGTQI.js";import"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";export{a as showPaywall};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as a}from"./chunk-
|
|
1
|
+
import{b as a}from"./chunk-3ZOUIESZ.js";import"./chunk-7QPCNDIY.js";import"./chunk-BT7IC765.js";import"./chunk-ME6QTD5Y.js";import"./chunk-6XRQR43F.js";import"./chunk-3532HSBP.js";import"./chunk-67WFVDTV.js";import"./chunk-6VVQWTHV.js";import"./chunk-VILB5M4X.js";import"./chunk-OJZWFIG3.js";import"./chunk-KCUE2VFJ.js";import"./chunk-Y3W5G4BF.js";import"./chunk-FYUMVOCV.js";import"./chunk-DUS5V65Z.js";import"./chunk-BOT6ZDLK.js";import"./chunk-A5WUQLAO.js";import"./chunk-UGATOG2T.js";import"./chunk-LFR2LWYC.js";import"./chunk-3VUPVXAV.js";import"./chunk-3P7M3WT7.js";import"./chunk-5MRSFLQA.js";import"./chunk-W22ESUYY.js";import"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";export{a as readPaywallContent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a}from"./chunk-
|
|
1
|
+
import{a}from"./chunk-TGCVYHPW.js";import"./chunk-CKMSSBJM.js";import"./chunk-FPJ3FE26.js";import"./chunk-S2S4ROGY.js";import"./chunk-EQBJNU6R.js";import"./chunk-MOIVJERE.js";import"./chunk-2OBXRQMW.js";import"./chunk-PUDTOCQF.js";import"./chunk-3ZOUIESZ.js";import"./chunk-7QPCNDIY.js";import"./chunk-BT7IC765.js";import"./chunk-ME6QTD5Y.js";import"./chunk-6XRQR43F.js";import"./chunk-3532HSBP.js";import"./chunk-67WFVDTV.js";import"./chunk-6VVQWTHV.js";import"./chunk-VILB5M4X.js";import"./chunk-SX7U2ONB.js";import"./chunk-OJZWFIG3.js";import"./chunk-KCUE2VFJ.js";import"./chunk-Y3W5G4BF.js";import"./chunk-FYUMVOCV.js";import"./chunk-DUS5V65Z.js";import"./chunk-BOT6ZDLK.js";import"./chunk-A5WUQLAO.js";import"./chunk-UGATOG2T.js";import"./chunk-LFR2LWYC.js";import"./chunk-3VUPVXAV.js";import"./chunk-3P7M3WT7.js";import"./chunk-5MRSFLQA.js";import"./chunk-W22ESUYY.js";import"./chunk-DSPLGTQI.js";import"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";export{a as createPaywallSession};
|
package/dist/react-native.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { f as createCustomerClient, d as createFunnelClient } from './funnel-process-client-
|
|
2
|
-
export { F as FunnelProcessAdapter, a as FunnelProcessOptions, c as createFunnelProcess } from './funnel-process-client-
|
|
3
|
-
import { I as IndianaOptions, S as SessionCredentials, N as Scope, B as createFunnelRunController, x as PaywallStartInput, l as createPaywallSession } from './funnel-local-client-
|
|
4
|
-
export { F as FunnelCommandStorage, h as FunnelRunController, u as LocalFunnelClientOptions, v as LongplayError, w as PaywallPurchaseInput, P as PaywallSession, y as PushHost, z as PushJournal, A as createFeatureClient, D as createLocalFunnelClient } from './funnel-local-client-
|
|
1
|
+
import { f as createCustomerClient, d as createFunnelClient } from './funnel-process-client-CVqSkdSl.js';
|
|
2
|
+
export { F as FunnelProcessAdapter, a as FunnelProcessOptions, c as createFunnelProcess } from './funnel-process-client-CVqSkdSl.js';
|
|
3
|
+
import { I as IndianaOptions, S as SessionCredentials, N as Scope, B as createFunnelRunController, x as PaywallStartInput, l as createPaywallSession } from './funnel-local-client-CsWyDEBw.js';
|
|
4
|
+
export { F as FunnelCommandStorage, h as FunnelRunController, u as LocalFunnelClientOptions, v as LongplayError, w as PaywallPurchaseInput, P as PaywallSession, y as PushHost, z as PushJournal, A as createFeatureClient, D as createLocalFunnelClient } from './funnel-local-client-CsWyDEBw.js';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
import { J as JsonValue } from './growth-rules-B4YYy64R.js';
|
|
7
7
|
export { a as ConfigurationStorage, b as ConfigurationSyncOptions, c as createConfigurationSync } from './configuration-sync-Dad8B5Pv.js';
|
package/dist/react-native.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as S,c as E,d as T}from"./chunk-
|
|
1
|
+
import{b as S,c as E,d as T}from"./chunk-PP3FCEXY.js";import"./chunk-XLGNBPGF.js";import{a as A}from"./chunk-TGCVYHPW.js";import{e as P}from"./chunk-CKMSSBJM.js";import"./chunk-FPJ3FE26.js";import{h as b,i as x,k as L}from"./chunk-ZTKPJTE4.js";import{E as C}from"./chunk-BSC3VAYP.js";import"./chunk-F4AIEI5N.js";import"./chunk-S2S4ROGY.js";import"./chunk-EQBJNU6R.js";import"./chunk-MOIVJERE.js";import"./chunk-2OBXRQMW.js";import"./chunk-PUDTOCQF.js";import"./chunk-3ZOUIESZ.js";import"./chunk-7QPCNDIY.js";import"./chunk-BT7IC765.js";import"./chunk-ME6QTD5Y.js";import"./chunk-6XRQR43F.js";import"./chunk-3532HSBP.js";import"./chunk-67WFVDTV.js";import"./chunk-KX67ZM7H.js";import"./chunk-6VVQWTHV.js";import"./chunk-VILB5M4X.js";import"./chunk-SX7U2ONB.js";import"./chunk-OJZWFIG3.js";import"./chunk-KCUE2VFJ.js";import"./chunk-Y3W5G4BF.js";import"./chunk-FYUMVOCV.js";import"./chunk-DUS5V65Z.js";import"./chunk-BOT6ZDLK.js";import"./chunk-A5WUQLAO.js";import{a as r}from"./chunk-UGATOG2T.js";import{h as R}from"./chunk-LFR2LWYC.js";import"./chunk-3VUPVXAV.js";import"./chunk-3P7M3WT7.js";import"./chunk-5MRSFLQA.js";import"./chunk-W22ESUYY.js";import"./chunk-DSPLGTQI.js";import"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.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.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { F as FoundationApi, I as InvoiceModeParams } from './api-KIp0I50M.js';
|
|
2
|
-
import { X as IndianaServerOptions, v as IndianaError, Y as FunnelProcessSuppression, Z as FunnelProcessCommand, T as FunnelProcessResponse, C as CustomerSession, Q as FunnelProcessOpenInput, V as FunnelProcessMutation, x as PaywallStartInput, P as PaywallSession, n as FeatureClientOptions, R as RemoteFeatureResult } from './funnel-local-client-
|
|
3
|
-
export { m as FeatureClient, d as FunnelStartInput, L as LocalFunnelClient, u as LocalFunnelClientOptions, A as createFeatureClient, _ as createFunnelStartClient, D as createLocalFunnelClient } from './funnel-local-client-
|
|
2
|
+
import { X as IndianaServerOptions, v as IndianaError, Y as FunnelProcessSuppression, Z as FunnelProcessCommand, T as FunnelProcessResponse, C as CustomerSession, Q as FunnelProcessOpenInput, V as FunnelProcessMutation, x as PaywallStartInput, P as PaywallSession, n as FeatureClientOptions, R as RemoteFeatureResult } from './funnel-local-client-CsWyDEBw.js';
|
|
3
|
+
export { m as FeatureClient, d as FunnelStartInput, L as LocalFunnelClient, u as LocalFunnelClientOptions, A as createFeatureClient, _ as createFunnelStartClient, D as createLocalFunnelClient } from './funnel-local-client-CsWyDEBw.js';
|
|
4
4
|
import * as zod from 'zod';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
import { S as StackNode } from './screen-Pv_pViF6.js';
|
package/dist/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as pn}from"./chunk-
|
|
1
|
+
import{a as pn}from"./chunk-TYDSAHJO.js";import{a as I}from"./chunk-EQUVI5QU.js";import{a as fn,b as hn,c as gn,d as yn}from"./chunk-Y6KA56V2.js";import{a as xt}from"./chunk-TGCVYHPW.js";import{a as Ue,b as Ve,c as qe,d as He,e as m}from"./chunk-CKMSSBJM.js";import"./chunk-FPJ3FE26.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-ZTKPJTE4.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-BSC3VAYP.js";import"./chunk-F4AIEI5N.js";import{c as h}from"./chunk-S2S4ROGY.js";import"./chunk-EQBJNU6R.js";import"./chunk-MOIVJERE.js";import"./chunk-2OBXRQMW.js";import{a as Et,b as _e}from"./chunk-PUDTOCQF.js";import"./chunk-3ZOUIESZ.js";import"./chunk-7QPCNDIY.js";import{e as at}from"./chunk-BT7IC765.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-ME6QTD5Y.js";import"./chunk-6XRQR43F.js";import"./chunk-3532HSBP.js";import{A as W,B as oe,C as tt,D as Se,E as ie,G as se,H as Ce,M as j,O as ce,P as nt,R as Ee,S as rt,T as ot,f as Ge,g as je,j as we,r as ze,s as Ke,u as an,v as sn,y as cn,z as X}from"./chunk-67WFVDTV.js";import{b as Oe}from"./chunk-KX67ZM7H.js";import{e as ve,i as Ze,l as it}from"./chunk-6VVQWTHV.js";import"./chunk-VILB5M4X.js";import"./chunk-SX7U2ONB.js";import"./chunk-OJZWFIG3.js";import{a as Ne,b as Le}from"./chunk-KCUE2VFJ.js";import{o as ue}from"./chunk-Y3W5G4BF.js";import"./chunk-FYUMVOCV.js";import{i as un,k as $e,l as Qe,m as Je}from"./chunk-DUS5V65Z.js";import{c as Ie}from"./chunk-BOT6ZDLK.js";import{e as Xe,h as We}from"./chunk-A5WUQLAO.js";import{a as c}from"./chunk-UGATOG2T.js";import{h as Y}from"./chunk-LFR2LWYC.js";import"./chunk-3VUPVXAV.js";import"./chunk-3P7M3WT7.js";import"./chunk-5MRSFLQA.js";import{b as u}from"./chunk-W22ESUYY.js";import"./chunk-DSPLGTQI.js";import{a as Ye}from"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.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-KV5MZ4NI.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-
|
|
1
|
+
import{a as pe,c as fe}from"./chunk-KV5MZ4NI.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-A6GBOXP2.js";import{a as re,b as ae,c as se,d as oe}from"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-3P7M3WT7.js";import"./chunk-5MRSFLQA.js";import{b as o}from"./chunk-W22ESUYY.js";import"./chunk-DSPLGTQI.js";import{c as te,e as ie,g as M}from"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.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
package/dist/chunk-2WXUJGGZ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as ve,b as be}from"./chunk-7CZEXBQY.js";import{d as qe,e as ne}from"./chunk-MOIVJERE.js";import{a as Me}from"./chunk-UGATOG2T.js";import{a as R}from"./chunk-DSPLGTQI.js";var Xe=5*6e4,$e=15e3,Le=new WeakMap;function an(s){return Le.get(s)}var k=s=>Array.isArray(s)?s.map(k):s&&typeof s=="object"?Object.fromEntries(Object.keys(s).sort().map(n=>[n,k(s[n])])):s,T=(s,n)=>JSON.stringify(k(s))===JSON.stringify(k(n)),re=s=>JSON.stringify(k([s.funnelId,s.locale??null,s.parameters??{}])),Qe=["onObservationChange","onPurchaseIntent","onPurchase","onCheckoutUrl","resumeCheckout","allowNewPurchase","checkoutNavigation","terminateCheckout","beforeCheckoutReplacement","purchaseConfirmation","confirmOnHostedCheckout","resolveOfferId","prepareSubscriptionChange","resolveSubscriptionChange","onOpenUrl","onEvent","onAction","onComplete","onError"];function Ye(s,n,S){let O=e=>structuredClone({funnelId:e.funnelId,locale:e.locale,parameters:e.parameters}),m,_="",E=n.start instanceof Promise?void 0:O(n.start),ae=e=>e?.parameters?.commerce,j=Promise.resolve(n.start).then(e=>e?O(e):void 0),te=n.maxAgeMs??Xe,Ie=new AbortController,g=AbortSignal.any([Ie.signal,n.client.identitySignal,...n.signal?[n.signal]:[]]),oe=()=>d("released","aborted"),a="preparing",Se,J,le=()=>{},U=0,b=null,v=null,C=null,p=null,h,x,V,Ce=new Map,P=null,W=new Set,D=new Map,ie,Ae=new Promise(e=>ie=e),G,se=new Promise(e=>G=e),ce,Te=new Promise(e=>ce=e);function K(e,r){a!==e&&(a=e,Se=r,R(n.onState,e))}function je(){g.removeEventListener("abort",oe),X(),v?.destroy(),v=null,b?.remove(),b=null,C=null}function d(e,r){["adopted","unavailable","released","closed"].includes(a)||(K(e,r),je(),ie(!1),G(!1),B(!1),ce(null))}function N(e){a!=="shown"&&d("unavailable",e)}let f,ue=!1,F=n.client.paywallCopies,de,Re=new Promise(e=>de=e),fe=!1,M=!1,ke,z=n.whenPurchasePending==="recover"&&!S,B,Je=new Promise(e=>B=e);function Ue(e){if(!z||f||!e||!p||!V||!A(p,V.commerce)||!["preparing","ready","shown"].includes(a))return!1;let r={savedAt:Date.now(),funnelId:e,context:V,resolution:structuredClone(p)};return f=r,we(r),Z(),!0}function pe(e){return!z||!f||!["preparing","ready","shown"].includes(a)?!1:(M=!0,ke=e,a==="shown"&&_e(),!0)}function _e(){let e=f?.context.locale??n.locale??"";v?.setPurchaseRecovery(e.startsWith("zh")?"正在查询原订单…":"Checking your purchase…")}function we(e){Re.then(r=>{r&&F&&F.write(r,e).catch(()=>{})})}function Ee(e){Re.then(async r=>{if(!r||!F)return;let l=await F.read(r);ue||l&&"presented"in l||await F.write(r,e)}).catch(()=>{})}let ye=e=>`error:${e?.code??e?.name??"unknown"}`,me=s.ownerDocument.defaultView,q=!S,Ve=null,H=!1,We=e=>e.storageArea===me?.localStorage&&(e.key===null||e.key.startsWith("indiana.funnel.purchases.")),De=e=>{We(e)&&$()},Ge=S?()=>{}:n.client.subscribe(()=>$());function X(){q&&(q=!1,me?.removeEventListener("storage",De),Ge(),le())}let ge=()=>q&&(a==="ready"||a==="preparing");function he(e){(a==="ready"||a==="preparing")&&d("unavailable",e)}function $(){if(a==="ready"&&Date.now()-U>=te)return X();H=!0,Ve??=(async()=>{for(;H&&m&&!M&&ge();){H=!1;try{await n.client.retained()==="pending"&&!pe("purchase_pending")&&he("purchase_pending")}catch(e){g.aborted?d("released","aborted"):he(ye(e))}}})().finally(()=>{Ve=null,H&&m&&!M&&ge()&&$()})}S||me?.addEventListener("storage",De),g.addEventListener("abort",oe,{once:!0});let Fe=S?Promise.resolve("none"):n.client.findPurchase();Fe.catch(()=>{});let Q;function Y(e){let r=Q?.paywallVersionId??n.paywallVersionId??f?.resolution.id??p?.id,l=JSON.stringify(k([r??null,e])),i=Ce.get(l);return i||(i=n.client.readPaywall({paywallVersionId:r,...r?{}:{paywallId:Q?.paywallId??n.paywallId},...e}),Ce.set(l,i)),i}function A(e,r){let l=Object.values(e.capabilities.plans),i=Object.values(e.document.buttons).some(t=>t.type==="checkout");return i&&l.length===0?!1:r.intent==="subscription_change"&&i?l.some(t=>t.available):l.every(t=>t.available)}function Pe(e,r){if(p&&!ne(e,p))return d("unavailable","paywall_changed"),!1;p=e,V=r,B(!0);for(let l of D.keys())R(l,structuredClone(e));return!0}function He(e,r){if(!(!p||!["preparing","ready","shown"].includes(a))){if(!ne(e,p))return N("paywall_changed");if(!A(e,r.commerce))return N("plan_unavailable");Pe(e,r)}}async function L(){let e=await Te;if(!e)throw new Me("PURCHASE_PENDING","The purchase did not start; open it again");return e}let Ke={get view(){return P?P.view:p},get signal(){return P?.signal??n.client.identitySignal},get quote(){return P?.quote??null},get operation(){return P?.operation??null},webViewUrl:"bundled",get canReselect(){return P?.canReselect},get recovery(){return P?.recovery},get pendingCancellation(){return P?.pendingCancellation},subscribe(e){return D.set(e,P?.subscribe?.(e)??(()=>{})),()=>{D.get(e)?.(),D.delete(e)}},refresh:async()=>P?P.refresh():structuredClone(p),preview:async e=>(await L()).preview(e),confirm:async()=>(await L()).confirm(),cancel:async()=>(await L()).cancel(),read:async()=>(await L()).read(),destroy(){P?.destroy()}},w={options:{},handoff:{}},Oe={loading:"host",focusAtReveal:!0,settleMotionAtReveal:!0,signal:n.client.identitySignal,start:async()=>Ke,canInteract:()=>w.options.canInteract?w.options.canInteract():!["unavailable","released","closed"].includes(a),async beforeAction(){let e=a!=="adopted",r=p?.capabilities,l=await L();if(e&&!T(l.view?.capabilities,r))throw new qe;await w.options.beforeAction?.()}};for(let e of Qe)Object.defineProperty(Oe,e,{enumerable:!0,get:()=>w.options[e]});function Z(){a!=="preparing"||!C||!v||!f&&(!m||!T(V?.commerce,ae(m))||V?.locale!==m.locale)||(K("ready"),ie(!0))}let xe={present(e){if(w.handoff.present)return w.handoff.present(e);a==="preparing"&&(C=e,U=Date.now(),Z())},async dismiss(){if(w.handoff.dismiss)return w.handoff.dismiss();d("closed");for(let e of[...W])R(e)},async closeAction(e){if(w.handoff.closeAction)return w.handoff.closeAction(e);w.options.onAction?await w.options.onAction(e):await xe.dismiss()},quoteError(e){w.handoff.quoteError?w.handoff.quoteError(e):R(w.options.onError,e)}};async function ze(){if(n.paywallVersionId||n.paywallId)return{paywallVersionId:n.paywallVersionId,paywallId:n.paywallId};let e=n.configuration;if(!e)return d("unavailable","paywall_missing"),null;let r=await Promise.resolve(n.start).catch(()=>null);if(!r||a!=="preparing")return null;let l=()=>ve(e,{funnelId:r.funnelId,customerId:n.client.customerId,parameters:r.parameters??{}});if(J=await l(),a!=="preparing")return null;let i=J;if(i.type!=="paywall")return d("unavailable",be(i)??"route"),null;let t=!1;return le=e.subscribe(()=>{t||!ge()||(t=!0,l().then(c=>{!(c.type==="unavailable"&&!["funnel_stopped","route_unavailable"].includes(c.reason))&&(c.type!=="paywall"||c.paywallVersionId!==i.paywallVersionId)&&he("route_changed")}).finally(()=>t=!1))}),q||le(),{paywallVersionId:i.paywallVersionId}}(async()=>{try{let[{showPaywall:e},r]=await Promise.all([import("./paywall-22EYVJAK.js"),ze()]),l=n.commerce??ae(E),i=n.locale??E?.locale,t=r&&l&&i?JSON.stringify(k([r.paywallVersionId??null,r.paywallId??null,{commerce:l,locale:i}])):null;if(de(t),g.throwIfAborted(),a!=="preparing"||!r)return;if(!l)return d("unavailable","commerce_missing");if(!i)return d("unavailable","locale_missing");Q=r;let c={commerce:l,locale:i},y=t?await F?.read(t).catch(()=>null):null;if(fe=!!y&&"presented"in y&&(!E||y.funnelId===E.funnelId),g.throwIfAborted(),a!=="preparing"||fe)return;y&&!("presented"in y)&&(!E||y.funnelId===E.funnelId)&&A(y.resolution,y.context.commerce)&&(f=y),G(!!f);let o;if(f){let ee=f.context;c=ee,o=structuredClone(f.resolution),Y(ee).then(Be=>He(Be,ee),()=>{})}else o=await Y(c);if(g.throwIfAborted(),a!=="preparing"||(!A(o,c.commerce)&&n.start instanceof Promise&&!h&&await j,!f&&h&&!T(c,h)&&(c=h,o=await Y(c)),g.throwIfAborted(),a!=="preparing"))return;if(!A(o,c.commerce))return d("unavailable","plan_unavailable");if(!Pe(o,c))return;b=s.ownerDocument.createElement("div"),s.append(b);let u=setTimeout(()=>a==="preparing"&&d("unavailable","timeout"),$e);Ae.then(()=>clearTimeout(u));let I=await e(b,Oe,xe);if(!I.host||g.aborted||a!=="preparing"){I.host?.destroy(),d(g.aborted?"released":"unavailable","error");return}v=I.host,Z()}catch(e){d(g.aborted?"released":"unavailable",ye(e))}finally{de(null),G(!1),B(!1)}})(),j.then(async e=>{let r=o=>{Ee(null),N(o)},l=async()=>{let o=await Fe;return o==="pending"?"purchase_pending":o==="found"?"original_purchase":o==="blocked"?"purchase_blocked":void 0},i=async o=>!o||o==="purchase_blocked"||!z?!1:(await se,pe(o)?!0:await Je&&Ue(e?.funnelId??await n.client.pendingFunnel().catch(()=>null)??void 0)&&pe(o));if(!e)return z&&await i(await l().catch(()=>{}))?void 0:r("gated");let t=e,c=ae(t),y=n.commerce??c;if(!T(c&&{...c,intent:void 0},y&&{...y,intent:void 0})||n.locale!==void 0&&t.locale!==n.locale)return r("start_mismatch");if(!c)return r("commerce_missing");h={commerce:c,locale:t.locale},x=t,f&&["preparing","ready","shown"].includes(a)&&(m=t,_=re(t));try{let o=await l();if(await i(o)){m=void 0,_="";return}if(o)return r(o);if(!["preparing","ready","shown"].includes(a))return;if(n.configuration&&(n.paywallId||n.paywallVersionId)){let u=await ve(n.configuration,{funnelId:t.funnelId,customerId:n.client.customerId,parameters:t.parameters??{}});g.throwIfAborted();let I=u.type==="unknown"||u.type==="unavailable"&&u.reason!=="funnel_stopped";if(u.type==="paywall"?f?u.paywallId!==f.resolution.paywallId:n.paywallVersionId?u.paywallVersionId!==n.paywallVersionId:u.paywallId!==n.paywallId:!I)return r(be(u)??"route_changed")}if(q&&(H=!1,await n.client.retained()==="pending")){if(await i("purchase_pending")){m=void 0,_="";return}return r("purchase_pending")}if(await se,fe){m=t,_=re(t);return}if(Q||n.paywallId||n.paywallVersionId||p){let u=await Y(h);if(g.throwIfAborted(),Ee(A(u,h.commerce)?{savedAt:Date.now(),funnelId:t.funnelId,context:h,resolution:u}:null),f)He(u,h);else{if(a!=="preparing")return;if(p){if(!A(u,h.commerce))return d("unavailable","plan_unavailable");if(!Pe(u,h))return}}}}catch(o){return g.aborted?d("released","aborted"):N(ye(o))}["preparing","ready","shown"].includes(a)&&(m=t,_=re(t),Z(),H&&$())},()=>N("gated"));let Ne={get state(){return a},get reason(){return Se??ke},ready:Ae,local:se,get start(){return m},get prediction(){return J?structuredClone(J):void 0},matches:e=>m?re(e)===_:!!f&&e.funnelId===f.funnelId&&e.locale===f.context.locale,open(){if(a==="preparing")return"pending";if(a!=="ready"||!C)return!1;if(Date.now()-U>=te)return d("unavailable","expired"),!1;let e=C;return C=null,X(),K("shown"),M&&_e(),e(),"shown"},destroy(){Ie.abort()}};return Le.set(Ne,{onClose(e){return a==="closed"?(R(e),()=>{}):(W.add(e),()=>{W.delete(e)})},claim(){X()},remember(e){ue=!0;let r=structuredClone(e);j.then(()=>{!x||!h||we({savedAt:Date.now(),funnelId:x.funnelId,context:h,resolution:r})},()=>{})},withhold(){ue=!0,j.then(()=>{x&&we({savedAt:Date.now(),funnelId:x.funnelId,presented:"nothing"})},()=>{})},async adopt(e,r){let l=e.paywall?.resolution,i=e.paywall&&!e.paywall.quote&&!e.paywall.operation&&!e.paywall.purchaseRequestId&&!(e.paywall.selectionGeneration??0);if(a!=="shown"||!v||!p||!l||!i||e.source.id!==m?.funnelId||e.locale!==m?.locale||!T(e.parameters??{},m?.parameters??{})||!["running","waiting"].includes(e.status)||!ne(l,p))return null;let t;try{t=await r.start()}catch{return null}if(a!=="shown"||!v)return t.destroy(),null;P=t,w.options=r.options,w.handoff=r.handoff;for(let[o]of D)D.set(o,t.subscribe?.(o)??(()=>{})),t.view&&R(o,structuredClone(t.view));g.removeEventListener("abort",oe),K("adopted"),ce(t),W.clear();let c=v,y=b;return v=null,b=null,C=null,new Proxy(c,{get(o,u){return u==="destroy"?()=>{o.destroy(),y?.remove()}:u==="retainPurchaseDialog"?()=>{let I=o.retainPurchaseDialog();if(I)return{dialog:I.dialog,release(){I.release(),y?.remove()}}}:Reflect.get(o,u,o)}})},retainPurchaseDialog(){if(a!=="shown")return;let e=v?.retainPurchaseDialog();if(!e)return;let r=b;return v=null,b=null,d("released"),{dialog:e.dialog,release(){e.release(),r?.remove()}}},get modal(){return p?.document.presentation.type!=="inline"},get revealable(){return a==="ready"&&!!C&&Date.now()-U<te},get recovering(){return M},release(){d("released")}}),Ne}function tn(s,n){let S=n.run.parameters??{},O=S?.commerce;return Ye(s,{client:n.client,start:{funnelId:n.run.source.id,locale:n.run.locale,parameters:S},paywallVersionId:n.paywallVersionId,...O&&{commerce:O},locale:n.run.locale,signal:n.signal},{run:!0})}export{Xe as a,an as b,Ye as c,tn as d};
|
package/dist/chunk-PGKKIL6M.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as kn,c as Rn,d as _t,f as Lt,g as An,k as Sn}from"./chunk-CHRNCOXJ.js";import{a as wn,b as Ye}from"./chunk-W32FI2A2.js";import{e as bn,f as Cn,g as Pn,h as vn,j as Ut,k as lt,l as In,m as En,n as xn}from"./chunk-CO6HDNOC.js";import{a as hn,c as Ot,d as mn,e as yn}from"./chunk-EQBJNU6R.js";import{a as st,b as oe,d as Nt,f as Dt,j as gn}from"./chunk-MOIVJERE.js";import{b as Pe}from"./chunk-6XRQR43F.js";import{B as _,C as ot,D as Ge,E as _e,y as fn}from"./chunk-3532HSBP.js";import{r as Le,t as Re}from"./chunk-Y3W5G4BF.js";import{i as pn}from"./chunk-FYUMVOCV.js";import{c as Ce,j as We}from"./chunk-DUS5V65Z.js";import{c as Tt}from"./chunk-BOT6ZDLK.js";import{a as I}from"./chunk-UGATOG2T.js";import{a as K}from"./chunk-DSPLGTQI.js";async function Tn(B,a,x){if(!Ge(a))throw new I("INVALID_RESPONSE","A verified completed purchase is required");let T=B?We.parse(B):null;if(await x.onComplete?.(a),!T||!x.check)return;let W=We.parse(await x.check());if(W.internal_feature_id!==T.internal_feature_id||W.quantity!==T.quantity||T.observation!==void 0&&(W.observation===void 0||W.observation.requirementDigest!==T.observation.requirementDigest||W.observation.authority!==T.observation.authority||Tt(W.observation.subject)!==Tt(T.observation.subject)))throw new I("INVALID_RESPONSE","The access requirement changed");W.allowed&&await x.onAccessGranted?.(W)}function On(B){return Object.entries(B.document.buttons).filter(([,a])=>a.type==="checkout"&&a.product.type==="fixed"&&!Pe(a.product,{},B.capabilities)).map(([a])=>a)}function Nn(B,a){let x=_(a)?void 0:a.lines[0];if(!_(a)&&(a.lines.length!==1||!x))return;let T=_(a)?a.productVersionId:x.productVersionId,{screen:W,buttons:se}=B.document,V=new Map(_(a)?Object.entries(a.featureQuantities??{}):(x?.prepaid??[]).map(b=>[b.internal_feature_id,b.quantity]));function le(b,d){if(b.hidden)return!1;if(b.type==="plan_picker"&&B.capabilities.pickers[b.id]?.options.includes(T))return d[b.id]=T,!0;if(b.type==="quantity_picker"){let ne=V.get(b.internalFeatureId);return ne!==void 0&&(!b.bind?.plan||b.bind.plan===T)&&(d[b.id]=ne),!1}if(b.type==="button"&&b.action){let ne=se[b.action];return ne?.type==="checkout"&&ne.product.type==="fixed"&&ne.product.productVersionId===T}if(b.type!=="stack")return!1;let te=b.interaction,i=b.bind?.plan===T;for(let[ne,f]of b.children.entries()){let Z={},L=le(f,Z);if(te?.type==="toggle"||te?.type==="tabs"){if(!L)continue;return d[b.id]=te.type==="toggle"?ne===0:f.id,Object.assign(d,Z),!0}Object.assign(d,Z),L&&(i=!0,te?.type==="select"&&te.purpose==="product"&&te.pickerId&&f.type==="stack"&&f.bind?.plan===T&&(d[b.id]=f.id,d[te.pickerId]=T))}return i}for(let b of W.pages){let d={__page:b.id};if(le(b.root,d))return d}}var Bn="position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0";async function Pr(B,a,x){let T=a.focusAtReveal?()=>{}:Ut(B.ownerDocument),W=()=>{V.finish("dismissed"),T()},se=()=>W(),V=In(B,a,"paywall",()=>{W(),K(a.onDismiss)},kn);a.signal?.throwIfAborted(),a.signal?.addEventListener("abort",se,{once:!0});let le=null,b,d,te;try{if(V.start(!0,a.loadingDocument?.screen.strings.defaultLocale,a.loadingDocument??null),V.cancelled)throw new DOMException("Presentation cancelled","AbortError");if(le=a.check?We.parse(await V.wait(a.check(),lt)):null,le?.allowed)return V.finish("skipped"),a.signal?.removeEventListener("abort",se),T(),await a.onAccessGranted?.(le),{check:le,host:null};let[e,n]=await Promise.allSettled([V.wait(import("./screen-renderer-HJOKBOZH.js")),V.wait(a.start().then(r=>(V.cancelled&&r.destroy(),r)),lt)]);if(e.status==="rejected")throw n.status==="fulfilled"&&n.value.destroy(),e.reason;if(n.status==="rejected")throw n.reason;te=e.value,b=n.value,a.signal?.throwIfAborted(),b.signal?.throwIfAborted(),b.signal?.addEventListener("abort",se,{once:!0});let t=b.view??await V.wait(b.refresh(),lt);if(!t)throw new I("INVALID_RESPONSE","Paywall presentation is missing");b.signal?.throwIfAborted(),d=t}catch(e){throw V.finish("error",e),x?.retainedDialog?.release(),a.signal?.removeEventListener("abort",se),b?.signal?.removeEventListener("abort",se),b?.destroy(),T(),e}let i=b,{mountScreenPreview:ne}=te,f=B.ownerDocument,Z=new AbortController,L=f.createElement("section"),pe=f.createElement("div"),G=f.createElement("div"),ct=a.mountControls,ee=ct?f.createElement("div"):void 0,p=f.createElement("p"),y=f.createElement("button"),ce=f.createElement("button"),N=f.createElement("button");(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&x?.hostPaywallTarget&&!x.retainedDialog&&d.document.presentation.type==="modal"&&(x.retainedDialog=vn(x.hostPaywallTarget));let ue=x?.retainedDialog,A=ue?.dialog??f.createElement("dialog"),Me=ue&&d.document.presentation.type==="inline"?{type:"modal",size:"md"}:d.document.presentation,re=Me.type==="inline"?G:f.createElement("div"),ut=i.locale||d.document.screen.strings.defaultLocale,o=ut.toLowerCase().startsWith("zh"),Dn=o?"正在处理…":"Processing…",Un=o?"正在准备报价…":"Preparing your price…",U=Rn(d.document.screen.theme);L.dataset.indianaPaywall="",L.setAttribute("aria-label",d.document.name),L.style.cssText=U.root,G.style.cssText=U.controls,p.style.cssText=U.message,p.setAttribute("role","status"),N.style.cssText=U.link,N.textContent=o?"关闭":"Close",y.style.cssText=U.secondary,y.textContent=o?"重试":"Retry",y.hidden=!0,ce.type="button",ce.style.cssText=U.primary,ce.textContent=o?"继续付款":"Continue payment",ce.hidden=!0,re.append(p,ce,y),G.append(N),ee&&(ee.style.cssText="flex:1 0 100%;min-width:0",ee.hidden=!0,G.prepend(ee)),re!==G&&(re.dataset.indianaPaywallStatus="",re.style.cssText="display:none;padding:0",L.append(re)),L.append(pe,G);let dt=()=>{let e=Mn();p.style.cssText=e?`${U.message};${Bn}`:U.message,zt();let n=s=>!s.hidden&&(s!==p||!!p.textContent&&!e);if(re!==G&&(re.style.cssText=!ie&&[...re.children].some(n)?`${U.controls};padding:12px 64px 12px 20px;flex-shrink:0`:e?"padding:0":"display:none;padding:0"),ee){let s=!ee.childElementCount&&!ee.textContent?.trim();ee.hidden!==s&&(ee.hidden=s)}let t=me??G,r=![...t.children].some(n),c=[...t.children].some(s=>s!==N&&n(s));t.style.cssText=r?U.controls.replace(/padding:[^;]+/,"padding:0"):c?`${U.controls};${U.pinned}`:U.controls,ft()},Mt=typeof MutationObserver>"u"?void 0:new MutationObserver(dt);Mt?.observe(L,{attributes:!0,attributeFilter:["hidden"],characterData:!0,childList:!0,subtree:!0});let _n=Object.entries(d.document.buttons).filter(([,e])=>e.type==="close").map(([e])=>e),O,Vt,Ve=!1,$t=JSON.stringify(d.capabilities),q;function ve(e){let n=On(e);if(q||fe&&!ae||j&&(C||!we()||ge))return Se(e).map(({actionId:r})=>r);if(Ct()||!C&&we())return n;let t=C?bt(e):Pt(e);return[...new Set([...n,...Se(e).map(({actionId:r})=>r).filter(r=>!t.includes(r))])]}function $e(e){if(w)return;let n=d.id!==e.id;d=e;let t=JSON.stringify(e.capabilities);if(n||t!==$t){let r=!P&&!i.quote&&!i.operation?st(e,J,Bt):J;n||JSON.stringify(r)!==JSON.stringify(J)?(J=r,O?.update(e.document.screen,ut,{capabilities:oe(e),unavailableActions:ve(e),serverInput:{bindings:[],answers:{}},selection:J})):O?.updateCapabilities(oe(e),ve(e)),$t=t}Vn(e),Ie(),Ze()}let M,pt=0;function Ht(){return(me??G).getBoundingClientRect().height+(re===G?0:re.getBoundingClientRect().height)}function ft(){let e=f.defaultView;if(!M?.responsive||!e)return;let n=me??G,t=e.innerHeight-(M.type==="modal"?32:0);n.style.maxHeight=`${Math.max(1,t)}px`,n.style.overflowY="auto",n.style.flexShrink="0",pt=Math.max(1,t-Ht()),O?.resizeViewport?.(pt,e.innerWidth)}let w=!1,fe=!1,P=null,ht,ze=!1,Qt=!1,he=!1,mt,Ke=!1,ie,me;function Ln(){return fe||w||ie||Ke?{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null}:Ot(i)}let E=()=>!w&&!ze&&!ie&&a.canInteract?.()!==!1,$,ke=!1,Ae=!1,yt,h=null,de=null,Je="",ye=()=>a.checkoutNavigation==="after_confirmation"&&!!(a.terminateCheckout||a.resumeCheckout),J={},Bt=new Set,ae,C;function gt(e){return!!e&&_(e)&&e.timing==="immediate"&&e.execution.provider==="merchant"}let wt=o?"正在确认付款…":"Confirming payment…",j=null,ge,Xe,qt=!1,we=()=>a.allowNewPurchase!==!1||qt;function jt(){return JSON.stringify([d.id,d.capabilities])}function Ft(){let e=yt;return e&&e.read===a.prepareSubscriptionChange&&e.basis===jt()?e:void 0}function Ze(){let e=a.prepareSubscriptionChange;if(!e||!he||!E()||!we()||a.onPurchaseIntent||f.visibilityState==="hidden"||P||i.quote||i.operation||!Se(d).length||Ft())return;let n=Z.signal,t=new Promise(r=>{let c=()=>r(void 0);n.addEventListener("abort",c,{once:!0}),Promise.resolve().then(()=>(n.throwIfAborted(),e(n))).then(s=>r(n.aborted?void 0:s),c).finally(()=>n.removeEventListener("abort",c))});yt={read:e,basis:jt(),result:t}}let Wt=()=>{f.visibilityState==="hidden"?yt=void 0:Ze()};f.addEventListener("visibilitychange",Wt);function Se(e){return Object.entries(e.document.buttons).flatMap(([n,t])=>t.type==="checkout"?[{actionId:n,policy:t}]:[])}function Gt(e){let n=C?.quote;return n?Se(e).filter(({actionId:t,policy:r})=>Te(n,e,t,r.product,J)).map(({actionId:t})=>t):[]}function bt(e){return C?.phase==="payment"?Gt(e):[]}function Ct(){return(C?C.phase==="payment":!we())&&(we()||!!a.prepareUpgradeReplacement)&&ye()&&!!a.terminateCheckout&&!!i.quote&&i.canReselect===!1&&!!i.operation&&R(i.operation).type==="checkout"}function Pt(e){let n=i.quote;return!ye()||j||!n||!i.operation||R(i.operation).type!=="checkout"?[]:Se(e).filter(({actionId:t,policy:r})=>Te(n,e,t,r.product,J)).map(({actionId:t})=>t)}function Ie(){let e=q?[]:C?bt(d):Pt(d),n=a.allowNewPurchase===!1&&!!i.operation&&R(i.operation).type==="checkout";ce.hidden=!!q||(C?C.phase!=="payment":!n)||e.length>0,zt(e)}function Yt(){if(!(ae===void 0||q))return p.textContent?p.textContent:C?.phase==="checking"?wt:void 0}function Mn(){return!!O?.updateCheckoutControls&&!!p.textContent&&Yt()!==void 0}let et;function zt(e=q?[]:C?bt(d):Pt(d)){if(!O?.updateCheckoutControls)return;let n=Yt(),t=ye()||!!C;if(!n&&!t&&et?.on!==O)return;let r={actions:Se(d).map(({actionId:s})=>s),resume:n?[ae]:t?e:[],resumeLabel:n??(o?"继续付款":C?"Continue payment":"Continue checkout"),busy:ae},c=JSON.stringify(r);et?.on===O&&et.key===c||(et={on:O,key:c},O.updateCheckoutControls(r))}function Kt(){de?.remove(),de=null}async function tt(){if(j)return;if(a.resumeCheckout&&i.operation){let n=i.operation.operationId;try{await a.resumeCheckout(n)}catch(t){if(!(t instanceof I&&t.code==="PURCHASE_PENDING"))throw t;let r=await i.read();if(!E())return;if(r.operationId!==n||R(r).type==="checkout")throw t;await H(r,!1)}return}let e=await i.read();if(R(e).type!=="checkout")return H(e,!1);E()&&(He.delete(e.operationId),await Qe(e))}function vt(){ge?.destroy(),ge=void 0,Xe=void 0}function Jt(){let e=j;if(!e||ge)return;let n=o?"仍在核对原订单,暂时无法更换套餐。":"We’re still checking the original purchase before changing plans.",t=Date.now()+6e5,r=wn({document:f,delay:()=>Date.now()<t?5e3:void 0,async run(){if(!E())return;let c=await i.read();if(ge!==r||!E())return;if(c.operationId!==e.operationId)throw new I("PURCHASE_PENDING","The original Checkout changed");let s=R(c);s.type==="native"?(vt(),p.textContent=o?"原订单已关闭。你可以继续更换套餐。":"The original checkout is closed. You can continue changing plans.",y.textContent=o?"继续更换套餐":"Continue changing plans",h=()=>nt(),y.hidden=!1):(s.type==="complete"||s.type==="fulfillment"||s.type==="recording")&&(vt(),j=null,y.hidden=!0,await H(c,!1))}});ge=r,Xe=async()=>{try{await r.refresh()}finally{ge===r&&(p.textContent=n,y.hidden=!1)}},h=Xe,y.textContent=o?"查询结果":"Check result",y.hidden=!1,p.textContent=n,r.schedule()}async function nt(e=!1,n=!1){let t=j;if(!t)return;h=()=>nt(),C&&(y.textContent=o?"查询状态":"Check status"),y.hidden=!0;let r=async()=>{if(!we()&&a.prepareUpgradeReplacement){let s=await a.prepareUpgradeReplacement(t.operationId,t.intent);if(!E())return;qt=!0,$e(s)}j=null,C&&Oe(C.quote),Kt(),P=t.selection,$=t.coupon,ke=!1,Ae=!1,await je()};if(n&&!we()&&a.prepareUpgradeReplacement)return r();let c=Date.now()+2e4;for(;E();){let s=await i.read();if(s.operationId!==t.operationId)throw new I("PURCHASE_PENDING","The original Checkout changed");if(!E())break;let l=R(s);if(l.type==="native"){await r();return}if(l.type==="complete"||l.type==="fulfillment"||l.type==="recording"){j=null,C?await Ee(C.quote,s):await H(s,!1);return}if(e&&l.type==="checkout"){e=!1;try{await a.terminateCheckout(t.operationId)}catch(u){K(a.onError,u)}}if(Date.now()>=c){C&&l.type==="checkout"&&(j=null,await Ee(C.quote,s));break}await Ye(1e3,f,Z.signal)}!j||w||(C?(p.textContent=o?"仍在核对原升级单,暂时无法更换套餐。":"We’re still checking the original upgrade before changing plans.",y.hidden=!1):Jt())}async function Xt(e,n,t,r){if(h=()=>Xt(e,n,t,r),await a.beforeCheckoutReplacement?.(structuredClone(r)),!E())return;let c=i.operation;if(c?.operationId!==e||R(c).type!=="checkout"){h=null,c&&await H(c,!1);return}j={operationId:e,selection:n,coupon:t,intent:r},C&&(p.textContent=o?"正在切换套餐…":"Changing plan…",y.hidden=!0);let s=!1,l=!1;try{let u=await a.terminateCheckout(e);l=(Array.isArray(u?.purchases)?u.purchases:[]).some(k=>k.operationId===e&&k.type==="native")}catch(u){if(u instanceof I&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(u.code)){j=null,C&&(h=It,y.textContent=o?"查询状态":"Check status",y.hidden=!1),p.textContent=o?"请继续原订单,或等待它过期后再更换方案。":"Continue your original checkout, or wait for it to expire before changing plans.",K(a.onError,u);return}s=u instanceof I&&(u.status??0)>=500,K(a.onError,u)}E()&&await nt(s,l)}function rt(e,n,t,r,c){let s=oe(e).checkoutCoupons?.[n],l=s?s.products[t]:a.claimCoupon&&c?pn(e.capabilities,c,r):void 0;return l?.couponId&&l.planVersionId===t?{id:l.couponId,offerId:l.offerId}:void 0}function Vn(e){fe||P||i.quote||i.operation||Je&&p.textContent===Je||(p.textContent=Object.values(e.capabilities.plans).some(n=>n.available)?"":o?"当前账号暂无可购买的方案。":"No plans are currently available for this account.")}let He=new Map,it=!1;function Te(e,n,t,r,c,s){let l=_(e),u=!l&&e.lines.length===1?e.lines[0]:void 0,m=Pe(r,c,n.capabilities);if(!m||m!==(l?e.productVersionId:u?.productVersionId))return!1;let k=rt(n,t,m,c,s),D;try{D=Re(n.document.screen,m,c,n.capabilities)}catch{return!1}if(l){let X=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return Object.keys(D).length===Object.keys(e.featureQuantities??{}).length&&Object.entries(D).every(([Ue,St])=>e.featureQuantities?.[Ue]===St)&&(!k||X?.couponId===k.id&&(!k.offerId||X.grantId===k.offerId))}if((k||oe(n).checkoutCoupons?.[t])&&(k?.id??null)!==(e.discount?.couponId??null))return!1;let Y=Object.fromEntries((u?.prepaid??[]).map(X=>[X.internal_feature_id,X.quantity]));return[...new Set([...Object.keys(D),...Object.keys(Y)])].every(X=>(D[X]??0)===(Y[X]??0))}let R=e=>hn({quote:i.quote,operation:e,requestId:null,pending:!1,destroyed:w,canReselect:i.canReselect});async function Qe(e){let n=e.merchantExecution,t=R(e),r=t.type==="checkout"?t.checkoutUrl:e.checkoutUrl;if(!(!E()||!r||ot(e)&&t.type!=="checkout"||a.checkoutNavigation==="after_confirmation"&&t.type!=="checkout"||n?.type==="purchase"&&!["not_started","pending"].includes(n.paymentStatus)||He.get(e.operationId)===r)){He.set(e.operationId,r);try{a.onCheckoutUrl?await a.onCheckoutUrl(r):f.defaultView?.location.assign(r)}catch(c){throw He.delete(e.operationId),c}}}let be=(e,n=!1)=>{if(e instanceof Nt)h=null,p.textContent=e.customerMessage(o);else if(An(e))h=null,p.textContent=n?o?"当前无法在此购买,付款尚未开始。请联系商户。":"Purchases aren’t available here right now. Payment hasn’t started. Contact the merchant for help.":Lt(e,o);else if(n){let t=e instanceof I?e.code:void 0;t==="CAPABILITY_UNAVAILABLE"||t==="NOT_CONFIGURED"?(h=null,p.textContent=o?"暂时无法为此套餐报价,付款尚未开始。":"Pricing for this plan is unavailable. Payment hasn’t started."):i.canReselect===!0&&!P?p.textContent=o?"未能取得报价,付款尚未开始。请重新选择套餐。":"We couldn’t prepare your price. Payment hasn’t started. Choose a plan again.":t==="COMMAND_PENDING"?p.textContent=o?"仍在准备报价,请重试以查看结果。":"Your price is still being prepared. Retry to check the result.":p.textContent=o?"未能取得报价,付款尚未开始。请重试。":"We couldn’t prepare your price. Payment hasn’t started. Try again."}else p.textContent=e instanceof I&&(e.code==="NETWORK_ERROR"||e.code==="TIMEOUT")?Lt(e,o):e instanceof I?e.message:o?"操作未完成,请重试。":"This action couldn’t be completed. Try again.";y.hidden=h===null,Je=p.textContent,n&&ae===void 0&&!M?.responsive&&p.scrollIntoView?.({block:"nearest"}),K(n&&x?.quoteError?x.quoteError:a.onError,e)},Be=new WeakMap;function qe(e){fe=e,y.disabled=e,ce.disabled=e,O?.updateCapabilities?.(oe(d),ve(d));for(let n of de?.querySelectorAll("button")??[])e?(Be.has(n)||Be.set(n,n.disabled),n.disabled=!0):Be.has(n)&&(n.disabled=Be.get(n),Be.delete(n)),_t(n)}function Zt(){q&&(p.textContent=q.message,y.textContent=o?"重试":"Retry",y.disabled=!1,y.hidden=!q.retry,ce.disabled=!0)}function kt(){p.textContent=o?"暂时无法操作,请稍后重试。":"This action is unavailable right now. Try again in a moment."}async function $n(e){if(a.beforeAction)try{await a.beforeAction()}catch(n){throw n instanceof Nt?(P=null,ke=!1,Ae=!1,h=null):h=e,n}}async function F(e,n){if(fe||w||q)return;if(!E()){kt();return}let t=e===je,r=t?Un:Dn;ae=n!==void 0&&O?.updateCheckoutControls?n:void 0,p.textContent=r,qe(!0),Ie(),y.hidden=!0;try{if(e!==on&&e!==It&&e!==Et&&e!==Xe&&(e!==tt||!a.resumeCheckout)&&await $n(e),w||q)return;if(!E()){h=e,y.hidden=!1,kt();return}await e()}catch(c){w||be(c,t)}finally{ae=void 0,qe(!1),Ie(),q?Zt():p.textContent===r&&(p.textContent="")}}async function en(e){await Tn(le,e,a)}function Oe(e,n){C=n?{quote:e,phase:n}:void 0,n==="checking"?(ae??=P?.actionId??Gt(d)[0],p.textContent=wt,h=It,y.textContent=o?"查询状态":"Check status",y.hidden=!0):ae=void 0,O?.updateCapabilities(oe(d),ve(d)),Ie()}function tn(e){return e instanceof I&&(e.code==="COMMAND_PENDING"||e.reason==="RESULT_UNKNOWN"||e.code==="NETWORK_ERROR"||e.code==="TIMEOUT"||e.status===429||(e.status??0)>=500)}function nn(e,n){Dt(e,{...n,featureQuantities:n.featureQuantities??{}},"Purchase operation changed")}async function It(){C&&await Ee(C.quote)}async function Ee(e,n){Oe(e,"checking"),Je="";let t=1e3;Ve=!0,K(a.onObservationChange,!0);try{for(let r=n;E();r=void 0){if(!r){try{r=await i.read()}catch(c){if(!tn(c))throw c}if(!E())return}if(r){nn(r,e);let c=R(r);if(c.type==="checkout"){Oe(e,"payment"),p.textContent=o?"请先完成原订单的付款。":"Finish paying for this upgrade.",y.hidden=!1;return}if(c.type==="complete"){Oe(e,"complete"),h=null;let s=d.capabilities.plans[e.productVersionId]?.name,l=e.merchantTerms?.subscriptionTerms?.items,u=l?.length===1?l[0].interval:void 0,m=u==="year"?o?"年付":"annual billing":u==="month"?o?"月付":"monthly billing":null;p.textContent=s?o?`已升级到 ${s}${m?" "+m:""}。`:`Upgraded to ${s}${m?" ("+m+")":""}.`:o?"已成功升级。":"Plan upgraded.",await en(r);return}if(c.type==="native"&&!_e(r)){Oe(e),P=null,h=null,p.textContent=o?"付款没有成功,套餐未变更。请检查付款方式后重新选择套餐。":"Your payment didn’t go through, so your plan is unchanged. Check your payment method, then choose a plan again.",y.textContent=o?"重试":"Retry";return}if(r.problem&&!["RESULT_UNKNOWN","STATE_CHANGED"].includes(r.problem.reason??""))throw new I(r.problem.code,o?"暂时无法完成升级。":"The upgrade needs attention.",void 0,void 0,r.problem)}await Ye(t,f,Z.signal),t=Math.min(t*1.5,15e3)}}finally{Ve=!1,K(a.onObservationChange,!1)}}async function Et(){let e=C?.quote;if(!e)return;let n=await i.read();if(nn(n,e),R(n).type!=="checkout")return Ee(e,n);if(a.resumeCheckout){await a.resumeCheckout(n.operationId);return}He.delete(n.operationId),await Qe(n)}function rn(e){return Ot(i).type==="recording"||R(e).type==="recording"}function an(e){let n=e.merchantTerms,t=n?.subscriptionTerms?.items??[],r=n?n.totalMinor:_(e)?e.totalMinor:e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),c=n?t.length===1&&t[0]?.amountMinor===r&&t[0]:!_(e)&&e.lines.length===1&&e.lines[0]?.catalogAmountMinor===r&&e.lines[0],s=r===null?Ce(n.subtotalMinor-n.discountMinor,e.currency)+(o?" + 待确认税费":" + tax confirmed at checkout"):Ce(r,e.currency)+(c?Le(c.interval,o?"zh-CN":"en",c.intervalCount??1):""),l=_(e)?i.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(u=>u.productName).join(", ");return{label:l?`${l} · ${s}`:s,recurring:c}}async function H(e,n=a.checkoutNavigation!=="after_confirmation"){if(w)return;if(!E()){h=async()=>H(await i.read()),y.hidden=!1;return}let t=e.quote??i.quote;if(gt(t)&&(e.confirmedAt||e.merchantExecution))return Ee(t,e);if(p.textContent=Sn(e.status,o),rn(e)){let m=e.merchantExecution?.recordingStatus==="failed";p.textContent=m?o?"付款和商户处理已完成,但交易记录失败。请联系商户修复,勿重复购买。":"Payment and fulfillment succeeded, but recording failed. Contact the merchant to repair this purchase; do not buy again.":o?"付款和商户处理已完成,正在确认交易记录。请勿重复购买。":"Payment and merchant fulfillment are complete. Recording is pending confirmation; do not purchase again.",y.textContent=o?"查询记录":"Check recording",h=async()=>H(await i.read()),y.hidden=!1;return}if(e.problem&&R(e).type!=="native"){let m=e.problem;h=Ne,y.textContent=o?"检查并恢复原操作":"Check and recover original purchase",be(new I(m.code,m.reason==="RESULT_UNKNOWN"?o?"付款结果尚未确定,请恢复原操作,暂勿重复购买。":"The payment result is unknown. Recover the original purchase before buying again.":m.phase==="fulfillment"?o?"付款已记录,商户权益处理需要核对。":"Payment was recorded. Access fulfillment needs attention.":m.code==="CAPABILITY_UNAVAILABLE"?o?"商户尚不支持本次购买所需的完整能力,请处理后恢复原操作。":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":m.code==="NOT_CONFIGURED"?o?"付款服务连接需要处理,请联系商户后恢复原操作。":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":o?"原购买操作需要处理,请查询或恢复此操作。":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,m));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)&&(p.textContent=o?"付款已记录,正在等待商户完成处理。":"Payment was recorded. Waiting for merchant fulfillment."),Ge(e)&&R(e).type==="complete"){h=null,await en(e);return}if(!_e(e)&&R(e).type!=="fulfillment"){if(i.canReselect===!1){p.textContent=o?"正在核对原购买结果":"Checking the original purchase result",y.textContent=o?"查询结果":"Check result",h=async()=>H(await i.read()),y.hidden=!1;return}e.status==="cancelled"?p.textContent=o?"这笔购买已取消,可以重新选择方案。":"This purchase was cancelled. Choose a plan to start again.":e.status==="failed"&&(p.textContent=o?"这笔购买未能完成,可以重新选择方案。":"This purchase didn’t go through. Choose a plan to try again."),y.textContent=o?"重试":"Retry",h=null,P=null;return}if(!n&&R(e).type==="checkout"){if(j){Jt();return}if(ye()){p.textContent="",it=!1,h=null,y.hidden=!0,O?.updateCapabilities?.(oe(d),ve(d)),Ie();return}let m=i.quote,k=m?.operationId===e.operationId?an(m).label:"";p.textContent=it?k?o?`${k} 尚未付款。再次选择该方案即可继续付款。`:`${k} is still unpaid. Choose it again to continue paying.`:o?"之前的购买尚未付款。再次选择该方案即可继续付款。":"Your earlier purchase is still unpaid. Choose that plan again to continue paying.":"",it=!1,h=null;return}await Qe(e);let r=Date.now(),c=r+6e5,s=2e3,l=R(e).type!=="checkout",u=()=>l&&Date.now()-r<15e3;Ve=!0,K(a.onObservationChange,!0);try{for(;!w&&Date.now()<c;){if(await Ye(u()?700:s,f,Z.signal),w)return;if(!E()){h=async()=>H(await i.read()),y.hidden=!1;return}let m=await i.read();if(R(m).type==="checkout"&&(l=!1),!n&&R(m).type==="checkout"){await H(m,!1);return}if(!m.problem&&_e(m)&&await Qe(m),!_e(m)||m.problem||rn(m)){await H(m);return}u()||(s=Math.min(s*1.5,3e4))}}finally{Ve=!1,K(a.onObservationChange,!1)}h=async()=>H(await i.read()),y.hidden=!1}async function xt(e=!1){let n=await i.read();if(w)return;if(!E()){h=()=>xt(e),y.hidden=!1;return}let t=i.quote;if(t&&Dt(n,{operationId:t.operationId,currency:t.currency},"The original purchase operation changed"),t&&(ot(n)?["prepared","quoted"].includes(n.status):n.status==="pending")&&(ot(n)||n.quoteFinalized===!1)&&!n.confirmedAt&&!n.checkoutUrl&&!("nativePurchase"in n&&n.nativePurchase)&&!n.merchantExecution&&!n.problem&&!i.pendingCancellation){if(a.purchaseConfirmation!=="paywall"){e?await Ne():h=null;return}setTimeout(sn,0,t);return}await H(n,e||void 0)}async function on(){await xt()}async function Hn(e){p.textContent=wt;let n=Date.now()+12e3;for(;!w&&Date.now()<n&&(await Ye(1500,f,Z.signal),!(w||!E()));){let t;try{t=await i.read()}catch{break}if(t.problem?.reason!=="RESULT_UNKNOWN")return t}return e}async function Ne(){if(i.quote&&!(Date.parse(i.quote.expiresAt)>Date.now()))throw new I("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");Kt();let e=i.quote;if(gt(e)){Oe(e,"checking");let t;try{t=await i.confirm()}catch(r){if(!tn(r))throw r;return Ee(e)}return Ee(e,t)}h=Ne;let n=await i.confirm();if(!E()){h=Ne,y.hidden=!1;return}if(n.problem?.reason==="RESULT_UNKNOWN"&&(n=await Hn(n)),n.problem){await H(n);return}if(_e(n)){if(R(n).type==="checkout")await Qe(n);else if(n.execution&&n.execution.provider!=="merchant"||"nativePurchase"in n&&n.nativePurchase){if(!a.onPurchase)throw new I("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await a.onPurchase({operation:n,signal:Z.signal})}}h=async()=>H(await i.read()),await H(n,!0)}function sn(e){if(w)return;de?.remove();let n=!(Date.parse(e.expiresAt)>Date.now());p.textContent=n?o?"此报价已过期。请先取消,再重新选择。":"This quote has expired. Cancel it, then choose again.":"";let t=f.createElement("div"),r=f.createElement("button"),c=f.createElement("button"),s=f.createElement("div"),l=f.createElement("p"),u=e.merchantTerms,m=o?"zh-CN":"en",k=u?.subscriptionTerms?.items??[],D=u?u.subscriptionTerms?.trial?.days:_(e)?void 0:e.lines.find(g=>g.trial)?.trial?.days,Y=_(e)?u?u.totalMinor:e.totalMinor:D===void 0?null:u?u.totalMinor:e.charge?e.charge.totalMinor:e.lines.every(g=>g.trial)?0:null,De=(g,v)=>o?`${v} 天试用结束后 ${g}`:`Then ${g} after the ${v}-day trial`,{label:X,recurring:Ue}=an(e),St=_(e)?i.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(g=>g.productName).join(", "),un=Y===null?"":`${o?"今天应付":"Due today"} ${Ce(Y,e.currency)}`;l.textContent=un?[St,un].filter(Boolean).join(" · "):X,r.textContent=_(e)?o?"确认变更":"Confirm change":o?"确认购买":"Confirm purchase",r.disabled=n,c.textContent=o?"取消":"Cancel",t.style.cssText=U.panel,l.style.cssText=U.summary,s.style.cssText=U.actions,r.style.cssText=U.primary,c.style.cssText=U.secondary,_t(r),r.onclick=()=>{F(Ne)};let dn=async()=>{let g=await i.cancel();w||(t.remove(),de=null,await H(g))};c.onclick=()=>{h=dn,F(dn)};let z=f.createElement("div");if(z.style.cssText=U.terms,_(e)){for(let[v,S]of Object.entries(e.featureQuantities??{})){let Q=i.view?.capabilities.plans[e.productVersionId]?.prepaid?.find(Qn=>Qn.internalFeatureId===v),at=f.createElement("p");at.textContent=`${Q?.name??v} · ${S} ${o?"份":"packs"}${Q?` × ${Q.terms.units}`:""}`,z.append(at)}for(let[v,S]of[[o?"原订阅抵扣":"Unused subscription credit",e.creditMinor],[o?"新套餐费用":"New plan charge",e.debitMinor],[o?"优惠减免":"Offer savings",u?.discountMinor??e.discountMinor],[o?"税费":"Tax",u?u.taxMinor:e.taxMinor]]){let Q=f.createElement("p");Q.textContent=`${v}: ${S===null?o?"结账时确认":"Confirmed at checkout":Ce(S,e.currency)}`,z.append(Q)}let g=f.createElement("p");g.textContent=`${o?"生效时间":"Effective"}: ${e.effectiveAt}`,z.append(g)}if(u){for(let v of k){if(Y===null&&v===Ue)continue;let S=f.createElement("p"),Q=Ce(v.amountMinor,e.currency)+Le(v.interval,m,v.intervalCount);S.textContent=Y!==null&&D!==void 0?De(Q,D):Q,v.amountAfterOfferMinor!==void 0&&(S.textContent+=` · ${o?"优惠结束后":"After the offer"} ${Ce(v.amountAfterOfferMinor,e.currency)}${Le(v.interval,m,v.intervalCount)}`),z.append(S)}let g=u.subscriptionTerms?.trial;if(g){let v=f.createElement("p");v.textContent=o?`试用 ${g.days} 天;${g.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${g.days}; ${g.cardRequired?"a payment method is required":"no payment method is required"}`,z.append(v)}for(let v of[...u.expectedEffects.map(S=>S.description),...u.requiredConsents.map(S=>S.summary)]){let S=f.createElement("p");S.textContent=v,z.append(S)}}else if(!_(e)){for(let g of e.lines){if(Y!==null||g!==Ue){let v=f.createElement("p"),S=`${Ce(g.catalogAmountMinor,e.currency)}${Le(g.interval,m,g.intervalCount??1)}`;v.textContent=Y!==null&&g.trial?(e.lines.length>1?`${g.productName} · `:"")+De(S,g.trial.days):`${g.productName} · ${S}`,z.append(v)}for(let v of g.prepaid??[]){let S=f.createElement("p"),Q=i.view?.capabilities.plans[g.productVersionId]?.prepaid?.find(at=>at.internalFeatureId===v.internal_feature_id);S.textContent=`${Q?.name??v.internal_feature_id} · ${v.quantity} ${o?"份":"packs"} × ${v.terms.units}`,Q&&(S.textContent+=Le(Q.reset==="week"||Q.reset==="month"||Q.reset==="year"?Q.reset:"one_time",m,Q.resetCount)),z.append(S)}if(g.trial){let v=f.createElement("p");v.textContent=o?`试用 ${g.trial.days} 天;${g.trial.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${g.trial.days}; ${g.trial.cardRequired?"a payment method is required":"no payment method is required"}`,z.append(v)}}if(!e.charge){let g=f.createElement("p");g.textContent=o?"目录价格;最终金额以结账时税费和试用规则为准。":"Catalog price; the final charge depends on checkout taxes and trial terms.",z.append(g)}}for(let g of z.children)g.style.margin="0";s.append(r,c),t.append(l,...z.childElementCount?[z]:[],s),G.prepend(t),M?.responsive||t.scrollIntoView?.({block:"nearest"}),r.focus({preventScroll:!0}),de=t,fe&&qe(!0),h=null}async function je(){if(!P)return;if(a.onPurchaseIntent&&!ke&&!i.quote&&!i.operation){let t=P,r=i.view,c=r?.document.buttons[t.actionId],s=r&&c?.type==="checkout"?Pe(c.product,t.selection,r.capabilities):null;if(!r||!s)throw new I("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");let l={actionId:t.actionId,productVersionId:s,selection:structuredClone(t.selection),featureQuantities:Re(r.document.screen,s,t.selection,r.capabilities),...$&&{coupon:{id:$.id,...$.offerId&&{offerId:$.offerId}}}};P=null,$=void 0,h=null,Ke=!0,await a.onPurchaseIntent(l);return}if(h=je,!ke){let t=i.view,r=t?.document.buttons[P.actionId],c=t&&r?.type==="checkout"?Pe(r.product,P.selection,t.capabilities):null;if(!t||!c)throw new I("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");if(!Ae){let l=Ft(),u=l?await l.result:void 0;if(w)return;let m=a.resolveSubscriptionChange;if(m||u){let k={actionId:P.actionId,productVersionId:c,featureQuantities:Re(t.document.screen,c,P.selection,t.capabilities)},D=u?[async()=>u(k)]:[],Y=m?await m(k,...D):await D[0]?.();if(w)return;Y!==void 0&&(P.subscriptionChange=fn.parse(Y))}Ae=!0}let s=$?.offerId;if($&&!s){if(!a.claimCoupon)throw new I("CAPABILITY_UNAVAILABLE","Coupon claiming is unavailable");let{offer:l}=await a.claimCoupon($.id,P.requestId);if(w)return;if(!l||l.couponId!==$.id||l.status!=="issued"||!(Date.parse(l.expiresAt)>Date.now()))throw P=null,$=void 0,h=async()=>{$e(await i.refresh()),h=null},new I("COUPON_UNAVAILABLE","This Coupon is no longer available for this purchase");s=l.id}if(!$&&!t.document.screen.actions.some(l=>l.id===P?.actionId&&typeof l.properties.couponBinding=="string")&&(s=await a.resolveOfferId?.({actionId:P.actionId,productVersionId:c,featureQuantities:Re(t.document.screen,c,P.selection,t.capabilities)})),w)return;s!==void 0&&(P.offerId=s),ke=!0}if(!E()){y.hidden=!1;return}let e;try{e=await i.preview(P)}catch(t){throw i.canReselect===!0&&(P=null,ke=!1,Ae=!1,$=void 0,h=null),t}if($&&(_(e)?(()=>{let t=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return t?.couponId!==$.id||t.grantId!==P.offerId})():e.discount?.couponId!==$.id||e.discount.offerId!==P.offerId))throw new I("INVALID_RESPONSE","The quote did not apply the Coupon selected on this Paywall");if(w)return;let n=e.merchantTerms;if(a.purchaseConfirmation!=="paywall"||a.confirmOnHostedCheckout&&E()&&!_(e)&&e.provider==="merchant"&&e.billingSubscriptionId===null&&n?.request.action==="purchase"&&n.request.mode==="subscription"&&n.subscriptionTerms?.trial===null&&n.requiredConsents.length===0&&Date.parse(e.expiresAt)>Date.now()){if(!E()){y.hidden=!1;return}if(!(Date.parse(e.expiresAt)>Date.now()))throw new I("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");let t=ae?"":o?"正在打开收银台…":"Opening checkout…";p.textContent=t;try{await Ne()}catch(r){w||be(r)}finally{p.textContent===t&&(p.textContent="")}return}sn(e)}function xe(e="destroy",n=!1){if(w)return;w=!0;let t=ht;ht=void 0,K(t),a.signal?.removeEventListener("abort",se),i.signal?.removeEventListener("abort",se),V.finish("dismissed"),Vt?.(),vt(),f.removeEventListener("visibilitychange",Wt),Z.abort(),Mt?.disconnect(),O?.destroy(),i.destroy(),A.removeEventListener("cancel",cn),N.remove(),L.remove(),n||ln(),e==="dismiss"&&K(a.onDismiss)}function ln(){if(M?.destroy(),ue){ue.release();return}A.open&&A.close(),A.remove(),T()}W=xe;async function Fe(){if(!he||w||ze||ie==="closing"||!ie&&!E())return;if(!x){xe("dismiss");return}let e=f.createElement("p");e.setAttribute("role","status"),e.textContent=o?"正在关闭…":"Closing…",me||(me=f.createElement("div"),me.style.cssText=G.style.cssText,G.replaceWith(me),pe.inert=!0),N.hidden=!1,me.replaceChildren(e,N),ie="closing",N.setAttribute("aria-disabled","true"),N.focus({preventScroll:!0});try{await x.dismiss()}catch(n){w||K(a.onError,n)}w||(ie="retry",e.textContent=o?"未能确认关闭,请重试。":"Could not confirm closure. Try again.",N.textContent=o?"重试关闭":"Retry closing",N.removeAttribute("aria-label"),N.removeAttribute("aria-disabled"))}N.onclick=()=>{Fe()};function cn(e){e.preventDefault(),Fe()}A.addEventListener("cancel",cn),ce.onclick=()=>{F(C?Et:tt)},y.onclick=()=>{if(q){q.retry?.();return}h&&F(h)};function Rt(e){V.finish("error",e),xe()}function At(){if(!(!Qt||he||w||ze||M&&!E()))try{let e=n=>{a.focusAtReveal&&(T=Ut(f)),a.settleMotionAtReveal?O?.setHidden?.(!1,!0):O?.setHidden?.(!1),mt?.(),M&&(A.open||A.showModal(),M.responsive&&A.focus({preventScroll:!0}),!n&&a.loading!=="host"&&Cn(A,M.type,M.responsive)),n&&a.loading!=="host"&&typeof pe.animate=="function"&&!f.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches&&pe.animate([{opacity:.55},{opacity:1}],{duration:160,easing:"ease-out"}),he=!0,Ze()};x?x.present(n=>V.present(t=>e(n??t))):V.present(e)}catch(e){Rt(e),be(e)}}try{if(Me.type==="inline"?(dt(),mt=xn(L,B),B.append(L)):(A.setAttribute("aria-label",d.document.name),N.textContent="×",N.setAttribute("aria-label",o?"关闭":"Close"),Pn(N,d.document.screen.theme),N.hidden=gn(d.document),(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&ue?.content?ue.content.append(N,L):A.replaceChildren(N,L),ue||B.append(A),M=bn(A,{...d.document.screen,presentation:Me},ft),M.latch(),M.responsive&&(L.style.display="flex",L.style.flexDirection="column",L.style.maxHeight="100%",pe.style.overflow="clip",pe.style.minHeight="0"),ue||(mt=En(A))),ct&&ee){let t=ct(ee);if(typeof t=="function"&&(w?K(t):ht=t),w)throw new DOMException("Presentation cancelled","AbortError");dt()}O=ne(pe,{mode:"live",rendererUrl:"bundled",title:d.document.name,closeActions:_n,onAuthoredClose(t){ie||w||(N.hidden=t)},hostPresentation:()=>M?.type??Me.type,reportContentHeight:M?.responsive,onResize:t=>{if(!M?.responsive)return;let r=Math.min(t,pt);pe.style.height=`${r}px`,M.setContentHeight(r+Ht())},onSelection(t){for(let[r,c]of Object.entries(t))typeof c=="number"&&typeof J[r]=="number"&&J[r]!==c&&Bt.add(r);J=t,Ie(),Ze()},onAction(t,r={},c,s){if(!he||w||ie)return;let l=i.view,u=l?.document.buttons[t];if(!u)return;if(q){u.type==="close"&&Fe();return}if(u.type==="close"&&x&&a.resumeCheckout&&i.operation&&mn(R(i.operation))){Fe();return}if(fe)return;if(!E()){kt();return}if(u.type==="close"){F(async()=>{x?.closeAction?await x.closeAction(t):await a.onAction?.(t),xe(a.onAction?"action":"dismiss")});return}if(u.type==="action"){h=async()=>{if(u.action.type==="event"){if(!a.onEvent)throw new I("EVENT_HANDLER_REQUIRED","Provide the event handler");await a.onEvent(u.action.event)}else a.onOpenUrl?await a.onOpenUrl(u.action.url):f.defaultView?.location.assign(u.action.url);await a.onAction?.(t),h=null},F(h);return}if(ye()&&j){!ge&&j.selection.actionId===t&&F(()=>nt(!0),t);return}if(C){if(C.phase==="payment"&&l&&Te(C.quote,l,t,u.product,r,s)){F(Et,t);return}if(!Ct())return}if(!we()&&!Ct()){ye()&&l&&i.quote&&i.operation&&R(i.operation).type==="checkout"&&Te(i.quote,l,t,u.product,r,s)?F(tt,t):p.textContent=o?"当前只能继续原订单。":"Only your original checkout is available.";return}if(de&&i.canReselect===!1){p.textContent=o?"请先确认或取消当前购买。":"Confirm or cancel the current purchase first.",M?.responsive||de.scrollIntoView?.({block:"nearest"}),de.querySelector("button")?.focus({preventScroll:!0});return}if(ye()&&a.terminateCheckout&&l&&i.quote&&i.operation&&i.canReselect===!1&&R(i.operation).type==="checkout"){if(Te(i.quote,l,t,u.product,r,s)){F(tt,t);return}let k=Pe(u.product,r,l.capabilities),D;try{if(!k)throw new I("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");D=Re(l.document.screen,k,r,l.capabilities)}catch(Ue){be(Ue);return}let Y=i.operation.operationId,De={actionId:t,requestId:crypto.randomUUID(),selection:structuredClone(r)},X=rt(l,t,k,r,s);F(()=>Xt(Y,De,X,{actionId:t,productVersionId:k,selection:De.selection,featureQuantities:D}),t);return}if((i.quote||P)&&i.canReselect===!1){let k=!!l&&!!i.quote&&Te(i.quote,l,t,u.product,r,s);it=!!i.quote&&!k,h=i.quote?()=>xt(k):je,F(h,t);return}let m=l&&Pe(u.product,r,l.capabilities);if(!l||!m){be(new I("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(a.onPurchaseIntent){h=null,F(async()=>{let k={actionId:t,productVersionId:m,selection:structuredClone(r),featureQuantities:Re(l.document.screen,m,r,l.capabilities)},D=rt(l,t,m,r,s);D&&(k.coupon={id:D.id,...D.offerId&&{offerId:D.offerId}}),Ke=!0,await a.onPurchaseIntent(k)},t);return}if(P&&P.actionId!==t){be(new I("COMMAND_PENDING","Finish the current purchase"));return}P||($=rt(l,t,m,r,s),P={requestId:crypto.randomUUID(),actionId:t,selection:structuredClone(r)},ke=!1,Ae=!1),F(je,t)},onEscape:()=>{Fe()},onError:t=>{let r=new Error(t);!he&&!w&&Rt(r),be(r)},onRendered:t=>{t&&A.setAttribute("aria-label",t),Qt=!0,At()}}),O.setHidden?.(!0),ft();let e=ye()&&!!i.quote&&!!i.operation&&R(i.operation).type==="checkout";J=i.quote?Nn(d,i.quote)??st(d,{}):st(d,{}),O.update(d.document.screen,ut,{capabilities:oe(d),unavailableActions:ve(d),serverInput:{bindings:[],answers:{}},...Object.keys(J).length?{selection:J}:{}}),Vt=i.subscribe?.($e),$e(i.view??d),await V.wait(O.ready);let n=i.operation;(!e||gt(i.quote))&&(i.quote||n&&(n.confirmedAt||n.checkoutUrl||Ge(n)))&&(h=on,F(h))}catch(e){throw Rt(e),e}return{check:le,host:{get currentResolution(){return d},setPurchaseRecovery(e,n){q={message:e,retry:n},O?.updateCapabilities?.(oe(d),ve(d)),Ie(),Zt()},get subscriptionUpgradeActive(){return C!==void 0},get observing(){return Ve},get recovery(){return Ln()},async prepareFallback(){if(fe||w||ie||Ke)return{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null};qe(!0);try{let e=await yn(i);return e.type==="native"&&xe(),e}finally{qe(!1)}},setSuspended(e){ze=e,L.hidden=e,e&&A.open?A.close():!e&&!he?At():!e&&!w&&he&&Me.type!=="inline"&&!A.open&&A.showModal()},destroy:xe,retainPurchaseDialog(){if(!(w||!A.open||!A.isConnected))return xe("destroy",!0),{dialog:A,content:ue?.content,release:ln}},refresh:async()=>{if(!E()){if(i.view)return i.view;throw new I("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await i.refresh();return $e(e),At(),e}}}}export{Pr as a};
|
package/dist/chunk-SYFRWKJP.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{o as n,r as t}from"./chunk-YQ2PQWHZ.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
|
package/dist/chunk-XH6VXXCX.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as He}from"./chunk-ORR47GDS.js";import{a as $}from"./chunk-EQUVI5QU.js";import{D as K,F as Qe,c as Te,e as z,j as xe,u as Le,v as Me,x as Ge,z as ze}from"./chunk-YQ2PQWHZ.js";import{a as Ne,b as je,c as Ue}from"./chunk-FFEJS4K3.js";import{a as se}from"./chunk-EQBJNU6R.js";import{i as ue}from"./chunk-MOIVJERE.js";import{K as G}from"./chunk-I5ZXIKOT.js";import{A as ae,B as ie,C as J,E as Ae}from"./chunk-3532HSBP.js";import{x as ye}from"./chunk-67WFVDTV.js";import{b as Ve}from"./chunk-3WCIX4VH.js";import{a as l}from"./chunk-UGATOG2T.js";import{h as oe}from"./chunk-LFR2LWYC.js";import{a as De}from"./chunk-5MRSFLQA.js";import{b as r}from"./chunk-W22ESUYY.js";import{a as ge}from"./chunk-DSPLGTQI.js";var R=G.options,st=r.discriminatedUnion("operation",[R[1].omit({customerToken:!0}),R[2].omit({customerToken:!0}),R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[7].omit({customerToken:!0}),R[8].omit({customerToken:!0}),xe.omit({customerToken:!0})]),Pe=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),yt=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("find_purchase")}),r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume","start"]),start:r.strictObject({requestId:R[0].shape.requestId,funnelId:R[0].shape.funnelId,locale:R[0].shape.locale,parameters:R[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe,includePaywallVersion:r.literal(!0).optional()}),r.strictObject({operation:r.literal("terminate_checkout"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[7].omit({customerToken:!0})]).optional()}).refine(a=>!a.command||a.requestId===a.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:st})]),ce=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:z.shape.run.shape.status}),H={scope:oe,customerId:r.uuid()},Be=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...H,outcome:r.literal("resolved"),target:ce,view:z.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((a,d)=>{a.outcome==="resolved"&&(a.access.type==="customer"!=(a.view!==null)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Ye=r.strictObject({...H,target:ce,view:z.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:z.shape.purchase.unwrap().nullable()}).superRefine((a,d)=>{let f=a.settlement;(f.acceptance==="accepted"!=(f.receiptPhase!==null)||f.acceptance==="accepted"&&f.basis!=="receipt"||f.acceptance==="unknown"&&(f.state!=="unknown"||f.basis!=="none")||f.acceptance!=="accepted"&&(f.operationId!==null||f.receiptId!==null)||f.acceptance==="not_accepted"&&(f.state!=="settled"||!["run_terminal","position_advanced"].includes(f.basis))||a.purchase&&(a.purchase.receiptId!==f.receiptId||a.purchase.operation&&a.purchase.operation.operationId!==f.operationId||a.purchase.quote&&a.purchase.quote.operationId!==f.operationId)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Je=r.strictObject({...H,target:ce,purchase:z.shape.purchase.unwrap(),paywallVersionId:r.uuid().optional()}).superRefine((a,d)=>{(!a.purchase.operation||typeof a.purchase.canReselect!="boolean"||a.purchase.quote&&a.purchase.quote.operationId!==a.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),Ke=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("none")}),r.strictObject({...H,outcome:r.literal("blocked")}),r.strictObject({...H,outcome:r.literal("found"),target:ce,start:r.strictObject({locale:R[0].shape.locale,parameters:R[0].shape.parameters}),purchase:Pe})]);var ut=G.options[0].refine(a=>!a.customer&&!a.customerData),ct=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),$e=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:oe,customerId:r.uuid(),sessionId:r.uuid(),start:ut,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:Te.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ct).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:Le.nullable()})});function We(a){return Ge({...a,namespace:"purchases",identity:[a.scope.projectId,a.scope.environment,a.customerId]})}function Xe(a){let d=new URL(a.baseUrl??De).href,f=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function S(){a.assertCurrent();try{let E=await a.storage.read();if(a.assertCurrent(),!Number.isSafeInteger(E.revision)||E.revision<0)throw f();let c=E.entry===null?null:$e.parse(E.entry);if(c&&(c.baseUrl!==d||c.customerId!==a.customerId||c.scope.projectId!==a.scope.projectId||c.scope.environment!==a.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(c?.journal.entry&&(c.journal.entry.scope.projectId!==c.scope.projectId||c.journal.entry.scope.environment!==c.scope.environment||c.journal.entry.funnelId!==c.start.funnelId||c.journal.entry.runId!==c.run?.id||c.journal.entry.versionId!==c.run?.versionId)||c?.operationCommand&&!c.purchases.some(k=>k.operationId===c.operationCommand?.operationId))throw f();return{revision:E.revision,entry:c}}catch(E){throw E instanceof l?E:f()}}async function W(E){for(let c=0;c<8;c++){let k=await S(),q=E(structuredClone(k.entry));if(JSON.stringify(q)===JSON.stringify(k.entry))return q;q&&$e.parse(q),a.assertCurrent();let U;try{U=await a.storage.write(k.revision,q)}catch{throw f()}if(a.assertCurrent(),U!==null){if(!Number.isSafeInteger(U)||U<=k.revision)throw f();return q}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:S,update:W,baseUrl:d}}var lt=5*6e4,dt=2e3;function pt(a,d){let f=a.purchases.find(S=>S.type==="checkout");if(!a.actions.includes("continue_checkout")||f?.type!=="checkout"||d!==void 0&&f.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return f.checkoutUrl}function Qt(a){let d={...a,scope:{...a.scope},executionPolicy:structuredClone(a.executionPolicy)},f=d.session.snapshot();if(!f)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:S,sessionId:W}=f,E=!1,c=null,k,q,U=null,A=!1,T,X,Z,b={mode:"idle",status:"idle",actions:["start"],purchases:[]},g=new Map,ve=new Map,x=new Map,le=new AbortController,ee=new Set,Q=Ve(d),te=He(Q.request);function B(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function P(){if(E||d.session.snapshot()?.customerId!==S)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let w=Xe({...d,customerId:S,assertCurrent:P,storage:d.storage??We({baseUrl:d.baseUrl,scope:d.scope,customerId:S})}),Ze,Re=()=>Ze??=import("./funnel-paywall-copies-SKNQNABD.js").then(({createPaywallCopies:e})=>e({baseUrl:d.baseUrl,scope:d.scope,customerId:S})),et={read:async e=>(await Re()).read(e),write:async(e,t)=>(await Re()).write(e,t)},tt=d.session.subscribeIdentity(Se);function Se(){E||(E=!0,clearTimeout(Z),le.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),tt(),c?.reset(),c=null,U=null,Q.dispose(),ee.clear(),g.clear(),x.clear())}function v(e){P();let t=JSON.stringify(e)!==JSON.stringify(b);b=e,clearTimeout(Z),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Z=setTimeout(()=>{M().catch(()=>{})},5e3)),t&&ge(d.onRecovery,structuredClone(e));for(let n of t?ee:[]){if(E)break;ge(n,structuredClone(e))}return structuredClone(e)}function y(e){if(P(),!e||e.start.requestId!==q)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function Ce(e){return!e.run&&!O(e).length&&!e.journal.entry&&!e.operationCommand}function O(e){let t=[...e.purchases],n=e.journal.entry?.purchase;return n&&!t.some(o=>o.operationId===n.operationId)&&t.push({receiptId:n.receiptId,operationId:n.operationId,terminal:null}),t}function N(e){let t=O(e),n=A&&t.length>0&&t.every(o=>o.terminal==="native"&&D(g.get(o.operationId))==="native")&&t.some(o=>{let i=g.get(o.operationId);return!!i&&J(i)&&x.get(o.operationId)===!0});return e.run&&(n||!["running","waiting"].includes(e.run.status))&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&t.every(o=>o.terminal!==null)}function F(e,t){let n=e.journal.entry?.command??e.journal.entry?.closeCommand,o=O(e).map(I=>{let C=g.get(I.operationId);return I.terminal&&!C?{type:I.terminal,operationId:I.operationId}:se({quote:C?.quote??null,operation:C??null,requestId:n?.requestId??null,pending:!1,destroyed:!1,canReselect:x.get(I.operationId)===!0})}),i=o.filter(I=>!["complete","native"].includes(I.type)),u=i[0],s=i.length===1&&u?.operationId?g.get(u.operationId):void 0;if(s&&(u?.type==="checkout"||u?.type==="cancel"))try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},s.quote)}catch(I){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:B(I)}}let m;if(t==="operation"&&!n&&u?.type==="cancel"&&s?.quote&&!s.problem&&!s.confirmedAt)try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},s.quote),Date.parse(s.quote.expiresAt)>Date.now()&&(m={operationId:s.operationId,quote:s.quote})}catch{}let p=o.length>0&&i.length===0,h=N(e)||t==="operation"&&p&&!n&&!e.operationCommand?"complete":u?.type==="checkout"?"checkout":u?.type==="fulfillment"?"fulfillment":u?.type==="recording"?"recording":n||e.operationCommand||u&&u.type!=="cancel"||t==="operation"&&!m?"waiting_result":"ready";return{mode:t,status:h,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...N(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...i.length===1&&u?.type==="checkout"?["continue_checkout"]:[]]}}function D(e){let t=se({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&x.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function de(e){if(!e.operation)return;let t=ae.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let n=ue(g.get(t.operationId)??null,t);g.set(t.operationId,n),n===t&&x.set(t.operationId,e.canReselect===!0)}async function nt(e){P();for(let n of[e.purchase,e.run.paywall])n&&de(n);let t=await w.update(n=>{if(y(n),n.run&&(n.run.id!==e.run.id||n.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=O(n);for(let i of[e.purchase,e.run.paywall]){let u=i?.operation?.operationId??i?.quote?.operationId;if(!i||!u)continue;let s=o.find(p=>p.operationId===u);if(s&&s.receiptId!==i.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=D(g.get(u));s?s.terminal??=m:o.push({receiptId:i.receiptId,operationId:u,terminal:m})}return{...n,purchases:o,run:n.run&&(n.run.revision>e.run.revision||!["running","waiting"].includes(n.run.status)&&["running","waiting"].includes(e.run.status))?n.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});y(t),t.run&&!["running","waiting"].includes(t.run.status)&&O(t).some(n=>!n.terminal)&&(t=await L(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(n=>!!n)))),y(t),v(F(t,"run"))}function rt(){return{async read(){let{entry:e}=await w.read();return y(e),structuredClone(e.journal)},async write(e,t){let n=null;return await w.update(o=>{if(y(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return n=null,o.journal.revision!==e?o:(n=e+1,{...o,journal:{revision:n,entry:t}})}),n}}}async function L(e,t=!1,n=new Set){y(e);let o=O(e);for(let u of o){if(u.terminal)continue;let s=n.has(u.operationId)?g.get(u.operationId):void 0;if(s??=await V(e,u),P(),s.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(s.merchantExecution&&s.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&se({quote:s.quote??null,operation:s,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let m=J(s)?await te.update({operationId:u.operationId,intent:"cancel"}):await te.attach({operationId:u.operationId,intent:"cancel"});if(s=ae.parse(m.operation),P(),s.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");s=await V(e,u)}g.set(u.operationId,ue(g.get(u.operationId)??null,s))}let i=await w.update(u=>{y(u);let s=u.operationCommand&&g.get(u.operationCommand.operationId);return{...u,...s&&(s.confirmedAt||s.merchantExecution||!Ae(s))?{operationCommand:void 0}:{},purchases:O(u).map(m=>({...m,terminal:m.terminal??D(g.get(m.operationId))}))}});return y(i),i}async function Y(e){P();let t=await Q.request("funnels",e);return P(),t}async function ot(e){try{return await Y(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return Y({...e,intent:"resume"})}}async function at(){let e=$(Ke,await Y({operation:"find_purchase"}));if(e.customerId!==S||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:n}=e;return await w.update(o=>o&&!N(o)?o:{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...n,terminal:null}],journal:{revision:0,entry:null}}),"found"}let ne;function pe(e){let t=ne;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<lt))return t.job;let n={at:Date.now(),job:at().then(o=>(n.outcome=o,n.at=Date.now(),o),o=>{throw ne===n&&(ne=void 0),o})};return ne=n,n.job}async function V(e,t,n="recover_purchase",o=!1){let i=$(Je,await Y({operation:n,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId},...o?{includePaywallVersion:!0}:{}}));if(me(e,i),i.purchase.receiptId!==t.receiptId||i.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return de(i.purchase),o&&i.paywallVersionId&&ve.set(t.operationId,i.paywallVersionId),g.get(t.operationId)}async function Ee(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let n=$(Ye,await Y({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(me(e,n),n.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");n.purchase&&de(n.purchase);let o=await w.update(i=>{y(i);let u=O(i),{receiptId:s,operationId:m}=n.settlement;if(s&&m){let h=u.find(I=>I.operationId===m);if(h&&h.receiptId!==s)throw new l("INVALID_RESPONSE","Original Receipt changed");h||u.push({receiptId:s,operationId:m,terminal:D(g.get(m))})}let p=n.settlement.state==="settled"?Me(i.journal.entry,t.requestId):i.journal.entry;return{...i,purchases:u,journal:p===i.journal.entry?i.journal:{revision:i.journal.revision+1,entry:p}}});y(o),e=o}return e}function me(e,t){if(t.customerId!==S||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function fe(e,t){if(y(e),e.run&&(e=await Ee(e)),!O(e).length&&N(e))return v(F(e,"operation"));if(!O(e).length)return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(t)});A=!0;let n=O(e);if(e.run&&["running","waiting"].includes(e.run.status)&&n.every(i=>i.terminal==="native"))for(let i of n)D(g.get(i.operationId))!=="native"&&await V(e,i);let o=await L(e);return v(F(o,"operation"))}async function re(e,t=!1,n=!0,o=!1){if(q=e.start.requestId,U=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!c){let i=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await ot(i)}catch(h){if(!e.run&&h instanceof l&&(h.status===void 0||h.status>=500))return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:B(h)});throw h}let s=$(Be,u);if(s.customerId!==S||s.scope.projectId!==d.scope.projectId||s.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(s.outcome==="unknown"){if(!t&&Ce(e)){let h=e.start.requestId;if(!await w.update(C=>C&&C.start.requestId===h&&Ce(C)?null:C))return v({mode:"idle",status:"idle",actions:["start"],purchases:[]})}return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}})}me(e,s);let m=await w.update(h=>(y(h),{...h,run:{id:s.target.runId,versionId:s.target.versionId,status:s.target.status,revision:s.view?.revision??h.run?.revision??0,runExpiresAt:s.target.runExpiresAt}}));if(y(m),e=m,s.access.type==="operation_only")return fe(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ee(e);let p=s.view;if(p.locale!==e.start.locale||!ze(p.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");c=Qe({...d,customerRun:{runId:s.target.runId,customerId:S,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(h=>d.executionPolicy.allowed.includes(h))},funnelCommandStorage:rt(),onAcceptedResponse:nt},{scope:s.scope,run:p})}try{let i=o&&k?.controller===c?performance.now()-k.at:1/0;(i>=dt||c.pendingCommands?.length||(c.viewAgeMs??0)<i)&&(k=void 0,await c.get(),k={controller:c,at:performance.now()}),c.view?.pendingRequest?.requestId===e.start.requestId&&!c.pendingCommands?.length&&await c.resume(c.view.pendingRequest.requestId);for(let s of c.pendingCommands??[])s.operation!=="close"&&await c.settle?.(s.requestId);c.pendingCommands?.length&&await c.retry(),P();let u=(await w.read()).entry;return y(u),v(F(u,"run"))}catch(i){if(P(),n&&i instanceof l&&(i.status===401||i.status===409&&i.reason==="STATE_CHANGED")){c.reset(),c=null;let u=(await w.read()).entry;return y(u),re(u,!1,!1,!1)}throw i}}function j(e,t="read",n){if(P(),T)return t==="read"||t===X?T:T.then(()=>j(e,t,n),()=>j(e,t,n));clearTimeout(Z);let o=e().catch(i=>{throw!E&&!n?.(i)&&v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:b.purchases,error:B(i)}),i});return T=o,X=t,o.then(()=>{T===o&&(T=void 0,X=void 0)},()=>{T===o&&(T=void 0,X=void 0)}),o}function M(e){let t=e?.reuseRecentRead===!0;return j(async()=>{let{entry:n}=await w.read();if(!n||N(n)){if(await pe(!1)==="blocked")return be();({entry:n}=await w.read())}return n?(q&&n.start.requestId!==q&&(c?.reset(),c=null,g.clear(),x.clear(),A=!1),A&&q===n.start.requestId?fe(n,b.error):re(n,!1,!0,t)):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function be(){return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function Oe(){let e=await M();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:j(async()=>{let t=(await w.read()).entry;if(y(t),!A){if(!c?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=c.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(J(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return v(F(t,"run"));if(c.pendingCommands?.length)await c.retry();else{let I=c.view;await c.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:I.nodeId,visit:I.visit,revision:I.revision,input:{type:"paywall_confirm",operationId:I.paywall.quote.operationId,...I.paywall.quote.merchantTerms?{merchantConfirmation:ye(I.paywall.quote.merchantTerms)}:{}}})}let h=(await w.read()).entry;return y(h),v(F(h,"run"))}let n=t.operationCommand?.operationId??b.confirmation?.operationId,o=n&&g.get(n);if(!n||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");K({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await w.update(p=>{if(y(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==n)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:n,intent:"confirm"}}});let i={operationId:n,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:ye(o.quote.merchantTerms)}:{}},u=J(o)?await te.update(i):await te.attach(i),s=ae.parse(u.operation);if(P(),u.operation.operationId!==n)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");g.set(n,ue(o,s));let m=(await w.read()).entry;return y(m),v(F(await L(m,!1,new Set([n])),"operation"))},"confirm")}function it(e){let t=e?.quote;return t&&ie(t)&&t.timing==="immediate"&&t.execution.provider==="merchant"&&(e.confirmedAt||e.merchantExecution)?t:null}function _e(){if(b.mode!=="operation"||b.status==="blocked")return null;let e=b.purchases.filter(({type:n})=>n!=="complete"&&n!=="native"),t=e.length===1&&e[0]?.operationId;return t?it(g.get(t)):null}async function qe(){P();let{entry:e}=await w.read();return e?N(e)?"finished":"pending":"none"}return{get controller(){return c},get recovery(){return structuredClone(b)},get attempt(){return P(),structuredClone(U)},get identitySignal(){return le.signal},get customerId(){return S},retained:qe,async pendingFunnel(){P();let{entry:e}=await w.read();return e&&!N(e)?e.start.funnelId:null},get paywallCopies(){return et},async findPurchase(){let e=await qe();if(e==="pending")return e;let t=await pe(!0);return P(),t==="none"?e:t},async readPaywall(e){P();let t=Ne(e),[n,{readPaywallContent:o},{validateResourceCheck:i}]=await Promise.all([je(Q.request,"resolvePaywall"),import("./paywall-content-XH344BMX.js"),import("./check-response-XGOTG3KL.js")]);P();let u=n.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),s=await Ue(Q.request,n,u);i(u,s.paywall.check,s.scope);let m=await o(d,s.paywall);if(P(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},get canRestoreUpgradePaywall(){return _e()!==null},recoverUpgradePaywall(){let e=_e();return e?this.recoverPurchasePaywall(void 0,e.operationId):Promise.resolve(null)},async recoverPurchasePaywall(e,t){if(b.mode!=="operation"||b.status==="blocked")return null;let{entry:n}=await w.read();if(!n?.run)return null;y(n);let o=O(n),i=o.filter(_=>!_.terminal),u=o.filter(_=>_.terminal==="complete"),s=i.length===1?i[0]:i.length?void 0:u.find(_=>e&&e.runId===n.run?.id&&_.receiptId===e.receiptId)??(u.length===1?u[0]:void 0);if(!s||t&&s.operationId!==t)return null;let m=e?.runId===n.run.id&&e.receiptId===s.receiptId?e.view:void 0,p;try{p=await V(n,s,"recover_purchase",!0)}catch(_){if(!(_ instanceof l&&_.status===400&&_.code==="INVALID_REQUEST"))throw _;if(!m)return null;p=await V(n,s)}let h=p.quote;if(!h||ie(h)&&(h.timing!=="immediate"||h.execution.provider!=="merchant")||!(p.confirmedAt||p.merchantExecution||p.checkoutUrl||D(p)==="complete"))return null;D(p)!=="complete"&&K({allowed:n.allowed.filter(_=>d.executionPolicy.allowed.includes(_))},h);let I=ve.get(s.operationId),C=n.start.parameters?.commerce,ke=n.start.locale??"en",he=m;if(I){if(typeof C!="object"||!C||!("provider"in C)||typeof C.provider!="string"||!("currency"in C)||typeof C.currency!="string")return null;he=await this.readPaywall({paywallVersionId:I,locale:ke,commerce:{provider:C.provider,currency:C.currency,...ie(h)?{intent:"subscription_change"}:{}}})}if(!he)return null;P();let Fe=he,we=!1,Ie=async()=>{throw new l("PURCHASE_PENDING","Only the original purchase can be recovered")};return{signal:le.signal,view:Fe,quote:h,locale:ke,get operation(){return p},get canReselect(){return x.get(s.operationId)===!0},async refresh(){return Fe},preview:Ie,confirm:Ie,cancel:Ie,async read(){if(we)throw new DOMException("Purchase view closed","AbortError");p=await V(n,s);let _=await L(n,!1,new Set([s.operationId]));return we||v(F(_,"operation")),structuredClone(p)},destroy(){we=!0}}},start(e){let t=G.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return j(async()=>{let n=(await w.read()).entry;if((!n||N(n))&&await pe(!0)==="blocked")return be();let o=await w.update(i=>{if(i&&!N(i)){if(i.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return i}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return q!==o.start.requestId&&(c?.reset(),c=null,g.clear(),x.clear(),A=!1),A?fe(o,b.error):re(o,!0,!0,!0)},`start:${t.funnelId}`)},refresh:M,confirm:Oe,retry:()=>A?Oe():j(async()=>{let{entry:e}=await w.read();return e?re(e,!0):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return c?.view?j(async()=>{if(!c?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(c.pendingCommands?.find(n=>n.operation==="close"))await c.retry();else if(["running","waiting"].includes(c.view.status)){let n=c.view;await c.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision})}let t=(await w.read()).entry;return y(t),v(F(t,"run"))},"close"):M()},async continueCheckout(e,t){let n=t?await j(async()=>{let{entry:o}=await w.read();if(y(o),!o.run||!O(o).some(u=>u.operationId===t&&!u.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let i=await L(o);return v(F(i,A?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await M();P(),await e(pt(n,t))},async terminateCheckout(e){let t=n=>n.actions.includes("continue_checkout")&&n.purchases.some(o=>o.type==="checkout"&&o.operationId===e);if(!t(b)&&!t(await M()))throw new l("PURCHASE_PENDING","The original Checkout has changed");return j(async()=>{let{entry:n}=await w.read();y(n);let o=O(n).find(u=>u.operationId===e&&!u.terminal);if(!o||!n.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await V(n,o,"terminate_checkout");let i=await L(n,!1,new Set([e]));return v(F(i,A?"operation":"run"))},`terminate:${e}`,n=>n instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(n.code))},subscribe(e){return ee.add(e),()=>{ee.delete(e)}},destroy:Se}}export{We as a,pt as b,Qt as c};
|
|
File without changes
|