@tinkerlandai/indiana-sdk 0.9.2 → 0.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +60 -4
  3. package/README.zh-CN.md +26 -3
  4. package/dist/{ai-usage-DMNKvCiq.d.ts → ai-usage-CUTIHAU0.d.ts} +5 -5
  5. package/dist/{api--Zf0gxfj.d.ts → api-BXu6TAoB.d.ts} +274 -127
  6. package/dist/{chunk-65TBYVCS.js → chunk-4C3HUZ3B.js} +1 -1
  7. package/dist/chunk-5ZWSFE2C.js +1 -0
  8. package/dist/chunk-6ZZUNGNE.js +1 -0
  9. package/dist/chunk-AOGPGUWE.js +1 -0
  10. package/dist/chunk-BOCKPUCM.js +2 -0
  11. package/dist/chunk-CLXORAOK.js +1 -0
  12. package/dist/chunk-HEGNIATD.js +1 -0
  13. package/dist/{chunk-WSVH6IQA.js → chunk-LMO3FXRT.js} +1 -1
  14. package/dist/chunk-M7JWCLYX.js +173 -0
  15. package/dist/chunk-MKV726FV.js +1 -0
  16. package/dist/chunk-QYECMZJJ.js +1 -0
  17. package/dist/chunk-UBMPFTGE.js +1 -0
  18. package/dist/chunk-UWFYBRM2.js +6 -0
  19. package/dist/chunk-XRXI3DMZ.js +1 -0
  20. package/dist/chunk-XSOEA4A5.js +4 -0
  21. package/dist/{configuration-sync-E98CqVwh.d.ts → configuration-sync-DuJl4SbM.d.ts} +64 -11
  22. package/dist/content-PQJYLAGQ.js +1 -0
  23. package/dist/coupon-fA1QujHt.d.ts +184 -0
  24. package/dist/{customer-page-9B97Qdt_.d.ts → customer-page-km5f1PJZ.d.ts} +86 -182
  25. package/dist/{funnel-local-client-BjPwXlQb.d.ts → funnel-local-client-BhHdi5_V.d.ts} +2843 -1187
  26. package/dist/funnel-node-evaluation-DuPmqIo1.d.ts +998 -0
  27. package/dist/funnel-resource-client-BoIhL_my.d.ts +9674 -0
  28. package/dist/funnel-runtime-host-3YUGXD3Y.js +1 -0
  29. package/dist/index.d.ts +1292 -9349
  30. package/dist/index.js +1 -1
  31. package/dist/native-shell.js +1 -1
  32. package/dist/openrouter.d.ts +3 -3
  33. package/dist/openrouter.js +1 -1
  34. package/dist/page.d.ts +3 -3
  35. package/dist/page.js +1 -1
  36. package/dist/paywall-CSAGKPCP.js +1 -0
  37. package/dist/popup.d.ts +7 -5
  38. package/dist/popup.js +1 -1
  39. package/dist/react-native.d.ts +23680 -173
  40. package/dist/react-native.js +1 -1
  41. package/dist/{screen-BITZ11jn.d.ts → screen-CvfI_L41.d.ts} +157 -4
  42. package/dist/{screen-renderer-A6VYE2QL.js → screen-renderer-VAMWY7ID.js} +1 -1
  43. package/dist/server.d.ts +355 -95
  44. package/dist/server.js +1 -1
  45. package/dist/visual-dom-OFB7BFFB.js +1 -0
  46. package/dist/visual.d.ts +1 -1
  47. package/dist/visual.js +1 -1
  48. package/package.json +1 -1
  49. package/dist/chunk-5O667MKA.js +0 -1
  50. package/dist/chunk-67A7I6MB.js +0 -1
  51. package/dist/chunk-CCQHYQ4P.js +0 -1
  52. package/dist/chunk-CPLLMISZ.js +0 -1
  53. package/dist/chunk-G23YNWWI.js +0 -1
  54. package/dist/chunk-L7LKE3MG.js +0 -173
  55. package/dist/chunk-NH2PTTNK.js +0 -2
  56. package/dist/chunk-PK5HYUHD.js +0 -1
  57. package/dist/chunk-SEW4YVR7.js +0 -1
  58. package/dist/chunk-UYSOTMY3.js +0 -1
  59. package/dist/chunk-YZSQDZXW.js +0 -4
  60. package/dist/content-3LOJVYQO.js +0 -1
  61. package/dist/errors-0TSUIbUi.d.ts +0 -115
  62. package/dist/funnel-runtime-host-NYHKQT6T.js +0 -1
  63. package/dist/paywall-ISCYOGPZ.js +0 -1
