@tinkerlandai/longplay-sdk 0.10.53 → 0.10.54

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 (48) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/chunk-66TY4EFN.js +1 -0
  3. package/dist/chunk-AEQUKR4O.js +1 -0
  4. package/dist/chunk-C4NXQMSO.js +1 -0
  5. package/dist/chunk-JCI5PGY3.js +1 -0
  6. package/dist/{chunk-JCOSQTFG.js → chunk-LBDLWHBY.js} +1 -1
  7. package/dist/{chunk-VSARBT7T.js → chunk-LFMAFY3P.js} +1 -1
  8. package/dist/chunk-MRL7XUBV.js +1 -0
  9. package/dist/{chunk-WTPS62L7.js → chunk-MZRDAMFQ.js} +1 -1
  10. package/dist/chunk-OJDO7546.js +1 -0
  11. package/dist/{chunk-RYZBE5FQ.js → chunk-PB34FLPJ.js} +1 -1
  12. package/dist/{chunk-PCSCRMPD.js → chunk-PPXVRQAG.js} +1 -1
  13. package/dist/{chunk-PSAAZJZA.js → chunk-R2L227PQ.js} +1 -1
  14. package/dist/{chunk-3CKAOP4L.js → chunk-S2MSRPR2.js} +1 -1
  15. package/dist/{chunk-QRBZYLE4.js → chunk-SK5JZ7HA.js} +2 -2
  16. package/dist/{chunk-DX33T5JM.js → chunk-TS26DZNO.js} +1 -1
  17. package/dist/chunk-ZEU56NVY.js +1 -0
  18. package/dist/{chunk-UYKPVE5Y.js → chunk-ZQY7OYHM.js} +1 -1
  19. package/dist/{content-NZHXCUXY.js → content-A4SPKH7N.js} +1 -1
  20. package/dist/funnel-host-purchase-V2TIWGCQ.js +1 -0
  21. package/dist/funnel-host-recovery-paywall-DWKTPDLY.js +1 -0
  22. package/dist/{funnel-local-client-bKBuUwkG.d.ts → funnel-local-client-Fxsyl7rh.d.ts} +75 -75
  23. package/dist/{funnel-paywall-prerender-I5IMXZ3D.js → funnel-paywall-prerender-DD7LQXDJ.js} +1 -1
  24. package/dist/{funnel-process-client-ABZkQ8sZ.d.ts → funnel-process-client-D9saqPse.d.ts} +1 -1
  25. package/dist/funnel-runtime-host-JG3OAYZ6.js +1 -0
  26. package/dist/index.d.ts +88 -82
  27. package/dist/index.js +1 -1
  28. package/dist/native-shell.js +1 -1
  29. package/dist/openrouter.js +1 -1
  30. package/dist/page.js +1 -1
  31. package/dist/{paywall-4YXZP2TO.js → paywall-NM4HMYMK.js} +1 -1
  32. package/dist/{paywall-content-IDET7P7K.js → paywall-content-T2FGNRBR.js} +1 -1
  33. package/dist/{paywall-session-6R4UYJJF.js → paywall-session-BAUWSWWR.js} +1 -1
  34. package/dist/react-native.d.ts +4 -4
  35. package/dist/react-native.js +1 -1
  36. package/dist/server.d.ts +2 -2
  37. package/dist/server.js +1 -1
  38. package/dist/visual.js +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-3JF2REGQ.js +0 -1
  41. package/dist/chunk-45XVSI2M.js +0 -1
  42. package/dist/chunk-DXQJ2JQZ.js +0 -1
  43. package/dist/chunk-SM44S6BK.js +0 -1
  44. package/dist/chunk-Y2B7RDRB.js +0 -1
  45. package/dist/funnel-host-purchase-CVJC5MYJ.js +0 -1
  46. package/dist/funnel-host-recovery-paywall-Q56M2FYK.js +0 -1
  47. package/dist/funnel-runtime-host-OVSFAGO5.js +0 -1
  48. /package/dist/{chunk-QRBZYLE4.js.LEGAL.txt → chunk-SK5JZ7HA.js.LEGAL.txt} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.54
4
+
5
+ - Keep the original Paywall open while switching from an unpaid merchant upgrade. Quote the selected plan only after the original is confirmed closed and unpaid.
6
+ - Restore the original payment link and checkout state after its Funnel Run expires. When an old payment has already succeeded, show that result in the same Paywall.
7
+
8
+ ## 0.10.53
9
+
10
+ - Restore the original plan and payment controls in the merchant's existing Paywall when the Funnel Run can no longer be rendered.
11
+
3
12
  ## 0.10.52
4
13
 
5
14
  - Keep confirming an immediate upgrade in the published Paywall. Reads follow the original operation until it completes, requires payment or returns a definitive failure.
