@tinkerlandai/longplay-sdk 0.10.30 → 0.10.31

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 CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.31
4
+
5
+ - A Funnel purchase whose only open purchase is an unpaid merchant Checkout no longer stops the Customer from starting again. Starting the Funnel closes the Run that is waiting on that Checkout and opens a new Run with a normal Paywall. The merchant decides what a new selection does to the unpaid Checkout, and Longplay still refuses to confirm a second purchase while one is open.
6
+ - Paid, recording or fulfilling purchases, Indiana-executed Checkouts and any purchase with a pending command are still recovered before anything new starts.
7
+ - Wire protocol remains `0.10`; public APIs are unchanged.
8
+
3
9
  ## 0.10.30
4
10
 
5
11
  - When a merchant quote fails in a Funnel Paywall, the SDK checks the original command's settlement. Once the Run confirms that the failed purchase can be cleared, customers can choose a plan again.
@@ -1 +1 @@
1
- import{A as et,B as fe,F as tt,c as Be,d as Je,e as we,i as qe,j as He,k as $e,o as Ke,r as We}from"./chunk-XHQBABH6.js";import{d as Xe}from"./chunk-STPMMA64.js";import{c as Fe,d as Ne,e as Te,f as _e,g as Le,i as De,m as Me,n as k,o as ke,q as ye,r as N,t as Ge,u as je,v as ze}from"./chunk-4ZVVG5LM.js";import{$ as D,H as he,I as Ve,u as Ue}from"./chunk-ITVSLSRM.js";import{a as de,b as Qe}from"./chunk-CLAZ7NVN.js";import{a as ce}from"./chunk-J4VTKRH7.js";import{V as le}from"./chunk-WRUW2UIJ.js";import{a as L}from"./chunk-HJLGRW4A.js";import{h as oe}from"./chunk-XIP32WI7.js";import{b as Ze}from"./chunk-3VUPVXAV.js";import{b as Ye}from"./chunk-OHOROFWN.js";import{b as e}from"./chunk-ZY4XAKNQ.js";import{c as Ae,f as Pe}from"./chunk-6BTJNSQQ.js";var G=e.literal(Ue),ft=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),Ie=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),nt=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:Ie}),e.strictObject({type:e.literal("customer"),customer:he,customerData:Ve.optional()})]),ve=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),mt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:ve.omit({runId:!0,requestId:!0}).nullable()}),pt=e.union([Be,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),gt=Je.omit({authenticated:!0}).extend({identity:mt,instruction:pt.nullable()}),ht=e.discriminatedUnion("operation",[D.options[2].omit({customerToken:!0}),D.options[3].omit({customerToken:!0}),D.options[4].omit({customerToken:!0}),D.options[5].omit({customerToken:!0}),D.options[6].omit({customerToken:!0}),D.options[7].omit({customerToken:!0})]),me={contract:G,customerToken:e.string().regex(ce)},rt={contract:G,requestId:e.uuid(),runToken:ft,externalUserId:he.options[1].shape.value},ot=e.discriminatedUnion("operation",[e.strictObject({contract:G,operation:e.literal("describe")}),e.strictObject({contract:G,operation:e.literal("start"),source:nt,funnelId:D.options[0].shape.funnelId,requestId:e.uuid(),locale:D.options[0].shape.locale,parameters:D.options[0].shape.parameters}),qe.omit({operation:!0}).extend({contract:G,operation:e.literal("entry_start"),source:nt}),e.strictObject({...rt,operation:e.literal("bind_customer"),guestToken:Ie,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...rt,operation:e.literal("binding_status"),guestToken:Ie.optional()}),D.options[1].omit({operation:!0,customerToken:!0}).extend({...me,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),D.options[8].omit({operation:!0,customerToken:!0}).extend({...me,operation:e.literal("review")}),$e.omit({customerToken:!0}).extend(me),e.strictObject({...me,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:ht})]),yt=we.omit({run:!0}).extend({contract:G,run:gt,settlement:we.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Nt=He.extend({contract:G}),Tt=e.discriminatedUnion("operation",[ot.options[1].omit({contract:!0,source:!0,requestId:!0}),ot.options[2].omit({contract:!0,source:!0,requestId:!0})]),_t=yt.extend({binding:ve,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Lt=e.discriminatedUnion("state",[e.strictObject({contract:G,scope:oe,state:e.literal("not_accepted")}),e.strictObject({contract:G,scope:oe,state:e.literal("conflict")}),e.strictObject({contract:G,scope:oe,state:e.literal("bound"),binding:ve})]),Dt=e.strictObject({contract:G,scope:oe,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var it=e.string().regex(/^[a-f0-9]{64}$/),wt=Fe.omit({variations:!0,active:!0}).extend({changeId:it,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),at=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:it,experiments:e.array(wt).max(100),savedGroups:Ne}),It=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),kt=e.strictObject({events:e.array(It).min(1).max(20)}),Gt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Ht(r){let o=null,f=null,E=0,b=0,C=new Set,c=null,y=null,d=new Set,v=()=>{for(let s of d)try{s()}catch{}},l={attributes:le.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,w)=>{!C.has(s)&&o&&(!("analyticsConfig"in o)||o.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(w),structuredClone(l.attributes),o.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,w)=>o&&(!("analyticsConfig"in o)||o.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(w),structuredClone(l.attributes),o.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function p(s,w=new Set){return C.has(s)?!c||!c.features[s]||["unknownFeature","cyclicPrerequisite"].includes(c.features[s].source):w.has(s)?!1:(w.add(s),(o?.features[s]?.rules??[]).some(O=>[...O.parentConditions??[],...(O.tracks??[]).flatMap(A=>A.experiment.parentConditions??[])].some(A=>p(A.id,w))))}let x=s=>{if(r.assertUsable?.(o?.generation),!o)throw new Error("Initialize the Feature client before evaluation");if(o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return c?.expiresAt&&Date.parse(c.expiresAt)<=Date.now()&&(c=null,l.features=o.features),C.has(s)?!c||c.expiresAt&&Date.parse(c.expiresAt)<=Date.now()?S():structuredClone(c.features[s]??S()):r.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!c||p(s)?S():structuredClone(Pe(s,l))};async function U(){if(!o||!C.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=b;if(y?.revision===s)return y.loading;let w=E,O=o,A=[...C],R=(async()=>{let h=De.parse(await r.evaluateRemote({attributes:structuredClone(l.attributes),features:A}));if(!(w!==E||s!==b||O!==o)){if(r.assertUsable?.(O.generation),h.generation!==O.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(A.some(P=>!Object.hasOwn(h.features,P))||Object.keys(h.features).some(P=>!C.has(P)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!h.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=le.parse({...l.attributes,...h.merchandiseContext})}c=structuredClone(h),l.features={...O.features,...Object.fromEntries(Object.entries(c.features).map(([P,z])=>[P,{defaultValue:z.value}]))},v()}})();y={revision:s,loading:R};try{await R}finally{y?.loading===R&&(y=null)}}function T(){U().catch(s=>{try{r.onError?.(s)}catch{}})}async function M(){if(f)return f;let s=E,w=(async()=>{let O=await r.load(),A="remoteFeatures"in O?_e.parse(O):null,R=A??Te.parse(O);if(R.scope.projectId!==r.scope.projectId||R.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==E)throw new Error("Feature client was reset");if(r.assertUsable&&o?.generation===R.generation){let{evaluatedAt:P,expiresAt:z,...ie}=o,{evaluatedAt:Y,expiresAt:pe,...j}=R;if(N(ie)!==N(j))throw new Error("Immutable Feature generation changed content");return o.evaluatedAt=R.evaluatedAt,o.expiresAt=R.expiresAt,v(),(!c||c.expiresAt&&Date.parse(c.expiresAt)<=Date.now())&&T(),structuredClone(o)}let h=new Set(A?.remoteFeatures??[]);if([...h].some(P=>Object.hasOwn(R.features,P)))throw new Error("Remote Feature definitions must not be delivered locally");return o&&"analyticsConfig"in o&&"analyticsConfig"in R&&!o.analyticsConfig.experimentViewsEnabled&&A?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),o=structuredClone(R),C=h,c=null,y=null,b++,l.features=o.features,l.savedGroups=Ae(o.savedGroups),l.trackedFeatureUsage={},v(),T(),structuredClone(o)})();f=w;try{return await w}finally{f===w&&(f=null)}}return{init:M,refresh:M,refreshRemote:U,get generation(){return o?.generation??null},get expiresAt(){return o?.expiresAt??null},subscribe(s){return d.add(s),()=>{d.delete(s)}},setAttributes(s){let w=le.parse(s);(l.attributes?.merchandise||l.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=w,b++,c=null,y=null,l.features=o?.features??{},l.trackedFeatureUsage={},v(),T()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,w){let O=x(s).value;return structuredClone(O===null?w:O)},reset(){E++,b++,f=null,y=null,o=null,c=null,C.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),v()}}}var vt=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),K=2*1048576,bt=100;function St(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function st(r,o){let f=o===void 0?St():o,E=new Map,b=0,C=!1,c=!1,y,d;async function v(S){if(!f)return null;let p;try{let x=await Promise.race([Promise.resolve().then(()=>f.getItem(S)),new Promise(U=>{p=setTimeout(()=>U(null),bt)})]);return typeof x=="string"&&x.length<=K&&new TextEncoder().encode(x).byteLength<=K?x:null}catch{return null}finally{clearTimeout(p)}}function l(){if(d)return d;let S=(async()=>{try{let p=await v(`${r}:artifacts`);if(p)return vt.parse(JSON.parse(p))}catch{}return{}})();return d=S,S.finally(()=>{d===S&&(d=void 0)}),S}return{async readManifest(){return v(r)},writeManifest(S){!f||S.length>K||new TextEncoder().encode(S).byteLength>K||(y=S,!c&&(c=!0,Promise.resolve().then(async()=>{try{for(;y!==void 0;){let p=y;try{await f.setItem(r,p)}catch{}y===p&&(y=void 0)}}finally{c=!1}})))},async readArtifact(S){let p=(await l())[S],x=Date.now();return p&&x>=p.at&&x-p.at<=k.retentionMs?p.text:void 0},writeArtifact(S,p){if(!f||p.length>K)return;let x=E.get(S);if(x?.text===p||!x&&E.size>=128)return;let U=new TextEncoder().encode(p).byteLength;b-(x?.byteLength??0)+U>K||(E.set(S,{text:p,byteLength:U}),b+=U-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;E.size;){let T=new Map(E);try{let M={...await l()},s=Date.now();for(let[R,h]of T)M[R]={at:s,text:h.text};let w={},O=2,A=0;for(let[R,h]of Object.entries(M).sort(([,P],[,z])=>z.at-P.at)){if(h.at>s||s-h.at>k.retentionMs)continue;let P=new TextEncoder().encode(JSON.stringify({[R]:h})).byteLength;O+P>K||A>=128||(w[R]=h,O+=P,A++)}await f.setItem(`${r}:artifacts`,JSON.stringify(w))}catch{}finally{for(let[M,s]of T)E.get(M)===s&&(E.delete(M),b-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,o)=>new L(r,o),q=()=>performance.now(),ut=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function ln(r){let o=ke.parse(r.scope),f=new de(r.origin??Ye);if(f.username||f.password||f.search||f.hash||f.pathname!=="/"||f.protocol!=="https:"&&!(f.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(f.hostname)))throw u("INVALID_URL","Configuration requires a trusted HTTPS origin");let E=new Set([f.origin,...(r.assetOrigins??[]).map(n=>{let t=new de(n);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return t.origin})]),b=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${o.environmentId}`,c=`indiana:configuration:1:${f.origin}:${N(o)}`,y=st(c,r.storage),d,v=0,l=0,S=!1,p=!1,x=0,U=0,T,M,s,w,O=0,A=new Set,R=new Set,h=new Map,P=new Map,z=0,ie=!1;function Y(){for(let n of A)try{n()}catch{}}function pe(n){try{r.onError?.(n)}catch{}}let j=()=>!p&&!S&&!!d&&q()<v&&Date.now()<l;function ne(){if(!j())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function be(n,t,i){if(!h.has(n)){for(;h.size&&(h.size>=128||z+i>k.maxCacheBytes);){let a=h.entries().next().value;z-=a[1].byteLength,h.delete(a[0])}h.set(n,{text:t,byteLength:i}),z+=i}}function Se(n,t,i){return Ze(n,t,{signal:i,error:a=>u("INVALID_RESPONSE",a==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function xe(n){let t=new de(n,f);if(!E.has(t.origin)||t.username||t.password||t.hash||t.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return t.href}async function ge(n,t,i=!1){let a=await b(xe(n),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:t,headers:{}});if(a.status===429){let g=a.headers.get("retry-after")??"";O=/^\d+$/.test(g)?Number(g)*1e3:Math.max(0,Date.parse(g)-Date.now())||15e3}if(!a.ok&&a.status!==304)throw u(`CONFIGURATION_HTTP_${a.status}`,"Configuration synchronization failed");return a}function lt(n,t,i){let a=Date.parse(n.headers.get("x-indiana-config-validated-at")??""),g=Date.parse(n.headers.get("x-indiana-config-valid-until")??""),I=Date.parse(n.headers.get("date")??""),m=n.headers.get("age"),V=m!==null&&/^\d+(\.\d+)?$/.test(m)?Number(m)*1e3:NaN;if(![a,g,I,V].every(Number.isFinite)||g<=a||g-a>k.maxControlAgeMs||a>I+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let F=Math.min(g-a,i.maxControlAgeSeconds*1e3,k.maxControlAgeMs)-Math.max(V,I-a,0)-(q()-t);if(F<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return q()+F}function ae(){if(clearTimeout(s),clearTimeout(w),p||!A.size||(j()&&(w=setTimeout(()=>{j()?ae():Y()},Math.max(1,v-q())),ut(w)),typeof document<"u"&&document.visibilityState==="hidden"))return;let n=U?Math.min(15e3,1e3*2**Math.min(U-1,4)):Math.min(15e3,(d?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{Q().catch(pe)},Math.max(O,n*(.8+Math.random()*.2))),ut(s)}async function Q(){if(p)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(T)return T;let n=x,t=new AbortController;M=t;let i=(async()=>{if(!ie){ie=!0;try{let ue=await y.readManifest();if(ue&&!d){let J=ye.parse(JSON.parse(ue));N(J.scope)===N(o)&&(d=J)}}catch{}}t.signal.throwIfAborted();let m=d,V=q(),_=await ge(C,t.signal);_.status===304&&(!m||!_.headers.has("x-indiana-config-validated-at")||!_.headers.has("x-indiana-config-valid-until")||!_.headers.has("age"))&&(_=await ge(C,t.signal));let F=_.status===304?m:ye.parse(JSON.parse(await Se(_,k.maxManifestBytes,t.signal))),{generation:ee,...te}=F,B=_.headers.get("etag");if(N(F.scope)!==N(o)||Ge(te)!==ee||B!==`"${ee}"`&&B!==`W/"${ee}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(m&&(F.revision<m.revision||F.revision===m.revision&&F.generation!==m.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ue,J]of Object.entries(m?.funnels??{})){let $=F.funnels[ue];if($&&($.controlRevision<J.controlRevision||$.evaluationRevision<J.evaluationRevision||$.controlRevision===J.controlRevision&&$.state!==J.state||$.evaluationRevision===J.evaluationRevision&&$.evaluationMode!==J.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let H=lt(_,V,F.policy);if(t.signal.throwIfAborted(),n!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return d=F,v=H,l=Date.now()+Math.max(0,H-q()),S=!1,U=0,O=0,y.writeManifest(N(F)),Y(),structuredClone(F)})(),a=setTimeout(()=>t.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),k.initializationMs),g=new Promise((m,V)=>t.signal.addEventListener("abort",()=>V(t.signal.reason),{once:!0})),I=Promise.race([i,g]).catch(m=>{throw U++,(m instanceof e.ZodError||m instanceof SyntaxError||m instanceof L&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(m.code))&&(v=0,S=!0,Y()),m}).finally(()=>{clearTimeout(a),T===I&&(T=void 0),ae()});return T=I,I}async function se(n){let t=n.sha256,i=te=>Xe(te,n);xe(n.url);let a=h.get(t);if(a){if(a.byteLength!==n.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return h.delete(t),h.set(t,a),a.text}let g=P.get(t);if(g){if(g.byteLength!==n.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return g.promise}let I=new AbortController;R.add(I);let m=x,V=(async()=>{try{let H=await y.readArtifact(t);if(H&&i(H)){if(I.signal.throwIfAborted(),p||m!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return be(t,H,n.byteLength),H}}catch{}I.signal.throwIfAborted();let te=await ge(n.url,I.signal,!0),B=await Se(te,n.byteLength,I.signal);if(!i(B))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(p||m!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return be(t,B,n.byteLength),y.writeArtifact(t,B),B})(),_=setTimeout(()=>I.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),k.initializationMs),F=new Promise((te,B)=>I.signal.addEventListener("abort",()=>B(I.signal.reason),{once:!0})),ee=Promise.race([V,F]).finally(()=>{clearTimeout(_),R.delete(I),P.delete(t)});return P.set(t,{promise:ee,byteLength:n.byteLength}),ee}async function re(){return j()||await Q(),ne(),d}async function W(n){let t,i=new Promise((a,g)=>{t=setTimeout(()=>g(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),k.initializationMs)});try{return await Promise.race([n(),i])}finally{clearTimeout(t)}}function Z(n,t){if(ne(),d?.generation!==n.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(t&&d.funnels[t]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Ee(n){let t=n.gb.features;if(!t)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=n.artifacts[t];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let a=Le.parse(JSON.parse(await se(i)));if(N(a.scope)!==N({projectId:o.projectId,environment:o.environment})||a.generation!==i.generation||a.remoteFeatures.some(g=>Object.hasOwn(a.features,g)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Z(n),{...a,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,v-q())).toISOString()}}async function Ce(n,t){let i=await re(),a=i.funnels[n];t&&(!a||a.evaluationMode==="local"&&!a.versions[t])&&(T&&await T,i=await Q()),Z(i,n);let g=i.funnels[n];if(g.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let I=t??g.currentVersionId,m=g.versions[I];if(!m)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[m.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[V,_]=await Promise.all([se(i.artifacts[m.artifact]).then(F=>ze(JSON.parse(F))),g.evaluationMode==="local"?Ee(i):void 0]);if(_&&N(je(V,_))!==N(m.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Z(i,n),{document:V,growth:_,versionId:I,control:structuredClone(g),manifest:structuredClone(i)}}async function Re(n,t){try{return await Ce(n,t)}catch(i){if(!(i instanceof L)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&j()))throw i;let a=d?.generation;if(T&&await T,await Q(),i.code!=="CONFIGURATION_CHANGED"&&d?.generation===a)throw i;return Ce(n,t)}}function X(){if(j()||Y(),typeof document<"u"&&document.visibilityState==="hidden"){ae();return}Q().catch(pe)}function dt(n){if(p)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return A.add(n),A.size===1&&(typeof window<"u"&&(window.addEventListener("online",X),window.addEventListener("focus",X),document.addEventListener("visibilitychange",X)),ae()),()=>{A.delete(n),A.size||(clearTimeout(s),clearTimeout(w),Oe())}}function Oe(){typeof window<"u"&&(window.removeEventListener("online",X),window.removeEventListener("focus",X),document.removeEventListener("visibilitychange",X))}return{scope:Object.freeze({...o}),refresh:Q,subscribe:dt,assertFresh:ne,assertFeatures(n){ne();let t=d.gb.features;if(!t)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(n!==void 0&&d.artifacts[t].generation!==n)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return j()},get snapshot(){return d?structuredClone(d):null},get remainingMs(){return j()?Math.max(0,v-q()):0},async features(){return W(async()=>Ee(await re()))},pageExperiments:()=>W(async()=>{let n=await re(),t=n.gb.pageExperiments;if(!t)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=n.artifacts[t];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let a=at.parse(JSON.parse(await se(i)));if(a.environmentId!==o.environmentId||a.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return Z(n),a}),funnel:(n,t)=>W(()=>Re(n,t)),funnelControl:n=>W(async()=>{let t=await re();return Z(t,n),structuredClone(t.funnels[n])}),paywall:(n,t)=>W(async()=>{let i=await re(),a=i.paywalls?.[n];if(!a||!t&&a.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let g=t??a.currentVersionId,I=a.versions[g],m=I&&i.artifacts[I.artifact];if(!m||m.kind!=="paywall"||m.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let V=Me.parse(JSON.parse(await se(m)));return Z(i),{document:V,versionId:g,version:I.version,control:structuredClone(a),manifest:structuredClone(i)}}),async localFunnel(n,t){let i=await W(()=>Re(n,t));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:a,remoteFeatures:g,...I}=i.growth;return Ke({scope:{projectId:o.projectId,environment:o.environment},funnelId:n,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:I})},assertFunnel(n,t,i){ne();let a=d.funnels[n];if(!a||a.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(a.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(t!==void 0&&a.controlRevision!==t)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!a.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!p){p=!0,x++,v=0,M?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(w),Oe(),Y(),A.clear();for(let n of R)n.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));h.clear(),z=0}}}}function ct(r){let o=ce.test(r.apiKey);if(typeof window<"u"&&!o)throw new L("SERVER_ONLY","Funnel starts are issued by your backend");if(!o&&!fe.test(r.apiKey))throw new L("INVALID_TOKEN","A customer credential or server API key is required");return{async start(f){let E=D.safeParse({...f,operation:"start"});if(!E.success||E.data.operation!=="start"||(o?E.data.customer!==void 0:E.data.customer===void 0))throw new L("INVALID_REQUEST","Invalid current Funnel start");let b=E.data,C=Qe({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let c=We(r,await C.request("funnels",b));if(!c.runToken)throw new L("INVALID_RESPONSE","Funnel start credentials are missing");if(c.run.source.id!==b.funnelId||c.run.locale!==(b.locale??"en")||!et(c.run.parameters,b.parameters??{})||(b.customer?!c.customerId||b.customer.type==="id"&&c.customerId!==b.customer.value:c.customerId!==void 0))throw new L("INVALID_RESPONSE","Funnel start contract changed");return{...c,runToken:c.runToken}}finally{C.dispose()}}}}async function En(r){r={...r};let o=r.configuration;if(!o)throw new L("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let f={projectId:o.scope.projectId,environment:o.scope.environment};if(r.scope&&N(f)!==N(r.scope))throw new L("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await o.funnelControl(r.funnelId)).evaluationMode!=="local")throw new L("EVALUATION_MODE","This Funnel uses Remote evaluation");let b=fe.test(r.credential);if(b?!r.customerId:r.customerId!==void 0)throw new L("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=ct({...r,scope:f,apiKey:r.credential}),c=(y,d)=>{let v=tt({...r,scope:f,runToken:y,initialResponse:d,...b?{serverKey:r.credential}:{}});return b||v.identify(r.credential),v};return{async start(y){let d=await C.start({...y,funnelId:r.funnelId,...b?{customer:{type:"id",value:r.customerId}}:{}}),v=c(d.runToken,d),l=await v.get();return{...d,...l,controller:v}},async restore(y){let d=c(y),v=await d.get();if(v.run.source.id!==r.funnelId)throw d.reset(),new L("SCOPE_MISMATCH","Run belongs to another Funnel");return{...v,runToken:y,controller:d}}}}export{ot as a,yt as b,Nt as c,Tt as d,_t as e,Lt as f,Dt as g,Ht as h,ln as i,ct as j,En as k};
1
+ import{A as et,B as fe,F as tt,c as Be,d as Je,e as we,i as qe,j as He,k as $e,o as Ke,r as We}from"./chunk-7Z7JT4HE.js";import{d as Xe}from"./chunk-WK4WQZHK.js";import{c as Fe,d as Ne,e as Te,f as _e,g as Le,i as De,m as Me,n as k,o as ke,q as ye,r as N,t as Ge,u as je,v as ze}from"./chunk-4ZVVG5LM.js";import{$ as D,H as he,I as Ve,u as Ue}from"./chunk-ITVSLSRM.js";import{a as de,b as Qe}from"./chunk-XZEGVBAI.js";import{a as ce}from"./chunk-J4VTKRH7.js";import{V as le}from"./chunk-WRUW2UIJ.js";import{a as L}from"./chunk-HJLGRW4A.js";import{h as oe}from"./chunk-XIP32WI7.js";import{b as Ze}from"./chunk-3VUPVXAV.js";import{b as Ye}from"./chunk-FVGUBIVT.js";import{b as e}from"./chunk-ZY4XAKNQ.js";import{c as Ae,f as Pe}from"./chunk-6BTJNSQQ.js";var G=e.literal(Ue),ft=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),Ie=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),nt=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:Ie}),e.strictObject({type:e.literal("customer"),customer:he,customerData:Ve.optional()})]),ve=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),mt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:ve.omit({runId:!0,requestId:!0}).nullable()}),pt=e.union([Be,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),gt=Je.omit({authenticated:!0}).extend({identity:mt,instruction:pt.nullable()}),ht=e.discriminatedUnion("operation",[D.options[2].omit({customerToken:!0}),D.options[3].omit({customerToken:!0}),D.options[4].omit({customerToken:!0}),D.options[5].omit({customerToken:!0}),D.options[6].omit({customerToken:!0}),D.options[7].omit({customerToken:!0})]),me={contract:G,customerToken:e.string().regex(ce)},rt={contract:G,requestId:e.uuid(),runToken:ft,externalUserId:he.options[1].shape.value},ot=e.discriminatedUnion("operation",[e.strictObject({contract:G,operation:e.literal("describe")}),e.strictObject({contract:G,operation:e.literal("start"),source:nt,funnelId:D.options[0].shape.funnelId,requestId:e.uuid(),locale:D.options[0].shape.locale,parameters:D.options[0].shape.parameters}),qe.omit({operation:!0}).extend({contract:G,operation:e.literal("entry_start"),source:nt}),e.strictObject({...rt,operation:e.literal("bind_customer"),guestToken:Ie,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...rt,operation:e.literal("binding_status"),guestToken:Ie.optional()}),D.options[1].omit({operation:!0,customerToken:!0}).extend({...me,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),D.options[8].omit({operation:!0,customerToken:!0}).extend({...me,operation:e.literal("review")}),$e.omit({customerToken:!0}).extend(me),e.strictObject({...me,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:ht})]),yt=we.omit({run:!0}).extend({contract:G,run:gt,settlement:we.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Nt=He.extend({contract:G}),Tt=e.discriminatedUnion("operation",[ot.options[1].omit({contract:!0,source:!0,requestId:!0}),ot.options[2].omit({contract:!0,source:!0,requestId:!0})]),_t=yt.extend({binding:ve,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Lt=e.discriminatedUnion("state",[e.strictObject({contract:G,scope:oe,state:e.literal("not_accepted")}),e.strictObject({contract:G,scope:oe,state:e.literal("conflict")}),e.strictObject({contract:G,scope:oe,state:e.literal("bound"),binding:ve})]),Dt=e.strictObject({contract:G,scope:oe,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var it=e.string().regex(/^[a-f0-9]{64}$/),wt=Fe.omit({variations:!0,active:!0}).extend({changeId:it,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),at=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:it,experiments:e.array(wt).max(100),savedGroups:Ne}),It=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),kt=e.strictObject({events:e.array(It).min(1).max(20)}),Gt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Ht(r){let o=null,f=null,E=0,b=0,C=new Set,c=null,y=null,d=new Set,v=()=>{for(let s of d)try{s()}catch{}},l={attributes:le.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,w)=>{!C.has(s)&&o&&(!("analyticsConfig"in o)||o.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(w),structuredClone(l.attributes),o.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,w)=>o&&(!("analyticsConfig"in o)||o.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(w),structuredClone(l.attributes),o.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function p(s,w=new Set){return C.has(s)?!c||!c.features[s]||["unknownFeature","cyclicPrerequisite"].includes(c.features[s].source):w.has(s)?!1:(w.add(s),(o?.features[s]?.rules??[]).some(O=>[...O.parentConditions??[],...(O.tracks??[]).flatMap(A=>A.experiment.parentConditions??[])].some(A=>p(A.id,w))))}let x=s=>{if(r.assertUsable?.(o?.generation),!o)throw new Error("Initialize the Feature client before evaluation");if(o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return c?.expiresAt&&Date.parse(c.expiresAt)<=Date.now()&&(c=null,l.features=o.features),C.has(s)?!c||c.expiresAt&&Date.parse(c.expiresAt)<=Date.now()?S():structuredClone(c.features[s]??S()):r.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!c||p(s)?S():structuredClone(Pe(s,l))};async function U(){if(!o||!C.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=b;if(y?.revision===s)return y.loading;let w=E,O=o,A=[...C],R=(async()=>{let h=De.parse(await r.evaluateRemote({attributes:structuredClone(l.attributes),features:A}));if(!(w!==E||s!==b||O!==o)){if(r.assertUsable?.(O.generation),h.generation!==O.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(A.some(P=>!Object.hasOwn(h.features,P))||Object.keys(h.features).some(P=>!C.has(P)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!h.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=le.parse({...l.attributes,...h.merchandiseContext})}c=structuredClone(h),l.features={...O.features,...Object.fromEntries(Object.entries(c.features).map(([P,z])=>[P,{defaultValue:z.value}]))},v()}})();y={revision:s,loading:R};try{await R}finally{y?.loading===R&&(y=null)}}function T(){U().catch(s=>{try{r.onError?.(s)}catch{}})}async function M(){if(f)return f;let s=E,w=(async()=>{let O=await r.load(),A="remoteFeatures"in O?_e.parse(O):null,R=A??Te.parse(O);if(R.scope.projectId!==r.scope.projectId||R.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==E)throw new Error("Feature client was reset");if(r.assertUsable&&o?.generation===R.generation){let{evaluatedAt:P,expiresAt:z,...ie}=o,{evaluatedAt:Y,expiresAt:pe,...j}=R;if(N(ie)!==N(j))throw new Error("Immutable Feature generation changed content");return o.evaluatedAt=R.evaluatedAt,o.expiresAt=R.expiresAt,v(),(!c||c.expiresAt&&Date.parse(c.expiresAt)<=Date.now())&&T(),structuredClone(o)}let h=new Set(A?.remoteFeatures??[]);if([...h].some(P=>Object.hasOwn(R.features,P)))throw new Error("Remote Feature definitions must not be delivered locally");return o&&"analyticsConfig"in o&&"analyticsConfig"in R&&!o.analyticsConfig.experimentViewsEnabled&&A?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),o=structuredClone(R),C=h,c=null,y=null,b++,l.features=o.features,l.savedGroups=Ae(o.savedGroups),l.trackedFeatureUsage={},v(),T(),structuredClone(o)})();f=w;try{return await w}finally{f===w&&(f=null)}}return{init:M,refresh:M,refreshRemote:U,get generation(){return o?.generation??null},get expiresAt(){return o?.expiresAt??null},subscribe(s){return d.add(s),()=>{d.delete(s)}},setAttributes(s){let w=le.parse(s);(l.attributes?.merchandise||l.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=w,b++,c=null,y=null,l.features=o?.features??{},l.trackedFeatureUsage={},v(),T()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,w){let O=x(s).value;return structuredClone(O===null?w:O)},reset(){E++,b++,f=null,y=null,o=null,c=null,C.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),v()}}}var vt=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),K=2*1048576,bt=100;function St(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function st(r,o){let f=o===void 0?St():o,E=new Map,b=0,C=!1,c=!1,y,d;async function v(S){if(!f)return null;let p;try{let x=await Promise.race([Promise.resolve().then(()=>f.getItem(S)),new Promise(U=>{p=setTimeout(()=>U(null),bt)})]);return typeof x=="string"&&x.length<=K&&new TextEncoder().encode(x).byteLength<=K?x:null}catch{return null}finally{clearTimeout(p)}}function l(){if(d)return d;let S=(async()=>{try{let p=await v(`${r}:artifacts`);if(p)return vt.parse(JSON.parse(p))}catch{}return{}})();return d=S,S.finally(()=>{d===S&&(d=void 0)}),S}return{async readManifest(){return v(r)},writeManifest(S){!f||S.length>K||new TextEncoder().encode(S).byteLength>K||(y=S,!c&&(c=!0,Promise.resolve().then(async()=>{try{for(;y!==void 0;){let p=y;try{await f.setItem(r,p)}catch{}y===p&&(y=void 0)}}finally{c=!1}})))},async readArtifact(S){let p=(await l())[S],x=Date.now();return p&&x>=p.at&&x-p.at<=k.retentionMs?p.text:void 0},writeArtifact(S,p){if(!f||p.length>K)return;let x=E.get(S);if(x?.text===p||!x&&E.size>=128)return;let U=new TextEncoder().encode(p).byteLength;b-(x?.byteLength??0)+U>K||(E.set(S,{text:p,byteLength:U}),b+=U-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;E.size;){let T=new Map(E);try{let M={...await l()},s=Date.now();for(let[R,h]of T)M[R]={at:s,text:h.text};let w={},O=2,A=0;for(let[R,h]of Object.entries(M).sort(([,P],[,z])=>z.at-P.at)){if(h.at>s||s-h.at>k.retentionMs)continue;let P=new TextEncoder().encode(JSON.stringify({[R]:h})).byteLength;O+P>K||A>=128||(w[R]=h,O+=P,A++)}await f.setItem(`${r}:artifacts`,JSON.stringify(w))}catch{}finally{for(let[M,s]of T)E.get(M)===s&&(E.delete(M),b-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,o)=>new L(r,o),q=()=>performance.now(),ut=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function ln(r){let o=ke.parse(r.scope),f=new de(r.origin??Ye);if(f.username||f.password||f.search||f.hash||f.pathname!=="/"||f.protocol!=="https:"&&!(f.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(f.hostname)))throw u("INVALID_URL","Configuration requires a trusted HTTPS origin");let E=new Set([f.origin,...(r.assetOrigins??[]).map(n=>{let t=new de(n);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return t.origin})]),b=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${o.environmentId}`,c=`indiana:configuration:1:${f.origin}:${N(o)}`,y=st(c,r.storage),d,v=0,l=0,S=!1,p=!1,x=0,U=0,T,M,s,w,O=0,A=new Set,R=new Set,h=new Map,P=new Map,z=0,ie=!1;function Y(){for(let n of A)try{n()}catch{}}function pe(n){try{r.onError?.(n)}catch{}}let j=()=>!p&&!S&&!!d&&q()<v&&Date.now()<l;function ne(){if(!j())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function be(n,t,i){if(!h.has(n)){for(;h.size&&(h.size>=128||z+i>k.maxCacheBytes);){let a=h.entries().next().value;z-=a[1].byteLength,h.delete(a[0])}h.set(n,{text:t,byteLength:i}),z+=i}}function Se(n,t,i){return Ze(n,t,{signal:i,error:a=>u("INVALID_RESPONSE",a==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function xe(n){let t=new de(n,f);if(!E.has(t.origin)||t.username||t.password||t.hash||t.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return t.href}async function ge(n,t,i=!1){let a=await b(xe(n),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:t,headers:{}});if(a.status===429){let g=a.headers.get("retry-after")??"";O=/^\d+$/.test(g)?Number(g)*1e3:Math.max(0,Date.parse(g)-Date.now())||15e3}if(!a.ok&&a.status!==304)throw u(`CONFIGURATION_HTTP_${a.status}`,"Configuration synchronization failed");return a}function lt(n,t,i){let a=Date.parse(n.headers.get("x-indiana-config-validated-at")??""),g=Date.parse(n.headers.get("x-indiana-config-valid-until")??""),I=Date.parse(n.headers.get("date")??""),m=n.headers.get("age"),V=m!==null&&/^\d+(\.\d+)?$/.test(m)?Number(m)*1e3:NaN;if(![a,g,I,V].every(Number.isFinite)||g<=a||g-a>k.maxControlAgeMs||a>I+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let F=Math.min(g-a,i.maxControlAgeSeconds*1e3,k.maxControlAgeMs)-Math.max(V,I-a,0)-(q()-t);if(F<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return q()+F}function ae(){if(clearTimeout(s),clearTimeout(w),p||!A.size||(j()&&(w=setTimeout(()=>{j()?ae():Y()},Math.max(1,v-q())),ut(w)),typeof document<"u"&&document.visibilityState==="hidden"))return;let n=U?Math.min(15e3,1e3*2**Math.min(U-1,4)):Math.min(15e3,(d?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{Q().catch(pe)},Math.max(O,n*(.8+Math.random()*.2))),ut(s)}async function Q(){if(p)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(T)return T;let n=x,t=new AbortController;M=t;let i=(async()=>{if(!ie){ie=!0;try{let ue=await y.readManifest();if(ue&&!d){let J=ye.parse(JSON.parse(ue));N(J.scope)===N(o)&&(d=J)}}catch{}}t.signal.throwIfAborted();let m=d,V=q(),_=await ge(C,t.signal);_.status===304&&(!m||!_.headers.has("x-indiana-config-validated-at")||!_.headers.has("x-indiana-config-valid-until")||!_.headers.has("age"))&&(_=await ge(C,t.signal));let F=_.status===304?m:ye.parse(JSON.parse(await Se(_,k.maxManifestBytes,t.signal))),{generation:ee,...te}=F,B=_.headers.get("etag");if(N(F.scope)!==N(o)||Ge(te)!==ee||B!==`"${ee}"`&&B!==`W/"${ee}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(m&&(F.revision<m.revision||F.revision===m.revision&&F.generation!==m.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ue,J]of Object.entries(m?.funnels??{})){let $=F.funnels[ue];if($&&($.controlRevision<J.controlRevision||$.evaluationRevision<J.evaluationRevision||$.controlRevision===J.controlRevision&&$.state!==J.state||$.evaluationRevision===J.evaluationRevision&&$.evaluationMode!==J.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let H=lt(_,V,F.policy);if(t.signal.throwIfAborted(),n!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return d=F,v=H,l=Date.now()+Math.max(0,H-q()),S=!1,U=0,O=0,y.writeManifest(N(F)),Y(),structuredClone(F)})(),a=setTimeout(()=>t.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),k.initializationMs),g=new Promise((m,V)=>t.signal.addEventListener("abort",()=>V(t.signal.reason),{once:!0})),I=Promise.race([i,g]).catch(m=>{throw U++,(m instanceof e.ZodError||m instanceof SyntaxError||m instanceof L&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(m.code))&&(v=0,S=!0,Y()),m}).finally(()=>{clearTimeout(a),T===I&&(T=void 0),ae()});return T=I,I}async function se(n){let t=n.sha256,i=te=>Xe(te,n);xe(n.url);let a=h.get(t);if(a){if(a.byteLength!==n.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return h.delete(t),h.set(t,a),a.text}let g=P.get(t);if(g){if(g.byteLength!==n.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return g.promise}let I=new AbortController;R.add(I);let m=x,V=(async()=>{try{let H=await y.readArtifact(t);if(H&&i(H)){if(I.signal.throwIfAborted(),p||m!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return be(t,H,n.byteLength),H}}catch{}I.signal.throwIfAborted();let te=await ge(n.url,I.signal,!0),B=await Se(te,n.byteLength,I.signal);if(!i(B))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(p||m!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return be(t,B,n.byteLength),y.writeArtifact(t,B),B})(),_=setTimeout(()=>I.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),k.initializationMs),F=new Promise((te,B)=>I.signal.addEventListener("abort",()=>B(I.signal.reason),{once:!0})),ee=Promise.race([V,F]).finally(()=>{clearTimeout(_),R.delete(I),P.delete(t)});return P.set(t,{promise:ee,byteLength:n.byteLength}),ee}async function re(){return j()||await Q(),ne(),d}async function W(n){let t,i=new Promise((a,g)=>{t=setTimeout(()=>g(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),k.initializationMs)});try{return await Promise.race([n(),i])}finally{clearTimeout(t)}}function Z(n,t){if(ne(),d?.generation!==n.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(t&&d.funnels[t]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Ee(n){let t=n.gb.features;if(!t)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=n.artifacts[t];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let a=Le.parse(JSON.parse(await se(i)));if(N(a.scope)!==N({projectId:o.projectId,environment:o.environment})||a.generation!==i.generation||a.remoteFeatures.some(g=>Object.hasOwn(a.features,g)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Z(n),{...a,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,v-q())).toISOString()}}async function Ce(n,t){let i=await re(),a=i.funnels[n];t&&(!a||a.evaluationMode==="local"&&!a.versions[t])&&(T&&await T,i=await Q()),Z(i,n);let g=i.funnels[n];if(g.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let I=t??g.currentVersionId,m=g.versions[I];if(!m)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[m.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[V,_]=await Promise.all([se(i.artifacts[m.artifact]).then(F=>ze(JSON.parse(F))),g.evaluationMode==="local"?Ee(i):void 0]);if(_&&N(je(V,_))!==N(m.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Z(i,n),{document:V,growth:_,versionId:I,control:structuredClone(g),manifest:structuredClone(i)}}async function Re(n,t){try{return await Ce(n,t)}catch(i){if(!(i instanceof L)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&j()))throw i;let a=d?.generation;if(T&&await T,await Q(),i.code!=="CONFIGURATION_CHANGED"&&d?.generation===a)throw i;return Ce(n,t)}}function X(){if(j()||Y(),typeof document<"u"&&document.visibilityState==="hidden"){ae();return}Q().catch(pe)}function dt(n){if(p)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return A.add(n),A.size===1&&(typeof window<"u"&&(window.addEventListener("online",X),window.addEventListener("focus",X),document.addEventListener("visibilitychange",X)),ae()),()=>{A.delete(n),A.size||(clearTimeout(s),clearTimeout(w),Oe())}}function Oe(){typeof window<"u"&&(window.removeEventListener("online",X),window.removeEventListener("focus",X),document.removeEventListener("visibilitychange",X))}return{scope:Object.freeze({...o}),refresh:Q,subscribe:dt,assertFresh:ne,assertFeatures(n){ne();let t=d.gb.features;if(!t)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(n!==void 0&&d.artifacts[t].generation!==n)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return j()},get snapshot(){return d?structuredClone(d):null},get remainingMs(){return j()?Math.max(0,v-q()):0},async features(){return W(async()=>Ee(await re()))},pageExperiments:()=>W(async()=>{let n=await re(),t=n.gb.pageExperiments;if(!t)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=n.artifacts[t];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let a=at.parse(JSON.parse(await se(i)));if(a.environmentId!==o.environmentId||a.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return Z(n),a}),funnel:(n,t)=>W(()=>Re(n,t)),funnelControl:n=>W(async()=>{let t=await re();return Z(t,n),structuredClone(t.funnels[n])}),paywall:(n,t)=>W(async()=>{let i=await re(),a=i.paywalls?.[n];if(!a||!t&&a.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let g=t??a.currentVersionId,I=a.versions[g],m=I&&i.artifacts[I.artifact];if(!m||m.kind!=="paywall"||m.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let V=Me.parse(JSON.parse(await se(m)));return Z(i),{document:V,versionId:g,version:I.version,control:structuredClone(a),manifest:structuredClone(i)}}),async localFunnel(n,t){let i=await W(()=>Re(n,t));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:a,remoteFeatures:g,...I}=i.growth;return Ke({scope:{projectId:o.projectId,environment:o.environment},funnelId:n,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:I})},assertFunnel(n,t,i){ne();let a=d.funnels[n];if(!a||a.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(a.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(t!==void 0&&a.controlRevision!==t)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!a.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!p){p=!0,x++,v=0,M?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(w),Oe(),Y(),A.clear();for(let n of R)n.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));h.clear(),z=0}}}}function ct(r){let o=ce.test(r.apiKey);if(typeof window<"u"&&!o)throw new L("SERVER_ONLY","Funnel starts are issued by your backend");if(!o&&!fe.test(r.apiKey))throw new L("INVALID_TOKEN","A customer credential or server API key is required");return{async start(f){let E=D.safeParse({...f,operation:"start"});if(!E.success||E.data.operation!=="start"||(o?E.data.customer!==void 0:E.data.customer===void 0))throw new L("INVALID_REQUEST","Invalid current Funnel start");let b=E.data,C=Qe({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let c=We(r,await C.request("funnels",b));if(!c.runToken)throw new L("INVALID_RESPONSE","Funnel start credentials are missing");if(c.run.source.id!==b.funnelId||c.run.locale!==(b.locale??"en")||!et(c.run.parameters,b.parameters??{})||(b.customer?!c.customerId||b.customer.type==="id"&&c.customerId!==b.customer.value:c.customerId!==void 0))throw new L("INVALID_RESPONSE","Funnel start contract changed");return{...c,runToken:c.runToken}}finally{C.dispose()}}}}async function En(r){r={...r};let o=r.configuration;if(!o)throw new L("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let f={projectId:o.scope.projectId,environment:o.scope.environment};if(r.scope&&N(f)!==N(r.scope))throw new L("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await o.funnelControl(r.funnelId)).evaluationMode!=="local")throw new L("EVALUATION_MODE","This Funnel uses Remote evaluation");let b=fe.test(r.credential);if(b?!r.customerId:r.customerId!==void 0)throw new L("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=ct({...r,scope:f,apiKey:r.credential}),c=(y,d)=>{let v=tt({...r,scope:f,runToken:y,initialResponse:d,...b?{serverKey:r.credential}:{}});return b||v.identify(r.credential),v};return{async start(y){let d=await C.start({...y,funnelId:r.funnelId,...b?{customer:{type:"id",value:r.customerId}}:{}}),v=c(d.runToken,d),l=await v.get();return{...d,...l,controller:v}},async restore(y){let d=c(y),v=await d.get();if(v.run.source.id!==r.funnelId)throw d.reset(),new L("SCOPE_MISMATCH","Run belongs to another Funnel");return{...v,runToken:y,controller:d}}}}export{ot as a,yt as b,Nt as c,Tt as d,_t as e,Lt as f,Dt as g,Ht as h,ln as i,ct as j,En as k};
@@ -1 +1 @@
1
- import{a,b as o,c as i}from"./chunk-STPMMA64.js";import{a as p}from"./chunk-HJLGRW4A.js";function c(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new p("INVALID_REQUEST","Customer requests use the verified session identity")}function I(e){return{async previewUpdate(t){t=a(t),c(t);let r=await o(e,"previewUpdate");return i(e,r,t)},async update(t){t=a(t),c(t);let r=await o(e,"update");return i(e,r,t)},async readSubscriptionUpdate(t){t=a(t),c(t);let r=await o(e,"readSubscriptionUpdate");return i(e,r,t)},async restoreNativePurchase(t){t=a(t),c(t);let r=await o(e,"restoreNativePurchase");return i(e,r,t)},async previewAttach(t){t=a(t),c(t);let r=await o(e,"previewAttach");return i(e,r,t)},async attach(t){t=a(t),c(t);let r=await o(e,"attach");return i(e,r,t)},async readSubscriptionOperation(t){t=a(t),c(t);let r=await o(e,"readSubscriptionOperation");return i(e,r,t)}}}export{c as a,I as b};
1
+ import{a,b as o,c as i}from"./chunk-WK4WQZHK.js";import{a as p}from"./chunk-HJLGRW4A.js";function c(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new p("INVALID_REQUEST","Customer requests use the verified session identity")}function I(e){return{async previewUpdate(t){t=a(t),c(t);let r=await o(e,"previewUpdate");return i(e,r,t)},async update(t){t=a(t),c(t);let r=await o(e,"update");return i(e,r,t)},async readSubscriptionUpdate(t){t=a(t),c(t);let r=await o(e,"readSubscriptionUpdate");return i(e,r,t)},async restoreNativePurchase(t){t=a(t),c(t);let r=await o(e,"restoreNativePurchase");return i(e,r,t)},async previewAttach(t){t=a(t),c(t);let r=await o(e,"previewAttach");return i(e,r,t)},async attach(t){t=a(t),c(t);let r=await o(e,"attach");return i(e,r,t)},async readSubscriptionOperation(t){t=a(t),c(t);let r=await o(e,"readSubscriptionOperation");return i(e,r,t)}}}export{c as a,I as b};
@@ -1 +1 @@
1
- import{e as rn}from"./chunk-STPMMA64.js";import{h as ue,i as se,r as nn,s as pe}from"./chunk-QPHT6QHE.js";import{c as Be,d as Ke,e as J,l as en}from"./chunk-4ZVVG5LM.js";import{$ as U,D as Qe,R as Ye,W as Ze,X as We,Y as $,Z as Xe,_ as de,a as j,b as qe,c as Me,d as je,e as G,f as Ge,g as Ue,i as X,w as ee,x as ze,z as Je}from"./chunk-ITVSLSRM.js";import{b as on}from"./chunk-B3KFE57L.js";import{b as ne}from"./chunk-CLAZ7NVN.js";import{a as W}from"./chunk-J4VTKRH7.js";import{D as Te,L as ae,U as L,V as De,W as Le,ja as $e,ka as le,la as He,ma as ce,t as Oe,z as Ae}from"./chunk-WRUW2UIJ.js";import{a as f}from"./chunk-HJLGRW4A.js";import{h as D}from"./chunk-XIP32WI7.js";import{b as tn}from"./chunk-OHOROFWN.js";import{b as n}from"./chunk-ZY4XAKNQ.js";import{c as _e,d as ke,e as Ve,f as z}from"./chunk-6BTJNSQQ.js";import{a as Pe,b as Ne}from"./chunk-PWXN3W4Q.js";function an(e){return En({...e,namespace:"commands",identity:[e.runToken]})}function En(e){let t,u,r=()=>new f("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let d=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??tn).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",d));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,o=>o.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function p(d){try{let a=await i;return await u.request(a,{mode:"exclusive"},()=>d(a))}catch(a){throw a instanceof f?a:r()}}function c(d){let a=t.getItem(d);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let o=JSON.parse(a);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw r();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(c),write:(d,a)=>p(o=>{if(c(o).revision!==d)return null;if(!Number.isSafeInteger(d+1))throw r();let y=JSON.stringify({revision:d+1,entry:a});if(y.length>1048576)throw r();return t.setItem(o,y),d+1})}}var un=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var q=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Cn=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Pn=n.discriminatedUnion("type",[Qe,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:q.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:Ze,openIn:We}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:q})]),Nn={id:q,presentation:Te,outputs:n.array(q).max(250),inputs:ce,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Oe,customerData:Ae,dataCursors:n.record(q,$e.nullable())},On=n.strictObject({...Nn,content:n.strictObject({type:n.literal("document"),document:ae})}),me=n.strictObject({id:n.uuid(),source:un,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:q,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Cn,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:le,parameters:He,variables:n.record(n.string(),L),output:L.nullable(),screen:On.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([nn,pe]),quote:ue.nullable(),operation:se.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Pn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),An=n.strictObject({scope:D,run:me,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:ue.nullable(),operation:se.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative(),document:ae,answers:le,inputs:ce,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=An.extend({run:me.extend({paywall:me.shape.paywall.unwrap().extend({resolution:pe}).nullable()})});var ln="X-Indiana-Server-Key";var H=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function fe(e,t,u){let r={},i,p,c,d="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let o=e.cases.findIndex(g=>ke(t.attributes??{},g.condition,t.savedGroups??{}));d=o<0?"default":`case:${o}`,a=o<0?e.default:e.cases[o].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new H("Required GB Feature is unavailable");i=z(e.featureKey,t),c=i.value,Object.assign(r,G(e,{value:c})),a=e.next;break;case"split":{let o=u[e.experimentId];if(!o)throw new H("Required GB Experiment is unavailable");if(p=Ve(o,t),c=p.value,d=p.inExperiment&&!p.passthrough&&typeof c=="string"?c:"notParticipating",a=d==="notParticipating"?e.notParticipating:e.routes[d],!a)throw new H("Experiment Variation has no published route");break}case"offering":{let o=e.configuration.source==="fixed"?e.configuration.versionId:z(e.configuration.featureKey,t).value;c={type:"offering_version",id:n.uuid().parse(o)},Object.assign(r,G(e,{value:c})),a=e.next;break}case"coupon":case"coupons":c=e.type==="coupons"?e.couponIds.map(o=>({type:"reward",id:o})):{type:"reward",id:e.couponId},Object.assign(r,G(e,{value:c})),a=e.next;break}return{port:d,target:a,projections:r,...c===void 0?{}:{value:c},...i?{feature:i}:{},...p?{experiment:p}:{}}}function cn(e,t,u){n.uuid().parse(e),n.number().int().nonnegative().parse(t);let r=Pe(Ne(new TextEncoder().encode(JSON.stringify([e,t,u])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var Tn=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()}),_n=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(Tn).max(200).default([]),iam:ze.optional(),renderGuard:ee.optional()}),ge=_n.omit({variation:!0,description:!0,iam:!0}),kn=Be.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20)}),dn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(kn).max(100),savedGroups:Ke});var Q=n.string().regex(/^[a-f0-9]{64}$/),qt=n.strictObject({iam:Q,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),Vn=n.strictObject({release:Q,render:ee,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),Mt=n.strictObject({scope:D.extend({environmentId:n.uuid()}),release:Q,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"]),target:Vn})).max(4e3)}),jt=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:Q,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Gt=n.strictObject({scope:D,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Ut=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)}),ye=n.strictObject({operation:n.literal("page_experiments"),release:Q,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(W).optional()}),pn=n.strictObject({scope:D,runId:n.uuid(),assignments:n.array(Dn.extend({receiptId:n.uuid()})).max(100),payload:dn});var B=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fn=n.strictObject({entry:B,nodes:n.array(n.strictObject({id:B,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),B),writes:n.record(j,j),resources:n.strictObject({screenId:B.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)}),mn={scope:D,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:fn},te=n.discriminatedUnion("evaluationMode",[n.strictObject({...mn,evaluationMode:n.literal("local"),growth:J,conditions:n.record(B,n.array(n.strictObject({condition:Le,port:n.string()})))}),n.strictObject({...mn,evaluationMode:n.literal("remote")})]),Ln=te.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,Me),outputSchema:qe,terminals:n.record(B,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Ye.nullable()}))})});function qn(e){return fn.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(c=>c.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,c)=>{u[`case:${c}`]=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 i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.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 ve(e){let t=de.parse(e.document),u=e.evaluationMode==="local"?J.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:qn(t)};return te.parse(e.evaluationMode==="remote"?r:{...r,growth:en(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((p,c)=>({condition:p.condition,port:`case:${c}`}))]))})}function Wt(e){let t=ve(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=de.parse(e.document);return Ln.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var he=32,Mn=522240;function we(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 jn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),Ie=n.record(n.string(),L),Gn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:$.shape.schemaVersion,kind:$.shape.kind,selector:$.shape.selector,contract:$.shape.contract}),context:Ie,removed:n.array(n.string()).max(100),attributes:Ie,removedAttributes:n.array(n.string()).max(100),result:Xe,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()})}),or=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:jn,context:Ie,steps:n.array(Gn).min(1).max(he)}).refine(e=>X(e)<=Mn,"Segment exceeds its byte budget");var Un=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Y(e){return Array.isArray(e)?e.some(Y):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Y(u):!Un.test(t))}function gn(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(d=>d.id===t.screenId&&d.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(d=>Y(d.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(d=>d.id===t.screenId):null]);for(let[d,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${d}`)||p.includes(JSON.stringify(d))))return"customer_required";if(t.type==="split"){let d=u.experiments?.[t.experimentId];if((d?.hashAttribute??"id")!=="funnelParticipantId"||Y(d?.condition)||d?.parentConditions?.length)return"customer_experiment_required"}let c=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return c&&u.features?.[c]?.rules?.some(d=>(d.hashAttribute??"id")!=="funnelParticipantId"||Y(d.condition)||d.parentConditions?.length)?"customer_experiment_required":null}var be=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},re=(e,t)=>new be(e,t),Bn=e=>({experiments:e.experiments,features:e.features});function xe(e,t=re){let u=new Map(e.topology.nodes.map(c=>[c.id,c])),r=_e(e.growth.savedGroups),i=Bn(e.growth);function p(c,d){if(!Object.hasOwn(e.growth.features,c))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return z(c,d).value}return{nodes:u,savedGroups:r,features:i.features,feature:p,evaluate(c,d){let a=u.get(c);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let o,g;if(a.type==="condition"){let I=e.conditions[a.id];if(!I)throw t("INVALID_RESPONSE","Local condition rules are unavailable");o=fe({id:a.id,name:a.id,type:"condition",cases:I.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},d,i.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,d),o="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=fe({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},d,i.experiments);g=h.value,o=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,d),o=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[o]??(o==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:c,port:o,target:y,...g===void 0?{}:{value:g}}}}}function vr(e,t,u,r=re){return Re(e,r)(t,u)}function Re(e,t){let u=te.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,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let p=xe(u,t);return(c,d)=>(i(),Kn(p,c,d))}function Kn(e,t,u){let r=De.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:p,onExperimentViewed:c}=u,d={attributes:r,...i?{saveStickyBucketAssignmentDoc:a=>i(structuredClone(a))}:{},...p?{onFeatureUsage:(a,o)=>p(a,structuredClone(o))}:{},...c?{onExperimentViewed:(a,o)=>c(structuredClone(a),structuredClone(o))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,d)}function Ir(e,t,u,r=re){return yn(Re(e,r),t,u)}function yn(e,t,u){let r=[],i=[],p=[],c=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(d){let a=r.findIndex(y=>y.next.attributeName===d.attributeName&&y.next.attributeValue===d.attributeValue),o=d.attributeName+"||"+d.attributeValue,g={expected:u.sticky[o]??null,next:d};a<0?r.push(g):r[a]=g},onExperimentViewed(d,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&i.push(L.parse({key:d.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(d,a){p.push(L.parse({feature:d,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:c.port,...c.value===void 0?{}:{value:c.value},sticky:r,exposures:i,features:p}}function vn(e,t,u,r=re){let i=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),c=structuredClone(u.variables),d=structuredClone(i.sticky),a=[],o=u.nodeId,g=u.visit,y=!1,I,h=O=>gn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),b=O=>(I??=Re(e,r),yn(I,O,{attributes:Je({declarations:t.variables,attributes:i.attributes,parameters:u.parameters,answers:u.answers,results:c,savedGroups:{}}),sticky:d}));for(let O=0;O<he;O++){let s=p.get(o);if(!s||!we(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 m,x;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")m=b(s.id),s.type==="offering"&&(m.value={type:"offering_version",id:String(m.value)}),s.type==="condition"?x=m.port==="default"?s.default:s.cases[Number(m.port.slice(5))]?.target:s.type==="split"?x=m.port==="notParticipating"?s.notParticipating:s.routes[m.port]:(s.type==="feature"||s.type==="offering")&&(x=s.next);else if(m={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(x=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(m.value={type:"offering_version",id:s.configuration.versionId},x=s.next),s.type==="end"||s.type==="output"){let R=s.type==="end"?s.output:s.value;if(m=R?.type==="feature"?b(s.id):{...m,port:"value",value:R?.type==="literal"?R.value:R?.type==="variable"?Ue({source:"variable",key:R.key,...R.path?{path:R.path}:{}},{declarations:t.variables,answers:u.answers,results:c,parameters:u.parameters,attributes:i.attributes,savedGroups:{}}):null},R&&(m.value===void 0||!je(t.outputSchema,m.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let C=[...a,{nodeId:o,result:m}];if(X({steps:C})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:o,result:m}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let R=s.type==="coupons"?s.couponIds.map(V=>({type:"reward",id:V})):s.type==="coupon"?{type:"reward",id:s.couponId}:m.value;if(R===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=G(s,{value:R});Ge(t.variables,s,_),Object.assign(c,_)}for(let R of m.sticky)d[`${R.next.attributeName}||${R.next.attributeValue}`]=structuredClone(R.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");o=x,g++}let T=p.get(o);return{steps:a,...!y&&T&&(!we(T)||h(T))?{boundary:{nodeId:o,visit:g}}:{}}}function In(e,t){let u=sn.safeParse(t);if(!u.success)throw new f("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 f("SCOPE_MISMATCH","Funnel scope changed");return r}var Se=(e,t)=>new f(e,t);function Fr(e){return xe(e,Se)}var zn=3,Jn=2e3;function $n(e){return e instanceof TypeError||e instanceof f&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Hn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===zn||!$n(u))throw u;await new Promise(r=>setTimeout(r,t*Jn))}}async function Fe(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 f("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new f("SCOPE_MISMATCH","Evaluation environment changed");let i=null,p;if(u)try{let c=await e.funnel(t.source.id,t.source.versionId);p=c.manifest.generation,i=Qn(e,t,c)}catch{i=null}return p??=e.snapshot?.generation??(await Hn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:i}}function Qn(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:i,remoteFeatures:p,...c}=u.growth,d=ve({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:J.parse(c)}),a=Yn(d,u.document,{...t,...r}),o=a.steps.at(-1),g=a.boundary??(o?.result.port==="value"?{nodeId:o.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 Yn(e,t,u){return vn(e,t,u,Se)}var hn=U.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 f("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),wn=n.strictObject({schemaVersion:n.literal(1),scope:D,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:hn.optional(),closeCommand:hn.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 f("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),oe=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Z(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 bn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),i=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new f("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:wn.parse(a.entry)}}function c(a){let o=i.then(a);return i=o.catch(()=>{}),o}async function d(a){for(let o=0;o<4;o++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(oe(g.entry,y)){t=g.revision;return}let I=await e.write(g.revision,y);if(I!==null){if(!Number.isSafeInteger(I)||I<=g.revision)throw A();t=I;return}}throw A()}return{bind(a){let o=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==o)throw A();u=o},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let o=wn.parse(a),g=o.command;return!g||u!==null&&r(o)!==u?Promise.reject(A()):(u??=r(o),c(()=>d((y,I)=>{if(y&&!oe(r(y),r(o)))throw A();if(y&&o.processBindingIds){for(let[h,b]of Object.entries(o.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==b)throw A();y={...y,processBindingIds:{...y.processBindingIds,...o.processBindingIds}}}if(!y){if(I!==t&&g.operation!=="close")throw A();return o}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&&!oe(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!oe(y.command,g))throw A();return y})))},observePurchase(a,o,g,y){return c(()=>d((I,h)=>{if(!I&&h!==t||I&&r(I)!==r({...a,schemaVersion:1}))throw A();if(I?.purchase&&I.purchase.generation>o.generation)return Z(I,y);if(I?.purchase&&I.purchase.generation===o.generation&&I.purchase.operationId!==o.operationId)throw A();return g?!I?.purchase||I.purchase.operationId!==o.operationId?Z(I,y):Z(I.command?{...I,purchase:void 0}:null,y):Z({schemaVersion:1,...a,...I,purchase:o},y)}))},settle(a){return c(()=>d(o=>Z(o,a)))}}}function qr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function ie(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((i,p)=>ie(i,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(([i,p])=>Object.hasOwn(t,i)&&ie(p,Reflect.get(t,i)))}function xn(e,t){let u=t&&{...t},r=null,i=0,p=-1,c=0,d=new AbortController;function a(){c++,d.abort(new f("IDENTITY_CHANGED","Run identity changed")),d=new AbortController}let o=!1,g,y=0,I=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new f("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return p===c?r:null},get viewAgeMs(){return r&&p===c?performance.now()-i:void 0},get generation(){return c},get signal(){return d.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,b="Run identity changed during the request"){if(h!==c||o)throw new f("IDENTITY_CHANGED",b)},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||!ie(h.parameters,r.parameters)))throw new f("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new f("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,b,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&b.run.revision<=r.revision)&&!(r&&b.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!b.run.stopped&&["running","waiting"].includes(b.run.status)&&r&&p===c&&b.run.nodeId===r.nodeId&&b.run.visit===r.visit&&b.run.revision===r.revision&&(b.run.screen=r.screen,(r.paywall?.quote?.operationId===b.review?.activeOperationId||!r.paywall?.quote&&b.review?.activeOperationId===null)&&(b.run.paywall=r.paywall)),!(r?.paywall&&b.run.paywall&&r.paywall.receiptId===b.run.paywall.receiptId&&(b.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||b.run.revision>=r.revision)r=b.run,i=performance.now(),p=c;else if(!s)return;if(r&&p===c)for(let m of I)try{m(structuredClone(r))}catch{}}},identify(h){if(o)throw new f("IDENTITY_CHANGED","Controller was reset");if(!W.test(h))throw new f("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return I.add(h),()=>I.delete(h)},reset(){o||(o=!0,a(),g=void 0,r=null,I.clear())}}}var Ee=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function zr(e,t,u="A server API key is required"){if(typeof window<"u")throw new f("SERVER_ONLY",t);if(!Ee.test(e))throw new f("INVALID_TOKEN",u)}function Jr(e){let t=ne(e);return t.identify(e.apiKey),t}function Rn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&["apple","google"].includes(t.provider)?"native":t?.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new f("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function M(e){let{customerToken:t,...u}=e;return u}var Zn=e=>!(e instanceof f&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof f)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Sn({journal:e,state:t,call:u,processIdentity:r}){let i=null,p=null,c=!1,d={command:null,close:null},a=new Set,o,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new f("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(x=>x&&!Object.hasOwn(s.processBindingIds??{},x.requestId)))throw new f("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 f("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=s.purchase,c=s.closed===!0,!s.command)return;let m=s.command;i=m.operation==="close"?null:m,p=m.operation==="close"?m:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(c=!0);for(let x of[i,p])x&&a.add(x.requestId)}):Promise.resolve();y.catch(()=>{});async function I(s){e&&await y;let m=t.generation;if(e){if(!t.view||!t.scope)throw new f("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:M(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(m!==t.generation||i!==s&&p!==s)throw new f("IDENTITY_CHANGED","Run changed before command dispatch");let x=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(C){let R=s.operation==="submit"&&s.input.type==="paywall_quote",_=!x&&!Zn(C),V=!1;if(R&&_&&m===t.generation&&i===s&&C instanceof f&&C.status!==void 0){let l=await T(s.requestId).catch(()=>{});V=l?.settlement?.state==="unknown"&&l.settlement.operationId===null}throw m===t.generation&&(i===s||p===s)&&_&&(!R||!(C instanceof f)||C.status===void 0||V)&&(e&&await e.settle(s.requestId),m===t.generation&&O(s)),C}}function h(s){let m=U.parse(s);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new f("INVALID_REQUEST","Mutation required");if(c&&m.operation!=="close"){if(i?.requestId===m.requestId)return T(m.requestId);throw new f("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(m.operation==="close"){if(i?.requestId===m.requestId)throw new f("INVALID_REQUEST","Close requires its own request identity");if(c=!0,p&&JSON.stringify(M(p))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original Close");return p??=m,d.close?d.close:b(p,"close")}if(i){if(JSON.stringify(M(i))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original command before sending another");if(d.command)return d.command}else i=m;return b(i,"command")}function b(s,m){let x=I(s);d[m]=x;let C=()=>{d[m]===x&&(d[m]=null)};return x.then(C,C),x}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||i!==s&&p!==s?!1:(i===s&&(i=null),p===s&&(p=null),a.delete(s.requestId),!i&&!p&&(g=null),!0)}return{ready:y,get pending(){return i},get closing(){return p},get closeRequested(){return c},get inFlight(){return d.command},get closeFlight(){return d.close},get purchase(){return o},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new f("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,m,x,C){let R=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=R&&m.settlement?.state==="settled"&&m.run.pendingRequest?.requestId!==R&&(s.operation==="get"||!c||s.operation==="close"||!["running","waiting"].includes(m.run.status))?R:void 0,V=i?.requestId===_?i:p?.requestId===_?p:void 0;e?.bind({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId});let l=m.run.paywall,v=l??m.purchase,P=v?.operation,E=m.settlement&&(!l||l.purchaseRequestId===m.settlement.requestId)&&(!o||o.operationId===m.settlement.operationId)?m.settlement:void 0,S=P?.operationId??v?.quote?.operationId??E?.operationId,F=v?.receiptId??E?.receiptId,w=l?.selectionGeneration??o?.generation??0;if(e&&S&&F&&s.operation!=="review"&&(!t.view||m.run.revision>=t.view.revision)&&(C===void 0||C>=t.readSequence)&&(!o||w>=o.generation)){let N={receiptId:F,operationId:S,generation:w},k=on(P,v?.canReselect===!0);await e.observePurchase({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId},N,k,_),t.assertCurrent(x),(!o||N.generation>=o.generation)&&(C===void 0||C>=t.readSequence)&&(k?o?.operationId===N.operationId&&(o=void 0):o=N)}else e&&_&&await e.settle(_);return t.assertCurrent(x),_?O(V):!1},stop(){c=!0},submit:h,settle:T,reset(){c=!0,i=null,p=null,o=void 0,g=null,d.close=null,a.clear(),d.command=null}}}function Wn(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 f("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new f("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Ee.test(e.serverKey)))throw new f("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new f("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=ne({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),i=xn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(b),c=null,d=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?an(e):void 0),a=d&&bn(d),o=Sn({journal:a,state:i,call:T,processIdentity:e.process}),g=0,y=new Map;function I(){g++,y.clear(),t=void 0}async function h(l){let v=l.operation==="resume"?o.pending?.operation==="resume"?null:o.pending:l;if(u&&l.operation==="resume"&&!v&&l.requestId!==e.customerRun?.startRequestId)throw new f("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(v?.operation==="submit"&&v.input.type==="paywall_confirm"){let N=i.view?.paywall;Rn(u,N?.quote?.operationId===v.input.operationId?N.quote:void 0)}if(e.process)return e.process.request(l);let P=i.generation;i.assertCurrent(P);let E=performance.now()+(e.timeoutMs??35e3),S=i.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let N=i.signal,k,K=()=>{},Fn=new Promise((Xn,Ce)=>{K=()=>Ce(N.reason),N.addEventListener("abort",K,{once:!0}),k=setTimeout(()=>Ce(new f("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(i.assertCurrent(P),e.session.access())),Fn])}finally{clearTimeout(k),N.removeEventListener("abort",K)}}i.assertCurrent(P);let F={...l,...S?{customerToken:S}:{}},w=l.operation==="page_experiments"?ye.parse(F):U.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!S)throw new f("IDENTITY_CHANGED","Original recovery Customer changed");let N={...w};return"customerToken"in N&&delete N.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:N},S,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",w,e.runToken,{headers:e.serverKey&&!S?{[ln]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function b(){I(),p?.(),i.reset(),o.reset(),c=null,r.dispose()}async function T(l,v){let P=t;t=void 0;let E=i.generation,S=()=>i.assertCurrent(E);a&&await o.ready,S();let F=i.view,w=In(e,P!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?P:await h(l));if(l.operation==="review"&&!w.review)throw new f("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&w.run.id!==e.customerRun.runId)throw new f("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&w.purchase&&(w.purchase.receiptId!==l.purchase.receiptId||(w.purchase.operation?.operationId??w.purchase.quote?.operationId)!==l.purchase.operationId))throw new f("INVALID_RESPONSE","The requested original purchase changed");if(S(),w.runToken&&w.runToken!==e.runToken)throw new f("INVALID_RESPONSE","Run credential changed");let N=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(N&&w.settlement?.requestId!==N)throw new f("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(w),i.assertRun(w.run),i.bindScope(w.scope);let k=await o.observe(l,w,E,v);return(!i.view||w.run.revision>=i.view.revision)&&(v===void 0||v>=i.readSequence)&&(await e.onAcceptedResponse?.(w),S()),!w.run.stopped&&["running","waiting"].includes(w.run.status)&&l.operation==="get"&&l.settlementRequestId||(S(),["running","waiting"].includes(w.run.status)||o.stop(),i.publish(l,w,F,v,k)),w}function O(l){let v=i.generation;I();let P=l(),E=()=>{i.generation===v&&I()};return P.then(E,E),P}let s=l=>O(()=>o.submit(l)),m=null,x=new WeakMap;function C(l){let v=x.get(l);if(v)return v;let P=_(l);return x.set(l,P),P}let R=!1;async function _(l){let v=await l;if(v.run.instruction?.type!=="evaluate_segment")return v;if(m)return m;R=!0;let P=i.generation,E=(async()=>{for(let S=0;S<32&&v.run.instruction?.type==="evaluate_segment";S++){if(o.pending||o.closeRequested)return v;let F=v.run;if(v.run.instruction?.type==="evaluate_segment"){let{advance:N}=await Fe(e.configuration,F,{predict:!1});if(P!==i.generation)throw new f("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return v;if(i.view&&(i.view.revision!==F.revision||i.view.visit!==F.visit||i.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Fe(e.configuration,F).then(({prediction:K})=>{k&&P===i.generation&&!o.closeRequested&&i.view?.id===F.id&&!i.view.stopped&&i.view.nodeId===F.nodeId&&i.view.visit===F.visit&&i.view.revision===F.revision&&(c=K)}).catch(()=>{});try{v=await s({operation:"commit_segment",requestId:cn(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...N})}finally{k=!1,c=null}}}return v})();m=E;try{return await E}finally{m===E&&(m=null)}}let V={get configuration(){return R?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=i.currentView;return l?structuredClone(l):null},get viewAgeMs(){return i.viewAgeMs},get pendingCommand(){let l=o.closing??o.pending;return l?structuredClone(M(l)):null},get pendingCommands(){return[o.pending,o.closing].filter(l=>l!==null).map(l=>structuredClone(M(l)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=i.view;return c&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===c.runId&&l.nodeId===c.from.nodeId&&l.visit===c.from.visit&&l.revision===c.from.revision&&!o.closeRequested?structuredClone(c):null},settle:(...l)=>O(()=>o.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return rn(e,l)},async pageExperiments(l,v=[]){let P=i.generation;i.assertCurrent(P);let E=i.view?.id;if(!E)throw new f("INVALID_REQUEST","Read the Run before its page experiments");let S=pn.parse(await h(ye.parse({operation:"page_experiments",release:l,usedReceiptIds:v})));if(i.assertCurrent(P),S.runId!==E||S.scope.projectId!==i.scope?.projectId||S.scope.environment!==i.scope?.environment)throw new f("SCOPE_MISMATCH","Page experiment Run changed");return S},review(l){return T({operation:"review",...l?{receiptId:l}:{}},i.nextRead())},async get(l,v){let P=i.generation;l=l&&structuredClone(l),v=v&&{...v},a&&await o.ready,i.assertCurrent(P),v??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let E=JSON.stringify([i.generation,g,l??null,v??null]),S=y.get(E);if(S)return S.then(k=>structuredClone(k));let F=i.nextRead(),w=C(T({operation:"get",...l?{data:l}:{},...v?{purchase:v}:{}},F));y.set(E,w);let N=()=>{y.get(E)===w&&y.delete(E)};return w.then(N,N),w.then(k=>structuredClone(k))},resume(l=i.view?.pendingRequest?.requestId){return l?o.closeRequested?V.settle(l):o.pending?.requestId===l?C(s(o.pending)):C(s({operation:"resume",requestId:l})):Promise.reject(new f("INVALID_REQUEST","No interrupted command is available"))},submit(l){return C(s(l))},async retry(){if(o.closeFlight)return o.closeFlight;if(o.closing)return s(o.closing);if(o.closeRequested&&o.pending)return V.settle(o.pending.requestId);if(o.inFlight)return C(o.inFlight);if(!o.pending)throw new f("INVALID_REQUEST","No command is pending");let l=o.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let v=i.generation;if(await V.settle(l.requestId),i.assertCurrent(v),!o.pending)return V.get();if(o.pending!==l||o.closeRequested)throw new f("COMMAND_PENDING","The original quote is being recovered")}return C(s(l))},identify(l){let v=i.customerToken?void 0:t;I(),i.identify(l),t=v,c=null,r.reset()},get identitySignal(){return i.signal},subscribe:i.subscribe,reset:b};return V}function go(e,t){return Wn({...e,runToken:"",initialResponse:t})}export{cn as a,un as b,Pn as c,me as d,An as e,sn as f,Vn as g,Mt as h,jt as i,Gt as j,ye as k,pn as l,te as m,Ln as n,Wt as o,vr as p,Ir as q,In as r,Se as s,Fr as t,Yn as u,wn as v,Z as w,an as x,En as y,qr as z,ie as A,Ee as B,zr as C,Jr as D,Rn as E,Wn as F,go as G};
1
+ import{e as rn}from"./chunk-WK4WQZHK.js";import{h as ue,i as se,r as nn,s as pe}from"./chunk-QPHT6QHE.js";import{c as Be,d as Ke,e as J,l as en}from"./chunk-4ZVVG5LM.js";import{$ as U,D as Qe,R as Ye,W as Ze,X as We,Y as $,Z as Xe,_ as de,a as j,b as qe,c as Me,d as je,e as G,f as Ge,g as Ue,i as X,w as ee,x as ze,z as Je}from"./chunk-ITVSLSRM.js";import{b as on}from"./chunk-B3KFE57L.js";import{b as ne}from"./chunk-XZEGVBAI.js";import{a as W}from"./chunk-J4VTKRH7.js";import{D as Te,L as ae,U as L,V as De,W as Le,ja as $e,ka as le,la as He,ma as ce,t as Oe,z as Ae}from"./chunk-WRUW2UIJ.js";import{a as f}from"./chunk-HJLGRW4A.js";import{h as D}from"./chunk-XIP32WI7.js";import{b as tn}from"./chunk-FVGUBIVT.js";import{b as n}from"./chunk-ZY4XAKNQ.js";import{c as _e,d as ke,e as Ve,f as z}from"./chunk-6BTJNSQQ.js";import{a as Pe,b as Ne}from"./chunk-PWXN3W4Q.js";function an(e){return En({...e,namespace:"commands",identity:[e.runToken]})}function En(e){let t,u,r=()=>new f("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let d=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??tn).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",d));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,o=>o.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function p(d){try{let a=await i;return await u.request(a,{mode:"exclusive"},()=>d(a))}catch(a){throw a instanceof f?a:r()}}function c(d){let a=t.getItem(d);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let o=JSON.parse(a);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw r();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(c),write:(d,a)=>p(o=>{if(c(o).revision!==d)return null;if(!Number.isSafeInteger(d+1))throw r();let y=JSON.stringify({revision:d+1,entry:a});if(y.length>1048576)throw r();return t.setItem(o,y),d+1})}}var un=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var q=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Cn=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Pn=n.discriminatedUnion("type",[Qe,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:q.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:Ze,openIn:We}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:q})]),Nn={id:q,presentation:Te,outputs:n.array(q).max(250),inputs:ce,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Oe,customerData:Ae,dataCursors:n.record(q,$e.nullable())},On=n.strictObject({...Nn,content:n.strictObject({type:n.literal("document"),document:ae})}),me=n.strictObject({id:n.uuid(),source:un,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:q,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Cn,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:le,parameters:He,variables:n.record(n.string(),L),output:L.nullable(),screen:On.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([nn,pe]),quote:ue.nullable(),operation:se.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Pn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),An=n.strictObject({scope:D,run:me,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:ue.nullable(),operation:se.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative(),document:ae,answers:le,inputs:ce,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=An.extend({run:me.extend({paywall:me.shape.paywall.unwrap().extend({resolution:pe}).nullable()})});var ln="X-Indiana-Server-Key";var H=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function fe(e,t,u){let r={},i,p,c,d="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let o=e.cases.findIndex(g=>ke(t.attributes??{},g.condition,t.savedGroups??{}));d=o<0?"default":`case:${o}`,a=o<0?e.default:e.cases[o].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new H("Required GB Feature is unavailable");i=z(e.featureKey,t),c=i.value,Object.assign(r,G(e,{value:c})),a=e.next;break;case"split":{let o=u[e.experimentId];if(!o)throw new H("Required GB Experiment is unavailable");if(p=Ve(o,t),c=p.value,d=p.inExperiment&&!p.passthrough&&typeof c=="string"?c:"notParticipating",a=d==="notParticipating"?e.notParticipating:e.routes[d],!a)throw new H("Experiment Variation has no published route");break}case"offering":{let o=e.configuration.source==="fixed"?e.configuration.versionId:z(e.configuration.featureKey,t).value;c={type:"offering_version",id:n.uuid().parse(o)},Object.assign(r,G(e,{value:c})),a=e.next;break}case"coupon":case"coupons":c=e.type==="coupons"?e.couponIds.map(o=>({type:"reward",id:o})):{type:"reward",id:e.couponId},Object.assign(r,G(e,{value:c})),a=e.next;break}return{port:d,target:a,projections:r,...c===void 0?{}:{value:c},...i?{feature:i}:{},...p?{experiment:p}:{}}}function cn(e,t,u){n.uuid().parse(e),n.number().int().nonnegative().parse(t);let r=Pe(Ne(new TextEncoder().encode(JSON.stringify([e,t,u])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var Tn=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()}),_n=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(Tn).max(200).default([]),iam:ze.optional(),renderGuard:ee.optional()}),ge=_n.omit({variation:!0,description:!0,iam:!0}),kn=Be.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20)}),dn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(kn).max(100),savedGroups:Ke});var Q=n.string().regex(/^[a-f0-9]{64}$/),qt=n.strictObject({iam:Q,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),Vn=n.strictObject({release:Q,render:ee,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),Mt=n.strictObject({scope:D.extend({environmentId:n.uuid()}),release:Q,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"]),target:Vn})).max(4e3)}),jt=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:Q,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Gt=n.strictObject({scope:D,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Ut=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)}),ye=n.strictObject({operation:n.literal("page_experiments"),release:Q,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(W).optional()}),pn=n.strictObject({scope:D,runId:n.uuid(),assignments:n.array(Dn.extend({receiptId:n.uuid()})).max(100),payload:dn});var B=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fn=n.strictObject({entry:B,nodes:n.array(n.strictObject({id:B,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),B),writes:n.record(j,j),resources:n.strictObject({screenId:B.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)}),mn={scope:D,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:fn},te=n.discriminatedUnion("evaluationMode",[n.strictObject({...mn,evaluationMode:n.literal("local"),growth:J,conditions:n.record(B,n.array(n.strictObject({condition:Le,port:n.string()})))}),n.strictObject({...mn,evaluationMode:n.literal("remote")})]),Ln=te.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,Me),outputSchema:qe,terminals:n.record(B,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Ye.nullable()}))})});function qn(e){return fn.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(c=>c.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,c)=>{u[`case:${c}`]=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 i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.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 ve(e){let t=de.parse(e.document),u=e.evaluationMode==="local"?J.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:qn(t)};return te.parse(e.evaluationMode==="remote"?r:{...r,growth:en(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((p,c)=>({condition:p.condition,port:`case:${c}`}))]))})}function Wt(e){let t=ve(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=de.parse(e.document);return Ln.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var he=32,Mn=522240;function we(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 jn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),Ie=n.record(n.string(),L),Gn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:$.shape.schemaVersion,kind:$.shape.kind,selector:$.shape.selector,contract:$.shape.contract}),context:Ie,removed:n.array(n.string()).max(100),attributes:Ie,removedAttributes:n.array(n.string()).max(100),result:Xe,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()})}),or=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:jn,context:Ie,steps:n.array(Gn).min(1).max(he)}).refine(e=>X(e)<=Mn,"Segment exceeds its byte budget");var Un=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Y(e){return Array.isArray(e)?e.some(Y):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Y(u):!Un.test(t))}function gn(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(d=>d.id===t.screenId&&d.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(d=>Y(d.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(d=>d.id===t.screenId):null]);for(let[d,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${d}`)||p.includes(JSON.stringify(d))))return"customer_required";if(t.type==="split"){let d=u.experiments?.[t.experimentId];if((d?.hashAttribute??"id")!=="funnelParticipantId"||Y(d?.condition)||d?.parentConditions?.length)return"customer_experiment_required"}let c=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return c&&u.features?.[c]?.rules?.some(d=>(d.hashAttribute??"id")!=="funnelParticipantId"||Y(d.condition)||d.parentConditions?.length)?"customer_experiment_required":null}var be=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},re=(e,t)=>new be(e,t),Bn=e=>({experiments:e.experiments,features:e.features});function xe(e,t=re){let u=new Map(e.topology.nodes.map(c=>[c.id,c])),r=_e(e.growth.savedGroups),i=Bn(e.growth);function p(c,d){if(!Object.hasOwn(e.growth.features,c))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return z(c,d).value}return{nodes:u,savedGroups:r,features:i.features,feature:p,evaluate(c,d){let a=u.get(c);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let o,g;if(a.type==="condition"){let I=e.conditions[a.id];if(!I)throw t("INVALID_RESPONSE","Local condition rules are unavailable");o=fe({id:a.id,name:a.id,type:"condition",cases:I.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},d,i.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,d),o="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=fe({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},d,i.experiments);g=h.value,o=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,d),o=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[o]??(o==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:c,port:o,target:y,...g===void 0?{}:{value:g}}}}}function vr(e,t,u,r=re){return Re(e,r)(t,u)}function Re(e,t){let u=te.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,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let p=xe(u,t);return(c,d)=>(i(),Kn(p,c,d))}function Kn(e,t,u){let r=De.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:p,onExperimentViewed:c}=u,d={attributes:r,...i?{saveStickyBucketAssignmentDoc:a=>i(structuredClone(a))}:{},...p?{onFeatureUsage:(a,o)=>p(a,structuredClone(o))}:{},...c?{onExperimentViewed:(a,o)=>c(structuredClone(a),structuredClone(o))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,d)}function Ir(e,t,u,r=re){return yn(Re(e,r),t,u)}function yn(e,t,u){let r=[],i=[],p=[],c=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(d){let a=r.findIndex(y=>y.next.attributeName===d.attributeName&&y.next.attributeValue===d.attributeValue),o=d.attributeName+"||"+d.attributeValue,g={expected:u.sticky[o]??null,next:d};a<0?r.push(g):r[a]=g},onExperimentViewed(d,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&i.push(L.parse({key:d.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(d,a){p.push(L.parse({feature:d,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:c.port,...c.value===void 0?{}:{value:c.value},sticky:r,exposures:i,features:p}}function vn(e,t,u,r=re){let i=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),c=structuredClone(u.variables),d=structuredClone(i.sticky),a=[],o=u.nodeId,g=u.visit,y=!1,I,h=O=>gn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),b=O=>(I??=Re(e,r),yn(I,O,{attributes:Je({declarations:t.variables,attributes:i.attributes,parameters:u.parameters,answers:u.answers,results:c,savedGroups:{}}),sticky:d}));for(let O=0;O<he;O++){let s=p.get(o);if(!s||!we(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 m,x;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")m=b(s.id),s.type==="offering"&&(m.value={type:"offering_version",id:String(m.value)}),s.type==="condition"?x=m.port==="default"?s.default:s.cases[Number(m.port.slice(5))]?.target:s.type==="split"?x=m.port==="notParticipating"?s.notParticipating:s.routes[m.port]:(s.type==="feature"||s.type==="offering")&&(x=s.next);else if(m={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(x=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(m.value={type:"offering_version",id:s.configuration.versionId},x=s.next),s.type==="end"||s.type==="output"){let R=s.type==="end"?s.output:s.value;if(m=R?.type==="feature"?b(s.id):{...m,port:"value",value:R?.type==="literal"?R.value:R?.type==="variable"?Ue({source:"variable",key:R.key,...R.path?{path:R.path}:{}},{declarations:t.variables,answers:u.answers,results:c,parameters:u.parameters,attributes:i.attributes,savedGroups:{}}):null},R&&(m.value===void 0||!je(t.outputSchema,m.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let C=[...a,{nodeId:o,result:m}];if(X({steps:C})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:o,result:m}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let R=s.type==="coupons"?s.couponIds.map(V=>({type:"reward",id:V})):s.type==="coupon"?{type:"reward",id:s.couponId}:m.value;if(R===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=G(s,{value:R});Ge(t.variables,s,_),Object.assign(c,_)}for(let R of m.sticky)d[`${R.next.attributeName}||${R.next.attributeValue}`]=structuredClone(R.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");o=x,g++}let T=p.get(o);return{steps:a,...!y&&T&&(!we(T)||h(T))?{boundary:{nodeId:o,visit:g}}:{}}}function In(e,t){let u=sn.safeParse(t);if(!u.success)throw new f("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 f("SCOPE_MISMATCH","Funnel scope changed");return r}var Se=(e,t)=>new f(e,t);function Fr(e){return xe(e,Se)}var zn=3,Jn=2e3;function $n(e){return e instanceof TypeError||e instanceof f&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Hn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===zn||!$n(u))throw u;await new Promise(r=>setTimeout(r,t*Jn))}}async function Fe(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 f("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new f("SCOPE_MISMATCH","Evaluation environment changed");let i=null,p;if(u)try{let c=await e.funnel(t.source.id,t.source.versionId);p=c.manifest.generation,i=Qn(e,t,c)}catch{i=null}return p??=e.snapshot?.generation??(await Hn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:i}}function Qn(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:i,remoteFeatures:p,...c}=u.growth,d=ve({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:J.parse(c)}),a=Yn(d,u.document,{...t,...r}),o=a.steps.at(-1),g=a.boundary??(o?.result.port==="value"?{nodeId:o.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 Yn(e,t,u){return vn(e,t,u,Se)}var hn=U.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 f("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),wn=n.strictObject({schemaVersion:n.literal(1),scope:D,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:hn.optional(),closeCommand:hn.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 f("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),oe=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Z(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 bn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),i=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new f("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:wn.parse(a.entry)}}function c(a){let o=i.then(a);return i=o.catch(()=>{}),o}async function d(a){for(let o=0;o<4;o++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(oe(g.entry,y)){t=g.revision;return}let I=await e.write(g.revision,y);if(I!==null){if(!Number.isSafeInteger(I)||I<=g.revision)throw A();t=I;return}}throw A()}return{bind(a){let o=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==o)throw A();u=o},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let o=wn.parse(a),g=o.command;return!g||u!==null&&r(o)!==u?Promise.reject(A()):(u??=r(o),c(()=>d((y,I)=>{if(y&&!oe(r(y),r(o)))throw A();if(y&&o.processBindingIds){for(let[h,b]of Object.entries(o.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==b)throw A();y={...y,processBindingIds:{...y.processBindingIds,...o.processBindingIds}}}if(!y){if(I!==t&&g.operation!=="close")throw A();return o}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&&!oe(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!oe(y.command,g))throw A();return y})))},observePurchase(a,o,g,y){return c(()=>d((I,h)=>{if(!I&&h!==t||I&&r(I)!==r({...a,schemaVersion:1}))throw A();if(I?.purchase&&I.purchase.generation>o.generation)return Z(I,y);if(I?.purchase&&I.purchase.generation===o.generation&&I.purchase.operationId!==o.operationId)throw A();return g?!I?.purchase||I.purchase.operationId!==o.operationId?Z(I,y):Z(I.command?{...I,purchase:void 0}:null,y):Z({schemaVersion:1,...a,...I,purchase:o},y)}))},settle(a){return c(()=>d(o=>Z(o,a)))}}}function qr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function ie(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((i,p)=>ie(i,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(([i,p])=>Object.hasOwn(t,i)&&ie(p,Reflect.get(t,i)))}function xn(e,t){let u=t&&{...t},r=null,i=0,p=-1,c=0,d=new AbortController;function a(){c++,d.abort(new f("IDENTITY_CHANGED","Run identity changed")),d=new AbortController}let o=!1,g,y=0,I=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new f("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return p===c?r:null},get viewAgeMs(){return r&&p===c?performance.now()-i:void 0},get generation(){return c},get signal(){return d.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,b="Run identity changed during the request"){if(h!==c||o)throw new f("IDENTITY_CHANGED",b)},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||!ie(h.parameters,r.parameters)))throw new f("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new f("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,b,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&b.run.revision<=r.revision)&&!(r&&b.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!b.run.stopped&&["running","waiting"].includes(b.run.status)&&r&&p===c&&b.run.nodeId===r.nodeId&&b.run.visit===r.visit&&b.run.revision===r.revision&&(b.run.screen=r.screen,(r.paywall?.quote?.operationId===b.review?.activeOperationId||!r.paywall?.quote&&b.review?.activeOperationId===null)&&(b.run.paywall=r.paywall)),!(r?.paywall&&b.run.paywall&&r.paywall.receiptId===b.run.paywall.receiptId&&(b.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||b.run.revision>=r.revision)r=b.run,i=performance.now(),p=c;else if(!s)return;if(r&&p===c)for(let m of I)try{m(structuredClone(r))}catch{}}},identify(h){if(o)throw new f("IDENTITY_CHANGED","Controller was reset");if(!W.test(h))throw new f("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return I.add(h),()=>I.delete(h)},reset(){o||(o=!0,a(),g=void 0,r=null,I.clear())}}}var Ee=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function zr(e,t,u="A server API key is required"){if(typeof window<"u")throw new f("SERVER_ONLY",t);if(!Ee.test(e))throw new f("INVALID_TOKEN",u)}function Jr(e){let t=ne(e);return t.identify(e.apiKey),t}function Rn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&["apple","google"].includes(t.provider)?"native":t?.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new f("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function M(e){let{customerToken:t,...u}=e;return u}var Zn=e=>!(e instanceof f&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof f)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Sn({journal:e,state:t,call:u,processIdentity:r}){let i=null,p=null,c=!1,d={command:null,close:null},a=new Set,o,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new f("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(x=>x&&!Object.hasOwn(s.processBindingIds??{},x.requestId)))throw new f("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 f("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=s.purchase,c=s.closed===!0,!s.command)return;let m=s.command;i=m.operation==="close"?null:m,p=m.operation==="close"?m:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(c=!0);for(let x of[i,p])x&&a.add(x.requestId)}):Promise.resolve();y.catch(()=>{});async function I(s){e&&await y;let m=t.generation;if(e){if(!t.view||!t.scope)throw new f("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:M(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(m!==t.generation||i!==s&&p!==s)throw new f("IDENTITY_CHANGED","Run changed before command dispatch");let x=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(C){let R=s.operation==="submit"&&s.input.type==="paywall_quote",_=!x&&!Zn(C),V=!1;if(R&&_&&m===t.generation&&i===s&&C instanceof f&&C.status!==void 0){let l=await T(s.requestId).catch(()=>{});V=l?.settlement?.state==="unknown"&&l.settlement.operationId===null}throw m===t.generation&&(i===s||p===s)&&_&&(!R||!(C instanceof f)||C.status===void 0||V)&&(e&&await e.settle(s.requestId),m===t.generation&&O(s)),C}}function h(s){let m=U.parse(s);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new f("INVALID_REQUEST","Mutation required");if(c&&m.operation!=="close"){if(i?.requestId===m.requestId)return T(m.requestId);throw new f("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(m.operation==="close"){if(i?.requestId===m.requestId)throw new f("INVALID_REQUEST","Close requires its own request identity");if(c=!0,p&&JSON.stringify(M(p))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original Close");return p??=m,d.close?d.close:b(p,"close")}if(i){if(JSON.stringify(M(i))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original command before sending another");if(d.command)return d.command}else i=m;return b(i,"command")}function b(s,m){let x=I(s);d[m]=x;let C=()=>{d[m]===x&&(d[m]=null)};return x.then(C,C),x}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||i!==s&&p!==s?!1:(i===s&&(i=null),p===s&&(p=null),a.delete(s.requestId),!i&&!p&&(g=null),!0)}return{ready:y,get pending(){return i},get closing(){return p},get closeRequested(){return c},get inFlight(){return d.command},get closeFlight(){return d.close},get purchase(){return o},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new f("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,m,x,C){let R=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=R&&m.settlement?.state==="settled"&&m.run.pendingRequest?.requestId!==R&&(s.operation==="get"||!c||s.operation==="close"||!["running","waiting"].includes(m.run.status))?R:void 0,V=i?.requestId===_?i:p?.requestId===_?p:void 0;e?.bind({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId});let l=m.run.paywall,v=l??m.purchase,P=v?.operation,E=m.settlement&&(!l||l.purchaseRequestId===m.settlement.requestId)&&(!o||o.operationId===m.settlement.operationId)?m.settlement:void 0,S=P?.operationId??v?.quote?.operationId??E?.operationId,F=v?.receiptId??E?.receiptId,w=l?.selectionGeneration??o?.generation??0;if(e&&S&&F&&s.operation!=="review"&&(!t.view||m.run.revision>=t.view.revision)&&(C===void 0||C>=t.readSequence)&&(!o||w>=o.generation)){let N={receiptId:F,operationId:S,generation:w},k=on(P,v?.canReselect===!0);await e.observePurchase({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId},N,k,_),t.assertCurrent(x),(!o||N.generation>=o.generation)&&(C===void 0||C>=t.readSequence)&&(k?o?.operationId===N.operationId&&(o=void 0):o=N)}else e&&_&&await e.settle(_);return t.assertCurrent(x),_?O(V):!1},stop(){c=!0},submit:h,settle:T,reset(){c=!0,i=null,p=null,o=void 0,g=null,d.close=null,a.clear(),d.command=null}}}function Wn(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 f("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new f("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Ee.test(e.serverKey)))throw new f("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new f("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=ne({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),i=xn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(b),c=null,d=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?an(e):void 0),a=d&&bn(d),o=Sn({journal:a,state:i,call:T,processIdentity:e.process}),g=0,y=new Map;function I(){g++,y.clear(),t=void 0}async function h(l){let v=l.operation==="resume"?o.pending?.operation==="resume"?null:o.pending:l;if(u&&l.operation==="resume"&&!v&&l.requestId!==e.customerRun?.startRequestId)throw new f("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(v?.operation==="submit"&&v.input.type==="paywall_confirm"){let N=i.view?.paywall;Rn(u,N?.quote?.operationId===v.input.operationId?N.quote:void 0)}if(e.process)return e.process.request(l);let P=i.generation;i.assertCurrent(P);let E=performance.now()+(e.timeoutMs??35e3),S=i.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let N=i.signal,k,K=()=>{},Fn=new Promise((Xn,Ce)=>{K=()=>Ce(N.reason),N.addEventListener("abort",K,{once:!0}),k=setTimeout(()=>Ce(new f("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(i.assertCurrent(P),e.session.access())),Fn])}finally{clearTimeout(k),N.removeEventListener("abort",K)}}i.assertCurrent(P);let F={...l,...S?{customerToken:S}:{}},w=l.operation==="page_experiments"?ye.parse(F):U.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!S)throw new f("IDENTITY_CHANGED","Original recovery Customer changed");let N={...w};return"customerToken"in N&&delete N.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:N},S,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",w,e.runToken,{headers:e.serverKey&&!S?{[ln]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function b(){I(),p?.(),i.reset(),o.reset(),c=null,r.dispose()}async function T(l,v){let P=t;t=void 0;let E=i.generation,S=()=>i.assertCurrent(E);a&&await o.ready,S();let F=i.view,w=In(e,P!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?P:await h(l));if(l.operation==="review"&&!w.review)throw new f("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&w.run.id!==e.customerRun.runId)throw new f("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&w.purchase&&(w.purchase.receiptId!==l.purchase.receiptId||(w.purchase.operation?.operationId??w.purchase.quote?.operationId)!==l.purchase.operationId))throw new f("INVALID_RESPONSE","The requested original purchase changed");if(S(),w.runToken&&w.runToken!==e.runToken)throw new f("INVALID_RESPONSE","Run credential changed");let N=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(N&&w.settlement?.requestId!==N)throw new f("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(w),i.assertRun(w.run),i.bindScope(w.scope);let k=await o.observe(l,w,E,v);return(!i.view||w.run.revision>=i.view.revision)&&(v===void 0||v>=i.readSequence)&&(await e.onAcceptedResponse?.(w),S()),!w.run.stopped&&["running","waiting"].includes(w.run.status)&&l.operation==="get"&&l.settlementRequestId||(S(),["running","waiting"].includes(w.run.status)||o.stop(),i.publish(l,w,F,v,k)),w}function O(l){let v=i.generation;I();let P=l(),E=()=>{i.generation===v&&I()};return P.then(E,E),P}let s=l=>O(()=>o.submit(l)),m=null,x=new WeakMap;function C(l){let v=x.get(l);if(v)return v;let P=_(l);return x.set(l,P),P}let R=!1;async function _(l){let v=await l;if(v.run.instruction?.type!=="evaluate_segment")return v;if(m)return m;R=!0;let P=i.generation,E=(async()=>{for(let S=0;S<32&&v.run.instruction?.type==="evaluate_segment";S++){if(o.pending||o.closeRequested)return v;let F=v.run;if(v.run.instruction?.type==="evaluate_segment"){let{advance:N}=await Fe(e.configuration,F,{predict:!1});if(P!==i.generation)throw new f("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return v;if(i.view&&(i.view.revision!==F.revision||i.view.visit!==F.visit||i.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Fe(e.configuration,F).then(({prediction:K})=>{k&&P===i.generation&&!o.closeRequested&&i.view?.id===F.id&&!i.view.stopped&&i.view.nodeId===F.nodeId&&i.view.visit===F.visit&&i.view.revision===F.revision&&(c=K)}).catch(()=>{});try{v=await s({operation:"commit_segment",requestId:cn(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...N})}finally{k=!1,c=null}}}return v})();m=E;try{return await E}finally{m===E&&(m=null)}}let V={get configuration(){return R?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=i.currentView;return l?structuredClone(l):null},get viewAgeMs(){return i.viewAgeMs},get pendingCommand(){let l=o.closing??o.pending;return l?structuredClone(M(l)):null},get pendingCommands(){return[o.pending,o.closing].filter(l=>l!==null).map(l=>structuredClone(M(l)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=i.view;return c&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===c.runId&&l.nodeId===c.from.nodeId&&l.visit===c.from.visit&&l.revision===c.from.revision&&!o.closeRequested?structuredClone(c):null},settle:(...l)=>O(()=>o.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return rn(e,l)},async pageExperiments(l,v=[]){let P=i.generation;i.assertCurrent(P);let E=i.view?.id;if(!E)throw new f("INVALID_REQUEST","Read the Run before its page experiments");let S=pn.parse(await h(ye.parse({operation:"page_experiments",release:l,usedReceiptIds:v})));if(i.assertCurrent(P),S.runId!==E||S.scope.projectId!==i.scope?.projectId||S.scope.environment!==i.scope?.environment)throw new f("SCOPE_MISMATCH","Page experiment Run changed");return S},review(l){return T({operation:"review",...l?{receiptId:l}:{}},i.nextRead())},async get(l,v){let P=i.generation;l=l&&structuredClone(l),v=v&&{...v},a&&await o.ready,i.assertCurrent(P),v??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let E=JSON.stringify([i.generation,g,l??null,v??null]),S=y.get(E);if(S)return S.then(k=>structuredClone(k));let F=i.nextRead(),w=C(T({operation:"get",...l?{data:l}:{},...v?{purchase:v}:{}},F));y.set(E,w);let N=()=>{y.get(E)===w&&y.delete(E)};return w.then(N,N),w.then(k=>structuredClone(k))},resume(l=i.view?.pendingRequest?.requestId){return l?o.closeRequested?V.settle(l):o.pending?.requestId===l?C(s(o.pending)):C(s({operation:"resume",requestId:l})):Promise.reject(new f("INVALID_REQUEST","No interrupted command is available"))},submit(l){return C(s(l))},async retry(){if(o.closeFlight)return o.closeFlight;if(o.closing)return s(o.closing);if(o.closeRequested&&o.pending)return V.settle(o.pending.requestId);if(o.inFlight)return C(o.inFlight);if(!o.pending)throw new f("INVALID_REQUEST","No command is pending");let l=o.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let v=i.generation;if(await V.settle(l.requestId),i.assertCurrent(v),!o.pending)return V.get();if(o.pending!==l||o.closeRequested)throw new f("COMMAND_PENDING","The original quote is being recovered")}return C(s(l))},identify(l){let v=i.customerToken?void 0:t;I(),i.identify(l),t=v,c=null,r.reset()},get identitySignal(){return i.signal},subscribe:i.subscribe,reset:b};return V}function go(e,t){return Wn({...e,runToken:"",initialResponse:t})}export{cn as a,un as b,Pn as c,me as d,An as e,sn as f,Vn as g,Mt as h,jt as i,Gt as j,ye as k,pn as l,te as m,Ln as n,Wt as o,vr as p,Ir as q,In as r,Se as s,Fr as t,Yn as u,wn as v,Z as w,an as x,En as y,qr as z,ie as A,Ee as B,zr as C,Jr as D,Rn as E,Wn as F,go as G};
@@ -1 +1 @@
1
- import{a as T,b as se}from"./chunk-JWPTJLAN.js";import{b as re,h as ae,j as ce}from"./chunk-DIMBCG2C.js";import{a as oe,b as j}from"./chunk-23WNEOK4.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-JNSU2AP2.js";import{F as M,b as J}from"./chunk-XHQBABH6.js";import{a as b,b as f,c as m}from"./chunk-STPMMA64.js";import{b as W,j as X}from"./chunk-4ZVVG5LM.js";import{E as $}from"./chunk-ITVSLSRM.js";import{b as ie}from"./chunk-CLAZ7NVN.js";import{a as B}from"./chunk-J4VTKRH7.js";import{a as s}from"./chunk-HJLGRW4A.js";import{h as Q}from"./chunk-XIP32WI7.js";import{b as K}from"./chunk-ZY4XAKNQ.js";import{a as z}from"./chunk-DSPLGTQI.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},Se=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ue(t,e,n){let r=null,o=0,a=0,d=0,y=Promise.resolve(),g=!1;if(t&&(!n||Q.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(g)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==o)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function F(i){let c=l();if(!c.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=c.sha256?await c.sha256(Uint8Array.from(i,A=>A.charCodeAt(0))):await Se(i);if(!/^[a-f0-9]{64}$/.test(u))throw new s("INVALID_STATE","Push credential digest is invalid");return u}function p(i){let c=G.parse(i);if(c.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let u=l(),A={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...c},w=await u.sign(ne(i,u.scope,A));return{...A,signature:w}}let I=(i,c,u)=>e.requestWithCredential?e.requestWithCredential(i,c,u):e.request(i,c);async function q(){let i=l(),c=o,u=r?await(e.session?.access()??r):null,A=_(i,v=>v),w;if(A.detachSeq!==null){let v=A.detachSeq,V=Z.parse(await S("detach",{sequence:v,platform:i.platform}));try{let k=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!k||typeof k!="object"||!("installation"in k))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let x=p(k.installation);if(x.bound||x.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(k){if(k instanceof s&&k.status===404)w=k;else if(!(k instanceof s)||k.status!==412)throw k}w||_(i,k=>({...k,detachSeq:k.detachSeq===v?null:k.detachSeq}))}if(O(c),!u){if(w)throw w;return null}let C=(await import("./operation-contracts-SP2RZUT3.js")).apiOperations.bindPushInstallation,D=C.request.parse(await S("bind",{sequence:d,platform:i.platform,credentialDigest:await F(u)}));O(c);let R=C.response.parse(await I(C.path,D,u));O(c);let N=p(R.installation);if(!N.bound||N.identitySeq!==d)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return w&&A.detachSeq!==null&&d>A.detachSeq&&_(i,v=>({...v,detachSeq:v.detachSeq===A.detachSeq?null:v.detachSeq})),N}async function h(){l();let i=o,c=r?await(e.session?.access()??r):null;if(!c)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let u=(await import("./operation-contracts-SP2RZUT3.js")).apiOperations.readPushInstallation,A=u.request.parse(await S("read",{credentialDigest:await F(c)}));O(i);let w=u.response.parse(await I(u.path,A,c));return O(i),p(w.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),c}async function E(i,c,u){let A=l(),w=c.identity,C=c.observation,D=r?await(e.session?.access()??r):null;if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");if(!D)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(w),await q(),O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(A,x=>u?x:{...x,addressSeq:U(x.addressSeq)}),v=await S(u?"recovery_confirm":"recovery_request",{...i,sequence:R.addressSeq,credentialDigest:await F(D),...u?{challenge:u}:{}}),V=u?te.parse(v):ee.parse(v);if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let k=await I(`push/installations/recovery/${u?"confirm":"request"}`,V,D);if(O(w),C!==a||_(A,x=>x).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(u){let{apiOperations:x}=await import("./operation-contracts-SP2RZUT3.js");if(O(w),C!==a||_(A,Oe=>Oe).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");let Ae=x.updatePushAddress.response.parse(k),L=p(Ae.installation);if(!L.bound||L.identitySeq!==d||L.addressSeq!==R.addressSeq||L.connectionId!==i.connectionId||L.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return L}if(!k||typeof k!="object"||!("recovery"in k))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return H.parse(k.recovery)})}return{recoveryObserver(){l();let i={identity:o,observation:++a};return{async request(c){return H.parse(await E(c,i))},async confirm(c,u){return G.parse(await E(u,i,c))}}},identify(i){if(!t)return;d=_(t,u=>({...u,identitySeq:U(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,o++,a++}},start(){t&&!g&&P()},destroy(){g=!0,r=null,o++,a++},async sync(){return await P()},read:h,async recover(){let i=l(),c=o,u=d;return a++,await P(async()=>{O(c);let A=await h();return O(c),d=_(i,C=>{if(C.identitySeq!==u)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...C,identitySeq:U(Math.max(C.identitySeq,A.identitySeq)),addressSeq:Math.max(C.addressSeq,A.addressSeq)}}).identitySeq,await q()})},tokenObserver(){l();let i=++a,c=o;return async u=>{if(i!==a||c!==o)return null;let A=l(),w=r?await(e.session?.access()??r):null;if(!w)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let C=_(A,v=>({...v,addressSeq:U(v.addressSeq)})),D=(await import("./operation-contracts-SP2RZUT3.js")).apiOperations.updatePushAddress,R=D.request.parse(await S("address",{...u,sequence:C.addressSeq,credentialDigest:await F(w)}));if(O(c),i!==a)return null;let N=await I(D.path,R,w);return O(c),i!==a||_(A,v=>v).addressSeq!==C.addressSeq?null:p(D.response.parse(N).installation)}}}}function de(t,e){let n={async preference(r){let o=await f(t,"readMessagingPreference");return(await m(t,o,{channel:r})).preference},async setPreference(r){r=b(r);let o=await f(t,"setMessagingPreference");return(await m(t,o,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return r=b(r),n.setPreference({...r,channel:"push"})}}}}function le(t,e,n={}){let r=!1;function o(){if(r)throw new s("CLOSED","SDK client was destroyed")}let a=new Set,d=g=>{for(let l of a)try{l(g)}catch{}},y=t.session.subscribeIdentity(()=>{d(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:o,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(g){return o(),a.add(g),()=>{a.delete(g)}},identify(g){o();let l=typeof g=="string"?g:g.accessToken;if(!B.test(l))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(l),t.identify(g)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function pe(t){return{async checkEntitlement(e){e=b(e),T(e);let n=await f(t,"checkEntitlement"),r=n.request.parse(e),o=await m(t,n,r);return oe(r.requirement,o.check,void 0,o.scope),o},async readHoldings(e={}){e=b(e);let n=await f(t,"readHoldings"),r={...n,request:n.request.omit({customerId:!0})};return m(t,r,e)}}}function fe(t){return{async readLedger(e){e=b(e);let n=await f(t,"readLedger");return m(t,n,{query:e})},async readCreditStatement(e){e=b(e),T(e);let n=await f(t,"readCreditStatement");return m(t,n,e)},async quoteBalance(e){e=b(e),T(e);let n=await f(t,"quoteBalance");return m(t,n,{command:e})}}}function me(t){return{async setupPayment(e){e=b(e),T(e);let n=await f(t,"setupPayment");return m(t,n,e)},async readPaymentSetup(e){e=b(e),T(e);let n=await f(t,"readPaymentSetup");return m(t,n,e)},async readBillingInvoice(e){e=b(e),T(e);let n=await f(t,"readBillingInvoice");return m(t,n,e)},async readBillingControls(e={}){e=b(e),T(e);let n=await f(t,"readBillingControls");return m(t,n,e)},async prepareBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"prepareBillingAuthorization");return m(t,n,e)},async confirmBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"confirmBillingAuthorization");return m(t,n,e)},async setBillingCoupons(e){e=b(e),T(e);let n=await f(t,"setBillingCoupons");return m(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"revokeBillingAuthorization");return m(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){e=b(e),T(e);let n=await f(t,"listBillingInvoices");return m(t,n,e)},async confirmBillingAdjustment(e){e=b(e),T(e);let n=await f(t,"confirmBillingAdjustment");return m(t,n,e)}}}function ye(t){return{async redeemReward(e){return e=b(e),T(e),(await m(t,await f(t,"redeemReward"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return e=b(e),T(e),(await m(t,await f(t,"claimRewardProduct"),e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return e=b(e),T(e),(await m(t,await f(t,"createReferralCode"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){typeof e=="string"&&(e=e.trim().toUpperCase());let r=await m(t,await f(t,"redeemCoupon"),{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await m(t,await f(t,"grantOffer"),{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await m(t,await f(t,"listOffers"),{},{response:"Invalid offers response"})).offers}}}function Ie(t){return{...pe(t),...fe(t),...me(t),...se(t),...ye(t)}}function he(t){return{async resolveContent(e){e=b(e),T(e);let n=await f(t,"resolveContent");return m(t,n,e)},async resolvePaywall(e){e=b(e),T(e);let n=await f(t,"resolvePaywall"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.paywall.check,o.scope),o},async resolveOffering(e){e=b(e),T(e);let n=await f(t,"resolveOffering"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.check,o.scope),o}}}var Y=t=>new TextEncoder().encode(JSON.stringify(t)).length,we=16384,Pe=5e3,Ce=6e4,Re=5;function Te(t){return t instanceof s&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function ge(t,e){let n=0,r,o=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],d=null,y,g=0;function l(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(Pe*2**g,Ce)),typeof y=="object"&&"unref"in y&&y.unref())}function F(h){if(l(),r&&Date.now()<r.until&&!W(r.config,h.kind))return;q();let P=X.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(Y({events:[P]})>we)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function p(h,P={},E={}){F({kind:"custom",name:h,properties:P,...E})}async function S(h=!1){if(l(),d)return d;let P=n,E=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let u=[],A=Y({events:[]});for(let C of a.slice(0,Math.min(c,100))){let D=Y(C)+(u.length?1:0);if(u.length&&A+D>we)break;u.push(C),A+=D}let w;try{let C=await f(t,"trackEvents");if(w=await m(t,C,{events:u},void 0,{keepalive:h}),P!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==u.length||w.rejections.length!==w.rejected)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(C){throw P===n&&(g++,(Te(C)||g>=Re)&&(a.splice(0,u.length),g=0)),C}g=0,o(w.analyticsConfig),a.splice(0,u.length),c-=u.length,i.inserted+=w.inserted,i.duplicates+=w.duplicates,i.rejected+=w.rejected,i.skipped+=w.skipped,i.rejections.push(...w.rejections)}return i})();d=E;try{return await E}finally{d===E&&(d=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:o,track:p,observe:F,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],g=0,d=null},detachVisibility(){I?.(),I=void 0}}}function ve(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var qe=new Set([...$,"merchandiseId","merchandise"]);function ke(t){let e=ve(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!qe.has(r))),...e?{merchandise:e}:{}}}function Ee(t,e,n,r,o){if(o&&r&&(o.scope.projectId!==r.projectId||o.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,d=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function g(l={}){o||y();let O=a,F=!1,p=async()=>{if(F||O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=o?{scope:{projectId:o.scope.projectId,environment:o.scope.environment},payload:await o.features()}:await m(t,await f(t,"getFeatures"),{});if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await p(),I=!0,q,h=R=>{try{l.onError?.(R)}catch{}},P=(R,N)=>{try{let v=ve(N);n.observe({...R,...v?{merchandise:v}:{}})}catch(v){h(v)}},E=ae({assertUsable:o?.assertFeatures,scope:S.scope,attributes:l.attributes,onError:l.onError,load:async()=>I?(I=!1,S.payload):(await p()).payload,evaluateRemote:async R=>{if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let N=await f(t,"evaluateFeatures"),v=await m(t,N,{...R,attributes:ke(R.attributes)});if(v.scope.projectId!==S.scope.projectId||v.scope.environment!==S.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,N,v,V)=>P({kind:"experiment_exposure",generation:V,experimentId:R.key,variationId:N.key},v),onFeatureUsage:(R,N,v,V)=>P({kind:"feature_usage",generation:V,feature:R,value:N.value??null,source:N.source,ruleId:N.ruleId,...N.experimentResult?{variationId:N.experimentResult.key}:{}},v)}),i=E.refresh;function c(){clearTimeout(q),!o&&(F||O!==a||!E.expiresAt||(q=setTimeout(()=>{u().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(E.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function u(){try{return await i()}finally{c()}}let A=()=>{F||u().catch(h)},w=E.subscribe(c),C=o?.subscribe(()=>{!F&&o.fresh&&u().catch(h)});function D(){F||(F=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",A),w(),C?.(),E.reset(),d.delete(D))}d.add(D);try{await E.init(),(l.attributes?.merchandise||l.attributes?.merchandiseId)&&await E.refreshRemote()}catch(R){throw D(),R}return c(),!o&&typeof window<"u"&&window.addEventListener("focus",A),Object.assign(E,{refresh:u,destroy:D})}return{features:g,reset(l){a++,l();for(let O of d)O()}}}function be(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=K.object({funnelId:J.shape.id,funnelVersionId:J.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let o=Object.freeze(r.data);function a(d){if("customerId"in d)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in d&&d.funnelId!==void 0&&d.funnelId!==o.funnelId||"funnelVersionId"in d&&d.funnelVersionId!==void 0&&d.funnelVersionId!==o.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...d,...o}}return{async claimCoupon(d,y=crypto.randomUUID()){let g=await f(t,"grantOffer"),l=await m(t,g,a({couponId:d,requestId:y}));return{offer:l.offer,reason:l.reason}},async resolveOffering(d){d=b(d);let y=await f(t,"resolveOffering"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.check,l.scope),l},async resolvePaywall(d){d=b(d);let y=await f(t,"resolvePaywall"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.paywall.check,l.scope),l},async previewAttach(d){d=b(d);let y=await f(t,"previewAttach");return m(t,y,a(d))}}}function xt(t){return Ne(t)}function Ne(t){let e=ie(t),n=e.request,r;try{r=ue(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let o=le(e,()=>{d.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ge(n,o.isIdentified),d=Ee(n,o.isIdentified,a,t.scope,t.configuration);return{session:e.session,...de(n,r),...Ie(n),...he(n),forFunnel(y){return o.assertActive(),be(n,y)},async features(y={}){return o.assertActive(),d.features(y)},track(y,g,l={}){return a.track(y,g,l)},flush(){return a.flush()},...o.methods}}function Mt(t){if(!B.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=ce({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),o=M({...t,runToken:r.runToken,initialResponse:r});o.identify(t.customerToken);let a=await o.get();return{...r,...a,controller:o}}}}function Kt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,o=new Set,a=new Map,d=new Map;async function y(p){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(p),I])}finally{clearTimeout(S)}}function g(p){throw p instanceof s&&(p.status===401||p.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear()),p}function l(p,S){if(S!==r)throw new s("IDENTITY_CHANGED","Process was detached during a request");let I=re.parse(p);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let A of o)z(A,I.run);I.run.instruction?.type==="authentication_required"&&z(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&d.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:E,settlement:i,...c}=I,u=i&&(({accepted:A,...w})=>w)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...u?{settlement:u}:{}}}let O=p=>(a.has(p)||a.set(p,e?.run.identity.binding?.id??null),a.get(p));async function F(p){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return g(P)};if(p.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(p.release,p.usedReceiptIds)).catch(q)}let h;if(p.operation==="get"){let{operation:P,customerToken:E,...i}=p;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(p.operation==="review")h=await y(()=>t.adapter.review(p.receiptId)).catch(q);else{if(p.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...E}=p;h=await y(()=>t.adapter.command(E,O(E.requestId))).catch(q)}}return l(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(p){let S=r,I=await y(()=>t.adapter.open(p)).catch(g),q=l(I,S);if(!n){n=M({...t,runToken:I.runToken,initialResponse:q,process:{request:F,binding:O,restore(E){for(let[i,c]of Object.entries(E))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async E=>{try{return await P(E)}catch(i){if(!(i instanceof s)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||E.operation!=="submit"||E.input.type!=="screen"||a.get(E.requestId)!==null)throw i;await h.settle?.(E.requestId),await h.get();let c=h.view;if(d.get(E.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==E.nodeId||c.visit!==E.visit||!e?.run.identity.binding)throw i;return P({...E,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let p=r;l(await y(()=>t.adapter.syncIdentity()).catch(g),p),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),await y(()=>t.adapter.detach())},forProcess(p){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:p}},subscribe(p){return o.add(p),()=>{o.delete(p)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),o.clear()}}}export{xt as a,Ne as b,Mt as c,Kt as d};
1
+ import{a as T,b as se}from"./chunk-2TPPGW7V.js";import{b as re,h as ae,j as ce}from"./chunk-2QQZSMTB.js";import{a as oe,b as j}from"./chunk-23WNEOK4.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-JNSU2AP2.js";import{F as M,b as J}from"./chunk-7Z7JT4HE.js";import{a as b,b as f,c as m}from"./chunk-WK4WQZHK.js";import{b as W,j as X}from"./chunk-4ZVVG5LM.js";import{E as $}from"./chunk-ITVSLSRM.js";import{b as ie}from"./chunk-XZEGVBAI.js";import{a as B}from"./chunk-J4VTKRH7.js";import{a as s}from"./chunk-HJLGRW4A.js";import{h as Q}from"./chunk-XIP32WI7.js";import{b as K}from"./chunk-ZY4XAKNQ.js";import{a as z}from"./chunk-DSPLGTQI.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},Se=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ue(t,e,n){let r=null,o=0,a=0,d=0,y=Promise.resolve(),g=!1;if(t&&(!n||Q.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(g)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==o)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function F(i){let c=l();if(!c.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=c.sha256?await c.sha256(Uint8Array.from(i,A=>A.charCodeAt(0))):await Se(i);if(!/^[a-f0-9]{64}$/.test(u))throw new s("INVALID_STATE","Push credential digest is invalid");return u}function p(i){let c=G.parse(i);if(c.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let u=l(),A={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...c},w=await u.sign(ne(i,u.scope,A));return{...A,signature:w}}let I=(i,c,u)=>e.requestWithCredential?e.requestWithCredential(i,c,u):e.request(i,c);async function q(){let i=l(),c=o,u=r?await(e.session?.access()??r):null,A=_(i,v=>v),w;if(A.detachSeq!==null){let v=A.detachSeq,V=Z.parse(await S("detach",{sequence:v,platform:i.platform}));try{let k=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!k||typeof k!="object"||!("installation"in k))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let x=p(k.installation);if(x.bound||x.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(k){if(k instanceof s&&k.status===404)w=k;else if(!(k instanceof s)||k.status!==412)throw k}w||_(i,k=>({...k,detachSeq:k.detachSeq===v?null:k.detachSeq}))}if(O(c),!u){if(w)throw w;return null}let C=(await import("./operation-contracts-SP2RZUT3.js")).apiOperations.bindPushInstallation,D=C.request.parse(await S("bind",{sequence:d,platform:i.platform,credentialDigest:await F(u)}));O(c);let R=C.response.parse(await I(C.path,D,u));O(c);let N=p(R.installation);if(!N.bound||N.identitySeq!==d)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return w&&A.detachSeq!==null&&d>A.detachSeq&&_(i,v=>({...v,detachSeq:v.detachSeq===A.detachSeq?null:v.detachSeq})),N}async function h(){l();let i=o,c=r?await(e.session?.access()??r):null;if(!c)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let u=(await import("./operation-contracts-SP2RZUT3.js")).apiOperations.readPushInstallation,A=u.request.parse(await S("read",{credentialDigest:await F(c)}));O(i);let w=u.response.parse(await I(u.path,A,c));return O(i),p(w.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),c}async function E(i,c,u){let A=l(),w=c.identity,C=c.observation,D=r?await(e.session?.access()??r):null;if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");if(!D)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(w),await q(),O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(A,x=>u?x:{...x,addressSeq:U(x.addressSeq)}),v=await S(u?"recovery_confirm":"recovery_request",{...i,sequence:R.addressSeq,credentialDigest:await F(D),...u?{challenge:u}:{}}),V=u?te.parse(v):ee.parse(v);if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let k=await I(`push/installations/recovery/${u?"confirm":"request"}`,V,D);if(O(w),C!==a||_(A,x=>x).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(u){let{apiOperations:x}=await import("./operation-contracts-SP2RZUT3.js");if(O(w),C!==a||_(A,Oe=>Oe).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");let Ae=x.updatePushAddress.response.parse(k),L=p(Ae.installation);if(!L.bound||L.identitySeq!==d||L.addressSeq!==R.addressSeq||L.connectionId!==i.connectionId||L.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return L}if(!k||typeof k!="object"||!("recovery"in k))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return H.parse(k.recovery)})}return{recoveryObserver(){l();let i={identity:o,observation:++a};return{async request(c){return H.parse(await E(c,i))},async confirm(c,u){return G.parse(await E(u,i,c))}}},identify(i){if(!t)return;d=_(t,u=>({...u,identitySeq:U(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,o++,a++}},start(){t&&!g&&P()},destroy(){g=!0,r=null,o++,a++},async sync(){return await P()},read:h,async recover(){let i=l(),c=o,u=d;return a++,await P(async()=>{O(c);let A=await h();return O(c),d=_(i,C=>{if(C.identitySeq!==u)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...C,identitySeq:U(Math.max(C.identitySeq,A.identitySeq)),addressSeq:Math.max(C.addressSeq,A.addressSeq)}}).identitySeq,await q()})},tokenObserver(){l();let i=++a,c=o;return async u=>{if(i!==a||c!==o)return null;let A=l(),w=r?await(e.session?.access()??r):null;if(!w)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let C=_(A,v=>({...v,addressSeq:U(v.addressSeq)})),D=(await import("./operation-contracts-SP2RZUT3.js")).apiOperations.updatePushAddress,R=D.request.parse(await S("address",{...u,sequence:C.addressSeq,credentialDigest:await F(w)}));if(O(c),i!==a)return null;let N=await I(D.path,R,w);return O(c),i!==a||_(A,v=>v).addressSeq!==C.addressSeq?null:p(D.response.parse(N).installation)}}}}function de(t,e){let n={async preference(r){let o=await f(t,"readMessagingPreference");return(await m(t,o,{channel:r})).preference},async setPreference(r){r=b(r);let o=await f(t,"setMessagingPreference");return(await m(t,o,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return r=b(r),n.setPreference({...r,channel:"push"})}}}}function le(t,e,n={}){let r=!1;function o(){if(r)throw new s("CLOSED","SDK client was destroyed")}let a=new Set,d=g=>{for(let l of a)try{l(g)}catch{}},y=t.session.subscribeIdentity(()=>{d(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:o,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(g){return o(),a.add(g),()=>{a.delete(g)}},identify(g){o();let l=typeof g=="string"?g:g.accessToken;if(!B.test(l))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(l),t.identify(g)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function pe(t){return{async checkEntitlement(e){e=b(e),T(e);let n=await f(t,"checkEntitlement"),r=n.request.parse(e),o=await m(t,n,r);return oe(r.requirement,o.check,void 0,o.scope),o},async readHoldings(e={}){e=b(e);let n=await f(t,"readHoldings"),r={...n,request:n.request.omit({customerId:!0})};return m(t,r,e)}}}function fe(t){return{async readLedger(e){e=b(e);let n=await f(t,"readLedger");return m(t,n,{query:e})},async readCreditStatement(e){e=b(e),T(e);let n=await f(t,"readCreditStatement");return m(t,n,e)},async quoteBalance(e){e=b(e),T(e);let n=await f(t,"quoteBalance");return m(t,n,{command:e})}}}function me(t){return{async setupPayment(e){e=b(e),T(e);let n=await f(t,"setupPayment");return m(t,n,e)},async readPaymentSetup(e){e=b(e),T(e);let n=await f(t,"readPaymentSetup");return m(t,n,e)},async readBillingInvoice(e){e=b(e),T(e);let n=await f(t,"readBillingInvoice");return m(t,n,e)},async readBillingControls(e={}){e=b(e),T(e);let n=await f(t,"readBillingControls");return m(t,n,e)},async prepareBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"prepareBillingAuthorization");return m(t,n,e)},async confirmBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"confirmBillingAuthorization");return m(t,n,e)},async setBillingCoupons(e){e=b(e),T(e);let n=await f(t,"setBillingCoupons");return m(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"revokeBillingAuthorization");return m(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){e=b(e),T(e);let n=await f(t,"listBillingInvoices");return m(t,n,e)},async confirmBillingAdjustment(e){e=b(e),T(e);let n=await f(t,"confirmBillingAdjustment");return m(t,n,e)}}}function ye(t){return{async redeemReward(e){return e=b(e),T(e),(await m(t,await f(t,"redeemReward"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return e=b(e),T(e),(await m(t,await f(t,"claimRewardProduct"),e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return e=b(e),T(e),(await m(t,await f(t,"createReferralCode"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){typeof e=="string"&&(e=e.trim().toUpperCase());let r=await m(t,await f(t,"redeemCoupon"),{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await m(t,await f(t,"grantOffer"),{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await m(t,await f(t,"listOffers"),{},{response:"Invalid offers response"})).offers}}}function Ie(t){return{...pe(t),...fe(t),...me(t),...se(t),...ye(t)}}function he(t){return{async resolveContent(e){e=b(e),T(e);let n=await f(t,"resolveContent");return m(t,n,e)},async resolvePaywall(e){e=b(e),T(e);let n=await f(t,"resolvePaywall"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.paywall.check,o.scope),o},async resolveOffering(e){e=b(e),T(e);let n=await f(t,"resolveOffering"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.check,o.scope),o}}}var Y=t=>new TextEncoder().encode(JSON.stringify(t)).length,we=16384,Pe=5e3,Ce=6e4,Re=5;function Te(t){return t instanceof s&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function ge(t,e){let n=0,r,o=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],d=null,y,g=0;function l(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(Pe*2**g,Ce)),typeof y=="object"&&"unref"in y&&y.unref())}function F(h){if(l(),r&&Date.now()<r.until&&!W(r.config,h.kind))return;q();let P=X.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(Y({events:[P]})>we)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function p(h,P={},E={}){F({kind:"custom",name:h,properties:P,...E})}async function S(h=!1){if(l(),d)return d;let P=n,E=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let u=[],A=Y({events:[]});for(let C of a.slice(0,Math.min(c,100))){let D=Y(C)+(u.length?1:0);if(u.length&&A+D>we)break;u.push(C),A+=D}let w;try{let C=await f(t,"trackEvents");if(w=await m(t,C,{events:u},void 0,{keepalive:h}),P!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==u.length||w.rejections.length!==w.rejected)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(C){throw P===n&&(g++,(Te(C)||g>=Re)&&(a.splice(0,u.length),g=0)),C}g=0,o(w.analyticsConfig),a.splice(0,u.length),c-=u.length,i.inserted+=w.inserted,i.duplicates+=w.duplicates,i.rejected+=w.rejected,i.skipped+=w.skipped,i.rejections.push(...w.rejections)}return i})();d=E;try{return await E}finally{d===E&&(d=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:o,track:p,observe:F,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],g=0,d=null},detachVisibility(){I?.(),I=void 0}}}function ve(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var qe=new Set([...$,"merchandiseId","merchandise"]);function ke(t){let e=ve(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!qe.has(r))),...e?{merchandise:e}:{}}}function Ee(t,e,n,r,o){if(o&&r&&(o.scope.projectId!==r.projectId||o.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,d=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function g(l={}){o||y();let O=a,F=!1,p=async()=>{if(F||O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=o?{scope:{projectId:o.scope.projectId,environment:o.scope.environment},payload:await o.features()}:await m(t,await f(t,"getFeatures"),{});if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await p(),I=!0,q,h=R=>{try{l.onError?.(R)}catch{}},P=(R,N)=>{try{let v=ve(N);n.observe({...R,...v?{merchandise:v}:{}})}catch(v){h(v)}},E=ae({assertUsable:o?.assertFeatures,scope:S.scope,attributes:l.attributes,onError:l.onError,load:async()=>I?(I=!1,S.payload):(await p()).payload,evaluateRemote:async R=>{if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let N=await f(t,"evaluateFeatures"),v=await m(t,N,{...R,attributes:ke(R.attributes)});if(v.scope.projectId!==S.scope.projectId||v.scope.environment!==S.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,N,v,V)=>P({kind:"experiment_exposure",generation:V,experimentId:R.key,variationId:N.key},v),onFeatureUsage:(R,N,v,V)=>P({kind:"feature_usage",generation:V,feature:R,value:N.value??null,source:N.source,ruleId:N.ruleId,...N.experimentResult?{variationId:N.experimentResult.key}:{}},v)}),i=E.refresh;function c(){clearTimeout(q),!o&&(F||O!==a||!E.expiresAt||(q=setTimeout(()=>{u().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(E.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function u(){try{return await i()}finally{c()}}let A=()=>{F||u().catch(h)},w=E.subscribe(c),C=o?.subscribe(()=>{!F&&o.fresh&&u().catch(h)});function D(){F||(F=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",A),w(),C?.(),E.reset(),d.delete(D))}d.add(D);try{await E.init(),(l.attributes?.merchandise||l.attributes?.merchandiseId)&&await E.refreshRemote()}catch(R){throw D(),R}return c(),!o&&typeof window<"u"&&window.addEventListener("focus",A),Object.assign(E,{refresh:u,destroy:D})}return{features:g,reset(l){a++,l();for(let O of d)O()}}}function be(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=K.object({funnelId:J.shape.id,funnelVersionId:J.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let o=Object.freeze(r.data);function a(d){if("customerId"in d)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in d&&d.funnelId!==void 0&&d.funnelId!==o.funnelId||"funnelVersionId"in d&&d.funnelVersionId!==void 0&&d.funnelVersionId!==o.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...d,...o}}return{async claimCoupon(d,y=crypto.randomUUID()){let g=await f(t,"grantOffer"),l=await m(t,g,a({couponId:d,requestId:y}));return{offer:l.offer,reason:l.reason}},async resolveOffering(d){d=b(d);let y=await f(t,"resolveOffering"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.check,l.scope),l},async resolvePaywall(d){d=b(d);let y=await f(t,"resolvePaywall"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.paywall.check,l.scope),l},async previewAttach(d){d=b(d);let y=await f(t,"previewAttach");return m(t,y,a(d))}}}function xt(t){return Ne(t)}function Ne(t){let e=ie(t),n=e.request,r;try{r=ue(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let o=le(e,()=>{d.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ge(n,o.isIdentified),d=Ee(n,o.isIdentified,a,t.scope,t.configuration);return{session:e.session,...de(n,r),...Ie(n),...he(n),forFunnel(y){return o.assertActive(),be(n,y)},async features(y={}){return o.assertActive(),d.features(y)},track(y,g,l={}){return a.track(y,g,l)},flush(){return a.flush()},...o.methods}}function Mt(t){if(!B.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=ce({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),o=M({...t,runToken:r.runToken,initialResponse:r});o.identify(t.customerToken);let a=await o.get();return{...r,...a,controller:o}}}}function Kt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,o=new Set,a=new Map,d=new Map;async function y(p){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(p),I])}finally{clearTimeout(S)}}function g(p){throw p instanceof s&&(p.status===401||p.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear()),p}function l(p,S){if(S!==r)throw new s("IDENTITY_CHANGED","Process was detached during a request");let I=re.parse(p);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let A of o)z(A,I.run);I.run.instruction?.type==="authentication_required"&&z(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&d.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:E,settlement:i,...c}=I,u=i&&(({accepted:A,...w})=>w)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...u?{settlement:u}:{}}}let O=p=>(a.has(p)||a.set(p,e?.run.identity.binding?.id??null),a.get(p));async function F(p){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return g(P)};if(p.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(p.release,p.usedReceiptIds)).catch(q)}let h;if(p.operation==="get"){let{operation:P,customerToken:E,...i}=p;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(p.operation==="review")h=await y(()=>t.adapter.review(p.receiptId)).catch(q);else{if(p.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...E}=p;h=await y(()=>t.adapter.command(E,O(E.requestId))).catch(q)}}return l(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(p){let S=r,I=await y(()=>t.adapter.open(p)).catch(g),q=l(I,S);if(!n){n=M({...t,runToken:I.runToken,initialResponse:q,process:{request:F,binding:O,restore(E){for(let[i,c]of Object.entries(E))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async E=>{try{return await P(E)}catch(i){if(!(i instanceof s)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||E.operation!=="submit"||E.input.type!=="screen"||a.get(E.requestId)!==null)throw i;await h.settle?.(E.requestId),await h.get();let c=h.view;if(d.get(E.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==E.nodeId||c.visit!==E.visit||!e?.run.identity.binding)throw i;return P({...E,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let p=r;l(await y(()=>t.adapter.syncIdentity()).catch(g),p),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),await y(()=>t.adapter.detach())},forProcess(p){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:p}},subscribe(p){return o.add(p),()=>{o.delete(p)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),o.clear()}}}export{xt as a,Ne as b,Mt as c,Kt as d};
@@ -1 +1 @@
1
- var s={name:"@tinkerlandai/longplay-sdk",version:"0.10.30",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var i="https://api.longplayai.com";export{s as a,i as b};
1
+ var s={name:"@tinkerlandai/longplay-sdk",version:"0.10.31",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var i="https://api.longplayai.com";export{s as a,i as b};
@@ -0,0 +1 @@
1
+ import{p as n,s as t}from"./chunk-7Z7JT4HE.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};