@tinkerlandai/longplay-sdk 0.10.90 → 0.10.91

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/{chunk-FYWMUFWC.js → chunk-62BAEBBF.js} +1 -1
  3. package/dist/{chunk-4JOYBJQO.js → chunk-C2OHZZTD.js} +1 -1
  4. package/dist/{chunk-3VDU2U66.js → chunk-C4H5JO7L.js} +1 -1
  5. package/dist/{chunk-AXK24XOE.js → chunk-DLOFAAE5.js} +2 -2
  6. package/dist/{chunk-P3J2GOGH.js → chunk-HWKCS5QP.js} +1 -1
  7. package/dist/{chunk-X3TJBUFF.js → chunk-IBHXEGCF.js} +1 -1
  8. package/dist/chunk-OG7GH5DG.js +1 -0
  9. package/dist/{chunk-KEFBS26K.js → chunk-SNLZALQZ.js} +1 -1
  10. package/dist/{chunk-XVTH3B5P.js → chunk-TMYU6Z2E.js} +1 -1
  11. package/dist/{chunk-47S2FZV7.js → chunk-TSAAYP6G.js} +1 -1
  12. package/dist/{chunk-XUKBBAME.js → chunk-XB2T2QXY.js} +1 -1
  13. package/dist/chunk-YSQHTIKP.js +1 -0
  14. package/dist/{content-T47OCROR.js → content-AGXECU25.js} +1 -1
  15. package/dist/{funnel-host-purchase-U5FSCSJF.js → funnel-host-purchase-OV3Q37HE.js} +1 -1
  16. package/dist/{funnel-host-recovery-paywall-VTH7QU2M.js → funnel-host-recovery-paywall-TXXXLNOV.js} +1 -1
  17. package/dist/{funnel-paywall-prerender-W3DBHEND.js → funnel-paywall-prerender-ETY6BGHT.js} +1 -1
  18. package/dist/{funnel-runtime-host-ZOOBQF3C.js → funnel-runtime-host-WORCYV2L.js} +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/openrouter.js +1 -1
  21. package/dist/page.js +1 -1
  22. package/dist/{paywall-GHU6D5SU.js → paywall-5LYPGPWU.js} +1 -1
  23. package/dist/{paywall-content-EGRO37Y2.js → paywall-content-IHFRC37S.js} +1 -1
  24. package/dist/{paywall-session-4MJC4RBH.js → paywall-session-YPIEEUF5.js} +1 -1
  25. package/dist/react-native.js +1 -1
  26. package/dist/server.js +1 -1
  27. package/dist/visual.js +1 -1
  28. package/package.json +1 -1
  29. package/dist/chunk-6OGBLDKX.js +0 -1
  30. package/dist/chunk-BQBXK2EG.js +0 -1
  31. /package/dist/{chunk-AXK24XOE.js.LEGAL.txt → chunk-DLOFAAE5.js.LEGAL.txt} +0 -0
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as En,c as bn}from"./chunk-BQBXK2EG.js";import{a as Rn}from"./chunk-7ZAM4YRK.js";import{a as We}from"./chunk-AEQUKR4O.js";import{a as Ie}from"./chunk-W32FI2A2.js";import{a as pn,c as wn,d as Sn}from"./chunk-KEFBS26K.js";import"./chunk-XLGNBPGF.js";import{a as In}from"./chunk-6OGBLDKX.js";import"./chunk-EQUVI5QU.js";import{h as mn,i as vn,k as Pn}from"./chunk-4JOYBJQO.js";import{E as Ae,d as Xe,f as Qe,g as ge,h as ve,i as Ye,w as yn}from"./chunk-FYWMUFWC.js";import"./chunk-F4AIEI5N.js";import{a as ze}from"./chunk-S2S4ROGY.js";import{d as hn,f as gn}from"./chunk-Y55OBV7D.js";import"./chunk-MOIVJERE.js";import"./chunk-2OBXRQMW.js";import"./chunk-PUDTOCQF.js";import"./chunk-X3TJBUFF.js";import"./chunk-7QPCNDIY.js";import"./chunk-BT7IC765.js";import{K as Ke}from"./chunk-ME6QTD5Y.js";import"./chunk-6XRQR43F.js";import{B as dn,C as ln,D as un,E as fn,c as an,d as sn,e as cn}from"./chunk-3532HSBP.js";import{A as Le,B as Be,D as He,F as qe,G as Ue,I as Ve,J as je,K as Ge,L as Je,M as Te,N as $e,z as _e}from"./chunk-67WFVDTV.js";import"./chunk-KX67ZM7H.js";import"./chunk-6VVQWTHV.js";import"./chunk-VILB5M4X.js";import{b as Ce}from"./chunk-47S2FZV7.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 G}from"./chunk-UGATOG2T.js";import"./chunk-LFR2LWYC.js";import{a as be,c as de}from"./chunk-J6KIN4RH.js";import"./chunk-SLUA7ABW.js";import{c as we,d as Ee}from"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-XUKBBAME.js";import"./chunk-5MRSFLQA.js";import{b as U}from"./chunk-W22ESUYY.js";import{a as Z}from"./chunk-DSPLGTQI.js";import"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";var I=class extends Error{constructor(f,b=0,w=!1,h="fix_request"){super(f);this.code=f;this.status=b;this.retryable=w;this.recovery=h;this.name="MerchantBridgeError"}code;status;retryable;recovery};async function _n(n,d){if(!n.headers.get("content-type")?.split(";",1)[0].trim().match(/^application\/(?:json|[a-z0-9.+-]+\+json)$/i))throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");let f=n.body?.getReader();if(!f)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");let b=()=>{f.cancel().catch(()=>{})};d.addEventListener("abort",b,{once:!0});let w=0,h="",t=new TextDecoder("utf-8",{fatal:!0});try{for(d.throwIfAborted();;){let i=await f.read();if(d.throwIfAborted(),i.done)break;if(w+=i.value.byteLength,w>262144)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");h+=t.decode(i.value,{stream:!0})}return h+=t.decode(),JSON.parse(h)}catch(i){throw d.throwIfAborted(),i instanceof I?i:new I("MERCHANT_BRIDGE_INVALID_RESPONSE")}finally{d.removeEventListener("abort",b),await f.cancel().catch(()=>{}),f.releaseLock()}}function Tn(n){let d=qe.parse(n.origin),f=Ue.parse(n.manifest),b={projectId:n.scope.projectId,environmentId:n.scope.environmentId,environment:n.scope.environment};for(let m of["projectId","environmentId","environment"])if(f[m]!==n.scope[m])throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");let w=n.customerId===void 0?null:U.uuid().parse(n.customerId),h=0,t=null,i=null,u=new AbortController,y=n.fetch??globalThis.fetch;async function P(m,s,E,_,O){if(!f.capabilities.includes(m))throw new I("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let S=He[m];if(["merchant_catalog_reader","merchant_refund_authority","indiana_server_key"].includes(S.authority))throw new I("MERCHANT_BRIDGE_FORBIDDEN",403);let l=h,o=AbortSignal.any([u.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],..._?[_]:[]]);o.throwIfAborted();let T=new Headers(await n.headers?.());if(o.throwIfAborted(),l!==h)throw new DOMException("Merchant identity changed","AbortError");if(/\bgg_(?:sk|ct|rt)_/.test(T.get("authorization")??"")||T.has("X-Indiana-Bridge-Signature")||T.has("X-Indiana-Bridge-Key-Id"))throw new I("MERCHANT_BRIDGE_FORBIDDEN",403);T.set(Be,String(_e)),T.set("Accept","application/json");let g=crypto.randomUUID();T.set("X-Request-Id",g),T.set("Content-Type","application/json");let M=await y(d+Le,{method:"POST",credentials:"include",redirect:"error",cache:"no-store",headers:T,signal:o,body:JSON.stringify({bridgeVersion:_e,requestId:g,command:S.command,scope:b,data:O??(E===void 0?{}:{operationId:E})})}),J=await _n(M,o);if(o.throwIfAborted(),l!==h)throw new DOMException("Merchant identity changed","AbortError");if(!M.ok){let F=$e.safeParse(J);throw!F.success||F.data.scope.projectId!==n.scope.projectId||F.data.scope.environment!==n.scope.environment||F.data.scope.environmentId!==n.scope.environmentId||F.data.requestId!==g||F.data.command!==S.command?new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status):new I(F.data.error.code,M.status,F.data.error.retryable,F.data.error.recovery)}let c=Ve(U.unknown()).safeParse(J);if(!c.success||c.data.scope.projectId!==n.scope.projectId||c.data.scope.environment!==n.scope.environment||c.data.scope.environmentId!==n.scope.environmentId||c.data.requestId!==g||c.data.command!==S.command)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status);let $=s.safeParse(c.data.data);if(!$.success)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status);return $.data}function R(){if(!w)throw new I("MERCHANT_BRIDGE_UNAUTHENTICATED",401);return w}async function B(m,s,E,_){let O=R();if(_!==void 0&&Te.parse({operationId:_,customerId:O}),!f.capabilities.includes(m))throw new I("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let S=h,l=AbortSignal.any([u.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],...s?[s]:[]]);l.throwIfAborted();let o,T=new Promise((g,M)=>{o=()=>M(l.reason),l.addEventListener("abort",o,{once:!0})});try{let M=E(async()=>{let c=await import("./merchant-bridge-contracts-OIYML3DE.js");if(l.throwIfAborted(),S!==h||w!==O)throw new DOMException("Merchant identity changed","AbortError");return c},l),J=await Promise.race([M,T]);return l.throwIfAborted(),J}finally{l.removeEventListener("abort",o)}}async function z(m,s,E,_){let O=R(),S=Te.parse({operationId:E,customerId:O}),l=await P(m,s,S.operationId,_,S);if(l.customerId!==O||l.operationId!==S.operationId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return l}return{async readPresentation(m){let s=await P("presentation",Ge,void 0,m);if(i!==null&&i!==s.nativeUserId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(s.presentation&&w!==null&&s.presentation.customerId!==w)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return i=s.nativeUserId,t=s.presentation,s},async createSession(m){let s=await P("session",je,void 0,m);if(i!==null&&i!==s.nativeUserId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(w!==null&&w!==s.session.customerId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(t&&t.customerId!==s.session.customerId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return w=s.session.customerId,i=s.nativeUserId,s.session},async reportPresentation(m,s){let E=R(),_=Je.parse(m);if(!t||t.customerId!==E||t.decisionId!==_.decisionId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return P("presentation_events",U.strictObject({queued:U.literal(!0)}),void 0,s,_)},async readCustomerCommerce(m){let s=R(),E=await B("customer_commerce",m,async(_,O)=>{let[S,l]=await Promise.all([_(),P("customer_commerce",U.unknown(),void 0,O)]),o=S.merchantBridgeCommerceSchema.safeParse(l);if(!o.success)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return o.data});if(E.customerId!==s)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return E},async executePurchase(m,s){let E=await B("purchases",s,async(_,O)=>z("purchases",(await _()).merchantBridgeOperationSchema,m,O),m);if(E.type!=="purchase")throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return E},readOperation:(m,s)=>B("operation_status",s,async(E,_)=>z("operation_status",(await E()).merchantOperationLookupSchema,m,_),m),async executeSubscriptionChange(m,s){let E=await B("subscription_changes",s,async(_,O)=>z("subscription_changes",(await _()).merchantBridgeOperationSchema,m,O),m);if(E.type!=="subscription_change")throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return E},reset(){h++,u.abort(),u=new AbortController,w=null,t=null,i=null}}}var en=U.strictObject({command:ve,target:Qe,runId:U.uuid().optional(),expiresAt:U.iso.datetime({offset:!0}).optional(),deliveryLimit:U.number().int().min(1).max(100).optional()}).refine(n=>n.command.release===n.target.release),Ze=U.strictObject({schemaVersion:U.literal(1),entries:U.array(en).max(4e3)});function nn(n){let d=!1,f=()=>{d||n.unavailable(),d=!0};function b(){return n.storage===!1?void 0:n.storage??globalThis.sessionStorage}function w(t){let i=b()?.getItem(t);if(!i)return[];if(i.length>1048576)throw Error("Entry recovery is too large");return Ze.parse(JSON.parse(i)).entries}function h(t,i){let u=b();if(!u)return;if(!i.length)return u.removeItem(t);let y=JSON.stringify(Ze.parse({schemaVersion:1,entries:i}));if(y.length>1048576)throw Error("Entry recovery is too large");u.setItem(t,y)}return{load(){try{let t=n.binding();if(!t||n.storage===!1)return;let i="indiana.funnel.entries.v1."+JSON.stringify(t);return{key:i,entries:w(i)}}catch{f();return}},retain(t,i){if(t)try{let u=en.parse(i);h(t,[...w(t).filter(y=>y.command.funnelId!==u.command.funnelId),u])}catch{f()}},forget(t,i){if(t)try{h(t,w(t).filter(u=>u.command.requestId!==i))}catch{f()}}}}var tn=U.strictObject({version:U.literal(1),runs:U.array(U.uuid()).max(100)}),De=new WeakMap,Oe=new WeakMap;function Se(n){let d=!1;function f(){d||n.unavailable(),d=!0}function b(t){let i=t.storage.getItem(t.key);if(!i)return[];if(i.length>8192)throw Error("Invalid entry delivery record");return tn.parse(JSON.parse(i)).runs}function w(t){let i=De.get(t.storage);i||De.set(t.storage,i=new Map);let u=i.get(t.key);return u||i.set(t.key,u=new Set),u}function h(t){if(!t)return;let i=De.get(t.storage),u=i?.get(t.key);u?.delete(t.requestId),u?.size===0&&i?.delete(t.key)}return{claim(t,i,u,y,P=!1){if(u!==void 0)try{let R=n.binding();if(!R)throw Error("Entry delivery identity is unavailable");let B={storage:n.storage??globalThis.sessionStorage,key:"indiana.funnel.delivery.v1."+JSON.stringify([...R,i,t]),requestId:y},z=b(B);if(Oe.get(B.storage)?.has(B.key))throw Error("Entry delivery storage is unavailable");B.storage.setItem(B.key,JSON.stringify({version:1,runs:z}));let m=w(B);return!P&&!m.has(y)&&z.length+m.size>=u?!1:(m.add(y),B)}catch{return f(),!1}},accept(t,i){if(t)try{let u=b(t);u.includes(i)||t.storage.setItem(t.key,JSON.stringify(tn.parse({version:1,runs:[...u,i].slice(-100)})))}catch{let u=Oe.get(t.storage);u||Oe.set(t.storage,u=new Set),u.add(t.key),f()}finally{h(t)}},release:h}}function Pe(){let n,d,f=()=>{clearTimeout(n),n=void 0;let b=d;d=void 0,b?.cancelled()};return{get active(){return d!==void 0},start(b,w,h,t){if(d)return;if(b===0){w()?h():t();return}let i={valid:w,cancelled:t};d=i,n=setTimeout(()=>{d===i&&(d=void 0,n=void 0,w()?h():t())},b*1e3)},recheck(){d&&!d.valid()&&f()},cancel:f}}var Re=n=>["running","waiting"].includes(n.status)&&!n.pendingRequest&&(n.stopped||!n.screen&&!n.paywall&&n.instruction?.type==="wait"&&n.instruction.kind!=="operation");function Cn(n){let d=we(n.baseUrl),f=n.scope,b=Ce(n),w=n.fetch??globalThis.fetch.bind(globalThis),h,t=!1,i=!1,u=0,y=0,P="",R=0,B=0,z=0,m=!1,s,E=!0,_,O,S,l,o,T=-1,g,M=e=>{g===e&&(F.release(e.deliveryTicket),g=void 0,x())},J=new Set,c=(e,a)=>Z(n.onStatus,e,a),$=Pe(),F=Se({storage:n.deliveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[d,f.projectId,f.environment,n.environmentId,"customer",e]:void 0},unavailable:()=>c("delivery_unavailable")}),ee=new Set,te=nn({storage:n.recoveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[d,f.projectId,f.environment,n.environmentId,n.appManifestRelease,e]:void 0},unavailable:()=>c("recovery_unavailable")}),Y=e=>te.forget(e.storageKey,e.command.requestId);function Q(e,a){a&&(e.runId=a.id,e.expiresAt=a.runExpiresAt),te.retain(e.storageKey,{command:e.command,target:e.target,...e.runId&&{runId:e.runId},...e.expiresAt&&{expiresAt:e.expiresAt},...e.deliveryLimit!==void 0&&{deliveryLimit:e.deliveryLimit}})}function re(){let e=o;o=void 0,e?.host.destroy(),e?.slot.remove(),e?.client.reset(),x()}let le=()=>$.active||g!==void 0||o!==void 0&&!o.background;function me(e,a){if(o?.client!==e)return;Q(o.recovery,a);let p=Re(a);o.slot.hidden=p,p!==o.background&&(o.background=p,p?c("run_background",o.entryId):T=y,x())}function pe(e,a,p){let v=e.client.view;if(!a||e.background||!v?.screen||v.paywall||v.pendingRequest||v.stopped||v.status!=="waiting")return;let K=Ke.parse({operation:"close",requestId:crypto.randomUUID(),nodeId:v.nodeId,visit:v.visit,revision:v.revision,customerToken:a}),j=Ce({...n,session:void 0});j.requestWithCredential("funnels",K,e.runToken,{keepalive:p}).then(()=>Y(e.recovery)).catch(()=>{}).finally(()=>j.dispose())}let ae=()=>{o&&pe(o,n.session.peek(),!0)},r=()=>Date.now()<B&&performance.now()<z;function C(e){if(e.target.release!==n.appManifestRelease||!r())return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return c("incompatible",e.id),!1}}function H(e){if(t||e.epoch!==R||e.visit!==y||document.visibilityState==="hidden")return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function W(e){if(le()){c("in_progress",e.id);return}let a=R,p=y;$.start(e.delivery?.delaySeconds??0,()=>!t&&a===R&&p===y&&document.visibilityState!=="hidden"&&C(e)&&h?.entries.some(v=>v.id===e.id&&v.funnelId===e.funnelId&&v.versionId===e.versionId&&v.event===e.event&&JSON.stringify(v.target)===JSON.stringify(e.target)&&JSON.stringify(v.delivery)===JSON.stringify(e.delivery))===!0,()=>{V(e)},()=>{J.delete(`${e.funnelId}:${e.id}`)})}async function V(e){if(le()){c("in_progress",e.id);return}if(!n.session.peek()){c("identity_required",e.id);return}let a=te.load(),p=a?.entries.find(A=>A.command.funnelId===e.funnelId&&(!A.expiresAt||Date.parse(A.expiresAt)>Date.now()));if(p){if(!X(p)){c("recovery_pending",e.id);return}let A={...p,storageKey:a.key,epoch:R,visit:y};ee.add(A.command.requestId),g=A,await N(A);return}let v=crypto.randomUUID(),K=F.claim(e.id,e.funnelId,e.delivery?.maxPerSession,v);if(K===!1){c("frequency",e.id),x();return}let j={freshStart:!0,deliveryLimit:e.delivery?.maxPerSession,deliveryTicket:K,command:ve.parse({operation:"entry_start",entryId:e.id,funnelId:e.funnelId,versionId:e.versionId,release:n.appManifestRelease,requestId:v,locale:document.documentElement.lang||"en"}),epoch:R,visit:y,target:e.target,storageKey:a?.key};ee.add(j.command.requestId),g=j,await N(j)}async function N(e){if(e.dispatching)return;e.dispatching=!0;let a=e.freshStart===!0;e.freshStart=!1;let p,v=!1,K=!1;async function j(A){if(e.epoch!==R)return;let D=A.view;if(!(e.storageKey&&D&&(Re(D)||D.paywall||D.pendingRequest))&&D&&["running","waiting"].includes(D.status))try{await A.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:D.nodeId,visit:D.visit,revision:D.revision}),Y(e)}catch(k){if(!(k instanceof G&&k.code==="FORBIDDEN"))throw k}}try{if(!e.deliveryTicket&&e.deliveryLimit!==void 0){let q=F.claim(e.command.entryId,e.command.funnelId,e.deliveryLimit,e.command.requestId,!0);q!==!1&&(e.deliveryTicket=q)}Q(e),c("starting",e.command.entryId);let A=await b.request("funnels",e.command),D=Ye.safeParse(A);if(D.success){if(D.data.scope.projectId!==f.projectId||D.data.scope.environment!==f.environment)throw new G("SCOPE_MISMATCH","Entry scope changed");e.epoch===R&&c(D.data.reason,e.command.entryId),Y(e),M(e);return}let k=Xe.parse(A);if(!k.runToken||k.scope.projectId!==f.projectId||k.scope.environment!==f.environment||k.run.source.type!=="funnel"||k.run.source.id!==e.command.funnelId||k.run.source.versionId!==e.command.versionId||e.runId!==void 0&&k.run.id!==e.runId)throw new G("INVALID_RESPONSE","Invalid entry Run");if(F.accept(e.deliveryTicket,k.run.id),e.epoch!==R){M(e),c("identity_changed",e.command.entryId);return}Q(e,k.run);let L=Ae({...n,runToken:k.runToken,funnelId:e.command.funnelId,initialResponse:a?A:void 0});p=L,K=!0,await L.get(),K=!1;let ne=L.view;if(!ne||ne.id!==k.run.id||ne.source.type!=="funnel"||ne.source.id!==e.command.funnelId||ne.source.versionId!==e.command.versionId)throw new G("INVALID_RESPONSE","Entry Run version changed");if(!["running","waiting"].includes(ne.status)){Y(e),M(e),c("run_ended",e.command.entryId);return}let{showFunnelRun:fe}=await import("./funnel-runtime-host-ZOOBQF3C.js");if(!H(e)){await j(L),c("left_screen",e.command.entryId),M(e);return}let Ne=!1,xe=!1;if(o&&!o.background){await j(L),c("in_progress",e.command.entryId),M(e);return}o&&re();let ie=document.createElement("div");ie.hidden=Re(ne),n.container.append(ie);let ke=await fe(ie,{...n.host,client:L,appManifestRelease:n.appManifestRelease,onState(q){me(L,q),Z(n.host?.onState,q)},onDismiss(q){Ne=!0,ie.remove(),q&&!["running","waiting"].includes(q.status)&&Y(e),o?.client===L&&(o=void 0,L.reset(),x(),q&&q.status!=="completed"&&c("run_ended",e.command.entryId)),Z(n.host?.onDismiss,q)},onComplete(q){xe=!0,Y(e),o?.client===L&&re(),Z(n.host?.onComplete,q)},onError(q){Z(n.host?.onError,q),o?.client===L&&q instanceof G&&q.code==="FORBIDDEN"&&(Y(e),re(),c("run_ended",e.command.entryId))}}).catch(q=>{throw ie.remove(),q});if(!H(e)||Ne||xe){ke.destroy(),ie.remove(),H(e)||await j(L),M(e);return}let he=Re(L.view??ne);ie.hidden=he,o={host:ke,client:L,slot:ie,entryId:e.command.entryId,background:he,runToken:k.runToken,owner:n.session.peek(),recovery:e},he||(T=e.visit),v=!0,M(e),c("started",e.command.entryId),he&&c("run_background",e.command.entryId)}catch(A){A instanceof G&&(!p||K&&A.code==="FORBIDDEN")&&A.status!==void 0&&A.status>=400&&A.status<500&&!A.retryable&&(Y(e),M(e)),e.epoch===R&&!t&&(c("start_failed",e.command.entryId),Z(n.host?.onError,A))}finally{v||p?.reset(),e.dispatching=!1}}function X(e){if(e.command.release!==n.appManifestRelease||e.target.release!==n.appManifestRelease)return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function ye(){if(le())return!1;let e=te.load();for(let a of e?.entries??[]){if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now()){te.forget(e.key,a.command.requestId);continue}if(a.command.requestId===o?.recovery.command.requestId||ee.has(a.command.requestId)||!X(a))continue;ee.add(a.command.requestId);let p={...a,storageKey:e.key,epoch:R,visit:y};return g=p,N(p),!0}return!1}function ue(){if(m=!1,$.recheck(),t||!i||document.visibilityState==="hidden")return;se();let e=o!==void 0&&!o.background;if(e&&(T=y),!ye()){if(!r()){E=!0;return}E=!1;for(let a of h?.entries??[]){let p=`${a.funnelId}:${a.id}`;if(!(a.event!=="screen_enter"||J.has(p)||!C(a))){if(!n.session.peek()){c("identity_required",a.id);continue}if(T===y){J.add(p),e&&c("in_progress",a.id);continue}if(g||$.active){c("in_progress",a.id);return}J.add(p),W(a);break}}}}let x=()=>{!m&&!t&&(m=!0,queueMicrotask(ue))};function se(){let e=location.origin+location.pathname;return e===P?!1:(P=e,y++,$.cancel(),E=!0,J.clear(),ee.clear(),!0)}function oe(){se()&&x()}function ce(e){if(!e.isTrusted||e.button!==0||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||document.visibilityState==="hidden")return;let a=e.target;if(!(a instanceof Element)||a.closest("[data-indiana-funnel]"))return;let p=a.closest("button,a,input");if(!(!p||p.matches(":disabled,[aria-disabled='true']")||p.closest("[hidden],[inert],[aria-hidden='true']")))for(let v of h?.entries??[]){let K=v.target.button;if(!(v.event!=="button_click"||!K||!C(v))){try{let j=be(document);if(!p.matches(K.selector)||j(K.selector,p)!==1)continue}catch{c("incompatible",v.id);continue}W(v);break}}}async function Me(){if(t)return;if(s)return s;let e=++u,a=new AbortController;_=a;let p,v=new Promise((A,D)=>{p=()=>D(new G("TIMEOUT","Funnel entry configuration read cancelled or timed out")),a.signal.addEventListener("abort",p,{once:!0})}),K=setTimeout(()=>a.abort(),n.timeoutMs??5e3),j=(async()=>{let A=async()=>{let fe=await w(`${d}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:a.signal});if(!fe.ok)throw new G("SERVICE_UNAVAILABLE","Funnel entries unavailable",fe.status);return ge.parse(await fe.json())},D=await Promise.race([A(),v]),k=Date.parse(D.validatedAt),L=Date.parse(D.validUntil);if(D.scope.projectId!==f.projectId||D.scope.environment!==f.environment||D.scope.environmentId!==n.environmentId||D.release!==n.appManifestRelease||L<=Date.now()||k>Date.now()+5e3||L-k>6e4||L<=k)throw new G("INVALID_RESPONSE","Entry configuration scope or deadline changed");if(t||e!==u)return;let ne=h===void 0;h=D,B=L,z=performance.now()+Math.min(L-Date.now(),6e4),$.recheck(),(ne||E)&&x()})();s=j;try{await j}finally{clearTimeout(K),a.signal.removeEventListener("abort",p),s===j&&(s=void 0)}}async function on(){if(!(!i||t)){try{await Me()}catch{t||c("configuration_unavailable")}x()}}let Fe=Ie({document,run:on,delay:()=>i&&!t?15e3:void 0});return{async start(){i||t||(i=!0,P=location.origin+location.pathname,O=Ee(oe),S=n.session.subscribeIdentity(()=>{R++,$.cancel(),F.release(g?.deliveryTicket),E=!0,g=void 0,J.clear(),T=-1,ee.clear(),o&&pe(o,o.owner,!1),re(),x()}),l=new MutationObserver(x),l.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",ce,!0),document.addEventListener("visibilitychange",x),addEventListener("pagehide",ae),await Fe.refresh())},refresh:Me,async retry(){g&&!t&&g.epoch===R&&await N(g)},destroy(){t=!0,u++,$.cancel(),F.release(g?.deliveryTicket),Fe.destroy(),_?.abort(),l?.disconnect(),O?.(),S?.(),document.removeEventListener("click",ce,!0),document.removeEventListener("visibilitychange",x),removeEventListener("pagehide",ae),ae(),re(),b.dispose(),h=void 0}}}function An(n){let d=we(n.baseUrl),f=n.fetch??globalThis.fetch.bind(globalThis),b,w=0,h=0,t=!1,i=!1,u=!1,y=0,P=0,R=-1,B=!1,z="",m,s,E,_,O=new Set,S,l,o,T=(r,C)=>Z(n.onStatus,r,C),g=Pe(),M=()=>{try{return n.deliveryIdentity?.()}catch{return}},J=()=>JSON.stringify(M()),c=Se({storage:n.deliveryStorage,binding:()=>{let r=M();return r?.id?[d,n.scope.projectId,n.scope.environment,n.environmentId,r.type,r.id]:void 0},unavailable:()=>T("delivery_unavailable")}),$=()=>Date.now()<w&&performance.now()<h;function F(r){try{return $()&&r.target.release===n.appManifestRelease&&de(r.target.render,document,location.pathname,()=>{})}catch{return T("incompatible",r.id),!1}}function ee(){let r=o;o=void 0,r?.host.destroy(),r?.slot.remove()}async function te(r){if(r.dispatching)return;r.dispatching=!0;let C=y;try{let H=await r.process.open({operation:"entry_start",funnelId:r.entry.funnelId,versionId:r.entry.versionId,entryId:r.entry.id,release:n.appManifestRelease,locale:n.locale??"en"});c.accept(r.deliveryTicket,H.run.id);let{showFunnelRun:W}=await import("./funnel-runtime-host-ZOOBQF3C.js");if(t||C!==y||l!==r)return;let V=document.createElement("div");n.container.append(V),R=P;let N=await W(V,{...n.host,client:H.controller,appManifestRelease:n.appManifestRelease,onDismiss(X){o?.process===r.process&&(o=void 0,V.remove()),Z(n.host?.onDismiss,X)}});if(t||C!==y||l!==r){N.destroy(),V.remove();return}o={entry:r.entry,process:r.process,host:N,slot:V,deliveryTicket:r.deliveryTicket},l=void 0,T("run_presented",r.entry.id)}catch(H){if(t||C!==y||l!==r)return;H instanceof G&&"result"in H?(c.release(r.deliveryTicket),l=void 0,r.process.destroy(),T("suppressed",r.entry.id),Q()):T("entry_unavailable",r.entry.id)}finally{r.dispatching=!1}}function Y(r){if(t||i||l||o||S||g.active||R===P||!F(r))return;let C=`${P}:${r.id}`;if(O.has(C))return;O.add(C);let H=P,W=y,V=J();g.start(r.delivery?.delaySeconds??0,()=>!t&&y===W&&P===H&&J()===V&&document.visibilityState!=="hidden"&&F(r)&&b?.entries.some(N=>N.id===r.id&&N.funnelId===r.funnelId&&N.versionId===r.versionId&&N.event===r.event&&JSON.stringify(N.target)===JSON.stringify(r.target)&&JSON.stringify(N.delivery)===JSON.stringify(r.delivery))===!0,()=>{let N=c.claim(r.id,r.funnelId,r.delivery?.maxPerSession,crypto.randomUUID());if(N===!1){T("frequency",r.id),Q();return}try{let X={entry:r,process:n.createProcess(r),visit:P,deliveryTicket:N};l=X,te(X)}catch(X){c.release(N),T("entry_unavailable",r.id),Z(n.host?.onError,X)}},()=>{O.delete(C)})}function Q(){B||t||(B=!0,queueMicrotask(()=>{if(B=!1,g.recheck(),!(t||i||document.visibilityState==="hidden"||!$()||l||o||S||g.active||R===P)){for(let r of b?.entries??[])if(r.event==="screen_enter"&&!O.has(`${P}:${r.id}`)&&F(r)){Y(r);break}}}))}function re(r){if(!r.isTrusted||r.defaultPrevented||!(r.target instanceof Element)||l||o||S||R===P)return;let C=be(document,()=>{});for(let H of b?.entries??[]){let W=H.target.button;if(H.event!=="button_click"||!W||!F(H))continue;let V=r.target.closest(W.selector);if(!(!V||V.tagName.toLowerCase()!==W.tag||C(W.selector)!==1||V.matches(":disabled")||V.closest('[inert],[hidden],[aria-hidden="true"]'))){Y(H);break}}}let le=()=>{let r=location.origin+location.pathname;r!==z&&(z=r,P++,g.cancel(),O.clear(),Q())};async function me(){if(t)return;if(s)return s;let r=y,C=new AbortController;m=C;let H,W=new Promise((ye,ue)=>{H=ue}),V=()=>H(new G("TIMEOUT","Funnel entry read cancelled"));C.signal.addEventListener("abort",V,{once:!0});let N=setTimeout(()=>C.abort(),n.timeoutMs??5e3),X=(async()=>{let ye=encodeURIComponent(JSON.stringify(["funnel-process/1"])),ue=async()=>{let ce=await f(`${d}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}&executionContracts=${ye}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:C.signal});if(!ce.ok)throw new G("SERVICE_UNAVAILABLE","Funnel entries unavailable",ce.status);return ge.parse(await ce.json())},x=await Promise.race([ue(),W]),se=Date.parse(x.validatedAt),oe=Date.parse(x.validUntil);if(x.scope.projectId!==n.scope.projectId||x.scope.environment!==n.scope.environment||x.scope.environmentId!==n.environmentId||x.release!==n.appManifestRelease||oe<=Date.now()||se>Date.now()+5e3||oe<=se||oe-se>6e4)throw new G("INVALID_RESPONSE","Entry scope or deadline changed");t||r!==y||(b=x,w=oe,h=performance.now()+Math.min(oe-Date.now(),6e4),g.recheck(),Q())})();s=X;try{await X}finally{clearTimeout(N),C.signal.removeEventListener("abort",V),s===X&&(s=void 0)}}async function pe(){if(!(!u||t))try{await me()}catch{t||T("configuration_unavailable")}}let ae=Ie({document,run:pe,delay:()=>u&&!t?15e3:void 0});return{async start(){u||t||(u=!0,z=location.origin+location.pathname,E=Ee(le),_=new MutationObserver(Q),_.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",re,!0),document.addEventListener("visibilitychange",Q),await ae.refresh())},refresh:me,async retry(){l&&!t&&await te(l)},async syncIdentity(){g.cancel();let r=o??l??S;if(!r){i=!1,Q();return}try{let C=await r.process.syncIdentity();return i=!1,S===r&&(l={...r,visit:P},S=void 0,await te(l)),C}catch(C){throw r.process.view||(S={...r,visit:P},l=void 0,ee()),C}},async detach(){i=!0,y++,g.cancel(),m?.abort();let r=o??l??S;r&&(S={...r,visit:P}),l=void 0,ee(),r&&await r.process.detach()},destroy(){t=!0,y++,g.cancel(),ae.destroy(),m?.abort(),_?.disconnect(),E?.(),document.removeEventListener("click",re,!0),document.removeEventListener("visibilitychange",Q);let r=o??l??S;c.release(r?.deliveryTicket),l=void 0,S=void 0,ee(),r?.process.destroy(),b=void 0}}}async function Dn(n,d){return(await import("./paywall-GHU6D5SU.js")).showPaywall(n,d)}async function dt(){return await Promise.all([import("./paywall-GHU6D5SU.js"),import("./screen-renderer-HJOKBOZH.js")]),Dn}async function lt(...n){return n[1]=ze(n[1]),(await import("./paywall-session-4MJC4RBH.js")).createPaywallSession(...n)}async function ut(...n){let d=n[1].signal?.aborted?void 0:We(n[1].client);try{return import("./screen-renderer-HJOKBOZH.js").catch(()=>{}),import("./paywall-GHU6D5SU.js").catch(()=>{}),await(await rn(()=>import("./funnel-runtime-host-ZOOBQF3C.js"),n[1].prepared)).showFunnelRun(...n)}finally{d?.()}}async function rn(n,d){try{return await n()}catch(f){throw d&&d.state!=="adopted"&&await import("./funnel-paywall-prerender-W3DBHEND.js").then(b=>b.preparedInternals(d)?.release(),()=>{}),f}}async function ft(...n){return import("./screen-renderer-HJOKBOZH.js").catch(()=>{}),import("./paywall-GHU6D5SU.js").catch(()=>{}),(await rn(()=>import("./funnel-host-purchase-U5FSCSJF.js"),n[1].prepared)).showFunnelPurchase(...n)}async function mt(...n){return import("./funnel-host-purchase-U5FSCSJF.js").catch(()=>{}),import("./screen-renderer-HJOKBOZH.js").catch(()=>{}),(await import("./funnel-paywall-prerender-W3DBHEND.js")).prerenderFunnelPurchase(...n)}async function pt(){await Promise.all([import("./funnel-paywall-prerender-W3DBHEND.js"),import("./funnel-host-purchase-U5FSCSJF.js"),import("./paywall-GHU6D5SU.js"),import("./screen-renderer-HJOKBOZH.js"),import("./paywall-content-EGRO37Y2.js"),import("./check-response-XGOTG3KL.js"),import("./operation-contracts-YJM6772C.js")])}async function yt(...n){return(await import("./funnel-route-prediction-Q4HMRAVQ.js")).predictFunnelStart(...n)}async function ht(...n){return(await import("./funnel-route-prediction-Q4HMRAVQ.js")).predictedPaywallLoadingDocument(...n)}async function gt(...n){return(await import("./funnel-host-recovery-paywall-VTH7QU2M.js")).mountFunnelRecoveryPaywall(...n)}async function vt(...n){return(await import("./content-T47OCROR.js")).mountContent(...n)}async function It(...n){return(await import("./content-T47OCROR.js")).prepareContent(...n)}export{G as LongplayError,I as MerchantBridgeError,yn as createBrowserFunnelCommandStorage,En as createBrowserFunnelPurchaseStorage,vn as createConfigurationSync,mn as createFeatureClient,wn as createFunnelClient,Rn as createFunnelPageExperiments,Sn as createFunnelProcess,bn as createFunnelPurchaseClient,Ae as createFunnelRunController,Cn as createIamFunnelEntries,An as createIamFunnelProcessEntries,Pn as createLocalFunnelClient,pn as createLongplay,Tn as createMerchantBridge,lt as createPaywallSession,In as evaluateFunnelNode,sn as formatCouponDiscount,an as formatCouponMoney,cn as formatCouponTerms,hn as getPaywallRecovery,un as isPaywallOperationComplete,fn as isPaywallOperationPending,ln as isPaywallUpdateOperation,dn as isPaywallUpdateQuote,vt as mountContent,gt as mountFunnelRecoveryPaywall,yt as predictFunnelStart,ht as predictedPaywallLoadingDocument,pt as preloadFunnelPurchase,dt as preloadPaywall,It as prepareContent,gn as preparePaywallFallback,mt as prerenderFunnelPurchase,ft as showFunnelPurchase,ut as showFunnelRun,Dn as showPaywall};
1
+ import{a as En,c as bn}from"./chunk-YSQHTIKP.js";import{a as Rn}from"./chunk-7ZAM4YRK.js";import{a as We}from"./chunk-AEQUKR4O.js";import{a as Ie}from"./chunk-W32FI2A2.js";import{a as pn,c as wn,d as Sn}from"./chunk-SNLZALQZ.js";import"./chunk-XLGNBPGF.js";import{a as In}from"./chunk-OG7GH5DG.js";import"./chunk-EQUVI5QU.js";import{h as mn,i as vn,k as Pn}from"./chunk-C2OHZZTD.js";import{E as Ae,d as Xe,f as Qe,g as ge,h as ve,i as Ye,w as yn}from"./chunk-62BAEBBF.js";import"./chunk-F4AIEI5N.js";import{a as ze}from"./chunk-S2S4ROGY.js";import{d as hn,f as gn}from"./chunk-Y55OBV7D.js";import"./chunk-MOIVJERE.js";import"./chunk-2OBXRQMW.js";import"./chunk-PUDTOCQF.js";import"./chunk-IBHXEGCF.js";import"./chunk-7QPCNDIY.js";import"./chunk-BT7IC765.js";import{K as Ke}from"./chunk-ME6QTD5Y.js";import"./chunk-6XRQR43F.js";import{B as dn,C as ln,D as un,E as fn,c as an,d as sn,e as cn}from"./chunk-3532HSBP.js";import{A as Le,B as Be,D as He,F as qe,G as Ue,I as Ve,J as je,K as Ge,L as Je,M as Te,N as $e,z as _e}from"./chunk-67WFVDTV.js";import"./chunk-KX67ZM7H.js";import"./chunk-6VVQWTHV.js";import"./chunk-VILB5M4X.js";import{b as Ce}from"./chunk-TSAAYP6G.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 G}from"./chunk-UGATOG2T.js";import"./chunk-LFR2LWYC.js";import{a as be,c as de}from"./chunk-J6KIN4RH.js";import"./chunk-SLUA7ABW.js";import{c as we,d as Ee}from"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-XB2T2QXY.js";import"./chunk-5MRSFLQA.js";import{b as U}from"./chunk-W22ESUYY.js";import{a as Z}from"./chunk-DSPLGTQI.js";import"./chunk-FYMVNLQN.js";import"./chunk-FRK6322O.js";import"./chunk-WOT6VMZA.js";var I=class extends Error{constructor(f,b=0,w=!1,h="fix_request"){super(f);this.code=f;this.status=b;this.retryable=w;this.recovery=h;this.name="MerchantBridgeError"}code;status;retryable;recovery};async function _n(n,d){if(!n.headers.get("content-type")?.split(";",1)[0].trim().match(/^application\/(?:json|[a-z0-9.+-]+\+json)$/i))throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");let f=n.body?.getReader();if(!f)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");let b=()=>{f.cancel().catch(()=>{})};d.addEventListener("abort",b,{once:!0});let w=0,h="",t=new TextDecoder("utf-8",{fatal:!0});try{for(d.throwIfAborted();;){let i=await f.read();if(d.throwIfAborted(),i.done)break;if(w+=i.value.byteLength,w>262144)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");h+=t.decode(i.value,{stream:!0})}return h+=t.decode(),JSON.parse(h)}catch(i){throw d.throwIfAborted(),i instanceof I?i:new I("MERCHANT_BRIDGE_INVALID_RESPONSE")}finally{d.removeEventListener("abort",b),await f.cancel().catch(()=>{}),f.releaseLock()}}function Tn(n){let d=qe.parse(n.origin),f=Ue.parse(n.manifest),b={projectId:n.scope.projectId,environmentId:n.scope.environmentId,environment:n.scope.environment};for(let m of["projectId","environmentId","environment"])if(f[m]!==n.scope[m])throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");let w=n.customerId===void 0?null:U.uuid().parse(n.customerId),h=0,t=null,i=null,u=new AbortController,y=n.fetch??globalThis.fetch;async function P(m,s,E,_,O){if(!f.capabilities.includes(m))throw new I("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let S=He[m];if(["merchant_catalog_reader","merchant_refund_authority","indiana_server_key"].includes(S.authority))throw new I("MERCHANT_BRIDGE_FORBIDDEN",403);let l=h,o=AbortSignal.any([u.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],..._?[_]:[]]);o.throwIfAborted();let T=new Headers(await n.headers?.());if(o.throwIfAborted(),l!==h)throw new DOMException("Merchant identity changed","AbortError");if(/\bgg_(?:sk|ct|rt)_/.test(T.get("authorization")??"")||T.has("X-Indiana-Bridge-Signature")||T.has("X-Indiana-Bridge-Key-Id"))throw new I("MERCHANT_BRIDGE_FORBIDDEN",403);T.set(Be,String(_e)),T.set("Accept","application/json");let g=crypto.randomUUID();T.set("X-Request-Id",g),T.set("Content-Type","application/json");let M=await y(d+Le,{method:"POST",credentials:"include",redirect:"error",cache:"no-store",headers:T,signal:o,body:JSON.stringify({bridgeVersion:_e,requestId:g,command:S.command,scope:b,data:O??(E===void 0?{}:{operationId:E})})}),J=await _n(M,o);if(o.throwIfAborted(),l!==h)throw new DOMException("Merchant identity changed","AbortError");if(!M.ok){let F=$e.safeParse(J);throw!F.success||F.data.scope.projectId!==n.scope.projectId||F.data.scope.environment!==n.scope.environment||F.data.scope.environmentId!==n.scope.environmentId||F.data.requestId!==g||F.data.command!==S.command?new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status):new I(F.data.error.code,M.status,F.data.error.retryable,F.data.error.recovery)}let c=Ve(U.unknown()).safeParse(J);if(!c.success||c.data.scope.projectId!==n.scope.projectId||c.data.scope.environment!==n.scope.environment||c.data.scope.environmentId!==n.scope.environmentId||c.data.requestId!==g||c.data.command!==S.command)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status);let $=s.safeParse(c.data.data);if(!$.success)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status);return $.data}function R(){if(!w)throw new I("MERCHANT_BRIDGE_UNAUTHENTICATED",401);return w}async function B(m,s,E,_){let O=R();if(_!==void 0&&Te.parse({operationId:_,customerId:O}),!f.capabilities.includes(m))throw new I("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let S=h,l=AbortSignal.any([u.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],...s?[s]:[]]);l.throwIfAborted();let o,T=new Promise((g,M)=>{o=()=>M(l.reason),l.addEventListener("abort",o,{once:!0})});try{let M=E(async()=>{let c=await import("./merchant-bridge-contracts-OIYML3DE.js");if(l.throwIfAborted(),S!==h||w!==O)throw new DOMException("Merchant identity changed","AbortError");return c},l),J=await Promise.race([M,T]);return l.throwIfAborted(),J}finally{l.removeEventListener("abort",o)}}async function z(m,s,E,_){let O=R(),S=Te.parse({operationId:E,customerId:O}),l=await P(m,s,S.operationId,_,S);if(l.customerId!==O||l.operationId!==S.operationId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return l}return{async readPresentation(m){let s=await P("presentation",Ge,void 0,m);if(i!==null&&i!==s.nativeUserId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(s.presentation&&w!==null&&s.presentation.customerId!==w)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return i=s.nativeUserId,t=s.presentation,s},async createSession(m){let s=await P("session",je,void 0,m);if(i!==null&&i!==s.nativeUserId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(w!==null&&w!==s.session.customerId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(t&&t.customerId!==s.session.customerId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return w=s.session.customerId,i=s.nativeUserId,s.session},async reportPresentation(m,s){let E=R(),_=Je.parse(m);if(!t||t.customerId!==E||t.decisionId!==_.decisionId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return P("presentation_events",U.strictObject({queued:U.literal(!0)}),void 0,s,_)},async readCustomerCommerce(m){let s=R(),E=await B("customer_commerce",m,async(_,O)=>{let[S,l]=await Promise.all([_(),P("customer_commerce",U.unknown(),void 0,O)]),o=S.merchantBridgeCommerceSchema.safeParse(l);if(!o.success)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return o.data});if(E.customerId!==s)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return E},async executePurchase(m,s){let E=await B("purchases",s,async(_,O)=>z("purchases",(await _()).merchantBridgeOperationSchema,m,O),m);if(E.type!=="purchase")throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return E},readOperation:(m,s)=>B("operation_status",s,async(E,_)=>z("operation_status",(await E()).merchantOperationLookupSchema,m,_),m),async executeSubscriptionChange(m,s){let E=await B("subscription_changes",s,async(_,O)=>z("subscription_changes",(await _()).merchantBridgeOperationSchema,m,O),m);if(E.type!=="subscription_change")throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return E},reset(){h++,u.abort(),u=new AbortController,w=null,t=null,i=null}}}var en=U.strictObject({command:ve,target:Qe,runId:U.uuid().optional(),expiresAt:U.iso.datetime({offset:!0}).optional(),deliveryLimit:U.number().int().min(1).max(100).optional()}).refine(n=>n.command.release===n.target.release),Ze=U.strictObject({schemaVersion:U.literal(1),entries:U.array(en).max(4e3)});function nn(n){let d=!1,f=()=>{d||n.unavailable(),d=!0};function b(){return n.storage===!1?void 0:n.storage??globalThis.sessionStorage}function w(t){let i=b()?.getItem(t);if(!i)return[];if(i.length>1048576)throw Error("Entry recovery is too large");return Ze.parse(JSON.parse(i)).entries}function h(t,i){let u=b();if(!u)return;if(!i.length)return u.removeItem(t);let y=JSON.stringify(Ze.parse({schemaVersion:1,entries:i}));if(y.length>1048576)throw Error("Entry recovery is too large");u.setItem(t,y)}return{load(){try{let t=n.binding();if(!t||n.storage===!1)return;let i="indiana.funnel.entries.v1."+JSON.stringify(t);return{key:i,entries:w(i)}}catch{f();return}},retain(t,i){if(t)try{let u=en.parse(i);h(t,[...w(t).filter(y=>y.command.funnelId!==u.command.funnelId),u])}catch{f()}},forget(t,i){if(t)try{h(t,w(t).filter(u=>u.command.requestId!==i))}catch{f()}}}}var tn=U.strictObject({version:U.literal(1),runs:U.array(U.uuid()).max(100)}),De=new WeakMap,Oe=new WeakMap;function Se(n){let d=!1;function f(){d||n.unavailable(),d=!0}function b(t){let i=t.storage.getItem(t.key);if(!i)return[];if(i.length>8192)throw Error("Invalid entry delivery record");return tn.parse(JSON.parse(i)).runs}function w(t){let i=De.get(t.storage);i||De.set(t.storage,i=new Map);let u=i.get(t.key);return u||i.set(t.key,u=new Set),u}function h(t){if(!t)return;let i=De.get(t.storage),u=i?.get(t.key);u?.delete(t.requestId),u?.size===0&&i?.delete(t.key)}return{claim(t,i,u,y,P=!1){if(u!==void 0)try{let R=n.binding();if(!R)throw Error("Entry delivery identity is unavailable");let B={storage:n.storage??globalThis.sessionStorage,key:"indiana.funnel.delivery.v1."+JSON.stringify([...R,i,t]),requestId:y},z=b(B);if(Oe.get(B.storage)?.has(B.key))throw Error("Entry delivery storage is unavailable");B.storage.setItem(B.key,JSON.stringify({version:1,runs:z}));let m=w(B);return!P&&!m.has(y)&&z.length+m.size>=u?!1:(m.add(y),B)}catch{return f(),!1}},accept(t,i){if(t)try{let u=b(t);u.includes(i)||t.storage.setItem(t.key,JSON.stringify(tn.parse({version:1,runs:[...u,i].slice(-100)})))}catch{let u=Oe.get(t.storage);u||Oe.set(t.storage,u=new Set),u.add(t.key),f()}finally{h(t)}},release:h}}function Pe(){let n,d,f=()=>{clearTimeout(n),n=void 0;let b=d;d=void 0,b?.cancelled()};return{get active(){return d!==void 0},start(b,w,h,t){if(d)return;if(b===0){w()?h():t();return}let i={valid:w,cancelled:t};d=i,n=setTimeout(()=>{d===i&&(d=void 0,n=void 0,w()?h():t())},b*1e3)},recheck(){d&&!d.valid()&&f()},cancel:f}}var Re=n=>["running","waiting"].includes(n.status)&&!n.pendingRequest&&(n.stopped||!n.screen&&!n.paywall&&n.instruction?.type==="wait"&&n.instruction.kind!=="operation");function Cn(n){let d=we(n.baseUrl),f=n.scope,b=Ce(n),w=n.fetch??globalThis.fetch.bind(globalThis),h,t=!1,i=!1,u=0,y=0,P="",R=0,B=0,z=0,m=!1,s,E=!0,_,O,S,l,o,T=-1,g,M=e=>{g===e&&(F.release(e.deliveryTicket),g=void 0,x())},J=new Set,c=(e,a)=>Z(n.onStatus,e,a),$=Pe(),F=Se({storage:n.deliveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[d,f.projectId,f.environment,n.environmentId,"customer",e]:void 0},unavailable:()=>c("delivery_unavailable")}),ee=new Set,te=nn({storage:n.recoveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[d,f.projectId,f.environment,n.environmentId,n.appManifestRelease,e]:void 0},unavailable:()=>c("recovery_unavailable")}),Y=e=>te.forget(e.storageKey,e.command.requestId);function Q(e,a){a&&(e.runId=a.id,e.expiresAt=a.runExpiresAt),te.retain(e.storageKey,{command:e.command,target:e.target,...e.runId&&{runId:e.runId},...e.expiresAt&&{expiresAt:e.expiresAt},...e.deliveryLimit!==void 0&&{deliveryLimit:e.deliveryLimit}})}function re(){let e=o;o=void 0,e?.host.destroy(),e?.slot.remove(),e?.client.reset(),x()}let le=()=>$.active||g!==void 0||o!==void 0&&!o.background;function me(e,a){if(o?.client!==e)return;Q(o.recovery,a);let p=Re(a);o.slot.hidden=p,p!==o.background&&(o.background=p,p?c("run_background",o.entryId):T=y,x())}function pe(e,a,p){let v=e.client.view;if(!a||e.background||!v?.screen||v.paywall||v.pendingRequest||v.stopped||v.status!=="waiting")return;let K=Ke.parse({operation:"close",requestId:crypto.randomUUID(),nodeId:v.nodeId,visit:v.visit,revision:v.revision,customerToken:a}),j=Ce({...n,session:void 0});j.requestWithCredential("funnels",K,e.runToken,{keepalive:p}).then(()=>Y(e.recovery)).catch(()=>{}).finally(()=>j.dispose())}let ae=()=>{o&&pe(o,n.session.peek(),!0)},r=()=>Date.now()<B&&performance.now()<z;function C(e){if(e.target.release!==n.appManifestRelease||!r())return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return c("incompatible",e.id),!1}}function H(e){if(t||e.epoch!==R||e.visit!==y||document.visibilityState==="hidden")return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function W(e){if(le()){c("in_progress",e.id);return}let a=R,p=y;$.start(e.delivery?.delaySeconds??0,()=>!t&&a===R&&p===y&&document.visibilityState!=="hidden"&&C(e)&&h?.entries.some(v=>v.id===e.id&&v.funnelId===e.funnelId&&v.versionId===e.versionId&&v.event===e.event&&JSON.stringify(v.target)===JSON.stringify(e.target)&&JSON.stringify(v.delivery)===JSON.stringify(e.delivery))===!0,()=>{V(e)},()=>{J.delete(`${e.funnelId}:${e.id}`)})}async function V(e){if(le()){c("in_progress",e.id);return}if(!n.session.peek()){c("identity_required",e.id);return}let a=te.load(),p=a?.entries.find(A=>A.command.funnelId===e.funnelId&&(!A.expiresAt||Date.parse(A.expiresAt)>Date.now()));if(p){if(!X(p)){c("recovery_pending",e.id);return}let A={...p,storageKey:a.key,epoch:R,visit:y};ee.add(A.command.requestId),g=A,await N(A);return}let v=crypto.randomUUID(),K=F.claim(e.id,e.funnelId,e.delivery?.maxPerSession,v);if(K===!1){c("frequency",e.id),x();return}let j={freshStart:!0,deliveryLimit:e.delivery?.maxPerSession,deliveryTicket:K,command:ve.parse({operation:"entry_start",entryId:e.id,funnelId:e.funnelId,versionId:e.versionId,release:n.appManifestRelease,requestId:v,locale:document.documentElement.lang||"en"}),epoch:R,visit:y,target:e.target,storageKey:a?.key};ee.add(j.command.requestId),g=j,await N(j)}async function N(e){if(e.dispatching)return;e.dispatching=!0;let a=e.freshStart===!0;e.freshStart=!1;let p,v=!1,K=!1;async function j(A){if(e.epoch!==R)return;let D=A.view;if(!(e.storageKey&&D&&(Re(D)||D.paywall||D.pendingRequest))&&D&&["running","waiting"].includes(D.status))try{await A.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:D.nodeId,visit:D.visit,revision:D.revision}),Y(e)}catch(k){if(!(k instanceof G&&k.code==="FORBIDDEN"))throw k}}try{if(!e.deliveryTicket&&e.deliveryLimit!==void 0){let q=F.claim(e.command.entryId,e.command.funnelId,e.deliveryLimit,e.command.requestId,!0);q!==!1&&(e.deliveryTicket=q)}Q(e),c("starting",e.command.entryId);let A=await b.request("funnels",e.command),D=Ye.safeParse(A);if(D.success){if(D.data.scope.projectId!==f.projectId||D.data.scope.environment!==f.environment)throw new G("SCOPE_MISMATCH","Entry scope changed");e.epoch===R&&c(D.data.reason,e.command.entryId),Y(e),M(e);return}let k=Xe.parse(A);if(!k.runToken||k.scope.projectId!==f.projectId||k.scope.environment!==f.environment||k.run.source.type!=="funnel"||k.run.source.id!==e.command.funnelId||k.run.source.versionId!==e.command.versionId||e.runId!==void 0&&k.run.id!==e.runId)throw new G("INVALID_RESPONSE","Invalid entry Run");if(F.accept(e.deliveryTicket,k.run.id),e.epoch!==R){M(e),c("identity_changed",e.command.entryId);return}Q(e,k.run);let L=Ae({...n,runToken:k.runToken,funnelId:e.command.funnelId,initialResponse:a?A:void 0});p=L,K=!0,await L.get(),K=!1;let ne=L.view;if(!ne||ne.id!==k.run.id||ne.source.type!=="funnel"||ne.source.id!==e.command.funnelId||ne.source.versionId!==e.command.versionId)throw new G("INVALID_RESPONSE","Entry Run version changed");if(!["running","waiting"].includes(ne.status)){Y(e),M(e),c("run_ended",e.command.entryId);return}let{showFunnelRun:fe}=await import("./funnel-runtime-host-WORCYV2L.js");if(!H(e)){await j(L),c("left_screen",e.command.entryId),M(e);return}let Ne=!1,xe=!1;if(o&&!o.background){await j(L),c("in_progress",e.command.entryId),M(e);return}o&&re();let ie=document.createElement("div");ie.hidden=Re(ne),n.container.append(ie);let ke=await fe(ie,{...n.host,client:L,appManifestRelease:n.appManifestRelease,onState(q){me(L,q),Z(n.host?.onState,q)},onDismiss(q){Ne=!0,ie.remove(),q&&!["running","waiting"].includes(q.status)&&Y(e),o?.client===L&&(o=void 0,L.reset(),x(),q&&q.status!=="completed"&&c("run_ended",e.command.entryId)),Z(n.host?.onDismiss,q)},onComplete(q){xe=!0,Y(e),o?.client===L&&re(),Z(n.host?.onComplete,q)},onError(q){Z(n.host?.onError,q),o?.client===L&&q instanceof G&&q.code==="FORBIDDEN"&&(Y(e),re(),c("run_ended",e.command.entryId))}}).catch(q=>{throw ie.remove(),q});if(!H(e)||Ne||xe){ke.destroy(),ie.remove(),H(e)||await j(L),M(e);return}let he=Re(L.view??ne);ie.hidden=he,o={host:ke,client:L,slot:ie,entryId:e.command.entryId,background:he,runToken:k.runToken,owner:n.session.peek(),recovery:e},he||(T=e.visit),v=!0,M(e),c("started",e.command.entryId),he&&c("run_background",e.command.entryId)}catch(A){A instanceof G&&(!p||K&&A.code==="FORBIDDEN")&&A.status!==void 0&&A.status>=400&&A.status<500&&!A.retryable&&(Y(e),M(e)),e.epoch===R&&!t&&(c("start_failed",e.command.entryId),Z(n.host?.onError,A))}finally{v||p?.reset(),e.dispatching=!1}}function X(e){if(e.command.release!==n.appManifestRelease||e.target.release!==n.appManifestRelease)return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function ye(){if(le())return!1;let e=te.load();for(let a of e?.entries??[]){if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now()){te.forget(e.key,a.command.requestId);continue}if(a.command.requestId===o?.recovery.command.requestId||ee.has(a.command.requestId)||!X(a))continue;ee.add(a.command.requestId);let p={...a,storageKey:e.key,epoch:R,visit:y};return g=p,N(p),!0}return!1}function ue(){if(m=!1,$.recheck(),t||!i||document.visibilityState==="hidden")return;se();let e=o!==void 0&&!o.background;if(e&&(T=y),!ye()){if(!r()){E=!0;return}E=!1;for(let a of h?.entries??[]){let p=`${a.funnelId}:${a.id}`;if(!(a.event!=="screen_enter"||J.has(p)||!C(a))){if(!n.session.peek()){c("identity_required",a.id);continue}if(T===y){J.add(p),e&&c("in_progress",a.id);continue}if(g||$.active){c("in_progress",a.id);return}J.add(p),W(a);break}}}}let x=()=>{!m&&!t&&(m=!0,queueMicrotask(ue))};function se(){let e=location.origin+location.pathname;return e===P?!1:(P=e,y++,$.cancel(),E=!0,J.clear(),ee.clear(),!0)}function oe(){se()&&x()}function ce(e){if(!e.isTrusted||e.button!==0||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||document.visibilityState==="hidden")return;let a=e.target;if(!(a instanceof Element)||a.closest("[data-indiana-funnel]"))return;let p=a.closest("button,a,input");if(!(!p||p.matches(":disabled,[aria-disabled='true']")||p.closest("[hidden],[inert],[aria-hidden='true']")))for(let v of h?.entries??[]){let K=v.target.button;if(!(v.event!=="button_click"||!K||!C(v))){try{let j=be(document);if(!p.matches(K.selector)||j(K.selector,p)!==1)continue}catch{c("incompatible",v.id);continue}W(v);break}}}async function Me(){if(t)return;if(s)return s;let e=++u,a=new AbortController;_=a;let p,v=new Promise((A,D)=>{p=()=>D(new G("TIMEOUT","Funnel entry configuration read cancelled or timed out")),a.signal.addEventListener("abort",p,{once:!0})}),K=setTimeout(()=>a.abort(),n.timeoutMs??5e3),j=(async()=>{let A=async()=>{let fe=await w(`${d}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:a.signal});if(!fe.ok)throw new G("SERVICE_UNAVAILABLE","Funnel entries unavailable",fe.status);return ge.parse(await fe.json())},D=await Promise.race([A(),v]),k=Date.parse(D.validatedAt),L=Date.parse(D.validUntil);if(D.scope.projectId!==f.projectId||D.scope.environment!==f.environment||D.scope.environmentId!==n.environmentId||D.release!==n.appManifestRelease||L<=Date.now()||k>Date.now()+5e3||L-k>6e4||L<=k)throw new G("INVALID_RESPONSE","Entry configuration scope or deadline changed");if(t||e!==u)return;let ne=h===void 0;h=D,B=L,z=performance.now()+Math.min(L-Date.now(),6e4),$.recheck(),(ne||E)&&x()})();s=j;try{await j}finally{clearTimeout(K),a.signal.removeEventListener("abort",p),s===j&&(s=void 0)}}async function on(){if(!(!i||t)){try{await Me()}catch{t||c("configuration_unavailable")}x()}}let Fe=Ie({document,run:on,delay:()=>i&&!t?15e3:void 0});return{async start(){i||t||(i=!0,P=location.origin+location.pathname,O=Ee(oe),S=n.session.subscribeIdentity(()=>{R++,$.cancel(),F.release(g?.deliveryTicket),E=!0,g=void 0,J.clear(),T=-1,ee.clear(),o&&pe(o,o.owner,!1),re(),x()}),l=new MutationObserver(x),l.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",ce,!0),document.addEventListener("visibilitychange",x),addEventListener("pagehide",ae),await Fe.refresh())},refresh:Me,async retry(){g&&!t&&g.epoch===R&&await N(g)},destroy(){t=!0,u++,$.cancel(),F.release(g?.deliveryTicket),Fe.destroy(),_?.abort(),l?.disconnect(),O?.(),S?.(),document.removeEventListener("click",ce,!0),document.removeEventListener("visibilitychange",x),removeEventListener("pagehide",ae),ae(),re(),b.dispose(),h=void 0}}}function An(n){let d=we(n.baseUrl),f=n.fetch??globalThis.fetch.bind(globalThis),b,w=0,h=0,t=!1,i=!1,u=!1,y=0,P=0,R=-1,B=!1,z="",m,s,E,_,O=new Set,S,l,o,T=(r,C)=>Z(n.onStatus,r,C),g=Pe(),M=()=>{try{return n.deliveryIdentity?.()}catch{return}},J=()=>JSON.stringify(M()),c=Se({storage:n.deliveryStorage,binding:()=>{let r=M();return r?.id?[d,n.scope.projectId,n.scope.environment,n.environmentId,r.type,r.id]:void 0},unavailable:()=>T("delivery_unavailable")}),$=()=>Date.now()<w&&performance.now()<h;function F(r){try{return $()&&r.target.release===n.appManifestRelease&&de(r.target.render,document,location.pathname,()=>{})}catch{return T("incompatible",r.id),!1}}function ee(){let r=o;o=void 0,r?.host.destroy(),r?.slot.remove()}async function te(r){if(r.dispatching)return;r.dispatching=!0;let C=y;try{let H=await r.process.open({operation:"entry_start",funnelId:r.entry.funnelId,versionId:r.entry.versionId,entryId:r.entry.id,release:n.appManifestRelease,locale:n.locale??"en"});c.accept(r.deliveryTicket,H.run.id);let{showFunnelRun:W}=await import("./funnel-runtime-host-WORCYV2L.js");if(t||C!==y||l!==r)return;let V=document.createElement("div");n.container.append(V),R=P;let N=await W(V,{...n.host,client:H.controller,appManifestRelease:n.appManifestRelease,onDismiss(X){o?.process===r.process&&(o=void 0,V.remove()),Z(n.host?.onDismiss,X)}});if(t||C!==y||l!==r){N.destroy(),V.remove();return}o={entry:r.entry,process:r.process,host:N,slot:V,deliveryTicket:r.deliveryTicket},l=void 0,T("run_presented",r.entry.id)}catch(H){if(t||C!==y||l!==r)return;H instanceof G&&"result"in H?(c.release(r.deliveryTicket),l=void 0,r.process.destroy(),T("suppressed",r.entry.id),Q()):T("entry_unavailable",r.entry.id)}finally{r.dispatching=!1}}function Y(r){if(t||i||l||o||S||g.active||R===P||!F(r))return;let C=`${P}:${r.id}`;if(O.has(C))return;O.add(C);let H=P,W=y,V=J();g.start(r.delivery?.delaySeconds??0,()=>!t&&y===W&&P===H&&J()===V&&document.visibilityState!=="hidden"&&F(r)&&b?.entries.some(N=>N.id===r.id&&N.funnelId===r.funnelId&&N.versionId===r.versionId&&N.event===r.event&&JSON.stringify(N.target)===JSON.stringify(r.target)&&JSON.stringify(N.delivery)===JSON.stringify(r.delivery))===!0,()=>{let N=c.claim(r.id,r.funnelId,r.delivery?.maxPerSession,crypto.randomUUID());if(N===!1){T("frequency",r.id),Q();return}try{let X={entry:r,process:n.createProcess(r),visit:P,deliveryTicket:N};l=X,te(X)}catch(X){c.release(N),T("entry_unavailable",r.id),Z(n.host?.onError,X)}},()=>{O.delete(C)})}function Q(){B||t||(B=!0,queueMicrotask(()=>{if(B=!1,g.recheck(),!(t||i||document.visibilityState==="hidden"||!$()||l||o||S||g.active||R===P)){for(let r of b?.entries??[])if(r.event==="screen_enter"&&!O.has(`${P}:${r.id}`)&&F(r)){Y(r);break}}}))}function re(r){if(!r.isTrusted||r.defaultPrevented||!(r.target instanceof Element)||l||o||S||R===P)return;let C=be(document,()=>{});for(let H of b?.entries??[]){let W=H.target.button;if(H.event!=="button_click"||!W||!F(H))continue;let V=r.target.closest(W.selector);if(!(!V||V.tagName.toLowerCase()!==W.tag||C(W.selector)!==1||V.matches(":disabled")||V.closest('[inert],[hidden],[aria-hidden="true"]'))){Y(H);break}}}let le=()=>{let r=location.origin+location.pathname;r!==z&&(z=r,P++,g.cancel(),O.clear(),Q())};async function me(){if(t)return;if(s)return s;let r=y,C=new AbortController;m=C;let H,W=new Promise((ye,ue)=>{H=ue}),V=()=>H(new G("TIMEOUT","Funnel entry read cancelled"));C.signal.addEventListener("abort",V,{once:!0});let N=setTimeout(()=>C.abort(),n.timeoutMs??5e3),X=(async()=>{let ye=encodeURIComponent(JSON.stringify(["funnel-process/1"])),ue=async()=>{let ce=await f(`${d}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}&executionContracts=${ye}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:C.signal});if(!ce.ok)throw new G("SERVICE_UNAVAILABLE","Funnel entries unavailable",ce.status);return ge.parse(await ce.json())},x=await Promise.race([ue(),W]),se=Date.parse(x.validatedAt),oe=Date.parse(x.validUntil);if(x.scope.projectId!==n.scope.projectId||x.scope.environment!==n.scope.environment||x.scope.environmentId!==n.environmentId||x.release!==n.appManifestRelease||oe<=Date.now()||se>Date.now()+5e3||oe<=se||oe-se>6e4)throw new G("INVALID_RESPONSE","Entry scope or deadline changed");t||r!==y||(b=x,w=oe,h=performance.now()+Math.min(oe-Date.now(),6e4),g.recheck(),Q())})();s=X;try{await X}finally{clearTimeout(N),C.signal.removeEventListener("abort",V),s===X&&(s=void 0)}}async function pe(){if(!(!u||t))try{await me()}catch{t||T("configuration_unavailable")}}let ae=Ie({document,run:pe,delay:()=>u&&!t?15e3:void 0});return{async start(){u||t||(u=!0,z=location.origin+location.pathname,E=Ee(le),_=new MutationObserver(Q),_.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",re,!0),document.addEventListener("visibilitychange",Q),await ae.refresh())},refresh:me,async retry(){l&&!t&&await te(l)},async syncIdentity(){g.cancel();let r=o??l??S;if(!r){i=!1,Q();return}try{let C=await r.process.syncIdentity();return i=!1,S===r&&(l={...r,visit:P},S=void 0,await te(l)),C}catch(C){throw r.process.view||(S={...r,visit:P},l=void 0,ee()),C}},async detach(){i=!0,y++,g.cancel(),m?.abort();let r=o??l??S;r&&(S={...r,visit:P}),l=void 0,ee(),r&&await r.process.detach()},destroy(){t=!0,y++,g.cancel(),ae.destroy(),m?.abort(),_?.disconnect(),E?.(),document.removeEventListener("click",re,!0),document.removeEventListener("visibilitychange",Q);let r=o??l??S;c.release(r?.deliveryTicket),l=void 0,S=void 0,ee(),r?.process.destroy(),b=void 0}}}async function Dn(n,d){return(await import("./paywall-5LYPGPWU.js")).showPaywall(n,d)}async function dt(){return await Promise.all([import("./paywall-5LYPGPWU.js"),import("./screen-renderer-HJOKBOZH.js")]),Dn}async function lt(...n){return n[1]=ze(n[1]),(await import("./paywall-session-YPIEEUF5.js")).createPaywallSession(...n)}async function ut(...n){let d=n[1].signal?.aborted?void 0:We(n[1].client);try{return import("./screen-renderer-HJOKBOZH.js").catch(()=>{}),import("./paywall-5LYPGPWU.js").catch(()=>{}),await(await rn(()=>import("./funnel-runtime-host-WORCYV2L.js"),n[1].prepared)).showFunnelRun(...n)}finally{d?.()}}async function rn(n,d){try{return await n()}catch(f){throw d&&d.state!=="adopted"&&await import("./funnel-paywall-prerender-ETY6BGHT.js").then(b=>b.preparedInternals(d)?.release(),()=>{}),f}}async function ft(...n){return import("./screen-renderer-HJOKBOZH.js").catch(()=>{}),import("./paywall-5LYPGPWU.js").catch(()=>{}),(await rn(()=>import("./funnel-host-purchase-OV3Q37HE.js"),n[1].prepared)).showFunnelPurchase(...n)}async function mt(...n){return import("./funnel-host-purchase-OV3Q37HE.js").catch(()=>{}),import("./screen-renderer-HJOKBOZH.js").catch(()=>{}),(await import("./funnel-paywall-prerender-ETY6BGHT.js")).prerenderFunnelPurchase(...n)}async function pt(){await Promise.all([import("./funnel-paywall-prerender-ETY6BGHT.js"),import("./funnel-host-purchase-OV3Q37HE.js"),import("./paywall-5LYPGPWU.js"),import("./screen-renderer-HJOKBOZH.js"),import("./paywall-content-IHFRC37S.js"),import("./check-response-XGOTG3KL.js"),import("./operation-contracts-YJM6772C.js")])}async function yt(...n){return(await import("./funnel-route-prediction-Q4HMRAVQ.js")).predictFunnelStart(...n)}async function ht(...n){return(await import("./funnel-route-prediction-Q4HMRAVQ.js")).predictedPaywallLoadingDocument(...n)}async function gt(...n){return(await import("./funnel-host-recovery-paywall-TXXXLNOV.js")).mountFunnelRecoveryPaywall(...n)}async function vt(...n){return(await import("./content-AGXECU25.js")).mountContent(...n)}async function It(...n){return(await import("./content-AGXECU25.js")).prepareContent(...n)}export{G as LongplayError,I as MerchantBridgeError,yn as createBrowserFunnelCommandStorage,En as createBrowserFunnelPurchaseStorage,vn as createConfigurationSync,mn as createFeatureClient,wn as createFunnelClient,Rn as createFunnelPageExperiments,Sn as createFunnelProcess,bn as createFunnelPurchaseClient,Ae as createFunnelRunController,Cn as createIamFunnelEntries,An as createIamFunnelProcessEntries,Pn as createLocalFunnelClient,pn as createLongplay,Tn as createMerchantBridge,lt as createPaywallSession,In as evaluateFunnelNode,sn as formatCouponDiscount,an as formatCouponMoney,cn as formatCouponTerms,hn as getPaywallRecovery,un as isPaywallOperationComplete,fn as isPaywallOperationPending,ln as isPaywallUpdateOperation,dn as isPaywallUpdateQuote,vt as mountContent,gt as mountFunnelRecoveryPaywall,yt as predictFunnelStart,ht as predictedPaywallLoadingDocument,pt as preloadFunnelPurchase,dt as preloadPaywall,It as prepareContent,gn as preparePaywallFallback,mt as prerenderFunnelPurchase,ft as showFunnelPurchase,ut as showFunnelRun,Dn as showPaywall};
@@ -1 +1 @@
1
- import"./chunk-Y6KA56V2.js";import"./chunk-SX7U2ONB.js";import"./chunk-47S2FZV7.js";import"./chunk-KCUE2VFJ.js";import{a as i}from"./chunk-UGATOG2T.js";import"./chunk-LFR2LWYC.js";import"./chunk-XUKBBAME.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
+ import"./chunk-Y6KA56V2.js";import"./chunk-SX7U2ONB.js";import"./chunk-TSAAYP6G.js";import"./chunk-KCUE2VFJ.js";import{a as i}from"./chunk-UGATOG2T.js";import"./chunk-LFR2LWYC.js";import"./chunk-XB2T2QXY.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};
package/dist/page.js CHANGED
@@ -1 +1 @@
1
- import{d as o,e as r,f as e,g as f}from"./chunk-AXK24XOE.js";import"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-XUKBBAME.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
+ import{d as o,e as r,f as e,g as f}from"./chunk-DLOFAAE5.js";import"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-XB2T2QXY.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-XAPMQRVJ.js";import"./chunk-CHRNCOXJ.js";import"./chunk-W32FI2A2.js";import"./chunk-CO6HDNOC.js";import"./chunk-Y55OBV7D.js";import"./chunk-MOIVJERE.js";import"./chunk-6XRQR43F.js";import"./chunk-3532HSBP.js";import"./chunk-67WFVDTV.js";import"./chunk-VILB5M4X.js";import"./chunk-47S2FZV7.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-XUKBBAME.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
+ import{a}from"./chunk-XAPMQRVJ.js";import"./chunk-CHRNCOXJ.js";import"./chunk-W32FI2A2.js";import"./chunk-CO6HDNOC.js";import"./chunk-Y55OBV7D.js";import"./chunk-MOIVJERE.js";import"./chunk-6XRQR43F.js";import"./chunk-3532HSBP.js";import"./chunk-67WFVDTV.js";import"./chunk-VILB5M4X.js";import"./chunk-TSAAYP6G.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-XB2T2QXY.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-X3TJBUFF.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-47S2FZV7.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-XUKBBAME.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
+ import{b as a}from"./chunk-IBHXEGCF.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-TSAAYP6G.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-XB2T2QXY.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-3VDU2U66.js";import"./chunk-CKMSSBJM.js";import"./chunk-FPJ3FE26.js";import"./chunk-S2S4ROGY.js";import"./chunk-Y55OBV7D.js";import"./chunk-MOIVJERE.js";import"./chunk-2OBXRQMW.js";import"./chunk-PUDTOCQF.js";import"./chunk-X3TJBUFF.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-47S2FZV7.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-XUKBBAME.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};
1
+ import{a}from"./chunk-C4H5JO7L.js";import"./chunk-CKMSSBJM.js";import"./chunk-FPJ3FE26.js";import"./chunk-S2S4ROGY.js";import"./chunk-Y55OBV7D.js";import"./chunk-MOIVJERE.js";import"./chunk-2OBXRQMW.js";import"./chunk-PUDTOCQF.js";import"./chunk-IBHXEGCF.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-TSAAYP6G.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-XB2T2QXY.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};
@@ -1 +1 @@
1
- import{b as S,c as E,d as T}from"./chunk-KEFBS26K.js";import"./chunk-XLGNBPGF.js";import{a as A}from"./chunk-3VDU2U66.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-4JOYBJQO.js";import{E as C}from"./chunk-FYWMUFWC.js";import"./chunk-F4AIEI5N.js";import"./chunk-S2S4ROGY.js";import"./chunk-Y55OBV7D.js";import"./chunk-MOIVJERE.js";import"./chunk-2OBXRQMW.js";import"./chunk-PUDTOCQF.js";import"./chunk-X3TJBUFF.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-47S2FZV7.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-XUKBBAME.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};
1
+ import{b as S,c as E,d as T}from"./chunk-SNLZALQZ.js";import"./chunk-XLGNBPGF.js";import{a as A}from"./chunk-C4H5JO7L.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-C2OHZZTD.js";import{E as C}from"./chunk-62BAEBBF.js";import"./chunk-F4AIEI5N.js";import"./chunk-S2S4ROGY.js";import"./chunk-Y55OBV7D.js";import"./chunk-MOIVJERE.js";import"./chunk-2OBXRQMW.js";import"./chunk-PUDTOCQF.js";import"./chunk-IBHXEGCF.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-TSAAYP6G.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-XB2T2QXY.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.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as pn}from"./chunk-6OGBLDKX.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-3VDU2U66.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-4JOYBJQO.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-FYWMUFWC.js";import"./chunk-F4AIEI5N.js";import{c as h}from"./chunk-S2S4ROGY.js";import"./chunk-Y55OBV7D.js";import"./chunk-MOIVJERE.js";import"./chunk-2OBXRQMW.js";import{a as Et,b as _e}from"./chunk-PUDTOCQF.js";import"./chunk-X3TJBUFF.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-47S2FZV7.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-XUKBBAME.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}
1
+ import{a as pn}from"./chunk-OG7GH5DG.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-C4H5JO7L.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-C2OHZZTD.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-62BAEBBF.js";import"./chunk-F4AIEI5N.js";import{c as h}from"./chunk-S2S4ROGY.js";import"./chunk-Y55OBV7D.js";import"./chunk-MOIVJERE.js";import"./chunk-2OBXRQMW.js";import{a as Et,b as _e}from"./chunk-PUDTOCQF.js";import"./chunk-IBHXEGCF.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-TSAAYP6G.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-XB2T2QXY.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-AXK24XOE.js";import{a as re,b as ae,c as se,d as oe}from"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-XUKBBAME.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};
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-DLOFAAE5.js";import{a as re,b as ae,c as se,d as oe}from"./chunk-MB2U2GWJ.js";import"./chunk-3VUPVXAV.js";import"./chunk-XB2T2QXY.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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tinkerlandai/longplay-sdk",
3
- "version": "0.10.90",
3
+ "version": "0.10.91",
4
4
  "description": "Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- import{o as n,r as t}from"./chunk-FYWMUFWC.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
