@tinkerlandai/longplay-sdk 0.10.14 → 0.10.15-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/README.md +9 -3
- package/dist/{chunk-ZQUUDOHV.js → chunk-3AMIAUQS.js} +1 -1
- package/dist/chunk-45LYG6Q2.js +1 -0
- package/dist/{chunk-PNIWWTLM.js → chunk-47YGA2YM.js} +1 -1
- package/dist/{chunk-NR2M6SNG.js → chunk-6ZGY3XIB.js} +1 -1
- package/dist/{chunk-2ODPDLTX.js → chunk-C76COHTI.js} +1 -1
- package/dist/{chunk-KOGWARWA.js → chunk-DR66DI6C.js} +1 -1
- package/dist/{chunk-3WVMD3FK.js → chunk-GTBAZ3ED.js} +1 -1
- package/dist/{chunk-J42MHRU7.js → chunk-KJ4KKOMF.js} +1 -1
- package/dist/{chunk-WVQM23J4.js → chunk-QENTCFYZ.js} +1 -1
- package/dist/{chunk-D5D75HM6.js → chunk-RNL2AGFW.js} +1 -1
- package/dist/{content-M6BANOTZ.js → content-CGE5WH2Q.js} +1 -1
- package/dist/funnel-runtime-host-3I67GD6U.js +1 -0
- package/dist/index.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/page.js +1 -1
- package/dist/{paywall-D3QFOE5C.js → paywall-ZUYIIFL7.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-OEQ2QTPD.js +0 -1
- package/dist/funnel-runtime-host-HPHUWGIF.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.10.15 — 2026-11-04
|
|
4
|
+
|
|
5
|
+
- No API or behavior change from 0.10.14. This is the first release published through a release candidate (`0.10.15-rc.1` on npm `next`) before the stable version. The README describes the `next` and `latest` channels. Wire protocol stays `0.10`.
|
|
6
|
+
|
|
3
7
|
## 0.10.14 — 2026-11-03
|
|
4
8
|
|
|
5
9
|
- Send bundled native Paywall commands one at a time, so a host refresh while a store purchase is being observed no longer fails the Paywall after the purchase is paid; Swift and Kotlin hosts receive completion instead of `command_pending`. Wire protocol stays `0.10`.
|
package/README.md
CHANGED
|
@@ -96,7 +96,7 @@ The canonical repository policy, including production/test domain roles, package
|
|
|
96
96
|
|
|
97
97
|
Omitting `baseUrl` selects `https://api.longplayai.com`. This applies to Customer/Server, Funnel, Feature, Paywall, page and visual clients. `createConfigurationSync` also defaults its optional `origin` to that address. Swift `LongplayConfiguration(scope: ...)` and Kotlin `LongplayConfiguration(scope = ...)` uses the same default and shared release version. Explicit `baseURL` / `baseUrl` still overrides it. Funnel and Paywall shells and renderers are packaged locally; their executable code is not downloaded from that API origin.
|
|
98
98
|
|
|
99
|
-
|
|
99
|
+
Release candidates (`next`) and stable releases (`latest`) published with this default both use the production API address. Tags select package versions, not deployments. The separate test API at `https://api.dev.longplayai.com` requires its own credentials and a runtime serving the current protocol 0.10.
|
|
100
100
|
|
|
101
101
|
Use the same API origin for every client and configuration-sync instance in one integration. Sandbox/Live selects business scope inside that deployment, not a different service or database. Never retry against another service automatically after an error or unknown command result. Maintainer test runs require an explicit target and must not fall back to production; follow the [SDK testing guide](../../docs/sdk-selfserve.md#maintainer-api-origin-testing).
|
|
102
102
|
|
|
@@ -182,7 +182,10 @@ On the merchant backend, create `createFunnelProcessAdapter` from the `/server`
|
|
|
182
182
|
Expose the adapter's operation-specific calls through your backend. Keep Guest proofs, Customer sessions and the Server Key there. A shared `guestKey` reuses an eligible Guest across process handles; one `processKey` retains its original start, bind and recovery intents.
|
|
183
183
|
|
|
184
184
|
```ts
|
|
185
|
-
import {
|
|
185
|
+
import {
|
|
186
|
+
createConfigurationSync,
|
|
187
|
+
createFunnelProcess,
|
|
188
|
+
} from "@tinkerlandai/longplay-sdk";
|
|
186
189
|
|
|
187
190
|
const configuration = createConfigurationSync({
|
|
188
191
|
origin: baseUrl,
|
|
@@ -195,7 +198,10 @@ const process = createFunnelProcess({
|
|
|
195
198
|
onAuthenticationRequired: () => showMerchantSignIn(),
|
|
196
199
|
});
|
|
197
200
|
const { controller } = await process.open({
|
|
198
|
-
operation: "start",
|
|
201
|
+
operation: "start",
|
|
202
|
+
funnelId,
|
|
203
|
+
locale: "en",
|
|
204
|
+
parameters: {},
|
|
199
205
|
});
|
|
200
206
|
// After verified merchant login, retain this instance and controller.
|
|
201
207
|
await process.syncIdentity();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as u}from"./chunk-OZZMZH7X.js";import{pa as E,qa as M,ra as j,sa as O,ta as T}from"./chunk-
|
|
1
|
+
import{a as u}from"./chunk-OZZMZH7X.js";import{pa as E,qa as M,ra as j,sa as O,ta as T}from"./chunk-DR66DI6C.js";import{k as w}from"./chunk-VSJOHWDL.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as t}from"./chunk-47YGA2YM.js";import{Za as n}from"./chunk-DR66DI6C.js";function r(e,o,a){return n(e,o,a,t)}export{r as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as dn,c as fn,d as mn,e as pn}from"./chunk-VSMITXQD.js";import{a as te,b as Y}from"./chunk-D5D75HM6.js";import{a as m}from"./chunk-OZZMZH7X.js";import{a as ln,b as cn,c as Ce}from"./chunk-2ODPDLTX.js";import{$a as un,Ea as Te,Fa as tn,R as Ge,T as Re,Ta as rn,U as Be,Ua as on,V as je,W as Je,Xa as an,Ya as sn,a as Ue,cb as le,da as Q,ea as ze,fa as B,ga as Ke,ha as Oe,ia as L,ka as Qe,la as Ye,ma as $e,n as ue,na as We,oa as Ze,ua as ne,va as Xe,ya as en,za as nn}from"./chunk-KOGWARWA.js";import{B as ve,Ca as He,v as qe,y as ke}from"./chunk-VSJOHWDL.js";function Mn(e){let n=null,r=null,s=0,l=0,y=new Set,f=null,i=null,p=new Set,a=()=>{for(let o of p)try{o()}catch{}},u={attributes:ve.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(o,t)=>{!y.has(o)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(o,structuredClone(t),structuredClone(u.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(o,t)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(o),structuredClone(t),structuredClone(u.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?o=>e.saveStickyBucketAssignmentDoc(structuredClone(o)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},c=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function d(o,t=new Set){return y.has(o)?!f||!f.features[o]||["unknownFeature","cyclicPrerequisite"].includes(f.features[o].source):t.has(o)?!1:(t.add(o),(n?.features[o]?.rules??[]).some(I=>[...I.parentConditions??[],...(I.tracks??[]).flatMap(b=>b.experiment.parentConditions??[])].some(b=>d(b.id,t))))}let h=o=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return f?.expiresAt&&Date.parse(f.expiresAt)<=Date.now()&&(f=null,u.features=n.features),y.has(o)?!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now()?c():structuredClone(f.features[o]??c()):e.evaluateRemote&&(u.attributes?.merchandise||u.attributes?.merchandiseId)&&!f||d(o)?c():structuredClone(ke(o,u))};async function A(){if(!n||!y.size&&!u.attributes?.merchandise&&!u.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(y.size)throw new Error("Remote Feature evaluation requires a server loader");return}let o=l;if(i?.revision===o)return i.loading;let t=s,I=n,b=[...y],S=(async()=>{let P=Je.parse(await e.evaluateRemote({attributes:structuredClone(u.attributes),features:b}));if(!(t!==s||o!==l||I!==n)){if(e.assertUsable?.(I.generation),P.generation!==I.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(b.some(v=>!Object.hasOwn(P.features,v))||Object.keys(P.features).some(v=>!y.has(v)))throw new Error("Invalid remote Feature results");if(u.attributes?.merchandise||u.attributes?.merchandiseId){if(!P.merchandiseContext)throw new Error("Server did not resolve merchandise context");u.attributes=ve.parse({...u.attributes,...P.merchandiseContext})}f=structuredClone(P),u.features={...I.features,...Object.fromEntries(Object.entries(f.features).map(([v,D])=>[v,{defaultValue:D.value}]))},a()}})();i={revision:o,loading:S};try{await S}finally{i?.loading===S&&(i=null)}}function F(){A().catch(o=>{try{e.onError?.(o)}catch{}})}async function T(){if(r)return r;let o=s,t=(async()=>{let I=await e.load(),b="remoteFeatures"in I?Be.parse(I):null,S=b??Re.parse(I);if(S.scope.projectId!==e.scope.projectId||S.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(o!==s)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===S.generation){let{evaluatedAt:v,expiresAt:D,...V}=n,{evaluatedAt:M,expiresAt:H,...k}=S;if(L(V)!==L(k))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=S.evaluatedAt,n.expiresAt=S.expiresAt,a(),(!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now())&&F(),structuredClone(n)}let P=new Set(b?.remoteFeatures??[]);if([...P].some(v=>Object.hasOwn(S.features,v)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in S&&!n.analyticsConfig.experimentViewsEnabled&&b?.analyticsConfig.experimentViewsEnabled&&u.trackedExperiments?.clear(),n=structuredClone(S),y=P,f=null,i=null,l++,u.features=n.features,u.savedGroups=qe(n.savedGroups),u.trackedFeatureUsage={},a(),F(),structuredClone(n)})();r=t;try{return await t}finally{r===t&&(r=null)}}return{init:T,refresh:T,refreshRemote:A,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(o){return p.add(o),()=>{p.delete(o)}},setAttributes(o){let t=ve.parse(o);(u.attributes?.merchandise||u.attributes?.merchandiseId||o.merchandise||o.merchandiseId)&&u.trackedExperiments?.clear(),u.attributes=t,l++,f=null,i=null,u.features=n?.features??{},u.trackedFeatureUsage={},a(),F()},evalFeature:h,isOn(o){return h(o).on},isOff(o){return h(o).off},getFeatureValue(o,t){let I=h(o).value;return structuredClone(I===null?t:I)},reset(){s++,l++,r=null,i=null,n=null,f=null,y.clear(),u.features={},u.savedGroups={},u.stickyBucketAssignmentDocs={},u.attributes={},u.trackedFeatureUsage={},u.trackedExperiments?.clear(),a()}}}function gn(e){let n,r,s=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),l=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,r=e.locks??globalThis.navigator?.locks,!n||!r||!globalThis.crypto?.subtle)throw s();let i=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??le).href,e.runToken])),p=new Uint8Array(await crypto.subtle.digest("SHA-256",i));return"indiana.funnel.commands.v1."+Array.from(p,a=>a.toString(16).padStart(2,"0")).join("")});l.catch(()=>{});async function y(i){try{let p=await l;return await r.request(p,{mode:"exclusive"},()=>i(p))}catch(p){throw p instanceof m?p:s()}}function f(i){let p=n.getItem(i);if(p===null)return{revision:0,entry:null};if(p.length>1048576)throw s();let a=JSON.parse(p);if(!a||typeof a!="object"||!("revision"in a)||!("entry"in a)||!Number.isSafeInteger(a.revision)||Number(a.revision)<0)throw s();return{revision:Number(a.revision),entry:a.entry}}return{read:()=>y(f),write:(i,p)=>y(a=>{if(f(a).revision!==i)return null;if(!Number.isSafeInteger(i+1))throw s();return n.setItem(a,JSON.stringify({revision:i+1,entry:p})),i+1})}}function be(e,n){let r=en.safeParse(n);if(!r.success)throw new m("INVALID_RESPONSE","Funnel response contract changed");let s=r.data;if(e.scope&&(s.scope.projectId!==e.scope.projectId||s.scope.environment!==e.scope.environment))throw new m("SCOPE_MISMATCH","Funnel scope changed");return s}async function Pe(e,n){let r=We.parse(n),{artifact:s,environmentId:l}=r.content,y=new te(e.baseUrl??le).origin,f=new te(s.url,y);if(f.origin!==y||f.username||f.password||f.search||f.hash||f.pathname!==`/api/v1/configuration/${l}/artifacts/${s.sha256}`)throw new m("INVALID_RESPONSE","Public Paywall locator is not trusted");let i=new AbortController,p,a=new Promise((c,d)=>{p=setTimeout(()=>{let h=new m("TIMEOUT","Public Paywall read timed out");i.abort(h),d(h)},B.initializationMs)}),u=(async()=>{let c=await(e.fetch??globalThis.fetch)(f,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:i.signal});if(i.signal.aborted&&(c.body?.cancel().catch(()=>{}),i.signal.throwIfAborted()),!c.ok||!c.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(c.headers.get("content-length"))>s.byteLength)throw c.body?.cancel().catch(()=>{}),new m("INVALID_RESPONSE","Public Paywall is unavailable");let d=await ln(c,s.byteLength,{signal:i.signal,error:h=>new m("INVALID_RESPONSE",h==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Ce(d,s))throw new m("INVALID_RESPONSE","Public Paywall digest or size changed");return Ze(r,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d)))})();try{return await Promise.race([u,a])}finally{clearTimeout(p)}}var _e=(e,n)=>new m(e,n);function Xn(e){return sn(e,_e)}async function De(e,n,{predict:r=!0}={}){let s=n.instruction;if(s?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==s.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let l=null,y;if(r)try{let f=await e.funnel(n.source.id,n.source.versionId);y=f.manifest.generation,l=An(e,n,f)}catch{l=null}return y??=e.snapshot?.generation??(await e.refresh()).generation,{advance:{policyRevision:s.policyRevision,generation:y},prediction:l}}function An(e,n,r){let s=n.instruction;if(s?.type!=="evaluate_segment"||!r.growth||r.control.evaluationMode!=="local"||r.control.evaluationRevision!==s.policyRevision)return null;let{analyticsConfig:l,remoteFeatures:y,...f}=r.growth,i=rn({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:s.policyRevision,document:r.document,payload:Re.parse(f)}),p=Nn(i,r.document,{...n,...s}),a=p.steps.at(-1),u=p.boundary??(a?.result.port==="value"?{nodeId:a.nodeId,visit:n.visit+p.steps.length-1}:null);return u?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:u.nodeId,visit:u.visit,terminal:!p.boundary}:null}function Nn(e,n,r){return un(e,n,r,_e)}import{z as j}from"zod";var yn=Q.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),wn=j.strictObject({schemaVersion:j.literal(1),scope:Ue,runId:j.uuid(),funnelId:j.uuid(),versionId:j.uuid(),processBindingIds:j.record(j.uuid(),j.uuid().nullable()).optional(),command:yn.optional(),closeCommand:yn.refine(e=>e.operation==="close").optional(),purchase:j.strictObject({receiptId:j.uuid(),operationId:j.uuid(),generation:j.number().int().nonnegative()}).optional(),closed:j.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),q=()=>new m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Se=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function In(e){let n=0,r=null,s=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),l=Promise.resolve();async function y(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:wn.parse(a.entry)}}function f(a){let u=l.then(a);return l=u.catch(()=>{}),u}async function i(a){for(let u=0;u<4;u++){let c=await y();if(c.entry&&r!==null&&s(c.entry)!==r)throw q();let d=a(c.entry,c.revision);if(Se(c.entry,d)){n=c.revision;return}let h=await e.write(c.revision,d);if(h!==null){if(!Number.isSafeInteger(h)||h<=c.revision)throw q();n=h;return}}throw q()}function p(a,u){if(!a||!u)return a;if(a.processBindingIds&&Object.hasOwn(a.processBindingIds,u)){let c={...a.processBindingIds};delete c[u],a={...a,processBindingIds:c}}return a.command?.requestId===u?a.closeCommand?{...a,command:a.closeCommand,closeCommand:void 0}:a.purchase?{...a,command:void 0}:null:a.closeCommand?.requestId===u?{...a,closeCommand:void 0}:a}return{bind(a){let u=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(r!==null&&r!==u)throw q();r=u},async load(){let a=await y();return n=a.revision,r=a.entry?s(a.entry):null,a.entry},retain(a){let u=wn.parse(a),c=u.command;return!c||r!==null&&s(u)!==r?Promise.reject(q()):(r??=s(u),f(()=>i((d,h)=>{if(d&&!Se(s(d),s(u)))throw q();if(d&&u.processBindingIds){for(let[A,F]of Object.entries(u.processBindingIds))if(d.processBindingIds&&Object.hasOwn(d.processBindingIds,A)&&d.processBindingIds[A]!==F)throw q();d={...d,processBindingIds:{...d.processBindingIds,...u.processBindingIds}}}if(!d){if(h!==n&&c.operation!=="close")throw q();return u}if(!d.command)return{...d,command:c,...c.operation==="close"?{closed:!0}:{}};if(c.operation==="close"&&d.command.operation!=="close"){if(d.command.requestId===c.requestId||d.closeCommand&&!Se(d.closeCommand,c))throw q();return{...d,closeCommand:c,closed:!0}}if(!Se(d.command,c))throw q();return d})))},observePurchase(a,u,c,d){return f(()=>i((h,A)=>{if(!h&&A!==n||h&&s(h)!==s({...a,schemaVersion:1}))throw q();if(h?.purchase&&h.purchase.generation>u.generation)return p(h,d);if(h?.purchase&&h.purchase.generation===u.generation&&h.purchase.operationId!==u.operationId)throw q();return c?!h?.purchase||h.purchase.operationId!==u.operationId?p(h,d):p(h.command?{...h,purchase:void 0}:null,d):p({schemaVersion:1,...a,...h,purchase:u},d)}))},settle(a){return f(()=>i(u=>p(u,a)))}}}function lt(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function ce(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((l,y)=>ce(l,n[y]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let r=Object.entries(e),s=Object.entries(n);return r.length===s.length&&r.every(([l,y])=>Object.hasOwn(n,l)&&ce(y,Reflect.get(n,l)))}function hn(e,n){let r=n&&{...n},s=null,l=0,y=new AbortController;function f(){l++,y.abort(new m("IDENTITY_CHANGED","Run identity changed")),y=new AbortController}let i=!1,p,a=0,u=new Set;return{get scope(){return r},bindScope(c){if(r&&(r.projectId!==c.projectId||r.environment!==c.environment))throw new m("SCOPE_MISMATCH","Run scope changed");r??={...c}},get view(){return s},get generation(){return l},get signal(){return y.signal},get disposed(){return i},get customerToken(){return p},get readSequence(){return a},nextRead(){return++a},assertCurrent(c,d="Run identity changed during the request"){if(c!==l||i)throw new m("IDENTITY_CHANGED",d)},assertRun(c){if(s&&(c.id!==s.id||c.source.type!==s.source.type||c.source.id!==s.source.id||c.source.versionId!==s.source.versionId||c.locale!==s.locale||!ce(c.parameters,s.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&c.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(c,d,h,A,F){if(!(c.operation==="review"&&s&&s!==h&&d.run.revision<=s.revision)&&!(s&&d.run.revision===s.revision&&A!==void 0&&A<a)&&(c.operation==="review"&&!d.run.stopped&&["running","waiting"].includes(d.run.status)&&s&&d.run.nodeId===s.nodeId&&d.run.visit===s.visit&&d.run.revision===s.revision&&(d.run.screen=s.screen,(s.paywall?.quote?.operationId===d.review?.activeOperationId||!s.paywall?.quote&&d.review?.activeOperationId===null)&&(d.run.paywall=s.paywall)),!(s?.paywall&&d.run.paywall&&s.paywall.receiptId===d.run.paywall.receiptId&&(d.run.paywall.selectionGeneration??0)<(s.paywall.selectionGeneration??0)))){if(!s||d.run.revision>=s.revision)s=d.run;else if(!F)return;if(s)for(let T of u)try{T(structuredClone(s))}catch{}}},identify(c){if(i)throw new m("IDENTITY_CHANGED","Controller was reset");if(!ue.test(c))throw new m("INVALID_TOKEN","Customer credential required");f(),p=c},subscribe(c){return u.add(c),()=>u.delete(c)},reset(){i||(i=!0,f(),p=void 0,s=null,u.clear())}}}var re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function yt(e,n,r="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",n);if(!re.test(e))throw new m("INVALID_TOKEN",r)}function wt(e){let n=Y(e);return n.identify(e.apiKey),n}function $(e){let{customerToken:n,...r}=e;return r}var On=e=>!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function vn({journal:e,state:n,call:r,processIdentity:s}){let l=null,y=null,f=!1,i={command:null,close:null},p=new Set,a,u=null,c=e?e.load().then(o=>{if(n.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(u=o,!o)return;if(s){if([o.command,o.closeCommand].some(I=>I&&!Object.hasOwn(o.processBindingIds??{},I.requestId)))throw new m("COMMAND_STORAGE_INVALID","The original process identity is missing");s.restore(o.processBindingIds??{})}if(n.scope&&(o.scope.projectId!==n.scope.projectId||o.scope.environment!==n.scope.environment))throw new m("SCOPE_MISMATCH","Pending command belongs to another scope");if(a=o.purchase,f=o.closed===!0,!o.command)return;let t=o.command;l=t.operation==="close"?null:t,y=t.operation==="close"?t:o.closeCommand?.operation==="close"?o.closeCommand:null,y&&(f=!0);for(let I of[l,y])I&&p.add(I.requestId)}):Promise.resolve();c.catch(()=>{});async function d(o){e&&await c;let t=n.generation;if(e){if(!n.view||!n.scope)throw new m("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:n.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:$(o),...s?{processBindingIds:{[o.requestId]:s.binding(o.requestId)}}:{}})}if(t!==n.generation||l!==o&&y!==o)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let I=p.has(o.requestId);p.add(o.requestId);try{return await r(o)}catch(b){throw t===n.generation&&(l===o||y===o)&&!I&&!On(b)&&(e&&await e.settle(o.requestId),t===n.generation&&T(o)),b}}function h(o){let t=Q.parse(o);if(t.operation==="start"||t.operation==="get"||t.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(f&&t.operation!=="close"){if(l?.requestId===t.requestId)return F(t.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(t.operation==="close"){if(l?.requestId===t.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(f=!0,y&&JSON.stringify($(y))!==JSON.stringify($(t)))throw new m("COMMAND_PENDING","Retry the original Close");return y??=t,i.close?i.close:A(y,"close")}if(l){if(JSON.stringify($(l))!==JSON.stringify($(t)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(i.command)return i.command}else l=t;return A(l,"command")}function A(o,t){let I=d(o);i[t]=I;let b=()=>{i[t]===I&&(i[t]=null)};return I.then(b,b),I}function F(o){return r({operation:"get",settlementRequestId:o})}function T(o){return!o||l!==o&&y!==o?!1:(l===o&&(l=null),y===o&&(y=null),p.delete(o.requestId),!l&&!y&&(u=null),!0)}return{ready:c,get pending(){return l},get closing(){return y},get closeRequested(){return f},get inFlight(){return i.command},get closeFlight(){return i.close},get purchase(){return a},assertBinding(o){if(u&&(o.run.id!==u.runId||o.run.source.id!==u.funnelId||o.run.source.versionId!==u.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(o,t,I,b){let S=o.operation==="get"?o.settlementRequestId:"requestId"in o&&o.operation!=="start"?o.requestId:void 0,P=S&&t.settlement?.state==="settled"&&t.run.pendingRequest?.requestId!==S&&(o.operation==="get"||!f||o.operation==="close"||!["running","waiting"].includes(t.run.status))?S:void 0,v=l?.requestId===P?l:y?.requestId===P?y:void 0;e?.bind({scope:t.scope,runId:t.run.id,funnelId:t.run.source.id,versionId:t.run.source.versionId});let D=t.run.paywall,V=D??t.purchase,M=V?.operation,H=t.settlement&&(!D||D.purchaseRequestId===t.settlement.requestId)&&(!a||a.operationId===t.settlement.operationId)?t.settlement:void 0,k=M?.operationId??V?.quote?.operationId??H?.operationId,J=V?.receiptId??H?.receiptId,de=D?.selectionGeneration??a?.generation??0;if(e&&k&&J&&o.operation!=="review"&&(!n.view||t.run.revision>=n.view.revision)&&(b===void 0||b>=n.readSequence)&&(!a||de>=a.generation)){let Z={receiptId:J,operationId:k,generation:de},fe=M?.status==="complete"||V?.canReselect===!0;await e.observePurchase({scope:t.scope,runId:t.run.id,funnelId:t.run.source.id,versionId:t.run.source.versionId},Z,fe,P),n.assertCurrent(I),(!a||Z.generation>=a.generation)&&(b===void 0||b>=n.readSequence)&&(fe?a?.operationId===Z.operationId&&(a=void 0):a=Z)}else e&&P&&await e.settle(P);return n.assertCurrent(I),P?T(v):!1},stop(){f=!0},submit:h,settle:F,reset(){f=!0,l=null,y=null,a=void 0,u=null,i.close=null,p.clear(),i.command=null}}}function Rn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new m("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!re.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let n=Y({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),r=hn(e.funnelId,e.scope??e.configuration?.scope),s=e.session?.subscribeIdentity(a),l=null,y=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?gn(e):void 0),f=y&&In(y),i=vn({journal:f,state:r,call:u,processIdentity:e.process});async function p(t){if(e.process)return e.process.request(t);let I=r.generation;r.assertCurrent(I);let b=performance.now()+(e.timeoutMs??35e3),S=r.customerToken??("customerToken"in t?t.customerToken:void 0);if(e.session){let D=r.signal,V,M=()=>{},H=new Promise((k,J)=>{M=()=>J(D.reason),D.addEventListener("abort",M,{once:!0}),V=setTimeout(()=>J(new m("TIMEOUT","Longplay request timed out")),Math.max(1,b-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(r.assertCurrent(I),e.session.access())),H])}finally{clearTimeout(V),D.removeEventListener("abort",M)}}r.assertCurrent(I);let P={...t,...S?{customerToken:S}:{}},v=t.operation==="page_experiments"?Te.parse(P):Q.parse(P);return n.requestWithCredential("funnels",v,e.runToken,{headers:e.serverKey&&!S?{[nn]:e.serverKey}:void 0,timeoutMs:Math.max(1,b-performance.now())})}function a(){s?.(),r.reset(),i.reset(),l=null,n.dispose()}async function u(t,I){let b=r.generation,S=()=>r.assertCurrent(b);f&&await i.ready,S();let P=r.view,v=be(e,await p(t));if(t.operation==="review"&&!v.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(S(),v.runToken&&v.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let D=t.operation==="get"?t.settlementRequestId:"requestId"in t&&t.operation!=="start"?t.requestId:void 0;if(D&&v.settlement?.requestId!==D)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");i.assertBinding(v),r.assertRun(v.run),r.bindScope(v.scope);let V=await i.observe(t,v,b,I);return!v.run.stopped&&["running","waiting"].includes(v.run.status)&&t.operation==="get"&&t.settlementRequestId||(S(),["running","waiting"].includes(v.run.status)||i.stop(),r.publish(t,v,P,I,V)),v}let c=i.submit,d=null,h=new WeakMap;function A(t){let I=h.get(t);if(I)return I;let b=T(t);return h.set(t,b),b}let F=!1;async function T(t){let I=await t;if(I.run.instruction?.type!=="evaluate_segment")return I;if(d)return d;F=!0;let b=r.generation,S=(async()=>{for(let P=0;P<32&&I.run.instruction?.type==="evaluate_segment";P++){if(i.pending||i.closeRequested)return I;let v=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:V}=await De(e.configuration,v,{predict:!1});if(b!==r.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(i.pending||i.closeRequested)return I;if(r.view&&(r.view.revision!==v.revision||r.view.visit!==v.visit||r.view.nodeId!==v.nodeId))return u({operation:"get"});let M=!0;De(e.configuration,v).then(({prediction:H})=>{M&&b===r.generation&&!i.closeRequested&&r.view?.id===v.id&&!r.view.stopped&&r.view.nodeId===v.nodeId&&r.view.visit===v.visit&&r.view.revision===v.revision&&(l=H)}).catch(()=>{});try{I=await c({operation:"commit_segment",requestId:Xe(v.id,v.visit,`segment:${v.revision}`),nodeId:v.nodeId,visit:v.visit,revision:v.revision,...V})}finally{M=!1,l=null}}}return I})();d=S;try{return await S}finally{d===S&&(d=null)}}let o={get configuration(){return F?e.configuration:void 0},get configurationReady(){return!0},get view(){return r.view?structuredClone(r.view):null},get pendingCommand(){let t=i.closing??i.pending;return t?structuredClone($(t)):null},get pendingCommands(){return[i.pending,i.closing].filter(t=>t!==null).map(t=>structuredClone($(t)))},get pendingPurchase(){return i.purchase?structuredClone(i.purchase):null},get prediction(){let t=r.view;return l&&t&&!t.stopped&&["running","waiting"].includes(t.status)&&t.id===l.runId&&t.nodeId===l.from.nodeId&&t.visit===l.from.visit&&t.revision===l.from.revision&&!i.closeRequested?structuredClone(l):null},settle:i.settle,get webViewUrl(){return"bundled"},resolvePaywall(t){return Pe(e,t)},async pageExperiments(t,I=[]){let b=r.generation;r.assertCurrent(b);let S=r.view?.id;if(!S)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let P=tn.parse(await p(Te.parse({operation:"page_experiments",release:t,usedReceiptIds:I})));if(r.assertCurrent(b),P.runId!==S||P.scope.projectId!==r.scope?.projectId||P.scope.environment!==r.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return P},review(t){return u({operation:"review",...t?{receiptId:t}:{}},r.nextRead())},async get(t,I){f&&await i.ready,I??=i.purchase&&{receiptId:i.purchase.receiptId,operationId:i.purchase.operationId};let b=r.nextRead();return A(u({operation:"get",...t?{data:t}:{},...I?{purchase:I}:{}},b))},resume(t=r.view?.pendingRequest?.requestId){return t?i.closeRequested?o.settle(t):i.pending?.requestId===t?A(c(i.pending)):A(c({operation:"resume",requestId:t})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(t){return A(c(t))},retry(){return i.closeFlight?i.closeFlight:i.closing?c(i.closing):i.closeRequested&&i.pending?o.settle(i.pending.requestId):i.inFlight?A(i.inFlight):i.pending?A(c(i.pending)):Promise.reject(new m("INVALID_REQUEST","No command is pending"))},identify(t){r.identify(t),l=null,n.reset()},subscribe:r.subscribe,reset:a};return o}import{ZodError as Tn}from"zod";function Cn(e,n,r,s){try{return e.parse(n)}catch(l){throw s&&l instanceof Tn?new m(r,s):l}}async function Ee(e,n,r,s={},l){let y=typeof s=="function"?{}:s,f=Cn(n.request,r,"INVALID_REQUEST",y.request);try{let i=await e(n.path,f,n.method,l),p=typeof s=="function"?s:s.parseResponse;return p?p(n.response,i):Cn(n.response,i,"INVALID_RESPONSE",y.response)}catch(i){throw i instanceof m&&f!==null&&typeof f=="object"&&"requestId"in f&&typeof f.requestId=="string"&&(i.commandRequestId??=f.requestId),i}}async function jt(e,n){if(!ue.test(n.customerToken))throw new m("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==n.customerToken)throw new m("SCOPE_MISMATCH","Paywall credential does not match the shared session");let r=ne.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),s=Y(e);e.session||s.identify(n.customerToken);let l=null,y=!1,f=null,i=null,p=null,a=null;function u(){if(y)throw new m("IDENTITY_CHANGED","Paywall is closed")}async function c(){u();let F=ne.resolvePaywall,T=await Ee(s.request,F,{...r,selector:l?{type:"version",versionId:l.id}:r.selector}),o=await Pe(e,T.paywall);if(u(),n.paywallVersionId?o.id!==n.paywallVersionId:o.paywallId!==n.paywallId)throw new m("INVALID_RESPONSE","The requested Paywall changed");if(l&&(!dn(o,l)||o.paywallId!==l.paywallId))throw new m("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return l=o,structuredClone(l)}async function d(F){if(u(),a&&F!=="read")throw new m("COMMAND_PENDING","Wait for the original quote");if(!f)throw new m("INVALID_REQUEST","A quoted purchase is required");let T=f,o=F==="read"?ne.readSubscriptionOperation:ne.attach,t=await Ee(s.request,o,{operationId:T.operationId,...F==="read"?{}:{intent:F}});return fn(t.operation,{operationId:T.operationId,currency:r.commerce.currency},"The purchase operation changed"),u(),f?.operationId!==T.operationId?structuredClone(t.operation):(i=pn(i,t.operation),structuredClone(i))}let h={get view(){return l?structuredClone(l):null},get quote(){return f?structuredClone(f):null},get operation(){return i?structuredClone(i):null},get webViewUrl(){return"bundled"},refresh:c,async preview(F){if(u(),!l)throw new m("INVALID_REQUEST","Load the Paywall first");let T=l.document.buttons[F.actionId];if(T?.type!=="checkout")throw new m("INVALID_REQUEST","Choose an authored purchase action");let o=Ge(T.product,F.selection,l.capabilities);if(!o)throw new m("PRODUCT_UNAVAILABLE","Choose an available Product");let t=He(l.document.screen,o,F.selection,l.capabilities),I=ne.previewAttach.request.parse({funnelId:r.funnelId,funnelVersionId:r.funnelVersionId,requestId:F.requestId,plans:[{productVersionId:o,...Object.keys(t).length?{featureQuantities:t}:{}}],provider:r.commerce.provider,currency:r.commerce.currency,...F.offerId?{offerId:F.offerId}:{},...F.nativeOffer?{nativeOffer:F.nativeOffer}:{}}),b=JSON.stringify(I);if(p&&p!==b&&(a||!i||i.status==="pending"))throw new m("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(p===b){if(a)return a;if(f)return structuredClone(f)}p!==b&&(f=null,i=null),p=b;let S=(async()=>{let P=ne.previewAttach,v=await Ee(s.request,P,I);return u(),mn(v.quote,{productVersionId:o,featureQuantities:t,currency:r.commerce.currency,provider:r.commerce.provider},"The purchase quote changed its selected Product or presentment"),f=v.quote,i=null,structuredClone(f)})();a=S;try{return await S}finally{a===S&&(a=null)}},confirm:()=>d("confirm"),cancel:()=>d("cancel"),read:()=>d("read"),destroy(){y||(y=!0,A?.(),s.dispose(),l=null,f=null,i=null,p=null)}},A=e.session?.subscribeIdentity(h.destroy);try{return await c(),h}catch(F){throw h.destroy(),F}}import{z as Ln}from"zod";import{z as ge}from"zod";var _n=ge.record(ge.string().regex(/^[a-f0-9]{64}$/),ge.strictObject({at:ge.number(),text:ge.string()})),oe=2*1048576,Dn=100;function xn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function bn(e,n){let r=n===void 0?xn():n,s=new Map,l=0,y=!1,f=!1,i,p;async function a(c){if(!r)return null;let d;try{let h=await Promise.race([Promise.resolve().then(()=>r.getItem(c)),new Promise(A=>{d=setTimeout(()=>A(null),Dn)})]);return typeof h=="string"&&h.length<=oe&&new TextEncoder().encode(h).byteLength<=oe?h:null}catch{return null}finally{clearTimeout(d)}}function u(){if(p)return p;let c=(async()=>{try{let d=await a(`${e}:artifacts`);if(d)return _n.parse(JSON.parse(d))}catch{}return{}})();return p=c,c.finally(()=>{p===c&&(p=void 0)}),c}return{async readManifest(){return a(e)},writeManifest(c){!r||c.length>oe||new TextEncoder().encode(c).byteLength>oe||(i=c,!f&&(f=!0,Promise.resolve().then(async()=>{try{for(;i!==void 0;){let d=i;try{await r.setItem(e,d)}catch{}i===d&&(i=void 0)}}finally{f=!1}})))},async readArtifact(c){let d=(await u())[c],h=Date.now();return d&&h>=d.at&&h-d.at<=B.retentionMs?d.text:void 0},writeArtifact(c,d){if(!r||d.length>oe)return;let h=s.get(c);if(h?.text===d||!h&&s.size>=128)return;let A=new TextEncoder().encode(d).byteLength;l-(h?.byteLength??0)+A>oe||(s.set(c,{text:d,byteLength:A}),l+=A-(h?.byteLength??0),!y&&(y=!0,Promise.resolve().then(async()=>{try{for(;s.size;){let F=new Map(s);try{let T={...await u()},o=Date.now();for(let[S,P]of F)T[S]={at:o,text:P.text};let t={},I=2,b=0;for(let[S,P]of Object.entries(T).sort(([,v],[,D])=>D.at-v.at)){if(P.at>o||o-P.at>B.retentionMs)continue;let v=new TextEncoder().encode(JSON.stringify({[S]:P})).byteLength;I+v>oe||b>=128||(t[S]=P,I+=v,b++)}await r.setItem(`${e}:artifacts`,JSON.stringify(t))}catch{}finally{for(let[T,o]of F)s.get(T)===o&&(s.delete(T),l-=o.byteLength)}}}finally{y=!1}})))}}}var E=(e,n)=>new m(e,n),W=()=>performance.now(),Pn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function nr(e){let n=Ke.parse(e.scope),r=new te(e.origin??le);if(r.username||r.password||r.search||r.hash||r.pathname!=="/"||r.protocol!=="https:"&&!(r.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(r.hostname)))throw E("INVALID_URL","Configuration requires a trusted HTTPS origin");let s=new Set([r.origin,...(e.assetOrigins??[]).map(w=>{let g=new te(w);if(g.protocol!=="https:"||g.username||g.password||g.search||g.hash||g.pathname!=="/")throw E("INVALID_URL","Invalid configuration asset origin");return g.origin})]),l=e.fetch??globalThis.fetch.bind(globalThis),y=`/api/v1/configuration/${n.environmentId}`,f=`indiana:configuration:1:${r.origin}:${L(n)}`,i=bn(f,e.storage),p,a=0,u=0,c=!1,d=!1,h=0,A=0,F,T,o,t,I=0,b=new Set,S=new Set,P=new Map,v=new Map,D=0,V=!1;function M(){for(let w of b)try{w()}catch{}}function H(w){try{e.onError?.(w)}catch{}}let k=()=>!d&&!c&&!!p&&W()<a&&Date.now()<u;function J(){if(!k())throw E("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function de(w,g,R){if(!P.has(w)){for(;P.size&&(P.size>=128||D+R>B.maxCacheBytes);){let C=P.entries().next().value;D-=C[1].byteLength,P.delete(C[0])}P.set(w,{text:g,byteLength:R}),D+=R}}function Z(w,g,R){return cn(w,g,{signal:R,error:C=>E("INVALID_RESPONSE",C==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function fe(w){let g=new te(w,r);if(!s.has(g.origin)||g.username||g.password||g.hash||g.search)throw E("INVALID_URL","Configuration artifact origin is not trusted");return g.href}async function Fe(w,g,R=!1){let C=await l(fe(w),{method:"GET",credentials:"omit",redirect:"error",cache:R?"default":"no-cache",signal:g,headers:{}});if(C.status===429){let O=C.headers.get("retry-after")??"";I=/^\d+$/.test(O)?Number(O)*1e3:Math.max(0,Date.parse(O)-Date.now())||15e3}if(!C.ok&&C.status!==304)throw E(`CONFIGURATION_HTTP_${C.status}`,"Configuration synchronization failed");return C}function En(w,g,R){let C=Date.parse(w.headers.get("x-indiana-config-validated-at")??""),O=Date.parse(w.headers.get("x-indiana-config-valid-until")??""),_=Date.parse(w.headers.get("date")??""),N=w.headers.get("age"),G=N!==null&&/^\d+(\.\d+)?$/.test(N)?Number(N)*1e3:NaN;if(![C,O,_,G].every(Number.isFinite)||O<=C||O-C>B.maxControlAgeMs||C>_+1e3)throw E("INVALID_RESPONSE","Configuration freshness evidence is invalid");let x=Math.min(O-C,R.maxControlAgeSeconds*1e3,B.maxControlAgeMs)-Math.max(G,_-C,0)-(W()-g);if(x<=0)throw E("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return W()+x}function Ae(){if(clearTimeout(o),clearTimeout(t),d||!b.size)return;k()&&(t=setTimeout(()=>{k()?Ae():M()},Math.max(1,a-W())),Pn(t));let w=A?Math.min(15e3,1e3*2**Math.min(A-1,4)):Math.min(15e3,(p?.policy.refreshIntervalSeconds??15)*1e3);o=setTimeout(()=>{ie().catch(H)},Math.max(I,w*(.8+Math.random()*.2))),Pn(o)}async function ie(){if(d)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(F)return F;let w=h,g=new AbortController;T=g;let R=(async()=>{if(!V){V=!0;try{let he=await i.readManifest();if(he&&!p){let K=Oe.parse(JSON.parse(he));L(K.scope)===L(n)&&(p=K)}}catch{}}g.signal.throwIfAborted();let N=p,G=W(),U=await Fe(y,g.signal);U.status===304&&(!N||!U.headers.has("x-indiana-config-validated-at")||!U.headers.has("x-indiana-config-valid-until")||!U.headers.has("age"))&&(U=await Fe(y,g.signal));let x=U.status===304?N:Oe.parse(JSON.parse(await Z(U,B.maxManifestBytes,g.signal))),{generation:ae,...se}=x,z=U.headers.get("etag");if(L(x.scope)!==L(n)||Qe(se)!==ae||z!==`"${ae}"`&&z!==`W/"${ae}"`)throw E("INVALID_RESPONSE","Configuration scope or content identity changed");if(N&&(x.revision<N.revision||x.revision===N.revision&&x.generation!==N.generation))throw E("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[he,K]of Object.entries(N?.funnels??{})){let ee=x.funnels[he];if(ee&&(ee.controlRevision<K.controlRevision||ee.evaluationRevision<K.evaluationRevision||ee.controlRevision===K.controlRevision&&ee.state!==K.state||ee.evaluationRevision===K.evaluationRevision&&ee.evaluationMode!==K.evaluationMode))throw E("INVALID_RESPONSE","Funnel control revision changed identity")}let X=En(U,G,x.policy);if(g.signal.throwIfAborted(),w!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return p=x,a=X,u=Date.now()+Math.max(0,X-W()),c=!1,A=0,I=0,i.writeManifest(L(x)),M(),structuredClone(x)})(),C=setTimeout(()=>g.abort(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),B.initializationMs),O=new Promise((N,G)=>g.signal.addEventListener("abort",()=>G(g.signal.reason),{once:!0})),_=Promise.race([R,O]).catch(N=>{throw A++,(N instanceof Ln.ZodError||N instanceof SyntaxError||N instanceof m&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(N.code))&&(a=0,c=!0,M()),N}).finally(()=>{clearTimeout(C),F===_&&(F=void 0),Ae()});return F=_,_}async function ye(w){let g=w.sha256,R=se=>Ce(se,w);fe(w.url);let C=P.get(g);if(C){if(C.byteLength!==w.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return P.delete(g),P.set(g,C),C.text}let O=v.get(g);if(O){if(O.byteLength!==w.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return O.promise}let _=new AbortController;S.add(_);let N=h,G=(async()=>{try{let X=await i.readArtifact(g);if(X&&R(X)){if(_.signal.throwIfAborted(),d||N!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(g,X,w.byteLength),X}}catch{}_.signal.throwIfAborted();let se=await Fe(w.url,_.signal,!0),z=await Z(se,w.byteLength,_.signal);if(!R(z))throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(d||N!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(g,z,w.byteLength),i.writeArtifact(g,z),z})(),U=setTimeout(()=>_.abort(E("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),B.initializationMs),x=new Promise((se,z)=>_.signal.addEventListener("abort",()=>z(_.signal.reason),{once:!0})),ae=Promise.race([G,x]).finally(()=>{clearTimeout(U),S.delete(_),v.delete(g)});return v.set(g,{promise:ae,byteLength:w.byteLength}),ae}async function we(){return k()||await ie(),J(),p}async function me(w){let g,R=new Promise((C,O)=>{g=setTimeout(()=>O(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),B.initializationMs)});try{return await Promise.race([w(),R])}finally{clearTimeout(g)}}function pe(w,g){if(J(),p?.generation!==w.generation)throw E("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(g&&p.funnels[g]?.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function xe(w){let g=w.gb.features;if(!g)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let R=w.artifacts[g];if(R.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let C=je.parse(JSON.parse(await ye(R)));if(L(C.scope)!==L({projectId:n.projectId,environment:n.environment})||C.generation!==R.generation||C.remoteFeatures.some(O=>Object.hasOwn(C.features,O)))throw E("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return pe(w),{...C,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,a-W())).toISOString()}}async function Le(w,g){let R=await we(),C=R.funnels[w];g&&(!C||C.evaluationMode==="local"&&!C.versions[g])&&(F&&await F,R=await ie()),pe(R,w);let O=R.funnels[w];if(O.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let _=g??O.currentVersionId,N=O.versions[_];if(!N)throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(R.artifacts[N.artifact].formatVersion!==3)throw E("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[G,U]=await Promise.all([ye(R.artifacts[N.artifact]).then(x=>$e(JSON.parse(x))),O.evaluationMode==="local"?xe(R):void 0]);if(U&&L(Ye(G,U))!==L(N.dependencies))throw E("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return pe(R,w),{document:G,growth:U,versionId:_,control:structuredClone(O),manifest:structuredClone(R)}}async function Ve(w,g){try{return await Le(w,g)}catch(R){if(!(R instanceof m)||!(R.code==="CONFIGURATION_CHANGED"||R.code==="CONFIGURATION_HTTP_404"&&k()))throw R;let C=p?.generation;if(F&&await F,await ie(),R.code!=="CONFIGURATION_CHANGED"&&p?.generation===C)throw R;return Le(w,g)}}function Ne(){c=!0,M(),ie().catch(H)}let Ie=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ne()};function Fn(w){if(d)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return b.add(w),b.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ne),window.addEventListener("focus",Ie),document.addEventListener("visibilitychange",Ie)),Ae()),()=>{b.delete(w),b.size||(clearTimeout(o),clearTimeout(t),Me())}}function Me(){typeof window<"u"&&(window.removeEventListener("online",Ne),window.removeEventListener("focus",Ie),document.removeEventListener("visibilitychange",Ie))}return{scope:Object.freeze({...n}),refresh:ie,subscribe:Fn,assertFresh:J,assertFeatures(w){J();let g=p.gb.features;if(!g)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(w!==void 0&&p.artifacts[g].generation!==w)throw E("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return k()},get snapshot(){return p?structuredClone(p):null},get remainingMs(){return k()?Math.max(0,a-W()):0},async features(){return me(async()=>xe(await we()))},pageExperiments:()=>me(async()=>{let w=await we(),g=w.gb.pageExperiments;if(!g)throw E("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let R=w.artifacts[g];if(R.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let C=an.parse(JSON.parse(await ye(R)));if(C.environmentId!==n.environmentId||C.generation!==R.generation)throw E("INVALID_RESPONSE","Page experiment scope or generation changed");return pe(w),C}),funnel:(w,g)=>me(()=>Ve(w,g)),paywall:(w,g)=>me(async()=>{let R=await we(),C=R.paywalls?.[w];if(!C||!g&&C.state!=="published")throw E("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let O=g??C.currentVersionId,_=C.versions[O],N=_&&R.artifacts[_.artifact];if(!N||N.kind!=="paywall"||N.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let G=ze.parse(JSON.parse(await ye(N)));return pe(R),{document:G,versionId:O,version:_.version,control:structuredClone(C),manifest:structuredClone(R)}}),async localFunnel(w,g){let R=await me(()=>Ve(w,g));if(!R.growth)throw E("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:C,remoteFeatures:O,..._}=R.growth;return on({scope:{projectId:n.projectId,environment:n.environment},funnelId:w,versionId:R.versionId,evaluationMode:"local",evaluationRevision:R.control.evaluationRevision,document:R.document,payload:_})},assertFunnel(w,g,R){J();let C=p.funnels[w];if(!C||C.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable");if(C.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel now executes at Longplay");if(g!==void 0&&C.controlRevision!==g)throw E("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(R!==void 0&&!C.versions[R])throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!d){d=!0,h++,a=0,T?.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(o),clearTimeout(t),Me(),M(),b.clear();for(let w of S)w.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));P.clear(),D=0}}}}function Sn(e){let n=ue.test(e.apiKey);if(typeof window<"u"&&!n)throw new m("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!re.test(e.apiKey))throw new m("INVALID_TOKEN","A customer credential or server API key is required");return{async start(r){let s=Q.safeParse({...r,operation:"start"});if(!s.success||s.data.operation!=="start"||(n?s.data.customer!==void 0:s.data.customer===void 0))throw new m("INVALID_REQUEST","Invalid current Funnel start");let l=s.data,y=Y({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||y.identify(e.apiKey);let f=be(e,await y.request("funnels",l));if(!f.runToken)throw new m("INVALID_RESPONSE","Funnel start credentials are missing");if(f.run.source.id!==l.funnelId||f.run.locale!==(l.locale??"en")||!ce(f.run.parameters,l.parameters??{})||(l.customer?!f.customerId||l.customer.type==="id"&&f.customerId!==l.customer.value:f.customerId!==void 0))throw new m("INVALID_RESPONSE","Funnel start contract changed");return{...f,runToken:f.runToken}}finally{y.dispose()}}}}async function pr(e){e={...e};let n=e.configuration;if(!n)throw new m("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let r={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&L(r)!==L(e.scope))throw new m("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new m("EVALUATION_MODE","This Funnel uses Remote evaluation");let l=re.test(e.credential);if(l?!e.customerId:e.customerId!==void 0)throw new m("INVALID_REQUEST","Only Server-Key starts name their Customer");let y=Sn({...e,scope:r,apiKey:e.credential}),f=i=>{let p=Rn({...e,scope:r,runToken:i,...l?{serverKey:e.credential}:{}});return l||p.identify(e.credential),p};return{async start(i){let p=await y.start({...i,funnelId:e.funnelId,...l?{customer:{type:"id",value:e.customerId}}:{}}),a=f(p.runToken),u=await a.get();return{...p,...u,controller:a}},async restore(i){let p=f(i),a=await p.get();if(a.run.source.id!==e.funnelId)throw p.reset(),new m("SCOPE_MISMATCH","Run belongs to another Funnel");return{...a,runToken:i,controller:p}}}}export{Ee as a,Mn as b,be as c,_e as d,Xn as e,Nn as f,gn as g,lt as h,ce as i,yt as j,wt as k,Rn as l,jt as m,nr as n,Sn as o,pr as p};
|
|
1
|
+
import{b as dn,c as fn,d as mn,e as pn}from"./chunk-VSMITXQD.js";import{a as te,b as Y}from"./chunk-RNL2AGFW.js";import{a as m}from"./chunk-OZZMZH7X.js";import{a as ln,b as cn,c as Ce}from"./chunk-C76COHTI.js";import{$a as un,Ea as Te,Fa as tn,R as Ge,T as Re,Ta as rn,U as Be,Ua as on,V as je,W as Je,Xa as an,Ya as sn,a as Ue,cb as le,da as Q,ea as ze,fa as B,ga as Ke,ha as Oe,ia as L,ka as Qe,la as Ye,ma as $e,n as ue,na as We,oa as Ze,ua as ne,va as Xe,ya as en,za as nn}from"./chunk-DR66DI6C.js";import{B as ve,Ca as He,v as qe,y as ke}from"./chunk-VSJOHWDL.js";function Mn(e){let n=null,r=null,s=0,l=0,y=new Set,f=null,i=null,p=new Set,a=()=>{for(let o of p)try{o()}catch{}},u={attributes:ve.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(o,t)=>{!y.has(o)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(o,structuredClone(t),structuredClone(u.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(o,t)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(o),structuredClone(t),structuredClone(u.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?o=>e.saveStickyBucketAssignmentDoc(structuredClone(o)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},c=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function d(o,t=new Set){return y.has(o)?!f||!f.features[o]||["unknownFeature","cyclicPrerequisite"].includes(f.features[o].source):t.has(o)?!1:(t.add(o),(n?.features[o]?.rules??[]).some(I=>[...I.parentConditions??[],...(I.tracks??[]).flatMap(b=>b.experiment.parentConditions??[])].some(b=>d(b.id,t))))}let h=o=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return f?.expiresAt&&Date.parse(f.expiresAt)<=Date.now()&&(f=null,u.features=n.features),y.has(o)?!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now()?c():structuredClone(f.features[o]??c()):e.evaluateRemote&&(u.attributes?.merchandise||u.attributes?.merchandiseId)&&!f||d(o)?c():structuredClone(ke(o,u))};async function A(){if(!n||!y.size&&!u.attributes?.merchandise&&!u.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(y.size)throw new Error("Remote Feature evaluation requires a server loader");return}let o=l;if(i?.revision===o)return i.loading;let t=s,I=n,b=[...y],S=(async()=>{let P=Je.parse(await e.evaluateRemote({attributes:structuredClone(u.attributes),features:b}));if(!(t!==s||o!==l||I!==n)){if(e.assertUsable?.(I.generation),P.generation!==I.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(b.some(v=>!Object.hasOwn(P.features,v))||Object.keys(P.features).some(v=>!y.has(v)))throw new Error("Invalid remote Feature results");if(u.attributes?.merchandise||u.attributes?.merchandiseId){if(!P.merchandiseContext)throw new Error("Server did not resolve merchandise context");u.attributes=ve.parse({...u.attributes,...P.merchandiseContext})}f=structuredClone(P),u.features={...I.features,...Object.fromEntries(Object.entries(f.features).map(([v,D])=>[v,{defaultValue:D.value}]))},a()}})();i={revision:o,loading:S};try{await S}finally{i?.loading===S&&(i=null)}}function F(){A().catch(o=>{try{e.onError?.(o)}catch{}})}async function T(){if(r)return r;let o=s,t=(async()=>{let I=await e.load(),b="remoteFeatures"in I?Be.parse(I):null,S=b??Re.parse(I);if(S.scope.projectId!==e.scope.projectId||S.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(o!==s)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===S.generation){let{evaluatedAt:v,expiresAt:D,...V}=n,{evaluatedAt:M,expiresAt:H,...k}=S;if(L(V)!==L(k))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=S.evaluatedAt,n.expiresAt=S.expiresAt,a(),(!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now())&&F(),structuredClone(n)}let P=new Set(b?.remoteFeatures??[]);if([...P].some(v=>Object.hasOwn(S.features,v)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in S&&!n.analyticsConfig.experimentViewsEnabled&&b?.analyticsConfig.experimentViewsEnabled&&u.trackedExperiments?.clear(),n=structuredClone(S),y=P,f=null,i=null,l++,u.features=n.features,u.savedGroups=qe(n.savedGroups),u.trackedFeatureUsage={},a(),F(),structuredClone(n)})();r=t;try{return await t}finally{r===t&&(r=null)}}return{init:T,refresh:T,refreshRemote:A,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(o){return p.add(o),()=>{p.delete(o)}},setAttributes(o){let t=ve.parse(o);(u.attributes?.merchandise||u.attributes?.merchandiseId||o.merchandise||o.merchandiseId)&&u.trackedExperiments?.clear(),u.attributes=t,l++,f=null,i=null,u.features=n?.features??{},u.trackedFeatureUsage={},a(),F()},evalFeature:h,isOn(o){return h(o).on},isOff(o){return h(o).off},getFeatureValue(o,t){let I=h(o).value;return structuredClone(I===null?t:I)},reset(){s++,l++,r=null,i=null,n=null,f=null,y.clear(),u.features={},u.savedGroups={},u.stickyBucketAssignmentDocs={},u.attributes={},u.trackedFeatureUsage={},u.trackedExperiments?.clear(),a()}}}function gn(e){let n,r,s=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),l=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,r=e.locks??globalThis.navigator?.locks,!n||!r||!globalThis.crypto?.subtle)throw s();let i=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??le).href,e.runToken])),p=new Uint8Array(await crypto.subtle.digest("SHA-256",i));return"indiana.funnel.commands.v1."+Array.from(p,a=>a.toString(16).padStart(2,"0")).join("")});l.catch(()=>{});async function y(i){try{let p=await l;return await r.request(p,{mode:"exclusive"},()=>i(p))}catch(p){throw p instanceof m?p:s()}}function f(i){let p=n.getItem(i);if(p===null)return{revision:0,entry:null};if(p.length>1048576)throw s();let a=JSON.parse(p);if(!a||typeof a!="object"||!("revision"in a)||!("entry"in a)||!Number.isSafeInteger(a.revision)||Number(a.revision)<0)throw s();return{revision:Number(a.revision),entry:a.entry}}return{read:()=>y(f),write:(i,p)=>y(a=>{if(f(a).revision!==i)return null;if(!Number.isSafeInteger(i+1))throw s();return n.setItem(a,JSON.stringify({revision:i+1,entry:p})),i+1})}}function be(e,n){let r=en.safeParse(n);if(!r.success)throw new m("INVALID_RESPONSE","Funnel response contract changed");let s=r.data;if(e.scope&&(s.scope.projectId!==e.scope.projectId||s.scope.environment!==e.scope.environment))throw new m("SCOPE_MISMATCH","Funnel scope changed");return s}async function Pe(e,n){let r=We.parse(n),{artifact:s,environmentId:l}=r.content,y=new te(e.baseUrl??le).origin,f=new te(s.url,y);if(f.origin!==y||f.username||f.password||f.search||f.hash||f.pathname!==`/api/v1/configuration/${l}/artifacts/${s.sha256}`)throw new m("INVALID_RESPONSE","Public Paywall locator is not trusted");let i=new AbortController,p,a=new Promise((c,d)=>{p=setTimeout(()=>{let h=new m("TIMEOUT","Public Paywall read timed out");i.abort(h),d(h)},B.initializationMs)}),u=(async()=>{let c=await(e.fetch??globalThis.fetch)(f,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:i.signal});if(i.signal.aborted&&(c.body?.cancel().catch(()=>{}),i.signal.throwIfAborted()),!c.ok||!c.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(c.headers.get("content-length"))>s.byteLength)throw c.body?.cancel().catch(()=>{}),new m("INVALID_RESPONSE","Public Paywall is unavailable");let d=await ln(c,s.byteLength,{signal:i.signal,error:h=>new m("INVALID_RESPONSE",h==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Ce(d,s))throw new m("INVALID_RESPONSE","Public Paywall digest or size changed");return Ze(r,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d)))})();try{return await Promise.race([u,a])}finally{clearTimeout(p)}}var _e=(e,n)=>new m(e,n);function Xn(e){return sn(e,_e)}async function De(e,n,{predict:r=!0}={}){let s=n.instruction;if(s?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==s.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let l=null,y;if(r)try{let f=await e.funnel(n.source.id,n.source.versionId);y=f.manifest.generation,l=An(e,n,f)}catch{l=null}return y??=e.snapshot?.generation??(await e.refresh()).generation,{advance:{policyRevision:s.policyRevision,generation:y},prediction:l}}function An(e,n,r){let s=n.instruction;if(s?.type!=="evaluate_segment"||!r.growth||r.control.evaluationMode!=="local"||r.control.evaluationRevision!==s.policyRevision)return null;let{analyticsConfig:l,remoteFeatures:y,...f}=r.growth,i=rn({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:s.policyRevision,document:r.document,payload:Re.parse(f)}),p=Nn(i,r.document,{...n,...s}),a=p.steps.at(-1),u=p.boundary??(a?.result.port==="value"?{nodeId:a.nodeId,visit:n.visit+p.steps.length-1}:null);return u?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:u.nodeId,visit:u.visit,terminal:!p.boundary}:null}function Nn(e,n,r){return un(e,n,r,_e)}import{z as j}from"zod";var yn=Q.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),wn=j.strictObject({schemaVersion:j.literal(1),scope:Ue,runId:j.uuid(),funnelId:j.uuid(),versionId:j.uuid(),processBindingIds:j.record(j.uuid(),j.uuid().nullable()).optional(),command:yn.optional(),closeCommand:yn.refine(e=>e.operation==="close").optional(),purchase:j.strictObject({receiptId:j.uuid(),operationId:j.uuid(),generation:j.number().int().nonnegative()}).optional(),closed:j.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),q=()=>new m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Se=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function In(e){let n=0,r=null,s=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),l=Promise.resolve();async function y(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:wn.parse(a.entry)}}function f(a){let u=l.then(a);return l=u.catch(()=>{}),u}async function i(a){for(let u=0;u<4;u++){let c=await y();if(c.entry&&r!==null&&s(c.entry)!==r)throw q();let d=a(c.entry,c.revision);if(Se(c.entry,d)){n=c.revision;return}let h=await e.write(c.revision,d);if(h!==null){if(!Number.isSafeInteger(h)||h<=c.revision)throw q();n=h;return}}throw q()}function p(a,u){if(!a||!u)return a;if(a.processBindingIds&&Object.hasOwn(a.processBindingIds,u)){let c={...a.processBindingIds};delete c[u],a={...a,processBindingIds:c}}return a.command?.requestId===u?a.closeCommand?{...a,command:a.closeCommand,closeCommand:void 0}:a.purchase?{...a,command:void 0}:null:a.closeCommand?.requestId===u?{...a,closeCommand:void 0}:a}return{bind(a){let u=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(r!==null&&r!==u)throw q();r=u},async load(){let a=await y();return n=a.revision,r=a.entry?s(a.entry):null,a.entry},retain(a){let u=wn.parse(a),c=u.command;return!c||r!==null&&s(u)!==r?Promise.reject(q()):(r??=s(u),f(()=>i((d,h)=>{if(d&&!Se(s(d),s(u)))throw q();if(d&&u.processBindingIds){for(let[A,F]of Object.entries(u.processBindingIds))if(d.processBindingIds&&Object.hasOwn(d.processBindingIds,A)&&d.processBindingIds[A]!==F)throw q();d={...d,processBindingIds:{...d.processBindingIds,...u.processBindingIds}}}if(!d){if(h!==n&&c.operation!=="close")throw q();return u}if(!d.command)return{...d,command:c,...c.operation==="close"?{closed:!0}:{}};if(c.operation==="close"&&d.command.operation!=="close"){if(d.command.requestId===c.requestId||d.closeCommand&&!Se(d.closeCommand,c))throw q();return{...d,closeCommand:c,closed:!0}}if(!Se(d.command,c))throw q();return d})))},observePurchase(a,u,c,d){return f(()=>i((h,A)=>{if(!h&&A!==n||h&&s(h)!==s({...a,schemaVersion:1}))throw q();if(h?.purchase&&h.purchase.generation>u.generation)return p(h,d);if(h?.purchase&&h.purchase.generation===u.generation&&h.purchase.operationId!==u.operationId)throw q();return c?!h?.purchase||h.purchase.operationId!==u.operationId?p(h,d):p(h.command?{...h,purchase:void 0}:null,d):p({schemaVersion:1,...a,...h,purchase:u},d)}))},settle(a){return f(()=>i(u=>p(u,a)))}}}function lt(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function ce(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((l,y)=>ce(l,n[y]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let r=Object.entries(e),s=Object.entries(n);return r.length===s.length&&r.every(([l,y])=>Object.hasOwn(n,l)&&ce(y,Reflect.get(n,l)))}function hn(e,n){let r=n&&{...n},s=null,l=0,y=new AbortController;function f(){l++,y.abort(new m("IDENTITY_CHANGED","Run identity changed")),y=new AbortController}let i=!1,p,a=0,u=new Set;return{get scope(){return r},bindScope(c){if(r&&(r.projectId!==c.projectId||r.environment!==c.environment))throw new m("SCOPE_MISMATCH","Run scope changed");r??={...c}},get view(){return s},get generation(){return l},get signal(){return y.signal},get disposed(){return i},get customerToken(){return p},get readSequence(){return a},nextRead(){return++a},assertCurrent(c,d="Run identity changed during the request"){if(c!==l||i)throw new m("IDENTITY_CHANGED",d)},assertRun(c){if(s&&(c.id!==s.id||c.source.type!==s.source.type||c.source.id!==s.source.id||c.source.versionId!==s.source.versionId||c.locale!==s.locale||!ce(c.parameters,s.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&c.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(c,d,h,A,F){if(!(c.operation==="review"&&s&&s!==h&&d.run.revision<=s.revision)&&!(s&&d.run.revision===s.revision&&A!==void 0&&A<a)&&(c.operation==="review"&&!d.run.stopped&&["running","waiting"].includes(d.run.status)&&s&&d.run.nodeId===s.nodeId&&d.run.visit===s.visit&&d.run.revision===s.revision&&(d.run.screen=s.screen,(s.paywall?.quote?.operationId===d.review?.activeOperationId||!s.paywall?.quote&&d.review?.activeOperationId===null)&&(d.run.paywall=s.paywall)),!(s?.paywall&&d.run.paywall&&s.paywall.receiptId===d.run.paywall.receiptId&&(d.run.paywall.selectionGeneration??0)<(s.paywall.selectionGeneration??0)))){if(!s||d.run.revision>=s.revision)s=d.run;else if(!F)return;if(s)for(let T of u)try{T(structuredClone(s))}catch{}}},identify(c){if(i)throw new m("IDENTITY_CHANGED","Controller was reset");if(!ue.test(c))throw new m("INVALID_TOKEN","Customer credential required");f(),p=c},subscribe(c){return u.add(c),()=>u.delete(c)},reset(){i||(i=!0,f(),p=void 0,s=null,u.clear())}}}var re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function yt(e,n,r="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",n);if(!re.test(e))throw new m("INVALID_TOKEN",r)}function wt(e){let n=Y(e);return n.identify(e.apiKey),n}function $(e){let{customerToken:n,...r}=e;return r}var On=e=>!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function vn({journal:e,state:n,call:r,processIdentity:s}){let l=null,y=null,f=!1,i={command:null,close:null},p=new Set,a,u=null,c=e?e.load().then(o=>{if(n.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(u=o,!o)return;if(s){if([o.command,o.closeCommand].some(I=>I&&!Object.hasOwn(o.processBindingIds??{},I.requestId)))throw new m("COMMAND_STORAGE_INVALID","The original process identity is missing");s.restore(o.processBindingIds??{})}if(n.scope&&(o.scope.projectId!==n.scope.projectId||o.scope.environment!==n.scope.environment))throw new m("SCOPE_MISMATCH","Pending command belongs to another scope");if(a=o.purchase,f=o.closed===!0,!o.command)return;let t=o.command;l=t.operation==="close"?null:t,y=t.operation==="close"?t:o.closeCommand?.operation==="close"?o.closeCommand:null,y&&(f=!0);for(let I of[l,y])I&&p.add(I.requestId)}):Promise.resolve();c.catch(()=>{});async function d(o){e&&await c;let t=n.generation;if(e){if(!n.view||!n.scope)throw new m("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:n.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:$(o),...s?{processBindingIds:{[o.requestId]:s.binding(o.requestId)}}:{}})}if(t!==n.generation||l!==o&&y!==o)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let I=p.has(o.requestId);p.add(o.requestId);try{return await r(o)}catch(b){throw t===n.generation&&(l===o||y===o)&&!I&&!On(b)&&(e&&await e.settle(o.requestId),t===n.generation&&T(o)),b}}function h(o){let t=Q.parse(o);if(t.operation==="start"||t.operation==="get"||t.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(f&&t.operation!=="close"){if(l?.requestId===t.requestId)return F(t.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(t.operation==="close"){if(l?.requestId===t.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(f=!0,y&&JSON.stringify($(y))!==JSON.stringify($(t)))throw new m("COMMAND_PENDING","Retry the original Close");return y??=t,i.close?i.close:A(y,"close")}if(l){if(JSON.stringify($(l))!==JSON.stringify($(t)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(i.command)return i.command}else l=t;return A(l,"command")}function A(o,t){let I=d(o);i[t]=I;let b=()=>{i[t]===I&&(i[t]=null)};return I.then(b,b),I}function F(o){return r({operation:"get",settlementRequestId:o})}function T(o){return!o||l!==o&&y!==o?!1:(l===o&&(l=null),y===o&&(y=null),p.delete(o.requestId),!l&&!y&&(u=null),!0)}return{ready:c,get pending(){return l},get closing(){return y},get closeRequested(){return f},get inFlight(){return i.command},get closeFlight(){return i.close},get purchase(){return a},assertBinding(o){if(u&&(o.run.id!==u.runId||o.run.source.id!==u.funnelId||o.run.source.versionId!==u.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(o,t,I,b){let S=o.operation==="get"?o.settlementRequestId:"requestId"in o&&o.operation!=="start"?o.requestId:void 0,P=S&&t.settlement?.state==="settled"&&t.run.pendingRequest?.requestId!==S&&(o.operation==="get"||!f||o.operation==="close"||!["running","waiting"].includes(t.run.status))?S:void 0,v=l?.requestId===P?l:y?.requestId===P?y:void 0;e?.bind({scope:t.scope,runId:t.run.id,funnelId:t.run.source.id,versionId:t.run.source.versionId});let D=t.run.paywall,V=D??t.purchase,M=V?.operation,H=t.settlement&&(!D||D.purchaseRequestId===t.settlement.requestId)&&(!a||a.operationId===t.settlement.operationId)?t.settlement:void 0,k=M?.operationId??V?.quote?.operationId??H?.operationId,J=V?.receiptId??H?.receiptId,de=D?.selectionGeneration??a?.generation??0;if(e&&k&&J&&o.operation!=="review"&&(!n.view||t.run.revision>=n.view.revision)&&(b===void 0||b>=n.readSequence)&&(!a||de>=a.generation)){let Z={receiptId:J,operationId:k,generation:de},fe=M?.status==="complete"||V?.canReselect===!0;await e.observePurchase({scope:t.scope,runId:t.run.id,funnelId:t.run.source.id,versionId:t.run.source.versionId},Z,fe,P),n.assertCurrent(I),(!a||Z.generation>=a.generation)&&(b===void 0||b>=n.readSequence)&&(fe?a?.operationId===Z.operationId&&(a=void 0):a=Z)}else e&&P&&await e.settle(P);return n.assertCurrent(I),P?T(v):!1},stop(){f=!0},submit:h,settle:F,reset(){f=!0,l=null,y=null,a=void 0,u=null,i.close=null,p.clear(),i.command=null}}}function Rn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new m("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!re.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let n=Y({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),r=hn(e.funnelId,e.scope??e.configuration?.scope),s=e.session?.subscribeIdentity(a),l=null,y=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?gn(e):void 0),f=y&&In(y),i=vn({journal:f,state:r,call:u,processIdentity:e.process});async function p(t){if(e.process)return e.process.request(t);let I=r.generation;r.assertCurrent(I);let b=performance.now()+(e.timeoutMs??35e3),S=r.customerToken??("customerToken"in t?t.customerToken:void 0);if(e.session){let D=r.signal,V,M=()=>{},H=new Promise((k,J)=>{M=()=>J(D.reason),D.addEventListener("abort",M,{once:!0}),V=setTimeout(()=>J(new m("TIMEOUT","Longplay request timed out")),Math.max(1,b-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(r.assertCurrent(I),e.session.access())),H])}finally{clearTimeout(V),D.removeEventListener("abort",M)}}r.assertCurrent(I);let P={...t,...S?{customerToken:S}:{}},v=t.operation==="page_experiments"?Te.parse(P):Q.parse(P);return n.requestWithCredential("funnels",v,e.runToken,{headers:e.serverKey&&!S?{[nn]:e.serverKey}:void 0,timeoutMs:Math.max(1,b-performance.now())})}function a(){s?.(),r.reset(),i.reset(),l=null,n.dispose()}async function u(t,I){let b=r.generation,S=()=>r.assertCurrent(b);f&&await i.ready,S();let P=r.view,v=be(e,await p(t));if(t.operation==="review"&&!v.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(S(),v.runToken&&v.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let D=t.operation==="get"?t.settlementRequestId:"requestId"in t&&t.operation!=="start"?t.requestId:void 0;if(D&&v.settlement?.requestId!==D)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");i.assertBinding(v),r.assertRun(v.run),r.bindScope(v.scope);let V=await i.observe(t,v,b,I);return!v.run.stopped&&["running","waiting"].includes(v.run.status)&&t.operation==="get"&&t.settlementRequestId||(S(),["running","waiting"].includes(v.run.status)||i.stop(),r.publish(t,v,P,I,V)),v}let c=i.submit,d=null,h=new WeakMap;function A(t){let I=h.get(t);if(I)return I;let b=T(t);return h.set(t,b),b}let F=!1;async function T(t){let I=await t;if(I.run.instruction?.type!=="evaluate_segment")return I;if(d)return d;F=!0;let b=r.generation,S=(async()=>{for(let P=0;P<32&&I.run.instruction?.type==="evaluate_segment";P++){if(i.pending||i.closeRequested)return I;let v=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:V}=await De(e.configuration,v,{predict:!1});if(b!==r.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(i.pending||i.closeRequested)return I;if(r.view&&(r.view.revision!==v.revision||r.view.visit!==v.visit||r.view.nodeId!==v.nodeId))return u({operation:"get"});let M=!0;De(e.configuration,v).then(({prediction:H})=>{M&&b===r.generation&&!i.closeRequested&&r.view?.id===v.id&&!r.view.stopped&&r.view.nodeId===v.nodeId&&r.view.visit===v.visit&&r.view.revision===v.revision&&(l=H)}).catch(()=>{});try{I=await c({operation:"commit_segment",requestId:Xe(v.id,v.visit,`segment:${v.revision}`),nodeId:v.nodeId,visit:v.visit,revision:v.revision,...V})}finally{M=!1,l=null}}}return I})();d=S;try{return await S}finally{d===S&&(d=null)}}let o={get configuration(){return F?e.configuration:void 0},get configurationReady(){return!0},get view(){return r.view?structuredClone(r.view):null},get pendingCommand(){let t=i.closing??i.pending;return t?structuredClone($(t)):null},get pendingCommands(){return[i.pending,i.closing].filter(t=>t!==null).map(t=>structuredClone($(t)))},get pendingPurchase(){return i.purchase?structuredClone(i.purchase):null},get prediction(){let t=r.view;return l&&t&&!t.stopped&&["running","waiting"].includes(t.status)&&t.id===l.runId&&t.nodeId===l.from.nodeId&&t.visit===l.from.visit&&t.revision===l.from.revision&&!i.closeRequested?structuredClone(l):null},settle:i.settle,get webViewUrl(){return"bundled"},resolvePaywall(t){return Pe(e,t)},async pageExperiments(t,I=[]){let b=r.generation;r.assertCurrent(b);let S=r.view?.id;if(!S)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let P=tn.parse(await p(Te.parse({operation:"page_experiments",release:t,usedReceiptIds:I})));if(r.assertCurrent(b),P.runId!==S||P.scope.projectId!==r.scope?.projectId||P.scope.environment!==r.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return P},review(t){return u({operation:"review",...t?{receiptId:t}:{}},r.nextRead())},async get(t,I){f&&await i.ready,I??=i.purchase&&{receiptId:i.purchase.receiptId,operationId:i.purchase.operationId};let b=r.nextRead();return A(u({operation:"get",...t?{data:t}:{},...I?{purchase:I}:{}},b))},resume(t=r.view?.pendingRequest?.requestId){return t?i.closeRequested?o.settle(t):i.pending?.requestId===t?A(c(i.pending)):A(c({operation:"resume",requestId:t})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(t){return A(c(t))},retry(){return i.closeFlight?i.closeFlight:i.closing?c(i.closing):i.closeRequested&&i.pending?o.settle(i.pending.requestId):i.inFlight?A(i.inFlight):i.pending?A(c(i.pending)):Promise.reject(new m("INVALID_REQUEST","No command is pending"))},identify(t){r.identify(t),l=null,n.reset()},subscribe:r.subscribe,reset:a};return o}import{ZodError as Tn}from"zod";function Cn(e,n,r,s){try{return e.parse(n)}catch(l){throw s&&l instanceof Tn?new m(r,s):l}}async function Ee(e,n,r,s={},l){let y=typeof s=="function"?{}:s,f=Cn(n.request,r,"INVALID_REQUEST",y.request);try{let i=await e(n.path,f,n.method,l),p=typeof s=="function"?s:s.parseResponse;return p?p(n.response,i):Cn(n.response,i,"INVALID_RESPONSE",y.response)}catch(i){throw i instanceof m&&f!==null&&typeof f=="object"&&"requestId"in f&&typeof f.requestId=="string"&&(i.commandRequestId??=f.requestId),i}}async function jt(e,n){if(!ue.test(n.customerToken))throw new m("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==n.customerToken)throw new m("SCOPE_MISMATCH","Paywall credential does not match the shared session");let r=ne.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),s=Y(e);e.session||s.identify(n.customerToken);let l=null,y=!1,f=null,i=null,p=null,a=null;function u(){if(y)throw new m("IDENTITY_CHANGED","Paywall is closed")}async function c(){u();let F=ne.resolvePaywall,T=await Ee(s.request,F,{...r,selector:l?{type:"version",versionId:l.id}:r.selector}),o=await Pe(e,T.paywall);if(u(),n.paywallVersionId?o.id!==n.paywallVersionId:o.paywallId!==n.paywallId)throw new m("INVALID_RESPONSE","The requested Paywall changed");if(l&&(!dn(o,l)||o.paywallId!==l.paywallId))throw new m("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return l=o,structuredClone(l)}async function d(F){if(u(),a&&F!=="read")throw new m("COMMAND_PENDING","Wait for the original quote");if(!f)throw new m("INVALID_REQUEST","A quoted purchase is required");let T=f,o=F==="read"?ne.readSubscriptionOperation:ne.attach,t=await Ee(s.request,o,{operationId:T.operationId,...F==="read"?{}:{intent:F}});return fn(t.operation,{operationId:T.operationId,currency:r.commerce.currency},"The purchase operation changed"),u(),f?.operationId!==T.operationId?structuredClone(t.operation):(i=pn(i,t.operation),structuredClone(i))}let h={get view(){return l?structuredClone(l):null},get quote(){return f?structuredClone(f):null},get operation(){return i?structuredClone(i):null},get webViewUrl(){return"bundled"},refresh:c,async preview(F){if(u(),!l)throw new m("INVALID_REQUEST","Load the Paywall first");let T=l.document.buttons[F.actionId];if(T?.type!=="checkout")throw new m("INVALID_REQUEST","Choose an authored purchase action");let o=Ge(T.product,F.selection,l.capabilities);if(!o)throw new m("PRODUCT_UNAVAILABLE","Choose an available Product");let t=He(l.document.screen,o,F.selection,l.capabilities),I=ne.previewAttach.request.parse({funnelId:r.funnelId,funnelVersionId:r.funnelVersionId,requestId:F.requestId,plans:[{productVersionId:o,...Object.keys(t).length?{featureQuantities:t}:{}}],provider:r.commerce.provider,currency:r.commerce.currency,...F.offerId?{offerId:F.offerId}:{},...F.nativeOffer?{nativeOffer:F.nativeOffer}:{}}),b=JSON.stringify(I);if(p&&p!==b&&(a||!i||i.status==="pending"))throw new m("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(p===b){if(a)return a;if(f)return structuredClone(f)}p!==b&&(f=null,i=null),p=b;let S=(async()=>{let P=ne.previewAttach,v=await Ee(s.request,P,I);return u(),mn(v.quote,{productVersionId:o,featureQuantities:t,currency:r.commerce.currency,provider:r.commerce.provider},"The purchase quote changed its selected Product or presentment"),f=v.quote,i=null,structuredClone(f)})();a=S;try{return await S}finally{a===S&&(a=null)}},confirm:()=>d("confirm"),cancel:()=>d("cancel"),read:()=>d("read"),destroy(){y||(y=!0,A?.(),s.dispose(),l=null,f=null,i=null,p=null)}},A=e.session?.subscribeIdentity(h.destroy);try{return await c(),h}catch(F){throw h.destroy(),F}}import{z as Ln}from"zod";import{z as ge}from"zod";var _n=ge.record(ge.string().regex(/^[a-f0-9]{64}$/),ge.strictObject({at:ge.number(),text:ge.string()})),oe=2*1048576,Dn=100;function xn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function bn(e,n){let r=n===void 0?xn():n,s=new Map,l=0,y=!1,f=!1,i,p;async function a(c){if(!r)return null;let d;try{let h=await Promise.race([Promise.resolve().then(()=>r.getItem(c)),new Promise(A=>{d=setTimeout(()=>A(null),Dn)})]);return typeof h=="string"&&h.length<=oe&&new TextEncoder().encode(h).byteLength<=oe?h:null}catch{return null}finally{clearTimeout(d)}}function u(){if(p)return p;let c=(async()=>{try{let d=await a(`${e}:artifacts`);if(d)return _n.parse(JSON.parse(d))}catch{}return{}})();return p=c,c.finally(()=>{p===c&&(p=void 0)}),c}return{async readManifest(){return a(e)},writeManifest(c){!r||c.length>oe||new TextEncoder().encode(c).byteLength>oe||(i=c,!f&&(f=!0,Promise.resolve().then(async()=>{try{for(;i!==void 0;){let d=i;try{await r.setItem(e,d)}catch{}i===d&&(i=void 0)}}finally{f=!1}})))},async readArtifact(c){let d=(await u())[c],h=Date.now();return d&&h>=d.at&&h-d.at<=B.retentionMs?d.text:void 0},writeArtifact(c,d){if(!r||d.length>oe)return;let h=s.get(c);if(h?.text===d||!h&&s.size>=128)return;let A=new TextEncoder().encode(d).byteLength;l-(h?.byteLength??0)+A>oe||(s.set(c,{text:d,byteLength:A}),l+=A-(h?.byteLength??0),!y&&(y=!0,Promise.resolve().then(async()=>{try{for(;s.size;){let F=new Map(s);try{let T={...await u()},o=Date.now();for(let[S,P]of F)T[S]={at:o,text:P.text};let t={},I=2,b=0;for(let[S,P]of Object.entries(T).sort(([,v],[,D])=>D.at-v.at)){if(P.at>o||o-P.at>B.retentionMs)continue;let v=new TextEncoder().encode(JSON.stringify({[S]:P})).byteLength;I+v>oe||b>=128||(t[S]=P,I+=v,b++)}await r.setItem(`${e}:artifacts`,JSON.stringify(t))}catch{}finally{for(let[T,o]of F)s.get(T)===o&&(s.delete(T),l-=o.byteLength)}}}finally{y=!1}})))}}}var E=(e,n)=>new m(e,n),W=()=>performance.now(),Pn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function nr(e){let n=Ke.parse(e.scope),r=new te(e.origin??le);if(r.username||r.password||r.search||r.hash||r.pathname!=="/"||r.protocol!=="https:"&&!(r.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(r.hostname)))throw E("INVALID_URL","Configuration requires a trusted HTTPS origin");let s=new Set([r.origin,...(e.assetOrigins??[]).map(w=>{let g=new te(w);if(g.protocol!=="https:"||g.username||g.password||g.search||g.hash||g.pathname!=="/")throw E("INVALID_URL","Invalid configuration asset origin");return g.origin})]),l=e.fetch??globalThis.fetch.bind(globalThis),y=`/api/v1/configuration/${n.environmentId}`,f=`indiana:configuration:1:${r.origin}:${L(n)}`,i=bn(f,e.storage),p,a=0,u=0,c=!1,d=!1,h=0,A=0,F,T,o,t,I=0,b=new Set,S=new Set,P=new Map,v=new Map,D=0,V=!1;function M(){for(let w of b)try{w()}catch{}}function H(w){try{e.onError?.(w)}catch{}}let k=()=>!d&&!c&&!!p&&W()<a&&Date.now()<u;function J(){if(!k())throw E("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function de(w,g,R){if(!P.has(w)){for(;P.size&&(P.size>=128||D+R>B.maxCacheBytes);){let C=P.entries().next().value;D-=C[1].byteLength,P.delete(C[0])}P.set(w,{text:g,byteLength:R}),D+=R}}function Z(w,g,R){return cn(w,g,{signal:R,error:C=>E("INVALID_RESPONSE",C==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function fe(w){let g=new te(w,r);if(!s.has(g.origin)||g.username||g.password||g.hash||g.search)throw E("INVALID_URL","Configuration artifact origin is not trusted");return g.href}async function Fe(w,g,R=!1){let C=await l(fe(w),{method:"GET",credentials:"omit",redirect:"error",cache:R?"default":"no-cache",signal:g,headers:{}});if(C.status===429){let O=C.headers.get("retry-after")??"";I=/^\d+$/.test(O)?Number(O)*1e3:Math.max(0,Date.parse(O)-Date.now())||15e3}if(!C.ok&&C.status!==304)throw E(`CONFIGURATION_HTTP_${C.status}`,"Configuration synchronization failed");return C}function En(w,g,R){let C=Date.parse(w.headers.get("x-indiana-config-validated-at")??""),O=Date.parse(w.headers.get("x-indiana-config-valid-until")??""),_=Date.parse(w.headers.get("date")??""),N=w.headers.get("age"),G=N!==null&&/^\d+(\.\d+)?$/.test(N)?Number(N)*1e3:NaN;if(![C,O,_,G].every(Number.isFinite)||O<=C||O-C>B.maxControlAgeMs||C>_+1e3)throw E("INVALID_RESPONSE","Configuration freshness evidence is invalid");let x=Math.min(O-C,R.maxControlAgeSeconds*1e3,B.maxControlAgeMs)-Math.max(G,_-C,0)-(W()-g);if(x<=0)throw E("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return W()+x}function Ae(){if(clearTimeout(o),clearTimeout(t),d||!b.size)return;k()&&(t=setTimeout(()=>{k()?Ae():M()},Math.max(1,a-W())),Pn(t));let w=A?Math.min(15e3,1e3*2**Math.min(A-1,4)):Math.min(15e3,(p?.policy.refreshIntervalSeconds??15)*1e3);o=setTimeout(()=>{ie().catch(H)},Math.max(I,w*(.8+Math.random()*.2))),Pn(o)}async function ie(){if(d)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(F)return F;let w=h,g=new AbortController;T=g;let R=(async()=>{if(!V){V=!0;try{let he=await i.readManifest();if(he&&!p){let K=Oe.parse(JSON.parse(he));L(K.scope)===L(n)&&(p=K)}}catch{}}g.signal.throwIfAborted();let N=p,G=W(),U=await Fe(y,g.signal);U.status===304&&(!N||!U.headers.has("x-indiana-config-validated-at")||!U.headers.has("x-indiana-config-valid-until")||!U.headers.has("age"))&&(U=await Fe(y,g.signal));let x=U.status===304?N:Oe.parse(JSON.parse(await Z(U,B.maxManifestBytes,g.signal))),{generation:ae,...se}=x,z=U.headers.get("etag");if(L(x.scope)!==L(n)||Qe(se)!==ae||z!==`"${ae}"`&&z!==`W/"${ae}"`)throw E("INVALID_RESPONSE","Configuration scope or content identity changed");if(N&&(x.revision<N.revision||x.revision===N.revision&&x.generation!==N.generation))throw E("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[he,K]of Object.entries(N?.funnels??{})){let ee=x.funnels[he];if(ee&&(ee.controlRevision<K.controlRevision||ee.evaluationRevision<K.evaluationRevision||ee.controlRevision===K.controlRevision&&ee.state!==K.state||ee.evaluationRevision===K.evaluationRevision&&ee.evaluationMode!==K.evaluationMode))throw E("INVALID_RESPONSE","Funnel control revision changed identity")}let X=En(U,G,x.policy);if(g.signal.throwIfAborted(),w!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return p=x,a=X,u=Date.now()+Math.max(0,X-W()),c=!1,A=0,I=0,i.writeManifest(L(x)),M(),structuredClone(x)})(),C=setTimeout(()=>g.abort(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),B.initializationMs),O=new Promise((N,G)=>g.signal.addEventListener("abort",()=>G(g.signal.reason),{once:!0})),_=Promise.race([R,O]).catch(N=>{throw A++,(N instanceof Ln.ZodError||N instanceof SyntaxError||N instanceof m&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(N.code))&&(a=0,c=!0,M()),N}).finally(()=>{clearTimeout(C),F===_&&(F=void 0),Ae()});return F=_,_}async function ye(w){let g=w.sha256,R=se=>Ce(se,w);fe(w.url);let C=P.get(g);if(C){if(C.byteLength!==w.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return P.delete(g),P.set(g,C),C.text}let O=v.get(g);if(O){if(O.byteLength!==w.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return O.promise}let _=new AbortController;S.add(_);let N=h,G=(async()=>{try{let X=await i.readArtifact(g);if(X&&R(X)){if(_.signal.throwIfAborted(),d||N!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(g,X,w.byteLength),X}}catch{}_.signal.throwIfAborted();let se=await Fe(w.url,_.signal,!0),z=await Z(se,w.byteLength,_.signal);if(!R(z))throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(d||N!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(g,z,w.byteLength),i.writeArtifact(g,z),z})(),U=setTimeout(()=>_.abort(E("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),B.initializationMs),x=new Promise((se,z)=>_.signal.addEventListener("abort",()=>z(_.signal.reason),{once:!0})),ae=Promise.race([G,x]).finally(()=>{clearTimeout(U),S.delete(_),v.delete(g)});return v.set(g,{promise:ae,byteLength:w.byteLength}),ae}async function we(){return k()||await ie(),J(),p}async function me(w){let g,R=new Promise((C,O)=>{g=setTimeout(()=>O(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),B.initializationMs)});try{return await Promise.race([w(),R])}finally{clearTimeout(g)}}function pe(w,g){if(J(),p?.generation!==w.generation)throw E("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(g&&p.funnels[g]?.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function xe(w){let g=w.gb.features;if(!g)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let R=w.artifacts[g];if(R.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let C=je.parse(JSON.parse(await ye(R)));if(L(C.scope)!==L({projectId:n.projectId,environment:n.environment})||C.generation!==R.generation||C.remoteFeatures.some(O=>Object.hasOwn(C.features,O)))throw E("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return pe(w),{...C,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,a-W())).toISOString()}}async function Le(w,g){let R=await we(),C=R.funnels[w];g&&(!C||C.evaluationMode==="local"&&!C.versions[g])&&(F&&await F,R=await ie()),pe(R,w);let O=R.funnels[w];if(O.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let _=g??O.currentVersionId,N=O.versions[_];if(!N)throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(R.artifacts[N.artifact].formatVersion!==3)throw E("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[G,U]=await Promise.all([ye(R.artifacts[N.artifact]).then(x=>$e(JSON.parse(x))),O.evaluationMode==="local"?xe(R):void 0]);if(U&&L(Ye(G,U))!==L(N.dependencies))throw E("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return pe(R,w),{document:G,growth:U,versionId:_,control:structuredClone(O),manifest:structuredClone(R)}}async function Ve(w,g){try{return await Le(w,g)}catch(R){if(!(R instanceof m)||!(R.code==="CONFIGURATION_CHANGED"||R.code==="CONFIGURATION_HTTP_404"&&k()))throw R;let C=p?.generation;if(F&&await F,await ie(),R.code!=="CONFIGURATION_CHANGED"&&p?.generation===C)throw R;return Le(w,g)}}function Ne(){c=!0,M(),ie().catch(H)}let Ie=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ne()};function Fn(w){if(d)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return b.add(w),b.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ne),window.addEventListener("focus",Ie),document.addEventListener("visibilitychange",Ie)),Ae()),()=>{b.delete(w),b.size||(clearTimeout(o),clearTimeout(t),Me())}}function Me(){typeof window<"u"&&(window.removeEventListener("online",Ne),window.removeEventListener("focus",Ie),document.removeEventListener("visibilitychange",Ie))}return{scope:Object.freeze({...n}),refresh:ie,subscribe:Fn,assertFresh:J,assertFeatures(w){J();let g=p.gb.features;if(!g)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(w!==void 0&&p.artifacts[g].generation!==w)throw E("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return k()},get snapshot(){return p?structuredClone(p):null},get remainingMs(){return k()?Math.max(0,a-W()):0},async features(){return me(async()=>xe(await we()))},pageExperiments:()=>me(async()=>{let w=await we(),g=w.gb.pageExperiments;if(!g)throw E("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let R=w.artifacts[g];if(R.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let C=an.parse(JSON.parse(await ye(R)));if(C.environmentId!==n.environmentId||C.generation!==R.generation)throw E("INVALID_RESPONSE","Page experiment scope or generation changed");return pe(w),C}),funnel:(w,g)=>me(()=>Ve(w,g)),paywall:(w,g)=>me(async()=>{let R=await we(),C=R.paywalls?.[w];if(!C||!g&&C.state!=="published")throw E("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let O=g??C.currentVersionId,_=C.versions[O],N=_&&R.artifacts[_.artifact];if(!N||N.kind!=="paywall"||N.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let G=ze.parse(JSON.parse(await ye(N)));return pe(R),{document:G,versionId:O,version:_.version,control:structuredClone(C),manifest:structuredClone(R)}}),async localFunnel(w,g){let R=await me(()=>Ve(w,g));if(!R.growth)throw E("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:C,remoteFeatures:O,..._}=R.growth;return on({scope:{projectId:n.projectId,environment:n.environment},funnelId:w,versionId:R.versionId,evaluationMode:"local",evaluationRevision:R.control.evaluationRevision,document:R.document,payload:_})},assertFunnel(w,g,R){J();let C=p.funnels[w];if(!C||C.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable");if(C.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel now executes at Longplay");if(g!==void 0&&C.controlRevision!==g)throw E("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(R!==void 0&&!C.versions[R])throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!d){d=!0,h++,a=0,T?.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(o),clearTimeout(t),Me(),M(),b.clear();for(let w of S)w.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));P.clear(),D=0}}}}function Sn(e){let n=ue.test(e.apiKey);if(typeof window<"u"&&!n)throw new m("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!re.test(e.apiKey))throw new m("INVALID_TOKEN","A customer credential or server API key is required");return{async start(r){let s=Q.safeParse({...r,operation:"start"});if(!s.success||s.data.operation!=="start"||(n?s.data.customer!==void 0:s.data.customer===void 0))throw new m("INVALID_REQUEST","Invalid current Funnel start");let l=s.data,y=Y({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||y.identify(e.apiKey);let f=be(e,await y.request("funnels",l));if(!f.runToken)throw new m("INVALID_RESPONSE","Funnel start credentials are missing");if(f.run.source.id!==l.funnelId||f.run.locale!==(l.locale??"en")||!ce(f.run.parameters,l.parameters??{})||(l.customer?!f.customerId||l.customer.type==="id"&&f.customerId!==l.customer.value:f.customerId!==void 0))throw new m("INVALID_RESPONSE","Funnel start contract changed");return{...f,runToken:f.runToken}}finally{y.dispose()}}}}async function pr(e){e={...e};let n=e.configuration;if(!n)throw new m("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let r={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&L(r)!==L(e.scope))throw new m("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new m("EVALUATION_MODE","This Funnel uses Remote evaluation");let l=re.test(e.credential);if(l?!e.customerId:e.customerId!==void 0)throw new m("INVALID_REQUEST","Only Server-Key starts name their Customer");let y=Sn({...e,scope:r,apiKey:e.credential}),f=i=>{let p=Rn({...e,scope:r,runToken:i,...l?{serverKey:e.credential}:{}});return l||p.identify(e.credential),p};return{async start(i){let p=await y.start({...i,funnelId:e.funnelId,...l?{customer:{type:"id",value:e.customerId}}:{}}),a=f(p.runToken),u=await a.get();return{...p,...u,controller:a}},async restore(i){let p=f(i),a=await p.get();if(a.run.source.id!==e.funnelId)throw p.reset(),new m("SCOPE_MISMATCH","Run belongs to another Funnel");return{...a,runToken:i,controller:p}}}}export{Ee as a,Mn as b,be as c,_e as d,Xn as e,Nn as f,gn as g,lt as h,ce as i,yt as j,wt as k,Rn as l,jt as m,nr as n,Sn as o,pr as p};
|
|
@@ -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-KJ4KKOMF.js";import{a as _}from"./chunk-DSPLGTQI.js";import{a as P}from"./chunk-C76COHTI.js";import{bb as D}from"./chunk-DR66DI6C.js";import{s as C,v as O,x as j}from"./chunk-VSJOHWDL.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{ja as g}from"./chunk-
|
|
1
|
+
import{ja as g}from"./chunk-DR66DI6C.js";async function u(t,r,e){if(Number(t.headers.get("content-length"))>r)throw t.body?.cancel().catch(()=>{}),e.error("limit");let o=t.body?.getReader();if(!o)throw e.error("missing");let i=[],s=0,c=!1,a=()=>{},b=new Promise((n,f)=>{a=()=>f(e.signal?.reason),e.signal?.addEventListener("abort",a,{once:!0}),e.signal?.aborted&&a()});try{for(;;){let n=await Promise.race([o.read(),b]);if(n.done){c=!0;break}if(s+=n.value.length,s>r)throw e.error("limit");i.push(n.value)}}finally{e.signal?.removeEventListener("abort",a),c||o.cancel().catch(()=>{}),o.releaseLock()}e.signal?.throwIfAborted();let l=new Uint8Array(s),d=0;for(let n of i)l.set(n,d),d+=n.length;return l}async function m(t,r,e){return new TextDecoder("utf-8",{fatal:!0}).decode(await u(t,r,e))}function y(t,r){let e=typeof t=="string"?new TextEncoder().encode(t):t;return e.byteLength===r.byteLength&&g(e)===r.sha256}export{u as a,m as b,y as c};
|