@@ -0,0 +1 @@
1
+ import{a as L}from"./chunk-W32FI2A2.js";import{b as q,e as A}from"./chunk-SLUA7ABW.js";import{d as N}from"./chunk-R2L227PQ.js";import{a as g}from"./chunk-DSPLGTQI.js";import{b as J}from"./chunk-HMJTABQ5.js";function _(n){if(!n.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let $=n.client.pageExperiments.bind(n.client),r=!1,o=!1,i=0,y=!1,w=!1,h="",E=()=>{let e=n.client.view;return JSON.stringify([e?.id,e?.source.versionId,e?.visit,e?.revision,e?.status,e?.stopped])},s=new Map,b=new Set,O={},c=new Map,U=q(n.appManifestRelease),M=()=>{for(let e of s.values())e.effect.revert();s.clear()},u=()=>{M();for(let e of c.values())e();c.clear()};function x(e){if(r||b.has(e))return;b.add(e);let p=i;$(n.appManifestRelease,[e]).catch(R=>{b.delete(e),!r&&p===i&&g(n.onError,R)})}async function d(){if(r)return;h=E();let e=n.client.view;if(!e||e.stopped||!["running","waiting"].includes(e.status)){i++,u();return}if(document.visibilityState==="hidden")return;if(y){w=!0;return}y=!0;let p=++i,R=`${e.id}:${e.visit}:${e.revision}`,j=location.href;try{let[m,{applyVisualVariation:z}]=await Promise.all([$(n.appManifestRelease),import("./visual-dom-MH3JDJHJ.js")]),l=n.client.view;if(r||p!==i||!l||l.stopped||!["running","waiting"].includes(l.status)||`${l.id}:${l.visit}:${l.revision}`!==R||location.href!==j)return;let I=new Set,K=new Set;for(let t of m.assignments){let a=`${m.payload.environmentId}:${t.experimentKey}`;if(K.add(a),c.has(a)||c.set(a,A(a,O)),!!t.inExperiment)for(let f of m.payload.experiments){if(f.key!==t.experimentKey||!J(location.href,f.urlPatterns??[]))continue;let B=f.meta?.findIndex(k=>k.key===t.variationKey)??-1,V=f.variations[B];if(!V?.renderGuard)continue;let v=t.receiptId+":"+f.changeId,P=JSON.stringify([t.variationKey,V]);I.add(v);let F=s.get(v);if(F?.signature===P){F.effect.applied&&x(t.receiptId);continue}s.get(v)?.effect.revert(),s.delete(v);let T=z(V,{requireUniqueTargets:!0,boundVariations:f.variations,allowJs:!1,onApplied:()=>x(t.receiptId),onError:k=>g(n.onError,k)});s.set(v,{signature:P,effect:T}),T.applied&&x(t.receiptId)}}for(let[t,a]of s)I.has(t)||(a.effect.revert(),s.delete(t));for(let[t,a]of c)K.has(t)||(a(),c.delete(t))}catch(m){p===i&&u(),!r&&p===i&&g(n.onError,m)}finally{y=!1,w&&!r&&(w=!1,d())}}let G=n.client.subscribe(()=>{if(E()===h)return;h=E(),i++;let e=n.client.view;(!e||e.stopped||!["running","waiting"].includes(e.status))&&u(),o&&d()}),H=N(()=>{i++,u(),o&&d()}),S=()=>{i++,M()};document.addEventListener("visibilitychange",S);let C=L({document,run:async()=>{o&&await d()},delay:()=>o&&!r?15e3:void 0});return{async start(){o||r||(o=!0,await C.refresh())},refresh:d,destroy(){r=!0,i++,C.destroy(),document.removeEventListener("visibilitychange",S),G(),H(),u(),U.destroy()}}}export{_ as a};
@@ -0,0 +1 @@
1
+ var r=new WeakMap;function y(e){let n=e.view,t=n?.paywall?.resolution;if(!n||!["running","waiting"].includes(n.status)||n.stopped||!t||"document"in t||!e.resolvePaywall||e.identitySignal?.aborted)return;let o=JSON.stringify(t);if(r.get(e)?.key===o)return;let i=JSON.parse(o),a=e.identitySignal,l=Promise.resolve().then(async()=>{a?.throwIfAborted();let u=await e.resolvePaywall(i);return a?.throwIfAborted(),u}),s={key:o,content:l};return r.set(e,s),l.catch(()=>{}),()=>{r.get(e)===s&&r.delete(e)}}function p(e,n){let t=r.get(e);return r.delete(e),t?.key===JSON.stringify(n)?t.content:e.resolvePaywall(n)}export{y as a,p as b};
@@ -0,0 +1 @@
1
+ import{b as B}from"./chunk-AEQUKR4O.js";import{K as L}from"./chunk-BX2MSRA4.js";import{a as Y}from"./chunk-ADTZEBQF.js";import{c as W,e as X,f as Z,g as $,h as ee,i as te}from"./chunk-OV46DXRX.js";import{b as J}from"./chunk-M4P6TGBU.js";import{B as V}from"./chunk-GGZG56GR.js";import{x as H}from"./chunk-NL7AXMUA.js";import{t as z}from"./chunk-QGKROSRD.js";import{a as u}from"./chunk-WE55LJEN.js";import{a as K}from"./chunk-DSPLGTQI.js";async function ye(r){let{session:m,load:d}=ie(r);try{return await d(),m}catch(h){throw m.destroy(),h}}function ie(r){let m=r.view;if(!m?.paywall)throw new u("INVALID_REQUEST","The current node is not a Paywall");let d=m.paywall.receiptId,h=m.nodeId,E=m.visit,R=m.paywall.resolution,n=m.paywall,N="document"in R?{document:R.document,offering:R.offering,capabilities:R.capabilities}:null;function D(){let e=n.resolution;return"document"in e?e:N&&{...e,document:N.document,offering:N.offering,capabilities:W(e.capabilities,N.capabilities)}}function F(e){if(!X(e,R))throw new u("INVALID_RESPONSE","The pinned Paywall binding changed")}let p=!1,A=new Set,_=null;function G(){let e=D();if(e&&!p)for(let o of A)K(o,structuredClone(e))}async function M(){b();let e=D();if(e)return structuredClone(e);if(!_){let o=(async()=>{if("document"in n.resolution||!r.resolvePaywall)throw new u("INVALID_RESPONSE","Public Paywall reader is unavailable");let s=await B(r,n.resolution);return b(),F(s),N={document:s.document,offering:s.offering,capabilities:s.capabilities},G(),D()})();_=o;let t=()=>{_===o&&(_=null)};o.then(t,t)}return _.then(o=>structuredClone(o))}let q=new AbortController,f=(r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])).find(e=>e.operation==="submit"&&e.nodeId===h&&e.visit===E&&e.input.type==="paywall_quote")?.requestId??m.paywall.purchaseRequestId,C=0,g=null,T=new Set,I=null,v=new Map;function U(e){if(e.purchase&&e.purchase.receiptId!==d)throw new u("INVALID_RESPONSE","Purchase receipt changed");let o=e.run.paywall;return e.purchase??(o?.receiptId===d?o:null)}function b(){if(p)throw new u("IDENTITY_CHANGED","Paywall presentation has closed")}function S(e,o,t){if(b(),o!==C||t!==void 0&&n.quote?.operationId!==t)return!1;let s=n.selectionGeneration??0,i=e.run.paywall;if(i?.receiptId===d){if((i.selectionGeneration??0)<(n.selectionGeneration??0))return!1;F(i.resolution)}let a=U(e),c=i?.receiptId===d&&(i.selectionGeneration??0)>s,l=c?a?.quote??null:a?.quote??n.quote,y=a?.operation??(l?.operationId===n.quote?.operationId?n.operation:null);return n.quote&&l&&ee(n.quote,l),l&&y&&Z(y,{operationId:l.operationId,membershipId:V(l)?l.membershipId:null,...V(l)?{featureQuantities:l.featureQuantities??{}}:{}},"Purchase operation changed"),(c||l?.operationId!==n.quote?.operationId)&&(C++,i?.receiptId===d&&(f=i.purchaseRequestId)),i?.canReselect===!0&&i.purchaseRequestId===I&&!(r.pendingCommands??[r.pendingCommand]).some(w=>w?.requestId===I)&&(I=null),n={...n,...i?.receiptId===d?i:{},...t!==void 0&&!c&&a?.canReselect!==void 0?{canReselect:a.canReselect}:{},quote:l,operation:te(n.operation,y,!0)},G(),!0}function O(e,o,t){return new Promise((s,i)=>{let a=!1,c=()=>{clearTimeout(P),q.signal.removeEventListener("abort",w)},l=Q=>{a||(a=!0,c(),s(Q))},y=Q=>{a||(a=!0,c(),i(Q))},w=()=>y(new u("IDENTITY_CHANGED","Paywall presentation has closed")),P=setTimeout(()=>y(new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t)),Math.max(0,o-Date.now()));q.signal.addEventListener("abort",w,{once:!0}),q.signal.aborted&&w(),e.then(l,y)})}function ne(e){return new Promise(o=>{let t=()=>{clearTimeout(s),q.signal.removeEventListener("abort",t),o()},s=setTimeout(t,e);q.signal.addEventListener("abort",t,{once:!0}),q.signal.aborted&&t()})}function j(e,o){b();let t=v.get(e)??r.pendingCommands?.find(a=>a.requestId===e)??r.pendingCommand;if(t?.operation==="submit"&&t.requestId===e&&t.nodeId===h&&t.visit===E){o.type==="paywall_quote"&&t.input.type==="paywall_quote"&&t.input.predecessor&&!o.predecessor&&(o={...o,predecessor:t.input.predecessor});let a=L.parse(t),c=L.parse({...t,input:o});if(a.operation!=="submit"||c.operation!=="submit"||JSON.stringify(a.input)!==JSON.stringify(c.input))throw new u("CONFLICT","A purchase request cannot change its input");return v.set(e,a),a}let s=r.view;if(!s||s.nodeId!==h||s.visit!==E||s.paywall?.receiptId!==d)throw new u("PRECONDITION_FAILED","The Paywall visit has changed");let i=L.parse({operation:"submit",requestId:e,nodeId:h,visit:E,revision:s.revision,input:structuredClone(o)});if(i.operation!=="submit")throw new u("INVALID_REQUEST","A purchase submission is required");return v.set(e,i),i}async function x(e,o){b();let{requestId:t,input:s}=e,i=Date.now()+3e4;T.add(t);try{let a=await O(r.submit(e),i,t);for(;a.run.pendingRequest?.requestId===t&&Date.now()<i&&!p&&(await ne(Math.min(1e3,i-Date.now())),!(p||Date.now()>=i));)a=await O(r.resume(t),i,t);if(p)throw new u("IDENTITY_CHANGED","Paywall presentation has closed");if(a.run.pendingRequest?.requestId===t)throw new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t);if(!S(a,o,s.type==="paywall_confirm"||s.type==="paywall_cancel"?s.operationId:void 0))throw new u("PRECONDITION_FAILED","The purchase selection has changed");I===t&&(I=null)}catch(a){if(I=t,s.type==="paywall_quote"&&r.settle&&!p&&a instanceof u&&a.status!==void 0&&![401,425].includes(a.status)&&!a.retryable&&a.recovery!=="recover_operation")try{if((await O(r.settle(t),i,t)).settlement?.state==="settled"){let l=await O(r.get(),i,t);S(l,o)&&l.run.paywall?.purchaseRequestId===t&&n.canReselect===!0&&v.delete(t)}}catch{}throw a instanceof u&&a.code==="COMMAND_PENDING"&&a.status===void 0&&v.delete(t),a}finally{T.delete(t)}}async function k(e){if(!n.quote)throw new u("INVALID_REQUEST","A quoted purchase is required");let o=e==="confirm"?"paywall_confirm":"paywall_cancel",t=[...v.values(),...r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])].find(i=>i.operation==="submit"&&i.input.type===o&&"operationId"in i.input&&i.input.operationId===n.quote.operationId),s=t?.operation==="submit"&&t.input.type===o&&"operationId"in t.input&&t.input.operationId===n.quote.operationId?t.requestId:crypto.randomUUID();if(await x(j(s,{type:e==="confirm"?"paywall_confirm":"paywall_cancel",operationId:n.quote.operationId,...e==="confirm"&&n.quote.merchantTerms?{merchantConfirmation:H(n.quote.merchantTerms)}:{}}),C),!n.operation)throw new u("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(n.operation)}let oe={get view(){return structuredClone(D())},get quote(){return n.quote?structuredClone(n.quote):null},get operation(){return n.operation?structuredClone(n.operation):null},get webViewUrl(){return r.webViewUrl},get locale(){return r.view?.locale??m.locale},get canReselect(){return n.canReselect===!0&&I===null},get recovery(){let e=r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[]),o=r.pendingPurchase;if(o&&(o.receiptId!==d||o.operationId!==n.quote?.operationId))return{type:"recover",operationId:o.operationId,requestId:e[0]?.requestId??null};let t=Y({quote:n.quote,operation:n.operation,requestId:e[0]?.requestId??I??f,pending:T.size>0||e.length>0||I!==null,destroyed:p,canReselect:n.canReselect});return t.type==="recover"&&t.requestId===null&&!p&&r.hasDurableJournal===!0&&!n.quote&&!n.operation&&(n.selectionGeneration??0)===0&&!o&&!e.length&&!T.size&&!f?{type:"native",operationId:null}:t},get pendingCancellation(){return!p&&(r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])).some(e=>e.operation==="submit"&&e.nodeId===h&&e.visit===E&&e.input.type==="paywall_cancel"&&e.input.operationId===n.quote?.operationId)},subscribe(e){return p?()=>{}:(A.add(e),()=>A.delete(e))},async refresh(){b();let e=C,o=await r.get();if(S(o,e),o.run.paywall?.receiptId!==d)throw new u("PRECONDITION_FAILED","Paywall presentation has changed");return M()},preview(e){let o=D();if(!o)return Promise.reject(new u("PRECONDITION_FAILED","Load the Paywall presentation first"));if(f&&f!==e.requestId&&(g||n.canReselect!==!0))return Promise.reject(new u("COMMAND_PENDING","Retry the original purchase before starting another"));let t=o.document.buttons[e.actionId],s=t?.type==="checkout"?J(t.product,e.selection,o.capabilities):null;if(!s)return Promise.reject(new u("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let i=z(o.document.screen,s,e.selection,o.capabilities),a=f!==e.requestId&&(n.selectionGeneration??0)>0?{operationId:n.quote?.operationId??null,generation:n.selectionGeneration??0}:void 0,c=r.view?.parameters.commerce;if(c&&typeof c=="object"&&!Array.isArray(c)&&c.intent==="subscription_change"&&!e.subscriptionChange)return Promise.reject(new u("INVALID_REQUEST","Choose the existing membership for this subscription change"));if(e.subscriptionChange&&e.nativeOffer)return Promise.reject(new u("INVALID_REQUEST","A web membership change cannot include a store offer"));if(a&&n.canReselect!==!0)return Promise.reject(new u("COMMAND_PENDING","Original purchase requires authoritative termination"));let l;try{l=j(e.requestId,{type:"paywall_quote",actionId:e.actionId,productVersionId:s,...Object.keys(i).length?{featureQuantities:i}:{},...a?{predecessor:a}:{},...e.offerId?{offerId:e.offerId}:{},...e.nativeOffer?{nativeOffer:e.nativeOffer}:{},...e.subscriptionChange?{subscriptionChange:e.subscriptionChange}:{}})}catch(P){return Promise.reject(P)}if(f===e.requestId&&g)return g;f!==e.requestId&&C++;let y=C;f=e.requestId;let w=(async()=>{if(await x(l,y),!n.quote)throw new u("INVALID_RESPONSE","The accepted quote is missing");return $(n.quote,{productVersionId:s,featureQuantities:i,subscriptionChange:e.subscriptionChange},"The selected purchase changed"),structuredClone(n.quote)})();return g=w,w.then(()=>{g===w&&(g=null)},P=>{g===w&&(g=null),f===e.requestId&&r.pendingCommand?.requestId!==e.requestId&&P instanceof u&&P.status!==void 0&&P.status<500&&![401,425].includes(P.status)&&(f=null)}),w},confirm:()=>k("confirm"),cancel:()=>k("cancel"),async read(){if(b(),!n.quote)throw new u("INVALID_REQUEST","A quoted purchase is required");let e=n.quote.operationId,o=C,t=r.pendingCommands?.find(l=>l.operation==="submit"&&(l.input.type==="paywall_confirm"||l.input.type==="paywall_cancel")&&l.input.operationId===e)??r.pendingCommand;t?.operation==="submit"&&(t.input.type==="paywall_confirm"||t.input.type==="paywall_cancel")&&t.input.operationId===e&&await r.settle?.(t.requestId);let s=await r.get(void 0,{receiptId:d,operationId:e});b();let i=U(s);if(i?.quote&&i.quote.operationId!==e||i?.operation&&i.operation.operationId!==e)throw new u("INVALID_RESPONSE","Purchase operation changed");let a=S(s,o,e),c=a?n.operation:i?.operation;if(!c)throw new u("INVALID_RESPONSE","The current purchase result is missing");return a&&T.size===0&&!(r.pendingCommands?.length??(r.pendingCommand?1:0))&&(I=null),structuredClone(c)},destroy(){p=!0,re(),A.clear(),q.abort(),v.clear()}},re=r.subscribe(e=>{p||e.nodeId!==h||e.visit!==E||e.paywall?.receiptId!==d||(e.paywall.selectionGeneration??0)<(n.selectionGeneration??0)||(F(e.paywall.resolution),n={...n,resolution:e.paywall.resolution},G())});return{session:oe,load:M}}export{ye as a};
@@ -0,0 +1 @@
1
+ import{b as xe}from"./chunk-PVMGYRGE.js";import{a as K}from"./chunk-36VNAOG6.js";import{D as J,F as Ge,c as Ne,e as M,j as je,u as De,v as Ve,x as He,z as Le}from"./chunk-MZRDAMFQ.js";import{a as qe,b as Ae,c as Fe}from"./chunk-CAE4KIZN.js";import{K as G}from"./chunk-BX2MSRA4.js";import{a as ie}from"./chunk-ADTZEBQF.js";import{i as se}from"./chunk-OV46DXRX.js";import{A as oe,B as ae,C as Y,E as ke}from"./chunk-GGZG56GR.js";import{x as we}from"./chunk-NL7AXMUA.js";import{b as Ue}from"./chunk-TS26DZNO.js";import{a as l}from"./chunk-WE55LJEN.js";import{h as re}from"./chunk-OZK47BUU.js";import{b as Te}from"./chunk-LBDLWHBY.js";import{b as r}from"./chunk-5YBTU4KS.js";import{a as ye}from"./chunk-DSPLGTQI.js";var P=G.options,nt=r.discriminatedUnion("operation",[P[1].omit({customerToken:!0}),P[2].omit({customerToken:!0}),P[3].omit({customerToken:!0}),P[4].omit({customerToken:!0}),P[5].omit({customerToken:!0}),P[6].omit({customerToken:!0}),P[7].omit({customerToken:!0}),P[8].omit({customerToken:!0}),je.omit({customerToken:!0})]),ge=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),pt=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("find_purchase")}),r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume","start"]),start:r.strictObject({requestId:P[0].shape.requestId,funnelId:P[0].shape.funnelId,locale:P[0].shape.locale,parameters:P[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:ge,includePaywallVersion:r.literal(!0).optional()}),r.strictObject({operation:r.literal("terminate_checkout"),runId:r.uuid(),funnelId:r.uuid(),purchase:ge}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[P[3].omit({customerToken:!0}),P[4].omit({customerToken:!0}),P[5].omit({customerToken:!0}),P[6].omit({customerToken:!0}),P[7].omit({customerToken:!0})]).optional()}).refine(a=>!a.command||a.requestId===a.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:nt})]),ue=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:M.shape.run.shape.status}),V={scope:re,customerId:r.uuid()},Me=r.discriminatedUnion("outcome",[r.strictObject({...V,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...V,outcome:r.literal("resolved"),target:ue,view:M.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((a,p)=>{a.outcome==="resolved"&&(a.access.type==="customer"!=(a.view!==null)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&p.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),ze=r.strictObject({...V,target:ue,view:M.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:M.shape.purchase.unwrap().nullable()}).superRefine((a,p)=>{let f=a.settlement;(f.acceptance==="accepted"!=(f.receiptPhase!==null)||f.acceptance==="accepted"&&f.basis!=="receipt"||f.acceptance==="unknown"&&(f.state!=="unknown"||f.basis!=="none")||f.acceptance!=="accepted"&&(f.operationId!==null||f.receiptId!==null)||f.acceptance==="not_accepted"&&(f.state!=="settled"||!["run_terminal","position_advanced"].includes(f.basis))||a.purchase&&(a.purchase.receiptId!==f.receiptId||a.purchase.operation&&a.purchase.operation.operationId!==f.operationId||a.purchase.quote&&a.purchase.quote.operationId!==f.operationId)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&p.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Qe=r.strictObject({...V,target:ue,purchase:M.shape.purchase.unwrap(),paywallVersionId:r.uuid().optional()}).superRefine((a,p)=>{(!a.purchase.operation||typeof a.purchase.canReselect!="boolean"||a.purchase.quote&&a.purchase.quote.operationId!==a.purchase.operation.operationId)&&p.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),Be=r.discriminatedUnion("outcome",[r.strictObject({...V,outcome:r.literal("none")}),r.strictObject({...V,outcome:r.literal("blocked")}),r.strictObject({...V,outcome:r.literal("found"),target:ue,start:r.strictObject({locale:P[0].shape.locale,parameters:P[0].shape.parameters}),purchase:ge})]);var rt=G.options[0].refine(a=>!a.customer&&!a.customerData),ot=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),Ye=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:re,customerId:r.uuid(),sessionId:r.uuid(),start:rt,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:Ne.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ot).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:De.nullable()})});function Je(a){return He({...a,namespace:"purchases",identity:[a.scope.projectId,a.scope.environment,a.customerId]})}function Ke(a){let p=new URL(a.baseUrl??Te).href,f=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function S(){a.assertCurrent();try{let C=await a.storage.read();if(a.assertCurrent(),!Number.isSafeInteger(C.revision)||C.revision<0)throw f();let u=C.entry===null?null:Ye.parse(C.entry);if(u&&(u.baseUrl!==p||u.customerId!==a.customerId||u.scope.projectId!==a.scope.projectId||u.scope.environment!==a.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(u?.journal.entry&&(u.journal.entry.scope.projectId!==u.scope.projectId||u.journal.entry.scope.environment!==u.scope.environment||u.journal.entry.funnelId!==u.start.funnelId||u.journal.entry.runId!==u.run?.id||u.journal.entry.versionId!==u.run?.versionId)||u?.operationCommand&&!u.purchases.some(_=>_.operationId===u.operationCommand?.operationId))throw f();return{revision:C.revision,entry:u}}catch(C){throw C instanceof l?C:f()}}async function $(C){for(let u=0;u<8;u++){let _=await S(),F=C(structuredClone(_.entry));if(JSON.stringify(F)===JSON.stringify(_.entry))return F;F&&Ye.parse(F),a.assertCurrent();let E;try{E=await a.storage.write(_.revision,F)}catch{throw f()}if(a.assertCurrent(),E!==null){if(!Number.isSafeInteger(E)||E<=_.revision)throw f();return F}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:S,update:$,baseUrl:p}}var at=5*6e4;function it(a,p){let f=a.purchases.find(S=>S.type==="checkout");if(!a.actions.includes("continue_checkout")||f?.type!=="checkout"||p!==void 0&&f.operationId!==p)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return f.checkoutUrl}function Vt(a){let p={...a,scope:{...a.scope},executionPolicy:structuredClone(a.executionPolicy)},f=p.session.snapshot();if(!f)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:S,sessionId:$}=f,C=!1,u=null,_,F=null,E=!1,j,W,X,b={mode:"idle",status:"idle",actions:["start"],purchases:[]},y=new Map,Pe=new Map,T=new Map,ce=new AbortController,Z=new Set,z=Ue(p),ee=xe(z.request);function Q(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 g(){if(C||p.session.snapshot()?.customerId!==S)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let h=Ke({...p,customerId:S,assertCurrent:g,storage:p.storage??Je({baseUrl:p.baseUrl,scope:p.scope,customerId:S})}),$e=p.session.subscribeIdentity(ve);function ve(){C||(C=!0,clearTimeout(X),ce.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),$e(),u?.reset(),u=null,F=null,z.dispose(),Z.clear(),y.clear(),T.clear())}function v(e){g();let t=JSON.stringify(e)!==JSON.stringify(b);b=e,clearTimeout(X),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(X=setTimeout(()=>{L().catch(()=>{})},5e3)),t&&ye(p.onRecovery,structuredClone(e));for(let n of t?Z:[]){if(C)break;ye(n,structuredClone(e))}return structuredClone(e)}function w(e){if(g(),!e||e.start.requestId!==_)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function k(e){let t=[...e.purchases],n=e.journal.entry?.purchase;return n&&!t.some(o=>o.operationId===n.operationId)&&t.push({receiptId:n.receiptId,operationId:n.operationId,terminal:null}),t}function U(e){let t=k(e),n=E&&t.length>0&&t.every(o=>o.terminal==="native"&&x(y.get(o.operationId))==="native")&&t.some(o=>{let i=y.get(o.operationId);return!!i&&Y(i)&&T.get(o.operationId)===!0});return e.run&&(n||!["running","waiting"].includes(e.run.status))&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&t.every(o=>o.terminal!==null)}function A(e,t){let n=e.journal.entry?.command??e.journal.entry?.closeCommand,o=k(e).map(I=>{let q=y.get(I.operationId);return I.terminal&&!q?{type:I.terminal,operationId:I.operationId}:ie({quote:q?.quote??null,operation:q??null,requestId:n?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(I.operationId)===!0})}),i=o.filter(I=>!["complete","native"].includes(I.type)),s=i[0],c=i.length===1&&s?.operationId?y.get(s.operationId):void 0;if(c&&(s?.type==="checkout"||s?.type==="cancel"))try{J({allowed:e.allowed.filter(I=>p.executionPolicy.allowed.includes(I))},c.quote)}catch(I){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:Q(I)}}let m;if(t==="operation"&&!n&&s?.type==="cancel"&&c?.quote&&!c.problem&&!c.confirmedAt)try{J({allowed:e.allowed.filter(I=>p.executionPolicy.allowed.includes(I))},c.quote),Date.parse(c.quote.expiresAt)>Date.now()&&(m={operationId:c.operationId,quote:c.quote})}catch{}let d=o.length>0&&i.length===0,R=U(e)||t==="operation"&&d&&!n&&!e.operationCommand?"complete":s?.type==="checkout"?"checkout":s?.type==="fulfillment"?"fulfillment":s?.type==="recording"?"recording":n||e.operationCommand||s&&s.type!=="cancel"||t==="operation"&&!m?"waiting_result":"ready";return{mode:t,status:R,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...U(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...i.length===1&&s?.type==="checkout"?["continue_checkout"]:[]]}}function x(e){let t=ie({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function le(e){if(!e.operation)return;let t=oe.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let n=se(y.get(t.operationId)??null,t);y.set(t.operationId,n),n===t&&T.set(t.operationId,e.canReselect===!0)}async function We(e){g();for(let n of[e.purchase,e.run.paywall])n&&le(n);let t=await h.update(n=>{if(w(n),n.run&&(n.run.id!==e.run.id||n.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=k(n);for(let i of[e.purchase,e.run.paywall]){let s=i?.operation?.operationId??i?.quote?.operationId;if(!i||!s)continue;let c=o.find(d=>d.operationId===s);if(c&&c.receiptId!==i.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=x(y.get(s));c?c.terminal??=m:o.push({receiptId:i.receiptId,operationId:s,terminal:m})}return{...n,purchases:o,run:n.run&&(n.run.revision>e.run.revision||!["running","waiting"].includes(n.run.status)&&["running","waiting"].includes(e.run.status))?n.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});w(t),t.run&&!["running","waiting"].includes(t.run.status)&&k(t).some(n=>!n.terminal)&&(t=await H(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(n=>!!n)))),w(t),v(A(t,"run"))}function Xe(){return{async read(){let{entry:e}=await h.read();return w(e),structuredClone(e.journal)},async write(e,t){let n=null;return await h.update(o=>{if(w(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return n=null,o.journal.revision!==e?o:(n=e+1,{...o,journal:{revision:n,entry:t}})}),n}}}async function H(e,t=!1,n=new Set){w(e);let o=k(e);for(let s of o){if(s.terminal)continue;let c=n.has(s.operationId)?y.get(s.operationId):void 0;if(c??=await D(e,s),g(),c.operationId!==s.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(c.merchantExecution&&c.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&ie({quote:c.quote??null,operation:c,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let m=Y(c)?await ee.update({operationId:s.operationId,intent:"cancel"}):await ee.attach({operationId:s.operationId,intent:"cancel"});if(c=oe.parse(m.operation),g(),c.operationId!==s.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");c=await D(e,s)}y.set(s.operationId,se(y.get(s.operationId)??null,c))}let i=await h.update(s=>{w(s);let c=s.operationCommand&&y.get(s.operationCommand.operationId);return{...s,...c&&(c.confirmedAt||c.merchantExecution||!ke(c))?{operationCommand:void 0}:{},purchases:k(s).map(m=>({...m,terminal:m.terminal??x(y.get(m.operationId))}))}});return w(i),i}async function B(e){g();let t=await z.request("funnels",e);return g(),t}async function Ze(e){try{return await B(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return B({...e,intent:"resume"})}}async function et(){let e=K(Be,await B({operation:"find_purchase"}));if(e.customerId!==S||e.scope.projectId!==p.scope.projectId||e.scope.environment!==p.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 h.update(o=>o&&!U(o)?o:{schemaVersion:1,baseUrl:h.baseUrl,scope:p.scope,customerId:S,sessionId:$,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...p.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 te;function de(e){let t=te;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<at))return t.job;let n={at:Date.now(),job:et().then(o=>(n.outcome=o,n.at=Date.now(),o),o=>{throw te===n&&(te=void 0),o})};return te=n,n.job}async function D(e,t,n="recover_purchase",o=!1){let i=K(Qe,await B({operation:n,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId},...o?{includePaywallVersion:!0}:{}}));if(pe(e,i),i.purchase.receiptId!==t.receiptId||i.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return le(i.purchase),o&&i.paywallVersionId&&Pe.set(t.operationId,i.paywallVersionId),y.get(t.operationId)}async function Se(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let n=K(ze,await B({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(pe(e,n),n.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");n.purchase&&le(n.purchase);let o=await h.update(i=>{w(i);let s=k(i),{receiptId:c,operationId:m}=n.settlement;if(c&&m){let R=s.find(I=>I.operationId===m);if(R&&R.receiptId!==c)throw new l("INVALID_RESPONSE","Original Receipt changed");R||s.push({receiptId:c,operationId:m,terminal:x(y.get(m))})}let d=n.settlement.state==="settled"?Ve(i.journal.entry,t.requestId):i.journal.entry;return{...i,purchases:s,journal:d===i.journal.entry?i.journal:{revision:i.journal.revision+1,entry:d}}});w(o),e=o}return e}function pe(e,t){if(t.customerId!==S||t.scope.projectId!==p.scope.projectId||t.scope.environment!==p.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 me(e,t){if(w(e),e.run&&(e=await Se(e)),!k(e).length&&U(e))return v(A(e,"operation"));if(!k(e).length)return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:Q(t)});E=!0;let n=k(e);if(e.run&&["running","waiting"].includes(e.run.status)&&n.every(i=>i.terminal==="native"))for(let i of n)x(y.get(i.operationId))!=="native"&&await D(e,i);let o=await H(e);return v(A(o,"operation"))}async function ne(e,t=!1,n=!0){if(_=e.start.requestId,F=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!u){let o=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 Ze(o)}catch(d){if(!e.run&&d instanceof l&&(d.status===void 0||d.status>=500))return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:Q(d)});throw d}let s=K(Me,i);if(s.customerId!==S||s.scope.projectId!==p.scope.projectId||s.scope.environment!==p.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(s.outcome==="unknown")return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});pe(e,s);let c=await h.update(d=>(w(d),{...d,run:{id:s.target.runId,versionId:s.target.versionId,status:s.target.status,revision:s.view?.revision??d.run?.revision??0,runExpiresAt:s.target.runExpiresAt}}));if(w(c),e=c,s.access.type==="operation_only")return me(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Se(e);let m=s.view;if(m.locale!==e.start.locale||!Le(m.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");u=Ge({...p,customerRun:{runId:s.target.runId,customerId:S,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(d=>p.executionPolicy.allowed.includes(d))},funnelCommandStorage:Xe(),onAcceptedResponse:We},{scope:s.scope,run:m})}try{await u.get(),u.view?.pendingRequest?.requestId===e.start.requestId&&!u.pendingCommands?.length&&await u.resume(u.view.pendingRequest.requestId);for(let i of u.pendingCommands??[])i.operation!=="close"&&await u.settle?.(i.requestId);u.pendingCommands?.length&&await u.retry(),g();let o=(await h.read()).entry;return w(o),v(A(o,"run"))}catch(o){if(g(),n&&o instanceof l&&(o.status===401||o.status===409&&o.reason==="STATE_CHANGED")){u.reset(),u=null;let i=(await h.read()).entry;return w(i),ne(i,!1,!1)}throw o}}function N(e,t="read",n){if(g(),j)return t==="read"||t===W?j:j.then(()=>N(e,t,n),()=>N(e,t,n));clearTimeout(X);let o=e().catch(i=>{throw!C&&!n?.(i)&&v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:b.purchases,error:Q(i)}),i});return j=o,W=t,o.then(()=>{j===o&&(j=void 0,W=void 0)},()=>{j===o&&(j=void 0,W=void 0)}),o}function L(){return N(async()=>{let{entry:e}=await h.read();if(!e||U(e)){if(await de(!1)==="blocked")return Ce();({entry:e}=await h.read())}return e?(_&&e.start.requestId!==_&&(u?.reset(),u=null,y.clear(),T.clear(),E=!1),E&&_===e.start.requestId?me(e,b.error):ne(e)):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function Ce(){return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:Q(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function Re(){let e=await L();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:N(async()=>{let t=(await h.read()).entry;if(w(t),!E){if(!u?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let d=u.view.paywall.operation;if(d?.confirmedAt||d?.merchantExecution||d&&!(Y(d)?["prepared","quoted"].includes(d.status):d.status==="pending"))return v(A(t,"run"));if(u.pendingCommands?.length)await u.retry();else{let I=u.view;await u.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:I.nodeId,visit:I.visit,revision:I.revision,input:{type:"paywall_confirm",operationId:I.paywall.quote.operationId,...I.paywall.quote.merchantTerms?{merchantConfirmation:we(I.paywall.quote.merchantTerms)}:{}}})}let R=(await h.read()).entry;return w(R),v(A(R,"run"))}let n=t.operationCommand?.operationId??b.confirmation?.operationId,o=n&&y.get(n);if(!n||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");J({allowed:t.allowed.filter(d=>p.executionPolicy.allowed.includes(d))},o.quote),await h.update(d=>{if(w(d),d.journal.entry?.command||d.journal.entry?.closeCommand||d.operationCommand&&d.operationCommand.operationId!==n)throw new l("PURCHASE_PENDING","Another original command is pending");return{...d,operationCommand:{operationId:n,intent:"confirm"}}});let i={operationId:n,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:we(o.quote.merchantTerms)}:{}},s=Y(o)?await ee.update(i):await ee.attach(i),c=oe.parse(s.operation);if(g(),s.operation.operationId!==n)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");y.set(n,se(o,c));let m=(await h.read()).entry;return w(m),v(A(await H(m,!1,new Set([n])),"operation"))},"confirm")}function tt(e){let t=e?.quote;return t&&ae(t)&&t.timing==="immediate"&&t.execution.provider==="merchant"&&(e.confirmedAt||e.merchantExecution)?t:null}function Ee(){if(b.mode!=="operation"||b.status==="blocked")return null;let e=b.purchases.filter(({type:n})=>n!=="complete"&&n!=="native"),t=e.length===1&&e[0]?.operationId;return t?tt(y.get(t)):null}async function be(){g();let{entry:e}=await h.read();return e?U(e)?"finished":"pending":"none"}return{get controller(){return u},get recovery(){return structuredClone(b)},get attempt(){return g(),structuredClone(F)},get identitySignal(){return ce.signal},get customerId(){return S},retained:be,async findPurchase(){let e=await be();if(e==="pending")return e;let t=await de(!0);return g(),t==="none"?e:t},async readPaywall(e){g();let t=qe(e),[n,{readPaywallContent:o},{validateResourceCheck:i}]=await Promise.all([Ae(z.request,"resolvePaywall"),import("./paywall-content-T2FGNRBR.js"),import("./check-response-MJHH5FWT.js")]);g();let s=n.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),c=await Fe(z.request,n,s);i(s,c.paywall.check,c.scope);let m=await o(p,c.paywall);if(g(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},get canRestoreUpgradePaywall(){return Ee()!==null},recoverUpgradePaywall(){let e=Ee();return e?this.recoverPurchasePaywall(void 0,e.operationId):Promise.resolve(null)},async recoverPurchasePaywall(e,t){if(b.mode!=="operation"||b.status==="blocked")return null;let{entry:n}=await h.read();if(!n?.run)return null;w(n);let o=k(n),i=o.filter(O=>!O.terminal),s=o.filter(O=>O.terminal==="complete"),c=i.length===1?i[0]:i.length?void 0:s.find(O=>e&&e.runId===n.run?.id&&O.receiptId===e.receiptId)??(s.length===1?s[0]:void 0);if(!c||t&&c.operationId!==t)return null;let m=e?.runId===n.run.id&&e.receiptId===c.receiptId?e.view:void 0,d;try{d=await D(n,c,"recover_purchase",!0)}catch(O){if(!(O instanceof l&&O.status===400&&O.code==="INVALID_REQUEST"))throw O;if(!m)return null;d=await D(n,c)}let R=d.quote;if(!R||ae(R)&&(R.timing!=="immediate"||R.execution.provider!=="merchant")||!(d.confirmedAt||d.merchantExecution||d.checkoutUrl||x(d)==="complete"))return null;x(d)!=="complete"&&J({allowed:n.allowed.filter(O=>p.executionPolicy.allowed.includes(O))},R);let I=Pe.get(c.operationId),q=n.start.parameters?.commerce,Oe=n.start.locale??"en",fe=m;if(I){if(typeof q!="object"||!q||!("provider"in q)||typeof q.provider!="string"||!("currency"in q)||typeof q.currency!="string")return null;fe=await this.readPaywall({paywallVersionId:I,locale:Oe,commerce:{provider:q.provider,currency:q.currency,...ae(R)?{intent:"subscription_change"}:{}}})}if(!fe)return null;g();let _e=fe,he=!1,Ie=async()=>{throw new l("PURCHASE_PENDING","Only the original purchase can be recovered")};return{signal:ce.signal,view:_e,quote:R,locale:Oe,get operation(){return d},get canReselect(){return T.get(c.operationId)===!0},async refresh(){return _e},preview:Ie,confirm:Ie,cancel:Ie,async read(){if(he)throw new DOMException("Purchase view closed","AbortError");d=await D(n,c);let O=await H(n,!1,new Set([c.operationId]));return he||v(A(O,"operation")),structuredClone(d)},destroy(){he=!0}}},start(e){let t=G.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return N(async()=>{let n=(await h.read()).entry;if((!n||U(n))&&await de(!0)==="blocked")return Ce();let o=await h.update(i=>{if(i&&!U(i)){if(i.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return i}return{schemaVersion:1,baseUrl:h.baseUrl,scope:p.scope,customerId:S,sessionId:$,start:t,allowed:[...p.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return _!==o.start.requestId&&(u?.reset(),u=null,y.clear(),T.clear(),E=!1),E?me(o,b.error):ne(o,!0)},`start:${t.funnelId}`)},refresh:L,confirm:Re,retry:()=>E?Re():N(async()=>{let{entry:e}=await h.read();return e?ne(e,!0):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return u?.view?N(async()=>{if(!u?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(u.pendingCommands?.find(n=>n.operation==="close"))await u.retry();else if(["running","waiting"].includes(u.view.status)){let n=u.view;await u.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision})}let t=(await h.read()).entry;return w(t),v(A(t,"run"))},"close"):L()},async continueCheckout(e,t){let n=t?await N(async()=>{let{entry:o}=await h.read();if(w(o),!o.run||!k(o).some(s=>s.operationId===t&&!s.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let i=await H(o);return v(A(i,E?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await L();g(),await e(it(n,t))},async terminateCheckout(e){let t=await L();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return N(async()=>{let{entry:o}=await h.read();w(o);let i=k(o).find(c=>c.operationId===e&&!c.terminal);if(!i||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await D(o,i,"terminate_checkout");let s=await H(o,!1,new Set([e]));return v(A(s,E?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return Z.add(e),()=>{Z.delete(e)}},destroy:ve}}export{Je as a,it as b,Vt as c};
@@ -1 +1 @@
1
- var t="https://api.longplayai.com";var p={name:"@tinkerlandai/longplay-sdk",version:"0.10.53",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md","native-funnel-host.NOTICES.txt"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};export{p as a,t as b};
1
+ var t="https://api.longplayai.com";var p={name:"@tinkerlandai/longplay-sdk",version:"0.10.54",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md","native-funnel-host.NOTICES.txt"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};export{p as a,t as b};
@@ -1 +1 @@
1
- import{e as w,f as b}from"./chunk-6HKQILBV.js";import{n as h,s as u}from"./chunk-EACC667P.js";import{a as y}from"./chunk-DX33T5JM.js";import{a as n}from"./chunk-WE55LJEN.js";import{a as g}from"./chunk-3VUPVXAV.js";import{b as f}from"./chunk-JCOSQTFG.js";function p(r,s){let a=typeof r=="string"?new TextEncoder().encode(r):r;return a.byteLength===s.byteLength&&u(a)===s.sha256}async function _(r,s){let a=w.parse(s),{artifact:i,environmentId:P}=a.content,m=new y(r.baseUrl??f).origin,e=new y(i.url,m);if(e.origin!==m||e.username||e.password||e.search||e.hash||e.pathname!==`/api/v1/configuration/${P}/artifacts/${i.sha256}`)throw new n("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,d,I=new Promise((t,l)=>{d=setTimeout(()=>{let c=new n("TIMEOUT","Public Paywall read timed out");o.abort(c),l(c)},h.initializationMs)}),E=(async()=>{let t=await(r.fetch??globalThis.fetch)(e,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(o.signal.aborted&&(t.body?.cancel().catch(()=>{}),o.signal.throwIfAborted()),!t.ok||!t.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(t.headers.get("content-length"))>i.byteLength)throw t.body?.cancel().catch(()=>{}),new n("INVALID_RESPONSE","Public Paywall is unavailable");let l=await g(t,i.byteLength,{signal:o.signal,error:c=>new n("INVALID_RESPONSE",c==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!p(l,i))throw new n("INVALID_RESPONSE","Public Paywall digest or size changed");return b(a,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))})();try{return await Promise.race([E,I])}finally{clearTimeout(d)}}export{p as a,_ as b};
1
+ import{e as w,f as b}from"./chunk-6HKQILBV.js";import{n as h,s as u}from"./chunk-EACC667P.js";import{a as y}from"./chunk-TS26DZNO.js";import{a as n}from"./chunk-WE55LJEN.js";import{a as g}from"./chunk-3VUPVXAV.js";import{b as f}from"./chunk-LBDLWHBY.js";function p(r,s){let a=typeof r=="string"?new TextEncoder().encode(r):r;return a.byteLength===s.byteLength&&u(a)===s.sha256}async function _(r,s){let a=w.parse(s),{artifact:i,environmentId:P}=a.content,m=new y(r.baseUrl??f).origin,e=new y(i.url,m);if(e.origin!==m||e.username||e.password||e.search||e.hash||e.pathname!==`/api/v1/configuration/${P}/artifacts/${i.sha256}`)throw new n("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,d,I=new Promise((t,l)=>{d=setTimeout(()=>{let c=new n("TIMEOUT","Public Paywall read timed out");o.abort(c),l(c)},h.initializationMs)}),E=(async()=>{let t=await(r.fetch??globalThis.fetch)(e,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(o.signal.aborted&&(t.body?.cancel().catch(()=>{}),o.signal.throwIfAborted()),!t.ok||!t.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(t.headers.get("content-length"))>i.byteLength)throw t.body?.cancel().catch(()=>{}),new n("INVALID_RESPONSE","Public Paywall is unavailable");let l=await g(t,i.byteLength,{signal:o.signal,error:c=>new n("INVALID_RESPONSE",c==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!p(l,i))throw new n("INVALID_RESPONSE","Public Paywall digest or size changed");return b(a,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))})();try{return await Promise.race([E,I])}finally{clearTimeout(d)}}export{p as a,_ as b};
@@ -0,0 +1 @@
1
+ import{o as n,r as t}from"./chunk-MZRDAMFQ.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
@@ -1 +1 @@
1
- import{a as tn}from"./chunk-73UFNVEP.js";import{b as nn}from"./chunk-VSARBT7T.js";import{d as We,e as ce}from"./chunk-6HKQILBV.js";import{c as qe,d as je,e as K,l as Ze}from"./chunk-EACC667P.js";import{A as Je,F as He,G as Qe,H as z,I as Ye,J as le,K as G,a as Me,c as Y,g as Z,h as Ge,i as Ue,m as $e}from"./chunk-BX2MSRA4.js";import{a as de,b as Xe}from"./chunk-LOBZ45T3.js";import{a as j,b as _e,c as ke,e as De,h as Ve,i as Le,l as Be}from"./chunk-J4RM5GQP.js";import{b as rn}from"./chunk-ADTZEBQF.js";import{A as ie,B as ae,z as oe}from"./chunk-GGZG56GR.js";import{b as W}from"./chunk-DX33T5JM.js";import{a as Q}from"./chunk-L64BS65O.js";import{m as Ke,n as ue,o as ze,p as se}from"./chunk-QGKROSRD.js";import{g as Ee,m as Ce,w as re}from"./chunk-RRZZUIFM.js";import{b as Pe,d as L,e as Ae,f as Te}from"./chunk-NNJVMJUG.js";import{a as m}from"./chunk-WE55LJEN.js";import{h as V}from"./chunk-OZK47BUU.js";import{b as en}from"./chunk-JCOSQTFG.js";import{b as n}from"./chunk-5YBTU4KS.js";import{a as on}from"./chunk-DSPLGTQI.js";import{c as Ne,f as Oe}from"./chunk-HMJTABQ5.js";function an(e){return Fn({...e,namespace:"commands",identity:[e.runToken]})}function Fn(e){let t,u,r=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),o=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let c=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??en).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",c));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,i=>i.toString(16).padStart(2,"0")).join("")});o.catch(()=>{});async function p(c){try{let a=await o;return await u.request(a,{mode:"exclusive"},()=>c(a))}catch(a){throw a instanceof m?a:r()}}function d(c){let a=t.getItem(c);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let i=JSON.parse(a);if(!i||typeof i!="object"||!("revision"in i)||!("entry"in i)||!Number.isSafeInteger(i.revision)||Number(i.revision)<0)throw r();return{revision:Number(i.revision),entry:i.entry}}return{read:()=>p(d),write:(c,a)=>p(i=>{if(d(i).revision!==c)return null;if(!Number.isSafeInteger(c+1))throw r();let y=JSON.stringify({revision:c+1,entry:a});if(y.length>1048576)throw r();return t.setItem(i,y),c+1})}}var un=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var M=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),En=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Cn=n.discriminatedUnion("type",[$e,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:M.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:He,openIn:Qe}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:M})]),Pn={id:M,presentation:Pe,outputs:n.array(M).max(250),inputs:se,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Ee,customerData:Ce,dataCursors:n.record(M,Ke.nullable())},Nn=n.strictObject({...Pn,content:n.strictObject({type:n.literal("document"),document:re})}),pe=n.strictObject({id:n.uuid(),source:un,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:M,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:En,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:ue,parameters:ze,variables:n.record(n.string(),L),output:L.nullable(),screen:Nn.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([We,ce]),quote:oe.nullable(),operation:ie.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Cn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),On=n.strictObject({scope:V,run:pe,settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),operationId:n.uuid().nullable(),receiptId:n.uuid().nullable().optional()}).optional(),purchase:n.strictObject({receiptId:n.uuid(),quote:oe.nullable(),operation:ie.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative(),document:re,answers:ue,inputs:se,values:n.record(n.string(),L).optional()}).nullable(),coupons:n.array(n.strictObject({grantId:n.uuid(),status:n.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:n.string().nullable()})).max(100),purchases:n.array(n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),status:n.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:n.uuid().optional()}),sn=On.extend({run:pe.extend({paywall:pe.shape.paywall.unwrap().extend({resolution:ce}).nullable()})});var ln="X-Indiana-Server-Key";var An=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),Tn=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(An).max(200).default([]),iam:Ge.optional(),renderGuard:Z.optional()}),me=Tn.omit({variation:!0,description:!0,iam:!0}),_n=qe.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([me,me]).rest(me).refine(e=>e.length<=20)}),cn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(_n).max(100),savedGroups:je});var $=n.string().regex(/^[a-f0-9]{64}$/),Tt=n.strictObject({iam:$,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),kn=n.strictObject({release:$,render:Z,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),_t=n.strictObject({scope:V.extend({environmentId:n.uuid()}),release:$,validatedAt:n.iso.datetime({offset:!0}),validUntil:n.iso.datetime({offset:!0}),entries:n.array(n.strictObject({id:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),event:n.enum(["screen_enter","button_click"]),delivery:Ue.optional(),target:kn})).max(4e3)}),kt=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:$,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Dt=n.strictObject({scope:V,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Vt=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Dn=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),fe=n.strictObject({operation:n.literal("page_experiments"),release:$,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(Q).optional()}),dn=n.strictObject({scope:V,runId:n.uuid(),assignments:n.array(Dn.extend({receiptId:n.uuid()})).max(100),payload:cn});var U=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),mn=n.strictObject({entry:U,nodes:n.array(n.strictObject({id:U,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),U),writes:n.record(j,j),resources:n.strictObject({screenId:U.optional(),paywallVersionId:n.uuid().optional(),couponId:n.uuid().optional(),couponIds:n.array(n.uuid()).max(20).optional(),experimentId:n.uuid().optional(),featureKey:n.string().optional(),offeringVersionId:n.uuid().optional()})})).min(1).max(500)}),pn={scope:V,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:mn},X=n.discriminatedUnion("evaluationMode",[n.strictObject({...pn,evaluationMode:n.literal("local"),growth:K,conditions:n.record(U,n.array(n.strictObject({condition:Te,port:n.string()})))}),n.strictObject({...pn,evaluationMode:n.literal("remote")})]),Vn=X.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,ke),outputSchema:_e,terminals:n.record(U,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Je.nullable()}))})});function Ln(e){return mn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let p=e.screens.find(d=>d.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,d)=>{u[`case:${d}`]=p.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let p of["success","cancel","unavailable","failure"])u[p]=t[p];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let o=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return o?.type==="feature"&&(r.featureKey=o.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ge(e){let t=le.parse(e.document),u=e.evaluationMode==="local"?K.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:u?.expiresAt??null,topology:Ln(t)};return X.parse(e.evaluationMode==="remote"?r:{...r,growth:Ze(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(o=>o.type==="condition").map(o=>[o.id,o.cases.map((p,d)=>({condition:p.condition,port:`case:${d}`}))]))})}function $t(e){let t=ge(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=le.parse(e.document);return Vn.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let o=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:o&&o.type!=="literal"&&o.type!=="feature"&&o.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:o??null}]]}))}})}var Ie=32,Mn=522240;function ve(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var qn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),ye=n.record(n.string(),L),jn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:z.shape.schemaVersion,kind:z.shape.kind,selector:z.shape.selector,contract:z.shape.contract}),context:ye,removed:n.array(n.string()).max(100),attributes:ye,removedAttributes:n.array(n.string()).max(100),result:Ye,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),Wt=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:qn,context:ye,steps:n.array(jn).min(1).max(Ie)}).refine(e=>Y(e)<=Mn,"Segment exceeds its byte budget");var Gn=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function J(e){return Array.isArray(e)?e.some(J):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&J(u):!Gn.test(t))}function fn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(c=>c.id===t.screenId&&c.type==="paywall")))return"customer_required";let o=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(o&&["bundle","selection","offering"].includes(o.type)||t.type==="condition"&&t.cases.some(c=>J(c.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(c=>c.id===t.screenId):null]);for(let[c,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${c}`)||p.includes(JSON.stringify(c))))return"customer_required";if(t.type==="split"){let c=u.experiments?.[t.experimentId];if((c?.hashAttribute??"id")!=="funnelParticipantId"||J(c?.condition)||c?.parentConditions?.length)return"customer_experiment_required"}let d=t.type==="feature"?t.featureKey:o?.type==="feature"?o.featureKey:void 0;return d&&u.features?.[d]?.rules?.some(c=>(c.hashAttribute??"id")!=="funnelParticipantId"||J(c.condition)||c.parentConditions?.length)?"customer_experiment_required":null}var he=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},ee=(e,t)=>new he(e,t),Un=e=>({experiments:e.experiments,features:e.features});function we(e,t=ee){let u=new Map(e.topology.nodes.map(d=>[d.id,d])),r=Ne(e.growth.savedGroups),o=Un(e.growth);function p(d,c){if(!Object.hasOwn(e.growth.features,d))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Oe(d,c).value}return{nodes:u,savedGroups:r,features:o.features,feature:p,evaluate(d,c){let a=u.get(d);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let i,g;if(a.type==="condition"){let v=e.conditions[a.id];if(!v)throw t("INVALID_RESPONSE","Local condition rules are unavailable");i=de({id:a.id,name:a.id,type:"condition",cases:v.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},c,o.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,c),i="next"}else if(a.type==="split"){if(!(a.resources.experimentId?e.growth.experiments[a.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let h=de({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},c,o.experiments);g=h.value,i=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,c),i=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[i]??(i==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:d,port:i,target:y,...g===void 0?{}:{value:g}}}}}function dr(e,t,u,r=ee){return be(e,r)(t,u)}function be(e,t){let u=X.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,o=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};o();let p=we(u,t);return(d,c)=>(o(),Bn(p,d,c))}function Bn(e,t,u){let r=Ae.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:o,onFeatureUsage:p,onExperimentViewed:d}=u,c={attributes:r,...o?{saveStickyBucketAssignmentDoc:a=>o(structuredClone(a))}:{},...p?{onFeatureUsage:(a,i)=>p(a,structuredClone(i))}:{},...d?{onExperimentViewed:(a,i)=>d(structuredClone(a),structuredClone(i))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,c)}function pr(e,t,u,r=ee){return gn(be(e,r),t,u)}function gn(e,t,u){let r=[],o=[],p=[],d=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(c){let a=r.findIndex(y=>y.next.attributeName===c.attributeName&&y.next.attributeValue===c.attributeValue),i=c.attributeName+"||"+c.attributeValue,g={expected:u.sticky[i]??null,next:c};a<0?r.push(g):r[a]=g},onExperimentViewed(c,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&o.push(L.parse({key:c.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(c,a){p.push(L.parse({feature:c,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:d.port,...d.value===void 0?{}:{value:d.value},sticky:r,exposures:o,features:p}}function yn(e,t,u,r=ee){let o=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),d=structuredClone(u.variables),c=structuredClone(o.sticky),a=[],i=u.nodeId,g=u.visit,y=!1,v,h=O=>fn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},o.attributes.funnelCustomerBound===!0),R=O=>(v??=be(e,r),gn(v,O,{attributes:Be({declarations:t.variables,attributes:o.attributes,parameters:u.parameters,answers:u.answers,results:d,savedGroups:{}}),sticky:c}));for(let O=0;O<Ie;O++){let s=p.get(i);if(!s||!ve(s)||h(s))break;if(g>=t.execution.maxTransitions&&(g>t.execution.maxTransitions||s.type!=="end"&&s.type!=="output")){if(!a.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let f,w;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")f=R(s.id),s.type==="offering"&&(f.value={type:"offering_version",id:String(f.value)}),s.type==="condition"?w=f.port==="default"?s.default:s.cases[Number(f.port.slice(5))]?.target:s.type==="split"?w=f.port==="notParticipating"?s.notParticipating:s.routes[f.port]:(s.type==="feature"||s.type==="offering")&&(w=s.next);else if(f={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(w=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(f.value={type:"offering_version",id:s.configuration.versionId},w=s.next),s.type==="end"||s.type==="output"){let x=s.type==="end"?s.output:s.value;if(f=x?.type==="feature"?R(s.id):{...f,port:"value",value:x?.type==="literal"?x.value:x?.type==="variable"?Me({source:"variable",key:x.key,...x.path?{path:x.path}:{}},{declarations:t.variables,answers:u.answers,results:d,parameters:u.parameters,attributes:o.attributes,savedGroups:{}}):null},x&&(f.value===void 0||!De(t.outputSchema,f.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let N=[...a,{nodeId:i,result:f}];if(Y({steps:N})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:i,result:f}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let x=s.type==="coupons"?s.couponIds.map(D=>({type:"reward",id:D})):s.type==="coupon"?{type:"reward",id:s.couponId}:f.value;if(x===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=Ve(s,{value:x});Le(t.variables,s,_),Object.assign(d,_)}for(let x of f.sticky)c[`${x.next.attributeName}||${x.next.attributeValue}`]=structuredClone(x.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!w)throw r("INVALID_RESPONSE","Local pure exit is unavailable");i=w,g++}let T=p.get(i);return{steps:a,...!y&&T&&(!ve(T)||h(T))?{boundary:{nodeId:i,visit:g}}:{}}}function In(e,t){let u=sn.safeParse(t);if(!u.success)throw new m("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new m("SCOPE_MISMATCH","Funnel scope changed");return r}var xe=(e,t)=>new m(e,t);function hr(e){return we(e,xe)}var Kn=3,zn=2e3;function $n(e){return e instanceof TypeError||e instanceof m&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Jn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===Kn||!$n(u))throw u;await new Promise(r=>setTimeout(r,t*zn))}}async function Re(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let o=null,p;if(u)try{let d=await e.funnel(t.source.id,t.source.versionId);p=d.manifest.generation,o=Hn(e,t,d)}catch{o=null}return p??=e.snapshot?.generation??(await Jn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:o}}function Hn(e,t,u){let r=t.instruction;if(r?.type!=="evaluate_segment"||!u.growth||u.control.evaluationMode!=="local"||u.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:o,remoteFeatures:p,...d}=u.growth,c=ge({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:u.document,payload:K.parse(d)}),a=Qn(c,u.document,{...t,...r}),i=a.steps.at(-1),g=a.boundary??(i?.result.port==="value"?{nodeId:i.nodeId,visit:t.visit+a.steps.length-1}:null);return g?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:g.nodeId,visit:g.visit,terminal:!a.boundary}:null}function Qn(e,t,u){return yn(e,t,u,xe)}var vn=G.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),hn=n.strictObject({schemaVersion:n.literal(1),scope:V,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:vn.optional(),closeCommand:vn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),A=()=>new m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),ne=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function H(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function wn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),o=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:hn.parse(a.entry)}}function d(a){let i=o.then(a);return o=i.catch(()=>{}),i}async function c(a){for(let i=0;i<4;i++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(ne(g.entry,y)){t=g.revision;return}let v=await e.write(g.revision,y);if(v!==null){if(!Number.isSafeInteger(v)||v<=g.revision)throw A();t=v;return}}throw A()}return{bind(a){let i=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==i)throw A();u=i},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let i=hn.parse(a),g=i.command;return!g||u!==null&&r(i)!==u?Promise.reject(A()):(u??=r(i),d(()=>c((y,v)=>{if(y&&!ne(r(y),r(i)))throw A();if(y&&i.processBindingIds){for(let[h,R]of Object.entries(i.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==R)throw A();y={...y,processBindingIds:{...y.processBindingIds,...i.processBindingIds}}}if(!y){if(v!==t&&g.operation!=="close")throw A();return i}if(!y.command)return{...y,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&y.command.operation!=="close"){if(y.command.requestId===g.requestId||y.closeCommand&&!ne(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!ne(y.command,g))throw A();return y})))},observePurchase(a,i,g,y){return d(()=>c((v,h)=>{if(!v&&h!==t||v&&r(v)!==r({...a,schemaVersion:1}))throw A();if(v?.purchase&&v.purchase.generation>i.generation)return H(v,y);if(v?.purchase&&v.purchase.generation===i.generation&&v.purchase.operationId!==i.operationId)throw A();return g?!v?.purchase||v.purchase.operationId!==i.operationId?H(v,y):H(v.command?{...v,purchase:void 0}:null,y):H({schemaVersion:1,...a,...v,purchase:i},y)}))},settle(a){return d(()=>c(i=>H(i,a)))}}}function Tr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function te(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((o,p)=>te(o,t[p]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([o,p])=>Object.hasOwn(t,o)&&te(p,Reflect.get(t,o)))}function bn(e,t){let u=t&&{...t},r=null,o=0,p=-1,d=0,c=new AbortController;function a(){d++,c.abort(new m("IDENTITY_CHANGED","Run identity changed")),c=new AbortController}let i=!1,g,y=0,v=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new m("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return p===d?r:null},get viewAgeMs(){return r&&p===d?performance.now()-o:void 0},get generation(){return d},get signal(){return c.signal},get disposed(){return i},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,R="Run identity changed during the request"){if(h!==d||i)throw new m("IDENTITY_CHANGED",R)},assertRun(h){if(r&&(h.id!==r.id||h.source.type!==r.source.type||h.source.id!==r.source.id||h.source.versionId!==r.source.versionId||h.locale!==r.locale||!te(h.parameters,r.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,R,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&R.run.revision<=r.revision)&&!(r&&R.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!R.run.stopped&&["running","waiting"].includes(R.run.status)&&r&&p===d&&R.run.nodeId===r.nodeId&&R.run.visit===r.visit&&R.run.revision===r.revision&&(R.run.screen=r.screen,(r.paywall?.quote?.operationId===R.review?.activeOperationId||!r.paywall?.quote&&R.review?.activeOperationId===null)&&(R.run.paywall=r.paywall)),!(r?.paywall&&R.run.paywall&&r.paywall.receiptId===R.run.paywall.receiptId&&(R.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||R.run.revision>=r.revision)r=R.run,o=performance.now(),p=d;else if(!s)return;if(r&&p===d)for(let f of v)try{f(structuredClone(r))}catch{}}},identify(h){if(i)throw new m("IDENTITY_CHANGED","Controller was reset");if(!Q.test(h))throw new m("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return v.add(h),()=>v.delete(h)},reset(){i||(i=!0,a(),g=void 0,r=null,v.clear())}}}var Se=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function qr(e,t,u="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",t);if(!Se.test(e))throw new m("INVALID_TOKEN",u)}function jr(e){let t=W(e);return t.identify(e.apiKey),t}function xn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&!ae(t)&&["apple","google"].includes(t.provider)?"native":t&&!ae(t)&&t.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new m("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function q(e){let{customerToken:t,...u}=e;return u}var Yn=e=>!(e instanceof m&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Rn({journal:e,state:t,call:u,processIdentity:r}){let o=null,p=null,d=!1,c={command:null,close:null},a=new Set,i,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(w=>w&&!Object.hasOwn(s.processBindingIds??{},w.requestId)))throw new m("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new m("SCOPE_MISMATCH","Pending command belongs to another scope");if(i=s.purchase,d=s.closed===!0,!s.command)return;let f=s.command;o=f.operation==="close"?null:f,p=f.operation==="close"?f:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(d=!0);for(let w of[o,p])w&&a.add(w.requestId)}):Promise.resolve();y.catch(()=>{});async function v(s,f){e&&await y;let w=t.generation;if(e){if(!t.view||!t.scope)throw new m("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:q(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(w!==t.generation||o!==s&&p!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");if(e&&on(f),t.assertCurrent(w),o!==s&&p!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let N=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(x){let _=s.operation==="submit"&&s.input.type==="paywall_quote",D=!N&&!Yn(x),l=!1;if(_&&D&&w===t.generation&&o===s&&x instanceof m&&x.status!==void 0){let I=await T(s.requestId).catch(()=>{});l=I?.settlement?.state==="unknown"&&I.settlement.operationId===null}throw w===t.generation&&(o===s||p===s)&&D&&(!_||!(x instanceof m)||x.status===void 0||l)&&(e&&await e.settle(s.requestId),w===t.generation&&O(s)),x}}function h(s,f){let w=G.parse(s);if(w.operation==="start"||w.operation==="get"||w.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(d&&w.operation!=="close"){if(o?.requestId===w.requestId)return T(w.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(w.operation==="close"){if(o?.requestId===w.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(d=!0,p&&JSON.stringify(q(p))!==JSON.stringify(q(w)))throw new m("COMMAND_PENDING","Retry the original Close");return p??=w,c.close?c.close:R(p,"close",f)}if(o){if(JSON.stringify(q(o))!==JSON.stringify(q(w)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(c.command)return c.command}else o=w;return R(o,"command",f)}function R(s,f,w){let N=v(s,w);c[f]=N;let x=()=>{c[f]===N&&(c[f]=null)};return N.then(x,x),N}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||o!==s&&p!==s?!1:(o===s&&(o=null),p===s&&(p=null),a.delete(s.requestId),!o&&!p&&(g=null),!0)}return{ready:y,get pending(){return o},get closing(){return p},get closeRequested(){return d},get inFlight(){return c.command},get closeFlight(){return c.close},get purchase(){return i},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,f,w,N){let x=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=x&&f.settlement?.state==="settled"&&f.run.pendingRequest?.requestId!==x&&(s.operation==="get"||!d||s.operation==="close"||!["running","waiting"].includes(f.run.status))?x:void 0,D=o?.requestId===_?o:p?.requestId===_?p:void 0;e?.bind({scope:f.scope,runId:f.run.id,funnelId:f.run.source.id,versionId:f.run.source.versionId});let l=f.run.paywall,I=l??f.purchase,C=I?.operation,E=f.settlement&&(!l||l.purchaseRequestId===f.settlement.requestId)&&(!i||i.operationId===f.settlement.operationId)?f.settlement:void 0,S=C?.operationId??I?.quote?.operationId??E?.operationId,F=I?.receiptId??E?.receiptId,b=l?.selectionGeneration??i?.generation??0;if(e&&S&&F&&s.operation!=="review"&&(!t.view||f.run.revision>=t.view.revision)&&(N===void 0||N>=t.readSequence)&&(!i||b>=i.generation)){let P={receiptId:F,operationId:S,generation:b},k=rn(C,I?.canReselect===!0);await e.observePurchase({scope:f.scope,runId:f.run.id,funnelId:f.run.source.id,versionId:f.run.source.versionId},P,k,_),t.assertCurrent(w),(!i||P.generation>=i.generation)&&(N===void 0||N>=t.readSequence)&&(k?i?.operationId===P.operationId&&(i=void 0):i=P)}else e&&_&&await e.settle(_);return t.assertCurrent(w),_?O(D):!1},stop(){d=!0},submit:h,settle:T,reset(){d=!0,o=null,p=null,i=void 0,g=null,c.close=null,a.clear(),c.command=null}}}function Zn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new m("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new m("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Se.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=W({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),o=bn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(R),d=null,c=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?an(e):void 0),a=c&&wn(c),i=Rn({journal:a,state:o,call:T,processIdentity:e.process}),g=0,y=new Map;function v(){g++,y.clear(),t=void 0}async function h(l){let I=l.operation==="resume"?i.pending?.operation==="resume"?null:i.pending:l;if(u&&l.operation==="resume"&&!I&&l.requestId!==e.customerRun?.startRequestId)throw new m("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(I?.operation==="submit"&&I.input.type==="paywall_confirm"){let P=o.view?.paywall;xn(u,P?.quote?.operationId===I.input.operationId?P.quote:void 0)}if(e.process)return e.process.request(l);let C=o.generation;o.assertCurrent(C);let E=performance.now()+(e.timeoutMs??35e3),S=o.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let P=o.signal,k,B=()=>{},Sn=new Promise((Wn,Fe)=>{B=()=>Fe(P.reason),P.addEventListener("abort",B,{once:!0}),k=setTimeout(()=>Fe(new m("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(o.assertCurrent(C),e.session.access())),Sn])}finally{clearTimeout(k),P.removeEventListener("abort",B)}}o.assertCurrent(C);let F={...l,...S?{customerToken:S}:{}},b=l.operation==="page_experiments"?fe.parse(F):G.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!S)throw new m("IDENTITY_CHANGED","Original recovery Customer changed");let P={...b};return"customerToken"in P&&delete P.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:P},S,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",b,e.runToken,{headers:e.serverKey&&!S?{[ln]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function R(){v(),p?.(),o.reset(),i.reset(),d=null,r.dispose()}async function T(l,I){let C=t;t=void 0;let E=o.generation,S=()=>o.assertCurrent(E);a&&await i.ready,S();let F=o.view,b=In(e,C!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?C:await h(l));if(l.operation==="review"&&!b.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&b.run.id!==e.customerRun.runId)throw new m("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&b.purchase&&(b.purchase.receiptId!==l.purchase.receiptId||(b.purchase.operation?.operationId??b.purchase.quote?.operationId)!==l.purchase.operationId))throw new m("INVALID_RESPONSE","The requested original purchase changed");if(S(),b.runToken&&b.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let P=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(P&&b.settlement?.requestId!==P)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");i.assertBinding(b),o.assertRun(b.run),o.bindScope(b.scope);let k=await i.observe(l,b,E,I);return(!o.view||b.run.revision>=o.view.revision)&&(I===void 0||I>=o.readSequence)&&(await e.onAcceptedResponse?.(b),S()),!b.run.stopped&&["running","waiting"].includes(b.run.status)&&l.operation==="get"&&l.settlementRequestId||(S(),["running","waiting"].includes(b.run.status)||i.stop(),o.publish(l,b,F,I,k)),b}function O(l){let I=o.generation;v();let C=l(),E=()=>{o.generation===I&&v()};return C.then(E,E),C}let s=(l,I)=>O(()=>i.submit(l,I)),f=null,w=new WeakMap;function N(l){let I=w.get(l);if(I)return I;let C=_(l);return w.set(l,C),C}let x=!1;async function _(l){let I=await l;if(I.run.instruction?.type!=="evaluate_segment")return I;if(f)return f;x=!0;let C=o.generation,E=(async()=>{for(let S=0;S<32&&I.run.instruction?.type==="evaluate_segment";S++){if(i.pending||i.closeRequested)return I;let F=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:P}=await Re(e.configuration,F,{predict:!1});if(C!==o.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(i.pending||i.closeRequested)return I;if(o.view&&(o.view.revision!==F.revision||o.view.visit!==F.visit||o.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Re(e.configuration,F).then(({prediction:B})=>{k&&C===o.generation&&!i.closeRequested&&o.view?.id===F.id&&!o.view.stopped&&o.view.nodeId===F.nodeId&&o.view.visit===F.visit&&o.view.revision===F.revision&&(d=B)}).catch(()=>{});try{I=await s({operation:"commit_segment",requestId:Xe(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...P})}finally{k=!1,d=null}}}return I})();f=E;try{return await E}finally{f===E&&(f=null)}}let D={get configuration(){return x?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=o.currentView;return l?structuredClone(l):null},get viewAgeMs(){return o.viewAgeMs},get pendingCommand(){let l=i.closing??i.pending;return l?structuredClone(q(l)):null},get pendingCommands(){return[i.pending,i.closing].filter(l=>l!==null).map(l=>structuredClone(q(l)))},get pendingPurchase(){return i.purchase?structuredClone(i.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=o.view;return d&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===d.runId&&l.nodeId===d.from.nodeId&&l.visit===d.from.visit&&l.revision===d.from.revision&&!i.closeRequested?structuredClone(d):null},settle:(...l)=>O(()=>i.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return nn(e,l)},async pageExperiments(l,I=[]){let C=o.generation;o.assertCurrent(C);let E=o.view?.id;if(!E)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let S=dn.parse(await h(fe.parse({operation:"page_experiments",release:l,usedReceiptIds:I})));if(o.assertCurrent(C),S.runId!==E||S.scope.projectId!==o.scope?.projectId||S.scope.environment!==o.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return S},review(l){return T({operation:"review",...l?{receiptId:l}:{}},o.nextRead())},async get(l,I){let C=o.generation;l=l&&structuredClone(l),I=I&&{...I},a&&await i.ready,o.assertCurrent(C),I??=i.purchase&&{receiptId:i.purchase.receiptId,operationId:i.purchase.operationId};let E=JSON.stringify([o.generation,g,l??null,I??null]),S=y.get(E);if(S)return S.then(k=>structuredClone(k));let F=o.nextRead(),b=N(T({operation:"get",...l?{data:l}:{},...I?{purchase:I}:{}},F));y.set(E,b);let P=()=>{y.get(E)===b&&y.delete(E)};return b.then(P,P),b.then(k=>structuredClone(k))},resume(l=o.view?.pendingRequest?.requestId){return l?i.closeRequested?D.settle(l):i.pending?.requestId===l?N(s(i.pending)):N(s({operation:"resume",requestId:l})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(l){return N(s(l))},async retry(){if(i.closeFlight)return i.closeFlight;if(i.closing)return s(i.closing);if(i.closeRequested&&i.pending)return D.settle(i.pending.requestId);if(i.inFlight)return N(i.inFlight);if(!i.pending)throw new m("INVALID_REQUEST","No command is pending");let l=i.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let I=o.generation;if(await D.settle(l.requestId),o.assertCurrent(I),!i.pending)return D.get();if(i.pending!==l||i.closeRequested)throw new m("COMMAND_PENDING","The original quote is being recovered")}return N(s(l))},identify(l){let I=o.customerToken?void 0:t;v(),o.identify(l),t=I,d=null,r.reset()},get identitySignal(){return o.signal},subscribe:o.subscribe,reset:R};return tn(D,(l,I)=>N(s(l,I))),D}function po(e,t){return Zn({...e,runToken:"",initialResponse:t})}export{un as a,Cn as b,pe as c,On as d,sn as e,kn as f,_t as g,kt as h,Dt as i,fe as j,dn as k,X as l,Vn as m,$t as n,dr as o,pr as p,In as q,xe as r,hr as s,Qn as t,hn as u,H as v,an as w,Fn as x,Tr as y,te as z,Se as A,qr as B,jr as C,xn as D,Zn as E,po as F};
1
+ import{a as tn}from"./chunk-73UFNVEP.js";import{b as nn}from"./chunk-LFMAFY3P.js";import{d as We,e as ce}from"./chunk-6HKQILBV.js";import{c as qe,d as je,e as K,l as Ze}from"./chunk-EACC667P.js";import{A as Je,F as He,G as Qe,H as z,I as Ye,J as le,K as G,a as Me,c as Y,g as Z,h as Ge,i as Ue,m as $e}from"./chunk-BX2MSRA4.js";import{a as de,b as Xe}from"./chunk-LOBZ45T3.js";import{a as j,b as _e,c as ke,e as De,h as Ve,i as Le,l as Be}from"./chunk-J4RM5GQP.js";import{b as rn}from"./chunk-ADTZEBQF.js";import{A as ie,B as ae,z as oe}from"./chunk-GGZG56GR.js";import{b as W}from"./chunk-TS26DZNO.js";import{a as Q}from"./chunk-L64BS65O.js";import{m as Ke,n as ue,o as ze,p as se}from"./chunk-QGKROSRD.js";import{g as Ee,m as Ce,w as re}from"./chunk-RRZZUIFM.js";import{b as Pe,d as L,e as Ae,f as Te}from"./chunk-NNJVMJUG.js";import{a as m}from"./chunk-WE55LJEN.js";import{h as V}from"./chunk-OZK47BUU.js";import{b as en}from"./chunk-LBDLWHBY.js";import{b as n}from"./chunk-5YBTU4KS.js";import{a as on}from"./chunk-DSPLGTQI.js";import{c as Ne,f as Oe}from"./chunk-HMJTABQ5.js";function an(e){return Fn({...e,namespace:"commands",identity:[e.runToken]})}function Fn(e){let t,u,r=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),o=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let c=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??en).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",c));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,i=>i.toString(16).padStart(2,"0")).join("")});o.catch(()=>{});async function p(c){try{let a=await o;return await u.request(a,{mode:"exclusive"},()=>c(a))}catch(a){throw a instanceof m?a:r()}}function d(c){let a=t.getItem(c);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let i=JSON.parse(a);if(!i||typeof i!="object"||!("revision"in i)||!("entry"in i)||!Number.isSafeInteger(i.revision)||Number(i.revision)<0)throw r();return{revision:Number(i.revision),entry:i.entry}}return{read:()=>p(d),write:(c,a)=>p(i=>{if(d(i).revision!==c)return null;if(!Number.isSafeInteger(c+1))throw r();let y=JSON.stringify({revision:c+1,entry:a});if(y.length>1048576)throw r();return t.setItem(i,y),c+1})}}var un=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var M=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),En=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Cn=n.discriminatedUnion("type",[$e,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:M.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:He,openIn:Qe}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:M})]),Pn={id:M,presentation:Pe,outputs:n.array(M).max(250),inputs:se,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Ee,customerData:Ce,dataCursors:n.record(M,Ke.nullable())},Nn=n.strictObject({...Pn,content:n.strictObject({type:n.literal("document"),document:re})}),pe=n.strictObject({id:n.uuid(),source:un,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:M,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:En,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:ue,parameters:ze,variables:n.record(n.string(),L),output:L.nullable(),screen:Nn.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([We,ce]),quote:oe.nullable(),operation:ie.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Cn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),On=n.strictObject({scope:V,run:pe,settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),operationId:n.uuid().nullable(),receiptId:n.uuid().nullable().optional()}).optional(),purchase:n.strictObject({receiptId:n.uuid(),quote:oe.nullable(),operation:ie.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative(),document:re,answers:ue,inputs:se,values:n.record(n.string(),L).optional()}).nullable(),coupons:n.array(n.strictObject({grantId:n.uuid(),status:n.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:n.string().nullable()})).max(100),purchases:n.array(n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),status:n.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:n.uuid().optional()}),sn=On.extend({run:pe.extend({paywall:pe.shape.paywall.unwrap().extend({resolution:ce}).nullable()})});var ln="X-Indiana-Server-Key";var An=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),Tn=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(An).max(200).default([]),iam:Ge.optional(),renderGuard:Z.optional()}),me=Tn.omit({variation:!0,description:!0,iam:!0}),_n=qe.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([me,me]).rest(me).refine(e=>e.length<=20)}),cn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(_n).max(100),savedGroups:je});var $=n.string().regex(/^[a-f0-9]{64}$/),Tt=n.strictObject({iam:$,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),kn=n.strictObject({release:$,render:Z,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),_t=n.strictObject({scope:V.extend({environmentId:n.uuid()}),release:$,validatedAt:n.iso.datetime({offset:!0}),validUntil:n.iso.datetime({offset:!0}),entries:n.array(n.strictObject({id:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),event:n.enum(["screen_enter","button_click"]),delivery:Ue.optional(),target:kn})).max(4e3)}),kt=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:$,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Dt=n.strictObject({scope:V,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Vt=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Dn=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),fe=n.strictObject({operation:n.literal("page_experiments"),release:$,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(Q).optional()}),dn=n.strictObject({scope:V,runId:n.uuid(),assignments:n.array(Dn.extend({receiptId:n.uuid()})).max(100),payload:cn});var U=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),mn=n.strictObject({entry:U,nodes:n.array(n.strictObject({id:U,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),U),writes:n.record(j,j),resources:n.strictObject({screenId:U.optional(),paywallVersionId:n.uuid().optional(),couponId:n.uuid().optional(),couponIds:n.array(n.uuid()).max(20).optional(),experimentId:n.uuid().optional(),featureKey:n.string().optional(),offeringVersionId:n.uuid().optional()})})).min(1).max(500)}),pn={scope:V,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:mn},X=n.discriminatedUnion("evaluationMode",[n.strictObject({...pn,evaluationMode:n.literal("local"),growth:K,conditions:n.record(U,n.array(n.strictObject({condition:Te,port:n.string()})))}),n.strictObject({...pn,evaluationMode:n.literal("remote")})]),Vn=X.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,ke),outputSchema:_e,terminals:n.record(U,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Je.nullable()}))})});function Ln(e){return mn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let p=e.screens.find(d=>d.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,d)=>{u[`case:${d}`]=p.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let p of["success","cancel","unavailable","failure"])u[p]=t[p];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let o=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return o?.type==="feature"&&(r.featureKey=o.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ge(e){let t=le.parse(e.document),u=e.evaluationMode==="local"?K.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:u?.expiresAt??null,topology:Ln(t)};return X.parse(e.evaluationMode==="remote"?r:{...r,growth:Ze(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(o=>o.type==="condition").map(o=>[o.id,o.cases.map((p,d)=>({condition:p.condition,port:`case:${d}`}))]))})}function $t(e){let t=ge(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=le.parse(e.document);return Vn.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let o=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:o&&o.type!=="literal"&&o.type!=="feature"&&o.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:o??null}]]}))}})}var Ie=32,Mn=522240;function ve(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var qn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),ye=n.record(n.string(),L),jn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:z.shape.schemaVersion,kind:z.shape.kind,selector:z.shape.selector,contract:z.shape.contract}),context:ye,removed:n.array(n.string()).max(100),attributes:ye,removedAttributes:n.array(n.string()).max(100),result:Ye,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),Wt=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:qn,context:ye,steps:n.array(jn).min(1).max(Ie)}).refine(e=>Y(e)<=Mn,"Segment exceeds its byte budget");var Gn=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function J(e){return Array.isArray(e)?e.some(J):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&J(u):!Gn.test(t))}function fn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(c=>c.id===t.screenId&&c.type==="paywall")))return"customer_required";let o=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(o&&["bundle","selection","offering"].includes(o.type)||t.type==="condition"&&t.cases.some(c=>J(c.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(c=>c.id===t.screenId):null]);for(let[c,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${c}`)||p.includes(JSON.stringify(c))))return"customer_required";if(t.type==="split"){let c=u.experiments?.[t.experimentId];if((c?.hashAttribute??"id")!=="funnelParticipantId"||J(c?.condition)||c?.parentConditions?.length)return"customer_experiment_required"}let d=t.type==="feature"?t.featureKey:o?.type==="feature"?o.featureKey:void 0;return d&&u.features?.[d]?.rules?.some(c=>(c.hashAttribute??"id")!=="funnelParticipantId"||J(c.condition)||c.parentConditions?.length)?"customer_experiment_required":null}var he=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},ee=(e,t)=>new he(e,t),Un=e=>({experiments:e.experiments,features:e.features});function we(e,t=ee){let u=new Map(e.topology.nodes.map(d=>[d.id,d])),r=Ne(e.growth.savedGroups),o=Un(e.growth);function p(d,c){if(!Object.hasOwn(e.growth.features,d))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Oe(d,c).value}return{nodes:u,savedGroups:r,features:o.features,feature:p,evaluate(d,c){let a=u.get(d);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let i,g;if(a.type==="condition"){let v=e.conditions[a.id];if(!v)throw t("INVALID_RESPONSE","Local condition rules are unavailable");i=de({id:a.id,name:a.id,type:"condition",cases:v.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},c,o.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,c),i="next"}else if(a.type==="split"){if(!(a.resources.experimentId?e.growth.experiments[a.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let h=de({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},c,o.experiments);g=h.value,i=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,c),i=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[i]??(i==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:d,port:i,target:y,...g===void 0?{}:{value:g}}}}}function dr(e,t,u,r=ee){return be(e,r)(t,u)}function be(e,t){let u=X.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,o=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};o();let p=we(u,t);return(d,c)=>(o(),Bn(p,d,c))}function Bn(e,t,u){let r=Ae.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:o,onFeatureUsage:p,onExperimentViewed:d}=u,c={attributes:r,...o?{saveStickyBucketAssignmentDoc:a=>o(structuredClone(a))}:{},...p?{onFeatureUsage:(a,i)=>p(a,structuredClone(i))}:{},...d?{onExperimentViewed:(a,i)=>d(structuredClone(a),structuredClone(i))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,c)}function pr(e,t,u,r=ee){return gn(be(e,r),t,u)}function gn(e,t,u){let r=[],o=[],p=[],d=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(c){let a=r.findIndex(y=>y.next.attributeName===c.attributeName&&y.next.attributeValue===c.attributeValue),i=c.attributeName+"||"+c.attributeValue,g={expected:u.sticky[i]??null,next:c};a<0?r.push(g):r[a]=g},onExperimentViewed(c,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&o.push(L.parse({key:c.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(c,a){p.push(L.parse({feature:c,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:d.port,...d.value===void 0?{}:{value:d.value},sticky:r,exposures:o,features:p}}function yn(e,t,u,r=ee){let o=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),d=structuredClone(u.variables),c=structuredClone(o.sticky),a=[],i=u.nodeId,g=u.visit,y=!1,v,h=O=>fn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},o.attributes.funnelCustomerBound===!0),R=O=>(v??=be(e,r),gn(v,O,{attributes:Be({declarations:t.variables,attributes:o.attributes,parameters:u.parameters,answers:u.answers,results:d,savedGroups:{}}),sticky:c}));for(let O=0;O<Ie;O++){let s=p.get(i);if(!s||!ve(s)||h(s))break;if(g>=t.execution.maxTransitions&&(g>t.execution.maxTransitions||s.type!=="end"&&s.type!=="output")){if(!a.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let f,w;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")f=R(s.id),s.type==="offering"&&(f.value={type:"offering_version",id:String(f.value)}),s.type==="condition"?w=f.port==="default"?s.default:s.cases[Number(f.port.slice(5))]?.target:s.type==="split"?w=f.port==="notParticipating"?s.notParticipating:s.routes[f.port]:(s.type==="feature"||s.type==="offering")&&(w=s.next);else if(f={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(w=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(f.value={type:"offering_version",id:s.configuration.versionId},w=s.next),s.type==="end"||s.type==="output"){let x=s.type==="end"?s.output:s.value;if(f=x?.type==="feature"?R(s.id):{...f,port:"value",value:x?.type==="literal"?x.value:x?.type==="variable"?Me({source:"variable",key:x.key,...x.path?{path:x.path}:{}},{declarations:t.variables,answers:u.answers,results:d,parameters:u.parameters,attributes:o.attributes,savedGroups:{}}):null},x&&(f.value===void 0||!De(t.outputSchema,f.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let N=[...a,{nodeId:i,result:f}];if(Y({steps:N})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:i,result:f}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let x=s.type==="coupons"?s.couponIds.map(D=>({type:"reward",id:D})):s.type==="coupon"?{type:"reward",id:s.couponId}:f.value;if(x===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=Ve(s,{value:x});Le(t.variables,s,_),Object.assign(d,_)}for(let x of f.sticky)c[`${x.next.attributeName}||${x.next.attributeValue}`]=structuredClone(x.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!w)throw r("INVALID_RESPONSE","Local pure exit is unavailable");i=w,g++}let T=p.get(i);return{steps:a,...!y&&T&&(!ve(T)||h(T))?{boundary:{nodeId:i,visit:g}}:{}}}function In(e,t){let u=sn.safeParse(t);if(!u.success)throw new m("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new m("SCOPE_MISMATCH","Funnel scope changed");return r}var xe=(e,t)=>new m(e,t);function hr(e){return we(e,xe)}var Kn=3,zn=2e3;function $n(e){return e instanceof TypeError||e instanceof m&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Jn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===Kn||!$n(u))throw u;await new Promise(r=>setTimeout(r,t*zn))}}async function Re(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let o=null,p;if(u)try{let d=await e.funnel(t.source.id,t.source.versionId);p=d.manifest.generation,o=Hn(e,t,d)}catch{o=null}return p??=e.snapshot?.generation??(await Jn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:o}}function Hn(e,t,u){let r=t.instruction;if(r?.type!=="evaluate_segment"||!u.growth||u.control.evaluationMode!=="local"||u.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:o,remoteFeatures:p,...d}=u.growth,c=ge({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:u.document,payload:K.parse(d)}),a=Qn(c,u.document,{...t,...r}),i=a.steps.at(-1),g=a.boundary??(i?.result.port==="value"?{nodeId:i.nodeId,visit:t.visit+a.steps.length-1}:null);return g?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:g.nodeId,visit:g.visit,terminal:!a.boundary}:null}function Qn(e,t,u){return yn(e,t,u,xe)}var vn=G.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),hn=n.strictObject({schemaVersion:n.literal(1),scope:V,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:vn.optional(),closeCommand:vn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),A=()=>new m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),ne=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function H(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function wn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),o=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:hn.parse(a.entry)}}function d(a){let i=o.then(a);return o=i.catch(()=>{}),i}async function c(a){for(let i=0;i<4;i++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(ne(g.entry,y)){t=g.revision;return}let v=await e.write(g.revision,y);if(v!==null){if(!Number.isSafeInteger(v)||v<=g.revision)throw A();t=v;return}}throw A()}return{bind(a){let i=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==i)throw A();u=i},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let i=hn.parse(a),g=i.command;return!g||u!==null&&r(i)!==u?Promise.reject(A()):(u??=r(i),d(()=>c((y,v)=>{if(y&&!ne(r(y),r(i)))throw A();if(y&&i.processBindingIds){for(let[h,R]of Object.entries(i.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==R)throw A();y={...y,processBindingIds:{...y.processBindingIds,...i.processBindingIds}}}if(!y){if(v!==t&&g.operation!=="close")throw A();return i}if(!y.command)return{...y,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&y.command.operation!=="close"){if(y.command.requestId===g.requestId||y.closeCommand&&!ne(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!ne(y.command,g))throw A();return y})))},observePurchase(a,i,g,y){return d(()=>c((v,h)=>{if(!v&&h!==t||v&&r(v)!==r({...a,schemaVersion:1}))throw A();if(v?.purchase&&v.purchase.generation>i.generation)return H(v,y);if(v?.purchase&&v.purchase.generation===i.generation&&v.purchase.operationId!==i.operationId)throw A();return g?!v?.purchase||v.purchase.operationId!==i.operationId?H(v,y):H(v.command?{...v,purchase:void 0}:null,y):H({schemaVersion:1,...a,...v,purchase:i},y)}))},settle(a){return d(()=>c(i=>H(i,a)))}}}function Tr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function te(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((o,p)=>te(o,t[p]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([o,p])=>Object.hasOwn(t,o)&&te(p,Reflect.get(t,o)))}function bn(e,t){let u=t&&{...t},r=null,o=0,p=-1,d=0,c=new AbortController;function a(){d++,c.abort(new m("IDENTITY_CHANGED","Run identity changed")),c=new AbortController}let i=!1,g,y=0,v=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new m("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return p===d?r:null},get viewAgeMs(){return r&&p===d?performance.now()-o:void 0},get generation(){return d},get signal(){return c.signal},get disposed(){return i},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,R="Run identity changed during the request"){if(h!==d||i)throw new m("IDENTITY_CHANGED",R)},assertRun(h){if(r&&(h.id!==r.id||h.source.type!==r.source.type||h.source.id!==r.source.id||h.source.versionId!==r.source.versionId||h.locale!==r.locale||!te(h.parameters,r.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,R,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&R.run.revision<=r.revision)&&!(r&&R.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!R.run.stopped&&["running","waiting"].includes(R.run.status)&&r&&p===d&&R.run.nodeId===r.nodeId&&R.run.visit===r.visit&&R.run.revision===r.revision&&(R.run.screen=r.screen,(r.paywall?.quote?.operationId===R.review?.activeOperationId||!r.paywall?.quote&&R.review?.activeOperationId===null)&&(R.run.paywall=r.paywall)),!(r?.paywall&&R.run.paywall&&r.paywall.receiptId===R.run.paywall.receiptId&&(R.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||R.run.revision>=r.revision)r=R.run,o=performance.now(),p=d;else if(!s)return;if(r&&p===d)for(let f of v)try{f(structuredClone(r))}catch{}}},identify(h){if(i)throw new m("IDENTITY_CHANGED","Controller was reset");if(!Q.test(h))throw new m("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return v.add(h),()=>v.delete(h)},reset(){i||(i=!0,a(),g=void 0,r=null,v.clear())}}}var Se=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function qr(e,t,u="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",t);if(!Se.test(e))throw new m("INVALID_TOKEN",u)}function jr(e){let t=W(e);return t.identify(e.apiKey),t}function xn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&!ae(t)&&["apple","google"].includes(t.provider)?"native":t&&!ae(t)&&t.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new m("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function q(e){let{customerToken:t,...u}=e;return u}var Yn=e=>!(e instanceof m&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Rn({journal:e,state:t,call:u,processIdentity:r}){let o=null,p=null,d=!1,c={command:null,close:null},a=new Set,i,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(w=>w&&!Object.hasOwn(s.processBindingIds??{},w.requestId)))throw new m("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new m("SCOPE_MISMATCH","Pending command belongs to another scope");if(i=s.purchase,d=s.closed===!0,!s.command)return;let f=s.command;o=f.operation==="close"?null:f,p=f.operation==="close"?f:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(d=!0);for(let w of[o,p])w&&a.add(w.requestId)}):Promise.resolve();y.catch(()=>{});async function v(s,f){e&&await y;let w=t.generation;if(e){if(!t.view||!t.scope)throw new m("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:q(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(w!==t.generation||o!==s&&p!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");if(e&&on(f),t.assertCurrent(w),o!==s&&p!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let N=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(x){let _=s.operation==="submit"&&s.input.type==="paywall_quote",D=!N&&!Yn(x),l=!1;if(_&&D&&w===t.generation&&o===s&&x instanceof m&&x.status!==void 0){let I=await T(s.requestId).catch(()=>{});l=I?.settlement?.state==="unknown"&&I.settlement.operationId===null}throw w===t.generation&&(o===s||p===s)&&D&&(!_||!(x instanceof m)||x.status===void 0||l)&&(e&&await e.settle(s.requestId),w===t.generation&&O(s)),x}}function h(s,f){let w=G.parse(s);if(w.operation==="start"||w.operation==="get"||w.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(d&&w.operation!=="close"){if(o?.requestId===w.requestId)return T(w.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(w.operation==="close"){if(o?.requestId===w.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(d=!0,p&&JSON.stringify(q(p))!==JSON.stringify(q(w)))throw new m("COMMAND_PENDING","Retry the original Close");return p??=w,c.close?c.close:R(p,"close",f)}if(o){if(JSON.stringify(q(o))!==JSON.stringify(q(w)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(c.command)return c.command}else o=w;return R(o,"command",f)}function R(s,f,w){let N=v(s,w);c[f]=N;let x=()=>{c[f]===N&&(c[f]=null)};return N.then(x,x),N}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||o!==s&&p!==s?!1:(o===s&&(o=null),p===s&&(p=null),a.delete(s.requestId),!o&&!p&&(g=null),!0)}return{ready:y,get pending(){return o},get closing(){return p},get closeRequested(){return d},get inFlight(){return c.command},get closeFlight(){return c.close},get purchase(){return i},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,f,w,N){let x=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=x&&f.settlement?.state==="settled"&&f.run.pendingRequest?.requestId!==x&&(s.operation==="get"||!d||s.operation==="close"||!["running","waiting"].includes(f.run.status))?x:void 0,D=o?.requestId===_?o:p?.requestId===_?p:void 0;e?.bind({scope:f.scope,runId:f.run.id,funnelId:f.run.source.id,versionId:f.run.source.versionId});let l=f.run.paywall,I=l??f.purchase,C=I?.operation,E=f.settlement&&(!l||l.purchaseRequestId===f.settlement.requestId)&&(!i||i.operationId===f.settlement.operationId)?f.settlement:void 0,S=C?.operationId??I?.quote?.operationId??E?.operationId,F=I?.receiptId??E?.receiptId,b=l?.selectionGeneration??i?.generation??0;if(e&&S&&F&&s.operation!=="review"&&(!t.view||f.run.revision>=t.view.revision)&&(N===void 0||N>=t.readSequence)&&(!i||b>=i.generation)){let P={receiptId:F,operationId:S,generation:b},k=rn(C,I?.canReselect===!0);await e.observePurchase({scope:f.scope,runId:f.run.id,funnelId:f.run.source.id,versionId:f.run.source.versionId},P,k,_),t.assertCurrent(w),(!i||P.generation>=i.generation)&&(N===void 0||N>=t.readSequence)&&(k?i?.operationId===P.operationId&&(i=void 0):i=P)}else e&&_&&await e.settle(_);return t.assertCurrent(w),_?O(D):!1},stop(){d=!0},submit:h,settle:T,reset(){d=!0,o=null,p=null,i=void 0,g=null,c.close=null,a.clear(),c.command=null}}}function Zn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new m("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new m("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Se.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=W({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),o=bn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(R),d=null,c=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?an(e):void 0),a=c&&wn(c),i=Rn({journal:a,state:o,call:T,processIdentity:e.process}),g=0,y=new Map;function v(){g++,y.clear(),t=void 0}async function h(l){let I=l.operation==="resume"?i.pending?.operation==="resume"?null:i.pending:l;if(u&&l.operation==="resume"&&!I&&l.requestId!==e.customerRun?.startRequestId)throw new m("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(I?.operation==="submit"&&I.input.type==="paywall_confirm"){let P=o.view?.paywall;xn(u,P?.quote?.operationId===I.input.operationId?P.quote:void 0)}if(e.process)return e.process.request(l);let C=o.generation;o.assertCurrent(C);let E=performance.now()+(e.timeoutMs??35e3),S=o.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let P=o.signal,k,B=()=>{},Sn=new Promise((Wn,Fe)=>{B=()=>Fe(P.reason),P.addEventListener("abort",B,{once:!0}),k=setTimeout(()=>Fe(new m("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(o.assertCurrent(C),e.session.access())),Sn])}finally{clearTimeout(k),P.removeEventListener("abort",B)}}o.assertCurrent(C);let F={...l,...S?{customerToken:S}:{}},b=l.operation==="page_experiments"?fe.parse(F):G.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!S)throw new m("IDENTITY_CHANGED","Original recovery Customer changed");let P={...b};return"customerToken"in P&&delete P.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:P},S,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",b,e.runToken,{headers:e.serverKey&&!S?{[ln]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function R(){v(),p?.(),o.reset(),i.reset(),d=null,r.dispose()}async function T(l,I){let C=t;t=void 0;let E=o.generation,S=()=>o.assertCurrent(E);a&&await i.ready,S();let F=o.view,b=In(e,C!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?C:await h(l));if(l.operation==="review"&&!b.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&b.run.id!==e.customerRun.runId)throw new m("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&b.purchase&&(b.purchase.receiptId!==l.purchase.receiptId||(b.purchase.operation?.operationId??b.purchase.quote?.operationId)!==l.purchase.operationId))throw new m("INVALID_RESPONSE","The requested original purchase changed");if(S(),b.runToken&&b.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let P=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(P&&b.settlement?.requestId!==P)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");i.assertBinding(b),o.assertRun(b.run),o.bindScope(b.scope);let k=await i.observe(l,b,E,I);return(!o.view||b.run.revision>=o.view.revision)&&(I===void 0||I>=o.readSequence)&&(await e.onAcceptedResponse?.(b),S()),!b.run.stopped&&["running","waiting"].includes(b.run.status)&&l.operation==="get"&&l.settlementRequestId||(S(),["running","waiting"].includes(b.run.status)||i.stop(),o.publish(l,b,F,I,k)),b}function O(l){let I=o.generation;v();let C=l(),E=()=>{o.generation===I&&v()};return C.then(E,E),C}let s=(l,I)=>O(()=>i.submit(l,I)),f=null,w=new WeakMap;function N(l){let I=w.get(l);if(I)return I;let C=_(l);return w.set(l,C),C}let x=!1;async function _(l){let I=await l;if(I.run.instruction?.type!=="evaluate_segment")return I;if(f)return f;x=!0;let C=o.generation,E=(async()=>{for(let S=0;S<32&&I.run.instruction?.type==="evaluate_segment";S++){if(i.pending||i.closeRequested)return I;let F=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:P}=await Re(e.configuration,F,{predict:!1});if(C!==o.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(i.pending||i.closeRequested)return I;if(o.view&&(o.view.revision!==F.revision||o.view.visit!==F.visit||o.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Re(e.configuration,F).then(({prediction:B})=>{k&&C===o.generation&&!i.closeRequested&&o.view?.id===F.id&&!o.view.stopped&&o.view.nodeId===F.nodeId&&o.view.visit===F.visit&&o.view.revision===F.revision&&(d=B)}).catch(()=>{});try{I=await s({operation:"commit_segment",requestId:Xe(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...P})}finally{k=!1,d=null}}}return I})();f=E;try{return await E}finally{f===E&&(f=null)}}let D={get configuration(){return x?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=o.currentView;return l?structuredClone(l):null},get viewAgeMs(){return o.viewAgeMs},get pendingCommand(){let l=i.closing??i.pending;return l?structuredClone(q(l)):null},get pendingCommands(){return[i.pending,i.closing].filter(l=>l!==null).map(l=>structuredClone(q(l)))},get pendingPurchase(){return i.purchase?structuredClone(i.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=o.view;return d&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===d.runId&&l.nodeId===d.from.nodeId&&l.visit===d.from.visit&&l.revision===d.from.revision&&!i.closeRequested?structuredClone(d):null},settle:(...l)=>O(()=>i.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return nn(e,l)},async pageExperiments(l,I=[]){let C=o.generation;o.assertCurrent(C);let E=o.view?.id;if(!E)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let S=dn.parse(await h(fe.parse({operation:"page_experiments",release:l,usedReceiptIds:I})));if(o.assertCurrent(C),S.runId!==E||S.scope.projectId!==o.scope?.projectId||S.scope.environment!==o.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return S},review(l){return T({operation:"review",...l?{receiptId:l}:{}},o.nextRead())},async get(l,I){let C=o.generation;l=l&&structuredClone(l),I=I&&{...I},a&&await i.ready,o.assertCurrent(C),I??=i.purchase&&{receiptId:i.purchase.receiptId,operationId:i.purchase.operationId};let E=JSON.stringify([o.generation,g,l??null,I??null]),S=y.get(E);if(S)return S.then(k=>structuredClone(k));let F=o.nextRead(),b=N(T({operation:"get",...l?{data:l}:{},...I?{purchase:I}:{}},F));y.set(E,b);let P=()=>{y.get(E)===b&&y.delete(E)};return b.then(P,P),b.then(k=>structuredClone(k))},resume(l=o.view?.pendingRequest?.requestId){return l?i.closeRequested?D.settle(l):i.pending?.requestId===l?N(s(i.pending)):N(s({operation:"resume",requestId:l})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(l){return N(s(l))},async retry(){if(i.closeFlight)return i.closeFlight;if(i.closing)return s(i.closing);if(i.closeRequested&&i.pending)return D.settle(i.pending.requestId);if(i.inFlight)return N(i.inFlight);if(!i.pending)throw new m("INVALID_REQUEST","No command is pending");let l=i.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let I=o.generation;if(await D.settle(l.requestId),o.assertCurrent(I),!i.pending)return D.get();if(i.pending!==l||i.closeRequested)throw new m("COMMAND_PENDING","The original quote is being recovered")}return N(s(l))},identify(l){let I=o.customerToken?void 0:t;v(),o.identify(l),t=I,d=null,r.reset()},get identitySignal(){return o.signal},subscribe:o.subscribe,reset:R};return tn(D,(l,I)=>N(s(l,I))),D}function po(e,t){return Zn({...e,runToken:"",initialResponse:t})}export{un as a,Cn as b,pe as c,On as d,sn as e,kn as f,_t as g,kt as h,Dt as i,fe as j,dn as k,X as l,Vn as m,$t as n,dr as o,pr as p,In as q,xe as r,hr as s,Qn as t,hn as u,H as v,an as w,Fn as x,Tr as y,te as z,Se as A,qr as B,jr as C,xn as D,Zn as E,po as F};
@@ -0,0 +1 @@
1
+ import{a as fn,c as pn,d as xt,f as At,g as mn,k as hn}from"./chunk-DXLBEXC6.js";import{b as et}from"./chunk-W32FI2A2.js";import{d as on,e as sn,f as ln,h as It,i as tt,j as cn,k as un,l as dn}from"./chunk-QAGK2SLZ.js";import{a as tn,c as Pt,d as nn,e as rn}from"./chunk-ADTZEBQF.js";import{a as Ze,b as ne,d as kt,f as Et,j as an}from"./chunk-OV46DXRX.js";import{b as ve}from"./chunk-M4P6TGBU.js";import{B as N,C as Xe,D as je,E as Oe,y as en}from"./chunk-GGZG56GR.js";import{r as Te,t as Ne}from"./chunk-QGKROSRD.js";import{i as Zt}from"./chunk-RRZZUIFM.js";import{c as he,j as Be}from"./chunk-RJT764B2.js";import{c as vt}from"./chunk-BKBWGPNR.js";import{a as k}from"./chunk-WE55LJEN.js";import{a as q}from"./chunk-DSPLGTQI.js";async function yn(V,i,E){if(!je(i))throw new k("INVALID_RESPONSE","A verified completed purchase is required");let O=V?Be.parse(V):null;if(await E.onComplete?.(i),!O||!E.check)return;let B=Be.parse(await E.check());if(B.internal_feature_id!==O.internal_feature_id||B.quantity!==O.quantity||O.observation!==void 0&&(B.observation===void 0||B.observation.requirementDigest!==O.observation.requirementDigest||B.observation.authority!==O.observation.authority||vt(B.observation.subject)!==vt(O.observation.subject)))throw new k("INVALID_RESPONSE","The access requirement changed");B.allowed&&await E.onAccessGranted?.(B)}function wn(V){return Object.entries(V.document.buttons).filter(([,i])=>i.type==="checkout"&&i.product.type==="fixed"&&!ve(i.product,{},V.capabilities)).map(([i])=>i)}function gn(V,i){let E=N(i)?void 0:i.lines[0];if(!N(i)&&(i.lines.length!==1||!E))return;let O=N(i)?i.productVersionId:E.productVersionId,{screen:B,buttons:re}=V.document,D=new Map(N(i)?Object.entries(i.featureQuantities??{}):(E?.prepaid??[]).map(g=>[g.internal_feature_id,g.quantity]));function ie(g,c){if(g.hidden)return!1;if(g.type==="plan_picker"&&V.capabilities.pickers[g.id]?.options.includes(O))return c[g.id]=O,!0;if(g.type==="quantity_picker"){let ee=D.get(g.internalFeatureId);return ee!==void 0&&(!g.bind?.plan||g.bind.plan===O)&&(c[g.id]=ee),!1}if(g.type==="button"&&g.action){let ee=re[g.action];return ee?.type==="checkout"&&ee.product.type==="fixed"&&ee.product.productVersionId===O}if(g.type!=="stack")return!1;let Z=g.interaction,a=g.bind?.plan===O;for(let[ee,p]of g.children.entries()){let ae={},U=ie(p,ae);if(Z?.type==="toggle"||Z?.type==="tabs"){if(!U)continue;return c[g.id]=Z.type==="toggle"?ee===0:p.id,Object.assign(c,ae),!0}Object.assign(c,ae),U&&(a=!0,Z?.type==="select"&&Z.purpose==="product"&&Z.pickerId&&p.type==="stack"&&p.bind?.plan===O&&(c[g.id]=p.id,c[Z.pickerId]=O))}return a}for(let g of B.pages){let c={__page:g.id};if(ie(g.root,c))return c}}async function ir(V,i,E){let O=i.focusAtReveal?()=>{}:It(V.ownerDocument),B=()=>{D.finish("dismissed"),O()},re=()=>B(),D=cn(V,i,"paywall",()=>{B(),q(i.onDismiss)},fn);i.signal?.throwIfAborted(),i.signal?.addEventListener("abort",re,{once:!0});let ie=null,g,c,Z;try{if(D.start(!0,i.loadingDocument?.screen.strings.defaultLocale,i.loadingDocument??null),D.cancelled)throw new DOMException("Presentation cancelled","AbortError");if(ie=i.check?Be.parse(await D.wait(i.check(),tt)):null,ie?.allowed)return D.finish("skipped"),i.signal?.removeEventListener("abort",re),O(),await i.onAccessGranted?.(ie),{check:ie,host:null};let[e,t]=await Promise.allSettled([D.wait(import("./screen-renderer-CMFJVI36.js")),D.wait(i.start().then(r=>(D.cancelled&&r.destroy(),r)),tt)]);if(e.status==="rejected")throw t.status==="fulfilled"&&t.value.destroy(),e.reason;if(t.status==="rejected")throw t.reason;Z=e.value,g=t.value,i.signal?.throwIfAborted(),g.signal?.throwIfAborted(),g.signal?.addEventListener("abort",re,{once:!0});let n=g.view??await D.wait(g.refresh(),tt);if(!n)throw new k("INVALID_RESPONSE","Paywall presentation is missing");g.signal?.throwIfAborted(),c=n}catch(e){throw D.finish("error",e),E?.retainedDialog?.release(),i.signal?.removeEventListener("abort",re),g?.signal?.removeEventListener("abort",re),g?.destroy(),O(),e}let a=g,{mountScreenPreview:ee}=Z,p=V.ownerDocument,ae=new AbortController,U=p.createElement("section"),de=p.createElement("div"),te=p.createElement("div"),nt=i.mountControls,J=nt?p.createElement("div"):void 0,d=p.createElement("p"),w=p.createElement("button"),oe=p.createElement("button"),T=p.createElement("button"),Pe=E?.retainedDialog,I=Pe?.dialog??p.createElement("dialog"),rt=a.locale||c.document.screen.strings.defaultLocale,o=rt.toLowerCase().startsWith("zh"),bn=o?"正在处理…":"Processing…",Cn=o?"正在准备报价…":"Preparing your price…",M=pn(c.document.screen.theme);U.dataset.indianaPaywall="",U.setAttribute("aria-label",c.document.name),U.style.cssText=M.root,te.style.cssText=M.controls,d.style.cssText=M.message,d.setAttribute("role","status"),T.style.cssText=M.link,T.textContent=o?"关闭":"Close",w.style.cssText=M.secondary,w.textContent=o?"重试":"Retry",w.hidden=!0,oe.type="button",oe.style.cssText=M.primary,oe.textContent=o?"继续付款":"Continue payment",oe.hidden=!0,te.append(d,oe,w,T),J&&(J.style.cssText="flex:1 0 100%;min-width:0",J.hidden=!0,te.prepend(J)),U.append(de,te);let it=()=>{if(J){let r=!J.childElementCount&&!J.textContent?.trim();J.hidden!==r&&(J.hidden=r)}let e=pe??te,t=[...e.children].every(r=>r===d?!d.textContent:r.hidden),n=[...e.children].some(r=>r===T?!1:r===d?!!d.textContent:!r.hidden);e.style.cssText=t?M.controls.replace(/padding:[^;]+/,"padding:0"):n?`${M.controls};${M.pinned}`:M.controls,ot()},Rt=typeof MutationObserver>"u"?void 0:new MutationObserver(it);Rt?.observe(U,{attributes:!0,attributeFilter:["hidden"],characterData:!0,childList:!0,subtree:!0});let Fe=Pe&&c.document.presentation.type==="inline"?{type:"modal",size:"md"}:c.document.presentation,vn=Object.entries(c.document.buttons).filter(([,e])=>e.type==="close").map(([e])=>e),$,St,De=!1,Ot=JSON.stringify(c.capabilities),j;function ye(e){let t=wn(e);if(j||fe&&!ue||G&&C)return Ue(e).map(({actionId:r})=>r);if(dt()||!C&&Ge())return t;let n=C?_t(e):Mt(e);return[...new Set([...t,...Ue(e).map(({actionId:r})=>r).filter(r=>!n.includes(r))])]}function Le(e){if(b)return;let t=c.id!==e.id;c=e;let n=JSON.stringify(e.capabilities);if(t||n!==Ot){let r=!P&&!a.quote&&!a.operation?Ze(e,W,Nt):W;t||JSON.stringify(r)!==JSON.stringify(W)?(W=r,$?.update(e.document.screen,rt,{capabilities:ne(e),unavailableActions:ye(e),serverInput:{bindings:[],answers:{}},selection:W})):$?.updateCapabilities(ne(e),ye(e)),Ot=n}kn(e),ge()}let L,at=0;function ot(){let e=p.defaultView;if(!L?.responsive||!e)return;let t=pe??te,n=e.innerHeight-(L.type==="modal"?32:0);t.style.maxHeight=`${Math.max(1,n)}px`,t.style.overflowY="auto",t.style.flexShrink="0",at=Math.max(1,n-t.getBoundingClientRect().height),$?.resizeViewport?.(at,e.innerWidth)}let b=!1,fe=!1,P=null,st,qe=!1,Tt=!1,we=!1,lt,ct=!1,se,pe;function Pn(){return fe||b||se||ct?{type:"recover",operationId:a.operation?.operationId??a.quote?.operationId??null,requestId:null}:Pt(a)}let x=()=>!b&&!qe&&!se&&i.canInteract?.()!==!1,z,ke=!1,Ee=!1,u=null,le=null,We="",ce=()=>i.checkoutNavigation==="after_confirmation"&&!!(i.terminateCheckout||i.resumeCheckout),W={},Nt=new Set,ue,C;function ut(e){return!!e&&N(e)&&e.timing==="immediate"&&e.execution.provider==="merchant"}let Dt=o?"正在确认付款…":"Confirming payment…",G=null,Lt=!1,Ge=()=>i.allowNewPurchase!==!1||Lt;function Ue(e){return Object.entries(e.document.buttons).flatMap(([t,n])=>n.type==="checkout"?[{actionId:t,policy:n}]:[])}function Ut(e){let t=C?.quote;return t?Ue(e).filter(({actionId:n,policy:r})=>Ie(t,e,n,r.product,W)).map(({actionId:n})=>n):[]}function _t(e){return C?.phase==="payment"?Ut(e):[]}function dt(){return C?.phase==="payment"&&(Ge()||!!i.prepareUpgradeReplacement)&&ce()&&!!i.terminateCheckout&&!!a.operation&&A(a.operation).type==="checkout"}function Mt(e){let t=a.quote;return!ce()||G||!t||!a.operation||A(a.operation).type!=="checkout"?[]:Ue(e).filter(({actionId:n,policy:r})=>Ie(t,e,n,r.product,W)).map(({actionId:n})=>n)}function ge(){let e=j?[]:C?_t(c):Mt(c),t=i.allowNewPurchase===!1&&!!a.operation&&A(a.operation).type==="checkout";if(oe.hidden=!!j||(C?C.phase!=="payment":!t)||e.length>0,!ce()&&!C||!$?.updateCheckoutControls)return;let n=!j&&C?.phase==="checking"?ue:void 0;$.updateCheckoutControls({actions:Ue(c).map(({actionId:r})=>r),resume:n?[n]:e,resumeLabel:n?Dt:o?"继续付款":C?"Continue payment":"Continue checkout",busy:ue})}function Vt(){le?.remove(),le=null}async function ze(){if(G)return;if(i.resumeCheckout&&a.operation){await i.resumeCheckout(a.operation.operationId);return}let e=await a.read();if(A(e).type!=="checkout")return H(e,!1);x()&&(_e.delete(e.operationId),await Me(e))}function $t(){d.textContent=o?"暂时无法打开付款页面。请重试。":"Couldn’t open checkout. Try again.",w.hidden=!0}async function ft(e=!1){let t=G;if(!t)return;C&&(u=()=>ft(),w.textContent=o?"查询状态":"Check status"),w.hidden=!0;let n=Date.now()+2e4;for(;x();){let r=await a.read();if(r.operationId!==t.operationId)throw new k("PURCHASE_PENDING","The original Checkout changed");if(!x())break;let l=A(r);if(l.type==="native"){if(C&&!Ge()&&i.prepareUpgradeReplacement){let m=await i.prepareUpgradeReplacement(t.operationId,t.intent);if(!x())return;Lt=!0,Le(m)}G=null,C&&xe(C.quote),Vt(),P=t.selection,z=t.coupon,ke=!1,Ee=!1,await Qe();return}if(l.type==="complete"||l.type==="fulfillment"||l.type==="recording"){G=null,C?await be(C.quote,r):await H(r,!1);return}if(e&&l.type==="checkout"){e=!1;try{await i.terminateCheckout(t.operationId)}catch(m){q(i.onError,m)}}if(Date.now()>=n){C&&l.type==="checkout"&&(G=null,await be(C.quote,r));break}await et(1e3,p,ae.signal)}!G||b||(C?(d.textContent=o?"仍在核对原升级单,暂时无法更换套餐。":"We’re still checking the original upgrade before changing plans.",w.hidden=!1):$t())}async function Qt(e,t,n,r){if(u=()=>Qt(e,t,n,r),await i.beforeCheckoutReplacement?.(structuredClone(r)),!x())return;let l=a.operation;if(l?.operationId!==e||A(l).type!=="checkout"){u=null,l&&await H(l,!1);return}G={operationId:e,selection:t,coupon:n,intent:r},C&&(d.textContent=o?"正在切换套餐…":"Changing plan…",w.hidden=!0);let m=!1;try{await i.terminateCheckout(e)}catch(s){if(s instanceof k&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(s.code)){G=null,C&&(u=Ke,w.textContent=o?"查询状态":"Check status",w.hidden=!1),d.textContent=o?"请继续原订单,或等待它过期后再更换方案。":"Continue your original checkout, or wait for it to expire before changing plans.",q(i.onError,s);return}m=s instanceof k&&(s.status??0)>=500,q(i.onError,s)}x()&&await ft(m)}function pt(e,t,n,r,l){let m=ne(e).checkoutCoupons?.[t],s=m?m.products[n]:i.claimCoupon&&l?Zt(e.capabilities,l,r):void 0;return s?.couponId&&s.planVersionId===n?{id:s.couponId,offerId:s.offerId}:void 0}function kn(e){fe||P||a.quote||a.operation||We&&d.textContent===We||(d.textContent=Object.values(e.capabilities.plans).some(t=>t.available)?"":o?"当前账号暂无可购买的方案。":"No plans are currently available for this account.")}let _e=new Map,Ye=!1;function Ie(e,t,n,r,l,m){let s=N(e),h=!s&&e.lines.length===1?e.lines[0]:void 0,f=ve(r,l,t.capabilities);if(!f||f!==(s?e.productVersionId:h?.productVersionId))return!1;let R=pt(t,n,f,l,m),Y;try{Y=Ne(t.document.screen,f,l,t.capabilities)}catch{return!1}if(s){let K=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return Object.keys(Y).length===Object.keys(e.featureQuantities??{}).length&&Object.entries(Y).every(([Se,Ct])=>e.featureQuantities?.[Se]===Ct)&&(!R||K?.couponId===R.id&&(!R.offerId||K.grantId===R.offerId))}if((R||ne(t).checkoutCoupons?.[n])&&(R?.id??null)!==(e.discount?.couponId??null))return!1;let X=Object.fromEntries((h?.prepaid??[]).map(K=>[K.internal_feature_id,K.quantity]));return[...new Set([...Object.keys(Y),...Object.keys(X)])].every(K=>(Y[K]??0)===(X[K]??0))}let A=e=>tn({quote:a.quote,operation:e,requestId:null,pending:!1,destroyed:b,canReselect:a.canReselect});async function Me(e){let t=e.merchantExecution,n=A(e),r=n.type==="checkout"?n.checkoutUrl:e.checkoutUrl;if(!(!x()||!r||Xe(e)&&n.type!=="checkout"||i.checkoutNavigation==="after_confirmation"&&n.type!=="checkout"||t?.type==="purchase"&&!["not_started","pending"].includes(t.paymentStatus)||_e.get(e.operationId)===r)){_e.set(e.operationId,r);try{i.onCheckoutUrl?await i.onCheckoutUrl(r):p.defaultView?.location.assign(r)}catch(l){throw _e.delete(e.operationId),l}}}let me=(e,t=!1)=>{if(e instanceof kt)u=null,d.textContent=e.customerMessage(o);else if(mn(e))u=null,d.textContent=t?o?"当前无法在此购买,付款尚未开始。请联系商户。":"Purchases aren’t available here right now. Payment hasn’t started. Contact the merchant for help.":At(e,o);else if(t){let n=e instanceof k?e.code:void 0;n==="CAPABILITY_UNAVAILABLE"||n==="NOT_CONFIGURED"?(u=null,d.textContent=o?"暂时无法为此套餐报价,付款尚未开始。":"Pricing for this plan is unavailable. Payment hasn’t started."):a.canReselect===!0&&!P?d.textContent=o?"未能取得报价,付款尚未开始。请重新选择套餐。":"We couldn’t prepare your price. Payment hasn’t started. Choose a plan again.":n==="COMMAND_PENDING"?d.textContent=o?"仍在准备报价,请重试以查看结果。":"Your price is still being prepared. Retry to check the result.":d.textContent=o?"未能取得报价,付款尚未开始。请重试。":"We couldn’t prepare your price. Payment hasn’t started. Try again."}else d.textContent=e instanceof k&&(e.code==="NETWORK_ERROR"||e.code==="TIMEOUT")?At(e,o):e instanceof k?e.message:o?"操作未完成,请重试。":"This action couldn’t be completed. Try again.";w.hidden=u===null,We=d.textContent,t&&ue===void 0&&!L?.responsive&&d.scrollIntoView?.({block:"nearest"}),q(t&&E?.quoteError?E.quoteError:i.onError,e)},Ve=new WeakMap;function $e(e){fe=e,w.disabled=e,oe.disabled=e,$?.updateCapabilities?.(ne(c),ye(c));for(let t of le?.querySelectorAll("button")??[])e?(Ve.has(t)||Ve.set(t,t.disabled),t.disabled=!0):Ve.has(t)&&(t.disabled=Ve.get(t),Ve.delete(t)),xt(t)}function Ht(){j&&(d.textContent=j.message,w.textContent=o?"重试":"Retry",w.disabled=!1,w.hidden=!j.retry,oe.disabled=!0)}function mt(){d.textContent=o?"暂时无法操作,请稍后重试。":"This action is unavailable right now. Try again in a moment."}async function En(e){if(i.beforeAction)try{await i.beforeAction()}catch(t){throw t instanceof kt?(P=null,ke=!1,Ee=!1,u=null):u=e,t}}async function Q(e,t){if(fe||b||j)return;if(!x()){mt();return}let n=e===Qe,r=n?Cn:bn,l=ce()&&t!==void 0;ue=l?t:void 0,$e(!0),ge(),w.hidden=!0,d.textContent=l?"":r;try{if(e!==wt&&e!==Ke&&e!==ht&&e!==Ke&&(e!==ze||!i.resumeCheckout)&&await En(e),b||j)return;if(!x()){u=e,w.hidden=!1,mt();return}await e()}catch(m){b||me(m,n)}finally{ue=void 0,$e(!1),ge(),j?Ht():d.textContent===r&&(d.textContent="")}}async function Bt(e){await yn(ie,e,i)}function xe(e,t){C=t?{quote:e,phase:t}:void 0,t==="checking"?(ue??=P?.actionId??Ut(c)[0],d.textContent=Dt,u=Ke,w.textContent=o?"查询状态":"Check status",w.hidden=!0):ue=void 0,$?.updateCapabilities(ne(c),ye(c)),ge()}function jt(e){return e instanceof k&&(e.code==="COMMAND_PENDING"||e.reason==="RESULT_UNKNOWN"||e.code==="NETWORK_ERROR"||e.code==="TIMEOUT"||e.status===429||(e.status??0)>=500)}function Ft(e,t){Et(e,{...t,featureQuantities:t.featureQuantities??{}},"Purchase operation changed")}async function Ke(){C&&await be(C.quote)}async function be(e,t){xe(e,"checking"),We="";let n=1e3;De=!0,q(i.onObservationChange,!0);try{for(let r=t;x();r=void 0){if(!r){try{r=await a.read()}catch(l){if(!jt(l))throw l}if(!x())return}if(r){Ft(r,e);let l=A(r);if(l.type==="checkout"){xe(e,"payment"),d.textContent=o?"请先完成原订单的付款。":"Finish paying for this upgrade.",w.hidden=!1;return}if(l.type==="complete"){xe(e,"complete"),u=null;let m=c.capabilities.plans[e.productVersionId]?.name,s=e.merchantTerms?.subscriptionTerms?.items,h=s?.length===1?s[0].interval:void 0,f=h==="year"?o?"年付":"annual billing":h==="month"?o?"月付":"monthly billing":null;d.textContent=m?o?`已升级到 ${m}${f?" "+f:""}。`:`Upgraded to ${m}${f?" ("+f+")":""}.`:o?"已成功升级。":"Plan upgraded.",await Bt(r);return}if(l.type==="native"&&!Oe(r)){xe(e),P=null,u=null,d.textContent=o?"付款未完成,请重新选择套餐。":"Payment failed. Choose a plan to start again.",w.textContent=o?"重试":"Retry";return}if(r.problem&&!["RESULT_UNKNOWN","STATE_CHANGED"].includes(r.problem.reason??""))throw new k(r.problem.code,o?"暂时无法完成升级。":"The upgrade needs attention.",void 0,void 0,r.problem)}await et(n,p,ae.signal),n=Math.min(n*1.5,15e3)}}finally{De=!1,q(i.onObservationChange,!1)}}async function ht(){let e=C?.quote;if(!e)return;let t=await a.read();if(Ft(t,e),A(t).type!=="checkout")return be(e,t);if(i.resumeCheckout){await i.resumeCheckout(t.operationId);return}_e.delete(t.operationId),await Me(t)}function qt(e){return Pt(a).type==="recording"||A(e).type==="recording"}function Wt(e){let t=e.merchantTerms,n=t?.subscriptionTerms?.items??[],r=t?t.totalMinor:N(e)?e.totalMinor:e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),l=t?n.length===1&&n[0]?.amountMinor===r&&n[0]:!N(e)&&e.lines.length===1&&e.lines[0]?.catalogAmountMinor===r&&e.lines[0],m=r===null?he(t.subtotalMinor-t.discountMinor,e.currency)+(o?" + 待确认税费":" + tax confirmed at checkout"):he(r,e.currency)+(l?Te(l.interval,o?"zh-CN":"en",l.intervalCount??1):""),s=N(e)?a.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(h=>h.productName).join(", ");return{label:s?`${s} · ${m}`:m,recurring:l}}async function H(e,t=i.checkoutNavigation!=="after_confirmation"){if(b)return;if(!x()){u=async()=>H(await a.read()),w.hidden=!1;return}let n=e.quote??a.quote;if(ut(n)&&(e.confirmedAt||e.merchantExecution))return be(n,e);if(d.textContent=hn(e.status,o),qt(e)){let f=e.merchantExecution?.recordingStatus==="failed";d.textContent=f?o?"付款和商户处理已完成,但交易记录失败。请联系商户修复,勿重复购买。":"Payment and fulfillment succeeded, but recording failed. Contact the merchant to repair this purchase; do not buy again.":o?"付款和商户处理已完成,正在确认交易记录。请勿重复购买。":"Payment and merchant fulfillment are complete. Recording is pending confirmation; do not purchase again.",w.textContent=o?"查询记录":"Check recording",u=async()=>H(await a.read()),w.hidden=!1;return}if(e.problem&&A(e).type!=="native"){let f=e.problem;u=Ae,w.textContent=o?"检查并恢复原操作":"Check and recover original purchase",me(new k(f.code,f.reason==="RESULT_UNKNOWN"?o?"付款结果尚未确定,请恢复原操作,暂勿重复购买。":"The payment result is unknown. Recover the original purchase before buying again.":f.phase==="fulfillment"?o?"付款已记录,商户权益处理需要核对。":"Payment was recorded. Access fulfillment needs attention.":f.code==="CAPABILITY_UNAVAILABLE"?o?"商户尚不支持本次购买所需的完整能力,请处理后恢复原操作。":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":f.code==="NOT_CONFIGURED"?o?"付款服务连接需要处理,请联系商户后恢复原操作。":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":o?"原购买操作需要处理,请查询或恢复此操作。":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,f));return}if((e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"||e.merchantExecution?.type==="subscription_change"&&e.merchantExecution.status==="applied")&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(d.textContent=o?"付款已记录,正在等待商户完成处理。":"Payment was recorded. Waiting for merchant fulfillment."),je(e)&&A(e).type==="complete"){u=null,await Bt(e);return}if(!Oe(e)&&A(e).type!=="fulfillment"){if(a.canReselect===!1){d.textContent=o?"正在核对原购买结果":"Checking the original purchase result",w.textContent=o?"查询结果":"Check result",u=async()=>H(await a.read()),w.hidden=!1;return}e.status==="cancelled"?d.textContent=o?"这笔购买已取消,可以重新选择方案。":"This purchase was cancelled. Choose a plan to start again.":e.status==="failed"&&(d.textContent=o?"这笔购买未能完成,可以重新选择方案。":"This purchase didn’t go through. Choose a plan to try again."),w.textContent=o?"重试":"Retry",u=null,P=null;return}if(!t&&A(e).type==="checkout"){if(G){$t();return}if(ce()){d.textContent="",Ye=!1,i.allowNewPurchase===!1?Gt():u=null,$?.updateCapabilities?.(ne(c),ye(c)),ge();return}let f=a.quote,R=f?.operationId===e.operationId?Wt(f).label:"";d.textContent=Ye?R?o?`${R} 尚未付款。再次选择该方案即可继续付款。`:`${R} is still unpaid. Choose it again to continue paying.`:o?"之前的购买尚未付款。再次选择该方案即可继续付款。":"Your earlier purchase is still unpaid. Choose that plan again to continue paying.":"",Ye=!1,u=null;return}await Me(e);let r=Date.now(),l=r+6e5,m=2e3,s=A(e).type!=="checkout",h=()=>s&&Date.now()-r<15e3;De=!0,q(i.onObservationChange,!0);try{for(;!b&&Date.now()<l;){if(await et(h()?700:m,p,ae.signal),b)return;if(!x()){u=async()=>H(await a.read()),w.hidden=!1;return}let f=await a.read();if(A(f).type==="checkout"&&(s=!1),!t&&A(f).type==="checkout"){await H(f,!1);return}if(!f.problem&&Oe(f)&&await Me(f),!Oe(f)||f.problem||qt(f)){await H(f);return}h()||(m=Math.min(m*1.5,3e4))}}finally{De=!1,q(i.onObservationChange,!1)}u=async()=>H(await a.read()),w.hidden=!1}async function yt(e=!1){let t=await a.read();if(b)return;if(!x()){u=()=>yt(e),w.hidden=!1;return}let n=a.quote;if(n&&Et(t,{operationId:n.operationId,currency:n.currency},"The original purchase operation changed"),n&&(Xe(t)?["prepared","quoted"].includes(t.status):t.status==="pending")&&(Xe(t)||t.quoteFinalized===!1)&&!t.confirmedAt&&!t.checkoutUrl&&!("nativePurchase"in t&&t.nativePurchase)&&!t.merchantExecution&&!t.problem&&!a.pendingCancellation){if(i.purchaseConfirmation!=="paywall"){e?await Ae():u=null;return}setTimeout(zt,0,n);return}await H(t,e||void 0)}function Gt(){u=wt,w.textContent=o?"查询状态":"Check status",w.hidden=!1}async function wt(){await yt()}async function Ae(){if(a.quote&&!(Date.parse(a.quote.expiresAt)>Date.now()))throw new k("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");Vt();let e=a.quote;if(ut(e)){xe(e,"checking");let n;try{n=await a.confirm()}catch(r){if(!jt(r))throw r;return be(e)}return be(e,n)}u=Ae;let t=await a.confirm();if(!x()){u=Ae,w.hidden=!1;return}if(t.problem){await H(t);return}if(Oe(t)){if(A(t).type==="checkout")await Me(t);else if(t.execution&&t.execution.provider!=="merchant"||"nativePurchase"in t&&t.nativePurchase){if(!i.onPurchase)throw new k("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await i.onPurchase({operation:t,signal:ae.signal})}}u=async()=>H(await a.read()),await H(t,!0)}function zt(e){if(b)return;le?.remove();let t=!(Date.parse(e.expiresAt)>Date.now());d.textContent=t?o?"此报价已过期。请先取消,再重新选择。":"This quote has expired. Cancel it, then choose again.":"";let n=p.createElement("div"),r=p.createElement("button"),l=p.createElement("button"),m=p.createElement("div"),s=p.createElement("p"),h=e.merchantTerms,f=o?"zh-CN":"en",R=h?.subscriptionTerms?.items??[],Y=h?h.subscriptionTerms?.trial?.days:N(e)?void 0:e.lines.find(y=>y.trial)?.trial?.days,X=N(e)?h?h.totalMinor:e.totalMinor:Y===void 0?null:h?h.totalMinor:e.charge?e.charge.totalMinor:e.lines.every(y=>y.trial)?0:null,Re=(y,v)=>o?`${v} 天试用结束后 ${y}`:`Then ${y} after the ${v}-day trial`,{label:K,recurring:Se}=Wt(e),Ct=N(e)?a.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(y=>y.productName).join(", "),Jt=X===null?"":`${o?"今天应付":"Due today"} ${he(X,e.currency)}`;s.textContent=Jt?[Ct,Jt].filter(Boolean).join(" · "):K,r.textContent=N(e)?o?"确认变更":"Confirm change":o?"确认购买":"Confirm purchase",r.disabled=t,l.textContent=o?"取消":"Cancel",n.style.cssText=M.panel,s.style.cssText=M.summary,m.style.cssText=M.actions,r.style.cssText=M.primary,l.style.cssText=M.secondary,xt(r),r.onclick=()=>{Q(Ae)};let Xt=async()=>{let y=await a.cancel();b||(n.remove(),le=null,await H(y))};l.onclick=()=>{u=Xt,Q(Xt)};let F=p.createElement("div");if(F.style.cssText=M.terms,N(e)){for(let[v,S]of Object.entries(e.featureQuantities??{})){let _=a.view?.capabilities.plans[e.productVersionId]?.prepaid?.find(In=>In.internalFeatureId===v),Je=p.createElement("p");Je.textContent=`${_?.name??v} · ${S} ${o?"份":"packs"}${_?` × ${_.terms.units}`:""}`,F.append(Je)}for(let[v,S]of[[o?"原订阅抵扣":"Unused subscription credit",e.creditMinor],[o?"新套餐费用":"New plan charge",e.debitMinor],[o?"优惠减免":"Offer savings",h?.discountMinor??e.discountMinor],[o?"税费":"Tax",h?h.taxMinor:e.taxMinor]]){let _=p.createElement("p");_.textContent=`${v}: ${S===null?o?"结账时确认":"Confirmed at checkout":he(S,e.currency)}`,F.append(_)}let y=p.createElement("p");y.textContent=`${o?"生效时间":"Effective"}: ${e.effectiveAt}`,F.append(y)}if(h){for(let v of R){if(X===null&&v===Se)continue;let S=p.createElement("p"),_=he(v.amountMinor,e.currency)+Te(v.interval,f,v.intervalCount);S.textContent=X!==null&&Y!==void 0?Re(_,Y):_,v.amountAfterOfferMinor!==void 0&&(S.textContent+=` · ${o?"优惠结束后":"After the offer"} ${he(v.amountAfterOfferMinor,e.currency)}${Te(v.interval,f,v.intervalCount)}`),F.append(S)}let y=h.subscriptionTerms?.trial;if(y){let v=p.createElement("p");v.textContent=o?`试用 ${y.days} 天;${y.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${y.days}; ${y.cardRequired?"a payment method is required":"no payment method is required"}`,F.append(v)}for(let v of[...h.expectedEffects.map(S=>S.description),...h.requiredConsents.map(S=>S.summary)]){let S=p.createElement("p");S.textContent=v,F.append(S)}}else if(!N(e)){for(let y of e.lines){if(X!==null||y!==Se){let v=p.createElement("p"),S=`${he(y.catalogAmountMinor,e.currency)}${Te(y.interval,f,y.intervalCount??1)}`;v.textContent=X!==null&&y.trial?(e.lines.length>1?`${y.productName} · `:"")+Re(S,y.trial.days):`${y.productName} · ${S}`,F.append(v)}for(let v of y.prepaid??[]){let S=p.createElement("p"),_=a.view?.capabilities.plans[y.productVersionId]?.prepaid?.find(Je=>Je.internalFeatureId===v.internal_feature_id);S.textContent=`${_?.name??v.internal_feature_id} · ${v.quantity} ${o?"份":"packs"} × ${v.terms.units}`,_&&(S.textContent+=Te(_.reset==="week"||_.reset==="month"||_.reset==="year"?_.reset:"one_time",f,_.resetCount)),F.append(S)}if(y.trial){let v=p.createElement("p");v.textContent=o?`试用 ${y.trial.days} 天;${y.trial.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${y.trial.days}; ${y.trial.cardRequired?"a payment method is required":"no payment method is required"}`,F.append(v)}}if(!e.charge){let y=p.createElement("p");y.textContent=o?"目录价格;最终金额以结账时税费和试用规则为准。":"Catalog price; the final charge depends on checkout taxes and trial terms.",F.append(y)}}for(let y of F.children)y.style.margin="0";m.append(r,l),n.append(s,...F.childElementCount?[F]:[],m),te.prepend(n),L?.responsive||n.scrollIntoView?.({block:"nearest"}),r.focus({preventScroll:!0}),le=n,fe&&$e(!0),u=null}async function Qe(){if(!P)return;if(u=Qe,!ke){let n=a.view,r=n?.document.buttons[P.actionId],l=n&&r?.type==="checkout"?ve(r.product,P.selection,n.capabilities):null;if(!n||!l)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");if(!Ee){let s=await i.resolveSubscriptionChange?.({actionId:P.actionId,productVersionId:l,featureQuantities:Ne(n.document.screen,l,P.selection,n.capabilities)});if(b)return;s!==void 0&&(P.subscriptionChange=en.parse(s)),Ee=!0}let m=z?.offerId;if(z&&!m){if(!i.claimCoupon)throw new k("CAPABILITY_UNAVAILABLE","Coupon claiming is unavailable");let{offer:s}=await i.claimCoupon(z.id,P.requestId);if(b)return;if(!s||s.couponId!==z.id||s.status!=="issued"||!(Date.parse(s.expiresAt)>Date.now()))throw P=null,z=void 0,u=async()=>{Le(await a.refresh()),u=null},new k("COUPON_UNAVAILABLE","This Coupon is no longer available for this purchase");m=s.id}if(!z&&!n.document.screen.actions.some(s=>s.id===P?.actionId&&typeof s.properties.couponBinding=="string")&&(m=await i.resolveOfferId?.({actionId:P.actionId,productVersionId:l,featureQuantities:Ne(n.document.screen,l,P.selection,n.capabilities)})),b)return;m!==void 0&&(P.offerId=m),ke=!0}if(!x()){w.hidden=!1;return}let e;try{e=await a.preview(P)}catch(n){throw a.canReselect===!0&&(P=null,ke=!1,Ee=!1,z=void 0,u=null),n}if(z&&(N(e)?(()=>{let n=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return n?.couponId!==z.id||n.grantId!==P.offerId})():e.discount?.couponId!==z.id||e.discount.offerId!==P.offerId))throw new k("INVALID_RESPONSE","The quote did not apply the Coupon selected on this Paywall");if(b)return;let t=e.merchantTerms;if(i.purchaseConfirmation!=="paywall"||i.confirmOnHostedCheckout&&x()&&!N(e)&&e.provider==="merchant"&&e.billingSubscriptionId===null&&t?.request.action==="purchase"&&t.request.mode==="subscription"&&t.subscriptionTerms?.trial===null&&t.requiredConsents.length===0&&Date.parse(e.expiresAt)>Date.now()){if(!x()){w.hidden=!1;return}if(!(Date.parse(e.expiresAt)>Date.now()))throw new k("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");let n=ue?"":o?"正在打开收银台…":"Opening checkout…";d.textContent=n;try{await Ae()}catch(r){b||me(r)}finally{d.textContent===n&&(d.textContent="")}return}zt(e)}function Ce(e="destroy",t=!1){if(b)return;b=!0;let n=st;st=void 0,q(n),i.signal?.removeEventListener("abort",re),a.signal?.removeEventListener("abort",re),D.finish("dismissed"),St?.(),ae.abort(),Rt?.disconnect(),$?.destroy(),a.destroy(),I.removeEventListener("cancel",Kt),T.remove(),U.remove(),t||Yt(),e==="dismiss"&&q(i.onDismiss)}function Yt(){if(L?.destroy(),Pe){Pe.release();return}I.open&&I.close(),I.remove(),O()}B=Ce;async function He(){if(!we||b||qe||se==="closing"||!se&&!x())return;if(!E){Ce("dismiss");return}let e=p.createElement("p");e.setAttribute("role","status"),e.textContent=o?"正在关闭…":"Closing…",pe||(pe=p.createElement("div"),pe.style.cssText=te.style.cssText,te.replaceWith(pe),de.inert=!0),T.hidden=!1,pe.replaceChildren(e,T),se="closing",T.setAttribute("aria-disabled","true"),T.focus({preventScroll:!0});try{await E.dismiss()}catch(t){b||q(i.onError,t)}b||(se="retry",e.textContent=o?"未能确认关闭,请重试。":"Could not confirm closure. Try again.",T.textContent=o?"重试关闭":"Retry closing",T.removeAttribute("aria-label"),T.removeAttribute("aria-disabled"))}T.onclick=()=>{He()};function Kt(e){e.preventDefault(),He()}I.addEventListener("cancel",Kt),oe.onclick=()=>{Q(C?ht:ze)},w.onclick=()=>{if(j){j.retry?.();return}u&&Q(u)};function gt(e){D.finish("error",e),Ce()}function bt(){if(!(!Tt||we||b||qe||L&&!x()))try{let e=t=>{i.focusAtReveal&&(O=It(p)),$?.setHidden?.(!1),lt?.(),L&&(I.open||I.showModal(),L.responsive&&I.focus({preventScroll:!0}),!t&&i.loading!=="host"&&sn(I,L.type,L.responsive)),t&&i.loading!=="host"&&typeof de.animate=="function"&&!p.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches&&de.animate([{opacity:.55},{opacity:1}],{duration:160,easing:"ease-out"}),we=!0};E?E.present(t=>D.present(n=>e(t??n))):D.present(e)}catch(e){gt(e),me(e)}}try{if(Fe.type==="inline"?(it(),lt=dn(U,V),V.append(U)):(I.setAttribute("aria-label",c.document.name),T.textContent="×",T.setAttribute("aria-label",o?"关闭":"Close"),ln(T,c.document.screen.theme),T.hidden=an(c.document),(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&E?.retainedContent?E.retainedContent.append(T,U):I.replaceChildren(T,U),Pe||V.append(I),L=on(I,{...c.document.screen,presentation:Fe},ot),L.latch(),L.responsive&&(U.style.display="flex",U.style.flexDirection="column",U.style.maxHeight="100%",de.style.overflow="clip",de.style.minHeight="0"),Pe||(lt=un(I))),nt&&J){let n=nt(J);if(typeof n=="function"&&(b?q(n):st=n),b)throw new DOMException("Presentation cancelled","AbortError");it()}$=ee(de,{mode:"live",loadingLayout:()=>D.getLoadingLayout?.()??E?.loadingLayout?.(),rendererUrl:"bundled",title:c.document.name,closeActions:vn,onAuthoredClose(n){se||b||(T.hidden=n)},hostPresentation:()=>L?.type??Fe.type,reportContentHeight:L?.responsive,onResize:n=>{if(!L?.responsive)return;let r=Math.min(n,at);de.style.height=`${r}px`,L.setContentHeight(r+(pe??te).getBoundingClientRect().height)},onSelection(n){for(let[r,l]of Object.entries(n))typeof l=="number"&&typeof W[r]=="number"&&W[r]!==l&&Nt.add(r);W=n,ge()},onAction(n,r={},l,m){if(!we||b||se)return;let s=a.view,h=s?.document.buttons[n];if(!h)return;if(j){h.type==="close"&&He();return}if(h.type==="close"&&E&&i.resumeCheckout&&a.operation&&nn(A(a.operation))){He();return}if(fe)return;if(!x()){mt();return}if(h.type==="close"){Q(async()=>{E?.closeAction?await E.closeAction(n):await i.onAction?.(n),Ce(i.onAction?"action":"dismiss")});return}if(h.type==="action"){u=async()=>{if(h.action.type==="event"){if(!i.onEvent)throw new k("EVENT_HANDLER_REQUIRED","Provide the event handler");await i.onEvent(h.action.event)}else i.onOpenUrl?await i.onOpenUrl(h.action.url):p.defaultView?.location.assign(h.action.url);await i.onAction?.(n),u=null},Q(u);return}if(ce()&&G){G.selection.actionId===n&&Q(()=>ft(!0),n);return}if(C){if(C.phase==="payment"&&s&&Ie(C.quote,s,n,h.product,r,m)){Q(ht,n);return}if(!dt())return}if(!Ge()&&!dt()){ce()&&s&&a.quote&&a.operation&&A(a.operation).type==="checkout"&&Ie(a.quote,s,n,h.product,r,m)?Q(ze,n):d.textContent=o?"当前只能继续原订单。":"Only your original checkout is available.";return}if(le&&a.canReselect===!1){d.textContent=o?"请先确认或取消当前购买。":"Confirm or cancel the current purchase first.",L?.responsive||le.scrollIntoView?.({block:"nearest"}),le.querySelector("button")?.focus({preventScroll:!0});return}if(ce()&&i.terminateCheckout&&s&&a.quote&&a.operation&&a.canReselect===!1&&A(a.operation).type==="checkout"){if(Ie(a.quote,s,n,h.product,r,m)){Q(ze,n);return}let R=ve(h.product,r,s.capabilities),Y;try{if(!R)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");Y=Ne(s.document.screen,R,r,s.capabilities)}catch(Se){me(Se);return}let X=a.operation.operationId,Re={actionId:n,requestId:crypto.randomUUID(),selection:structuredClone(r)},K=pt(s,n,R,r,m);Q(()=>Qt(X,Re,K,{actionId:n,productVersionId:R,selection:Re.selection,featureQuantities:Y}),n);return}if((a.quote||P)&&a.canReselect===!1){let R=!!s&&!!a.quote&&Ie(a.quote,s,n,h.product,r,m);Ye=!!a.quote&&!R,u=a.quote?()=>yt(R):Qe,Q(u);return}let f=s&&ve(h.product,r,s.capabilities);if(!s||!f){me(new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(i.onPurchaseIntent){u=null,Q(async()=>{let R={actionId:n,productVersionId:f,selection:structuredClone(r),featureQuantities:Ne(s.document.screen,f,r,s.capabilities)};ct=!0,await i.onPurchaseIntent(R)});return}if(P&&P.actionId!==n){me(new k("COMMAND_PENDING","Finish the current purchase"));return}P||(z=pt(s,n,f,r,m),P={requestId:crypto.randomUUID(),actionId:n,selection:structuredClone(r)},ke=!1,Ee=!1),Q(Qe,n)},onEscape:()=>{He()},onError:n=>{let r=new Error(n);!we&&!b&&gt(r),me(r)},onRendered:n=>{n&&I.setAttribute("aria-label",n),Tt=!0,bt()}}),$.setHidden?.(!0),ot();let e=ce()&&!!a.quote&&!!a.operation&&A(a.operation).type==="checkout";W=a.quote?gn(c,a.quote)??Ze(c,{}):Ze(c,{}),$.update(c.document.screen,rt,{capabilities:ne(c),unavailableActions:ye(c),serverInput:{bindings:[],answers:{}},...Object.keys(W).length?{selection:W}:{}}),St=a.subscribe?.(Le),Le(a.view??c),await D.wait($.ready);let t=a.operation;(!e||ut(a.quote))&&(a.quote||t&&(t.confirmedAt||t.checkoutUrl||je(t)))?(u=wt,Q(u)):e&&i.allowNewPurchase===!1&&Gt()}catch(e){throw gt(e),e}return{check:ie,host:{get currentResolution(){return c},setPurchaseRecovery(e,t){j={message:e,retry:t},$?.updateCapabilities?.(ne(c),ye(c)),ge(),Ht()},get subscriptionUpgradeActive(){return C!==void 0},get observing(){return De},get recovery(){return Pn()},async prepareFallback(){if(fe||b||se||ct)return{type:"recover",operationId:a.operation?.operationId??a.quote?.operationId??null,requestId:null};$e(!0);try{let e=await rn(a);return e.type==="native"&&Ce(),e}finally{$e(!1)}},setSuspended(e){qe=e,U.hidden=e,e&&I.open?I.close():!e&&!we?bt():!e&&!b&&we&&Fe.type!=="inline"&&!I.open&&I.showModal()},destroy:Ce,retainPurchaseDialog(){if(!(b||!I.open||!I.isConnected))return Ce("destroy",!0),{dialog:I,release:Yt}},refresh:async()=>{if(!x()){if(a.view)return a.view;throw new k("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await a.refresh();return Le(e),bt(),e}}}}export{ir as a};