@tinkerlandai/longplay-sdk 0.10.26-rc.1 → 0.10.26
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/dist/{chunk-UNG42D7U.js → chunk-2MTTK3BT.js} +1 -1
- package/dist/{chunk-4CH6FLDU.js → chunk-3FPYCF7Z.js} +1 -1
- package/dist/{chunk-5K2E5XBL.js → chunk-CZ3H2X7D.js} +1 -1
- package/dist/{chunk-GCNYVAYY.js → chunk-DCCM7FYR.js} +1 -1
- package/dist/{chunk-4IJU33UM.js → chunk-DCIGO3NJ.js} +1 -1
- package/dist/{chunk-6DBYFYEU.js → chunk-G7NSECIG.js} +1 -1
- package/dist/{chunk-N7CRURKE.js → chunk-KRTX4QEH.js} +1 -1
- package/dist/{chunk-I5RVPWVD.js → chunk-MRFBMFNK.js} +1 -1
- package/dist/{chunk-NZSLDALU.js → chunk-MWDR5FEU.js} +1 -1
- package/dist/chunk-ORPOCB2J.js +1 -0
- package/dist/chunk-SMIO7OG5.js +1 -0
- package/dist/{chunk-WZLEYOWM.js → chunk-UHI7SPHK.js} +1 -1
- package/dist/{chunk-HPXSHXSB.js → chunk-YSNMXK4R.js} +1 -1
- package/dist/{content-BP7GV42L.js → content-UDP5VQS4.js} +1 -1
- package/dist/{funnel-host-purchase-LWIBVHF2.js → funnel-host-purchase-5NLPYJRK.js} +1 -1
- package/dist/{funnel-runtime-host-GWRYR523.js → funnel-runtime-host-ZWUAGDBU.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/page.js +1 -1
- package/dist/{paywall-54WX5YUZ.js → paywall-QQ2MC4KO.js} +1 -1
- package/dist/{paywall-session-7VQENUWU.js → paywall-session-WC2WFWBQ.js} +1 -1
- package/dist/react-native.js +1 -1
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-4RQNPBLW.js +0 -1
- package/dist/chunk-ATMVXNDD.js +0 -1
|
@@ -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-WZLEYOWM.js";import{d as Xe}from"./chunk-6DBYFYEU.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-MYUYN7ZG.js";import{$ as D,H as he,I as Ve,u as Ue}from"./chunk-PMCGTXGH.js";import{a as de,b as Qe}from"./chunk-NZSLDALU.js";import{a as ce}from"./chunk-UBKD6VMS.js";import{V as le}from"./chunk-5RXU57I5.js";import{a as L}from"./chunk-X7G7JMZ3.js";import{h as oe}from"./chunk-JAKOBECD.js";import{b as Ze}from"./chunk-3VUPVXAV.js";import{b as Ye}from"./chunk-ATMVXNDD.js";import{b as e}from"./chunk-WM27UTWT.js";import{c as Ae,f as Pe}from"./chunk-O4KXODTJ.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-UHI7SPHK.js";import{d as Xe}from"./chunk-G7NSECIG.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-MYUYN7ZG.js";import{$ as D,H as he,I as Ve,u as Ue}from"./chunk-PMCGTXGH.js";import{a as de,b as Qe}from"./chunk-MWDR5FEU.js";import{a as ce}from"./chunk-UBKD6VMS.js";import{V as le}from"./chunk-5RXU57I5.js";import{a as L}from"./chunk-X7G7JMZ3.js";import{h as oe}from"./chunk-JAKOBECD.js";import{b as Ze}from"./chunk-3VUPVXAV.js";import{b as Ye}from"./chunk-SMIO7OG5.js";import{b as e}from"./chunk-WM27UTWT.js";import{c as Ae,f as Pe}from"./chunk-O4KXODTJ.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-
|
|
1
|
+
import{a,b as o,c as i}from"./chunk-G7NSECIG.js";import{a as p}from"./chunk-X7G7JMZ3.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 h}from"./chunk-6VY4PZZ6.js";import{b as J}from"./chunk-BZSKOOMM.js";import{c as N,e as x}from"./chunk-
|
|
1
|
+
import{e as h}from"./chunk-6VY4PZZ6.js";import{b as J}from"./chunk-BZSKOOMM.js";import{c as N,e as x}from"./chunk-G7NSECIG.js";import{v as Q}from"./chunk-C6JRUYKW.js";import{a as j,f as H,g as K,h as B,i as F}from"./chunk-PWQ5BHBJ.js";import{b as L}from"./chunk-HMRIMJ5W.js";import{b as U}from"./chunk-MWDR5FEU.js";import{a as M}from"./chunk-UBKD6VMS.js";import{qa as G}from"./chunk-5RXU57I5.js";import{a as l}from"./chunk-X7G7JMZ3.js";import{a as W}from"./chunk-DSPLGTQI.js";async function ce(I,o){if(!M.test(o.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");if(I.session&&I.session.peek()!==o.customerToken)throw new l("SCOPE_MISMATCH","Paywall credential does not match the shared session");let u=h.resolvePaywall.request.parse({funnelId:o.funnelId,funnelVersionId:o.funnelVersionId,selector:o.paywallVersionId?{type:"version",versionId:o.paywallVersionId}:{type:"paywall",paywallId:o.paywallId},commerce:o.commerce,locale:o.locale,...o.requirement?{requirement:o.requirement}:{}}),S=U(I);I.session||S.identify(o.customerToken);let r=null,P=!1,D=new AbortController,s=null,c=null,v=null,w=null,R=null,d=null,f=null,A=0,O=null,_="",V=0,b=new Map,q=new Set;function g(){if(P)throw new l("IDENTITY_CHANGED","Paywall is closed")}function k(){let e=JSON.stringify([A,f!==null]);if(!O||e!==_){_=e;let t=Y(++V);O=t;let a=()=>{O===t&&(O=null)};t.then(a,a)}return O.then(t=>structuredClone(t))}async function Y(e){g();let t=h.resolvePaywall,a=await N(S.request,t,{...u,selector:r?{type:"version",versionId:r.id}:u.selector});J(u,a.paywall.check,a.scope);let i=await x(I,a.paywall);if(g(),o.paywallVersionId?i.id!==o.paywallVersionId:i.paywallId!==o.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(r&&(!H(i,r)||i.paywallId!==r.paywallId))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");if(e!==V)return structuredClone(r??i);r=i;for(let m of q)W(m,structuredClone(r));return structuredClone(r)}async function E(e){if(g(),w&&e!=="read")throw new l("COMMAND_PENDING","Wait for the original quote");if(!s)throw new l("INVALID_REQUEST","A quoted purchase is required");let t=s;if(e!=="read"){if(f){if(d===e)return f;throw new l("COMMAND_PENDING","Wait for the original purchase command")}if(d&&d!==e)throw new l("COMMAND_PENDING","Read the original purchase before changing an uncertain command");d=e,A++,V++}let a=d,i=A,m=e==="read"&&f===null,p=JSON.stringify([t.operationId,i,f!==null]);if(e==="read"&&b.has(p))return b.get(p).then(n=>structuredClone(n));let C=e==="read"?h.readSubscriptionOperation:h.attach,y=(async()=>{let n=await N(S.request,C,{operationId:t.operationId,...e==="read"?{}:{intent:e},...e==="confirm"&&t.merchantTerms?{merchantConfirmation:Q(t.merchantTerms)}:{}});return K(n.operation,{operationId:t.operationId,currency:u.commerce.currency},"The purchase operation changed"),g(),s?.operationId!==t.operationId?structuredClone(n.operation):(c=F(c,n.operation),(e!=="read"||m&&f===null)&&A===i&&d===a&&(d=null),structuredClone(c))})();if(e!=="read"){f=y;let n=()=>{f===y&&(f=null)};y.then(n,n)}else{b.set(p,y);let n=()=>{b.get(p)===y&&b.delete(p)};y.then(n,n)}return y.then(n=>structuredClone(n))}let T={signal:D.signal,get view(){return r?structuredClone(r):null},get quote(){return s?structuredClone(s):null},get operation(){return c?structuredClone(c):null},get webViewUrl(){return"bundled"},get recovery(){return j({quote:s,operation:c,requestId:R,pending:w!==null||d!==null,destroyed:P})},get pendingCancellation(){return!P&&d==="cancel"},refresh:k,subscribe(e){return P?()=>{}:(q.add(e),()=>q.delete(e))},async preview(e){if(g(),!r)throw new l("INVALID_REQUEST","Load the Paywall first");let t=r.document.buttons[e.actionId];if(t?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let a=L(t.product,e.selection,r.capabilities);if(!a)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let i=G(r.document.screen,a,e.selection,r.capabilities),m=h.previewAttach.request.parse({funnelId:u.funnelId,funnelVersionId:u.funnelVersionId,requestId:e.requestId,plans:[{productVersionId:a,...Object.keys(i).length?{featureQuantities:i}:{}}],provider:u.commerce.provider,currency:u.commerce.currency,...e.offerId?{offerId:e.offerId}:{},...e.nativeOffer?{nativeOffer:e.nativeOffer}:{}}),p=JSON.stringify(m);if(v&&v!==p&&(w||d||!c||c.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(v===p){if(w)return w;if(s)return structuredClone(s)}v!==p&&(s=null,c=null),v=p,R=m.requestId;let C=(async()=>{let y=h.previewAttach,n=await N(S.request,y,m);return g(),B(n.quote,{productVersionId:a,featureQuantities:i,currency:u.commerce.currency,provider:u.commerce.provider},"The purchase quote changed its selected Product or presentment"),s=n.quote,c=null,structuredClone(s)})();w=C;try{return await C}finally{w===C&&(w=null)}},confirm:()=>E("confirm"),cancel:()=>E("cancel"),read:()=>E("read"),destroy(){P||(P=!0,D.abort(),q.clear(),b.clear(),z?.(),S.dispose(),r=null,s=null,c=null,v=null,R=null)}},z=I.session?.subscribeIdentity(T.destroy);try{return await k(),T}catch(e){throw T.destroy(),e}}export{ce as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as Ie}from"./chunk-4CH6FLDU.js";import{a as Q}from"./chunk-ECMWY3G2.js";import{A as Se,E as z,G as Pe,d as pe,f as k,k as me,v as we,w as ge,y as ye}from"./chunk-WZLEYOWM.js";import{$ as N}from"./chunk-PMCGTXGH.js";import{a as B,i as J}from"./chunk-PWQ5BHBJ.js";import{b as he}from"./chunk-NZSLDALU.js";import{a as c}from"./chunk-X7G7JMZ3.js";import{h as G}from"./chunk-JAKOBECD.js";import{b as fe}from"./chunk-ATMVXNDD.js";import{b as r}from"./chunk-WM27UTWT.js";import{a as oe}from"./chunk-DSPLGTQI.js";var g=N.options,Ae=r.discriminatedUnion("operation",[g[1].omit({customerToken:!0}),g[2].omit({customerToken:!0}),g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0}),g[8].omit({customerToken:!0}),me.omit({customerToken:!0})]),je=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),Me=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume"]),start:r.strictObject({requestId:g[0].shape.requestId,funnelId:g[0].shape.funnelId,locale:g[0].shape.locale,parameters:g[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:je}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0})]).optional()}).refine(o=>!o.command||o.requestId===o.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:Ae})]),ae=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:k.shape.run.shape.status}),K={scope:G,customerId:r.uuid()},Ce=r.discriminatedUnion("outcome",[r.strictObject({...K,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...K,outcome:r.literal("resolved"),target:ae,view:k.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((o,d)=>{o.outcome==="resolved"&&(o.access.type==="customer"!=(o.view!==null)||o.view&&(o.view.id!==o.target.runId||o.view.source.id!==o.target.funnelId||o.view.source.versionId!==o.target.versionId||o.view.status!==o.target.status||o.view.runExpiresAt!==o.target.runExpiresAt||o.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Re=r.strictObject({...K,target:ae,view:k.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:k.shape.purchase.unwrap().nullable()}).superRefine((o,d)=>{let p=o.settlement;(p.acceptance==="accepted"!=(p.receiptPhase!==null)||p.acceptance==="accepted"&&p.basis!=="receipt"||p.acceptance==="unknown"&&(p.state!=="unknown"||p.basis!=="none")||p.acceptance!=="accepted"&&(p.operationId!==null||p.receiptId!==null)||p.acceptance==="not_accepted"&&(p.state!=="settled"||!["run_terminal","position_advanced"].includes(p.basis))||o.purchase&&(o.purchase.receiptId!==p.receiptId||o.purchase.operation&&o.purchase.operation.operationId!==p.operationId||o.purchase.quote&&o.purchase.quote.operationId!==p.operationId)||o.view&&(o.view.id!==o.target.runId||o.view.source.id!==o.target.funnelId||o.view.source.versionId!==o.target.versionId||o.view.status!==o.target.status||o.view.runExpiresAt!==o.target.runExpiresAt||o.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ee=r.strictObject({...K,target:ae,purchase:k.shape.purchase.unwrap()}).superRefine((o,d)=>{(!o.purchase.operation||typeof o.purchase.canReselect!="boolean"||o.purchase.quote&&o.purchase.quote.operationId!==o.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})});var Ne=N.options[0].refine(o=>!o.customer&&!o.customerData),ke=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),ve=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:G,customerId:r.uuid(),sessionId:r.uuid(),start:Ne,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:pe.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ke).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:we.nullable()})});function be(o){return ye({...o,namespace:"purchases",identity:[o.scope.projectId,o.scope.environment,o.customerId]})}function Oe(o){let d=new URL(o.baseUrl??fe).href,p=()=>new c("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function E(){o.assertCurrent();try{let y=await o.storage.read();if(o.assertCurrent(),!Number.isSafeInteger(y.revision)||y.revision<0)throw p();let a=y.entry===null?null:ve.parse(y.entry);if(a&&(a.baseUrl!==d||a.customerId!==o.customerId||a.scope.projectId!==o.scope.projectId||a.scope.environment!==o.scope.environment))throw new c("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(a?.journal.entry&&(a.journal.entry.scope.projectId!==a.scope.projectId||a.journal.entry.scope.environment!==a.scope.environment||a.journal.entry.funnelId!==a.start.funnelId||a.journal.entry.runId!==a.run?.id||a.journal.entry.versionId!==a.run?.versionId)||a?.operationCommand&&!a.purchases.some(R=>R.operationId===a.operationCommand?.operationId))throw p();return{revision:y.revision,entry:a}}catch(y){throw y instanceof c?y:p()}}async function Y(y){for(let a=0;a<8;a++){let R=await E(),b=y(structuredClone(R.entry));if(JSON.stringify(b)===JSON.stringify(R.entry))return b;b&&ve.parse(b),o.assertCurrent();let v;try{v=await o.storage.write(R.revision,b)}catch{throw p()}if(o.assertCurrent(),v!==null){if(!Number.isSafeInteger(v)||v<=R.revision)throw p();return b}}throw new c("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:E,update:Y,baseUrl:d}}function Te(o){let d=o.purchases.find(p=>p.type==="checkout");if(!o.actions.includes("continue_checkout")||d?.type!=="checkout")throw new c("PURCHASE_PENDING","No single resumable Checkout is confirmed");return d.checkoutUrl}function pn(o){let d={...o,scope:{...o.scope},executionPolicy:structuredClone(o.executionPolicy)},p=d.session.snapshot();if(!p)throw new c("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:E,sessionId:Y}=p,y=!1,a=null,R,b=null,v=!1,q,U,D,O={mode:"idle",status:"idle",actions:["start"],purchases:[]},I=new Map,j=new Map,ie=new AbortController,H=new Set,W=he(d),se=Ie(W.request);function L(e){return{code:e instanceof c?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof c&&e.status!==void 0?{status:e.status}:{}}}function P(){if(y||d.session.snapshot()?.customerId!==E)throw new c("IDENTITY_CHANGED","The original purchase Customer changed")}let w=Oe({...d,customerId:E,assertCurrent:P,storage:d.storage??be({baseUrl:d.baseUrl,scope:d.scope,customerId:E})}),Fe=d.session.subscribeIdentity(ue);function ue(){y||(y=!0,clearTimeout(D),ie.abort(new c("IDENTITY_CHANGED","Purchase consumer was destroyed")),Fe(),a?.reset(),a=null,b=null,W.dispose(),H.clear(),I.clear(),j.clear())}function C(e){P();let n=JSON.stringify(e)!==JSON.stringify(O);O=e,clearTimeout(D),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(D=setTimeout(()=>{T().catch(()=>{})},5e3)),n&&oe(d.onRecovery,structuredClone(e));for(let t of n?H:[]){if(y)break;oe(t,structuredClone(e))}return structuredClone(e)}function h(e){if(P(),!e||e.start.requestId!==R)throw new c("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function F(e){let n=[...e.purchases],t=e.journal.entry?.purchase;return t&&!n.some(u=>u.operationId===t.operationId)&&n.push({receiptId:t.receiptId,operationId:t.operationId,terminal:null}),n}function M(e){return e.run&&!["running","waiting"].includes(e.run.status)&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&F(e).every(n=>n.terminal!==null)}function _(e,n){let t=e.journal.entry?.command??e.journal.entry?.closeCommand,u=F(e).map(S=>{let re=I.get(S.operationId);return S.terminal&&!re?{type:S.terminal,operationId:S.operationId}:B({quote:re?.quote??null,operation:re??null,requestId:t?.requestId??null,pending:!1,destroyed:!1,canReselect:j.get(S.operationId)===!0})}),l=u.filter(S=>!["complete","native"].includes(S.type)),i=l[0],s=l.length===1&&i?.operationId?I.get(i.operationId):void 0;if(s&&(i?.type==="checkout"||i?.type==="cancel"))try{z({allowed:e.allowed.filter(S=>d.executionPolicy.allowed.includes(S))},s.quote)}catch(S){return{mode:n,status:"blocked",actions:["refresh",...n==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:u,error:L(S)}}let m;if(n==="operation"&&!t&&i?.type==="cancel"&&s?.quote&&!s.problem&&!s.confirmedAt)try{z({allowed:e.allowed.filter(S=>d.executionPolicy.allowed.includes(S))},s.quote),Date.parse(s.quote.expiresAt)>Date.now()&&(m={operationId:s.operationId,quote:s.quote})}catch{}let f=u.length>0&&l.length===0,x=M(e)||n==="operation"&&f&&!t&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":t||e.operationCommand||i&&i.type!=="cancel"||n==="operation"&&!m?"waiting_result":"ready";return{mode:n,status:x,purchases:u,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...M(e)?["start"]:[],...n==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...l.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function $(e){let n=B({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&j.get(e.operationId)===!0});return n.type==="complete"||n.type==="native"?n.type:null}function X(e){if(!e.operation)return;let n={...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}};if(n.merchantExecution&&n.merchantExecution.customerId!==E)throw new c("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let t=J(I.get(n.operationId)??null,n);I.set(n.operationId,t),t===n&&j.set(n.operationId,e.canReselect===!0)}async function qe(e){P();for(let t of[e.purchase,e.run.paywall])t&&X(t);let n=await w.update(t=>{if(h(t),t.run&&(t.run.id!==e.run.id||t.run.versionId!==e.run.source.versionId))throw new c("SCOPE_MISMATCH","The original purchase Run changed");let u=F(t);for(let l of[e.purchase,e.run.paywall]){let i=l?.operation?.operationId??l?.quote?.operationId;if(!l||!i)continue;let s=u.find(f=>f.operationId===i);if(s&&s.receiptId!==l.receiptId)throw new c("INVALID_RESPONSE","The original purchase Receipt changed");let m=$(I.get(i));s?s.terminal??=m:u.push({receiptId:l.receiptId,operationId:i,terminal:m})}return{...t,purchases:u,run:t.run&&(t.run.revision>e.run.revision||!["running","waiting"].includes(t.run.status)&&["running","waiting"].includes(e.run.status))?t.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});h(n),n.run&&!["running","waiting"].includes(n.run.status)&&F(n).some(t=>!t.terminal)&&(n=await Z(n,!n.journal.entry?.command&&!n.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(t=>!!t)))),h(n),C(_(n,"run"))}function _e(){return{async read(){let{entry:e}=await w.read();return h(e),structuredClone(e.journal)},async write(e,n){let t=null;return await w.update(u=>{if(h(u),u.operationCommand&&n?.command&&n.command.operation!=="close")throw new c("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return t=null,u.journal.revision!==e?u:(t=e+1,{...u,journal:{revision:t,entry:n}})}),t}}}async function Z(e,n=!1,t=new Set){h(e);let u=F(e);for(let i of u){if(i.terminal)continue;let s=t.has(i.operationId)?I.get(i.operationId):void 0;if(s??=await ce(e,i),P(),s.operationId!==i.operationId)throw new c("INVALID_RESPONSE","Original Operation changed");if(s.merchantExecution&&s.merchantExecution.customerId!==E)throw new c("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(n&&!e.operationCommand&&B({quote:s.quote??null,operation:s,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){if({operation:s}=await se.attach({operationId:i.operationId,intent:"cancel"}),P(),s.operationId!==i.operationId)throw new c("INVALID_RESPONSE","Original cancellation Operation changed");s=await ce(e,i)}I.set(i.operationId,J(I.get(i.operationId)??null,s))}let l=await w.update(i=>{h(i);let s=i.operationCommand&&I.get(i.operationCommand.operationId);return{...i,...s&&(s.confirmedAt||s.merchantExecution||s.status!=="pending")?{operationCommand:void 0}:{},purchases:F(i).map(m=>({...m,terminal:m.terminal??$(I.get(m.operationId))}))}});return h(l),l}async function ee(e){P();let n=await W.request("funnels",e);return P(),n}async function ce(e,n){let t=Q(Ee,await ee({operation:"recover_purchase",runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:n.receiptId,operationId:n.operationId}}));if(ne(e,t),t.purchase.receiptId!==n.receiptId||t.purchase.operation?.operationId!==n.operationId)throw new c("INVALID_RESPONSE","Original purchase reference changed");return X(t.purchase),I.get(n.operationId)}async function le(e){for(let n of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!n)continue;let t=Q(Re,await ee({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:n.requestId,...n.operation==="resume"?{}:{command:n}}));if(ne(e,t),t.settlement.requestId!==n.requestId)throw new c("INVALID_RESPONSE","Original command settlement changed");t.purchase&&X(t.purchase);let u=await w.update(l=>{h(l);let i=F(l),{receiptId:s,operationId:m}=t.settlement;if(s&&m){let x=i.find(S=>S.operationId===m);if(x&&x.receiptId!==s)throw new c("INVALID_RESPONSE","Original Receipt changed");x||i.push({receiptId:s,operationId:m,terminal:$(I.get(m))})}let f=t.settlement.state==="settled"?ge(l.journal.entry,n.requestId):l.journal.entry;return{...l,purchases:i,journal:f===l.journal.entry?l.journal:{revision:l.journal.revision+1,entry:f}}});h(u),e=u}return e}function ne(e,n){if(n.customerId!==E||n.scope.projectId!==d.scope.projectId||n.scope.environment!==d.scope.environment||n.target.funnelId!==e.start.funnelId||n.target.startRequestId!==e.start.requestId||e.run&&(n.target.runId!==e.run.id||n.target.versionId!==e.run.versionId))throw new c("SCOPE_MISMATCH","The original recovery binding changed")}async function te(e,n){if(h(e),e.run&&(e=await le(e)),!F(e).length&&M(e))return C(_(e,"operation"));if(!F(e).length)return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(n)});v=!0;let t=await Z(e);return C(_(t,"operation"))}async function V(e,n=!1,t=!0){if(R=e.start.requestId,b=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!a){let u=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:n?"resume":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},l;try{l=await ee(u)}catch(f){if(!e.run&&f instanceof c&&(f.status===void 0||f.status>=500))return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:O.purchases,error:L(f)});throw f}let i=Q(Ce,l);if(i.customerId!==E||i.scope.projectId!==d.scope.projectId||i.scope.environment!==d.scope.environment)throw new c("SCOPE_MISMATCH","Recovery Customer or environment changed");if(i.outcome==="unknown")return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:O.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});ne(e,i);let s=await w.update(f=>(h(f),{...f,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??f.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(h(s),e=s,i.access.type==="operation_only")return te(e,new c("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await le(e);let m=i.view;if(m.locale!==e.start.locale||!Se(m.parameters,e.start.parameters))throw new c("INVALID_RESPONSE","The original Start input changed");a=Pe({...d,customerRun:{runId:i.target.runId,customerId:E,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(f=>d.executionPolicy.allowed.includes(f))},funnelCommandStorage:_e(),onAcceptedResponse:qe},{scope:i.scope,run:m})}try{await a.get(),a.view?.pendingRequest?.requestId===e.start.requestId&&!a.pendingCommands?.length&&await a.resume(a.view.pendingRequest.requestId);for(let l of a.pendingCommands??[])l.operation!=="close"&&await a.settle?.(l.requestId);a.pendingCommands?.length&&await a.retry(),P();let u=(await w.read()).entry;return h(u),C(_(u,"run"))}catch(u){if(P(),t&&u instanceof c&&(u.status===401||u.status===409&&u.reason==="STATE_CHANGED")){a.reset(),a=null;let l=(await w.read()).entry;return h(l),V(l,!1,!1)}throw u}}function A(e,n="read"){if(P(),q)return n==="read"||n===U?q:q.then(()=>A(e,n),()=>A(e,n));clearTimeout(D);let t=e().catch(u=>{throw y||C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:O.purchases,error:L(u)}),u});return q=t,U=n,t.then(()=>{q===t&&(q=void 0,U=void 0)},()=>{q===t&&(q=void 0,U=void 0)}),t}function T(){return A(async()=>{let{entry:e}=await w.read();return e?(R&&e.start.requestId!==R&&(a?.reset(),a=null,I.clear(),j.clear()),v&&R===e.start.requestId?te(e,O.error):V(e)):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}async function de(){let e=await T();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:A(async()=>{let n=(await w.read()).entry;if(h(n),!v){if(!a?.view?.paywall?.quote)throw new c("PURCHASE_PENDING","Read the original quote before confirming");let s=a.view.paywall.operation;if(s?.confirmedAt||s?.merchantExecution||s&&s.status!=="pending")return C(_(n,"run"));if(a.pendingCommands?.length)await a.retry();else{let f=a.view;await a.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:f.nodeId,visit:f.visit,revision:f.revision,input:{type:"paywall_confirm",operationId:f.paywall.quote.operationId}})}let m=(await w.read()).entry;return h(m),C(_(m,"run"))}let t=n.operationCommand?.operationId??O.confirmation?.operationId,u=t&&I.get(t);if(!t||!u||n.journal.entry?.command||n.journal.entry?.closeCommand)throw new c("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");z({allowed:n.allowed.filter(s=>d.executionPolicy.allowed.includes(s))},u.quote),await w.update(s=>{if(h(s),s.journal.entry?.command||s.journal.entry?.closeCommand||s.operationCommand&&s.operationCommand.operationId!==t)throw new c("PURCHASE_PENDING","Another original command is pending");return{...s,operationCommand:{operationId:t,intent:"confirm"}}});let l=await se.attach({operationId:t,intent:"confirm"});if(P(),l.operation.operationId!==t)throw new c("INVALID_RESPONSE","Original confirmation Operation changed");I.set(t,J(u,l.operation));let i=(await w.read()).entry;return h(i),C(_(await Z(i,!1,new Set([t])),"operation"))},"confirm")}return{get controller(){return a},get recovery(){return structuredClone(O)},get attempt(){return P(),structuredClone(b)},get identitySignal(){return ie.signal},start(e){let n=N.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(n.operation!=="start"||n.customer||n.customerData)throw new c("INVALID_REQUEST","A Customer-owned Funnel start is required");return A(async()=>{let t=await w.update(u=>{if(u&&!M(u)){if(u.start.funnelId!==n.funnelId)throw new c("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return u}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:E,sessionId:Y,start:n,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!t)throw new c("PURCHASE_STORAGE_INVALID","Original start was not retained");return R!==t.start.requestId&&(a?.reset(),a=null,I.clear(),j.clear(),v=!1),v?te(t,O.error):V(t,!0)},`start:${n.funnelId}`)},refresh:T,confirm:de,retry:()=>v?de():A(async()=>{let{entry:e}=await w.read();return e?V(e,!0):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return a?.view?A(async()=>{if(!a?.view)throw new c("PURCHASE_PENDING","Recover the original Run before closing");if(a.pendingCommands?.find(t=>t.operation==="close"))await a.retry();else if(["running","waiting"].includes(a.view.status)){let t=a.view;await a.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision})}let n=(await w.read()).entry;return h(n),C(_(n,"run"))},"close"):T()},async continueCheckout(e){let n=await T();P(),await e(Te(n))},subscribe(e){return H.add(e),()=>{H.delete(e)}},destroy:ue}}export{be as a,Te as b,pn as c};
|
|
1
|
+
import{b as Ie}from"./chunk-3FPYCF7Z.js";import{a as Q}from"./chunk-ECMWY3G2.js";import{A as Se,E as z,G as Pe,d as pe,f as k,k as me,v as we,w as ge,y as ye}from"./chunk-UHI7SPHK.js";import{$ as N}from"./chunk-PMCGTXGH.js";import{a as B,i as J}from"./chunk-PWQ5BHBJ.js";import{b as he}from"./chunk-MWDR5FEU.js";import{a as c}from"./chunk-X7G7JMZ3.js";import{h as G}from"./chunk-JAKOBECD.js";import{b as fe}from"./chunk-SMIO7OG5.js";import{b as r}from"./chunk-WM27UTWT.js";import{a as oe}from"./chunk-DSPLGTQI.js";var g=N.options,Ae=r.discriminatedUnion("operation",[g[1].omit({customerToken:!0}),g[2].omit({customerToken:!0}),g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0}),g[8].omit({customerToken:!0}),me.omit({customerToken:!0})]),je=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),Me=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume"]),start:r.strictObject({requestId:g[0].shape.requestId,funnelId:g[0].shape.funnelId,locale:g[0].shape.locale,parameters:g[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:je}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0})]).optional()}).refine(o=>!o.command||o.requestId===o.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:Ae})]),ae=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:k.shape.run.shape.status}),K={scope:G,customerId:r.uuid()},Ce=r.discriminatedUnion("outcome",[r.strictObject({...K,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...K,outcome:r.literal("resolved"),target:ae,view:k.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((o,d)=>{o.outcome==="resolved"&&(o.access.type==="customer"!=(o.view!==null)||o.view&&(o.view.id!==o.target.runId||o.view.source.id!==o.target.funnelId||o.view.source.versionId!==o.target.versionId||o.view.status!==o.target.status||o.view.runExpiresAt!==o.target.runExpiresAt||o.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Re=r.strictObject({...K,target:ae,view:k.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:k.shape.purchase.unwrap().nullable()}).superRefine((o,d)=>{let p=o.settlement;(p.acceptance==="accepted"!=(p.receiptPhase!==null)||p.acceptance==="accepted"&&p.basis!=="receipt"||p.acceptance==="unknown"&&(p.state!=="unknown"||p.basis!=="none")||p.acceptance!=="accepted"&&(p.operationId!==null||p.receiptId!==null)||p.acceptance==="not_accepted"&&(p.state!=="settled"||!["run_terminal","position_advanced"].includes(p.basis))||o.purchase&&(o.purchase.receiptId!==p.receiptId||o.purchase.operation&&o.purchase.operation.operationId!==p.operationId||o.purchase.quote&&o.purchase.quote.operationId!==p.operationId)||o.view&&(o.view.id!==o.target.runId||o.view.source.id!==o.target.funnelId||o.view.source.versionId!==o.target.versionId||o.view.status!==o.target.status||o.view.runExpiresAt!==o.target.runExpiresAt||o.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ee=r.strictObject({...K,target:ae,purchase:k.shape.purchase.unwrap()}).superRefine((o,d)=>{(!o.purchase.operation||typeof o.purchase.canReselect!="boolean"||o.purchase.quote&&o.purchase.quote.operationId!==o.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})});var Ne=N.options[0].refine(o=>!o.customer&&!o.customerData),ke=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),ve=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:G,customerId:r.uuid(),sessionId:r.uuid(),start:Ne,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:pe.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ke).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:we.nullable()})});function be(o){return ye({...o,namespace:"purchases",identity:[o.scope.projectId,o.scope.environment,o.customerId]})}function Oe(o){let d=new URL(o.baseUrl??fe).href,p=()=>new c("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function E(){o.assertCurrent();try{let y=await o.storage.read();if(o.assertCurrent(),!Number.isSafeInteger(y.revision)||y.revision<0)throw p();let a=y.entry===null?null:ve.parse(y.entry);if(a&&(a.baseUrl!==d||a.customerId!==o.customerId||a.scope.projectId!==o.scope.projectId||a.scope.environment!==o.scope.environment))throw new c("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(a?.journal.entry&&(a.journal.entry.scope.projectId!==a.scope.projectId||a.journal.entry.scope.environment!==a.scope.environment||a.journal.entry.funnelId!==a.start.funnelId||a.journal.entry.runId!==a.run?.id||a.journal.entry.versionId!==a.run?.versionId)||a?.operationCommand&&!a.purchases.some(R=>R.operationId===a.operationCommand?.operationId))throw p();return{revision:y.revision,entry:a}}catch(y){throw y instanceof c?y:p()}}async function Y(y){for(let a=0;a<8;a++){let R=await E(),b=y(structuredClone(R.entry));if(JSON.stringify(b)===JSON.stringify(R.entry))return b;b&&ve.parse(b),o.assertCurrent();let v;try{v=await o.storage.write(R.revision,b)}catch{throw p()}if(o.assertCurrent(),v!==null){if(!Number.isSafeInteger(v)||v<=R.revision)throw p();return b}}throw new c("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:E,update:Y,baseUrl:d}}function Te(o){let d=o.purchases.find(p=>p.type==="checkout");if(!o.actions.includes("continue_checkout")||d?.type!=="checkout")throw new c("PURCHASE_PENDING","No single resumable Checkout is confirmed");return d.checkoutUrl}function pn(o){let d={...o,scope:{...o.scope},executionPolicy:structuredClone(o.executionPolicy)},p=d.session.snapshot();if(!p)throw new c("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:E,sessionId:Y}=p,y=!1,a=null,R,b=null,v=!1,q,U,D,O={mode:"idle",status:"idle",actions:["start"],purchases:[]},I=new Map,j=new Map,ie=new AbortController,H=new Set,W=he(d),se=Ie(W.request);function L(e){return{code:e instanceof c?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof c&&e.status!==void 0?{status:e.status}:{}}}function P(){if(y||d.session.snapshot()?.customerId!==E)throw new c("IDENTITY_CHANGED","The original purchase Customer changed")}let w=Oe({...d,customerId:E,assertCurrent:P,storage:d.storage??be({baseUrl:d.baseUrl,scope:d.scope,customerId:E})}),Fe=d.session.subscribeIdentity(ue);function ue(){y||(y=!0,clearTimeout(D),ie.abort(new c("IDENTITY_CHANGED","Purchase consumer was destroyed")),Fe(),a?.reset(),a=null,b=null,W.dispose(),H.clear(),I.clear(),j.clear())}function C(e){P();let n=JSON.stringify(e)!==JSON.stringify(O);O=e,clearTimeout(D),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(D=setTimeout(()=>{T().catch(()=>{})},5e3)),n&&oe(d.onRecovery,structuredClone(e));for(let t of n?H:[]){if(y)break;oe(t,structuredClone(e))}return structuredClone(e)}function h(e){if(P(),!e||e.start.requestId!==R)throw new c("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function F(e){let n=[...e.purchases],t=e.journal.entry?.purchase;return t&&!n.some(u=>u.operationId===t.operationId)&&n.push({receiptId:t.receiptId,operationId:t.operationId,terminal:null}),n}function M(e){return e.run&&!["running","waiting"].includes(e.run.status)&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&F(e).every(n=>n.terminal!==null)}function _(e,n){let t=e.journal.entry?.command??e.journal.entry?.closeCommand,u=F(e).map(S=>{let re=I.get(S.operationId);return S.terminal&&!re?{type:S.terminal,operationId:S.operationId}:B({quote:re?.quote??null,operation:re??null,requestId:t?.requestId??null,pending:!1,destroyed:!1,canReselect:j.get(S.operationId)===!0})}),l=u.filter(S=>!["complete","native"].includes(S.type)),i=l[0],s=l.length===1&&i?.operationId?I.get(i.operationId):void 0;if(s&&(i?.type==="checkout"||i?.type==="cancel"))try{z({allowed:e.allowed.filter(S=>d.executionPolicy.allowed.includes(S))},s.quote)}catch(S){return{mode:n,status:"blocked",actions:["refresh",...n==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:u,error:L(S)}}let m;if(n==="operation"&&!t&&i?.type==="cancel"&&s?.quote&&!s.problem&&!s.confirmedAt)try{z({allowed:e.allowed.filter(S=>d.executionPolicy.allowed.includes(S))},s.quote),Date.parse(s.quote.expiresAt)>Date.now()&&(m={operationId:s.operationId,quote:s.quote})}catch{}let f=u.length>0&&l.length===0,x=M(e)||n==="operation"&&f&&!t&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":t||e.operationCommand||i&&i.type!=="cancel"||n==="operation"&&!m?"waiting_result":"ready";return{mode:n,status:x,purchases:u,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...M(e)?["start"]:[],...n==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...l.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function $(e){let n=B({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&j.get(e.operationId)===!0});return n.type==="complete"||n.type==="native"?n.type:null}function X(e){if(!e.operation)return;let n={...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}};if(n.merchantExecution&&n.merchantExecution.customerId!==E)throw new c("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let t=J(I.get(n.operationId)??null,n);I.set(n.operationId,t),t===n&&j.set(n.operationId,e.canReselect===!0)}async function qe(e){P();for(let t of[e.purchase,e.run.paywall])t&&X(t);let n=await w.update(t=>{if(h(t),t.run&&(t.run.id!==e.run.id||t.run.versionId!==e.run.source.versionId))throw new c("SCOPE_MISMATCH","The original purchase Run changed");let u=F(t);for(let l of[e.purchase,e.run.paywall]){let i=l?.operation?.operationId??l?.quote?.operationId;if(!l||!i)continue;let s=u.find(f=>f.operationId===i);if(s&&s.receiptId!==l.receiptId)throw new c("INVALID_RESPONSE","The original purchase Receipt changed");let m=$(I.get(i));s?s.terminal??=m:u.push({receiptId:l.receiptId,operationId:i,terminal:m})}return{...t,purchases:u,run:t.run&&(t.run.revision>e.run.revision||!["running","waiting"].includes(t.run.status)&&["running","waiting"].includes(e.run.status))?t.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});h(n),n.run&&!["running","waiting"].includes(n.run.status)&&F(n).some(t=>!t.terminal)&&(n=await Z(n,!n.journal.entry?.command&&!n.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(t=>!!t)))),h(n),C(_(n,"run"))}function _e(){return{async read(){let{entry:e}=await w.read();return h(e),structuredClone(e.journal)},async write(e,n){let t=null;return await w.update(u=>{if(h(u),u.operationCommand&&n?.command&&n.command.operation!=="close")throw new c("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return t=null,u.journal.revision!==e?u:(t=e+1,{...u,journal:{revision:t,entry:n}})}),t}}}async function Z(e,n=!1,t=new Set){h(e);let u=F(e);for(let i of u){if(i.terminal)continue;let s=t.has(i.operationId)?I.get(i.operationId):void 0;if(s??=await ce(e,i),P(),s.operationId!==i.operationId)throw new c("INVALID_RESPONSE","Original Operation changed");if(s.merchantExecution&&s.merchantExecution.customerId!==E)throw new c("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(n&&!e.operationCommand&&B({quote:s.quote??null,operation:s,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){if({operation:s}=await se.attach({operationId:i.operationId,intent:"cancel"}),P(),s.operationId!==i.operationId)throw new c("INVALID_RESPONSE","Original cancellation Operation changed");s=await ce(e,i)}I.set(i.operationId,J(I.get(i.operationId)??null,s))}let l=await w.update(i=>{h(i);let s=i.operationCommand&&I.get(i.operationCommand.operationId);return{...i,...s&&(s.confirmedAt||s.merchantExecution||s.status!=="pending")?{operationCommand:void 0}:{},purchases:F(i).map(m=>({...m,terminal:m.terminal??$(I.get(m.operationId))}))}});return h(l),l}async function ee(e){P();let n=await W.request("funnels",e);return P(),n}async function ce(e,n){let t=Q(Ee,await ee({operation:"recover_purchase",runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:n.receiptId,operationId:n.operationId}}));if(ne(e,t),t.purchase.receiptId!==n.receiptId||t.purchase.operation?.operationId!==n.operationId)throw new c("INVALID_RESPONSE","Original purchase reference changed");return X(t.purchase),I.get(n.operationId)}async function le(e){for(let n of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!n)continue;let t=Q(Re,await ee({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:n.requestId,...n.operation==="resume"?{}:{command:n}}));if(ne(e,t),t.settlement.requestId!==n.requestId)throw new c("INVALID_RESPONSE","Original command settlement changed");t.purchase&&X(t.purchase);let u=await w.update(l=>{h(l);let i=F(l),{receiptId:s,operationId:m}=t.settlement;if(s&&m){let x=i.find(S=>S.operationId===m);if(x&&x.receiptId!==s)throw new c("INVALID_RESPONSE","Original Receipt changed");x||i.push({receiptId:s,operationId:m,terminal:$(I.get(m))})}let f=t.settlement.state==="settled"?ge(l.journal.entry,n.requestId):l.journal.entry;return{...l,purchases:i,journal:f===l.journal.entry?l.journal:{revision:l.journal.revision+1,entry:f}}});h(u),e=u}return e}function ne(e,n){if(n.customerId!==E||n.scope.projectId!==d.scope.projectId||n.scope.environment!==d.scope.environment||n.target.funnelId!==e.start.funnelId||n.target.startRequestId!==e.start.requestId||e.run&&(n.target.runId!==e.run.id||n.target.versionId!==e.run.versionId))throw new c("SCOPE_MISMATCH","The original recovery binding changed")}async function te(e,n){if(h(e),e.run&&(e=await le(e)),!F(e).length&&M(e))return C(_(e,"operation"));if(!F(e).length)return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(n)});v=!0;let t=await Z(e);return C(_(t,"operation"))}async function V(e,n=!1,t=!0){if(R=e.start.requestId,b=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!a){let u=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:n?"resume":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},l;try{l=await ee(u)}catch(f){if(!e.run&&f instanceof c&&(f.status===void 0||f.status>=500))return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:O.purchases,error:L(f)});throw f}let i=Q(Ce,l);if(i.customerId!==E||i.scope.projectId!==d.scope.projectId||i.scope.environment!==d.scope.environment)throw new c("SCOPE_MISMATCH","Recovery Customer or environment changed");if(i.outcome==="unknown")return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:O.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});ne(e,i);let s=await w.update(f=>(h(f),{...f,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??f.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(h(s),e=s,i.access.type==="operation_only")return te(e,new c("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await le(e);let m=i.view;if(m.locale!==e.start.locale||!Se(m.parameters,e.start.parameters))throw new c("INVALID_RESPONSE","The original Start input changed");a=Pe({...d,customerRun:{runId:i.target.runId,customerId:E,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(f=>d.executionPolicy.allowed.includes(f))},funnelCommandStorage:_e(),onAcceptedResponse:qe},{scope:i.scope,run:m})}try{await a.get(),a.view?.pendingRequest?.requestId===e.start.requestId&&!a.pendingCommands?.length&&await a.resume(a.view.pendingRequest.requestId);for(let l of a.pendingCommands??[])l.operation!=="close"&&await a.settle?.(l.requestId);a.pendingCommands?.length&&await a.retry(),P();let u=(await w.read()).entry;return h(u),C(_(u,"run"))}catch(u){if(P(),t&&u instanceof c&&(u.status===401||u.status===409&&u.reason==="STATE_CHANGED")){a.reset(),a=null;let l=(await w.read()).entry;return h(l),V(l,!1,!1)}throw u}}function A(e,n="read"){if(P(),q)return n==="read"||n===U?q:q.then(()=>A(e,n),()=>A(e,n));clearTimeout(D);let t=e().catch(u=>{throw y||C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:O.purchases,error:L(u)}),u});return q=t,U=n,t.then(()=>{q===t&&(q=void 0,U=void 0)},()=>{q===t&&(q=void 0,U=void 0)}),t}function T(){return A(async()=>{let{entry:e}=await w.read();return e?(R&&e.start.requestId!==R&&(a?.reset(),a=null,I.clear(),j.clear()),v&&R===e.start.requestId?te(e,O.error):V(e)):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}async function de(){let e=await T();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:A(async()=>{let n=(await w.read()).entry;if(h(n),!v){if(!a?.view?.paywall?.quote)throw new c("PURCHASE_PENDING","Read the original quote before confirming");let s=a.view.paywall.operation;if(s?.confirmedAt||s?.merchantExecution||s&&s.status!=="pending")return C(_(n,"run"));if(a.pendingCommands?.length)await a.retry();else{let f=a.view;await a.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:f.nodeId,visit:f.visit,revision:f.revision,input:{type:"paywall_confirm",operationId:f.paywall.quote.operationId}})}let m=(await w.read()).entry;return h(m),C(_(m,"run"))}let t=n.operationCommand?.operationId??O.confirmation?.operationId,u=t&&I.get(t);if(!t||!u||n.journal.entry?.command||n.journal.entry?.closeCommand)throw new c("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");z({allowed:n.allowed.filter(s=>d.executionPolicy.allowed.includes(s))},u.quote),await w.update(s=>{if(h(s),s.journal.entry?.command||s.journal.entry?.closeCommand||s.operationCommand&&s.operationCommand.operationId!==t)throw new c("PURCHASE_PENDING","Another original command is pending");return{...s,operationCommand:{operationId:t,intent:"confirm"}}});let l=await se.attach({operationId:t,intent:"confirm"});if(P(),l.operation.operationId!==t)throw new c("INVALID_RESPONSE","Original confirmation Operation changed");I.set(t,J(u,l.operation));let i=(await w.read()).entry;return h(i),C(_(await Z(i,!1,new Set([t])),"operation"))},"confirm")}return{get controller(){return a},get recovery(){return structuredClone(O)},get attempt(){return P(),structuredClone(b)},get identitySignal(){return ie.signal},start(e){let n=N.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(n.operation!=="start"||n.customer||n.customerData)throw new c("INVALID_REQUEST","A Customer-owned Funnel start is required");return A(async()=>{let t=await w.update(u=>{if(u&&!M(u)){if(u.start.funnelId!==n.funnelId)throw new c("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return u}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:E,sessionId:Y,start:n,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!t)throw new c("PURCHASE_STORAGE_INVALID","Original start was not retained");return R!==t.start.requestId&&(a?.reset(),a=null,I.clear(),j.clear(),v=!1),v?te(t,O.error):V(t,!0)},`start:${n.funnelId}`)},refresh:T,confirm:de,retry:()=>v?de():A(async()=>{let{entry:e}=await w.read();return e?V(e,!0):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return a?.view?A(async()=>{if(!a?.view)throw new c("PURCHASE_PENDING","Recover the original Run before closing");if(a.pendingCommands?.find(t=>t.operation==="close"))await a.retry();else if(["running","waiting"].includes(a.view.status)){let t=a.view;await a.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision})}let n=(await w.read()).entry;return h(n),C(_(n,"run"))},"close"):T()},async continueCheckout(e){let n=await T();P(),await e(Te(n))},subscribe(e){return H.add(e),()=>{H.delete(e)}},destroy:ue}}export{be as a,Te as b,pn as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as d}from"./chunk-
|
|
1
|
+
import{b as d}from"./chunk-SMIO7OG5.js";import{a as u}from"./chunk-DSPLGTQI.js";function m(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let i of document.cookie.split(";"))if(i.trim().startsWith(`${e}=`))try{t=decodeURIComponent(i.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function y(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function g(e=d){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var o=new Set,s;function S(e){let t=()=>e();if(o.add(t),!s){let i=!0,a=history.pushState,p=history.replaceState,r=()=>{if(i)for(let n of[...o])o.has(n)&&u(n)},c=function(...n){a.apply(this,n),r()},h=function(...n){p.apply(this,n),r()};history.pushState=c,history.replaceState=h,addEventListener("popstate",r),addEventListener("hashchange",r),s=()=>{i=!1,history.pushState===c&&(history.pushState=a),history.replaceState===h&&(history.replaceState=p),removeEventListener("popstate",r),removeEventListener("hashchange",r)}}return()=>{o.delete(t)&&(o.size||(s?.(),s=void 0))}}export{m as a,y as b,g as c,S as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{s as g,t as w}from"./chunk-GIV4FOOW.js";import{n as I,s as h}from"./chunk-MYUYN7ZG.js";import{a as y}from"./chunk-
|
|
1
|
+
import{s as g,t as w}from"./chunk-GIV4FOOW.js";import{n as I,s as h}from"./chunk-MYUYN7ZG.js";import{a as y}from"./chunk-MWDR5FEU.js";import{a}from"./chunk-X7G7JMZ3.js";import{a as T}from"./chunk-3VUPVXAV.js";import{b as P}from"./chunk-SMIO7OG5.js";import{a as f}from"./chunk-WM27UTWT.js";function b(r,n,o){if(!["subscriptions/operations/read","subscriptions/updates/read","subscriptions/refunds/read"].includes(r))return;let e=n,c=o,s=c.operation;if(s.operationId!==e.operationId||[s.authority,s.merchantExecution].some(t=>t&&(t.operationId!==e.operationId||e.customerId!==void 0&&t.customerId!==e.customerId))||s.authority&&(s.authority.scope.projectId!==c.scope.projectId||s.authority.scope.environment!==c.scope.environment))throw new a("INVALID_RESPONSE","Original commerce operation changed")}function D(r){try{return structuredClone(r)}catch{return r}}async function q(r,n){let o=r.captureIdentity?.(),{apiOperations:e}=await import("./operation-contracts-VURXKAFX.js");return o?.(),e[n]}function E(r,n,o,e){try{return r.parse(n)}catch(c){throw e&&c instanceof f?new a(o,e):c}}async function x(r,n,o,e={},c){let s=typeof e=="function"?{}:e,t=E(n.request,o,"INVALID_REQUEST",s.request);try{let i=await r(n.path,t,n.method,c),u=typeof e=="function"?e:e.parseResponse,d=u?u(n.response,i):E(n.response,i,"INVALID_RESPONSE",s.response);return b(n.path,t,d),d}catch(i){throw i instanceof a&&t!==null&&typeof t=="object"&&"requestId"in t&&typeof t.requestId=="string"&&(i.commandRequestId??=t.requestId),i}}function O(r,n){let o=typeof r=="string"?new TextEncoder().encode(r):r;return o.byteLength===n.byteLength&&h(o)===n.sha256}async function F(r,n){let o=g.parse(n),{artifact:e,environmentId:c}=o.content,s=new y(r.baseUrl??P).origin,t=new y(e.url,s);if(t.origin!==s||t.username||t.password||t.search||t.hash||t.pathname!==`/api/v1/configuration/${c}/artifacts/${e.sha256}`)throw new a("INVALID_RESPONSE","Public Paywall locator is not trusted");let i=new AbortController,u,d=new Promise((p,l)=>{u=setTimeout(()=>{let m=new a("TIMEOUT","Public Paywall read timed out");i.abort(m),l(m)},I.initializationMs)}),R=(async()=>{let p=await(r.fetch??globalThis.fetch)(t,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:i.signal});if(i.signal.aborted&&(p.body?.cancel().catch(()=>{}),i.signal.throwIfAborted()),!p.ok||!p.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(p.headers.get("content-length"))>e.byteLength)throw p.body?.cancel().catch(()=>{}),new a("INVALID_RESPONSE","Public Paywall is unavailable");let l=await T(p,e.byteLength,{signal:i.signal,error:m=>new a("INVALID_RESPONSE",m==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!O(l,e))throw new a("INVALID_RESPONSE","Public Paywall digest or size changed");return w(o,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))})();try{return await Promise.race([R,d])}finally{clearTimeout(u)}}export{D as a,q as b,x as c,O as d,F as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as $,b as N,c as J,d as q}from"./chunk-
|
|
1
|
+
import{a as $,b as N,c as J,d as q}from"./chunk-DCIGO3NJ.js";import{a as P}from"./chunk-3VUPVXAV.js";import{a as D}from"./chunk-SMIO7OG5.js";import{a as _}from"./chunk-DSPLGTQI.js";import{b as C,c as O,e as j}from"./chunk-O4KXODTJ.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}/*!
|
|
2
2
|
Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
|
|
3
3
|
plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
|
|
4
4
|
*/function ue(e,t){let o,n;try{o=new URL(e),n=new URL(t)}catch{return t}return o.searchParams.forEach((r,s)=>{n.searchParams.has(s)||n.searchParams.set(s,r)}),n.toString()}function de(e,t){let o=navigator.userAgent,n=new URLSearchParams(t.search),r={};for(let s of["source","medium","campaign","term","content"]){let u=n.get(`utm_${s}`);u!==null&&(r[`utm${s[0].toUpperCase()}${s.slice(1)}`]=u)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(o)?"edge":/Chrome/.test(o)?"chrome":/Firefox/.test(o)?"firefox":/Safari/.test(o)?"safari":"unknown",deviceType:/Mobi/.test(o)?"mobile":"desktop",...r}}function le(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(n=>!!n&&!["namespace","status","url","groups"].some(r=>Object.hasOwn(n,r))&&(n.hashVersion===void 0||n.hashVersion===2)&&typeof n.key=="string"&&Array.isArray(n.variations)&&n.variations.length>=2&&n.variations.every(r=>!!r&&typeof r.urlRedirect=="string")&&(n.urlPatterns===void 0||Array.isArray(n.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function Te(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=J(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let o=e.fetch??globalThis.fetch.bind(globalThis),n=H(async(i,d)=>{let l=await o(i,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),r=e.log?(i,d)=>_(e.log,i,d):void 0,s=`${t}/api/v1/page-experiments/${e.environmentId}`,u=$(e.deviceIdCookie??"indiana_did"),p=N(),a=null,c={...e.attributes??{}},g="",f=!1,h=!1,m=0,y=0,b=new Map,S=F({endpoint:`${s}/events`,fetch:o,log:r,label:"Exposure"}),k=S.flush,E={trackedExperiments:new Set,log:r,onExperimentViewed:(i,d)=>{e.trackExposures===!1||a?.trackExposures===!1||S.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:u,...p?{sessionId:p}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:i.key,variationKey:d.key})}},z=()=>{E.url=location.href,E.attributes={...de(u,location),...c}};function W(i){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return i.variations.some(l=>{if(!l.urlRedirect)return!1;let v=new URL(l.urlRedirect);return v.protocol!==d.protocol||v.host!==d.host})}catch{return!0}}function X(i,d){let l=e.configuration?.snapshot?.generation,v=y,te=location.href;g=i;let re=e.navigate??(w=>location.replace(w)),ne=e.navigateDelay??(e.navigate?0:100),oe=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(w=>setTimeout(w,oe))]),new Promise(w=>setTimeout(w,ne))]).then(()=>{!f&&v===y&&location.href===te&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&re(i)})}function x(){if(!(!a||f||e.configuration&&!e.configuration.fresh)){z();for(let i of a.experiments){if(W(i)){r?.("Auto experiment blocked",{id:i.key});continue}let d;try{d=j(i,E)}catch(l){r?.("Skipping page experiment",{id:i.key,error:String(l)});continue}if(b.set(i.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=i.persistQueryString?ue(location.href,d.value.urlRedirect):d.value.urlRedirect;C(l,i.urlPatterns??[])?r?.("Skipping redirect because original URL matches redirect URL",{id:i.key}):l!==g&&X(l,k())}break}}}}let R="",Z=()=>{location.href!==R&&(y++,R=location.href,g="",x())},T,L;function ee(){T??=q(Z),addEventListener("pagehide",I)}let I=()=>{k()};async function A(){if(f)return!1;let i=++m,d;try{d=e.configuration?await e.configuration.pageExperiments():await n.read(s,V)}catch(v){if(f||i!==m)return!1;throw v}if(f||i!==m)return!1;let l=le(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return a?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),a=l,E.savedGroups=O(l.savedGroups),!0}function U(){f||(L??=e.configuration?.subscribe(()=>{!f&&e.configuration?.fresh&&A().then(i=>{i&&x()}).catch(i=>r?.("Page configuration unavailable",{error:String(i)}))}),ee(),R=location.href)}return{async start(){h||f||(h=!0,await A()&&(U(),x()))},async refresh(){await A()&&(y++,h&&U(),g="",x())},setAttributes(i){y++,g="",c={...i},x()},getResults(){return new Map(b)},get generation(){return a?.generation??null},destroy(){f||(f=!0,m++,n.destroy(),L?.(),T?.(),removeEventListener("pagehide",I),a=null,b.clear(),k())}}}export{be as a,H as b,F as c,ue as d,de as e,le as f,Te as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as T,b as se}from"./chunk-4CH6FLDU.js";import{b as re,h as ae,j as ce}from"./chunk-UNG42D7U.js";import{a as oe,b as j}from"./chunk-BZSKOOMM.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-LPDUK7HT.js";import{F as M,b as J}from"./chunk-WZLEYOWM.js";import{a as b,b as f,c as m}from"./chunk-6DBYFYEU.js";import{b as W,j as X}from"./chunk-MYUYN7ZG.js";import{E as $}from"./chunk-PMCGTXGH.js";import{b as ie}from"./chunk-NZSLDALU.js";import{a as U}from"./chunk-UBKD6VMS.js";import{a as s}from"./chunk-X7G7JMZ3.js";import{h as Q}from"./chunk-JAKOBECD.js";import{b as K}from"./chunk-WM27UTWT.js";import{a as z}from"./chunk-DSPLGTQI.js";var B=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-VURXKAFX.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-VURXKAFX.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:B(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-VURXKAFX.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:B(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=B(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:B(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:B(v.addressSeq)})),D=(await import("./operation-contracts-VURXKAFX.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(!U.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()){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(!U.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-3FPYCF7Z.js";import{b as re,h as ae,j as ce}from"./chunk-2MTTK3BT.js";import{a as oe,b as j}from"./chunk-BZSKOOMM.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-LPDUK7HT.js";import{F as M,b as J}from"./chunk-UHI7SPHK.js";import{a as b,b as f,c as m}from"./chunk-G7NSECIG.js";import{b as W,j as X}from"./chunk-MYUYN7ZG.js";import{E as $}from"./chunk-PMCGTXGH.js";import{b as ie}from"./chunk-MWDR5FEU.js";import{a as U}from"./chunk-UBKD6VMS.js";import{a as s}from"./chunk-X7G7JMZ3.js";import{h as Q}from"./chunk-JAKOBECD.js";import{b as K}from"./chunk-WM27UTWT.js";import{a as z}from"./chunk-DSPLGTQI.js";var B=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-VURXKAFX.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-VURXKAFX.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:B(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-VURXKAFX.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:B(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=B(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:B(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:B(v.addressSeq)})),D=(await import("./operation-contracts-VURXKAFX.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(!U.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()){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(!U.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};
|