@tinkerlandai/longplay-sdk 0.10.72 → 0.10.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/dist/check-response-2VZGH33N.js +1 -0
- package/dist/{chunk-6TX2UFWN.js → chunk-2XTBFJN4.js} +1 -1
- package/dist/{chunk-XHJ33SCP.js → chunk-4DMVOAXB.js} +1 -1
- package/dist/{chunk-FU4XNGGP.js → chunk-4ZIA22MI.js} +1 -1
- package/dist/{chunk-WWEHYERC.js → chunk-724YT3J5.js} +1 -1
- package/dist/{chunk-MYYLRNLZ.js → chunk-7KQWJBFQ.js} +1 -1
- package/dist/chunk-7XQKSA4R.js +1 -0
- package/dist/{chunk-ANNZWFFN.js → chunk-AVXJB4O6.js} +1 -1
- package/dist/{chunk-HATZIRVQ.js → chunk-CN2INQIX.js} +1 -1
- package/dist/{chunk-FXRBRAJR.js → chunk-DCPRELJA.js} +1 -1
- package/dist/{chunk-FZSVLHCH.js → chunk-DKEQCWIR.js} +2 -2
- package/dist/{chunk-NSNEBNOM.js → chunk-E3DRXDDQ.js} +1 -1
- package/dist/{chunk-UFEILUGE.js → chunk-EK5U2JOM.js} +1 -1
- package/dist/{chunk-6DE2YAGZ.js → chunk-GNRFL6KF.js} +1 -1
- package/dist/{chunk-DRY3ZZCD.js → chunk-GWREHUOB.js} +1 -1
- package/dist/{chunk-UZAJOV75.js → chunk-H4RDA4MD.js} +1 -1
- package/dist/{chunk-EHWMZCNT.js → chunk-HLK7L2RV.js} +1 -1
- package/dist/{chunk-5MX7OICH.js → chunk-HQWZWHHM.js} +1 -1
- package/dist/{chunk-X3VCEYMU.js → chunk-JFQBHUUN.js} +1 -1
- package/dist/{chunk-WO6BLOJI.js → chunk-KLPRVDHS.js} +1 -1
- package/dist/{chunk-64TKCCJF.js → chunk-KWOB5LYC.js} +1 -1
- package/dist/{chunk-6OXRK7PK.js → chunk-LM6TMEMB.js} +1 -1
- package/dist/{chunk-EU4XNTEE.js → chunk-MCFHMWLX.js} +1 -1
- package/dist/{chunk-Y7CKOODV.js → chunk-MQ3543DO.js} +1 -1
- package/dist/{chunk-GACCPVPU.js → chunk-MSRPJSCY.js} +1 -1
- package/dist/{chunk-FXKZJP4T.js → chunk-NE64O6U6.js} +2 -2
- package/dist/{chunk-2UB5RFXZ.js → chunk-NPDRXDI7.js} +1 -1
- package/dist/{chunk-4MGLQ6UP.js → chunk-O273JQ7U.js} +1 -1
- package/dist/{chunk-JR56NRGI.js → chunk-OHPNHCQS.js} +1 -1
- package/dist/{chunk-K3GKANLZ.js → chunk-PHUD42K4.js} +1 -1
- package/dist/{chunk-ZQZFQHV4.js → chunk-PLXNTIX4.js} +1 -1
- package/dist/{chunk-C57G3LX4.js → chunk-QLUP7E5M.js} +1 -1
- package/dist/{chunk-2WINZC4O.js → chunk-SOUVNTG4.js} +1 -1
- package/dist/{chunk-JLDKGCU2.js → chunk-SSVSXSYE.js} +1 -1
- package/dist/{chunk-TQM2JVHJ.js → chunk-SUAUY6IF.js} +1 -1
- package/dist/{chunk-V6RXIFHI.js → chunk-SZPHTRYE.js} +1 -1
- package/dist/{chunk-L5IBJODQ.js → chunk-T3JVQBQT.js} +1 -1
- package/dist/{chunk-QPCIIQ6Q.js → chunk-TY4PJ2AG.js} +1 -1
- package/dist/{chunk-2DAYQCEC.js → chunk-UG5RBIWP.js} +1 -1
- package/dist/{chunk-G7QLMLCR.js → chunk-V53RJR3S.js} +1 -1
- package/dist/{chunk-3TKVWOFW.js → chunk-VVZLNTWC.js} +1 -1
- package/dist/chunk-VWVLWUBX.js +1 -0
- package/dist/{chunk-RHARJTIX.js → chunk-WG2DKREQ.js} +1 -1
- package/dist/{chunk-X6IKITFV.js → chunk-WX55MS2F.js} +1 -1
- package/dist/{chunk-5HDJT7E5.js → chunk-XJTEGBPR.js} +1 -1
- package/dist/{chunk-RPN7SE4S.js → chunk-XOX4O4A7.js} +1 -1
- package/dist/{chunk-K55XWFEI.js → chunk-Y4MFO2FU.js} +1 -1
- package/dist/chunk-ZUBDANL4.js +1 -0
- package/dist/{chunk-3DW3Q6RU.js → chunk-ZZ4X4DMO.js} +1 -1
- package/dist/{content-KUCHBKX6.js → content-RJTGQ5OG.js} +1 -1
- package/dist/funnel-host-purchase-HBKEI5SU.js +1 -0
- package/dist/funnel-host-recovery-paywall-FVRMHF6K.js +1 -0
- package/dist/{funnel-paywall-copies-WAX7Q2N4.js → funnel-paywall-copies-E7GHHCVL.js} +1 -1
- package/dist/funnel-paywall-prerender-BU4VSPDB.js +1 -0
- package/dist/funnel-route-prediction-6IXHGQYB.js +1 -0
- package/dist/funnel-route-source-CALCHIZL.js +1 -0
- package/dist/funnel-runtime-host-GF6XCCO3.js +1 -0
- package/dist/index.d.ts +4 -1
- package/dist/index.js +1 -1
- package/dist/merchant-bridge-contracts-2TYLNFKF.js +1 -0
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/operation-contracts-KYYM2PJO.js +1 -0
- package/dist/page.js +1 -1
- package/dist/paywall-KGICSTDM.js +1 -0
- package/dist/paywall-content-7NCG5I7S.js +1 -0
- package/dist/paywall-session-AEDGMP7W.js +1 -0
- package/dist/popup.d.ts +2 -1
- package/dist/popup.js +1 -1
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-AVHPHFXT.js +1 -0
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +10 -9
- package/dist/check-response-FTYRCENP.js +0 -1
- package/dist/chunk-2WMBBFPQ.js +0 -1
- package/dist/chunk-JT5RMCS6.js +0 -1
- package/dist/funnel-host-purchase-WMAKTI2H.js +0 -1
- package/dist/funnel-host-recovery-paywall-YMOYXK4D.js +0 -1
- package/dist/funnel-paywall-prerender-U5BVF7QG.js +0 -1
- package/dist/funnel-route-prediction-EKSGU3ZG.js +0 -1
- package/dist/funnel-route-source-AV45OI6M.js +0 -1
- package/dist/funnel-runtime-host-SCBNV4VB.js +0 -1
- package/dist/merchant-bridge-contracts-LPMJFG7V.js +0 -1
- package/dist/operation-contracts-YFZHNHKS.js +0 -1
- package/dist/paywall-BHPQH2ZJ.js +0 -1
- package/dist/paywall-content-WAUQRLBP.js +0 -1
- package/dist/paywall-session-I2YT3WUZ.js +0 -1
- package/dist/screen-renderer-4X5MLXGZ.js +0 -1
- /package/dist/{chunk-RTKI4V2J.js → chunk-35JZDDF3.js} +0 -0
- /package/dist/{chunk-FZSVLHCH.js.LEGAL.txt → chunk-DKEQCWIR.js.LEGAL.txt} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.10.73
|
|
4
|
+
|
|
5
|
+
- A purchase presentation whose Run has ended while its original Checkout is still unpaid no longer limits the Paywall to Continue checkout when it was opened with a Start and sells new purchases. Choosing another plan closes the original Checkout first, reads it back closed and unpaid, and only then quotes that plan with a new Run of the same Start (a fresh request) in the same rendered Paywall. A paid or settling original is shown instead. A recovery without a Start, or with `allowNewPurchase: false`, still offers only the original Checkout
|
|
6
|
+
- A Paywall rendered ahead of its click (a pre-render revealed by `open()`, such as a next Paywall or a host preview) appears settled: its entrance motion, every animation with an end, is finished at the reveal, so its plans show at once instead of arriving in sequence. Endless loops keep running, and a Paywall opened normally keeps its motion
|
|
7
|
+
|
|
3
8
|
## 0.10.72
|
|
4
9
|
|
|
5
10
|
- A Funnel footer that holds something for the Customer (an error, Retry, Back or History) stays in view in a dialog that sizes itself to its screen. When the screen's frame filled the viewport, as for a pre-rendered popup handed to the Funnel, the footer followed the frame out of view and the dialog showed only the empty room added for it, a blank band under the screen. The footer now sticks to the dialog's bottom edge in that room
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b}from"./chunk-PLXNTIX4.js";import"./chunk-XJTEGBPR.js";import"./chunk-7KQWJBFQ.js";import"./chunk-HLK7L2RV.js";import"./chunk-GNRFL6KF.js";import"./chunk-35JZDDF3.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{a as validateEntitlementCheck,b as validateResourceCheck};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as m,m as f,p as y}from"./chunk-
|
|
1
|
+
import{a as m,m as f,p as y}from"./chunk-SZPHTRYE.js";import{g as d}from"./chunk-NPDRXDI7.js";import{e as l,f as u,j as p}from"./chunk-XJTEGBPR.js";import{b as e}from"./chunk-35JZDDF3.js";var h={funnelId:e.uuid().optional(),funnelVersionId:e.uuid().optional()};var w=e.strictObject({runId:e.uuid(),bindingId:e.uuid(),receiptId:e.uuid()});var q=e.strictObject({processContext:w.optional(),...h,selector:e.discriminatedUnion("type",[e.strictObject({type:e.literal("paywall"),paywallId:e.uuid()}),e.strictObject({type:e.literal("version"),versionId:e.uuid()})]),customerId:e.uuid().optional(),commerce:l,locale:e.string().min(1).max(35),requirement:u.optional()}),c=e.strictObject({id:e.uuid(),paywallId:e.uuid(),version:e.number().int().positive(),document:m.omit({requirement:!0,offeringId:!0}),offering:e.strictObject({id:e.uuid()}),content:e.strictObject({environmentId:e.uuid(),offeringVersionId:e.uuid(),artifact:y.refine(n=>n.kind==="paywall"&&n.formatVersion===1)}).optional(),capabilities:d,check:p.nullable()}).superRefine((n,r)=>{let t=new Set(n.document.products.items.map(o=>o.productVersionId));(n.document.offeringVersionId!==n.offering.id||Object.values(n.capabilities.plans).some(o=>!t.has(o.versionId)))&&r.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),M=e.strictObject(c.shape).omit({document:!0,offering:!0}).extend({content:c.shape.content.unwrap()});function _(n,r){let t=f.parse(r);if(t.offeringVersionId!==n.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let o=structuredClone(n.capabilities);for(let[g,i]of Object.entries(t.catalog)){let a=o.plans[g],s=i.channels.stripe?.prices.find(I=>I.currency===a?.currency);a&&s&&Object.assign(a,{amountMinor:s.amountMinor,interval:i.interval,intervalCount:i.intervalCount,...i.prepaid?.length?{prepaid:i.prepaid}:{}})}return c.parse({...n,capabilities:o,document:{schemaVersion:3,kind:t.kind,name:t.name,presentation:t.presentation,products:t.products,offeringVersionId:t.offeringVersionId,screen:t.screen,buttons:t.buttons},offering:{id:t.offeringVersionId}})}export{h as a,w as b,q as c,c as d,M as e,_ as f};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as e}from"./chunk-
|
|
1
|
+
import{b as e}from"./chunk-35JZDDF3.js";var s=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,o=e.object({customerId:e.uuid(),sessionId:e.uuid(),accessToken:e.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:e.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:e.iso.datetime(),refreshExpiresAt:e.iso.datetime()});export{s as a,o as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as tn}from"./chunk-HATZIRVQ.js";import{b as rn}from"./chunk-QPCIIQ6Q.js";import{b as nn}from"./chunk-UZAJOV75.js";import{d as We,e as ce}from"./chunk-6TX2UFWN.js";import{c as qe,d as je,e as K,l as Ze}from"./chunk-V6RXIFHI.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-K55XWFEI.js";import{A as ie,B as ae,z as oe}from"./chunk-WO6BLOJI.js";import{a as de,b as Xe}from"./chunk-ANNZWFFN.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-UFEILUGE.js";import{b as W}from"./chunk-6OXRK7PK.js";import{a as Q}from"./chunk-XHJ33SCP.js";import{m as Ke,n as ue,o as ze,p as se}from"./chunk-5MX7OICH.js";import{g as Ee,m as Ce,w as re}from"./chunk-2UB5RFXZ.js";import{b as Pe,d as L,e as Ae,f as Te}from"./chunk-RHARJTIX.js";import{a as m}from"./chunk-EHWMZCNT.js";import{h as V}from"./chunk-6DE2YAGZ.js";import{a as en}from"./chunk-5MRSFLQA.js";import{b as n}from"./chunk-RTKI4V2J.js";import{a as on}from"./chunk-DSPLGTQI.js";import{c as Ne,f as Oe}from"./chunk-VPT5MFDG.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),nextPaywalls:n.record(M,n.strictObject({paywallVersionId:n.uuid()})).optional(),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-CN2INQIX.js";import{b as rn}from"./chunk-TY4PJ2AG.js";import{b as nn}from"./chunk-H4RDA4MD.js";import{d as We,e as ce}from"./chunk-2XTBFJN4.js";import{c as qe,d as je,e as K,l as Ze}from"./chunk-SZPHTRYE.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-Y4MFO2FU.js";import{A as ie,B as ae,z as oe}from"./chunk-KLPRVDHS.js";import{a as de,b as Xe}from"./chunk-AVXJB4O6.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-EK5U2JOM.js";import{b as W}from"./chunk-LM6TMEMB.js";import{a as Q}from"./chunk-4DMVOAXB.js";import{m as Ke,n as ue,o as ze,p as se}from"./chunk-HQWZWHHM.js";import{g as Ee,m as Ce,w as re}from"./chunk-NPDRXDI7.js";import{b as Pe,d as L,e as Ae,f as Te}from"./chunk-WG2DKREQ.js";import{a as m}from"./chunk-HLK7L2RV.js";import{h as V}from"./chunk-GNRFL6KF.js";import{a as en}from"./chunk-5MRSFLQA.js";import{b as n}from"./chunk-35JZDDF3.js";import{a as on}from"./chunk-DSPLGTQI.js";import{c as Ne,f as Oe}from"./chunk-VPT5MFDG.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),nextPaywalls:n.record(M,n.strictObject({paywallVersionId:n.uuid()})).optional(),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 +1 @@
|
|
|
1
|
-
import{b as He}from"./chunk-EU4XNTEE.js";import{a as $}from"./chunk-3DW3Q6RU.js";import{D as K,F as Qe,c as Te,e as z,j as xe,u as Le,v as Me,x as Ge,z as ze}from"./chunk-FU4XNGGP.js";import{a as Ne,b as je,c as Ue}from"./chunk-64TKCCJF.js";import{a as se}from"./chunk-QPCIIQ6Q.js";import{i as ue}from"./chunk-FXRBRAJR.js";import{K as G}from"./chunk-K55XWFEI.js";import{A as ae,B as ie,C as J,E as Fe}from"./chunk-WO6BLOJI.js";import{x as ye}from"./chunk-G7QLMLCR.js";import{b as Ve}from"./chunk-6OXRK7PK.js";import{a as l}from"./chunk-EHWMZCNT.js";import{h as oe}from"./chunk-6DE2YAGZ.js";import{a as De}from"./chunk-5MRSFLQA.js";import{b as r}from"./chunk-RTKI4V2J.js";import{a as ge}from"./chunk-DSPLGTQI.js";var R=G.options,st=r.discriminatedUnion("operation",[R[1].omit({customerToken:!0}),R[2].omit({customerToken:!0}),R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[7].omit({customerToken:!0}),R[8].omit({customerToken:!0}),xe.omit({customerToken:!0})]),Pe=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),yt=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("find_purchase")}),r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume","start"]),start:r.strictObject({requestId:R[0].shape.requestId,funnelId:R[0].shape.funnelId,locale:R[0].shape.locale,parameters:R[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe,includePaywallVersion:r.literal(!0).optional()}),r.strictObject({operation:r.literal("terminate_checkout"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[7].omit({customerToken:!0})]).optional()}).refine(i=>!i.command||i.requestId===i.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:st})]),ce=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:z.shape.run.shape.status}),H={scope:oe,customerId:r.uuid()},Be=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...H,outcome:r.literal("resolved"),target:ce,view:z.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((i,d)=>{i.outcome==="resolved"&&(i.access.type==="customer"!=(i.view!==null)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Ye=r.strictObject({...H,target:ce,view:z.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:z.shape.purchase.unwrap().nullable()}).superRefine((i,d)=>{let f=i.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))||i.purchase&&(i.purchase.receiptId!==f.receiptId||i.purchase.operation&&i.purchase.operation.operationId!==f.operationId||i.purchase.quote&&i.purchase.quote.operationId!==f.operationId)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Je=r.strictObject({...H,target:ce,purchase:z.shape.purchase.unwrap(),paywallVersionId:r.uuid().optional()}).superRefine((i,d)=>{(!i.purchase.operation||typeof i.purchase.canReselect!="boolean"||i.purchase.quote&&i.purchase.quote.operationId!==i.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),Ke=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("none")}),r.strictObject({...H,outcome:r.literal("blocked")}),r.strictObject({...H,outcome:r.literal("found"),target:ce,start:r.strictObject({locale:R[0].shape.locale,parameters:R[0].shape.parameters}),purchase:Pe})]);var ut=G.options[0].refine(i=>!i.customer&&!i.customerData),ct=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),$e=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:oe,customerId:r.uuid(),sessionId:r.uuid(),start:ut,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:Te.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ct).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:Le.nullable()})});function We(i){return Ge({...i,namespace:"purchases",identity:[i.scope.projectId,i.scope.environment,i.customerId]})}function Xe(i){let d=new URL(i.baseUrl??De).href,f=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function S(){i.assertCurrent();try{let E=await i.storage.read();if(i.assertCurrent(),!Number.isSafeInteger(E.revision)||E.revision<0)throw f();let c=E.entry===null?null:$e.parse(E.entry);if(c&&(c.baseUrl!==d||c.customerId!==i.customerId||c.scope.projectId!==i.scope.projectId||c.scope.environment!==i.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(c?.journal.entry&&(c.journal.entry.scope.projectId!==c.scope.projectId||c.journal.entry.scope.environment!==c.scope.environment||c.journal.entry.funnelId!==c.start.funnelId||c.journal.entry.runId!==c.run?.id||c.journal.entry.versionId!==c.run?.versionId)||c?.operationCommand&&!c.purchases.some(k=>k.operationId===c.operationCommand?.operationId))throw f();return{revision:E.revision,entry:c}}catch(E){throw E instanceof l?E:f()}}async function W(E){for(let c=0;c<8;c++){let k=await S(),q=E(structuredClone(k.entry));if(JSON.stringify(q)===JSON.stringify(k.entry))return q;q&&$e.parse(q),i.assertCurrent();let j;try{j=await i.storage.write(k.revision,q)}catch{throw f()}if(i.assertCurrent(),j!==null){if(!Number.isSafeInteger(j)||j<=k.revision)throw f();return q}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:S,update:W,baseUrl:d}}var lt=5*6e4,dt=2e3;function pt(i,d){let f=i.purchases.find(S=>S.type==="checkout");if(!i.actions.includes("continue_checkout")||f?.type!=="checkout"||d!==void 0&&f.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return f.checkoutUrl}function Qt(i){let d={...i,scope:{...i.scope},executionPolicy:structuredClone(i.executionPolicy)},f=d.session.snapshot();if(!f)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:S,sessionId:W}=f,E=!1,c=null,k,q,j=null,F=!1,U,X,Z,b={mode:"idle",status:"idle",actions:["start"],purchases:[]},g=new Map,ve=new Map,T=new Map,le=new AbortController,ee=new Set,Q=Ve(d),te=He(Q.request);function B(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function P(){if(E||d.session.snapshot()?.customerId!==S)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let w=Xe({...d,customerId:S,assertCurrent:P,storage:d.storage??We({baseUrl:d.baseUrl,scope:d.scope,customerId:S})}),Ze,Re=()=>Ze??=import("./funnel-paywall-copies-WAX7Q2N4.js").then(({createPaywallCopies:e})=>e({baseUrl:d.baseUrl,scope:d.scope,customerId:S})),et={read:async e=>(await Re()).read(e),write:async(e,t)=>(await Re()).write(e,t)},tt=d.session.subscribeIdentity(Se);function Se(){E||(E=!0,clearTimeout(Z),le.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),tt(),c?.reset(),c=null,j=null,Q.dispose(),ee.clear(),g.clear(),T.clear())}function v(e){P();let t=JSON.stringify(e)!==JSON.stringify(b);b=e,clearTimeout(Z),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Z=setTimeout(()=>{M().catch(()=>{})},5e3)),t&&ge(d.onRecovery,structuredClone(e));for(let n of t?ee:[]){if(E)break;ge(n,structuredClone(e))}return structuredClone(e)}function y(e){if(P(),!e||e.start.requestId!==q)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function Ce(e){return!e.run&&!O(e).length&&!e.journal.entry&&!e.operationCommand}function O(e){let t=[...e.purchases],n=e.journal.entry?.purchase;return n&&!t.some(o=>o.operationId===n.operationId)&&t.push({receiptId:n.receiptId,operationId:n.operationId,terminal:null}),t}function x(e){let t=O(e),n=F&&t.length>0&&t.every(o=>o.terminal==="native"&&D(g.get(o.operationId))==="native")&&t.some(o=>{let s=g.get(o.operationId);return!!s&&J(s)&&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=O(e).map(I=>{let C=g.get(I.operationId);return I.terminal&&!C?{type:I.terminal,operationId:I.operationId}:se({quote:C?.quote??null,operation:C??null,requestId:n?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(I.operationId)===!0})}),s=o.filter(I=>!["complete","native"].includes(I.type)),u=s[0],a=s.length===1&&u?.operationId?g.get(u.operationId):void 0;if(a&&(u?.type==="checkout"||u?.type==="cancel"))try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote)}catch(I){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:B(I)}}let m;if(t==="operation"&&!n&&u?.type==="cancel"&&a?.quote&&!a.problem&&!a.confirmedAt)try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote),Date.parse(a.quote.expiresAt)>Date.now()&&(m={operationId:a.operationId,quote:a.quote})}catch{}let p=o.length>0&&s.length===0,h=x(e)||t==="operation"&&p&&!n&&!e.operationCommand?"complete":u?.type==="checkout"?"checkout":u?.type==="fulfillment"?"fulfillment":u?.type==="recording"?"recording":n||e.operationCommand||u&&u.type!=="cancel"||t==="operation"&&!m?"waiting_result":"ready";return{mode:t,status:h,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...x(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...s.length===1&&u?.type==="checkout"?["continue_checkout"]:[]]}}function D(e){let t=se({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function de(e){if(!e.operation)return;let t=ae.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let n=ue(g.get(t.operationId)??null,t);g.set(t.operationId,n),n===t&&T.set(t.operationId,e.canReselect===!0)}async function nt(e){P();for(let n of[e.purchase,e.run.paywall])n&&de(n);let t=await w.update(n=>{if(y(n),n.run&&(n.run.id!==e.run.id||n.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=O(n);for(let s of[e.purchase,e.run.paywall]){let u=s?.operation?.operationId??s?.quote?.operationId;if(!s||!u)continue;let a=o.find(p=>p.operationId===u);if(a&&a.receiptId!==s.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=D(g.get(u));a?a.terminal??=m:o.push({receiptId:s.receiptId,operationId:u,terminal:m})}return{...n,purchases:o,run:n.run&&(n.run.revision>e.run.revision||!["running","waiting"].includes(n.run.status)&&["running","waiting"].includes(e.run.status))?n.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});y(t),t.run&&!["running","waiting"].includes(t.run.status)&&O(t).some(n=>!n.terminal)&&(t=await L(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(n=>!!n)))),y(t),v(A(t,"run"))}function rt(){return{async read(){let{entry:e}=await w.read();return y(e),structuredClone(e.journal)},async write(e,t){let n=null;return await w.update(o=>{if(y(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return n=null,o.journal.revision!==e?o:(n=e+1,{...o,journal:{revision:n,entry:t}})}),n}}}async function L(e,t=!1,n=new Set){y(e);let o=O(e);for(let u of o){if(u.terminal)continue;let a=n.has(u.operationId)?g.get(u.operationId):void 0;if(a??=await V(e,u),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(a.merchantExecution&&a.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&se({quote:a.quote??null,operation:a,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let m=J(a)?await te.update({operationId:u.operationId,intent:"cancel"}):await te.attach({operationId:u.operationId,intent:"cancel"});if(a=ae.parse(m.operation),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");a=await V(e,u)}g.set(u.operationId,ue(g.get(u.operationId)??null,a))}let s=await w.update(u=>{y(u);let a=u.operationCommand&&g.get(u.operationCommand.operationId);return{...u,...a&&(a.confirmedAt||a.merchantExecution||!Fe(a))?{operationCommand:void 0}:{},purchases:O(u).map(m=>({...m,terminal:m.terminal??D(g.get(m.operationId))}))}});return y(s),s}async function Y(e){P();let t=await Q.request("funnels",e);return P(),t}async function ot(e){try{return await Y(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return Y({...e,intent:"resume"})}}async function at(){let e=$(Ke,await Y({operation:"find_purchase"}));if(e.customerId!==S||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:n}=e;return await w.update(o=>o&&!x(o)?o:{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...n,terminal:null}],journal:{revision:0,entry:null}}),"found"}let ne;function pe(e){let t=ne;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<lt))return t.job;let n={at:Date.now(),job:at().then(o=>(n.outcome=o,n.at=Date.now(),o),o=>{throw ne===n&&(ne=void 0),o})};return ne=n,n.job}async function V(e,t,n="recover_purchase",o=!1){let s=$(Je,await Y({operation:n,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId},...o?{includePaywallVersion:!0}:{}}));if(me(e,s),s.purchase.receiptId!==t.receiptId||s.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return de(s.purchase),o&&s.paywallVersionId&&ve.set(t.operationId,s.paywallVersionId),g.get(t.operationId)}async function Ee(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let n=$(Ye,await Y({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(me(e,n),n.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");n.purchase&&de(n.purchase);let o=await w.update(s=>{y(s);let u=O(s),{receiptId:a,operationId:m}=n.settlement;if(a&&m){let h=u.find(I=>I.operationId===m);if(h&&h.receiptId!==a)throw new l("INVALID_RESPONSE","Original Receipt changed");h||u.push({receiptId:a,operationId:m,terminal:D(g.get(m))})}let p=n.settlement.state==="settled"?Me(s.journal.entry,t.requestId):s.journal.entry;return{...s,purchases:u,journal:p===s.journal.entry?s.journal:{revision:s.journal.revision+1,entry:p}}});y(o),e=o}return e}function me(e,t){if(t.customerId!==S||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function fe(e,t){if(y(e),e.run&&(e=await Ee(e)),!O(e).length&&x(e))return v(A(e,"operation"));if(!O(e).length)return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(t)});F=!0;let n=O(e);if(e.run&&["running","waiting"].includes(e.run.status)&&n.every(s=>s.terminal==="native"))for(let s of n)D(g.get(s.operationId))!=="native"&&await V(e,s);let o=await L(e);return v(A(o,"operation"))}async function re(e,t=!1,n=!0,o=!1){if(q=e.start.requestId,j=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!c){let s=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await ot(s)}catch(h){if(!e.run&&h instanceof l&&(h.status===void 0||h.status>=500))return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:B(h)});throw h}let a=$(Be,u);if(a.customerId!==S||a.scope.projectId!==d.scope.projectId||a.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(a.outcome==="unknown"){if(!t&&Ce(e)){let h=e.start.requestId;if(!await w.update(C=>C&&C.start.requestId===h&&Ce(C)?null:C))return v({mode:"idle",status:"idle",actions:["start"],purchases:[]})}return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}})}me(e,a);let m=await w.update(h=>(y(h),{...h,run:{id:a.target.runId,versionId:a.target.versionId,status:a.target.status,revision:a.view?.revision??h.run?.revision??0,runExpiresAt:a.target.runExpiresAt}}));if(y(m),e=m,a.access.type==="operation_only")return fe(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ee(e);let p=a.view;if(p.locale!==e.start.locale||!ze(p.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");c=Qe({...d,customerRun:{runId:a.target.runId,customerId:S,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(h=>d.executionPolicy.allowed.includes(h))},funnelCommandStorage:rt(),onAcceptedResponse:nt},{scope:a.scope,run:p})}try{let s=o&&k?.controller===c?performance.now()-k.at:1/0;(s>=dt||c.pendingCommands?.length||(c.viewAgeMs??0)<s)&&(k=void 0,await c.get(),k={controller:c,at:performance.now()}),c.view?.pendingRequest?.requestId===e.start.requestId&&!c.pendingCommands?.length&&await c.resume(c.view.pendingRequest.requestId);for(let a of c.pendingCommands??[])a.operation!=="close"&&await c.settle?.(a.requestId);c.pendingCommands?.length&&await c.retry(),P();let u=(await w.read()).entry;return y(u),v(A(u,"run"))}catch(s){if(P(),n&&s instanceof l&&(s.status===401||s.status===409&&s.reason==="STATE_CHANGED")){c.reset(),c=null;let u=(await w.read()).entry;return y(u),re(u,!1,!1,!1)}throw s}}function N(e,t="read",n){if(P(),U)return t==="read"||t===X?U:U.then(()=>N(e,t,n),()=>N(e,t,n));clearTimeout(Z);let o=e().catch(s=>{throw!E&&!n?.(s)&&v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:b.purchases,error:B(s)}),s});return U=o,X=t,o.then(()=>{U===o&&(U=void 0,X=void 0)},()=>{U===o&&(U=void 0,X=void 0)}),o}function M(e){let t=e?.reuseRecentRead===!0;return N(async()=>{let{entry:n}=await w.read();if(!n||x(n)){if(await pe(!1)==="blocked")return be();({entry:n}=await w.read())}return n?(q&&n.start.requestId!==q&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F&&q===n.start.requestId?fe(n,b.error):re(n,!1,!0,t)):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function be(){return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function Oe(){let e=await M();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:N(async()=>{let t=(await w.read()).entry;if(y(t),!F){if(!c?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=c.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(J(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return v(A(t,"run"));if(c.pendingCommands?.length)await c.retry();else{let I=c.view;await c.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:I.nodeId,visit:I.visit,revision:I.revision,input:{type:"paywall_confirm",operationId:I.paywall.quote.operationId,...I.paywall.quote.merchantTerms?{merchantConfirmation:ye(I.paywall.quote.merchantTerms)}:{}}})}let h=(await w.read()).entry;return y(h),v(A(h,"run"))}let n=t.operationCommand?.operationId??b.confirmation?.operationId,o=n&&g.get(n);if(!n||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");K({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await w.update(p=>{if(y(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==n)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:n,intent:"confirm"}}});let s={operationId:n,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:ye(o.quote.merchantTerms)}:{}},u=J(o)?await te.update(s):await te.attach(s),a=ae.parse(u.operation);if(P(),u.operation.operationId!==n)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");g.set(n,ue(o,a));let m=(await w.read()).entry;return y(m),v(A(await L(m,!1,new Set([n])),"operation"))},"confirm")}function it(e){let t=e?.quote;return t&&ie(t)&&t.timing==="immediate"&&t.execution.provider==="merchant"&&(e.confirmedAt||e.merchantExecution)?t:null}function _e(){if(b.mode!=="operation"||b.status==="blocked")return null;let e=b.purchases.filter(({type:n})=>n!=="complete"&&n!=="native"),t=e.length===1&&e[0]?.operationId;return t?it(g.get(t)):null}async function qe(){P();let{entry:e}=await w.read();return e?x(e)?"finished":"pending":"none"}return{get controller(){return c},get recovery(){return structuredClone(b)},get attempt(){return P(),structuredClone(j)},get identitySignal(){return le.signal},get customerId(){return S},retained:qe,get paywallCopies(){return et},async findPurchase(){let e=await qe();if(e==="pending")return e;let t=await pe(!0);return P(),t==="none"?e:t},async readPaywall(e){P();let t=Ne(e),[n,{readPaywallContent:o},{validateResourceCheck:s}]=await Promise.all([je(Q.request,"resolvePaywall"),import("./paywall-content-WAUQRLBP.js"),import("./check-response-FTYRCENP.js")]);P();let u=n.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),a=await Ue(Q.request,n,u);s(u,a.paywall.check,a.scope);let m=await o(d,a.paywall);if(P(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},get canRestoreUpgradePaywall(){return _e()!==null},recoverUpgradePaywall(){let e=_e();return e?this.recoverPurchasePaywall(void 0,e.operationId):Promise.resolve(null)},async recoverPurchasePaywall(e,t){if(b.mode!=="operation"||b.status==="blocked")return null;let{entry:n}=await w.read();if(!n?.run)return null;y(n);let o=O(n),s=o.filter(_=>!_.terminal),u=o.filter(_=>_.terminal==="complete"),a=s.length===1?s[0]:s.length?void 0:u.find(_=>e&&e.runId===n.run?.id&&_.receiptId===e.receiptId)??(u.length===1?u[0]:void 0);if(!a||t&&a.operationId!==t)return null;let m=e?.runId===n.run.id&&e.receiptId===a.receiptId?e.view:void 0,p;try{p=await V(n,a,"recover_purchase",!0)}catch(_){if(!(_ instanceof l&&_.status===400&&_.code==="INVALID_REQUEST"))throw _;if(!m)return null;p=await V(n,a)}let h=p.quote;if(!h||ie(h)&&(h.timing!=="immediate"||h.execution.provider!=="merchant")||!(p.confirmedAt||p.merchantExecution||p.checkoutUrl||D(p)==="complete"))return null;D(p)!=="complete"&&K({allowed:n.allowed.filter(_=>d.executionPolicy.allowed.includes(_))},h);let I=ve.get(a.operationId),C=n.start.parameters?.commerce,ke=n.start.locale??"en",he=m;if(I){if(typeof C!="object"||!C||!("provider"in C)||typeof C.provider!="string"||!("currency"in C)||typeof C.currency!="string")return null;he=await this.readPaywall({paywallVersionId:I,locale:ke,commerce:{provider:C.provider,currency:C.currency,...ie(h)?{intent:"subscription_change"}:{}}})}if(!he)return null;P();let Ae=he,we=!1,Ie=async()=>{throw new l("PURCHASE_PENDING","Only the original purchase can be recovered")};return{signal:le.signal,view:Ae,quote:h,locale:ke,get operation(){return p},get canReselect(){return T.get(a.operationId)===!0},async refresh(){return Ae},preview:Ie,confirm:Ie,cancel:Ie,async read(){if(we)throw new DOMException("Purchase view closed","AbortError");p=await V(n,a);let _=await L(n,!1,new Set([a.operationId]));return we||v(A(_,"operation")),structuredClone(p)},destroy(){we=!0}}},start(e){let t=G.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return N(async()=>{let n=(await w.read()).entry;if((!n||x(n))&&await pe(!0)==="blocked")return be();let o=await w.update(s=>{if(s&&!x(s)){if(s.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return s}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return q!==o.start.requestId&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F?fe(o,b.error):re(o,!0,!0,!0)},`start:${t.funnelId}`)},refresh:M,confirm:Oe,retry:()=>F?Oe():N(async()=>{let{entry:e}=await w.read();return e?re(e,!0):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return c?.view?N(async()=>{if(!c?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(c.pendingCommands?.find(n=>n.operation==="close"))await c.retry();else if(["running","waiting"].includes(c.view.status)){let n=c.view;await c.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision})}let t=(await w.read()).entry;return y(t),v(A(t,"run"))},"close"):M()},async continueCheckout(e,t){let n=t?await N(async()=>{let{entry:o}=await w.read();if(y(o),!o.run||!O(o).some(u=>u.operationId===t&&!u.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let s=await L(o);return v(A(s,F?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await M();P(),await e(pt(n,t))},async terminateCheckout(e){let t=await M();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 w.read();y(o);let s=O(o).find(a=>a.operationId===e&&!a.terminal);if(!s||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await V(o,s,"terminate_checkout");let u=await L(o,!1,new Set([e]));return v(A(u,F?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return ee.add(e),()=>{ee.delete(e)}},destroy:Se}}export{We as a,pt as b,Qt as c};
|
|
1
|
+
import{b as He}from"./chunk-MCFHMWLX.js";import{a as $}from"./chunk-ZZ4X4DMO.js";import{D as K,F as Qe,c as Te,e as z,j as xe,u as Le,v as Me,x as Ge,z as ze}from"./chunk-4ZIA22MI.js";import{a as Ne,b as je,c as Ue}from"./chunk-KWOB5LYC.js";import{a as se}from"./chunk-TY4PJ2AG.js";import{i as ue}from"./chunk-DCPRELJA.js";import{K as G}from"./chunk-Y4MFO2FU.js";import{A as ae,B as ie,C as J,E as Fe}from"./chunk-KLPRVDHS.js";import{x as ye}from"./chunk-V53RJR3S.js";import{b as Ve}from"./chunk-LM6TMEMB.js";import{a as l}from"./chunk-HLK7L2RV.js";import{h as oe}from"./chunk-GNRFL6KF.js";import{a as De}from"./chunk-5MRSFLQA.js";import{b as r}from"./chunk-35JZDDF3.js";import{a as ge}from"./chunk-DSPLGTQI.js";var R=G.options,st=r.discriminatedUnion("operation",[R[1].omit({customerToken:!0}),R[2].omit({customerToken:!0}),R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[7].omit({customerToken:!0}),R[8].omit({customerToken:!0}),xe.omit({customerToken:!0})]),Pe=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),yt=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("find_purchase")}),r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume","start"]),start:r.strictObject({requestId:R[0].shape.requestId,funnelId:R[0].shape.funnelId,locale:R[0].shape.locale,parameters:R[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe,includePaywallVersion:r.literal(!0).optional()}),r.strictObject({operation:r.literal("terminate_checkout"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[7].omit({customerToken:!0})]).optional()}).refine(i=>!i.command||i.requestId===i.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:st})]),ce=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:z.shape.run.shape.status}),H={scope:oe,customerId:r.uuid()},Be=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...H,outcome:r.literal("resolved"),target:ce,view:z.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((i,d)=>{i.outcome==="resolved"&&(i.access.type==="customer"!=(i.view!==null)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Ye=r.strictObject({...H,target:ce,view:z.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:z.shape.purchase.unwrap().nullable()}).superRefine((i,d)=>{let f=i.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))||i.purchase&&(i.purchase.receiptId!==f.receiptId||i.purchase.operation&&i.purchase.operation.operationId!==f.operationId||i.purchase.quote&&i.purchase.quote.operationId!==f.operationId)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Je=r.strictObject({...H,target:ce,purchase:z.shape.purchase.unwrap(),paywallVersionId:r.uuid().optional()}).superRefine((i,d)=>{(!i.purchase.operation||typeof i.purchase.canReselect!="boolean"||i.purchase.quote&&i.purchase.quote.operationId!==i.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),Ke=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("none")}),r.strictObject({...H,outcome:r.literal("blocked")}),r.strictObject({...H,outcome:r.literal("found"),target:ce,start:r.strictObject({locale:R[0].shape.locale,parameters:R[0].shape.parameters}),purchase:Pe})]);var ut=G.options[0].refine(i=>!i.customer&&!i.customerData),ct=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),$e=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:oe,customerId:r.uuid(),sessionId:r.uuid(),start:ut,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:Te.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ct).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:Le.nullable()})});function We(i){return Ge({...i,namespace:"purchases",identity:[i.scope.projectId,i.scope.environment,i.customerId]})}function Xe(i){let d=new URL(i.baseUrl??De).href,f=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function S(){i.assertCurrent();try{let E=await i.storage.read();if(i.assertCurrent(),!Number.isSafeInteger(E.revision)||E.revision<0)throw f();let c=E.entry===null?null:$e.parse(E.entry);if(c&&(c.baseUrl!==d||c.customerId!==i.customerId||c.scope.projectId!==i.scope.projectId||c.scope.environment!==i.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(c?.journal.entry&&(c.journal.entry.scope.projectId!==c.scope.projectId||c.journal.entry.scope.environment!==c.scope.environment||c.journal.entry.funnelId!==c.start.funnelId||c.journal.entry.runId!==c.run?.id||c.journal.entry.versionId!==c.run?.versionId)||c?.operationCommand&&!c.purchases.some(k=>k.operationId===c.operationCommand?.operationId))throw f();return{revision:E.revision,entry:c}}catch(E){throw E instanceof l?E:f()}}async function W(E){for(let c=0;c<8;c++){let k=await S(),q=E(structuredClone(k.entry));if(JSON.stringify(q)===JSON.stringify(k.entry))return q;q&&$e.parse(q),i.assertCurrent();let j;try{j=await i.storage.write(k.revision,q)}catch{throw f()}if(i.assertCurrent(),j!==null){if(!Number.isSafeInteger(j)||j<=k.revision)throw f();return q}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:S,update:W,baseUrl:d}}var lt=5*6e4,dt=2e3;function pt(i,d){let f=i.purchases.find(S=>S.type==="checkout");if(!i.actions.includes("continue_checkout")||f?.type!=="checkout"||d!==void 0&&f.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return f.checkoutUrl}function Qt(i){let d={...i,scope:{...i.scope},executionPolicy:structuredClone(i.executionPolicy)},f=d.session.snapshot();if(!f)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:S,sessionId:W}=f,E=!1,c=null,k,q,j=null,F=!1,U,X,Z,b={mode:"idle",status:"idle",actions:["start"],purchases:[]},g=new Map,ve=new Map,T=new Map,le=new AbortController,ee=new Set,Q=Ve(d),te=He(Q.request);function B(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function P(){if(E||d.session.snapshot()?.customerId!==S)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let w=Xe({...d,customerId:S,assertCurrent:P,storage:d.storage??We({baseUrl:d.baseUrl,scope:d.scope,customerId:S})}),Ze,Re=()=>Ze??=import("./funnel-paywall-copies-E7GHHCVL.js").then(({createPaywallCopies:e})=>e({baseUrl:d.baseUrl,scope:d.scope,customerId:S})),et={read:async e=>(await Re()).read(e),write:async(e,t)=>(await Re()).write(e,t)},tt=d.session.subscribeIdentity(Se);function Se(){E||(E=!0,clearTimeout(Z),le.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),tt(),c?.reset(),c=null,j=null,Q.dispose(),ee.clear(),g.clear(),T.clear())}function v(e){P();let t=JSON.stringify(e)!==JSON.stringify(b);b=e,clearTimeout(Z),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Z=setTimeout(()=>{M().catch(()=>{})},5e3)),t&&ge(d.onRecovery,structuredClone(e));for(let n of t?ee:[]){if(E)break;ge(n,structuredClone(e))}return structuredClone(e)}function y(e){if(P(),!e||e.start.requestId!==q)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function Ce(e){return!e.run&&!O(e).length&&!e.journal.entry&&!e.operationCommand}function O(e){let t=[...e.purchases],n=e.journal.entry?.purchase;return n&&!t.some(o=>o.operationId===n.operationId)&&t.push({receiptId:n.receiptId,operationId:n.operationId,terminal:null}),t}function x(e){let t=O(e),n=F&&t.length>0&&t.every(o=>o.terminal==="native"&&D(g.get(o.operationId))==="native")&&t.some(o=>{let s=g.get(o.operationId);return!!s&&J(s)&&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=O(e).map(I=>{let C=g.get(I.operationId);return I.terminal&&!C?{type:I.terminal,operationId:I.operationId}:se({quote:C?.quote??null,operation:C??null,requestId:n?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(I.operationId)===!0})}),s=o.filter(I=>!["complete","native"].includes(I.type)),u=s[0],a=s.length===1&&u?.operationId?g.get(u.operationId):void 0;if(a&&(u?.type==="checkout"||u?.type==="cancel"))try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote)}catch(I){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:B(I)}}let m;if(t==="operation"&&!n&&u?.type==="cancel"&&a?.quote&&!a.problem&&!a.confirmedAt)try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote),Date.parse(a.quote.expiresAt)>Date.now()&&(m={operationId:a.operationId,quote:a.quote})}catch{}let p=o.length>0&&s.length===0,h=x(e)||t==="operation"&&p&&!n&&!e.operationCommand?"complete":u?.type==="checkout"?"checkout":u?.type==="fulfillment"?"fulfillment":u?.type==="recording"?"recording":n||e.operationCommand||u&&u.type!=="cancel"||t==="operation"&&!m?"waiting_result":"ready";return{mode:t,status:h,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...x(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...s.length===1&&u?.type==="checkout"?["continue_checkout"]:[]]}}function D(e){let t=se({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function de(e){if(!e.operation)return;let t=ae.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let n=ue(g.get(t.operationId)??null,t);g.set(t.operationId,n),n===t&&T.set(t.operationId,e.canReselect===!0)}async function nt(e){P();for(let n of[e.purchase,e.run.paywall])n&&de(n);let t=await w.update(n=>{if(y(n),n.run&&(n.run.id!==e.run.id||n.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=O(n);for(let s of[e.purchase,e.run.paywall]){let u=s?.operation?.operationId??s?.quote?.operationId;if(!s||!u)continue;let a=o.find(p=>p.operationId===u);if(a&&a.receiptId!==s.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=D(g.get(u));a?a.terminal??=m:o.push({receiptId:s.receiptId,operationId:u,terminal:m})}return{...n,purchases:o,run:n.run&&(n.run.revision>e.run.revision||!["running","waiting"].includes(n.run.status)&&["running","waiting"].includes(e.run.status))?n.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});y(t),t.run&&!["running","waiting"].includes(t.run.status)&&O(t).some(n=>!n.terminal)&&(t=await L(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(n=>!!n)))),y(t),v(A(t,"run"))}function rt(){return{async read(){let{entry:e}=await w.read();return y(e),structuredClone(e.journal)},async write(e,t){let n=null;return await w.update(o=>{if(y(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return n=null,o.journal.revision!==e?o:(n=e+1,{...o,journal:{revision:n,entry:t}})}),n}}}async function L(e,t=!1,n=new Set){y(e);let o=O(e);for(let u of o){if(u.terminal)continue;let a=n.has(u.operationId)?g.get(u.operationId):void 0;if(a??=await V(e,u),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(a.merchantExecution&&a.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&se({quote:a.quote??null,operation:a,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let m=J(a)?await te.update({operationId:u.operationId,intent:"cancel"}):await te.attach({operationId:u.operationId,intent:"cancel"});if(a=ae.parse(m.operation),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");a=await V(e,u)}g.set(u.operationId,ue(g.get(u.operationId)??null,a))}let s=await w.update(u=>{y(u);let a=u.operationCommand&&g.get(u.operationCommand.operationId);return{...u,...a&&(a.confirmedAt||a.merchantExecution||!Fe(a))?{operationCommand:void 0}:{},purchases:O(u).map(m=>({...m,terminal:m.terminal??D(g.get(m.operationId))}))}});return y(s),s}async function Y(e){P();let t=await Q.request("funnels",e);return P(),t}async function ot(e){try{return await Y(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return Y({...e,intent:"resume"})}}async function at(){let e=$(Ke,await Y({operation:"find_purchase"}));if(e.customerId!==S||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:n}=e;return await w.update(o=>o&&!x(o)?o:{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...n,terminal:null}],journal:{revision:0,entry:null}}),"found"}let ne;function pe(e){let t=ne;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<lt))return t.job;let n={at:Date.now(),job:at().then(o=>(n.outcome=o,n.at=Date.now(),o),o=>{throw ne===n&&(ne=void 0),o})};return ne=n,n.job}async function V(e,t,n="recover_purchase",o=!1){let s=$(Je,await Y({operation:n,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId},...o?{includePaywallVersion:!0}:{}}));if(me(e,s),s.purchase.receiptId!==t.receiptId||s.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return de(s.purchase),o&&s.paywallVersionId&&ve.set(t.operationId,s.paywallVersionId),g.get(t.operationId)}async function Ee(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let n=$(Ye,await Y({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(me(e,n),n.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");n.purchase&&de(n.purchase);let o=await w.update(s=>{y(s);let u=O(s),{receiptId:a,operationId:m}=n.settlement;if(a&&m){let h=u.find(I=>I.operationId===m);if(h&&h.receiptId!==a)throw new l("INVALID_RESPONSE","Original Receipt changed");h||u.push({receiptId:a,operationId:m,terminal:D(g.get(m))})}let p=n.settlement.state==="settled"?Me(s.journal.entry,t.requestId):s.journal.entry;return{...s,purchases:u,journal:p===s.journal.entry?s.journal:{revision:s.journal.revision+1,entry:p}}});y(o),e=o}return e}function me(e,t){if(t.customerId!==S||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function fe(e,t){if(y(e),e.run&&(e=await Ee(e)),!O(e).length&&x(e))return v(A(e,"operation"));if(!O(e).length)return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(t)});F=!0;let n=O(e);if(e.run&&["running","waiting"].includes(e.run.status)&&n.every(s=>s.terminal==="native"))for(let s of n)D(g.get(s.operationId))!=="native"&&await V(e,s);let o=await L(e);return v(A(o,"operation"))}async function re(e,t=!1,n=!0,o=!1){if(q=e.start.requestId,j=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!c){let s=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await ot(s)}catch(h){if(!e.run&&h instanceof l&&(h.status===void 0||h.status>=500))return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:B(h)});throw h}let a=$(Be,u);if(a.customerId!==S||a.scope.projectId!==d.scope.projectId||a.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(a.outcome==="unknown"){if(!t&&Ce(e)){let h=e.start.requestId;if(!await w.update(C=>C&&C.start.requestId===h&&Ce(C)?null:C))return v({mode:"idle",status:"idle",actions:["start"],purchases:[]})}return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}})}me(e,a);let m=await w.update(h=>(y(h),{...h,run:{id:a.target.runId,versionId:a.target.versionId,status:a.target.status,revision:a.view?.revision??h.run?.revision??0,runExpiresAt:a.target.runExpiresAt}}));if(y(m),e=m,a.access.type==="operation_only")return fe(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ee(e);let p=a.view;if(p.locale!==e.start.locale||!ze(p.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");c=Qe({...d,customerRun:{runId:a.target.runId,customerId:S,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(h=>d.executionPolicy.allowed.includes(h))},funnelCommandStorage:rt(),onAcceptedResponse:nt},{scope:a.scope,run:p})}try{let s=o&&k?.controller===c?performance.now()-k.at:1/0;(s>=dt||c.pendingCommands?.length||(c.viewAgeMs??0)<s)&&(k=void 0,await c.get(),k={controller:c,at:performance.now()}),c.view?.pendingRequest?.requestId===e.start.requestId&&!c.pendingCommands?.length&&await c.resume(c.view.pendingRequest.requestId);for(let a of c.pendingCommands??[])a.operation!=="close"&&await c.settle?.(a.requestId);c.pendingCommands?.length&&await c.retry(),P();let u=(await w.read()).entry;return y(u),v(A(u,"run"))}catch(s){if(P(),n&&s instanceof l&&(s.status===401||s.status===409&&s.reason==="STATE_CHANGED")){c.reset(),c=null;let u=(await w.read()).entry;return y(u),re(u,!1,!1,!1)}throw s}}function N(e,t="read",n){if(P(),U)return t==="read"||t===X?U:U.then(()=>N(e,t,n),()=>N(e,t,n));clearTimeout(Z);let o=e().catch(s=>{throw!E&&!n?.(s)&&v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:b.purchases,error:B(s)}),s});return U=o,X=t,o.then(()=>{U===o&&(U=void 0,X=void 0)},()=>{U===o&&(U=void 0,X=void 0)}),o}function M(e){let t=e?.reuseRecentRead===!0;return N(async()=>{let{entry:n}=await w.read();if(!n||x(n)){if(await pe(!1)==="blocked")return be();({entry:n}=await w.read())}return n?(q&&n.start.requestId!==q&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F&&q===n.start.requestId?fe(n,b.error):re(n,!1,!0,t)):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function be(){return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function Oe(){let e=await M();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:N(async()=>{let t=(await w.read()).entry;if(y(t),!F){if(!c?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=c.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(J(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return v(A(t,"run"));if(c.pendingCommands?.length)await c.retry();else{let I=c.view;await c.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:I.nodeId,visit:I.visit,revision:I.revision,input:{type:"paywall_confirm",operationId:I.paywall.quote.operationId,...I.paywall.quote.merchantTerms?{merchantConfirmation:ye(I.paywall.quote.merchantTerms)}:{}}})}let h=(await w.read()).entry;return y(h),v(A(h,"run"))}let n=t.operationCommand?.operationId??b.confirmation?.operationId,o=n&&g.get(n);if(!n||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");K({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await w.update(p=>{if(y(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==n)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:n,intent:"confirm"}}});let s={operationId:n,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:ye(o.quote.merchantTerms)}:{}},u=J(o)?await te.update(s):await te.attach(s),a=ae.parse(u.operation);if(P(),u.operation.operationId!==n)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");g.set(n,ue(o,a));let m=(await w.read()).entry;return y(m),v(A(await L(m,!1,new Set([n])),"operation"))},"confirm")}function it(e){let t=e?.quote;return t&&ie(t)&&t.timing==="immediate"&&t.execution.provider==="merchant"&&(e.confirmedAt||e.merchantExecution)?t:null}function _e(){if(b.mode!=="operation"||b.status==="blocked")return null;let e=b.purchases.filter(({type:n})=>n!=="complete"&&n!=="native"),t=e.length===1&&e[0]?.operationId;return t?it(g.get(t)):null}async function qe(){P();let{entry:e}=await w.read();return e?x(e)?"finished":"pending":"none"}return{get controller(){return c},get recovery(){return structuredClone(b)},get attempt(){return P(),structuredClone(j)},get identitySignal(){return le.signal},get customerId(){return S},retained:qe,get paywallCopies(){return et},async findPurchase(){let e=await qe();if(e==="pending")return e;let t=await pe(!0);return P(),t==="none"?e:t},async readPaywall(e){P();let t=Ne(e),[n,{readPaywallContent:o},{validateResourceCheck:s}]=await Promise.all([je(Q.request,"resolvePaywall"),import("./paywall-content-7NCG5I7S.js"),import("./check-response-2VZGH33N.js")]);P();let u=n.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),a=await Ue(Q.request,n,u);s(u,a.paywall.check,a.scope);let m=await o(d,a.paywall);if(P(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},get canRestoreUpgradePaywall(){return _e()!==null},recoverUpgradePaywall(){let e=_e();return e?this.recoverPurchasePaywall(void 0,e.operationId):Promise.resolve(null)},async recoverPurchasePaywall(e,t){if(b.mode!=="operation"||b.status==="blocked")return null;let{entry:n}=await w.read();if(!n?.run)return null;y(n);let o=O(n),s=o.filter(_=>!_.terminal),u=o.filter(_=>_.terminal==="complete"),a=s.length===1?s[0]:s.length?void 0:u.find(_=>e&&e.runId===n.run?.id&&_.receiptId===e.receiptId)??(u.length===1?u[0]:void 0);if(!a||t&&a.operationId!==t)return null;let m=e?.runId===n.run.id&&e.receiptId===a.receiptId?e.view:void 0,p;try{p=await V(n,a,"recover_purchase",!0)}catch(_){if(!(_ instanceof l&&_.status===400&&_.code==="INVALID_REQUEST"))throw _;if(!m)return null;p=await V(n,a)}let h=p.quote;if(!h||ie(h)&&(h.timing!=="immediate"||h.execution.provider!=="merchant")||!(p.confirmedAt||p.merchantExecution||p.checkoutUrl||D(p)==="complete"))return null;D(p)!=="complete"&&K({allowed:n.allowed.filter(_=>d.executionPolicy.allowed.includes(_))},h);let I=ve.get(a.operationId),C=n.start.parameters?.commerce,ke=n.start.locale??"en",he=m;if(I){if(typeof C!="object"||!C||!("provider"in C)||typeof C.provider!="string"||!("currency"in C)||typeof C.currency!="string")return null;he=await this.readPaywall({paywallVersionId:I,locale:ke,commerce:{provider:C.provider,currency:C.currency,...ie(h)?{intent:"subscription_change"}:{}}})}if(!he)return null;P();let Ae=he,we=!1,Ie=async()=>{throw new l("PURCHASE_PENDING","Only the original purchase can be recovered")};return{signal:le.signal,view:Ae,quote:h,locale:ke,get operation(){return p},get canReselect(){return T.get(a.operationId)===!0},async refresh(){return Ae},preview:Ie,confirm:Ie,cancel:Ie,async read(){if(we)throw new DOMException("Purchase view closed","AbortError");p=await V(n,a);let _=await L(n,!1,new Set([a.operationId]));return we||v(A(_,"operation")),structuredClone(p)},destroy(){we=!0}}},start(e){let t=G.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return N(async()=>{let n=(await w.read()).entry;if((!n||x(n))&&await pe(!0)==="blocked")return be();let o=await w.update(s=>{if(s&&!x(s)){if(s.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return s}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return q!==o.start.requestId&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F?fe(o,b.error):re(o,!0,!0,!0)},`start:${t.funnelId}`)},refresh:M,confirm:Oe,retry:()=>F?Oe():N(async()=>{let{entry:e}=await w.read();return e?re(e,!0):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return c?.view?N(async()=>{if(!c?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(c.pendingCommands?.find(n=>n.operation==="close"))await c.retry();else if(["running","waiting"].includes(c.view.status)){let n=c.view;await c.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision})}let t=(await w.read()).entry;return y(t),v(A(t,"run"))},"close"):M()},async continueCheckout(e,t){let n=t?await N(async()=>{let{entry:o}=await w.read();if(y(o),!o.run||!O(o).some(u=>u.operationId===t&&!u.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let s=await L(o);return v(A(s,F?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await M();P(),await e(pt(n,t))},async terminateCheckout(e){let t=await M();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 w.read();y(o);let s=O(o).find(a=>a.operationId===e&&!a.terminal);if(!s||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await V(o,s,"terminate_checkout");let u=await L(o,!1,new Set([e]));return v(A(u,F?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return ee.add(e),()=>{ee.delete(e)}},destroy:Se}}export{We as a,pt as b,Qt as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{g as p}from"./chunk-
|
|
1
|
+
import{g as p}from"./chunk-GNRFL6KF.js";import{b as r}from"./chunk-35JZDDF3.js";import{a as i,b as s}from"./chunk-CILM5XMH.js";var b=r.string().regex(/^[a-f0-9]{64}$/),j=r.strictObject({scope:r.strictObject({projectId:r.uuid(),environmentId:r.uuid(),environment:p}),customerId:r.uuid()});function l(u){let n=e=>{if(Array.isArray(e))return`[${e.map(n).join(",")}]`;if(e!==null&&typeof e=="object"){let c=Object.getPrototypeOf(e);if(c!==Object.prototype&&c!==null)throw new TypeError("Commerce protocol digests require JSON objects");return`{${Object.entries(e).filter(([,o])=>o!==void 0).sort(([o],[t])=>o<t?-1:o>t?1:0).map(([o,t])=>`${JSON.stringify(o)}:${n(t)}`).join(",")}}`}if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return JSON.stringify(e);throw new TypeError("Commerce protocol digests require JSON values")};return i(s(new TextEncoder().encode(n(u))))}export{b as a,j as b,l as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as C}from"./chunk-WX55MS2F.js";import{a as v}from"./chunk-OHPNHCQS.js";import{h as I}from"./chunk-VVZLNTWC.js";import{b as g}from"./chunk-SSVSXSYE.js";import{t as b}from"./chunk-HQWZWHHM.js";import{a as u}from"./chunk-HLK7L2RV.js";async function F(s,t){if(!s.closest("dialog")?.open)return null;let r=AbortSignal.any([t.signal,t.client.identitySignal]);r.throwIfAborted();let o=t.operationId?await t.client.recoverPurchasePaywall(void 0,t.operationId):await t.client.recoverPurchasePaywall();if(!o)return null;let c=o.view;if(!c||c.document.presentation.type!=="modal"||r.aborted)return o.destroy(),null;let l=t.upgradeReplacement,{session:m,prepare:f}=A({client:t.client,session:o,start:l?.start,signal:r}),p=I(s);if(!p)return o.destroy(),null;let n,i=new Promise(e=>{n=e}),w=!1,d=()=>n(!1);r.addEventListener("abort",d,{once:!0});try{let{host:e}=await C(s,{signal:r,start:async()=>m,loading:"host",checkoutNavigation:"after_confirmation",allowNewPurchase:!1,...l&&{beforeCheckoutReplacement:l.beforeCheckoutReplacement,resolveOfferId:l.resolveOfferId,resolveSubscriptionChange:l.resolveSubscriptionChange,terminateCheckout:a=>t.client.terminateCheckout(a),prepareUpgradeReplacement:f},resumeCheckout:a=>t.client.continueCheckout(t.onCheckoutUrl,a),onComplete:t.onComplete,onError(a){w?t.onError?.(a):n(!1)}},{retainedDialog:p,present(a){a(!0),w=!0,n(!0)},async dismiss(){t.onDismiss()}});return!e||!await i||r.aborted?(e?.destroy(),null):{document:c.document,destroy:()=>e.destroy()}}finally{r.removeEventListener("abort",d)}}function A(s){let t=s.start;if(!t)return{session:s.session};let{client:h,signal:r}=s,o=s.session,c=o,l;return{session:new Proxy(o,{get(p,n){let i=c[n];return typeof i=="function"?i.bind(c):i}}),prepare:async(p,n)=>{if(r.throwIfAborted(),o.operation?.operationId!==p||!o.canReselect)throw new u("PURCHASE_PENDING","The original purchase has not been closed");if(!l){let e=await t();if(!e)throw new u("PRODUCT_UNAVAILABLE","The selected plan is unavailable");if(e.funnelId!==h.attempt?.funnelId)throw new u("SCOPE_MISMATCH","The new purchase belongs to another Funnel");l={...e,requestId:e.requestId??crypto.randomUUID()}}r.throwIfAborted();let i=await h.start(l),w=h.controller;if(i.mode!=="run"||i.status!=="ready"||!w?.view?.paywall)throw new u("PURCHASE_PENDING","The current Paywall could not be opened for the replacement");let d=await v(w);try{r.throwIfAborted();let e=d.view,a=e?.document.buttons[n.actionId],y=e&&a?.type==="checkout"?g(a.product,n.selection,e.capabilities):null;if(!e||y!==n.productVersionId)throw new u("PRODUCT_UNAVAILABLE","The selected plan is no longer available");let P=b(e.document.screen,y,n.selection,e.capabilities);if(Object.keys(P).length!==Object.keys(n.featureQuantities).length||Object.entries(P).some(([S,k])=>n.featureQuantities[S]!==k))throw new u("PRODUCT_UNAVAILABLE","The selected plan quantities have changed");return c=d,o.destroy(),e}catch(e){throw d.destroy(),e}}}}export{F as a,A as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as c}from"./chunk-
|
|
1
|
+
import{h as c}from"./chunk-EK5U2JOM.js";import{b as p}from"./chunk-35JZDDF3.js";import{d as x,e as y,f as g}from"./chunk-VPT5MFDG.js";import{a as m,b as d}from"./chunk-CILM5XMH.js";var u=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function F(e,t,f){let i={},l,s,n,o="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let r=e.cases.findIndex(b=>x(t.attributes??{},b.condition,t.savedGroups??{}));o=r<0?"default":`case:${r}`,a=r<0?e.default:e.cases[r].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new u("Required GB Feature is unavailable");l=g(e.featureKey,t),n=l.value,Object.assign(i,c(e,{value:n})),a=e.next;break;case"split":{let r=f[e.experimentId];if(!r)throw new u("Required GB Experiment is unavailable");if(s=y(r,t),n=s.value,o=s.inExperiment&&!s.passthrough&&typeof n=="string"?n:"notParticipating",a=o==="notParticipating"?e.notParticipating:e.routes[o],!a)throw new u("Experiment Variation has no published route");break}case"offering":{let r=e.configuration.source==="fixed"?e.configuration.versionId:g(e.configuration.featureKey,t).value;n={type:"offering_version",id:p.uuid().parse(r)},Object.assign(i,c(e,{value:n})),a=e.next;break}case"coupon":case"coupons":n=e.type==="coupons"?e.couponIds.map(r=>({type:"reward",id:r})):{type:"reward",id:e.couponId},Object.assign(i,c(e,{value:n})),a=e.next;break}return{port:o,target:a,projections:i,...n===void 0?{}:{value:n},...l?{feature:l}:{},...s?{experiment:s}:{}}}function E(e,t,f){p.uuid().parse(e),p.number().int().nonnegative().parse(t);let i=m(d(new TextEncoder().encode(JSON.stringify([e,t,f])))).slice(0,32);return`${i.slice(0,8)}-${i.slice(8,12)}-5${i.slice(13,16)}-a${i.slice(17,20)}-${i.slice(20)}`}export{F as a,E as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as s}from"./chunk-
|
|
1
|
+
import{a as s}from"./chunk-HLK7L2RV.js";var p=new WeakMap;function P(i,n){p.set(i,n)}function v(i){let n,l=!1,d=new AbortController,u=e=>(i.client.pendingCommands??(i.client.pendingCommand?[i.client.pendingCommand]:[])).some(r=>r.requestId===e.command.requestId),m=()=>i.document.defaultView?.navigator.onLine!==!1,C=e=>new Promise((r,t)=>{let o=()=>{clearTimeout(c),d.signal.removeEventListener("abort",a),r()},a=()=>{clearTimeout(c),d.signal.removeEventListener("abort",a),t(new s("IDENTITY_CHANGED","Closing presentation was released"))},c=setTimeout(o,e);d.signal.addEventListener("abort",a,{once:!0}),d.signal.aborted&&a()});async function b(e,r){try{let t;for(let o=0;o<3;o++){if(l)throw new s("IDENTITY_CHANGED","Closing presentation was released");if(o&&(!m()||(await C(o===1?500:2e3),!m())))break;try{let a=p.get(i.client),c=r&&o===0?await(a?a(e.command,()=>{l||n!==e||(e.retained=!0,i.conceal())}):i.client.submit(e.command)):await i.client.retry();if(l)return c;if(!e.retained||!u(e))return n===e&&(n=void 0),await i.receive(c),c;t=new s("COMMAND_PENDING","Closing is still being confirmed. Retry the original request.")}catch(a){if(t=a,!e.retained||!u(e))throw a}}throw t??new s("COMMAND_PENDING","Closing is still being confirmed. Retry the original request.")}catch(t){throw!u(e)&&n===e&&(n=void 0),!l&&e.retained&&i.failed(t),t}}function f(e,r){if(e.flight)return e.flight;let t=b(e,r);e.flight=t;let o=()=>{e.flight===t&&(e.flight=void 0)};return t.then(o,o),t}function g(){if(l)return Promise.reject(new s("IDENTITY_CHANGED","Closing presentation was released"));let e=n;return!e||!u(e)?Promise.reject(new s("INVALID_REQUEST","No closing command is pending")):(!e.flight&&e.retained&&i.conceal(),f(e,!1))}let w=()=>{!l&&n?.retained&&!n.flight&&u(n)&&g().catch(()=>{})};return i.document.defaultView?.addEventListener("online",w),{get pending(){return n?.retained===!0},observe(){n&&!n.flight&&!u(n)&&(n=void 0)},submit(e){if(e.operation==="submit"&&e.input.type!=="screen")return Promise.reject(new s("INVALID_REQUEST","Presentation closure cannot execute a purchase"));if(l)return Promise.reject(new s("IDENTITY_CHANGED","Closing presentation was released"));if(n&&u(n)){let t=n.command;return t.operation===e.operation&&t.nodeId===e.nodeId&&t.visit===e.visit&&(t.operation==="close"||t.operation==="submit"&&e.operation==="submit"&&JSON.stringify(t.input)===JSON.stringify(e.input))?f(n,!n.retained):Promise.reject(new s("COMMAND_PENDING","Recover the original closing command"))}let r={command:e,retained:!1};return n=r,f(r,!0)},retry:g,destroy(){l=!0,d.abort(),i.document.defaultView?.removeEventListener("online",w)}}}export{P as a,v as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{B as p,C as u,D as d,E as f}from"./chunk-
|
|
1
|
+
import{B as p,C as u,D as d,E as f}from"./chunk-KLPRVDHS.js";import{v as y}from"./chunk-NPDRXDI7.js";import{a as s}from"./chunk-HLK7L2RV.js";function Q(e,t,r=new Set){let i={...t};return y(e.document.screen,n=>{if(n.hidden)return!1;if(n.type!=="quantity_picker"||r.has(n.id))return;let a=e.capabilities.quantities?.[n.id],o=a?.available?a.value:i[n.id]??n.defaultQuantity;if(a?.available&&(typeof o!="number"||!Number.isSafeInteger(o)||o<Math.max(n.minimumQuantity,a.minimum)||o>Math.min(n.maximumQuantity,a.maximum)||(o-n.minimumQuantity)%n.step!==0))throw new s("INVALID_RESPONSE","The current subscription quantity is outside this control's bounds");typeof o=="number"&&(i[n.id]=o)}),i}function V(e){let t=Object.create(null);for(let r of e.document.screen.actions){let i=r.properties.couponBinding,n=e.document.buttons[r.id];if(typeof i!="string"||n?.type!=="checkout")continue;let a=Object.hasOwn(e.capabilities.nodes,i)?e.capabilities.nodes[i]:void 0,{product:o}=n,b=o.type==="fixed"?[o.productVersionId]:o.allowedProductVersionIds,I=a?[a.base,...Object.values(a.byPlan??{})]:[],w=Object.fromEntries(I.flatMap(l=>l.planVersionId&&l.couponId&&l.text&&b.includes(l.planVersionId)?[[l.planVersionId,l]]:[]));t[r.id]={products:w,...o.type==="picker"?{picker:o.pickerId}:{}}}return Object.keys(t).length?{...e.capabilities,checkoutCoupons:t}:e.capabilities}function E(e,t){let r=structuredClone(e);for(let[i,n]of Object.entries(r.plans)){let a=t.plans[i];!a||a.versionId!==n.versionId||(a.amountMinor!==void 0&&(n.amountMinor=a.amountMinor),a.interval!==void 0&&(n.interval=a.interval),a.intervalCount!==void 0&&(n.intervalCount=a.intervalCount),a.prepaid!==void 0&&(n.prepaid=structuredClone(a.prepaid)))}return r}var h=class extends s{constructor(r="Plans were updated. Choose again.",i="套餐已更新,请重新选择。"){super("CONFLICT",r);this.zhMessage=i}zhMessage;customerMessage(r){return r?this.zhMessage:this.message}};function N(e,t){let r=i=>"document"in i?i.offering.id:i.content.offeringVersionId;return e.id===t.id&&r(e)===r(t)&&e.content?.artifact.sha256===t.content?.artifact.sha256}function D(e,t,r){if(e.operationId!==t.operationId||t.currency!==void 0&&"currency"in e&&e.currency!==t.currency||t.membershipId!==void 0&&(t.membershipId===null?u(e):!u(e)||e.membershipId!==t.membershipId)||t.featureQuantities!==void 0&&(!u(e)||!c(e.featureQuantities,t.featureQuantities)))throw new s("INVALID_RESPONSE",r)}function c(e,t){return Object.keys(e??{}).length===Object.keys(t??{}).length&&Object.entries(t??{}).every(([r,i])=>e?.[r]===i)}function P(e,t,r){if(p(e)){if(!t.subscriptionChange||e.membershipId!==t.subscriptionChange.membershipId||e.timing!==t.subscriptionChange.timing||e.productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||!c(e.featureQuantities,t.featureQuantities))throw new s("INVALID_RESPONSE",r);if(e.execution.provider==="merchant"){let n=e.execution.change,a=e.merchantTerms?.request;if(e.execution.membershipId!==e.membershipId||e.execution.timing!==e.timing||n.type!=="plan"||n.productVersionId!==e.productVersionId||!c(n.featureQuantities,e.featureQuantities)||a&&(a.action!=="subscription_change"||a.timing!==e.timing||a.change.type!=="plan"||a.change.productVersionId!==e.productVersionId||!c(a.change.featureQuantities,e.featureQuantities)))throw new s("INVALID_RESPONSE",r)}return}if(t.subscriptionChange)throw new s("INVALID_RESPONSE",r);let i=Object.fromEntries((e.lines[0]?.prepaid??[]).map(n=>[n.internal_feature_id,n.quantity]));if(t.featureQuantities&&(Object.keys(i).length!==Object.keys(t.featureQuantities).length||Object.entries(t.featureQuantities).some(([n,a])=>i[n]!==a)))throw new s("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(e.lines.length!==1||e.lines[0].productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||t.provider!==void 0&&e.provider!==t.provider&&!(t.provider==="stripe"&&e.provider==="merchant"&&e.execution?.provider==="merchant"))throw new s("INVALID_RESPONSE",r)}function m(e,t){if(e.operationId===t.operationId){if(p(e))P(t,{productVersionId:e.productVersionId,currency:e.currency,subscriptionChange:{membershipId:e.membershipId,timing:e.timing},featureQuantities:e.featureQuantities??{}},"The original membership change selection changed");else if(p(t))throw new s("INVALID_RESPONSE","The commercial operation kind changed")}}function C(e,t,r=!1){if(t&&u(t)&&t.quote&&!c(t.featureQuantities,t.quote.featureQuantities))throw new s("INVALID_RESPONSE","The original membership change quantities changed");if(t&&u(t)&&t.quote&&m(t.quote,t.quote),!e||e.operationId!==t?.operationId)return t;if(e.quote&&t.quote&&m(e.quote,t.quote),u(e)&&u(t)&&!c(e.featureQuantities,t.featureQuantities))throw new s("INVALID_RESPONSE","The original membership change quantities changed");let i=e.merchantExecution,n=t.merchantExecution;if(i&&(!n||Date.parse(n.updatedAt)<Date.parse(i.updatedAt)))return e;if(u(e)!==u(t))throw new s("INVALID_RESPONSE","The commercial operation kind changed");if(d(e)&&!d(t))return e;let a=t.status===e.status&&i?.recordingStatus!=="accepted"&&n?.recordingStatus==="accepted";return!f(e)&&(f(t)||r&&!d(t)&&!a)?e:t}function R(e){return e.screen.actions.some(t=>t.properties.closeControl==="content"&&e.buttons[t.id]?.type==="close")}export{Q as a,V as b,E as c,h as d,N as e,D as f,P as g,m as h,C as i,R as j};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as $,b as N,c as J,d as q}from"./chunk-MB2U2GWJ.js";import{a as P}from"./chunk-3VUPVXAV.js";import{a as D}from"./chunk-
|
|
2
|
-
/*! For license information please see chunk-
|
|
1
|
+
import{a as $,b as N,c as J,d as q}from"./chunk-MB2U2GWJ.js";import{a as P}from"./chunk-3VUPVXAV.js";import{a as D}from"./chunk-SUAUY6IF.js";import{a as _}from"./chunk-DSPLGTQI.js";import{b as C,c as O,e as j}from"./chunk-VPT5MFDG.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}function ue(e,t){let o,n;try{o=new URL(e),n=new URL(t)}catch{return t}return o.searchParams.forEach((r,s)=>{n.searchParams.has(s)||n.searchParams.set(s,r)}),n.toString()}function de(e,t){let o=navigator.userAgent,n=new URLSearchParams(t.search),r={};for(let s of["source","medium","campaign","term","content"]){let u=n.get(`utm_${s}`);u!==null&&(r[`utm${s[0].toUpperCase()}${s.slice(1)}`]=u)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(o)?"edge":/Chrome/.test(o)?"chrome":/Firefox/.test(o)?"firefox":/Safari/.test(o)?"safari":"unknown",deviceType:/Mobi/.test(o)?"mobile":"desktop",...r}}function le(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(n=>!!n&&!["namespace","status","url","groups"].some(r=>Object.hasOwn(n,r))&&(n.hashVersion===void 0||n.hashVersion===2)&&typeof n.key=="string"&&Array.isArray(n.variations)&&n.variations.length>=2&&n.variations.every(r=>!!r&&typeof r.urlRedirect=="string")&&(n.urlPatterns===void 0||Array.isArray(n.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function Te(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=J(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let o=e.fetch??globalThis.fetch.bind(globalThis),n=H(async(i,d)=>{let l=await o(i,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),r=e.log?(i,d)=>_(e.log,i,d):void 0,s=`${t}/api/v1/page-experiments/${e.environmentId}`,u=$(e.deviceIdCookie??"indiana_did"),p=N(),a=null,c={...e.attributes??{}},g="",f=!1,h=!1,m=0,y=0,b=new Map,S=F({endpoint:`${s}/events`,fetch:o,log:r,label:"Exposure"}),k=S.flush,E={trackedExperiments:new Set,log:r,onExperimentViewed:(i,d)=>{e.trackExposures===!1||a?.trackExposures===!1||S.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:u,...p?{sessionId:p}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:i.key,variationKey:d.key})}},z=()=>{E.url=location.href,E.attributes={...de(u,location),...c}};function W(i){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return i.variations.some(l=>{if(!l.urlRedirect)return!1;let v=new URL(l.urlRedirect);return v.protocol!==d.protocol||v.host!==d.host})}catch{return!0}}function X(i,d){let l=e.configuration?.snapshot?.generation,v=y,te=location.href;g=i;let re=e.navigate??(w=>location.replace(w)),ne=e.navigateDelay??(e.navigate?0:100),oe=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(w=>setTimeout(w,oe))]),new Promise(w=>setTimeout(w,ne))]).then(()=>{!f&&v===y&&location.href===te&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&re(i)})}function x(){if(!(!a||f||e.configuration&&!e.configuration.fresh)){z();for(let i of a.experiments){if(W(i)){r?.("Auto experiment blocked",{id:i.key});continue}let d;try{d=j(i,E)}catch(l){r?.("Skipping page experiment",{id:i.key,error:String(l)});continue}if(b.set(i.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=i.persistQueryString?ue(location.href,d.value.urlRedirect):d.value.urlRedirect;C(l,i.urlPatterns??[])?r?.("Skipping redirect because original URL matches redirect URL",{id:i.key}):l!==g&&X(l,k())}break}}}}let R="",Z=()=>{location.href!==R&&(y++,R=location.href,g="",x())},T,L;function ee(){T??=q(Z),addEventListener("pagehide",I)}let I=()=>{k()};async function A(){if(f)return!1;let i=++m,d;try{d=e.configuration?await e.configuration.pageExperiments():await n.read(s,V)}catch(v){if(f||i!==m)return!1;throw v}if(f||i!==m)return!1;let l=le(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return a?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),a=l,E.savedGroups=O(l.savedGroups),!0}function U(){f||(L??=e.configuration?.subscribe(()=>{!f&&e.configuration?.fresh&&A().then(i=>{i&&x()}).catch(i=>r?.("Page configuration unavailable",{error:String(i)}))}),ee(),R=location.href)}return{async start(){h||f||(h=!0,await A()&&(U(),x()))},async refresh(){await A()&&(y++,h&&U(),g="",x())},setAttributes(i){y++,g="",c={...i},x()},getResults(){return new Map(b)},get generation(){return a?.generation??null},destroy(){f||(f=!0,m++,n.destroy(),L?.(),T?.(),removeEventListener("pagehide",I),a=null,b.clear(),k())}}}export{be as a,H as b,F as c,ue as d,de as e,le as f,Te as g};
|
|
2
|
+
/*! For license information please see chunk-DKEQCWIR.js.LEGAL.txt */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as o}from"./chunk-
|
|
1
|
+
import{b as o}from"./chunk-35JZDDF3.js";var s=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],n=o.string().regex(/.+\/.+/),e=o.number().min(-100),t=o.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),p=o.strictObject({input:t,output:t,cache_read:t.optional(),cache_write:t.optional(),reasoning:t.optional(),input_audio:t.optional(),output_audio:t.optional()}),i=(r,a)=>o.record(r,a).refine(c=>Object.keys(c).length<=100,"At most 100 AI overrides"),d=o.strictObject({defaultMarkup:e,providerMarkups:i(o.string().min(1),e),modelMarkups:i(n,e),customModels:i(n,p.partial())});export{s as a,n as b,e as c,p as d,d as e};
|