@@ -1 +0,0 @@
1
- import{b as Me}from"./chunk-XLGNBPGF.js";import{a as ee}from"./chunk-EQUVI5QU.js";import{D as Z,F as Ye,c as Ve,e as Y,j as He,u as ze,v as Qe,x as Be,z as Je}from"./chunk-FYWMUFWC.js";import{a as Ue,b as xe,c as De}from"./chunk-S2S4ROGY.js";import{b as de}from"./chunk-Y55OBV7D.js";import{i as pe}from"./chunk-MOIVJERE.js";import{K as J}from"./chunk-ME6QTD5Y.js";import{A as le,B as X,C as B,E as Te}from"./chunk-3532HSBP.js";import{x as Re}from"./chunk-67WFVDTV.js";import{b as Ge}from"./chunk-47S2FZV7.js";import{a as l}from"./chunk-UGATOG2T.js";import{h as ce}from"./chunk-LFR2LWYC.js";import{a as Le}from"./chunk-5MRSFLQA.js";import{b as o}from"./chunk-W22ESUYY.js";import{a as Ee}from"./chunk-DSPLGTQI.js";var R=J.options,mt=o.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}),He.omit({customerToken:!0})]),Se=o.strictObject({receiptId:o.uuid(),operationId:o.uuid()}),Et=o.discriminatedUnion("operation",[o.strictObject({operation:o.literal("find_purchase")}),o.strictObject({operation:o.literal("recover_start"),intent:o.enum(["lookup","resume","start"]),start:o.strictObject({requestId:R[0].shape.requestId,funnelId:R[0].shape.funnelId,locale:R[0].shape.locale,parameters:R[0].shape.parameters})}),o.strictObject({operation:o.literal("recover_run"),runId:o.uuid(),funnelId:o.uuid()}),o.strictObject({operation:o.literal("recover_purchase"),runId:o.uuid(),funnelId:o.uuid(),purchase:Se,includePaywallVersion:o.literal(!0).optional()}),o.strictObject({operation:o.literal("terminate_checkout"),runId:o.uuid(),funnelId:o.uuid(),purchase:Se,intent:o.literal("expire_unconfirmed_quote").optional()}),o.strictObject({operation:o.literal("settle_command"),runId:o.uuid(),funnelId:o.uuid(),requestId:o.uuid(),command:o.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(u=>!u.command||u.requestId===u.command.requestId),o.strictObject({operation:o.literal("run_command"),runId:o.uuid(),funnelId:o.uuid(),command:mt})]),me=o.strictObject({runId:o.uuid(),funnelId:o.uuid(),versionId:o.uuid(),startRequestId:o.uuid(),runExpiresAt:o.iso.datetime({offset:!0}),status:Y.shape.run.shape.status}),M={scope:ce,customerId:o.uuid()},Ke=o.discriminatedUnion("outcome",[o.strictObject({...M,outcome:o.literal("unknown"),target:o.null(),view:o.null(),access:o.null()}),o.strictObject({...M,outcome:o.literal("resolved"),target:me,view:Y.shape.run.nullable(),access:o.discriminatedUnion("type",[o.strictObject({type:o.literal("customer")}),o.strictObject({type:o.literal("operation_only"),cause:o.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((u,m)=>{u.outcome==="resolved"&&(u.access.type==="customer"!=(u.view!==null)||u.view&&(u.view.id!==u.target.runId||u.view.source.id!==u.target.funnelId||u.view.source.versionId!==u.target.versionId||u.view.status!==u.target.status||u.view.runExpiresAt!==u.target.runExpiresAt||u.view.credentialExpiresAt!==null))&&m.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),$e=o.strictObject({...M,target:me,view:Y.shape.run.nullable(),settlement:o.strictObject({requestId:o.uuid(),state:o.enum(["pending","unknown","settled"]),acceptance:o.enum(["accepted","not_accepted","unknown"]),receiptPhase:o.enum(["accepted","processing","done"]).nullable(),basis:o.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:o.uuid().nullable(),operationId:o.uuid().nullable()}),purchase:Y.shape.purchase.unwrap().nullable()}).superRefine((u,m)=>{let h=u.settlement;(h.acceptance==="accepted"!=(h.receiptPhase!==null)||h.acceptance==="accepted"&&h.basis!=="receipt"||h.acceptance==="unknown"&&(h.state!=="unknown"||h.basis!=="none")||h.acceptance!=="accepted"&&(h.operationId!==null||h.receiptId!==null)||h.acceptance==="not_accepted"&&(h.state!=="settled"||!["run_terminal","position_advanced"].includes(h.basis))||u.purchase&&(u.purchase.receiptId!==h.receiptId||u.purchase.operation&&u.purchase.operation.operationId!==h.operationId||u.purchase.quote&&u.purchase.quote.operationId!==h.operationId)||u.view&&(u.view.id!==u.target.runId||u.view.source.id!==u.target.funnelId||u.view.source.versionId!==u.target.versionId||u.view.status!==u.target.status||u.view.runExpiresAt!==u.target.runExpiresAt||u.view.credentialExpiresAt!==null))&&m.addIssue({code:"custom",message:"Original command settlement binding differs"})}),We=o.strictObject({...M,target:me,purchase:Y.shape.purchase.unwrap(),paywallVersionId:o.uuid().optional()}).superRefine((u,m)=>{(!u.purchase.operation||typeof u.purchase.canReselect!="boolean"||u.purchase.quote&&u.purchase.quote.operationId!==u.purchase.operation.operationId)&&m.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),Xe=o.discriminatedUnion("outcome",[o.strictObject({...M,outcome:o.literal("none")}),o.strictObject({...M,outcome:o.literal("blocked")}),o.strictObject({...M,outcome:o.literal("found"),target:me,start:o.strictObject({locale:R[0].shape.locale,parameters:R[0].shape.parameters}),purchase:Se})]);var ft=J.options[0].refine(u=>!u.customer&&!u.customerData),ht=o.strictObject({receiptId:o.uuid(),operationId:o.uuid(),terminal:o.enum(["complete","native"]).nullable()}),Ze=o.strictObject({schemaVersion:o.literal(1),baseUrl:o.url(),scope:ce,customerId:o.uuid(),sessionId:o.uuid(),start:ft,allowed:o.array(o.enum(["merchant","record_only","indiana","native"])),run:o.strictObject({id:o.uuid(),versionId:o.uuid(),status:Ve.shape.status,revision:o.number().int().nonnegative(),runExpiresAt:o.iso.datetime({offset:!0}).optional()}).optional(),purchases:o.array(ht).max(100),operationCommand:o.strictObject({operationId:o.uuid(),intent:o.literal("confirm")}).optional(),journal:o.strictObject({revision:o.number().int().nonnegative(),entry:ze.nullable()})});function et(u){return Be({...u,namespace:"purchases",identity:[u.scope.projectId,u.scope.environment,u.customerId]})}function tt(u){let m=new URL(u.baseUrl??Le).href,h=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function E(){u.assertCurrent();try{let S=await u.storage.read();if(u.assertCurrent(),!Number.isSafeInteger(S.revision)||S.revision<0)throw h();let c=S.entry===null?null:Ze.parse(S.entry);if(c&&(c.baseUrl!==m||c.customerId!==u.customerId||c.scope.projectId!==u.scope.projectId||c.scope.environment!==u.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 h();return{revision:S.revision,entry:c}}catch(S){throw S instanceof l?S:h()}}async function te(S){for(let c=0;c<8;c++){let k=await E(),O=S(structuredClone(k.entry));if(JSON.stringify(O)===JSON.stringify(k.entry))return O;O&&Ze.parse(O),u.assertCurrent();let U;try{U=await u.storage.write(k.revision,O)}catch{throw h()}if(u.assertCurrent(),U!==null){if(!Number.isSafeInteger(U)||U<=k.revision)throw h();return O}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:E,update:te,baseUrl:m}}var wt=5*6e4,It=2e3;function yt(u,m){let h=u.purchases.find(E=>E.type==="checkout");if(!u.actions.includes("continue_checkout")||h?.type!=="checkout"||m!==void 0&&h.operationId!==m)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return h.checkoutUrl}function fe(u){return!u||u.operation==="close"||u.operation==="back"||u.operation==="shown"||u.operation==="submit"&&u.input.type==="screen"}var nt=()=>({revision:0,entry:null});function Wt(u){let m={...u,scope:{...u.scope},executionPolicy:structuredClone(u.executionPolicy)},h=m.session.snapshot();if(!h)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:E,sessionId:te}=h,S=!1,c=null,k,O,U=null,A=!1,x,ne,re,_={mode:"idle",status:"idle",actions:["start"],purchases:[]},v=new Map,be=new Map,D=new Map,he=new AbortController,oe=new Set,K=Ge(m),ae=Me(K.request);function $(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 y(){if(S||m.session.snapshot()?.customerId!==E)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let w=tt({...m,customerId:E,assertCurrent:y,storage:m.storage??et({baseUrl:m.baseUrl,scope:m.scope,customerId:E})}),rt,qe=()=>rt??=import("./funnel-paywall-copies-LPOTYSTS.js").then(({createPaywallCopies:e})=>e({baseUrl:m.baseUrl,scope:m.scope,customerId:E})),ot={read:async e=>(await qe()).read(e),write:async(e,t)=>(await qe()).write(e,t)},at=m.session.subscribeIdentity(_e);function _e(){S||(S=!0,clearTimeout(re),he.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),at(),c?.reset(),c=null,U=null,K.dispose(),oe.clear(),v.clear(),D.clear())}function C(e){y();let t=JSON.stringify(e)!==JSON.stringify(_);_=e,clearTimeout(re),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(re=setTimeout(()=>{Q().catch(()=>{})},5e3)),t&&Ee(m.onRecovery,structuredClone(e));for(let n of t?oe:[]){if(S)break;Ee(n,structuredClone(e))}return structuredClone(e)}function g(e){if(y(),!e||e.start.requestId!==O)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function Oe(e){return!e.run&&!b(e).length&&!e.journal.entry&&!e.operationCommand}function we(e){let t=e.journal.entry;return!b(e).length&&!e.operationCommand&&fe(t?.command)&&fe(t?.closeCommand)}function z(e){return!!e.run&&we(e)}function b(e){let t=[...e.purchases],n=e.journal.entry?.purchase;return n&&!t.some(a=>a.operationId===n.operationId)&&t.push({receiptId:n.receiptId,operationId:n.operationId,terminal:null}),t}function j(e){let t=b(e),n=A&&t.length>0&&t.every(a=>a.terminal==="native"&&H(v.get(a.operationId))==="native")&&t.some(a=>{let r=v.get(a.operationId);return!r||D.get(a.operationId)!==!0?!1:B(r)?!0:r.status==="cancelled"&&r.confirmedAt===null&&!r.quoteFinalized&&!r.merchantExecution&&!r.problem&&!!r.quote&&Date.parse(r.quote.expiresAt)<=Date.now()});return e.run&&(n||!["running","waiting"].includes(e.run.status))&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&t.every(a=>a.terminal!==null)}function N(e,t){let n=e.journal.entry?.command??e.journal.entry?.closeCommand,a=b(e).map(f=>{let q=v.get(f.operationId),P=de({quote:q?.quote??null,operation:q??null,requestId:n?.requestId??null,pending:!1,destroyed:!1,canReselect:D.get(f.operationId)===!0});return f.terminal&&(P.type==="checkout"||P.type==="recover"||P.type==="cancel")?{type:f.terminal,operationId:f.operationId}:P}),r=a.filter(f=>!["complete","native"].includes(f.type)),i=r[0],s=r.length===1&&i?.operationId?v.get(i.operationId):void 0;if(s&&(i?.type==="checkout"||i?.type==="cancel"))try{Z({allowed:e.allowed.filter(f=>m.executionPolicy.allowed.includes(f))},s.quote)}catch(f){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:a,error:$(f)}}let d;if(t==="operation"&&!n&&i?.type==="cancel"&&s?.quote&&!s.problem&&!s.confirmedAt)try{Z({allowed:e.allowed.filter(f=>m.executionPolicy.allowed.includes(f))},s.quote),Date.parse(s.quote.expiresAt)>Date.now()&&(d={operationId:s.operationId,quote:s.quote})}catch{}let p=a.length>0&&r.length===0,I=j(e)||t==="operation"&&p&&!n&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":n||e.operationCommand||i&&i.type!=="cancel"||t==="operation"&&!d?"waiting_result":"ready";return{mode:t,status:I,purchases:a,...d?{confirmation:structuredClone(d)}:{},actions:["refresh",...j(e)||z(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:d?["confirm"]:[],...r.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function H(e){let t=de({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&D.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function Ie(e){if(!e.operation)return;let t=le.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==E)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let n=pe(v.get(t.operationId)??null,t);v.set(t.operationId,n),n===t&&D.set(t.operationId,e.canReselect===!0)}async function it(e,t,n){y();for(let i of[e.purchase,e.run.paywall])i&&Ie(i);let a=!1,r=await w.update(i=>{if(i&&i.start.requestId!==t)return a=!0,i;if(g(i),i.run&&(i.run.id!==e.run.id||i.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let s=b(i);for(let d of[e.purchase,e.run.paywall]){let p=d?.operation?.operationId??d?.quote?.operationId;if(!d||!p)continue;let I=s.find(q=>q.operationId===p);if(I&&I.receiptId!==d.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let f=H(v.get(p));I?I.terminal??=f:s.push({receiptId:d.receiptId,operationId:p,terminal:f})}return{...i,purchases:s,run:i.run&&(i.run.revision>e.run.revision||!["running","waiting"].includes(i.run.status)&&["running","waiting"].includes(e.run.status))?i.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});if(a){n();return}g(r),r.run&&!["running","waiting"].includes(r.run.status)&&b(r).some(i=>!i.terminal)&&(r=await L(r,!r.journal.entry?.command&&!r.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(i=>!!i)))),g(r),C(N(r,"run"))}function st(e){let t;return()=>{t||S||(t=setTimeout(()=>{let n=e(),a=n.view;if(S||!a||!["running","waiting"].includes(a.status)||n.pendingCommands?.some(r=>r.operation==="close")){t=void 0;return}t=n.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:a.nodeId,visit:a.visit,revision:a.revision}).catch(()=>{}).finally(()=>{t=void 0})}))}}function ut(e,t){let n=null,a=r=>!!r&&r.start.requestId!==e;return{async read(){let{entry:r}=await w.read();return y(),a(r)?(t(),structuredClone(n??=nt())):(g(r),structuredClone(r.journal))},async write(r,i){let s=null;return await w.update(d=>{if(a(d)){if(t(),!fe(i?.command)||!fe(i?.closeCommand))throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; its Run can only be dismissed");let p=n??=nt();return s=null,p.revision!==r||(s=r+1,n={revision:s,entry:i}),d}if(g(d),d.operationCommand&&i?.command&&i.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return s=null,d.journal.revision!==r?d:(s=r+1,{...d,journal:{revision:s,entry:i}})}),s}}}async function L(e,t=!1,n=new Set){g(e);let a=b(e);for(let i of a){if(i.terminal)continue;let s=n.has(i.operationId)?v.get(i.operationId):void 0;if(s??=await V(e,i),y(),s.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(s.merchantExecution&&s.merchantExecution.customerId!==E)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&de({quote:s.quote??null,operation:s,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let d=B(s)?await ae.update({operationId:i.operationId,intent:"cancel"}):await ae.attach({operationId:i.operationId,intent:"cancel"});if(s=le.parse(d.operation),y(),s.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");s=await V(e,i)}v.set(i.operationId,pe(v.get(i.operationId)??null,s))}let r=await w.update(i=>{g(i);let s=i.operationCommand&&v.get(i.operationCommand.operationId);return{...i,...s&&(s.confirmedAt||s.merchantExecution||!Te(s))?{operationCommand:void 0}:{},purchases:b(i).map(d=>({...d,terminal:d.terminal??H(v.get(d.operationId))}))}});return g(r),r}async function W(e){y();let t=await K.request("funnels",e);return y(),t}async function ct(e){try{return await W(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return W({...e,intent:"resume"})}}async function lt(){let e=ee(Xe,await W({operation:"find_purchase"}));if(e.customerId!==E||e.scope.projectId!==m.scope.projectId||e.scope.environment!==m.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(a=>a&&!j(a)&&!z(a)?a:{schemaVersion:1,baseUrl:w.baseUrl,scope:m.scope,customerId:E,sessionId:te,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...m.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 ie;function ye(e){let t=ie;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<wt))return t.job;let n={at:Date.now(),job:lt().then(a=>(n.outcome=a,n.at=Date.now(),a),a=>{throw ie===n&&(ie=void 0),a})};return ie=n,n.job}async function V(e,t,n="recover_purchase",a=!1){let r={runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId}},i=n==="recover_purchase"?{...r,operation:n,...a?{includePaywallVersion:!0}:{}}:{...r,operation:"terminate_checkout",...n==="expire_unconfirmed_quote"?{intent:n}:{}},s=ee(We,await W(i));if(ge(e,s),s.purchase.receiptId!==t.receiptId||s.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return Ie(s.purchase),a&&s.paywallVersionId&&be.set(t.operationId,s.paywallVersionId),v.get(t.operationId)}async function Fe(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let n=ee($e,await W({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(ge(e,n),n.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");n.purchase&&Ie(n.purchase);let a=await w.update(r=>{g(r);let i=b(r),{receiptId:s,operationId:d}=n.settlement;if(s&&d){let I=i.find(f=>f.operationId===d);if(I&&I.receiptId!==s)throw new l("INVALID_RESPONSE","Original Receipt changed");I||i.push({receiptId:s,operationId:d,terminal:H(v.get(d))})}let p=n.settlement.state==="settled"?Qe(r.journal.entry,t.requestId):r.journal.entry;return{...r,purchases:i,journal:p===r.journal.entry?r.journal:{revision:r.journal.revision+1,entry:p}}});g(a),e=a}return e}function ge(e,t){if(t.customerId!==E||t.scope.projectId!==m.scope.projectId||t.scope.environment!==m.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 Pe(e,t){if(g(e),e.run&&(e=await Fe(e)),!b(e).length&&j(e))return C(N(e,"operation"));if(we(e)){let r=e.start.requestId;if(!await w.update(s=>s&&s.start.requestId===r&&we(s)?null:s))return c?.reset(),c=null,A=!1,C({mode:"idle",status:"idle",actions:["start"],purchases:[]})}if(!b(e).length)return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:$(t)});A=!0;let n=b(e);if(e.run&&["running","waiting"].includes(e.run.status)&&n.every(r=>r.terminal==="native"))for(let r of n)H(v.get(r.operationId))!=="native"&&await V(e,r);let a=await dt(await L(e));return C(N(a,"operation"))}async function dt(e){if(e.journal.entry?.command||e.journal.entry?.closeCommand||e.operationCommand)return e;let t=b(e).filter(i=>!i.terminal),n=t[0];if(!n||t.length!==1)return e;let a=v.get(n.operationId),r=a?.quote;if(!a||B(a)||!r||X(r)||r.provider!=="merchant"||a.status!=="pending"||a.confirmedAt!==null||a.quoteFinalized||a.checkoutUrl||a.nativePurchase||a.merchantExecution||a.problem||Date.parse(r.expiresAt)>Date.now())return e;try{await V(e,n,"expire_unconfirmed_quote")}catch{return y(),e}return L(e,!1,new Set([n.operationId]))}async function se(e,t=!1,n=!0,a=!1){if(O=e.start.requestId,U=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!c){let r=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}},i;try{i=await ct(r)}catch(P){if(!e.run&&P instanceof l&&(P.status===void 0||P.status>=500))return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:_.purchases,error:$(P)});throw P}let s=ee(Ke,i);if(s.customerId!==E||s.scope.projectId!==m.scope.projectId||s.scope.environment!==m.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(s.outcome==="unknown"){if(!t&&Oe(e)){let P=e.start.requestId;if(!await w.update(G=>G&&G.start.requestId===P&&Oe(G)?null:G))return C({mode:"idle",status:"idle",actions:["start"],purchases:[]})}return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:_.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}})}ge(e,s);let d=await w.update(P=>(g(P),{...P,run:{id:s.target.runId,versionId:s.target.versionId,status:s.target.status,revision:s.view?.revision??P.run?.revision??0,runExpiresAt:s.target.runExpiresAt}}));if(g(d),e=d,s.access.type==="operation_only")return Pe(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Fe(e);let p=s.view;if(p.locale!==e.start.locale||!Je(p.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");let I=e.start.requestId,f=st(()=>q),q=Ye({...m,customerRun:{runId:s.target.runId,customerId:E,startRequestId:I},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(P=>m.executionPolicy.allowed.includes(P))},funnelCommandStorage:ut(I,f),onAcceptedResponse:P=>it(P,I,f)},{scope:s.scope,run:p});c=q}try{let r=a&&k?.controller===c?performance.now()-k.at:1/0;(r>=It||c.pendingCommands?.length||(c.viewAgeMs??0)<r)&&(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(),y();let i=(await w.read()).entry;return g(i),C(N(i,"run"))}catch(r){if(y(),n&&r instanceof l&&(r.status===401||r.status===409&&r.reason==="STATE_CHANGED")){c.reset(),c=null;let i=(await w.read()).entry;return g(i),se(i,!1,!1,!1)}throw r}}function T(e,t="read",n){if(y(),x)return t==="read"||t===ne?x:x.then(()=>T(e,t,n),()=>T(e,t,n));clearTimeout(re);let a=e().catch(r=>{throw!S&&!n?.(r)&&C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:_.purchases,error:$(r)}),r});return x=a,ne=t,a.then(()=>{x===a&&(x=void 0,ne=void 0)},()=>{x===a&&(x=void 0,ne=void 0)}),a}function Q(e){let t=e?.reuseRecentRead===!0;return T(async()=>{let{entry:n}=await w.read();if(!n||j(n)){if(await ye(!1)==="blocked")return ke();({entry:n}=await w.read())}return n?(O&&n.start.requestId!==O&&(c?.reset(),c=null,v.clear(),D.clear(),A=!1),A&&O===n.start.requestId?Pe(n,_.error):se(n,!1,!0,t)):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function ke(){return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:$(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function Ae(){let e=await Q();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:T(async()=>{let t=(await w.read()).entry;if(g(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&&!(B(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return C(N(t,"run"));if(c.pendingCommands?.length)await c.retry();else{let f=c.view;await c.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:f.nodeId,visit:f.visit,revision:f.revision,input:{type:"paywall_confirm",operationId:f.paywall.quote.operationId,...f.paywall.quote.merchantTerms?{merchantConfirmation:Re(f.paywall.quote.merchantTerms)}:{}}})}let I=(await w.read()).entry;return g(I),C(N(I,"run"))}let n=t.operationCommand?.operationId??_.confirmation?.operationId,a=n&&v.get(n);if(!n||!a||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");Z({allowed:t.allowed.filter(p=>m.executionPolicy.allowed.includes(p))},a.quote),await w.update(p=>{if(g(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 r={operationId:n,intent:"confirm",...a.quote?.merchantTerms?{merchantConfirmation:Re(a.quote.merchantTerms)}:{}},i=B(a)?await ae.update(r):await ae.attach(r),s=le.parse(i.operation);if(y(),i.operation.operationId!==n)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");v.set(n,pe(a,s));let d=(await w.read()).entry;return g(d),C(N(await L(d,!1,new Set([n])),"operation"))},"confirm")}function pt(e){let t=e?.quote;return t&&X(t)&&t.timing==="immediate"&&t.execution.provider==="merchant"&&(e.confirmedAt||e.merchantExecution)?t:null}function Ne(){if(_.mode!=="operation"||_.status==="blocked")return null;let e=_.purchases.filter(({type:n})=>n!=="complete"&&n!=="native"),t=e.length===1&&e[0]?.operationId;return t?pt(v.get(t)):null}async function je(){y();let{entry:e}=await w.read();return e?j(e)||z(e)?"finished":"pending":"none"}return{get controller(){return c},get recovery(){return structuredClone(_)},get attempt(){return y(),structuredClone(U)},get identitySignal(){return he.signal},get customerId(){return E},retained:je,async pendingFunnel(){y();let{entry:e}=await w.read();return e&&!j(e)&&!z(e)?e.start.funnelId:null},get paywallCopies(){return ot},async findPurchase(){let e=await je();if(e==="pending")return e;let t=await ye(!0);return y(),t==="none"?e:t},async readPaywall(e){y();let t=Ue(e),[n,{readPaywallContent:a},{validateResourceCheck:r}]=await Promise.all([xe(K.request,"resolvePaywall"),import("./paywall-content-EGRO37Y2.js"),import("./check-response-XGOTG3KL.js")]);y();let i=n.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),s=await De(K.request,n,i);r(i,s.paywall.check,s.scope);let d=await a(m,s.paywall);if(y(),t.paywallVersionId?d.id!==t.paywallVersionId:d.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return d},get canRestoreUpgradePaywall(){return Ne()!==null},recoverUpgradePaywall(){let e=Ne();return e?this.recoverPurchasePaywall(void 0,e.operationId):Promise.resolve(null)},async recoverPurchasePaywall(e,t){if(_.mode!=="operation"||_.status==="blocked")return null;let{entry:n}=await w.read();if(!n?.run)return null;g(n);let a=b(n),r=a.filter(F=>!F.terminal),i=a.filter(F=>F.terminal==="complete"),s=r.length===1?r[0]:r.length?void 0:i.find(F=>e&&e.runId===n.run?.id&&F.receiptId===e.receiptId)??(i.length===1?i[0]:void 0);if(!s||t&&s.operationId!==t)return null;let d=e?.runId===n.run.id&&e.receiptId===s.receiptId?e.view:void 0,p;try{p=await V(n,s,"recover_purchase",!0)}catch(F){if(!(F instanceof l&&F.status===400&&F.code==="INVALID_REQUEST"))throw F;if(!d)return null;p=await V(n,s)}let I=p.quote;if(!I||X(I)&&(I.timing!=="immediate"||I.execution.provider!=="merchant")||!(p.confirmedAt||p.merchantExecution||p.checkoutUrl||H(p)==="complete"))return null;H(p)!=="complete"&&Z({allowed:n.allowed.filter(F=>m.executionPolicy.allowed.includes(F))},I);let f=be.get(s.operationId),q=n.start.parameters?.commerce,P=n.start.locale??"en",ue=d;if(f){if(typeof q!="object"||!q||!("provider"in q)||typeof q.provider!="string"||!("currency"in q)||typeof q.currency!="string")return null;ue=await this.readPaywall({paywallVersionId:f,locale:P,commerce:{provider:q.provider,currency:q.currency,...X(I)?{intent:"subscription_change"}:{}}})}if(!ue)return null;y();let G=ue,ve=!1,Ce=async()=>{throw new l("PURCHASE_PENDING","Only the original purchase can be recovered")};return{signal:he.signal,view:G,quote:I,locale:P,get operation(){return p},get canReselect(){return D.get(s.operationId)===!0},async refresh(){return G},preview:Ce,confirm:Ce,cancel:Ce,async read(){if(ve)throw new DOMException("Purchase view closed","AbortError");p=await V(n,s);let F=await L(n,!1,new Set([s.operationId]));return ve||C(N(F,"operation")),structuredClone(p)},destroy(){ve=!0}}},start(e){let t=J.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 T(async()=>{let n=(await w.read()).entry;if((!n||j(n)||z(n))&&await ye(!0)==="blocked")return ke();let a=await w.update(r=>{if(r&&!j(r)&&!(z(r)&&r.start.requestId!==t.requestId)){if(r.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return r}return{schemaVersion:1,baseUrl:w.baseUrl,scope:m.scope,customerId:E,sessionId:te,start:t,allowed:[...m.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!a)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return O!==a.start.requestId&&(c?.reset(),c=null,v.clear(),D.clear(),A=!1),A?Pe(a,_.error):se(a,!0,!0,!0)},`start:${t.funnelId}`)},refresh:Q,confirm:Ae,retry:()=>A?Ae():T(async()=>{let{entry:e}=await w.read();return e?se(e,!0):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return c?.view?T(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 t&&t.start.requestId!==O?C({mode:"idle",status:"idle",actions:["start"],purchases:[]}):(g(t),C(N(t,"run")))},"close"):Q()},async continueCheckout(e,t){let n=t?await T(async()=>{let{entry:a}=await w.read();if(g(a),!a.run||!b(a).some(i=>i.operationId===t&&!i.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let r=await L(a);return C(N(r,A?"operation":"run"))},`continue:${t}`,a=>a instanceof l&&a.code==="PURCHASE_PENDING"):await Q();y(),await e(yt(n,t))},async terminateCheckout(e){let t=n=>n.actions.includes("continue_checkout")&&n.purchases.some(a=>a.type==="checkout"&&a.operationId===e);if(!t(_)&&!t(await Q()))throw new l("PURCHASE_PENDING","The original Checkout has changed");return T(async()=>{let{entry:n}=await w.read();g(n);let a=b(n).find(i=>i.operationId===e&&!i.terminal);if(!a||!n.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await V(n,a,"terminate_checkout");let r=await L(n,!1,new Set([e]));return C(N(r,A?"operation":"run"))},`terminate:${e}`,n=>n instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(n.code))},subscribe(e){return oe.add(e),()=>{oe.delete(e)}},destroy:_e}}export{et as a,yt as b,Wt as c};