@@ -0,0 +1 @@
1
+ import{ea as E,fa as M,ga as j,ha as O,ia as T}from"./chunk-UWFYBRM2.js";import{i as w,oa as u}from"./chunk-HEGNIATD.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{a as u,b as Y,l as W,o as $}from"./chunk-UBMPFTGE.js";import{J as Q,Ma as K,a as J,b as H,c as z,d as U,e as B,f as G,g as j,ja as i,la as L}from"./chunk-UWFYBRM2.js";import{oa as a}from"./chunk-HEGNIATD.js";import{a as M}from"./chunk-G56XGVMS.js";var x=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new a("INVALID_STATE","Installation sequence exhausted");return t+1},me=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function V(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new a("INVALID_STATE","Installation journal is invalid");return e({...n})})}function X(t,e,n){let r=null,d=0,p=0,c=0,m=Promise.resolve();if(t&&(!n||M.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new a("SCOPE_MISMATCH","Push installation belongs to another scope");let A=()=>{if(!t)throw new a("NOT_CONFIGURED","Configure this client's native Push host first");return t},h=o=>{if(o!==d)throw new a("IDENTITY_CHANGED","Identity changed during Push operation")};async function T(o){let s=A();if(!s.sha256&&!globalThis.crypto?.subtle)throw new a("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let l=s.sha256?await s.sha256(Uint8Array.from(o,f=>f.charCodeAt(0))):await me(o);if(!/^[a-f0-9]{64}$/.test(l))throw new a("INVALID_STATE","Push credential digest is invalid");return l}function C(o){let s=B.parse(o);if(s.installationId.toLowerCase()!==A().installationId.toLowerCase())throw new a("INVALID_RESPONSE","Push response belongs to another installation");return s}async function R(o,s){let l=A(),f={installationId:l.installationId,publicKey:l.publicKey,issuedAt:new Date().toISOString(),...s},g=await l.sign(G(o,l.scope,f));return{...f,signature:g}}let k=(o,s,l)=>e.requestWithCredential?e.requestWithCredential(o,s,l):e.request(o,s);async function S(){let o=A(),s=d,l=r?await(e.session?.access()??r):null,f=V(o,y=>y),g;if(f.detachSeq!==null){let y=f.detachSeq,b=J.parse(await R("detach",{sequence:y,platform:o.platform}));try{let w=await e.request("push/installations/detach",{...o.scope,...b},"POST",{installationDetach:!0});if(!w||typeof w!="object"||!("installation"in w))throw new a("INVALID_RESPONSE","Push detach acknowledgement is invalid");let _=C(w.installation);if(_.bound||_.identitySeq!==y)throw new a("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(w){if(w instanceof a&&w.status===404)g=w;else if(!(w instanceof a)||w.status!==412)throw w}g||V(o,w=>({...w,detachSeq:w.detachSeq===y?null:w.detachSeq}))}if(h(s),!l){if(g)throw g;return null}let E=i.bindPushInstallation,N=E.request.parse(await R("bind",{sequence:c,platform:o.platform,credentialDigest:await T(l)}));h(s);let D=E.response.parse(await k(E.path,N,l));h(s);let v=C(D.installation);if(!v.bound||v.identitySeq!==c)throw new a("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return g&&f.detachSeq!==null&&c>f.detachSeq&&V(o,y=>({...y,detachSeq:y.detachSeq===f.detachSeq?null:y.detachSeq})),v}async function P(){A();let o=d,s=r?await(e.session?.access()??r):null;if(!s)throw new a("NOT_IDENTIFIED","Identify before reading this installation");let l=i.readPushInstallation,f=l.request.parse(await R("read",{credentialDigest:await T(s)}));h(o);let g=l.response.parse(await k(l.path,f,s));return h(o),C(g.installation)}function O(o=S){let s=m.catch(()=>{}).then(o);return m=s,s.catch(l=>{try{t?.onError?.(l instanceof Error?l:new Error("Push synchronization failed"))}catch{}}),s}async function q(o,s,l){let f=A(),g=s.identity,E=s.observation,N=r?await(e.session?.access()??r):null;if(h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");if(!N)throw new a("NOT_IDENTIFIED","Identify before recovering a Push address");if(!o.connectionId||!o.kind||!o.token||!["granted","provisional"].includes(o.permission))throw new a("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await O(async()=>{if(h(g),await S(),h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");let D=V(f,_=>l?_:{..._,addressSeq:x(_.addressSeq)}),y=await R(l?"recovery_confirm":"recovery_request",{...o,sequence:D.addressSeq,credentialDigest:await T(N),...l?{challenge:l}:{}}),b=l?z.parse(y):H.parse(y);if(h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");let w=await k(`push/installations/recovery/${l?"confirm":"request"}`,b,N);if(h(g),E!==p||V(f,_=>_).addressSeq!==D.addressSeq)throw new a("INVALID_STATE","Push observation changed during recovery");if(l){let _=i.updatePushAddress.response.parse(w),F=C(_.installation);if(!F.bound||F.identitySeq!==c||F.addressSeq!==D.addressSeq||F.connectionId!==o.connectionId||F.addressStatus!=="active")throw new a("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return F}if(!w||typeof w!="object"||!("recovery"in w))throw new a("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return U.parse(w.recovery)})}return{recoveryObserver(){A();let o={identity:d,observation:++p};return{async request(s){return U.parse(await q(s,o))},async confirm(s,l){return B.parse(await q(l,o,s))}}},identify(o){if(!t)return;c=V(t,l=>({...l,identitySeq:x(l.identitySeq)})).identitySeq,r=o,d++,p++},reset(){if(t)try{V(t,o=>{let s=x(o.identitySeq);return{...o,identitySeq:s,detachSeq:s}})}finally{r=null,d++,p++}},start(){t&&O()},async sync(){return await O()},read:P,async recover(){let o=A(),s=d,l=c;return p++,await O(async()=>{h(s);let f=await P();return h(s),c=V(o,E=>{if(E.identitySeq!==l)throw new a("IDENTITY_CHANGED","A newer installation intent exists");return{...E,identitySeq:x(Math.max(E.identitySeq,f.identitySeq)),addressSeq:Math.max(E.addressSeq,f.addressSeq)}}).identitySeq,await S()})},tokenObserver(){A();let o=++p,s=d;return async l=>{if(o!==p||s!==d)return null;let f=A(),g=r?await(e.session?.access()??r):null;if(!g)throw new a("NOT_IDENTIFIED","Identify before registering a Push token");if(await O(),h(s),o!==p)return null;let E=V(f,y=>({...y,addressSeq:x(y.addressSeq)})),N=i.updatePushAddress,D=N.request.parse(await R("address",{...l,sequence:E.addressSeq,credentialDigest:await T(g)}));if(h(s),o!==p)return null;let v=N.response.parse(await k(N.path,D,g));return h(s),C(v.installation)}}}}function Z(t,e){return{messaging:{async preference(n){let r=i.readMessagingPreference;return r.response.parse(await t(r.path,r.request.parse({channel:n}))).preference},async setPreference(n){let r=i.setMessagingPreference;return r.response.parse(await t(r.path,r.request.parse(n))).preference}},push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){let n=i.readMessagingPreference;return n.response.parse(await t(n.path,{channel:"push"})).preference},async setPreference(n){let r=i.setMessagingPreference;return r.response.parse(await t(r.path,r.request.parse({...n,channel:"push"}))).preference}}}}function ee(t,e,n={}){let r=!!t.session.peek(),d=new Set,p=c=>{for(let m of d)try{m(c)}catch{}};return t.session.subscribeIdentity(()=>{r=!!t.session.peek(),p(r),n.afterChange?.()},()=>{r=!1,e()}),{isIdentified:()=>r,methods:{subscribeIdentity(c){return d.add(c),()=>{d.delete(c)}},identify(c){let m=typeof c=="string"?c:c.accessToken;if(!j.test(m))throw new a("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(m),t.identify(c)},reset(){try{n.beforeReset?.()}finally{t.reset()}}}}}function I(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new a("INVALID_REQUEST","Customer requests use the verified session identity")}function te(t){return{async checkEntitlement(e){I(e);let n=i.checkEntitlement;return u(t,n,e)},async readHoldings(e={}){let n=i.readHoldings;return u(t,{...n,request:n.request.omit({customerId:!0})},e)}}}function ne(t){return{async readLedger(e){let n=i.readLedger;return u(t,n,{query:e})},async readCreditStatement(e){I(e);let n=i.readCreditStatement;return u(t,n,e)},async quoteBalance(e){I(e);let n=i.quoteBalance;return u(t,n,{command:e})}}}function re(t){return{async setupPayment(e){I(e);let n=i.setupPayment;return u(t,n,e)},async readPaymentSetup(e){I(e);let n=i.readPaymentSetup;return u(t,n,e)},async readBillingInvoice(e){I(e);let n=i.readBillingInvoice;return u(t,n,e)},async readBillingControls(e={}){I(e);let n=i.readBillingControls;return u(t,n,e)},async prepareBillingAuthorization(e){I(e);let n=i.prepareBillingAuthorization;return u(t,n,e)},async confirmBillingAuthorization(e){I(e);let n=i.confirmBillingAuthorization;return u(t,n,e)},async setBillingCoupons(e){I(e);let n=i.setBillingCoupons;return u(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){I(e);let n=i.revokeBillingAuthorization;return u(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){I(e);let n=i.listBillingInvoices;return u(t,n,e)},async confirmBillingAdjustment(e){I(e);let n=i.confirmBillingAdjustment;return u(t,n,e)}}}function ie(t){return{async previewUpdate(e){I(e);let n=i.previewUpdate;return u(t,n,e)},async update(e){I(e);let n=i.update;return u(t,n,e)},async readSubscriptionUpdate(e){I(e);let n=i.readSubscriptionUpdate;return u(t,n,e)},async restoreNativePurchase(e){I(e);let n=i.restoreNativePurchase;return u(t,n,e)},async previewAttach(e){I(e);let n=i.previewAttach;return u(t,n,e)},async attach(e){I(e);let n=i.attach;return u(t,n,e)},async readSubscriptionOperation(e){I(e);let n=i.readSubscriptionOperation;return u(t,n,e)}}}function oe(t){return{async redeemReward(e){return I(e),(await u(t,i.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return I(e),(await u(t,i.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return I(e),(await u(t,i.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let r=await u(t,i.redeemCoupon,{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await u(t,i.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await u(t,i.listOffers,{},{response:"Invalid offers response"})).offers}}}function se(t){return{...te(t),...ne(t),...re(t),...ie(t),...oe(t)}}function ae(t){return{async resolveContent(e){I(e);let n=i.resolveContent;return u(t,n,e)},async resolvePaywall(e){I(e);let n=i.resolvePaywall;return u(t,n,e)},async resolveOffering(e){I(e);let n=i.resolveOffering;return u(t,n,e)}}}var ce=t=>new TextEncoder().encode(JSON.stringify(t)).length,ue=16384;function de(t,e){let n=0,r,d=S=>{r={config:structuredClone(S),until:Date.now()+3e4}},p=[],c=null,m;function A(){if(!e())throw new a("NOT_IDENTIFIED","Call identify before using Features or events")}function h(){m||!p.length||(m=setTimeout(()=>{m=void 0,C().catch(()=>{}).finally(h)},5e3),typeof m=="object"&&"unref"in m&&m.unref())}function T(S,P={},O={}){if(A(),r&&Date.now()<r.until&&!Q(r.config,S))return;k();let q=i.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:S,properties:P,...O}]}).events[0];if(ce({events:[q]})>ue)throw new a("INVALID_REQUEST","Event exceeds the delivery size limit");if(p.length>=500)throw new a("EVENT_QUEUE_FULL","Flush pending events before tracking more");p.push(structuredClone(q)),h()}async function C(S=!1){if(A(),c)return c;let P=n,O=(async()=>{let q={inserted:0,duplicates:0,rejected:0,skipped:0},o=p.length;for(;o&&P===n;){let s=[];for(let g of p.slice(0,Math.min(o,100))){if(s.length&&ce({events:[...s,g]})>ue)break;s.push(g)}let l=i.trackEvents,f=await u(t,l,{events:s},void 0,{keepalive:S});if(P!==n)throw new a("IDENTITY_CHANGED","Event identity changed during delivery");if(f.inserted+f.duplicates+f.rejected+f.skipped!==s.length)throw new a("INVALID_RESPONSE","Incomplete event acknowledgement");d(f.analyticsConfig),p.splice(0,s.length),o-=s.length,q.inserted+=f.inserted,q.duplicates+=f.duplicates,q.rejected+=f.rejected,q.skipped+=f.skipped}return q})();c=O;try{return await O}finally{c===O&&(c=null)}}let R;function k(){if(R||typeof document>"u")return;let S=()=>{document.visibilityState==="hidden"&&e()&&p.length&&C(!0).catch(()=>{})};document.addEventListener("visibilitychange",S),R=()=>document.removeEventListener("visibilitychange",S)}return{rememberConfiguration:d,track(S,P,O={}){return k(),T(S,P,O)},flush:C,reset(){n++,r=void 0,clearTimeout(m),m=void 0,p=[],c=null},detachVisibility(){R?.(),R=void 0}}}function pe(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}function ye(t){let e=pe(t),{merchandiseId:n,merchandise:r,...d}=t;return{...d,...e?{merchandise:e}:{}}}function le(t,e,n,r,d){if(d&&r&&(d.scope.projectId!==r.projectId||d.scope.environment!==r.environment))throw new a("SCOPE_MISMATCH","Configuration belongs to another App/environment");let p=0,c=new Set;function m(){if(!e())throw new a("NOT_IDENTIFIED","Call identify before using Features or events")}async function A(h={}){d||m();let T=p,C=!1,R=async()=>{if(C||T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");let v=i.getFeatures,y=d?{scope:{projectId:d.scope.projectId,environment:d.scope.environment},payload:await d.features()}:await u(t,v,{});if(T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");if(r&&(y.scope.projectId!==r.projectId||y.scope.environment!==r.environment))throw new a("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(y.payload.analyticsConfig),y},k=await R(),S=!0,P,O=v=>{try{h.onError?.(v)}catch{}},q=(v,y,b)=>{try{let w=pe(b);n.track(v,y,w?{merchandise:w}:{})}catch(w){O(w)}},o=Y({assertUsable:d?.assertFeatures,scope:k.scope,attributes:h.attributes,onError:h.onError,load:async()=>S?(S=!1,k.payload):(await R()).payload,evaluateRemote:async v=>{if(T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");let y=i.evaluateFeatures,b=await u(t,y,{...v,attributes:ye(v.attributes)});if(b.scope.projectId!==k.scope.projectId||b.scope.environment!==k.scope.environment)throw new a("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:b.generation,evaluatedAt:b.evaluatedAt,expiresAt:b.expiresAt,features:b.features,...b.merchandiseContext?{merchandiseContext:b.merchandiseContext}:{}}},onExperimentViewed:(v,y,b)=>q("Experiment Viewed",{experimentId:v.key,variationId:y.key},b),onFeatureUsage:(v,y,b)=>q("Feature Evaluated",{feature:v,value:y.value,source:y.source,ruleId:y.ruleId,...y.experimentResult?{variationId:y.experimentResult.key}:{}},b)}),s=o.refresh;function l(){clearTimeout(P),!d&&(C||T!==p||!o.expiresAt||(P=setTimeout(()=>{f().catch(O)},Math.min(2147483647,Math.max(1e3,Date.parse(o.expiresAt)-Date.now()))),typeof P=="object"&&"unref"in P&&P.unref()))}async function f(){try{return await s()}finally{l()}}let g=()=>{C||f().catch(O)},E=o.subscribe(l),N=d?.subscribe(()=>{!C&&d.fresh&&f().catch(O)});function D(){C||(C=!0,clearTimeout(P),typeof window<"u"&&window.removeEventListener("focus",g),E(),N?.(),o.reset(),c.delete(D))}c.add(D);try{await o.init(),(h.attributes?.merchandise||h.attributes?.merchandiseId)&&await o.refreshRemote()}catch(v){throw D(),v}return l(),!d&&typeof window<"u"&&window.addEventListener("focus",g),Object.assign(o,{refresh:f,destroy:D})}return{features:A,reset(h){p++,h();for(let T of c)T()}}}import{z as Ie}from"zod";function fe(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=Ie.object({funnelId:L.shape.id,funnelVersionId:L.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new a("INVALID_REQUEST","A valid Funnel source is required");let d=Object.freeze(r.data);function p(c){if("customerId"in c)throw new a("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in c&&c.funnelId!==void 0&&c.funnelId!==d.funnelId||"funnelVersionId"in c&&c.funnelVersionId!==void 0&&c.funnelVersionId!==d.funnelVersionId)throw new a("SCOPE_MISMATCH","The original Funnel source cannot change");return{...c,...d}}return{async claimCoupon(c,m=crypto.randomUUID()){let A=i.grantOffer,h=await u(t,A,p({couponId:c,requestId:m}));return{offer:h.offer,reason:h.reason}},async resolveOffering(c){let m=i.resolveOffering;return u(t,m,p(c))},async resolvePaywall(c){let m=i.resolvePaywall;return u(t,m,p(c))},async previewAttach(c){let m=i.previewAttach;return u(t,m,p(c))}}}function Pt(t){return he(t)}function he(t){let e=K(t),n=e.request,r=X(t.push,e,t.scope??t.configuration?.scope),d=ee(e,()=>{c.reset(p.reset),p.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start}),p=de(n,d.isIdentified),c=le(n,d.isIdentified,p,t.scope,t.configuration);return{session:e.session,...Z(n,r),...se(n),...ae(n),forFunnel(m){return fe(n,m)},async features(m={}){return c.features(m)},track(m,A,h={}){return p.track(m,A,h)},flush(){return p.flush()},...d.methods}}function Nt(t){if(!j.test(t.customerToken))throw new a("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new a("INVALID_REQUEST","An explicit App and environment scope is required");let e=$({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),d=W({...t,runToken:r.runToken});d.identify(t.customerToken);let p=r.run.instruction?.type==="evaluate_segment"?await d.get():r;return{...r,...p,controller:d}}}}export{Pt as a,he as b,Nt as c};
@@ -0,0 +1 @@
1
+ import{b as dn,c as mn,d as fn,e as pn}from"./chunk-5ZWSFE2C.js";import{$ as Ye,Aa as an,Ba as sn,Ea as un,I as Ge,Ja as ln,K as Je,Ka as cn,L as Be,La as te,M as je,Ma as Q,U as H,V as ze,W as q,X as Ke,Y as Ee,Z as L,_ as Qe,aa as $e,ba as We,ca as Ze,da as Xe,g as ie,ja as ne,ka as en,ma as we,na as nn,oa as tn,wa as rn,xa as on}from"./chunk-UWFYBRM2.js";import{ma as He,oa as l}from"./chunk-HEGNIATD.js";import{a as Me,e as ye}from"./chunk-G56XGVMS.js";import{b as ae}from"./chunk-LMO3FXRT.js";import{b as ge}from"./chunk-7DXL3LHT.js";import{e as Ue,h as qe}from"./chunk-3PZ4Y6UD.js";function Un(e){let n=null,t=null,f=0,u=0,g=!1,c=new Set,r=null,o=null,a=new Set,w=()=>{for(let m of a)try{m()}catch{}},d={attributes:ge.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(m,v)=>{!c.has(m)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(m,structuredClone(v),structuredClone(d.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(m,v)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(m),structuredClone(v),structuredClone(d.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?m=>e.saveStickyBucketAssignmentDoc(structuredClone(m)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},C=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function _(m,v=new Set){return c.has(m)?!r||!r.features[m]||["unknownFeature","cyclicPrerequisite"].includes(r.features[m].source):v.has(m)?!1:(v.add(m),(n?.features[m]?.rules??[]).some(S=>[...S.parentConditions??[],...(S.tracks??[]).flatMap(R=>R.experiment.parentConditions??[])].some(R=>_(R.id,v))))}let E=m=>{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 r?.expiresAt&&Date.parse(r.expiresAt)<=Date.now()&&(r=null,d.features=n.features),c.has(m)?!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now()?C():structuredClone(r.features[m]??C()):e.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!g||_(m)?C():structuredClone(qe(m,d))};async function F(){if(!n||!c.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(c.size)throw new Error("Remote Feature evaluation requires a server loader");return}let m=u;if(o?.revision===m)return o.loading;let v=f,S=n,R=[...c],P=(async()=>{let T=je.parse(await e.evaluateRemote({attributes:structuredClone(d.attributes),features:R}));if(!(v!==f||m!==u||S!==n)){if(e.assertUsable?.(S.generation),T.generation!==S.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(R.some(O=>!Object.hasOwn(T.features,O))||Object.keys(T.features).some(O=>!c.has(O)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!T.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=ge.parse({...d.attributes,...T.merchandiseContext}),g=!0}r=structuredClone(T),d.features={...S.features,...Object.fromEntries(Object.entries(r.features).map(([O,k])=>[O,{defaultValue:k.value}]))},w()}})();o={revision:m,loading:P};try{await P}finally{o?.loading===P&&(o=null)}}function i(){F().catch(m=>{try{e.onError?.(m)}catch{}})}async function s(){if(t)return t;let m=f,v=(async()=>{let S=await e.load(),R="remoteFeatures"in S?Je.parse(S):null,P=R??ye.parse(S);if(P.scope.projectId!==e.scope.projectId||P.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(m!==f)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===P.generation){let{evaluatedAt:O,expiresAt:k,...G}=n,{evaluatedAt:W,expiresAt:J,...Z}=P;if(L(G)!==L(Z))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=P.evaluatedAt,n.expiresAt=P.expiresAt,w(),(!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now())&&i(),structuredClone(n)}let T=new Set(R?.remoteFeatures??[]);if([...T].some(O=>Object.hasOwn(P.features,O)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in P&&!n.analyticsConfig.experimentViewsEnabled&&R?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),n=structuredClone(P),c=T,r=null,o=null,u++,d.features=n.features,d.savedGroups=Ue(n.savedGroups),d.trackedFeatureUsage={},w(),i(),structuredClone(n)})();t=v;try{return await v}finally{t===v&&(t=null)}}return{init:s,refresh:s,refreshRemote:F,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(m){return a.add(m),()=>{a.delete(m)}},setAttributes(m){let v=ge.parse(m);(d.attributes?.merchandise||d.attributes?.merchandiseId||m.merchandise||m.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=v,u++,g=!1,r=null,o=null,d.features=n?.features??{},d.trackedFeatureUsage={},w(),i()},evalFeature:E,isOn(m){return E(m).on},isOff(m){return E(m).off},getFeatureValue(m,v){let S=E(m).value;return structuredClone(S===null?v:S)},reset(){f++,u++,t=null,o=null,n=null,r=null,c.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),w()}}}function gn(e){let n,t,f=()=>new l("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),u=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,t=e.locks??globalThis.navigator?.locks,!n||!t||!globalThis.crypto?.subtle)throw f();let r=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??ae).href,e.runToken])),o=new Uint8Array(await crypto.subtle.digest("SHA-256",r));return"indiana.funnel.commands.v1."+Array.from(o,a=>a.toString(16).padStart(2,"0")).join("")});u.catch(()=>{});async function g(r){try{let o=await u;return await t.request(o,{mode:"exclusive"},()=>r(o))}catch(o){throw o instanceof l?o:f()}}function c(r){let o=n.getItem(r);if(o===null)return{revision:0,entry:null};if(o.length>1048576)throw f();let a=JSON.parse(o);if(!a||typeof a!="object"||!("revision"in a)||!("entry"in a)||!Number.isSafeInteger(a.revision)||Number(a.revision)<0)throw f();return{revision:Number(a.revision),entry:a.entry}}return{read:()=>g(c),write:(r,o)=>g(a=>{if(c(a).revision!==r)return null;if(!Number.isSafeInteger(r+1))throw f();return n.setItem(a,JSON.stringify({revision:r+1,entry:o})),r+1})}}async function he(e,n){let t=nn.safeParse(n);if(!t.success)throw new l("INVALID_RESPONSE","Funnel response contract changed");let f=t.data;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Funnel scope changed");return f}async function Ae(e,n,t){if(Number(e.headers.get("content-length"))>n)throw t.error("limit");let f=e.body?.getReader();if(!f)throw t.error("missing");let u=[],g=0;try{for(;;){t.signal?.throwIfAborted();let o=await f.read();if(o.done)break;if(g+=o.value.length,g>n)throw t.error("limit");u.push(o.value)}}finally{await f.cancel().catch(()=>{})}t.signal?.throwIfAborted();let c=new Uint8Array(g),r=0;for(let o of u)c.set(o,r),r+=o.length;return c}async function yn(e,n,t){return new TextDecoder("utf-8",{fatal:!0}).decode(await Ae(e,n,t))}function Ie(e,n){let t=typeof e=="string"?new TextEncoder().encode(e):e;return t.byteLength===n.byteLength&&Qe(t)===n.sha256}async function ve(e,n){let t=Ze.parse(n),{artifact:f,environmentId:u}=t.content,g=new te(e.baseUrl??ae).origin,c=new te(f.url,g);if(c.origin!==g||c.username||c.password||c.search||c.hash||c.pathname!==`/api/v1/configuration/${u}/artifacts/${f.sha256}`)throw new l("INVALID_RESPONSE","Public Paywall locator is not trusted");let r=new AbortController,o=setTimeout(()=>r.abort(),q.initializationMs);try{let a=await(e.fetch??globalThis.fetch)(c,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:r.signal});if(!a.ok||!a.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(a.headers.get("content-length"))>f.byteLength)throw new l("INVALID_RESPONSE","Public Paywall is unavailable");let w=await Ae(a,f.byteLength,{signal:r.signal,error:d=>new l("INVALID_RESPONSE",d==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Ie(w,f))throw new l("INVALID_RESPONSE","Public Paywall digest or size changed");return Xe(t,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(w)))}finally{clearTimeout(o)}}var Fe=(e,n)=>new l(e,n);function rt(e){return sn(e,Fe)}async function Ne(e,n,{predict:t=!0}={}){let f=n.instruction;if(f?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new l("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==f.environmentId)throw new l("SCOPE_MISMATCH","Evaluation environment changed");let u=null,g;if(t)try{let c=await e.funnel(n.source.id,n.source.versionId);g=c.manifest.generation,u=Tn(e,n,c)}catch{u=null}return g??=e.snapshot?.generation??(await e.refresh()).generation,{advance:{policyRevision:f.policyRevision,generation:g},prediction:u}}function Tn(e,n,t){let f=n.instruction;if(f?.type!=="evaluate_segment"||!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==f.policyRevision)return null;let{analyticsConfig:u,remoteFeatures:g,...c}=t.growth,r=rn({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:f.policyRevision,document:t.document,payload:ye.parse(c)}),o=On(r,t.document,{...n,...f}),a=o.steps.at(-1),w=o.boundary??(a?.result.port==="value"?{nodeId:a.nodeId,visit:n.visit+o.steps.length-1}:null);return w?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:w.nodeId,visit:w.visit,terminal:!o.boundary}:null}function On(e,n,t){return un(e,n,t,Fe)}import{z as B}from"zod";var wn=H.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 l("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),hn=B.strictObject({schemaVersion:B.literal(1),scope:Me,runId:B.uuid(),funnelId:B.uuid(),versionId:B.uuid(),command:wn.optional(),closeCommand:wn.refine(e=>e.operation==="close").optional(),purchase:B.strictObject({receiptId:B.uuid(),operationId:B.uuid(),generation:B.number().int().nonnegative()}).optional(),closed:B.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"),M=()=>new l("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Re=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function In(e){let n=0,t=null,f=o=>JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]),u=Promise.resolve();async function g(){let o=await e.read();if(!Number.isSafeInteger(o.revision)||o.revision<0)throw new l("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:o.revision,entry:o.entry===null?null:hn.parse(o.entry)}}function c(o){let a=u.then(o);return u=a.catch(()=>{}),a}async function r(o){for(let a=0;a<4;a++){let w=await g();if(w.entry&&t!==null&&f(w.entry)!==t)throw M();let d=o(w.entry,w.revision);if(Re(w.entry,d)){n=w.revision;return}let C=await e.write(w.revision,d);if(C!==null){if(!Number.isSafeInteger(C)||C<=w.revision)throw M();n=C;return}}throw M()}return{bind(o){let a=JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]);if(t!==null&&t!==a)throw M();t=a},async load(){let o=await g();return n=o.revision,t=o.entry?f(o.entry):null,o.entry},retain(o){let a=hn.parse(o),w=a.command;return!w||t!==null&&f(a)!==t?Promise.reject(M()):(t??=f(a),c(()=>r((d,C)=>{if(d&&!Re(f(d),f(a)))throw M();if(!d){if(C!==n&&w.operation!=="close")throw M();return a}if(!d.command)return{...d,command:w,...w.operation==="close"?{closed:!0}:{}};if(w.operation==="close"&&d.command.operation!=="close"){if(d.command.requestId===w.requestId||d.closeCommand&&!Re(d.closeCommand,w))throw M();return{...d,closeCommand:w,closed:!0}}if(!Re(d.command,w))throw M();return d})))},observePurchase(o,a,w){return c(()=>r((d,C)=>{if(!d&&C!==n||d&&f(d)!==f({...o,schemaVersion:1}))throw M();if(d?.purchase&&d.purchase.generation>a.generation)return d;if(d?.purchase&&d.purchase.generation===a.generation&&d.purchase.operationId!==a.operationId)throw M();return w?!d?.purchase||d.purchase.operationId!==a.operationId?d:d.command?{...d,purchase:void 0}:null:{schemaVersion:1,...o,...d,purchase:a}}))},settle(o){return c(()=>r(a=>a?a.command&&"requestId"in a.command&&a.command.requestId===o?a.closeCommand?{...a,command:a.closeCommand,closeCommand:void 0}:a.purchase?{...a,command:void 0}:null:a.closeCommand&&"requestId"in a.closeCommand&&a.closeCommand.requestId===o?{...a,closeCommand:void 0}:a:null))}}}function ft(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function se(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((u,g)=>se(u,n[g]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let t=Object.entries(e),f=Object.entries(n);return t.length===f.length&&t.every(([u,g])=>Object.hasOwn(n,u)&&se(g,Reflect.get(n,u)))}function vn(e){let n=null,t=0,f=!1,u,g=0,c=new Set;return{get view(){return n},get generation(){return t},get disposed(){return f},get customerToken(){return u},get readSequence(){return g},nextRead(){return++g},assertCurrent(r,o="Run identity changed during the request"){if(r!==t||f)throw new l("IDENTITY_CHANGED",o)},assertRun(r){if(n&&(r.id!==n.id||r.source.type!==n.source.type||r.source.id!==n.source.id||r.source.versionId!==n.source.versionId||r.locale!==n.locale||!se(r.parameters,n.parameters)))throw new l("INVALID_RESPONSE","Run version changed");if(e&&r.source.id!==e)throw new l("INVALID_RESPONSE","Run belongs to another Funnel")},publish(r,o,a,w,d){if(!(r.operation==="review"&&n&&n!==a&&o.run.revision<=n.revision)&&!(n&&o.run.revision===n.revision&&w!==void 0&&w<g)&&(r.operation==="review"&&!o.run.stopped&&["running","waiting"].includes(o.run.status)&&n&&o.run.nodeId===n.nodeId&&o.run.visit===n.visit&&o.run.revision===n.revision&&(o.run.screen=n.screen,(n.paywall?.quote?.operationId===o.review?.activeOperationId||!n.paywall?.quote&&o.review?.activeOperationId===null)&&(o.run.paywall=n.paywall)),!(n?.paywall&&o.run.paywall&&n.paywall.receiptId===o.run.paywall.receiptId&&(o.run.paywall.selectionGeneration??0)<(n.paywall.selectionGeneration??0)))){if(!n||o.run.revision>=n.revision)n=o.run;else if(!d)return;if(n)for(let C of c)try{C(structuredClone(n))}catch{}}},identify(r){if(!ie.test(r))throw new l("INVALID_TOKEN","Customer credential required");t++,u=r},subscribe(r){return c.add(r),()=>c.delete(r)},reset(){f=!0,t++,u=void 0,n=null,c.clear()}}}var re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function vt(e,n,t="A server API key is required"){if(typeof window<"u")throw new l("SERVER_ONLY",n);if(!re.test(e))throw new l("INVALID_TOKEN",t)}function Rt(e){let n=Q(e);return n.identify(e.apiKey),n}function Y(e){let{customerToken:n,...t}=e;return t}var _n=e=>!(e instanceof l)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function Rn({options:e,journal:n,state:t,call:f}){let u=null,g=null,c=!1,r={command:null,close:null},o=!1,a,w=null,d=n?n.load().then(i=>{if(t.disposed)throw new l("IDENTITY_CHANGED","Controller was reset during command restoration");if(w=i,!i)return;if(e.scope&&(i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Pending command belongs to another scope");if(a=i.purchase,c=i.closed===!0,!i.command)return;let s=H.parse(i.command);if(s.operation==="start"||s.operation==="get"||s.operation==="review")throw new l("COMMAND_STORAGE_INVALID","Stored mutation required");u=s,i.closeCommand&&(g=i.closeCommand,c=!0),s.operation==="close"&&(c=!0),o=!0}):Promise.resolve();d.catch(()=>{});async function C(i=u){if(n&&await d,!i)throw new l("INVALID_REQUEST","No command is pending");let s=i,m=t.generation;if(n){if(!t.view||!e.scope)throw new l("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await n.retain({schemaVersion:1,scope:e.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:Y(s)})}if(m!==t.generation||u!==s&&g!==s)throw new l("IDENTITY_CHANGED","Run changed before command dispatch");let v={...s,...t.customerToken?{customerToken:t.customerToken}:{}},S=o;o=!0;try{return await f(v,R=>{if(!R.settlement)throw new l("INVALID_RESPONSE","Exact command settlement is missing");if(R.settlement.requestId!==s.requestId)throw new l("INVALID_RESPONSE","Command settlement identity changed");if(m===t.generation&&(u===s||g===s)&&R.run.pendingRequest?.requestId!==s.requestId&&R.settlement.state==="settled"&&(!c||s.operation==="close"||R.settlement?.state==="settled"&&!["running","waiting"].includes(R.run.status))){let P=()=>m!==t.generation||u!==s&&g!==s?!1:(u===s&&(u=null),g===s&&(g=null),o=u!==null,w=null,!0);return n?n.settle(s.requestId).then(P):P()}return!1})}catch(R){throw m===t.generation&&u===s&&!S&&!_n(R)&&(n&&await n.settle(s.requestId),m===t.generation&&u===s&&(u=null,o=!1,w=null)),R}}function _(i){let s=H.parse(i);if(s.operation==="start"||s.operation==="get"||s.operation==="review")throw new l("INVALID_REQUEST","Mutation required");if(c&&s.operation!=="close"){if(u?.requestId===s.requestId)return F(s.requestId);throw new l("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(s.operation==="close"&&u?.operation!=="close"){if(c=!0,g&&JSON.stringify(Y(g))!==JSON.stringify(Y(s)))throw new l("COMMAND_PENDING","Retry the original Close");return g??=s,r.close?r.close:E(g,"close")}if(u){if(JSON.stringify(Y(u))!==JSON.stringify(Y(s)))throw new l("COMMAND_PENDING","Retry the original command before sending another");if(r.command)return r.command}else u=s,o=!1;return E(u,"command")}function E(i,s){let m=C(i);r[s]=m;let v=()=>{r[s]===m&&(r[s]=null)};return m.then(v,v),m}async function F(i){let s=await f({operation:"get",settlementRequestId:i,...t.customerToken?{customerToken:t.customerToken}:{}});if(s.settlement?.requestId!==i)throw new l("INVALID_RESPONSE","Exact command settlement is missing");return s.settlement.state==="settled"&&(n&&await n.settle(i),u?.requestId===i&&(u=null,o=!1),g?.requestId===i&&(g=null)),s}return{ready:d,get pending(){return u},get closing(){return g},get closeRequested(){return c},get inFlight(){return r.command},get closeFlight(){return r.close},get purchase(){return a},assertBinding(i){if(w&&(i.run.id!==w.runId||i.run.source.id!==w.funnelId||i.run.source.versionId!==w.versionId))throw new l("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(i,s,m,v){n?.bind({scope:s.scope,runId:s.run.id,funnelId:s.run.source.id,versionId:s.run.source.versionId}),n&&!e.scope&&(e.scope=s.scope);let S=s.run.paywall,R=S??s.purchase,P=R?.operation,T=s.settlement&&(!S||S.purchaseRequestId===s.settlement.requestId)&&(!a||a.operationId===s.settlement.operationId)?s.settlement:void 0,O=P?.operationId??R?.quote?.operationId??T?.operationId,k=R?.receiptId??T?.receiptId,G=S?.selectionGeneration??a?.generation??0;if(n&&O&&k&&i.operation!=="review"&&(!t.view||s.run.revision>=t.view.revision)&&(v===void 0||v>=t.readSequence)&&(!a||G>=a.generation)){let W={receiptId:k,operationId:O,generation:G},J=P?.status==="complete"||R?.canReselect===!0;return n.observePurchase({scope:s.scope,runId:s.run.id,funnelId:s.run.source.id,versionId:s.run.source.versionId},W,J).then(()=>{t.assertCurrent(m),J?a?.operationId===W.operationId&&(a=void 0):a=W})}},stop(){c=!0},submit:_,executePending:C,settle:F,reset(){u=null,g=null,r.close=null,o=!1,r.command=null}}}function Pn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new l("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!re.test(e.serverKey)))throw new l("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new l("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let n=Q({...e,session:void 0,...e.serverKey?{fetch:(i,s)=>{let m=new Headers(s?.headers),v=typeof s?.body=="string"?JSON.parse(s.body):null;return v!==null&&typeof v=="object"&&"customerToken"in v&&typeof v.customerToken=="string"&&v.customerToken.length>0||m.set(tn,e.serverKey),(e.fetch??globalThis.fetch)(i,{...s,headers:m})}}:{},...e.session?{fetch:async(i,s)=>{let m=await e.session.access(),v=typeof s?.body=="string"?JSON.parse(s.body):{};if(!v||typeof v!="object"||Array.isArray(v))throw new l("INVALID_REQUEST","Run command must be an object");return(e.fetch??globalThis.fetch)(i,{...s,body:JSON.stringify({...v,customerToken:m})})}}:{},timeoutMs:e.timeoutMs??35e3});n.identify(e.runToken);let t=vn(e.funnelId),f=e.session?.subscribeIdentity(()=>{t.reset(),n.reset()}),u=null,g=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?gn(e):void 0),c=g&&In(g),r=Rn({options:e,journal:c,state:t,call:o});async function o(i,s,m){let v=t.generation,S=()=>t.assertCurrent(v);c&&await r.ready,S();let R=t.view,P=we.parse(await he(e,await n.request("funnels",H.parse(i))));if(i.operation==="review"&&!P.review)throw new l("INVALID_RESPONSE","Historical projection is missing");if(S(),P.runToken&&P.runToken!==e.runToken)throw new l("INVALID_RESPONSE","Run credential changed");let T=i.operation==="get"?i.settlementRequestId:"requestId"in i&&i.operation!=="start"?i.requestId:void 0;if(T&&P.settlement?.requestId!==T)throw new l("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");r.assertBinding(P),t.assertRun(P.run);let O=r.observePurchase(i,P,v,m);if(O&&await O,!P.run.stopped&&["running","waiting"].includes(P.run.status)&&i.operation==="get"&&i.settlementRequestId)return P;let k=s?.(P),G=typeof k=="boolean"?k:k?await k:!1;return S(),["running","waiting"].includes(P.run.status)||r.stop(),t.publish(i,P,R,m,G),P}let a=r.submit,w=null,d=new WeakMap;function C(i){let s=d.get(i);if(s)return s;let m=E(i);return d.set(i,m),m}let _=!1;async function E(i){let s=await i;if(s.run.instruction?.type!=="evaluate_segment")return s;if(w)return w;_=!0;let m=t.generation,v=(async()=>{for(let S=0;S<32&&s.run.instruction?.type==="evaluate_segment";S++){if(r.pending||r.closeRequested)return s;let R=s.run;if(s.run.instruction?.type==="evaluate_segment"){let{advance:T}=await Ne(e.configuration,R,{predict:!1});if(m!==t.generation)throw new l("IDENTITY_CHANGED","Run identity changed during segment calculation");if(r.pending||r.closeRequested)return s;if(t.view&&(t.view.revision!==R.revision||t.view.visit!==R.visit||t.view.nodeId!==R.nodeId))return o({operation:"get",...t.customerToken?{customerToken:t.customerToken}:{}});let O=!0;Ne(e.configuration,R).then(({prediction:k})=>{O&&m===t.generation&&!r.closeRequested&&t.view?.id===R.id&&!t.view.stopped&&t.view.nodeId===R.nodeId&&t.view.visit===R.visit&&t.view.revision===R.revision&&(u=k)}).catch(()=>{});try{s=await a({operation:"commit_segment",requestId:en(R.id,R.visit,`segment:${R.revision}`),nodeId:R.nodeId,visit:R.visit,revision:R.revision,...T})}finally{O=!1,u=null}}}return s})();w=v;try{return await v}finally{w===v&&(w=null)}}let F={get configuration(){return _?e.configuration:void 0},get configurationReady(){return!0},get view(){return t.view?structuredClone(t.view):null},get pendingCommand(){let i=r.closing??r.pending;return i?structuredClone(Y(i)):null},get pendingCommands(){return[r.pending,r.closing].filter(i=>i!==null).map(i=>structuredClone(Y(i)))},get pendingPurchase(){return r.purchase?structuredClone(r.purchase):null},get prediction(){let i=t.view;return u&&i&&!i.stopped&&["running","waiting"].includes(i.status)&&i.id===u.runId&&i.nodeId===u.from.nodeId&&i.visit===u.from.visit&&i.revision===u.from.revision&&!r.closeRequested?structuredClone(u):null},settle:r.settle,get webViewUrl(){return"bundled"},resolvePaywall(i){return ve(e,i)},async pageExperiments(i,s=[]){let m=t.generation;t.assertCurrent(m);let v=t.view?.id;if(!v)throw new l("INVALID_REQUEST","Read the Run before its page experiments");let S=cn.parse(await n.request("funnels",ln.parse({operation:"page_experiments",release:i,usedReceiptIds:s,...t.customerToken?{customerToken:t.customerToken}:{}})));if(t.assertCurrent(m),S.runId!==v||S.scope.projectId!==e.scope?.projectId||S.scope.environment!==e.scope?.environment)throw new l("SCOPE_MISMATCH","Page experiment Run changed");return S},review(i){return o({operation:"review",...i?{receiptId:i}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,t.nextRead())},async get(i,s){c&&await r.ready,s??=r.purchase&&{receiptId:r.purchase.receiptId,operationId:r.purchase.operationId};let m=t.nextRead();return C(o({operation:"get",...i?{data:i}:{},...s?{purchase:s}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,m))},resume(i=t.view?.pendingRequest?.requestId){return i?r.closeRequested?F.settle(i):r.pending?.requestId===i?C(a(r.pending)):C(a({operation:"resume",requestId:i})):Promise.reject(new l("INVALID_REQUEST","No interrupted command is available"))},submit(i){return C(a(i))},retry(){return r.closeFlight?r.closeFlight:r.closing?r.executePending(r.closing):r.closeRequested&&r.pending?F.settle(r.pending.requestId):r.inFlight?C(r.inFlight):r.pending?C(a(r.pending)):Promise.reject(new l("INVALID_REQUEST","No command is pending"))},identify(i){t.identify(i),u=null,n.identify(e.runToken)},subscribe:t.subscribe,reset(){f?.(),t.reset(),r.reset(),u=null,n.reset()}};return F}import{ZodError as Dn}from"zod";function Sn(e,n,t,f){try{return e.parse(n)}catch(u){throw f&&u instanceof Dn?new l(t,f):u}}async function Pe(e,n,t,f={},u){let g=typeof f=="function"?{}:f,c=Sn(n.request,t,"INVALID_REQUEST",g.request),r=await e(n.path,c,n.method,u),o=typeof f=="function"?f:f.parseResponse;return o?o(n.response,r):Sn(n.response,r,"INVALID_RESPONSE",g.response)}async function Kt(e,n){if(!ie.test(n.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");let t=Q(e);if(!e.session)t.identify(n.customerToken);else if(e.session.peek()!==n.customerToken)throw new l("SCOPE_MISMATCH","Paywall credential does not match the shared session");let f=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}:{}}),u=null,g=!1,c=null,r=null,o=null,a=null,w=e.session?.subscribeIdentity(()=>{g=!0,t.dispose(),u=null,c=null,r=null,o=null});async function d(){if(g)throw new l("IDENTITY_CHANGED","Paywall is closed");let E=ne.resolvePaywall,F=await Pe(t.request,E,{...f,selector:u?{type:"version",versionId:u.id}:f.selector}),i={paywall:await ve(e,F.paywall)};if(g)throw new l("IDENTITY_CHANGED","Paywall is closed");if(n.paywallVersionId?i.paywall.id!==n.paywallVersionId:i.paywall.paywallId!==n.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(u&&(!dn(i.paywall,u)||i.paywall.paywallId!==u.paywallId))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return u=i.paywall,structuredClone(u)}async function C(E){if(!c)throw new l("INVALID_REQUEST","A quoted purchase is required");let F=E==="read"?ne.readSubscriptionOperation:ne.attach,i=await Pe(t.request,F,{operationId:c.operationId,...E==="read"?{}:{intent:E}});return mn(i.operation,{operationId:c.operationId,currency:f.commerce.currency},"The purchase operation changed"),r=pn(r,i.operation),structuredClone(r)}let _={get view(){return u?structuredClone(u):null},get quote(){return c?structuredClone(c):null},get operation(){return r?structuredClone(r):null},get webViewUrl(){return"bundled"},refresh:d,async preview(E){if(!u)throw new l("INVALID_REQUEST","Load the Paywall first");let F=u.document.buttons[E.actionId];if(F?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let i=Ge(F.product,E.selection,u.capabilities);if(!i)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let s=He(u.document.screen,i,E.selection,u.capabilities),m=ne.previewAttach.request.parse({funnelId:f.funnelId,funnelVersionId:f.funnelVersionId,requestId:E.requestId,plans:[{productVersionId:i,...Object.keys(s).length?{featureQuantities:s}:{}}],provider:f.commerce.provider,currency:f.commerce.currency,...E.offerId?{offerId:E.offerId}:{},...E.nativeOffer?{nativeOffer:E.nativeOffer}:{}}),v=JSON.stringify(m);if(o&&o!==v&&(!r||r.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(o===v){if(a)return a;if(c)return structuredClone(c)}o=v;let S=(async()=>{let R=ne.previewAttach,P=await Pe(t.request,R,m);return fn(P.quote,{productVersionId:i,featureQuantities:s,currency:f.commerce.currency,provider:f.commerce.provider},"The purchase quote changed its selected Product or presentment"),c=P.quote,r=null,structuredClone(c)})();a=S;try{return await S}finally{a===S&&(a=null)}},confirm:()=>C("confirm"),cancel:()=>C("cancel"),read:()=>C("read"),destroy(){w?.(),g=!0,t.dispose(),u=null,c=null,r=null,o=null}};return await d(),_}import{z as kn}from"zod";import{z as ce}from"zod";var xn=ce.record(ce.string().regex(/^[a-f0-9]{64}$/),ce.strictObject({at:ce.number(),text:ce.string()})),bn=2*1048576,Ln=100;function Vn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Cn(e,n){let t=n===void 0?Vn():n,f=Promise.resolve();async function u(c){if(!t)return null;let r;try{return await Promise.race([Promise.resolve().then(()=>t.getItem(c)),new Promise(o=>{r=setTimeout(()=>o(null),Ln)})])}catch{return null}finally{clearTimeout(r)}}async function g(){try{let c=await u(`${e}:artifacts`);if(c&&c.length<=bn)return xn.parse(JSON.parse(c))}catch{}return{}}return{async readManifest(){return u(e)},writeManifest(c){Promise.resolve().then(()=>t?.setItem(e,c)).catch(()=>{})},async readArtifact(c){let r=(await g())[c];return r&&Date.now()>=r.at&&Date.now()-r.at<=q.retentionMs?r.text:void 0},writeArtifact(c,r){t&&(f=f.catch(()=>{}).then(async()=>{let o=await g(),a=Date.now();o[c]={at:a,text:r};let w={},d=2,C=0;for(let[_,E]of Object.entries(o).sort(([,F],[,i])=>i.at-F.at)){if(E.at>a||a-E.at>q.retentionMs)continue;let F=new TextEncoder().encode(JSON.stringify({[_]:E})).byteLength;d+F>bn||C>=128||(w[_]=E,d+=F,C++)}await t.setItem(`${e}:artifacts`,JSON.stringify(w))}).catch(()=>{}))}}}var b=(e,n)=>new l(e,n),$=()=>performance.now(),En=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function ir(e){let n=Ke.parse(e.scope),t=new te(e.origin??ae);if(t.username||t.password||t.search||t.hash||t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw b("INVALID_URL","Configuration requires a trusted HTTPS origin");let f=new Set([t.origin,...(e.assetOrigins??[]).map(y=>{let p=new te(y);if(p.protocol!=="https:"||p.username||p.password||p.search||p.hash||p.pathname!=="/")throw b("INVALID_URL","Invalid configuration asset origin");return p.origin})]),u=e.fetch??globalThis.fetch.bind(globalThis),g=`/api/v1/configuration/${n.environmentId}`,c=`indiana:configuration:1:${t.origin}:${L(n)}`,r=Cn(c,e.storage),o,a=0,w=0,d=!1,C=!1,_=0,E=0,F,i,s,m,v=0,S=new Set,R=new Set,P=new Map,T=new Map,O=0,k=!1;function G(){for(let y of S)try{y()}catch{}}function W(y){try{e.onError?.(y)}catch{}}let J=()=>!C&&!d&&!!o&&$()<a&&Date.now()<w;function Z(){if(!J())throw b("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Te(y,p){let h=new TextEncoder().encode(p).byteLength;if(!P.has(y)){for(;P.size&&(P.size>=128||O+h>q.maxCacheBytes);){let I=P.entries().next().value;O-=new TextEncoder().encode(I[1]).byteLength,P.delete(I[0])}P.set(y,p),O+=h}}function Oe(y,p,h){return yn(y,p,{signal:h,error:I=>b("INVALID_RESPONSE",I==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function _e(y){let p=new te(y,t);if(!f.has(p.origin)||p.username||p.password||p.hash||p.search)throw b("INVALID_URL","Configuration artifact origin is not trusted");return p.href}async function Se(y,p,h=!1){let I=await u(_e(y),{method:"GET",credentials:"omit",redirect:"error",cache:h?"default":"no-cache",signal:p,headers:{}});if(I.status===429){let A=I.headers.get("retry-after")??"";v=/^\d+$/.test(A)?Number(A)*1e3:Math.max(0,Date.parse(A)-Date.now())||15e3}if(!I.ok&&I.status!==304)throw b(`CONFIGURATION_HTTP_${I.status}`,"Configuration synchronization failed");return I}function Fn(y,p,h){let I=Date.parse(y.headers.get("x-indiana-config-validated-at")??""),A=Date.parse(y.headers.get("x-indiana-config-valid-until")??""),D=Date.parse(y.headers.get("date")??""),N=y.headers.get("age"),U=N!==null&&/^\d+(\.\d+)?$/.test(N)?Number(N)*1e3:NaN;if(![I,A,D,U].every(Number.isFinite)||A<=I||A-I>q.maxControlAgeMs||I>D+1e3)throw b("INVALID_RESPONSE","Configuration freshness evidence is invalid");let x=Math.min(A-I,h.maxControlAgeSeconds*1e3,q.maxControlAgeMs)-Math.max(U,D-I,0)-($()-p);if(x<=0)throw b("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return $()+x}function be(){if(clearTimeout(s),clearTimeout(m),C||!S.size)return;J()&&(m=setTimeout(()=>{J()?be():G()},Math.max(1,a-$())),En(m));let y=E?Math.min(15e3,1e3*2**Math.min(E-1,4)):Math.min(15e3,(o?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{oe().catch(W)},Math.max(v,y*(.8+Math.random()*.2))),En(s)}async function oe(){if(C)throw b("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(F)return F;let y=_,p=new AbortController;i=p;let h=(async()=>{if(!k){k=!0;try{let pe=await r.readManifest();if(pe&&!o){let j=Ee.parse(JSON.parse(pe));L(j.scope)===L(n)&&(o=j)}}catch{}}p.signal.throwIfAborted();let N=o,U=$(),V=await Se(g,p.signal);V.status===304&&(!N||!V.headers.has("x-indiana-config-validated-at")||!V.headers.has("x-indiana-config-valid-until")||!V.headers.has("age"))&&(V=await Se(g,p.signal));let x=V.status===304?N:Ee.parse(JSON.parse(await Oe(V,q.maxManifestBytes,p.signal))),{generation:z,...K}=x,X=V.headers.get("etag");if(L(x.scope)!==L(n)||Ye(K)!==z||X!==`"${z}"`&&X!==`W/"${z}"`)throw b("INVALID_RESPONSE","Configuration scope or content identity changed");if(N&&(x.revision<N.revision||x.revision===N.revision&&x.generation!==N.generation))throw b("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[pe,j]of Object.entries(N?.funnels??{})){let ee=x.funnels[pe];if(ee&&(ee.controlRevision<j.controlRevision||ee.evaluationRevision<j.evaluationRevision||ee.controlRevision===j.controlRevision&&ee.state!==j.state||ee.evaluationRevision===j.evaluationRevision&&ee.evaluationMode!==j.evaluationMode))throw b("INVALID_RESPONSE","Funnel control revision changed identity")}let ke=Fn(V,U,x.policy);if(p.signal.throwIfAborted(),y!==_)throw b("CONFIGURATION_DISPOSED","Configuration scope changed");return o=x,a=ke,w=Date.now()+Math.max(0,ke-$()),d=!1,E=0,v=0,r.writeManifest(L(x)),G(),structuredClone(x)})(),I=setTimeout(()=>p.abort(b("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),q.initializationMs),A=new Promise((N,U)=>p.signal.addEventListener("abort",()=>U(p.signal.reason),{once:!0})),D=Promise.race([h,A]).catch(N=>{throw E++,(N instanceof kn.ZodError||N instanceof SyntaxError||N instanceof l&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(N.code))&&(a=0,d=!0,G()),N}).finally(()=>{clearTimeout(I),F===D&&(F=void 0),be()});return F=D,D}async function de(y){let p=y.sha256,h=z=>Ie(z,y);_e(y.url);let I=P.get(p);if(I&&h(I))return P.delete(p),P.set(p,I),I;if(T.has(p))return T.get(p);let A=new AbortController;R.add(A);let D=_,N=(async()=>{try{let X=await r.readArtifact(p);if(X&&h(X))return Te(p,X),X}catch{}A.signal.throwIfAborted();let z=await Se(y.url,A.signal,!0),K=await Oe(z,y.byteLength,A.signal);if(!h(K))throw b("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(C||D!==_)throw b("CONFIGURATION_DISPOSED","Configuration scope changed");return Te(p,K),r.writeArtifact(p,K),K})(),U=setTimeout(()=>A.abort(b("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),q.initializationMs),V=new Promise((z,K)=>A.signal.addEventListener("abort",()=>K(A.signal.reason),{once:!0})),x=Promise.race([N,V]).finally(()=>{clearTimeout(U),R.delete(A),T.delete(p)});return T.set(p,x),x}async function me(){return J()||await oe(),Z(),o}async function ue(y){let p,h=new Promise((I,A)=>{p=setTimeout(()=>A(b("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),q.initializationMs)});try{return await Promise.race([y(),h])}finally{clearTimeout(p)}}function le(y,p){if(Z(),o?.generation!==y.generation)throw b("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(p&&o.funnels[p]?.state!=="active")throw b("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function De(y){let p=y.gb.features;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let h=y.artifacts[p];if(h.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let I=Be.parse(JSON.parse(await de(h)));if(L(I.scope)!==L({projectId:n.projectId,environment:n.environment})||I.generation!==h.generation||I.remoteFeatures.some(A=>Object.hasOwn(I.features,A)))throw b("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return le(y),{...I,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,a-$())).toISOString()}}async function xe(y,p){let h=await me(),I=h.funnels[y];p&&(!I||I.evaluationMode==="local"&&!I.versions[p])&&(F&&await F,h=await oe()),le(h,y);let A=h.funnels[y];if(A.evaluationMode!=="local")throw b("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let D=p??A.currentVersionId,N=A.versions[D];if(!N)throw b("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(h.artifacts[N.artifact].formatVersion!==3)throw b("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[U,V]=await Promise.all([de(h.artifacts[N.artifact]).then(x=>We(JSON.parse(x))),A.evaluationMode==="local"?De(h):void 0]);if(V&&L($e(U,V))!==L(N.dependencies))throw b("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return le(h,y),{document:U,growth:V,versionId:D,control:structuredClone(A),manifest:structuredClone(h)}}async function Le(y,p){try{return await xe(y,p)}catch(h){if(!(h instanceof l)||!(h.code==="CONFIGURATION_CHANGED"||h.code==="CONFIGURATION_HTTP_404"&&J()))throw h;let I=o?.generation;if(F&&await F,await oe(),h.code!=="CONFIGURATION_CHANGED"&&o?.generation===I)throw h;return xe(y,p)}}function Ce(){d=!0,G(),oe().catch(W)}let fe=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ce()};function Nn(y){if(C)throw b("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return S.add(y),S.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ce),window.addEventListener("focus",fe),document.addEventListener("visibilitychange",fe)),be()),()=>{S.delete(y),S.size||(clearTimeout(s),clearTimeout(m),Ve())}}function Ve(){typeof window<"u"&&(window.removeEventListener("online",Ce),window.removeEventListener("focus",fe),document.removeEventListener("visibilitychange",fe))}return{scope:Object.freeze({...n}),refresh:oe,subscribe:Nn,assertFresh:Z,assertFeatures(y){Z();let p=o.gb.features;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(y!==void 0&&o.artifacts[p].generation!==y)throw b("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return J()},get snapshot(){return o?structuredClone(o):null},get remainingMs(){return J()?Math.max(0,a-$()):0},async features(){return ue(async()=>De(await me()))},pageExperiments:()=>ue(async()=>{let y=await me(),p=y.gb.pageExperiments;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let h=y.artifacts[p];if(h.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let I=an.parse(JSON.parse(await de(h)));if(I.environmentId!==n.environmentId||I.generation!==h.generation)throw b("INVALID_RESPONSE","Page experiment scope or generation changed");return le(y),I}),funnel:(y,p)=>ue(()=>Le(y,p)),paywall:(y,p)=>ue(async()=>{let h=await me(),I=h.paywalls?.[y];if(!I||!p&&I.state!=="published")throw b("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let A=p??I.currentVersionId,D=I.versions[A],N=D&&h.artifacts[D.artifact];if(!N||N.kind!=="paywall"||N.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let U=ze.parse(JSON.parse(await de(N)));return le(h),{document:U,versionId:A,version:D.version,control:structuredClone(I),manifest:structuredClone(h)}}),async localFunnel(y,p){let h=await ue(()=>Le(y,p));if(!h.growth)throw b("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:I,remoteFeatures:A,...D}=h.growth;return on({scope:{projectId:n.projectId,environment:n.environment},funnelId:y,versionId:h.versionId,evaluationMode:"local",evaluationRevision:h.control.evaluationRevision,document:h.document,payload:D})},assertFunnel(y,p,h){Z();let I=o.funnels[y];if(!I||I.state!=="active")throw b("FUNNEL_STOPPED","Funnel is paused or unavailable");if(I.evaluationMode!=="local")throw b("EVALUATION_MODE","This Funnel now executes at Indiana");if(p!==void 0&&I.controlRevision!==p)throw b("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(h!==void 0&&!I.versions[h])throw b("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!C){C=!0,_++,a=0,i?.abort(b("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(m),Ve(),G(),S.clear();for(let y of R)y.abort(b("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));P.clear(),O=0}}}}function An(e){let n=ie.test(e.apiKey);if(typeof window<"u"&&!n)throw new l("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!re.test(e.apiKey))throw new l("INVALID_TOKEN","A customer credential or server API key is required");let t=Q({...e,timeoutMs:e.timeoutMs??35e3});return e.session||t.identify(e.apiKey),{async start(f){let u=H.safeParse({...f,operation:"start"});if(!u.success||u.data.operation!=="start"||(n?u.data.customer!==void 0:u.data.customer===void 0))throw new l("INVALID_REQUEST","Invalid current Funnel start");let g=u.data,c=we.safeParse(await he(e,await t.request("funnels",g)));if(!c.success||!c.data.runToken)throw new l("INVALID_RESPONSE","Funnel start credentials are missing");let r=c.data;if(r.run.source.id!==g.funnelId||r.run.locale!==(g.locale??"en")||!se(r.run.parameters,g.parameters??{})||(g.customer?!r.customerId||g.customer.type==="id"&&r.customerId!==g.customer.value:r.customerId!==void 0))throw new l("INVALID_RESPONSE","Funnel start contract changed");return{...r,runToken:r.runToken}}}}async function hr(e){e={...e};let n=e.configuration;if(!n)throw new l("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let t={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&L(t)!==L(e.scope))throw new l("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new l("EVALUATION_MODE","This Funnel uses Remote evaluation");let u=re.test(e.credential);if(u?!e.customerId:e.customerId!==void 0)throw new l("INVALID_REQUEST","Only Server-Key starts name their Customer");let g=An({...e,scope:t,apiKey:e.credential}),c=r=>{let o=Pn({...e,scope:t,runToken:r,...u?{serverKey:e.credential}:{}});return u||o.identify(e.credential),o};return{async start(r){let o=await g.start({...r,funnelId:e.funnelId,...u?{customer:{type:"id",value:e.customerId}}:{}}),a=c(o.runToken),w=await a.get();return{...o,...w,controller:a}},async restore(r){let o=c(r),a=await o.get();if(a.run.source.id!==e.funnelId)throw o.reset(),new l("SCOPE_MISMATCH","Run belongs to another Funnel");return{...a,runToken:r,controller:o}}}}export{Pe as a,Un as b,he as c,Fe as d,rt as e,On as f,gn as g,ft as h,se as i,vt as j,Rt as k,Pn as l,Kt as m,ir as n,An as o,hr as p};