@tinkerlandai/indiana-sdk 0.7.0 → 0.8.0

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 (52) hide show
  1. package/CHANGELOG.md +6 -1
  2. package/README.md +11 -10
  3. package/README.zh-CN.md +16 -11
  4. package/dist/{ai-usage-BsrSG955.d.ts → ai-usage-Bigjb8MS.d.ts} +468 -274
  5. package/dist/chunk-2A6UYUFA.js +1 -0
  6. package/dist/chunk-3BQFJANQ.js +1 -0
  7. package/dist/chunk-3ENVRJE6.js +350 -0
  8. package/dist/chunk-A3N4ZZTM.js +7 -0
  9. package/dist/chunk-AE4CUTUE.js +1 -0
  10. package/dist/chunk-CXYOZSOF.js +1 -0
  11. package/dist/{chunk-4AWSZWZD.js → chunk-G2R56FKU.js} +1 -1
  12. package/dist/{chunk-6MO6Y24B.js → chunk-OVMNCZYC.js} +1 -1
  13. package/dist/{configuration-sync-Bvd956GL.d.ts → configuration-sync-VFbY1pCN.d.ts} +34 -35
  14. package/dist/content-K2HCZVC2.js +1 -0
  15. package/dist/{customer-page-B4LkIr5q.d.ts → customer-page-BrCZxcaQ.d.ts} +279 -6
  16. package/dist/funnel-runtime-host-HNZ47TZW.js +1 -0
  17. package/dist/{funnel-runtime-start-ChVYbLzV.d.ts → funnel-runtime-start-DKcTCRrd.d.ts} +1646 -1913
  18. package/dist/index.d.ts +13975 -13679
  19. package/dist/index.js +1 -1
  20. package/dist/native-shell.js +1 -1
  21. package/dist/openrouter.d.ts +3 -2
  22. package/dist/openrouter.js +1 -1
  23. package/dist/page.d.ts +9 -9
  24. package/dist/paywall-PD62B2AY.js +1 -0
  25. package/dist/popup.d.ts +3 -271
  26. package/dist/popup.js +1 -350
  27. package/dist/react-native.d.ts +8 -8
  28. package/dist/react-native.js +1 -1
  29. package/dist/{screen-iFngkxaL.d.ts → screen-BazUOjwM.d.ts} +168 -165
  30. package/dist/server.d.ts +5 -5
  31. package/dist/server.js +1 -1
  32. package/dist/src-4MRSESVS.js +1 -0
  33. package/dist/visual.d.ts +5 -2
  34. package/dist/visual.js +2 -2
  35. package/package.json +1 -7
  36. package/dist/chunk-3SONNXFG.js +0 -1
  37. package/dist/chunk-467Z5ISI.js +0 -11
  38. package/dist/chunk-4K25DELJ.js +0 -1
  39. package/dist/chunk-HD74AAFS.js +0 -1
  40. package/dist/chunk-J4RHVU3W.js +0 -1
  41. package/dist/chunk-NOFNOHUI.js +0 -1
  42. package/dist/chunk-QO4YQLZ4.js +0 -1
  43. package/dist/chunk-U6S6AZM6.js +0 -1
  44. package/dist/chunk-WCFVNF5D.js +0 -1
  45. package/dist/client-F6UPJMHR.js +0 -1
  46. package/dist/controls-XG46TKUU.js +0 -2
  47. package/dist/funnel-runtime-host-26QI2W3S.js +0 -1
  48. package/dist/iam.d.ts +0 -131
  49. package/dist/iam.js +0 -1
  50. package/dist/paywall-WKOHBYW7.js +0 -1
  51. package/dist/src-UHLPVD6E.js +0 -1
  52. package/dist/{errors-DrdTlPwf.d.ts → errors-BpCmukJr.d.ts} +1 -1
package/dist/server.d.ts CHANGED
@@ -1,9 +1,9 @@
1
+ export { I as IndianaError } from './errors-BpCmukJr.js';
1
2
  import 'zod';
2
- export { I as IndianaError } from './errors-DrdTlPwf.js';
3
- export { f as AiPricingOptions, d as AiTokenQuote, b as AiTokenUsage, a as AiUsageContext, g as AiUsageMiddlewareOptions, h as AiUsageRecord, i as aiPriceSnapshotSchema, j as aiTokenQuoteSchema, c as createAiPricing, k as createAiUsageMiddleware, l as createConfiguredAiPricing } from './ai-usage-BsrSG955.js';
4
- import './screen-iFngkxaL.js';
5
- export { j as FeatureClient, g as FeatureClientOptions, t as FunnelDecisionInput, u as FunnelDecisionTimeoutError, v as FunnelDecisionUsedInput, w as FunnelLocalEvaluation, x as FunnelLocalEvaluator, y as FunnelLocalEvaluatorOptions, z as FunnelLocalSession, A as FunnelLocalSessionOptions, k as FunnelNodeEvaluationContext, B as FunnelSignalInput, i as FunnelStartInput, C as IndianaServerOptions, L as LocalFunnelClient, m as LocalFunnelClientOptions, p as createFeatureClient, D as createFunnelCampaignClient, E as createFunnelDecisionClient, G as createFunnelLocalEvaluator, H as createFunnelOrchestrationClient, J as createFunnelStartClient, K as createGuestToken, M as createIndianaServer, q as createLocalFunnelClient, N as createNativeReceiptClient, O as createPaywallStartClient, Q as createSynchronizedFunnelLocalEvaluator, s as evaluateFunnelNode, T as renewFunnelRun } from './funnel-runtime-start-ChVYbLzV.js';
6
- export { C as ConfigurationSync, c as createConfigurationSync } from './configuration-sync-Bvd956GL.js';
3
+ export { f as AiPricingOptions, d as AiTokenQuote, b as AiTokenUsage, a as AiUsageContext, g as AiUsageMiddlewareOptions, h as AiUsageRecord, i as aiPriceSnapshotSchema, j as aiTokenQuoteSchema, c as createAiPricing, k as createAiUsageMiddleware, l as createConfiguredAiPricing } from './ai-usage-Bigjb8MS.js';
4
+ import './screen-BazUOjwM.js';
5
+ export { k as FeatureClient, h as FeatureClientOptions, u as FunnelDecisionInput, v as FunnelDecisionTimeoutError, w as FunnelDecisionUsedInput, x as FunnelLocalEvaluation, y as FunnelLocalEvaluator, z as FunnelLocalEvaluatorOptions, A as FunnelLocalSession, B as FunnelLocalSessionOptions, l as FunnelNodeEvaluationContext, C as FunnelSignalInput, j as FunnelStartInput, D as IndianaServerOptions, L as LocalFunnelClient, n as LocalFunnelClientOptions, q as createFeatureClient, E as createFunnelCampaignClient, G as createFunnelDecisionClient, H as createFunnelLocalEvaluator, J as createFunnelOrchestrationClient, K as createFunnelStartClient, M as createGuestToken, N as createIndianaServer, r as createLocalFunnelClient, O as createNativeReceiptClient, Q as createPaywallStartClient, T as createSynchronizedFunnelLocalEvaluator, t as evaluateFunnelNode, U as renewFunnelRun } from './funnel-runtime-start-DKcTCRrd.js';
6
+ export { C as ConfigurationSync, c as createConfigurationSync } from './configuration-sync-VFbY1pCN.js';
7
7
  import '@ai-sdk/provider';
8
8
  import 'zod/v4';
9
9
  import './growth-rules-B4YYy64R.js';
package/dist/server.js CHANGED
@@ -1 +1 @@
1
- import{a as G,b,c as de,d as k,e as me,f as fe,g as we,j as ye,k as qe,l as Ae,m as Re,n as Ce}from"./chunk-NOFNOHUI.js";import{a as Fe,b as Le,c as De,d as Oe}from"./chunk-4AWSZWZD.js";import{a as q}from"./chunk-QO4YQLZ4.js";import{Ce as ne,Ne as M,Oe as re,Pi as B,Qe as ae,fj as j,gj as oe,hj as ie,jj as _,kf as N,kj as ce,lf as C,li as o,mf as se,ok as ue,pk as pe,pl as le,re as V,ue as ee,we as te}from"./chunk-467Z5ISI.js";import{b as H,h as W}from"./chunk-3SONNXFG.js";import"./chunk-U6S6AZM6.js";import"./chunk-4K25DELJ.js";import"./chunk-S5TVMQRC.js";import{a}from"./chunk-6MO6Y24B.js";import{Mb as X}from"./chunk-HD74AAFS.js";import{b as J,q as Z}from"./chunk-RRII2DMC.js";import{d as $}from"./chunk-KQCTDXVD.js";function p(n,r){try{return n.parse(r)}catch{throw new a("INVALID_RESPONSE","Invalid gateway response")}}function Ie(n){let r=me(n),t=c=>{throw new a("INVALID_RESPONSE",c)};r.nodes.size!==n.topology.nodes.length&&t("Duplicate local node identity"),r.nodes.get(n.topology.entry)?.type!=="entry"&&t("A local Funnel must start at Entry");let e=new Set(["entry","condition","feature","split","end","output"]);for(let c of r.nodes.values()){if(!e.has(c.type))throw new a("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(c.type==="entry"&&c.id!==n.topology.entry&&t("Unexpected Entry node"),["entry","feature"].includes(c.type)&&!c.outputs.next&&t("Local next exit is unavailable"),c.type==="feature"){let u=c.resources.featureKey;(!u||!Object.hasOwn(n.evaluation.variables,c.writes.value)||!Object.hasOwn(r.features,u))&&t("Local Feature definition or declaration is unavailable")}if(c.type==="condition"){let u=n.conditions[c.id];(!u||!c.outputs.default||u.some((f,m)=>f.port!==`case:${m}`||!c.outputs[f.port]))&&t("Local Condition exits are unavailable")}if(c.type==="split"&&(!c.resources.experimentId||!Object.hasOwn(n.growth.experiments,c.resources.experimentId)||!c.outputs.notParticipating)&&t("Local Experiment definition or exit is unavailable"),c.type==="end"||c.type==="output"){let u=n.evaluation.terminals[c.id];if(!u)throw new a("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(c.outputs).length&&t("A terminal cannot have outgoing edges"),u.output?.type==="feature"&&!Object.hasOwn(r.features,u.output.featureKey)&&t("Terminal Feature definition is unavailable")}for(let u of Object.values(c.outputs))r.nodes.has(u)||t("Local target is unavailable")}let s=new Set,i=new Set;function l(c){if(i.has(c)&&t("Local graph contains a cycle"),!s.has(c)){i.add(c);for(let u of Object.values(r.nodes.get(c).outputs))l(u);i.delete(c),s.add(c)}}return l(n.topology.entry),s.size!==r.nodes.size&&t("Local graph contains unreachable nodes"),{evaluate(c){let u={},f=c.context;f.features=r.features,f.savedGroups=r.savedGroups;let m=()=>{f.attributes=te({declarations:n.evaluation.variables,attributes:c.attributes,parameters:c.parameters,answers:{},results:u,savedGroups:r.savedGroups})};m();let I=n.topology.entry,d=0;for(;;){let w=r.nodes.get(I);if(w.type==="end"||w.type==="output"){let y=n.evaluation.terminals[I],h=y.output,v=h?.type==="feature"?r.feature(h.featureKey,f):h?.type==="variable"?ne({source:"variable",key:h.key,...h.path?{path:h.path}:{}},{declarations:n.evaluation.variables,answers:{},results:u,parameters:c.parameters,attributes:c.attributes,savedGroups:r.savedGroups}):h?.value??null;return V(n.evaluation.outputSchema,v)||t("Local output does not match its declaration"),{outcome:y.outcome,value:v}}if(d++>=n.evaluation.maxTransitions)throw new a("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(w.type==="entry")I=w.outputs.next;else{let y=r.evaluate(I,f);if(w.type==="feature"){let h=w.writes.value,v=y.value??null;V(n.evaluation.variables[h],v)||t("Local Feature value does not match its declaration"),ee(n.evaluation.variables,{writes:w.writes},{[h]:v}),u[h]=v,m()}I=y.target}}}}}import{z as he}from"zod";function ge(n,r,t){let e=J.parse(n.attributes);if(["parameters","answers","results"].some(S=>Object.hasOwn(e,S)))throw new a("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let s=X.parse(n.parameters??{}),i=he.record(he.string(),Z).parse(n.stickyBucketAssignmentDocs??{});for(let[S,g]of Object.entries(i))if(S!==`${g.attributeName}||${g.attributeValue}`||!Object.hasOwn(e,g.attributeName)||$(e[g.attributeName])!==g.attributeValue)throw new a("INVALID_REQUEST","Sticky document identity does not match this session");let l=n.saveStickyBucketAssignmentDoc,c=n.onFeatureUsage,u=n.onExperimentViewed,f=n.onError,m=new Map,I=new Set,d={},w=Promise.resolve();function y(S){let g=w.then(()=>(t(),S()));return w=g.catch(()=>{}),g}function h(S){try{f?.(S)}catch{}}function v(S){try{let g=S();g&&typeof g.catch=="function"&&g.catch(h)}catch(g){h(g)}}async function L(){for(let[S,g]of m){if(t(),l)try{await l(structuredClone(g))}catch{throw new a("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}t(),m.delete(S)}}return{evaluate(S={}){let g=S.track===!0;return y(async()=>{let D=await r();t(D);let z=new Set(I),Q={...d},Y=new Map,T=[],ve={stickyBucketAssignmentDocs:structuredClone(i),saveStickyBucketAssignmentDoc(E){Y.set(`${E.attributeName}||${E.attributeValue}`,structuredClone(E))},...g?{trackedExperiments:z,trackedFeatureUsage:Q,onExperimentViewed(E,R){let U=structuredClone(E),Ee=structuredClone(R);u&&T.push(()=>u(structuredClone(U),structuredClone(Ee)))},onFeatureUsage(E,R){let U=structuredClone(R);c&&T.push(()=>c(E,structuredClone(U)))}}:{}},Se=D.program.evaluate({attributes:e,parameters:s,context:ve});t(D);for(let[E,R]of Y)i[E]=R,m.set(E,R);await L(),t(D),g&&(I=z,d=Q);for(let E of T)v(E);let O=D.configuration;return structuredClone({evaluationMode:"local",scope:O.scope,funnelId:O.funnelId,versionId:O.versionId,evaluationRevision:O.evaluationRevision,generation:O.growth.generation,...Se})})},flush:()=>y(L),get stickyBucketAssignmentDocs(){return t(),structuredClone(i)}}}var _e=6e4;function x(n){if(typeof window<"u")throw new a("SERVER_ONLY","Local Funnel sessions run on your backend");let r=H.parse(n.scope),t=n.funnelId,e=n.load,s,i,l,c=0,u=I=>Date.now()>=I.expiresAt;async function f(){if(i)return i;let I=c;s=void 0;let d=(async()=>{let w=await e();if(I!==c)throw new a("IDENTITY_CHANGED","Local evaluator was reset");if(w&&typeof w=="object"&&"evaluationMode"in w&&w.evaluationMode==="remote")throw p(_,w),new a("EVALUATION_MODE","This Funnel requires remote decide");let y=p(ce,w);if(I!==c)throw new a("IDENTITY_CHANGED","Local evaluator was reset");if(y.scope.projectId!==r.projectId||y.scope.environment!==r.environment||y.funnelId!==t)throw new a("SCOPE_MISMATCH","Local configuration scope changed");if(y.growth.scope.projectId!==r.projectId||y.growth.scope.environment!==r.environment||y.growth.expiresAt!==y.expiresAt)throw new a("INVALID_RESPONSE","GB configuration scope or expiry changed");let h=Math.min(Date.now()+_e,y.expiresAt?Date.parse(y.expiresAt):1/0);if(Date.now()>=h)throw new a("CONFIGURATION_EXPIRED","Refresh expired local rules");let v=JSON.stringify([r.projectId,r.environment,t,y.versionId,y.evaluationRevision,y.growth.generation]),L=[y.topology,y.conditions,y.evaluation,y.growth.features,y.growth.experiments,y.growth.savedGroups];if(l?.key===v&&!de(l.body,L))throw new a("INVALID_RESPONSE","Immutable local configuration identity changed");return l?.key!==v&&(l={key:v,body:L,program:Ie(y)}),s={key:v,configuration:y,expiresAt:h,program:l.program},s})();i=d;try{return await d}finally{i===d&&(i=void 0)}}function m(){return i??(s&&!u(s)?Promise.resolve(s):f())}return{session(I){let d=c;return ge(I,m,w=>{if(n.assertUsable?.(),d!==c)throw new a("IDENTITY_CHANGED","Local evaluator was reset");if(w&&(u(w)||s?.key!==w.key))throw new a("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await f()).configuration)},reset(){c++,s=void 0,i=void 0,l=void 0}}}function Ne(n,r){let t=n.snapshot?.generation,e=x({scope:{projectId:n.scope.projectId,environment:n.scope.environment},funnelId:r,load:()=>n.localFunnel(r),assertUsable:()=>n.assertFunnel(r)}),s=n.subscribe(()=>{let l=n.snapshot?.generation;n.fresh&&l!==t&&(t=l,e.refresh().catch(()=>{}))}),i=e.session;return Object.assign(e,{session(l){let c=i(l),u=c.evaluate;return Object.assign(c,{async evaluate(...f){return n.fresh||await n.refresh(),u(...f)}})},destroy(){s(),e.reset()}})}function be(n){if(typeof window<"u")throw new a("SERVER_ONLY","Secret API keys must stay on the backend");return{start:r=>ye(n,r)}}var F=class extends a{constructor(t,e){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,e);this.decisionId=t;this.decisionRequestId=e}decisionId;decisionRequestId};async function P(n,r,t,e){let{decisionId:s,requestId:i}=n,l=n,c=250;for(;;){if(l.decisionId!==s||l.requestId!==i||l.decision&&!b(l.decision,r))throw new a("INVALID_RESPONSE","Decision request or customer changed");if(l.decision)return l.decision;if(l.status==="failed")throw new a("DECISION_FAILED","Decision execution failed",503,i);if(Date.now()>=t)throw new F(s,i);if(await new Promise(u=>setTimeout(u,Math.min(c,t-Date.now()))),Date.now()>=t)throw new F(s,i);c=Math.min(1e3,c*2);try{l=await e(s,t)}catch(u){if(u instanceof a&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(u.code))continue;throw u}}}function K(n){if("remoteEval"in n)throw new a("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");if(typeof window<"u")throw new a("SERVER_ONLY","Funnel decisions are requested by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new a("INVALID_TOKEN","A server API key is required");let r,t,e=new Map;async function s(u,f){let m=u;m.status!=="pending"&&e.delete(m.decisionId);for(let I=0;I<32&&m.evaluation;I++){let d=m.evaluation;if(d.runId!==m.decisionId)throw new a("INVALID_RESPONSE","Local evaluation Run changed");let w=e.get(m.decisionId);if(!w&&d.type==="evaluate_segment"){let h=le.parse(await i({operation:"segment_configuration",funnelId:n.funnelId,versionId:d.versionId},f));if(h.configuration.scope.projectId!==n.scope.projectId||h.configuration.scope.environment!==n.scope.environment||h.configuration.funnelId!==n.funnelId||h.configuration.versionId!==d.versionId||h.configuration.evaluationRevision!==d.policyRevision)throw new a("SCOPE_MISMATCH","Original decision segment configuration changed");if(e.size>=128)throw new a("COMMAND_PENDING","Reconcile outstanding decisions first");w={operation:"commit_decision_segment",decisionId:m.decisionId,requestId:B(m.decisionId,d.visit,`segment:${d.revision}`),nodeId:d.nodeId,visit:d.visit,revision:d.revision,policyRevision:d.policyRevision,generation:h.configuration.growth.generation,...we(h.configuration,h.document,d)},e.set(m.decisionId,w)}if(!w){if(d.type!=="evaluate")throw new a("INVALID_RESPONSE","Unknown decision instruction");if((!t||t.versionId!==d.versionId||t.evaluationRevision!==d.policyRevision||t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())&&(t=_.parse(await i({operation:"configuration",funnelId:n.funnelId,versionId:d.versionId},f))),t.scope.projectId!==n.scope.projectId||t.scope.environment!==n.scope.environment||t.funnelId!==n.funnelId)throw new a("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(t.evaluationMode!=="local"||t.versionId!==d.versionId||t.evaluationRevision!==d.policyRevision)throw new a("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(e.size>=128)throw new a("COMMAND_PENDING","Reconcile outstanding Local decisions first");w={operation:"evaluate_decision",decisionId:m.decisionId,requestId:B(m.decisionId,d.visit,"evaluation"),nodeId:d.nodeId,visit:d.visit,revision:d.revision,receiptId:d.receiptId,policyRevision:d.policyRevision,generation:t.growth.generation,result:fe(t,d.nodeId,d)},e.set(m.decisionId,w)}let y=C.parse(await i(w,f));if(y.decisionId!==u.decisionId||y.requestId!==u.requestId)throw new a("INVALID_RESPONSE","Decision identity changed during local evaluation");e.delete(m.decisionId),m=y}return m}async function i(u,f,m=!1){let I=q({...n,fetch:(d,w)=>{let y=new Headers(w?.headers);return y.set("Accept-Encoding","identity"),m&&y.set("Prefer","respond-async"),(n.fetch??globalThis.fetch)(d,{...w,headers:y})},timeoutMs:Math.min(n.timeoutMs??1e4,f?Math.max(1,f-Date.now()):12e4)});return I.identify(n.apiKey),I.request("funnels",u)}async function l(u,f){let m=C.parse(await i(N.parse({operation:"read_decision",decisionId:u}),f));if(m.decisionId!==u)throw new a("INVALID_RESPONSE","Decision identity changed");return s(m,f)}async function c(u,f,m=!1){let I=N.options[0].parse({...u,operation:"decide",funnelId:n.funnelId}),d;try{d=C.parse(await i(I,f,m))}catch(w){throw w instanceof a&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(w.code)?new a("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",w.status,u.requestId):w}if(d.requestId!==u.requestId||d.decision&&!b(d.decision,I.customer))throw new a("INVALID_RESPONSE","Decision request or customer changed");return{response:await s(d,f),customer:I.customer}}return{local(){return r??=x({scope:n.scope,funnelId:n.funnelId,load:()=>i({operation:"local_configuration",funnelId:n.funnelId})})},async configuration(){let u=_.parse(await i({operation:"configuration",funnelId:n.funnelId}));if(u.scope.projectId!==n.scope.projectId||u.scope.environment!==n.scope.environment||u.funnelId!==n.funnelId)throw new a("SCOPE_MISMATCH","Configuration scope changed");return u},features(u={}){return G({...u,scope:n.scope,load:async()=>W.parse(await i({operation:"feature_config",funnelId:n.funnelId}))})},read:u=>l(u),async submit(u){return(await c(u,void 0,!0)).response},async decide(u){let f=Date.now()+3e4,m=await c(u,f);return P(m.response,m.customer,f,l)},async reportUsed(u){let f=se.parse(await i(N.parse({...u,operation:"report_used"})));if(f.decisionId!==u.decisionId||f.eventId!==u.eventId)throw new a("INVALID_RESPONSE","Usage receipt identity changed");return f}}}function ke(n){if(typeof window<"u")throw new a("SERVER_ONLY","Native receipts are verified by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new a("INVALID_TOKEN","Server API key required");let r=q({...n,timeoutMs:n.timeoutMs??35e3});return r.identify(n.apiKey),{async recover(t){let e=ue.parse(t);if(e.orderId!==e.receiptId)throw new a("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let s=e.nativeEvidence,i={requestId:e.requestId,customerToken:e.customerToken,purchaseIntentId:e.orderId,...s===null?{intent:"read"}:s.provider==="apple"?{provider:"apple",signedTransaction:s.signedTransaction}:{provider:"google",purchaseToken:s.purchaseToken}},l=o.restoreNativePurchase.response.parse(await r.request(o.restoreNativePurchase.path,i));if(l.operation.requestId!==e.requestId)throw new a("INVALID_RESPONSE","Native receipt request identity changed");let c=pe.parse({scope:l.scope,requestId:e.requestId,orderId:l.operation.orderId,receiptId:l.operation.orderId,orderStatus:l.operation.status,refunded:l.operation.refunded,...l.operation.completion===null?{}:{nativeCompletion:{orderId:l.operation.orderId,receiptId:l.operation.orderId,...l.operation.completion}}});if(c.requestId!==e.requestId||c.orderId!==e.orderId||c.receiptId!==e.receiptId||c.scope.projectId!==n.scope.projectId||c.scope.environment!==n.scope.environment)throw new a("INVALID_RESPONSE","Current order receipt scope changed");return c}}}import{z as xe}from"zod";var A=xe.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function Pe(n,r){let t=A.parse(n.inputTokens.total),e=A.parse(n.outputTokens.total),s=A.parse(n.inputTokens.cacheRead??0),i=A.parse(n.inputTokens.cacheWrite??0),l=A.parse(n.outputTokens.reasoning??0);if(s+i>t||l>e||n.inputTokens.noCache!==void 0&&A.parse(n.inputTokens.noCache)!==t-s-i||n.outputTokens.text!==void 0&&A.parse(n.outputTokens.text)!==e-l)throw new a("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:t-s-i,cache_read:s,cache_write:i,output:r==="output"?e:e-l,reasoning:r==="separate"?l:0,input_audio:0,output_audio:0}}function Te(n){if(typeof window<"u")throw new a("SERVER_ONLY","AI usage belongs on the trusted backend");if(!n.modelId||!["output","separate"].includes(n.reasoning))throw new a("INVALID_REQUEST","Model ID and reasoning pricing are required");async function r(e){await n.persist({context:e,modelId:n.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function t(e,s){let i={context:e,modelId:n.modelId,usage:s,tokens:null,quote:null,receipt:null,phase:"captured"};await n.persist(i);let l=n.mapTokens?n.mapTokens(s):Pe(s,n.reasoning),c=await n.pricing.quoteTokens({modelId:n.modelId,tokens:l});await n.persist({...i,tokens:l,quote:c,phase:"quoted"});let u=await n.pricing.trackTokens(n.client,{...e,quote:c});if(!u.receipt.accepted)throw new a("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await n.persist({...i,tokens:l,quote:c,receipt:u,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:e}){let s=await n.context(),i;try{i=await e()}catch(l){throw await r(s),l}return await t(s,i.usage),i},async wrapStream({doStream:e}){let s=await n.context(),i;try{i=await e()}catch(m){throw await r(s),m}let l=!1,c=!1,u=i.stream.getReader();async function f(){l||c||(c=!0,await r(s))}return{...i,stream:new ReadableStream({async pull(m){try{let{value:I,done:d}=await u.read();if(d){if(!l)throw await f(),new a("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");m.close();return}if(I.type==="finish"){if(l)throw new a("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");l=!0,await t(s,I.usage)}m.enqueue(I)}catch(I){try{await f()}finally{m.error(I),await u.cancel(I)}}},async cancel(m){try{await f()}finally{await u.cancel(m)}}})}}}}function Ue(n){if(typeof window<"u")throw new a("SERVER_ONLY","Funnel receipts are sent by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new a("INVALID_TOKEN","A server API key is required");let r=q(n);return r.identify(n.apiKey),{async signal(t){let e=M.parse({...t,operation:"signal"}),s=re.parse(await r.request("funnels",e));if(s.runId!==t.runId||s.eventId!==t.eventId||s.scope.projectId!==n.scope.projectId||s.scope.environment!==n.scope.environment)throw new a("INVALID_RESPONSE","Receipt identity changed");return s},async readResults(t){let e=M.parse({operation:"read_results",runId:t}),s=ae.parse(await r.request("funnels",e));if(s.runId!==t||s.scope.projectId!==n.scope.projectId||s.scope.environment!==n.scope.environment)throw new a("INVALID_RESPONSE","Result identity changed");return s}}}function Ve(n){if("remoteEval"in n)throw new a("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");if(typeof window<"u")throw new a("SERVER_ONLY","Campaign entry requires your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new a("INVALID_TOKEN","A server API key is required");let r=q({...n,timeoutMs:n.timeoutMs??35e3});return r.identify(n.apiKey),{async decide(t){let e=Date.now()+(n.timeoutMs??3e4),s=j.parse({...t,funnelId:n.funnelId,operation:"campaign_decide"}),i=q({...n,timeoutMs:Math.min(n.timeoutMs??35e3,Math.max(1,e-Date.now()))});i.identify(n.apiKey);let l=C.parse(await i.request("funnels",s));if(l.scope.projectId!==n.scope.projectId||l.scope.environment!==n.scope.environment)throw new a("SCOPE_MISMATCH","Campaign scope changed");return P(l,s.customer,e,(c,u)=>K({...n,timeoutMs:Math.min(n.timeoutMs??1e4,Math.max(1,u-Date.now()))}).read(c))},async start(t){let e=j.parse({...t,funnelId:n.funnelId,operation:"campaign_start"}),s=ie.parse(await r.request("funnels",e)),i=oe.parse("suppressed"in s?s:await k(n,s));if(i.scope.projectId!==n.scope.projectId||i.scope.environment!==n.scope.environment)throw new a("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in i)&&(i.run.source.id!==n.funnelId||!i.customerId||e.customer.type==="id"&&i.customerId!==e.customer.value))throw new a("INVALID_RESPONSE","Campaign Funnel or Customer changed");return i}}}function Ut(){if(typeof window<"u")throw new a("SERVER_ONLY","Guest identity is issued by your backend");let n=crypto.getRandomValues(new Uint8Array(32));return"gg_gc_"+btoa(String.fromCharCode(...n)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}function Vt(n){if(typeof window<"u")throw new a("SERVER_ONLY","Secret API keys must stay on your backend");let r=q(n);return r.identify(n.apiKey),{async listInvoiceTemplates(t={}){let e=o.listInvoiceTemplates;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewInvoice(t){let e=o.previewInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async createInvoice(t){let e=o.createInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageInvoice(t){let e=o.manageInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readInvoiceOperation(t){let e=o.readInvoiceOperation;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listInvoices(t){let e=o.listInvoices;return p(e.response,await r.request(e.path,e.request.parse(t)))},async getInvoice(t){let e=o.getInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async recordCouponRedemption(t){let e=o.recordCouponRedemption,s=e.request.safeParse(t);if(!s.success)throw new a("INVALID_REQUEST","Invalid Coupon redemption facts");return p(e.response,await r.request(e.path,s.data))},async getFeatures(t={}){let e=o.getFeatures;return p(e.response,await r.request(e.path,e.request.parse(t),e.method))},async evaluateFeatures(t){let e=o.evaluateFeatures;return p(e.response,await r.request(e.path,e.request.parse(t),e.method))},async trackEvents(t){let e=o.trackEvents;return p(e.response,await r.request(e.path,e.request.parse(t),e.method))},async resolvePaywall(t){let e=o.resolvePaywall;return p(e.response,await r.request(e.path,e.request.parse(t)))},async resolveOffering(t){let e=o.resolveOffering;return p(e.response,await r.request(e.path,e.request.parse(t)))},async checkEntitlement(t){let e=o.checkEntitlement;return p(e.response,await r.request(e.path,e.request.parse(t)))},async setupPayment(t){let e=o.setupPayment;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readPaymentSetup(t){let e=o.readPaymentSetup;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewSubscriptionBatch(t){let e=o.previewSubscriptionBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async confirmSubscriptionBatch(t){let e=o.confirmSubscriptionBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSubscriptionBatch(t){let e=o.readSubscriptionBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async abandonSubscriptionBatch(t){let e=o.abandonSubscriptionBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageSubscriptionTrial(t){let e=o.manageSubscriptionTrial;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSubscriptionTrial(t){let e=o.readSubscriptionTrial;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listSubscriptions(t){let e=o.listSubscriptions;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listPurchases(t){let e=o.listPurchases;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listSubscriptionConflicts(t){let e=o.listSubscriptionConflicts;return p(e.response,await r.request(e.path,e.request.parse(t)))},async retrySubscriptionConflict(t){let e=o.retrySubscriptionConflict;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewRefund(t){let e=o.previewRefund;return p(e.response,await r.request(e.path,e.request.parse(t)))},async refund(t){let e=o.refund;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readRefund(t){let e=o.readRefund;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewUpdate(t){let e=o.previewUpdate;return p(e.response,await r.request(e.path,e.request.parse(t)))},async update(t){let e=o.update;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSubscriptionUpdate(t){let e=o.readSubscriptionUpdate;return p(e.response,await r.request(e.path,e.request.parse(t)))},async restoreNativePurchase(t){let e=o.restoreNativePurchase;return p(e.response,await r.request(e.path,e.request.parse(t)))},async verifySubscriptions(t){let e=o.verifySubscriptions;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewAttach(t){let e=o.previewAttach;return p(e.response,await r.request(e.path,e.request.parse(t)))},async attach(t){let e=o.attach;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSubscriptionOperation(t){let e=o.readSubscriptionOperation;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readAiPricing(t){let e=o.readAiPricing;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readUsage(t){let e=o.readUsage;return p(e.response,await r.request(e.path,e.request.parse(t)))},async setUsage(t){let e=o.setUsage;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageBalanceGrant(t){let e=o.manageBalanceGrant;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readBalanceSource(t){let e=o.readBalanceSource;return p(e.response,await r.request(e.path,e.request.parse(t)))},async adjustBalance(t){let e=o.adjustBalance;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listBalanceGrants(t){let e=o.listBalanceGrants;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageBillingLimits(t){let e=o.manageBillingLimits;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSeats(t){let e=o.readSeats;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageSeat(t){let e=o.manageSeat;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageUsageEntity(t){let e=o.manageUsageEntity;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readUsageAnalytics(t){let e=o.readUsageAnalytics;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readCreditAnalytics(t){let e=o.readCreditAnalytics;return p(e.response,await r.request(e.path,e.request.parse(t)))},async submitUsageBatch(t){let e=o.submitUsageBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readUsageBatch(t){let e=o.readUsageBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readHoldings(t){let e=o.readHoldings;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readLedger(t){let e=o.readLedger;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readBillingInvoice(t){let e=o.readBillingInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readCreditStatement(t){let e=o.readCreditStatement;return p(e.response,await r.request(e.path,e.request.parse(t)))},async quoteBalance(t){let e=o.quoteBalance;return p(e.response,await r.request(e.path,e.request.parse(t)))},async trackUsage(t){let e=o.trackUsage;return p(e.response,await r.request(e.path,e.request.parse(t)))},async mutateBalance(t){let e=o.mutateBalance;return p(e.response,await r.request(e.path,e.request.parse(t)))},async getCustomer(t){let e=o.getCustomer,s=e.request.safeParse(t);if(!s.success)throw new a("INVALID_REQUEST","Invalid customer lookup");let i=e.response.safeParse(await r.request(e.path,s.data));if(!i.success)throw new a("INVALID_RESPONSE","Invalid customer response");return i.data},async listCustomers(t={}){let e=o.listCustomers,s=e.request.safeParse(t);if(!s.success)throw new a("INVALID_REQUEST","Invalid customer filters");let i=e.response.safeParse(await r.request(e.path,s.data));if(!i.success)throw new a("INVALID_RESPONSE","Invalid customer response");return i.data},async updateCustomer(t){let e=o.updateCustomer,s=e.request.safeParse(t);if(!s.success)throw new a("INVALID_REQUEST","Invalid customer patch");let i=e.response.safeParse(await r.request(e.path,s.data));if(!i.success)throw new a("INVALID_RESPONSE","Invalid customer response");return i.data},async createGuestCustomer(t){let e=o.createGuestCustomer;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async resumeGuestSession(t){let e=o.resumeGuestSession;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async claimGuestCustomer(t){let e=o.claimGuestCustomer;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async renewCustomerSession(t){let e=o.renewSession;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async revokeCustomerSessions(t){let e=o.revokeSessions;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async createCustomerSession(t){let e=o.createSession.request.safeParse({customerId:t});if(!e.success)throw new a("INVALID_REQUEST","A customer ID is required");let s=o.createSession.response.safeParse(await r.request("customer-sessions",e.data));if(!s.success)throw new a("INVALID_RESPONSE","Invalid customer session response");return s.data},async getOrCreateCustomer(t){let e=o.createCustomer.request.safeParse(t);if(!e.success)throw new a("INVALID_REQUEST","Invalid customer input");let s=o.createCustomer.response.safeParse(await r.request("customers",e.data));if(!s.success)throw new a("INVALID_RESPONSE","Invalid customer response");return s.data},async grantOffer(t){let e=o.grantOffer.request.safeParse({...t,requestId:t.requestId??crypto.randomUUID()});if(!e.success||!e.data.customerId)throw new a("INVALID_REQUEST","Invalid offer grant");let s=o.grantOffer.response.safeParse(await r.request("offers/grant",e.data));if(!s.success)throw new a("INVALID_RESPONSE","Invalid offer response");return s.data}}}async function Mt(n,r){if(typeof window<"u")throw new a("SERVER_ONLY","Renewal requires your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new a("INVALID_TOKEN","A server API key is required");let{funnelCredentialCommandSchema:t,funnelCredentialResponseSchema:e}=await import("./src-UHLPVD6E.js"),s=q(n);s.identify(n.apiKey);let i=e.parse(await k(n,await s.request("funnels",t.parse({...r,operation:"renew_run"}))));if(i.run.id!==r.runId)throw new a("INVALID_RESPONSE","Run renewal identity changed");return i}export{F as FunnelDecisionTimeoutError,a as IndianaError,Fe as aiPriceSnapshotSchema,Le as aiTokenQuoteSchema,De as createAiPricing,Te as createAiUsageMiddleware,qe as createConfigurationSync,Oe as createConfiguredAiPricing,G as createFeatureClient,Ve as createFunnelCampaignClient,K as createFunnelDecisionClient,x as createFunnelLocalEvaluator,Ue as createFunnelOrchestrationClient,Re as createFunnelStartClient,Ut as createGuestToken,Vt as createIndianaServer,Ce as createLocalFunnelClient,ke as createNativeReceiptClient,be as createPaywallStartClient,Ne as createSynchronizedFunnelLocalEvaluator,Ae as evaluateFunnelNode,Mt as renewFunnelRun};
1
+ import{a as G,b as k,c as de,d as b,e as me,f as fe,g as we,j as ye,k as qe,l as Ae,m as Ce,n as Re}from"./chunk-2A6UYUFA.js";import{a as Fe,b as Le,c as _e,d as De}from"./chunk-G2R56FKU.js";import{a as q}from"./chunk-CXYOZSOF.js";import{Ai as j,Bi as oe,Ci as ie,Ei as O,Fi as ce,Ij as le,Ke as M,Le as re,Mb as V,Ne as ae,Pb as W,Tb as X,ei as o,ej as ue,fj as pe,hf as N,if as R,jf as se,mi as B,ye as ne}from"./chunk-A3N4ZZTM.js";import{a}from"./chunk-OVMNCZYC.js";import{Mb as te}from"./chunk-3BQFJANQ.js";import{b as H,h as ee}from"./chunk-AE4CUTUE.js";import"./chunk-S5TVMQRC.js";import{b as J,q as Z}from"./chunk-RRII2DMC.js";import{d as $}from"./chunk-KQCTDXVD.js";function p(n,r){try{return n.parse(r)}catch{throw new a("INVALID_RESPONSE","Invalid gateway response")}}function Ie(n){let r=me(n),t=c=>{throw new a("INVALID_RESPONSE",c)};r.nodes.size!==n.topology.nodes.length&&t("Duplicate local node identity"),r.nodes.get(n.topology.entry)?.type!=="entry"&&t("A local Funnel must start at Entry");let e=new Set(["entry","condition","feature","split","end","output"]);for(let c of r.nodes.values()){if(!e.has(c.type))throw new a("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(c.type==="entry"&&c.id!==n.topology.entry&&t("Unexpected Entry node"),["entry","feature"].includes(c.type)&&!c.outputs.next&&t("Local next exit is unavailable"),c.type==="feature"){let u=c.resources.featureKey;(!u||!Object.hasOwn(n.evaluation.variables,c.writes.value)||!Object.hasOwn(r.features,u))&&t("Local Feature definition or declaration is unavailable")}if(c.type==="condition"){let u=n.conditions[c.id];(!u||!c.outputs.default||u.some((f,m)=>f.port!==`case:${m}`||!c.outputs[f.port]))&&t("Local Condition exits are unavailable")}if(c.type==="split"&&(!c.resources.experimentId||!Object.hasOwn(n.growth.experiments,c.resources.experimentId)||!c.outputs.notParticipating)&&t("Local Experiment definition or exit is unavailable"),c.type==="end"||c.type==="output"){let u=n.evaluation.terminals[c.id];if(!u)throw new a("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(c.outputs).length&&t("A terminal cannot have outgoing edges"),u.output?.type==="feature"&&!Object.hasOwn(r.features,u.output.featureKey)&&t("Terminal Feature definition is unavailable")}for(let u of Object.values(c.outputs))r.nodes.has(u)||t("Local target is unavailable")}let s=new Set,i=new Set;function l(c){if(i.has(c)&&t("Local graph contains a cycle"),!s.has(c)){i.add(c);for(let u of Object.values(r.nodes.get(c).outputs))l(u);i.delete(c),s.add(c)}}return l(n.topology.entry),s.size!==r.nodes.size&&t("Local graph contains unreachable nodes"),{evaluate(c){let u={},f=c.context;f.features=r.features,f.savedGroups=r.savedGroups;let m=()=>{f.attributes=ne({declarations:n.evaluation.variables,attributes:c.attributes,parameters:c.parameters,answers:{},results:u,savedGroups:r.savedGroups})};m();let I=n.topology.entry,d=0;for(;;){let w=r.nodes.get(I);if(w.type==="end"||w.type==="output"){let y=n.evaluation.terminals[I],h=y.output,v=h?.type==="feature"?r.feature(h.featureKey,f):h?.type==="variable"?X({source:"variable",key:h.key,...h.path?{path:h.path}:{}},{declarations:n.evaluation.variables,answers:{},results:u,parameters:c.parameters,attributes:c.attributes,savedGroups:r.savedGroups}):h?.value??null;return V(n.evaluation.outputSchema,v)||t("Local output does not match its declaration"),{outcome:y.outcome,value:v}}if(d++>=n.evaluation.maxTransitions)throw new a("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(w.type==="entry")I=w.outputs.next;else{let y=r.evaluate(I,f);if(w.type==="feature"){let h=w.writes.value,v=y.value??null;V(n.evaluation.variables[h],v)||t("Local Feature value does not match its declaration"),W(n.evaluation.variables,{writes:w.writes},{[h]:v}),u[h]=v,m()}I=y.target}}}}}import{z as he}from"zod";function ge(n,r,t){let e=J.parse(n.attributes);if(["parameters","answers","results"].some(S=>Object.hasOwn(e,S)))throw new a("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let s=te.parse(n.parameters??{}),i=he.record(he.string(),Z).parse(n.stickyBucketAssignmentDocs??{});for(let[S,g]of Object.entries(i))if(S!==`${g.attributeName}||${g.attributeValue}`||!Object.hasOwn(e,g.attributeName)||$(e[g.attributeName])!==g.attributeValue)throw new a("INVALID_REQUEST","Sticky document identity does not match this session");let l=n.saveStickyBucketAssignmentDoc,c=n.onFeatureUsage,u=n.onExperimentViewed,f=n.onError,m=new Map,I=new Set,d={},w=Promise.resolve();function y(S){let g=w.then(()=>(t(),S()));return w=g.catch(()=>{}),g}function h(S){try{f?.(S)}catch{}}function v(S){try{let g=S();g&&typeof g.catch=="function"&&g.catch(h)}catch(g){h(g)}}async function L(){for(let[S,g]of m){if(t(),l)try{await l(structuredClone(g))}catch{throw new a("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}t(),m.delete(S)}}return{evaluate(S={}){let g=S.track===!0;return y(async()=>{let _=await r();t(_);let z=new Set(I),Q={...d},Y=new Map,T=[],ve={stickyBucketAssignmentDocs:structuredClone(i),saveStickyBucketAssignmentDoc(E){Y.set(`${E.attributeName}||${E.attributeValue}`,structuredClone(E))},...g?{trackedExperiments:z,trackedFeatureUsage:Q,onExperimentViewed(E,C){let U=structuredClone(E),Ee=structuredClone(C);u&&T.push(()=>u(structuredClone(U),structuredClone(Ee)))},onFeatureUsage(E,C){let U=structuredClone(C);c&&T.push(()=>c(E,structuredClone(U)))}}:{}},Se=_.program.evaluate({attributes:e,parameters:s,context:ve});t(_);for(let[E,C]of Y)i[E]=C,m.set(E,C);await L(),t(_),g&&(I=z,d=Q);for(let E of T)v(E);let D=_.configuration;return structuredClone({evaluationMode:"local",scope:D.scope,funnelId:D.funnelId,versionId:D.versionId,evaluationRevision:D.evaluationRevision,generation:D.growth.generation,...Se})})},flush:()=>y(L),get stickyBucketAssignmentDocs(){return t(),structuredClone(i)}}}var Oe=6e4;function x(n){if(typeof window<"u")throw new a("SERVER_ONLY","Local Funnel sessions run on your backend");let r=H.parse(n.scope),t=n.funnelId,e=n.load,s,i,l,c=0,u=I=>Date.now()>=I.expiresAt;async function f(){if(i)return i;let I=c;s=void 0;let d=(async()=>{let w=await e();if(I!==c)throw new a("IDENTITY_CHANGED","Local evaluator was reset");if(w&&typeof w=="object"&&"evaluationMode"in w&&w.evaluationMode==="remote")throw p(O,w),new a("EVALUATION_MODE","This Funnel requires remote decide");let y=p(ce,w);if(I!==c)throw new a("IDENTITY_CHANGED","Local evaluator was reset");if(y.scope.projectId!==r.projectId||y.scope.environment!==r.environment||y.funnelId!==t)throw new a("SCOPE_MISMATCH","Local configuration scope changed");if(y.growth.scope.projectId!==r.projectId||y.growth.scope.environment!==r.environment||y.growth.expiresAt!==y.expiresAt)throw new a("INVALID_RESPONSE","GB configuration scope or expiry changed");let h=Math.min(Date.now()+Oe,y.expiresAt?Date.parse(y.expiresAt):1/0);if(Date.now()>=h)throw new a("CONFIGURATION_EXPIRED","Refresh expired local rules");let v=JSON.stringify([r.projectId,r.environment,t,y.versionId,y.evaluationRevision,y.growth.generation]),L=[y.topology,y.conditions,y.evaluation,y.growth.features,y.growth.experiments,y.growth.savedGroups];if(l?.key===v&&!de(l.body,L))throw new a("INVALID_RESPONSE","Immutable local configuration identity changed");return l?.key!==v&&(l={key:v,body:L,program:Ie(y)}),s={key:v,configuration:y,expiresAt:h,program:l.program},s})();i=d;try{return await d}finally{i===d&&(i=void 0)}}function m(){return i??(s&&!u(s)?Promise.resolve(s):f())}return{session(I){let d=c;return ge(I,m,w=>{if(n.assertUsable?.(),d!==c)throw new a("IDENTITY_CHANGED","Local evaluator was reset");if(w&&(u(w)||s?.key!==w.key))throw new a("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await f()).configuration)},reset(){c++,s=void 0,i=void 0,l=void 0}}}function Ne(n,r){let t=n.snapshot?.generation,e=x({scope:{projectId:n.scope.projectId,environment:n.scope.environment},funnelId:r,load:()=>n.localFunnel(r),assertUsable:()=>n.assertFunnel(r)}),s=n.subscribe(()=>{let l=n.snapshot?.generation;n.fresh&&l!==t&&(t=l,e.refresh().catch(()=>{}))}),i=e.session;return Object.assign(e,{session(l){let c=i(l),u=c.evaluate;return Object.assign(c,{async evaluate(...f){return n.fresh||await n.refresh(),u(...f)}})},destroy(){s(),e.reset()}})}function ke(n){if(typeof window<"u")throw new a("SERVER_ONLY","Secret API keys must stay on the backend");return{start:r=>ye(n,r)}}var F=class extends a{constructor(t,e){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,e);this.decisionId=t;this.decisionRequestId=e}decisionId;decisionRequestId};async function P(n,r,t,e){let{decisionId:s,requestId:i}=n,l=n,c=250;for(;;){if(l.decisionId!==s||l.requestId!==i||l.decision&&!k(l.decision,r))throw new a("INVALID_RESPONSE","Decision request or customer changed");if(l.decision)return l.decision;if(l.status==="failed")throw new a("DECISION_FAILED","Decision execution failed",503,i);if(Date.now()>=t)throw new F(s,i);if(await new Promise(u=>setTimeout(u,Math.min(c,t-Date.now()))),Date.now()>=t)throw new F(s,i);c=Math.min(1e3,c*2);try{l=await e(s,t)}catch(u){if(u instanceof a&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(u.code))continue;throw u}}}function K(n){if("remoteEval"in n)throw new a("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");if(typeof window<"u")throw new a("SERVER_ONLY","Funnel decisions are requested by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new a("INVALID_TOKEN","A server API key is required");let r,t,e=new Map;async function s(u,f){let m=u;m.status!=="pending"&&e.delete(m.decisionId);for(let I=0;I<32&&m.evaluation;I++){let d=m.evaluation;if(d.runId!==m.decisionId)throw new a("INVALID_RESPONSE","Local evaluation Run changed");let w=e.get(m.decisionId);if(!w&&d.type==="evaluate_segment"){let h=le.parse(await i({operation:"segment_configuration",funnelId:n.funnelId,versionId:d.versionId},f));if(h.configuration.scope.projectId!==n.scope.projectId||h.configuration.scope.environment!==n.scope.environment||h.configuration.funnelId!==n.funnelId||h.configuration.versionId!==d.versionId||h.configuration.evaluationRevision!==d.policyRevision)throw new a("SCOPE_MISMATCH","Original decision segment configuration changed");if(e.size>=128)throw new a("COMMAND_PENDING","Reconcile outstanding decisions first");w={operation:"commit_decision_segment",decisionId:m.decisionId,requestId:B(m.decisionId,d.visit,`segment:${d.revision}`),nodeId:d.nodeId,visit:d.visit,revision:d.revision,policyRevision:d.policyRevision,generation:h.configuration.growth.generation,...we(h.configuration,h.document,d)},e.set(m.decisionId,w)}if(!w){if(d.type!=="evaluate")throw new a("INVALID_RESPONSE","Unknown decision instruction");if((!t||t.versionId!==d.versionId||t.evaluationRevision!==d.policyRevision||t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())&&(t=O.parse(await i({operation:"configuration",funnelId:n.funnelId,versionId:d.versionId},f))),t.scope.projectId!==n.scope.projectId||t.scope.environment!==n.scope.environment||t.funnelId!==n.funnelId)throw new a("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(t.evaluationMode!=="local"||t.versionId!==d.versionId||t.evaluationRevision!==d.policyRevision)throw new a("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(e.size>=128)throw new a("COMMAND_PENDING","Reconcile outstanding Local decisions first");w={operation:"evaluate_decision",decisionId:m.decisionId,requestId:B(m.decisionId,d.visit,"evaluation"),nodeId:d.nodeId,visit:d.visit,revision:d.revision,receiptId:d.receiptId,policyRevision:d.policyRevision,generation:t.growth.generation,result:fe(t,d.nodeId,d)},e.set(m.decisionId,w)}let y=R.parse(await i(w,f));if(y.decisionId!==u.decisionId||y.requestId!==u.requestId)throw new a("INVALID_RESPONSE","Decision identity changed during local evaluation");e.delete(m.decisionId),m=y}return m}async function i(u,f,m=!1){let I=q({...n,fetch:(d,w)=>{let y=new Headers(w?.headers);return y.set("Accept-Encoding","identity"),m&&y.set("Prefer","respond-async"),(n.fetch??globalThis.fetch)(d,{...w,headers:y})},timeoutMs:Math.min(n.timeoutMs??1e4,f?Math.max(1,f-Date.now()):12e4)});return I.identify(n.apiKey),I.request("funnels",u)}async function l(u,f){let m=R.parse(await i(N.parse({operation:"read_decision",decisionId:u}),f));if(m.decisionId!==u)throw new a("INVALID_RESPONSE","Decision identity changed");return s(m,f)}async function c(u,f,m=!1){let I=N.options[0].parse({...u,operation:"decide",funnelId:n.funnelId}),d;try{d=R.parse(await i(I,f,m))}catch(w){throw w instanceof a&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(w.code)?new a("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",w.status,u.requestId):w}if(d.requestId!==u.requestId||d.decision&&!k(d.decision,I.customer))throw new a("INVALID_RESPONSE","Decision request or customer changed");return{response:await s(d,f),customer:I.customer}}return{local(){return r??=x({scope:n.scope,funnelId:n.funnelId,load:()=>i({operation:"local_configuration",funnelId:n.funnelId})})},async configuration(){let u=O.parse(await i({operation:"configuration",funnelId:n.funnelId}));if(u.scope.projectId!==n.scope.projectId||u.scope.environment!==n.scope.environment||u.funnelId!==n.funnelId)throw new a("SCOPE_MISMATCH","Configuration scope changed");return u},features(u={}){return G({...u,scope:n.scope,load:async()=>ee.parse(await i({operation:"feature_config",funnelId:n.funnelId}))})},read:u=>l(u),async submit(u){return(await c(u,void 0,!0)).response},async decide(u){let f=Date.now()+3e4,m=await c(u,f);return P(m.response,m.customer,f,l)},async reportUsed(u){let f=se.parse(await i(N.parse({...u,operation:"report_used"})));if(f.decisionId!==u.decisionId||f.eventId!==u.eventId)throw new a("INVALID_RESPONSE","Usage receipt identity changed");return f}}}function be(n){if(typeof window<"u")throw new a("SERVER_ONLY","Native receipts are verified by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new a("INVALID_TOKEN","Server API key required");let r=q({...n,timeoutMs:n.timeoutMs??35e3});return r.identify(n.apiKey),{async recover(t){let e=ue.parse(t);if(e.orderId!==e.receiptId)throw new a("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let s=e.nativeEvidence,i={requestId:e.requestId,customerToken:e.customerToken,purchaseIntentId:e.orderId,...s===null?{intent:"read"}:s.provider==="apple"?{provider:"apple",signedTransaction:s.signedTransaction}:{provider:"google",purchaseToken:s.purchaseToken}},l=o.restoreNativePurchase.response.parse(await r.request(o.restoreNativePurchase.path,i));if(l.operation.requestId!==e.requestId)throw new a("INVALID_RESPONSE","Native receipt request identity changed");let c=pe.parse({scope:l.scope,requestId:e.requestId,orderId:l.operation.orderId,receiptId:l.operation.orderId,orderStatus:l.operation.status,refunded:l.operation.refunded,...l.operation.completion===null?{}:{nativeCompletion:{orderId:l.operation.orderId,receiptId:l.operation.orderId,...l.operation.completion}}});if(c.requestId!==e.requestId||c.orderId!==e.orderId||c.receiptId!==e.receiptId||c.scope.projectId!==n.scope.projectId||c.scope.environment!==n.scope.environment)throw new a("INVALID_RESPONSE","Current order receipt scope changed");return c}}}import{z as xe}from"zod";var A=xe.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function Pe(n,r){let t=A.parse(n.inputTokens.total),e=A.parse(n.outputTokens.total),s=A.parse(n.inputTokens.cacheRead??0),i=A.parse(n.inputTokens.cacheWrite??0),l=A.parse(n.outputTokens.reasoning??0);if(s+i>t||l>e||n.inputTokens.noCache!==void 0&&A.parse(n.inputTokens.noCache)!==t-s-i||n.outputTokens.text!==void 0&&A.parse(n.outputTokens.text)!==e-l)throw new a("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:t-s-i,cache_read:s,cache_write:i,output:r==="output"?e:e-l,reasoning:r==="separate"?l:0,input_audio:0,output_audio:0}}function Te(n){if(typeof window<"u")throw new a("SERVER_ONLY","AI usage belongs on the trusted backend");if(!n.modelId||!["output","separate"].includes(n.reasoning))throw new a("INVALID_REQUEST","Model ID and reasoning pricing are required");async function r(e){await n.persist({context:e,modelId:n.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function t(e,s){let i={context:e,modelId:n.modelId,usage:s,tokens:null,quote:null,receipt:null,phase:"captured"};await n.persist(i);let l=n.mapTokens?n.mapTokens(s):Pe(s,n.reasoning),c=await n.pricing.quoteTokens({modelId:n.modelId,tokens:l});await n.persist({...i,tokens:l,quote:c,phase:"quoted"});let u=await n.pricing.trackTokens(n.client,{...e,quote:c});if(!u.receipt.accepted)throw new a("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await n.persist({...i,tokens:l,quote:c,receipt:u,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:e}){let s=await n.context(),i;try{i=await e()}catch(l){throw await r(s),l}return await t(s,i.usage),i},async wrapStream({doStream:e}){let s=await n.context(),i;try{i=await e()}catch(m){throw await r(s),m}let l=!1,c=!1,u=i.stream.getReader();async function f(){l||c||(c=!0,await r(s))}return{...i,stream:new ReadableStream({async pull(m){try{let{value:I,done:d}=await u.read();if(d){if(!l)throw await f(),new a("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");m.close();return}if(I.type==="finish"){if(l)throw new a("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");l=!0,await t(s,I.usage)}m.enqueue(I)}catch(I){try{await f()}finally{m.error(I),await u.cancel(I)}}},async cancel(m){try{await f()}finally{await u.cancel(m)}}})}}}}function Ue(n){if(typeof window<"u")throw new a("SERVER_ONLY","Funnel receipts are sent by your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new a("INVALID_TOKEN","A server API key is required");let r=q(n);return r.identify(n.apiKey),{async signal(t){let e=M.parse({...t,operation:"signal"}),s=re.parse(await r.request("funnels",e));if(s.runId!==t.runId||s.eventId!==t.eventId||s.scope.projectId!==n.scope.projectId||s.scope.environment!==n.scope.environment)throw new a("INVALID_RESPONSE","Receipt identity changed");return s},async readResults(t){let e=M.parse({operation:"read_results",runId:t}),s=ae.parse(await r.request("funnels",e));if(s.runId!==t||s.scope.projectId!==n.scope.projectId||s.scope.environment!==n.scope.environment)throw new a("INVALID_RESPONSE","Result identity changed");return s}}}function Ve(n){if("remoteEval"in n)throw new a("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");if(typeof window<"u")throw new a("SERVER_ONLY","Campaign entry requires your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new a("INVALID_TOKEN","A server API key is required");let r=q({...n,timeoutMs:n.timeoutMs??35e3});return r.identify(n.apiKey),{async decide(t){let e=Date.now()+(n.timeoutMs??3e4),s=j.parse({...t,funnelId:n.funnelId,operation:"campaign_decide"}),i=q({...n,timeoutMs:Math.min(n.timeoutMs??35e3,Math.max(1,e-Date.now()))});i.identify(n.apiKey);let l=R.parse(await i.request("funnels",s));if(l.scope.projectId!==n.scope.projectId||l.scope.environment!==n.scope.environment)throw new a("SCOPE_MISMATCH","Campaign scope changed");return P(l,s.customer,e,(c,u)=>K({...n,timeoutMs:Math.min(n.timeoutMs??1e4,Math.max(1,u-Date.now()))}).read(c))},async start(t){let e=j.parse({...t,funnelId:n.funnelId,operation:"campaign_start"}),s=ie.parse(await r.request("funnels",e)),i=oe.parse("suppressed"in s?s:await b(n,s));if(i.scope.projectId!==n.scope.projectId||i.scope.environment!==n.scope.environment)throw new a("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in i)&&(i.run.source.id!==n.funnelId||!i.customerId||e.customer.type==="id"&&i.customerId!==e.customer.value))throw new a("INVALID_RESPONSE","Campaign Funnel or Customer changed");return i}}}function Ut(){if(typeof window<"u")throw new a("SERVER_ONLY","Guest identity is issued by your backend");let n=crypto.getRandomValues(new Uint8Array(32));return"gg_gc_"+btoa(String.fromCharCode(...n)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}function Vt(n){if(typeof window<"u")throw new a("SERVER_ONLY","Secret API keys must stay on your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new a("INVALID_TOKEN","A server API key is required");let r=q(n);return r.identify(n.apiKey),{async listInvoiceTemplates(t={}){let e=o.listInvoiceTemplates;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewInvoice(t){let e=o.previewInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async createInvoice(t){let e=o.createInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageInvoice(t){let e=o.manageInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readInvoiceOperation(t){let e=o.readInvoiceOperation;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listInvoices(t){let e=o.listInvoices;return p(e.response,await r.request(e.path,e.request.parse(t)))},async getInvoice(t){let e=o.getInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async recordCouponRedemption(t){let e=o.recordCouponRedemption,s=e.request.safeParse(t);if(!s.success)throw new a("INVALID_REQUEST","Invalid Coupon redemption facts");return p(e.response,await r.request(e.path,s.data))},async getFeatures(t={}){let e=o.getFeatures;return p(e.response,await r.request(e.path,e.request.parse(t),e.method))},async evaluateFeatures(t){let e=o.evaluateFeatures;return p(e.response,await r.request(e.path,e.request.parse(t),e.method))},async trackEvents(t){let e=o.trackEvents;return p(e.response,await r.request(e.path,e.request.parse(t),e.method))},async resolveContent(t){let e=o.resolveContent;return p(e.response,await r.request(e.path,e.request.parse(t)))},async resolvePaywall(t){let e=o.resolvePaywall;return p(e.response,await r.request(e.path,e.request.parse(t)))},async resolveOffering(t){let e=o.resolveOffering;return p(e.response,await r.request(e.path,e.request.parse(t)))},async checkEntitlement(t){let e=o.checkEntitlement;return p(e.response,await r.request(e.path,e.request.parse(t)))},async setupPayment(t){let e=o.setupPayment;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readPaymentSetup(t){let e=o.readPaymentSetup;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewSubscriptionBatch(t){let e=o.previewSubscriptionBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async confirmSubscriptionBatch(t){let e=o.confirmSubscriptionBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSubscriptionBatch(t){let e=o.readSubscriptionBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async abandonSubscriptionBatch(t){let e=o.abandonSubscriptionBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageSubscriptionTrial(t){let e=o.manageSubscriptionTrial;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSubscriptionTrial(t){let e=o.readSubscriptionTrial;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listSubscriptions(t){let e=o.listSubscriptions;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listPurchases(t){let e=o.listPurchases;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listSubscriptionConflicts(t){let e=o.listSubscriptionConflicts;return p(e.response,await r.request(e.path,e.request.parse(t)))},async retrySubscriptionConflict(t){let e=o.retrySubscriptionConflict;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewRefund(t){let e=o.previewRefund;return p(e.response,await r.request(e.path,e.request.parse(t)))},async refund(t){let e=o.refund;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readRefund(t){let e=o.readRefund;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewUpdate(t){let e=o.previewUpdate;return p(e.response,await r.request(e.path,e.request.parse(t)))},async update(t){let e=o.update;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSubscriptionUpdate(t){let e=o.readSubscriptionUpdate;return p(e.response,await r.request(e.path,e.request.parse(t)))},async restoreNativePurchase(t){let e=o.restoreNativePurchase;return p(e.response,await r.request(e.path,e.request.parse(t)))},async verifySubscriptions(t){let e=o.verifySubscriptions;return p(e.response,await r.request(e.path,e.request.parse(t)))},async previewAttach(t){let e=o.previewAttach;return p(e.response,await r.request(e.path,e.request.parse(t)))},async attach(t){let e=o.attach;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSubscriptionOperation(t){let e=o.readSubscriptionOperation;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readAiPricing(t){let e=o.readAiPricing;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readUsage(t){let e=o.readUsage;return p(e.response,await r.request(e.path,e.request.parse(t)))},async setUsage(t){let e=o.setUsage;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageBalanceGrant(t){let e=o.manageBalanceGrant;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readBalanceSource(t){let e=o.readBalanceSource;return p(e.response,await r.request(e.path,e.request.parse(t)))},async adjustBalance(t){let e=o.adjustBalance;return p(e.response,await r.request(e.path,e.request.parse(t)))},async listBalanceGrants(t){let e=o.listBalanceGrants;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageBillingLimits(t){let e=o.manageBillingLimits;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readSeats(t){let e=o.readSeats;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageSeat(t){let e=o.manageSeat;return p(e.response,await r.request(e.path,e.request.parse(t)))},async manageUsageEntity(t){let e=o.manageUsageEntity;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readUsageAnalytics(t){let e=o.readUsageAnalytics;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readCreditAnalytics(t){let e=o.readCreditAnalytics;return p(e.response,await r.request(e.path,e.request.parse(t)))},async submitUsageBatch(t){let e=o.submitUsageBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readUsageBatch(t){let e=o.readUsageBatch;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readHoldings(t){let e=o.readHoldings;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readLedger(t){let e=o.readLedger;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readBillingInvoice(t){let e=o.readBillingInvoice;return p(e.response,await r.request(e.path,e.request.parse(t)))},async readCreditStatement(t){let e=o.readCreditStatement;return p(e.response,await r.request(e.path,e.request.parse(t)))},async quoteBalance(t){let e=o.quoteBalance;return p(e.response,await r.request(e.path,e.request.parse(t)))},async trackUsage(t){let e=o.trackUsage;return p(e.response,await r.request(e.path,e.request.parse(t)))},async mutateBalance(t){let e=o.mutateBalance;return p(e.response,await r.request(e.path,e.request.parse(t)))},async getCustomer(t){let e=o.getCustomer,s=e.request.safeParse(t);if(!s.success)throw new a("INVALID_REQUEST","Invalid customer lookup");let i=e.response.safeParse(await r.request(e.path,s.data));if(!i.success)throw new a("INVALID_RESPONSE","Invalid customer response");return i.data},async listCustomers(t={}){let e=o.listCustomers,s=e.request.safeParse(t);if(!s.success)throw new a("INVALID_REQUEST","Invalid customer filters");let i=e.response.safeParse(await r.request(e.path,s.data));if(!i.success)throw new a("INVALID_RESPONSE","Invalid customer response");return i.data},async updateCustomer(t){let e=o.updateCustomer,s=e.request.safeParse(t);if(!s.success)throw new a("INVALID_REQUEST","Invalid customer patch");let i=e.response.safeParse(await r.request(e.path,s.data));if(!i.success)throw new a("INVALID_RESPONSE","Invalid customer response");return i.data},async createGuestCustomer(t){let e=o.createGuestCustomer;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async resumeGuestSession(t){let e=o.resumeGuestSession;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async claimGuestCustomer(t){let e=o.claimGuestCustomer;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async renewCustomerSession(t){let e=o.renewSession;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async revokeCustomerSessions(t){let e=o.revokeSessions;return e.response.parse(await r.request(e.path,e.request.parse(t)))},async createCustomerSession(t){let e=o.createSession.request.safeParse({customerId:t});if(!e.success)throw new a("INVALID_REQUEST","A customer ID is required");let s=o.createSession.response.safeParse(await r.request("customer-sessions",e.data));if(!s.success)throw new a("INVALID_RESPONSE","Invalid customer session response");return s.data},async getOrCreateCustomer(t){let e=o.createCustomer.request.safeParse(t);if(!e.success)throw new a("INVALID_REQUEST","Invalid customer input");let s=o.createCustomer.response.safeParse(await r.request("customers",e.data));if(!s.success)throw new a("INVALID_RESPONSE","Invalid customer response");return s.data},async grantOffer(t){let e=o.grantOffer.request.safeParse({...t,requestId:t.requestId??crypto.randomUUID()});if(!e.success||!e.data.customerId)throw new a("INVALID_REQUEST","Invalid offer grant");let s=o.grantOffer.response.safeParse(await r.request("offers/grant",e.data));if(!s.success)throw new a("INVALID_RESPONSE","Invalid offer response");return s.data}}}async function Mt(n,r){if(typeof window<"u")throw new a("SERVER_ONLY","Renewal requires your backend");if(!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new a("INVALID_TOKEN","A server API key is required");let{funnelCredentialCommandSchema:t,funnelCredentialResponseSchema:e}=await import("./src-4MRSESVS.js"),s=q(n);s.identify(n.apiKey);let i=e.parse(await b(n,await s.request("funnels",t.parse({...r,operation:"renew_run"}))));if(i.run.id!==r.runId)throw new a("INVALID_RESPONSE","Run renewal identity changed");return i}export{F as FunnelDecisionTimeoutError,a as IndianaError,Fe as aiPriceSnapshotSchema,Le as aiTokenQuoteSchema,_e as createAiPricing,Te as createAiUsageMiddleware,qe as createConfigurationSync,De as createConfiguredAiPricing,G as createFeatureClient,Ve as createFunnelCampaignClient,K as createFunnelDecisionClient,x as createFunnelLocalEvaluator,Ue as createFunnelOrchestrationClient,Ce as createFunnelStartClient,Ut as createGuestToken,Vt as createIndianaServer,Re as createLocalFunnelClient,be as createNativeReceiptClient,ke as createPaywallStartClient,Ne as createSynchronizedFunnelLocalEvaluator,Ae as evaluateFunnelNode,Mt as renewFunnelRun};
@@ -0,0 +1 @@
1
+ import{$ as Ha,$a as lc,$b as lf,$c as lg,$d as lh,$e as xi,$f as xj,$g as xk,$h as xl,$i as xm,A as ga,Aa as Mb,Ab as Uc,Ac as Mf,Ad as Mg,Ae as Yh,Af as Yi,Ag as Yj,Ah as Yk,Ai as Yl,Aj as bn,B as ha,Ba as Nb,Bb as Vc,Bc as Nf,Bd as Ng,Be as Zh,Bf as Zi,Bg as Zj,Bh as Zk,Bi as Zl,Bj as cn,C as ia,Ca as Ob,Cb as Wc,Cc as Of,Cd as Og,Ce as _h,Cf as _i,Cg as _j,Ch as _k,Ci as _l,Cj as dn,D as ja,Da as Pb,Db as Xc,Dc as Pf,Dd as Pg,De as $h,Df as $i,Dg as $j,Dh as $k,Di as $l,Dj as en,E as ka,Ea as Qb,Eb as Yc,Ec as Qf,Ed as Qg,Ee as ai,Ef as aj,Eg as ak,Eh as al,Ei as am,Ej as fn,F as la,Fa as Rb,Fb as hd,Fc as Rf,Fd as Rg,Fe as bi,Ff as bj,Fg as bk,Fh as bl,Fi as bm,Fj as gn,G as ma,Ga as Sb,Gb as id,Gc as Sf,Gd as Sg,Ge as ci,Gf as cj,Gg as ck,Gh as cl,Gi as cm,Gj as hn,H as na,Ha as Tb,Hb as jd,Hc as Tf,Hd as Tg,He as di,Hf as dj,Hg as dk,Hh as dl,Hi as dm,Hj as jn,I as oa,Ia as Ub,Ib as Te,Ic as Uf,Id as Ug,Ie as ei,If as ej,Ig as ek,Ih as el,Ii as em,Ij as kn,J as pa,Ja as Vb,Jb as Ue,Jc as Vf,Jd as Vg,Je as fi,Jf as fj,Jg as fk,Jh as fl,Ji as fm,K as qa,Ka as Wb,Kb as Ve,Kc as Wf,Kd as Wg,Ke as gi,Kf as gj,Kg as gk,Kh as gl,Ki as gm,L as ra,La as Xb,Lb as We,Lc as Xf,Ld as Xg,Le as hi,Lf as hj,Lg as hk,Lh as hl,Li as hm,M as sa,Ma as Yb,Mb as Xe,Mc as Yf,Md as Yg,Me as ii,Mf as ij,Mg as ik,Mh as il,Mi as im,N as ta,Na as Zb,Nb as Ye,Nc as Zf,Nd as Zg,Ne as ji,Nf as jj,Ng as jk,Nh as jl,Ni as jm,O as ua,Oa as _b,Ob as Ze,Oc as _f,Od as _g,Oe as ki,Of as kj,Og as kk,Oh as kl,Oi as km,P as va,Pa as $b,Pb as _e,Pc as $f,Pd as $g,Pe as li,Pf as lj,Pg as lk,Ph as ll,Pi as lm,Q as wa,Qa as ac,Qb as $e,Qc as ag,Qd as ah,Qe as mi,Qf as mj,Qg as mk,Qh as ml,Qi as mm,R as xa,Ra as bc,Rb as af,Rc as bg,Rd as bh,Re as ni,Rf as nj,Rg as nk,Rh as nl,Ri as nm,S as ya,Sa as cc,Sb as bf,Sc as cg,Sd as ch,Se as oi,Sf as oj,Sg as ok,Sh as ol,Si as om,T as za,Ta as dc,Tb as cf,Tc as dg,Td as dh,Te as pi,Tf as pj,Tg as pk,Th as pl,Ti as pm,U as Aa,Ua as ec,Ub as df,Uc as eg,Ud as eh,Ue as qi,Uf as qj,Ug as qk,Uh as ql,Ui as qm,V as Ba,Va as fc,Vb as ef,Vc as fg,Vd as fh,Ve as ri,Vf as rj,Vg as rk,Vh as rl,Vi as rm,W as Ca,Wa as gc,Wb as ff,Wc as gg,Wd as gh,We as si,Wf as sj,Wg as sk,Wh as sl,Wi as sm,X as Da,Xa as hc,Xb as gf,Xc as hg,Xd as hh,Xe as ti,Xf as tj,Xg as tk,Xh as tl,Xi as tm,Y as Ea,Ya as ic,Yb as hf,Yc as ig,Yd as ih,Ye as ui,Yf as uj,Yg as uk,Yh as ul,Yi as um,Z as Fa,Za as jc,Zb as jf,Zc as jg,Zd as jh,Ze as vi,Zf as vj,Zg as vk,Zh as vl,Zi as vm,_ as Ga,_a as kc,_b as kf,_c as kg,_d as kh,_e as wi,_f as wj,_g as wk,_h as wl,_i as wm,a as s,aa as Ia,ab as mc,ac as mf,ad as mg,ae as mh,af as yi,ag as yj,ah as yk,ai as yl,aj as ym,b as t,ba as Ja,bb as nc,bc as nf,bd as ng,be as nh,bf as zi,bg as zj,bh as zk,bi as zl,bj as zm,c as u,ca as Ka,cb as oc,cc as of,cd as og,ce as oh,cf as Ai,cg as Aj,ch as Ak,ci as Al,cj as Am,d as v,da as La,db as pc,dc as pf,dd as pg,de as ph,df as Bi,dg as Bj,dh as Bk,di as Bl,dj as Bm,e as w,ea as Ma,eb as qc,ec as qf,ed as qg,ee as qh,ef as Ci,eg as Cj,eh as Ck,ei as Cl,ej as Cm,f as x,fa as rb,fb as rc,fc as rf,fd as rg,fe as rh,ff as Di,fg as Dj,fh as Dk,fi as Dl,fj as Dm,g as y,ga as sb,gb as sc,gc as sf,gd as sg,ge as yh,gf as Ei,gg as Ej,gh as Ek,gi as El,gj as Em,h as z,ha as tb,hb as tc,hc as tf,hd as tg,he as zh,hf as Fi,hg as Fj,hh as Fk,hi as Fl,hj as Fm,i as A,ia as ub,ib as uc,ic as uf,id as ug,ie as Ah,if as Gi,ig as Gj,ih as Gk,ii as Gl,ij as Gm,j as B,ja as vb,jb as vc,jc as vf,jd as vg,je as Bh,jf as Hi,jg as Hj,jh as Hk,ji as Hl,jj as Hm,k as C,ka as wb,kb as wc,kc as wf,kd as wg,ke as Ch,kf as Ii,kg as Ij,kh as Ik,ki as Il,kj as Im,l as D,la as xb,lb as xc,lc as xf,ld as xg,le as Dh,lf as Ji,lg as Jj,lh as Jk,li as Jl,lj as Jm,m as K,ma as yb,mb as yc,mc as yf,md as yg,me as Eh,mf as Ki,mg as Kj,mh as Kk,mi as Kl,mj as Km,n as L,na as zb,nb as zc,nc as zf,nd as zg,ne as Fh,nf as Li,ng as Lj,nh as Lk,ni as Ll,nj as Lm,o as M,oa as Ab,ob as Ac,oc as Af,od as Ag,oe as Gh,of as Mi,og as Mj,oh as Mk,oi as Ml,oj as Mm,p as N,pa as Bb,pb as Bc,pc as Bf,pd as Bg,pe as Hh,pf as Ni,pg as Nj,ph as Nk,pi as Nl,pj as Nm,q as O,qa as Cb,qb as Cc,qc as Cf,qd as Cg,qe as Oh,qf as Oi,qg as Oj,qh as Ok,qi as Ol,qj as Om,r as P,ra as Db,rb as Dc,rc as Df,rd as Dg,re as Ph,rf as Pi,rg as Pj,rh as Pk,ri as Pl,rj as Pm,s as _,sa as Eb,sb as Ec,sc as Ef,sd as Eg,se as Qh,sf as Qi,sg as Qj,sh as Qk,si as Ql,sj as Qm,t as $,ta as Fb,tb as Fc,tc as Ff,td as Fg,te as Rh,tf as Ri,tg as Rj,th as Rk,ti as Rl,tj as Wm,u as aa,ua as Gb,ub as Gc,uc as Gf,ud as Gg,ue as Sh,uf as Si,ug as Sj,uh as Sk,ui as Sl,uj as Xm,v as ba,va as Hb,vb as Pc,vc as Hf,vd as Hg,ve as Th,vf as Ti,vg as Tj,vh as Tk,vi as Tl,vj as Ym,w as ca,wa as Ib,wb as Qc,wc as If,wd as Ig,we as Uh,wf as Ui,wg as Uj,wh as Uk,wi as Ul,wj as Zm,x as da,xa as Jb,xb as Rc,xc as Jf,xd as Jg,xe as Vh,xf as Vi,xg as Vj,xh as Vk,xi as Vl,xj as _m,y as ea,ya as Kb,yb as Sc,yc as Kf,yd as Kg,ye as Wh,yf as Wi,yg as Wj,yh as Wk,yi as Wl,yj as $m,z as fa,za as Lb,zb as Tc,zc as Lf,zd as Lg,ze as Xh,zf as Xi,zg as Xj,zh as Xk,zi as Xl,zj as an}from"./chunk-A3N4ZZTM.js";import{$ as fd,$a as ie,A as U,Aa as Jd,Ab as Je,B as V,Ba as Kd,Bb as Ke,C as W,Ca as Ld,Cb as Le,D as X,Da as Md,Db as Me,E as Y,Ea as Nd,Eb as Ne,F as Z,Fa as Od,Fb as Oe,G as mb,Ga as Pd,Gb as Pe,H as nb,Ha as Qd,Hb as Qe,I as ob,Ia as Rd,Ib as Re,J as pb,Ja as Sd,Jb as Se,K as qb,Ka as Td,Kb as Ih,L as Hc,La as Ud,Lb as Jh,M as Ic,Ma as Vd,Mb as Kh,N as Jc,Na as Wd,Nb as Lh,O as Kc,Oa as Xd,Ob as Mh,P as Lc,Pa as Yd,Pb as Nh,Q as Mc,Qa as Zd,R as Nc,Ra as _d,S as Oc,Sa as $d,T as Zc,Ta as ae,U as _c,Ua as be,V as $c,Va as ce,W as ad,Wa as de,X as bd,Xa as ee,Y as cd,Ya as fe,Z as dd,Za as ge,_ as ed,_a as he,a as c,aa as gd,ab as je,b as d,ba as kd,bb as ke,c as e,ca as ld,cb as le,d as f,da as md,db as me,e as g,ea as nd,eb as ne,f as h,fa as od,fb as oe,g as i,ga as pd,gb as pe,h as j,ha as qd,hb as qe,i as k,ia as rd,ib as re,j as l,ja as sd,jb as se,k as m,ka as td,kb as te,l as n,la as ud,lb as ue,m as o,ma as vd,mb as ve,n as p,na as wd,nb as we,o as q,oa as xd,ob as xe,p as r,pa as yd,pb as ye,q as E,qa as zd,qb as ze,r as F,ra as Ad,rb as Ae,s as G,sa as Bd,sb as Be,t as H,ta as Cd,tb as Ce,u as I,ua as Dd,ub as De,v as J,va as Ed,vb as Ee,w as Q,wa as Fd,wb as Fe,x as R,xa as Gd,xb as Ge,y as S,ya as Hd,yb as He,z as T,za as Id,zb as Ie}from"./chunk-3BQFJANQ.js";import{a,b,c as sh,d as th,e as uh,f as vh,g as wh,h as xh,j as Rm,k as Sm,l as Tm,m as Um,n as Vm}from"./chunk-AE4CUTUE.js";import{a as Va,b as Wa,c as Xa,d as Ya,e as Za,f as _a,g as $a,h as ab,i as bb,j as cb,k as db,l as eb,m as fb,n as gb,o as hb,p as ib,q as jb,r as kb,s as lb}from"./chunk-RRII2DMC.js";import{c as Na,d as Oa,e as Pa,h as Qa,i as Ra,j as Sa,k as Ta,l as Ua}from"./chunk-KQCTDXVD.js";export{Uk as CODE_REFERENCE_LIMITS,pb as COMMON_LOCALES,Mj as CONFIGURATION_POLICY,mf as CONTENT_DOCUMENT_BYTES,rb as COUPON_TERM_LOCALES,Id as CUSTOMER_DATA_SOURCES,Jf as CreateInvoiceParamsSchema,If as CreateInvoicePreviewSchema,ci as DEFAULT_FUNNEL_EXECUTION_POLICY,Ri as FUNNEL_API_CAPABILITIES,cj as FUNNEL_EXECUTION_LIMITS,ki as FUNNEL_LIMITS,dj as FUNNEL_RECORDING_LIMITS,Ym as FUNNEL_SEGMENT_BYTES,Xm as FUNNEL_SEGMENT_LIMIT,Ul as FUNNEL_SERVER_KEY_HEADER,fj as FUNNEL_TRANSITION_BUDGET_MESSAGE,Il as FunnelCalculationError,en as FunnelLocalCalculationError,Gf as InvoiceModeParamsSchema,Hf as InvoiceTemplateSchema,Ig as OFFERING_MAX_DEPTH,Kg as OFFERING_MAX_ITEMS,Jg as OFFERING_MAX_PRODUCTS,Ce as POPUP_WIDTHS,Dj as PUBLIC_PAYWALL_UNSUPPORTED_NODES,Ff as ReissueInvoiceParamsSchema,Td as SCREEN_LIMITS,Sd as SCREEN_SCHEMA_VERSION,s as SDK_PROTOCOL_HEADER,u as SDK_SUPPORT_HEADER,v as SDK_SUPPORT_POLICY,t as SDK_VERSION_HEADER,Ae as SURFACE_PATHS,vd as SURFACE_VARIABLES,B as SdkProtocolError,li as UNBOUND_PRODUCT_VERSION_ID,z as addSupportMonths,Da as aiCreditSystemConfigSchema,hk as aiMarkupSchema,gk as aiModelIdSchema,ik as aiModelRatesSchema,jk as aiPricingConfigurationSchema,fk as aiTokenPools,H as amountToMinor,ph as analyticsConfigSchema,rh as analyticsEventEnabled,h as apiErrorCatalog,i as apiErrorCodeForStatus,c as apiErrorCodeSchema,Cl as apiOperations,vl as apiPermissionSchema,Hl as archiveSurfaceTemplateSchema,Sb as autoTopupPurchaseLimitSchema,cc as autoTopupStateSchema,Om as autumnAmountToMinor,nm as autumnCustomerAutoTopupSchema,sm as autumnCustomerControlsSchema,um as autumnCustomerMetadataSchema,rm as autumnCustomerOverageAllowedSchema,wm as autumnCustomerProductSummarySchema,vm as autumnCustomerProfileRecordSchema,om as autumnCustomerSpendLimitSchema,qm as autumnCustomerUsageAlertSchema,pm as autumnCustomerUsageLimitSchema,tm as autumnEntityControlsSchema,Pm as autumnMinorToAmount,Qm as autumnUsageUnitAmountDecimal,ak as balanceAdjustmentCommandSchema,bk as balanceAdjustmentStateSchema,Lc as balanceAllocationSchema,Ic as balanceCommandSchema,Qc as balanceGrantCommandSchema,Pc as balanceGrantCreateSchema,Tc as balanceGrantPageSchema,Sc as balanceGrantReadSchema,Rc as balanceGrantSchema,Oc as balanceOperationSchema,Jc as balancePricingSegmentSchema,Nc as balanceQuoteSchema,Kc as balanceReceiptUnitsSchema,Mc as balanceRejectionReasonSchema,ck as balanceSourceStateSchema,gm as bannerVersionReferenceSchema,Lb as billingAccruedMinorSchema,Kb as billingAmountMinorSchema,Vb as billingAuthorizationSchema,Ub as billingAuthorizationTermsSchema,Mb as billingBudgetMinorSchema,dc as billingControlInputSchema,ec as billingControlsSchema,mc as billingCouponsSchema,K as billingCurrencies,fc as billingInvoiceLineSchema,gc as billingInvoiceSchema,jc as billingInvoicesSchema,Zb as billingLimitSchema,O as billingSettingsMutationSchema,M as billingSettingsSchema,N as billingSettingsScopeSchema,bc as billingUsageWindowSchema,fe as borderSchema,le as buttonNodeSchema,Jl as calculateFunnelNode,hn as calculateLocalFunnelEvaluation,jn as calculateLocalFunnelSegment,nb as canonicalLocale,wd as capabilityBindingSchema,Qb as cashPriceSchema,Ob as cashPricingSchema,Nb as cashPricingTiersSchema,Jb as cashUnitAmountMinorSchema,Kk as claimRewardProductRequestSchema,Xk as codeReferenceBranchSchema,bl as codeReferenceConfigRequestSchema,al as codeReferenceConfigureSchema,hl as codeReferenceFeatureSummarySchema,Vk as codeReferenceKeySchema,Yk as codeReferencePathSchema,el as codeReferenceReceiptSchema,Wk as codeReferenceRepoSchema,dl as codeReferenceReportSchema,_k as codeReferenceRepositoryInputSchema,$k as codeReferenceRepositorySchema,cl as codeReferenceScanConfigSchema,fl as codeReferenceScanSchema,gl as codeReferenceSettingsSchema,il as codeReferenceSummarySchema,md as commerceAccessSchema,od as commerceContextSchema,tg as commerceCursorSchema,ug as commerceListQuerySchema,nd as commerceMoneySchema,Fm as commerceProductKind,ld as commerceProductKindSchema,kd as commerceProviderSchema,eb as compileGrowthFeatures,Pj as configurationArtifactSchema,Vj as configurationDependencies,Oj as configurationDependenciesSchema,Tj as configurationDigest,Qj as configurationFunnelSchema,Uj as configurationGeneration,Sj as configurationJson,Lj as configurationPaywallSchema,Nj as configurationScopeSchema,hc as confirmBillingAdjustmentInputSchema,Xb as confirmBillingAuthorizationInputSchema,e as consoleErrorCodeSchema,q as consoleErrorResponseSchema,dg as consoleRefundRequestSchema,uf as contentCollectionSchema,of as contentContractSchema,pf as contentDocumentDraftSchema,rf as contentDocumentSchema,lf as contentKindSchema,tf as contentRecordSchema,sf as contentSummarySchema,qf as contentValueMatches,nf as contentValueSchema,vf as contentVersionSchema,wf as contentVersionSummarySchema,xf as contentWriteSchema,se as countdownNodeSchema,yb as couponAppliesToSchema,Db as couponChangeErrors,re as couponCodeNodeSchema,nh as couponContentDigestSchema,wb as couponDiscountSchema,Bj as couponDisplaySchema,xb as couponDurationSchema,zb as couponEligibilitySchema,Ab as couponInputSchema,jl as couponRedemptionCommandSchema,kl as couponRedemptionReceiptSchema,vb as couponStatusSchema,Gb as couponWindow,yl as createCustomerRequestSchema,zl as createCustomerResponseSchema,Mk as createReferralCodeRequestSchema,Q as creditAmountSchema,mk as creditAnalyticsFilterSchema,ok as creditAnalyticsPageSchema,nk as creditAnalyticsQuerySchema,kk as creditAnalyticsRangeSchema,lk as creditAnalyticsTimezoneSchema,W as creditDimensionSchema,X as creditMultiplierSchema,S as creditPriceAdjustmentSchema,Y as creditPricingSchema,U as creditPropertiesSchema,R as creditQuantitySchema,Z as creditRateSchema,oc as creditResetCountSchema,nc as creditResetSchema,T as creditResourceKeySchema,pc as creditRolloverSchema,wa as creditSchemaItemSchema,Xc as creditStatementInputSchema,Yc as creditStatementSchema,Ca as creditSystemConfigSchema,V as creditTiersSchema,E as currencies,L as currencyAmountOptionsSchema,G as currencyDecimals,F as currencySchema,Dl as currentApiOperations,pe as customHtmlNodeSchema,ta as customerActivitySchema,ni as customerAttributesSchema,Kd as customerDataConfigSchema,Nd as customerDataIntentSchema,ne as customerDataNodeSchema,ti as customerDataReferenceMessage,si as customerDataReferenced,ri as customerDataSchema,Jd as customerDataSourceSchema,Bl as customerEntitlementsSchema,Ai as customerFiltersSchema,oi as customerFingerprintSchema,yi as customerGetSchema,bd as customerHoldingsSchema,pi as customerInputSchema,fd as customerLedgerEntrySchema,gd as customerLedgerPageSchema,ed as customerLedgerQuerySchema,wi as customerLookupSchema,vi as customerMutationSchema,Md as customerPageDataSchema,Ld as customerPageNodeStateSchema,Bi as customerPageSchema,xi as customerPatchSchema,sa as customerPlanSchema,ui as customerProfileSchema,qi as customerReferenceSchema,mi as customerTagsSchema,zi as customerUpdateRequestSchema,Zk as defaultCodeReferenceMethods,Tl as deliveredFunnelResponse,_j as deliveredPaywall,Gh as deliveredScreenDocument,Eb as describeCoupon,Ac as diffProductVariant,me as dividerNodeSchema,Od as emptyCustomerPageNode,qd as entitlementCheckInputSchema,rd as entitlementCheckReasonSchema,td as entitlementCheckResultSchema,pd as entitlementRequirementSchema,pa as entitlementSnapshotSchema,Al as entitlementStatusSchema,a as environmentSchema,l as errorCodeMatchesStatus,r as errorMetadata,n as errorMetadataSchema,k as errorPolicy,g as errorReasonSchema,f as errorRecoverySchema,o as errorResponseSchema,Qd as escapeHtmlText,Ra as evalCondition,Ua as evalFeature,Ah as evaluateFeaturesRequestSchema,Ch as evaluateFeaturesResultSchema,gn as evaluateLocalFunnelNode,Pl as executionSourceSchema,dn as expandFunnelSegment,db as experimentConfigurationSchema,cb as experimentPhaseSchema,hb as experimentSnapshotSchema,Ha as featureCollectionSchema,Aa as featureConfigOverrideSchema,Ea as featureDefinitionSchema,yh as featureDeliveryPayloadSchema,ua as featureIdSchema,ia as featureInputSchema,za as featureMarkupsOverrideSchema,Ia as featureOptionsSchema,xh as featurePayloadSchema,Ga as featureRecordSchema,ja as featureSchema,Fa as featureUpdateRulesSchema,Zc as featureUsageReadSchema,_c as featureUsageSetSchema,$c as featureUsageStateSchema,va as featureUsageTypeSchema,Ja as featureWriteSchema,Ie as fieldValue,de as fillSchema,ad as financialAmountSchema,dd as financialCursorSchema,cd as financialEntryTypeSchema,Qe as findDocumentNode,Pe as findNode,mm as formatCouponConditions,tb as formatCouponDiscount,sb as formatCouponMoney,ub as formatCouponTerms,J as formatCurrencyMinor,Im as formatProductBillingPeriod,Fb as formatUsd,Si as funnelApiBindingSchema,Pi as funnelApiProjectionSchema,im as funnelAuthorDraftSchema,Ii as funnelBundleDefinitionSchema,Mi as funnelBundleLiterals,Li as funnelBundleResultSchema,Ji as funnelBundleSelectionSchema,Yl as funnelCampaignCommandSchema,_l as funnelCampaignStartDeliverySchema,Zl as funnelCampaignStartResponseSchema,Ti as funnelCapabilitySchema,zj as funnelCommandSchema,am as funnelConfigurationSchema,hj as funnelConsumedVariables,hm as funnelContentDraftSchema,jm as funnelContentPublishedSchema,fm as funnelContentReferenceSchema,cn as funnelContextDelta,Vl as funnelCredentialCommandSchema,Xl as funnelCredentialDeliverySchema,Wl as funnelCredentialResponseSchema,yj as funnelDataQueriesSchema,Ei as funnelDecideShape,Fi as funnelDecisionCommandSchema,Rh as funnelDecisionEvaluationSchema,Ci as funnelDecisionOutputSchema,Gi as funnelDecisionResponseSchema,Di as funnelDecisionSchema,Uh as funnelDecisionSegmentEvaluationSchema,Hi as funnelDecisionUsedResponseSchema,qj as funnelDocumentDraftSchema,uj as funnelDocumentSchema,Wh as funnelEvaluationAttributes,Qh as funnelEvaluationInstructionSchema,Oh as funnelEvaluationModeSchema,Ph as funnelEvaluationResultSchema,bi as funnelExecutionPolicySchema,nj as funnelExecutionStateSchema,Vi as funnelExternalPageUrlSchema,ai as funnelExternalTaskSchema,Yi as funnelGraphDraftSchema,Xi as funnelGraphNodeSchema,Zi as funnelGraphSchema,_i as funnelGraphTargets,Ol as funnelInstructionSchema,Kl as funnelInvocationId,bm as funnelLocalConfigurationSchema,Ll as funnelLocalScreenCommandSchema,Ml as funnelLocalScreenResponseSchema,Th as funnelLocalSegmentStepSchema,lj as funnelNodeInputSchema,jj as funnelNodeKindSchema,Ze as funnelNodeProjections,mj as funnelNodeResultSchema,gj as funnelNodeVisitAllowed,We as funnelNodeWritesSchema,Wi as funnelOpenInSchema,gi as funnelOrchestrationCommandSchema,Lh as funnelParametersFromUrl,xj as funnelPresentationSubmissionSchema,Ni as funnelProjectionFilterValueSchema,Oi as funnelProjectionWhereSchema,wj as funnelPublicationDraftSchema,sj as funnelPublicationRules,vj as funnelPublicationSchema,tj as funnelPublishableDraftSchema,Zm as funnelPureNode,kj as funnelResourceReferenceSchema,xm as funnelResultsCursorSchema,ym as funnelResultsQuerySchema,ji as funnelResultsResponseSchema,zm as funnelResultsSchema,Ql as funnelRunViewSchema,Sl as funnelRuntimeDeliverySchema,Rl as funnelRuntimeResponseSchema,Nl as funnelRuntimeStatusSchema,gf as funnelScreenReads,ff as funnelScreenTokens,hf as funnelScreenValues,kn as funnelSegmentConfigurationSchema,Sh as funnelSegmentEvaluationInstructionSchema,_m as funnelSegmentPositionSchema,an as funnelSegmentSchema,$m as funnelSegmentStepSchema,hi as funnelSignalResponseSchema,bn as funnelStepId,$h as funnelTaskBindingSchema,Zh as funnelTaskDataSchema,_h as funnelTaskOutputsSchema,di as funnelTaskResponseSchema,ii as funnelTaskResultsSchema,cm as funnelTopology,$l as funnelTopologySchema,oj as funnelTraceEventSchema,af as funnelValueBindingSchema,Te as funnelValueDeclarationSchema,Xe as funnelValueMatches,$e as funnelValuePathSchema,Vh as funnelValueSchema,Ue as funnelVariableDeclarationSchema,Ve as funnelVariableDeclarationsSchema,ef as funnelVariableRead,Ye as funnelVariableValues,ej as funnelVisitAllowed,ij as funnelWaitKindSchema,th as gbRuntimeExperimentResultSchema,sh as gbRuntimeExperimentSchema,uh as gbRuntimeFeatureRuleSchema,vh as gbRuntimeFeatureSchema,wh as gbRuntimeSavedGroupsSchema,Na as getQueryStringOverride,Sa as getStickyBucketAttributes,Wa as growthAttributesSchema,Za as growthConditionGroupIds,Yh as growthConditionPaths,Xa as growthConditionSchema,fb as growthExperimentStop,gb as growthFeatureExpiry,$a as growthFeatureRuleSchema,ab as growthFeatureSchema,bb as growthFeaturesSchema,Ya as growthGroupSchema,kb as growthRuleContextSchema,_a as growthSavedGroupsSchema,ib as growthSnapshotSchema,lb as growthSplitResultSchema,Pd as htmlVariableErrors,$j as hydratePaywall,Vd as identifierSchema,ke as imageNodeSchema,ce as imagePositionSchema,ae as insetsSchema,pl as invoiceCommandSchema,Uc as invoiceDetailInputSchema,Wc as invoiceDetailSchema,sl as invoiceOperationSchema,Vc as invoiceProductItemSchema,cg as invoiceRefundsSchema,ol as invoiceTemplateCommandSchema,nl as invoiceTemplatePageSchema,ll as invoiceTemplateValuesSchema,Rb as isInvoiceCreditPrice,Dd as isProductGroup,Em as isRecurringMembership,Re as isRtlLocale,y as isStableSdkProtocol,Pa as isURLTargeted,Pb as itemBillingCycleSchema,kf as jsonStorageBytes,Va as jsonValueSchema,P as licenseOfferSchema,ic as listBillingInvoicesInputSchema,j as localErrorRecovery,qb as localeLabel,mb as localeSchema,Je as localeStatuses,Oe as localizeScreen,$b as manageBillingLimitsInputSchema,_b as manageOveragePolicyInputSchema,rl as managedInvoiceDetailSchema,tl as managedInvoicePageSchema,ql as managedInvoiceSchema,ml as managedInvoiceTemplateSchema,d as managementErrorCodeSchema,p as managementErrorResponseSchema,be as marginSchema,ob as matchLocale,Xh as matchesGrowthCondition,km as materializeFunnelContent,ca as membershipActionSchema,Gm as membershipBillingCount,da as membershipChangeSchema,ea as membershipHoldingSchema,aa as membershipRulesSchema,fa as membershipStateSchema,ba as membershipTimingSchema,ha as metadataSchema,Ba as meteredConfigSchema,I as minorToAmount,ya as modelMarkupsSchema,Bm as nativeCompletionSchema,yf as nativeCouponStoreOfferLinkWriteSchema,zf as nativeCouponStoreOfferLinksSchema,Am as nativeProofSchema,Ef as nativePurchaseInstructionSchema,Cm as nativeReceiptCommandSchema,Dm as nativeReceiptResponseSchema,Eg as nativeRestoreCommandSchema,Fg as nativeRestoreResultSchema,Cf as nativeStoreOfferForProduct,Af as nativeStoreOfferSelectionSchema,Bf as nativeStoreOfferSelectionsSchema,Df as nativeStoreSelectionMatches,Wf as nativeSubscriptionUpdatePreviewSchema,Xf as nativeSubscriptionUpdateResultSchema,Cb as newCouponInput,qh as newEnvironmentAnalyticsConfig,Ud as nodeIdSchema,rj as offerCopyUnscoped,Hb as offerSchema,Ib as offerUnavailableReasonSchema,Tg as offeringCollectionSchema,Pg as offeringDocumentSchema,Lg as offeringItemSchema,Mg as offeringItemsSchema,Hg as offeringMetadataSchema,Qg as offeringProductEvidenceSchema,Gg as offeringProductIdSchema,Ng as offeringProductIds,Xg as offeringProductOptionSchema,Og as offeringProductPaths,Zg as offeringPublicationIssues,Rg as offeringRecordSchema,Wg as offeringSelectorSchema,_g as offeringValueSchema,Sg as offeringVersionSchema,Yg as offeringWorkspaceSchema,Vg as offeringWriteResultSchema,Ug as offeringWriteSchema,Hc as overageBehaviorSchema,ac as overagePolicySchema,pj as ownedFunnelScreenSchema,Lm as pageExperimentEventSchema,Mm as pageExperimentEventsRequestSchema,Nm as pageExperimentEventsResponseSchema,Km as pageExperimentPayloadSchema,Jm as pageExperimentSchema,_d as paintColorSchema,Wj as parsePublicFunnel,m as parseRetryAfter,ng as paymentSetupCommandSchema,og as paymentSetupReadSchema,qg as paymentSetupSchema,sd as paywallCandidateSchema,dh as paywallClientActionSchema,jh as paywallCollectionSchema,Zj as paywallDeliverySchema,eh as paywallDocumentDraftSchema,fh as paywallDocumentSchema,hh as paywallFlowIssues,mh as paywallLibrarySchema,gh as paywallProductIssues,$g as paywallProductsSchema,ih as paywallRecordSchema,ud as paywallRequestSchema,Yj as paywallResolutionSchema,Xj as paywallResolveInputSchema,kh as paywallSummarySchema,lh as paywallWriteSchema,ma as planConfigSchema,na as planInputSchema,la as planItemSchema,te as planPickerNodeSchema,oa as planSchema,qa as planVersionSchema,Fc as prepaidAllowanceAmount,La as prepaidPriceAmount,Ma as prepaidQuantityAmount,Gc as prepaidQuantitySchema,Ka as prepaidTierPricingSchema,Tb as prepareBillingAuthorizationInputSchema,fn as prepareLocalFunnelNodes,Qa as prepareSavedGroups,Wb as preparedBillingAuthorizationSchema,Be as presentationSchema,qe as priceNodeSchema,ka as priceSchema,sc as productAllowanceSchema,Dc as productCollectionSchema,vc as productConfigurationSchema,yc as productDefinitionSchema,Ec as productEditorOptionsSchema,Hd as productGroupingMatches,Gd as productGroupingSchema,uc as productLicenseSchema,Bc as productOptionsSchema,rc as productPrepaidPriceSchema,qc as productPricesSchema,Cc as productRecordSchema,bh as productSelectionSchema,tc as productTrialSchema,wc as productVariantOverridesSchema,xc as productVariantSchema,Qi as projectFunnelApiOutputs,dm as projectFunnelConfiguration,em as projectFunnelLocalConfiguration,Bb as promotionCodeInputSchema,x as protocolForSdkVersion,xa as providerMarkupsSchema,oh as publicCouponScreenDataSchema,zh as publicFeatureConfigurationSchema,Wm as publicFunnelDocument,Fj as publicPaywallBenefitSchema,Jj as publicPaywallButtonSchema,Gj as publicPaywallChannelsSchema,Ij as publicPaywallCouponSchema,Ej as publicPaywallPriceSchema,Hj as publicPaywallProductSchema,Kj as publicPaywallSchema,Hh as publicScreenDocument,Fh as publicScreenIssues,Ke as publishChecks,wg as purchaseListItemSchema,Cg as purchaseListPageSchema,Xd as radiusSchema,bf as readFunnelValuePath,Jk as redeemRewardRequestSchema,Nk as referralCodeSchema,Pk as referralProgramCollectionSchema,Ck as referralProgramInputSchema,Ek as referralProgramRecordSchema,Hk as referralProgramWriteSchema,Bh as remoteFeatureResultSchema,jf as renameFunnelScreenVariable,Ee as replaceFirstPageRoot,Cj as resolveCouponDisplay,Ki as resolveFunnelBundle,Ui as resolveFunnelCapabilityInputs,fi as resolveFunnelTaskInputs,cf as resolveFunnelValueBinding,df as resolveFunnelValueBindings,zc as resolveProductVariant,Ne as resolveScreenLocale,C as resolveSdkProtocol,xl as responseMetaSchema,Yb as revokeBillingAuthorizationInputSchema,Rk as rewardActivityRedemptionSchema,Sk as rewardActivitySchema,Bk as rewardCodeInputSchema,Qk as rewardCodeSchema,Tk as rewardCodeWriteSchema,Ok as rewardCollectionSchema,yk as rewardConfigurationSchema,wk as rewardGrantExpirySchema,xk as rewardGrantSchema,Ak as rewardInputSchema,zk as rewardKeySchema,Fk as rewardOptionSchema,Lk as rewardProductCheckoutSchema,Dk as rewardRecordSchema,Ik as rewardRedemptionSchema,vk as rewardStatusSchema,uk as rewardTypeSchema,Gk as rewardWriteSchema,Ta as runExperiment,Hm as sameMembershipBillingCycle,Gl as saveSurfaceTemplateSchema,b as scopeSchema,xe as screenActionSchema,Jh as screenAnswersSchema,Ih as screenDataCursorSchema,Fe as screenDocumentSchema,Yd as screenImageSourceSchema,Mh as screenInputBindingsSchema,we as screenNodeSchema,Kh as screenParametersSchema,ch as screenPresentationSchema,Ed as screenProductScopes,Fd as screenProductSelections,Nh as screenRendererInputSchema,Se as screenSelections,ye as screenStringsSchema,Rj as sdkConfigurationManifestSchema,w as sdkProtocolRegistry,D as sdkProtocolResponseHeaders,id as seatCommandSchema,hd as seatReadSchema,jd as seatsStateSchema,aj as selectFunnelCondition,ah as selectedPaywallProduct,Cd as selectedSurfaceValue,Me as servableLocales,lc as setBillingCouponsInputSchema,ge as shadowSchema,ee as shapeSchema,$d as sizeSchema,Wd as spaceSchema,oe as spacerNodeSchema,ga as stableKeySchema,ue as stackInteractionSchema,ve as stackNodeSchema,jb as stickyAssignmentDocumentSchema,Nf as stripeAppendContextSchema,Mf as stripeCouponTermsSchema,Of as stripePurchaseExecutionSchema,$f as stripeRefundExecutionSchema,pg as stripeSetupExecutionSchema,Tf as stripeSubscriptionUpdateExecutionSchema,Uf as stripeSubscriptionUpdatePreviewSchema,Vf as stripeSubscriptionUpdateResultSchema,kg as stripeTrialExecutionSchema,ie as styleSchema,Kf as subscriptionAttachCommandSchema,Pf as subscriptionAttachQuoteSchema,eg as subscriptionBatchCommandSchema,gg as subscriptionBatchGroupSchema,fg as subscriptionBatchReadSchema,hg as subscriptionBatchSchema,Rf as subscriptionCarryOptionsSchema,Dg as subscriptionConflictPageSchema,yg as subscriptionConflictQuerySchema,Ag as subscriptionConflictRetryResultSchema,zg as subscriptionConflictRetrySchema,xg as subscriptionConflictSchema,kc as subscriptionCouponExecutionSchema,ul as subscriptionInvoiceModeSchema,vg as subscriptionListItemSchema,Bg as subscriptionListPageSchema,Lf as subscriptionOperationInputSchema,Qf as subscriptionOperationSchema,_f as subscriptionRefundCommandSchema,ag as subscriptionRefundPreviewSchema,bg as subscriptionRefundResultSchema,ig as subscriptionTrialCommandSchema,mg as subscriptionTrialPolicySchema,jg as subscriptionTrialReadSchema,lg as subscriptionTrialResultSchema,Sf as subscriptionUpdateCommandSchema,Yf as subscriptionUpdatePreviewSchema,Zf as subscriptionUpdateResultSchema,rg as subscriptionVerificationInputSchema,sg as subscriptionVerificationSchema,Rd as substituteHtmlVariables,Bd as substituteSurfaceVariables,yd as surfaceDataSchema,ze as surfaceSchema,Fl as surfaceTemplateSchema,xd as surfaceValueSchema,zd as surfaceVariableNames,Le as templateChecks,El as templateCoverImageSchema,je as textNodeSchema,he as textStyleSchema,Zd as themeSchema,Oa as toAttributeString,Dh as trackEventsRequestSchema,Eh as trackEventsResultSchema,bj as transitionFunnelGraph,He as translatableFields,_ as trialPolicySchema,$ as trialRecordSchema,Ad as unknownSurfaceVariables,qk as usageAnalyticsPageSchema,pk as usageAnalyticsQuerySchema,tk as usageBatchPageSchema,sk as usageBatchReadSchema,rk as usageBatchSubmitSchema,dk as usageEntityCommandSchema,ek as usageEntitySchema,lm as validateFunnelContentPublication,$i as validateFunnelGraph,_e as validateFunnelProjections,ei as validateFunnelTaskData,Aj as validateScreenAnswers,A as validateSdkProtocolRegistry,ra as validitySchema,wl as verifiedPrincipalSchema,Sm as visualChangeSchema,Vm as visualExperimentPayloadSchema,Um as visualExperimentSchema,Rm as visualMutationSchema,Tm as visualVariationSchema,De as walkDocument,Ge as walkScreen};
package/dist/visual.d.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  import { J as JsonValue, R as Result } from './growth-rules-B4YYy64R.js';
2
2
  import 'zod';
3
3
 
4
+ /** Optional post-build release descriptor. Keeps bundler CSS output out of a digest/rebuild cycle. */
5
+ declare function loadAppManifestRelease(path: string, document: Document, signal: AbortSignal): Promise<string>;
6
+
4
7
  type VisualExperimentsOptions = {
5
8
  environmentId: string;
6
9
  baseUrl?: string;
@@ -13,7 +16,7 @@ type VisualExperimentsOptions = {
13
16
  antiFlickerTimeout?: number;
14
17
  fetch?: typeof globalThis.fetch;
15
18
  log?: (message: string, details: Record<string, unknown>) => void;
16
- /** Exact IAM file digest emitted by the local build. Only this version's IAM experiments are eligible. */
19
+ /** Exact local IAM digest. Delivery safely rebinds compatible authored changes to this release. */
17
20
  appManifestRelease?: string;
18
21
  };
19
22
  declare function createVisualExperiments(options: VisualExperimentsOptions): {
@@ -46,4 +49,4 @@ declare function createVisualExperiments(options: VisualExperimentsOptions): {
46
49
  };
47
50
  type VisualExperiments = ReturnType<typeof createVisualExperiments>;
48
51
 
49
- export { type VisualExperiments, type VisualExperimentsOptions, createVisualExperiments };
52
+ export { type VisualExperiments, type VisualExperimentsOptions, createVisualExperiments, loadAppManifestRelease };
package/dist/visual.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as ce}from"./chunk-WCFVNF5D.js";import{c as de}from"./chunk-J4RHVU3W.js";import{a as me,b as he,c as ge,d as ye,f as ve}from"./chunk-YAFMBXIE.js";import"./chunk-3SONNXFG.js";import"./chunk-U6S6AZM6.js";import"./chunk-4K25DELJ.js";import"./chunk-S5TVMQRC.js";import"./chunk-RRII2DMC.js";import{h as fe,k as pe,m as B}from"./chunk-KQCTDXVD.js";async function be(e,t){let r=e?.body;if(!r)return;let n=r.getReader(),o=0,a=!1,s,i=new Promise((g,d)=>{s=setTimeout(()=>d(Error("Exposure response timeout")),2e3)}),u=()=>{},c=new Promise((g,d)=>{u=()=>d(t?.reason),t?.addEventListener("abort",u,{once:!0}),t?.aborted&&u()});try{for(;;){let g=await Promise.race([n.read(),i,c]);if(g.done){a=!0;return}if(o+=g.value.byteLength,o>16384)throw Error("Exposure response budget")}}finally{clearTimeout(s),t?.removeEventListener("abort",u),a||n.cancel().catch(()=>{}),n.releaseLock()}}var we=2*1024*1024,At=256*1024;async function Ee(e,t,r,n){let o=()=>{},a=new Promise((s,i)=>{o=()=>i(n.reason),n.addEventListener("abort",o,{once:!0}),n.aborted&&o()});try{let s=e(t,{...r,signal:n});return s.then(i=>{n.aborted&&i.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([s,a])}finally{n.removeEventListener("abort",o)}}async function Ve(e,t,r,n=!1){if(new TextEncoder().encode(r).byteLength>65536)throw Error("Exposure request budget");let o=new AbortController,a=setTimeout(()=>o.abort(Error("Exposure request timeout")),5e3);try{let s=await Ee(e,t,{method:"POST",headers:{"Content-Type":"text/plain"},body:r,credentials:"omit",keepalive:n,redirect:"error"},o.signal);await be(s,o.signal)}finally{clearTimeout(a)}}function Ae(e){let t,r=!1;return{async read(n,o){if(r)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let a=new AbortController;t=a;let{signal:s}=a,i=setTimeout(()=>a.abort(Error("Experiment request timeout")),5e3);try{let u=await Ee(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},s),c=await ce(u,o,s);return s.throwIfAborted(),c}finally{clearTimeout(i),t===a&&(t=void 0)}},destroy(){r=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}function J(e,t=()=>{}){let r=new WeakMap,n=0,o=a=>{let s=r.get(a);if(s!==void 0)return s;let i=[],u=a,c=!0;for(;u;){let g=r.get(u);if(g!==void 0){c=g;break}if(++n>8192||i.length>=256)throw Error("IAM render ancestry budget exceeded");if(i.push(u),t(),u.hasAttribute("hidden")||/(?:^|;)\s*display\s*:\s*none\s*(?:!\s*important\s*)?(?:;|$)/i.test(u.getAttribute("style")??"")){c=!1;break}u=u.parentElement}for(let g of i)r.set(g,c);return c};return a=>{let s=0,i=e.querySelectorAll(a);for(let u=0;u<i.length;u++){let c=i[u];if(!c)throw Error("IAM render selection changed");o(c)&&s++,t()}return s}}var je=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function j(e){if(!je(e)||Object.keys(e).some(a=>!["schemaVersion","renderKey","routeTemplate","selectors","present","absent"].includes(a))||e.schemaVersion!==1||typeof e.renderKey!="string"||!e.renderKey||e.renderKey.length>256||typeof e.routeTemplate!="string"||!e.routeTemplate.startsWith("/")||e.routeTemplate.length>2048||!Array.isArray(e.selectors)||e.selectors.length>512||e.selectors.some(a=>typeof a!="string"||a.length>512||!/^[a-z][a-z0-9-]*\[data-indiana-id="(?:[^"\\\x00-\x1f]|\\["\\])*"\]$/.test(a))||!Array.isArray(e.present)||!Array.isArray(e.absent))throw new Error("Invalid IAM render guard");if(e.present.length===0)throw Error("IAM render needs positive source evidence");let t=e.selectors,r=e.present,n=e.absent,o=[...r,...n];if(new Set(t).size!==t.length||o.length!==t.length||new Set(o).size!==o.length||o.some(a=>typeof a!="number"||!Number.isInteger(a)||a<0||a>=t.length))throw new Error("Invalid IAM render signature");return{schemaVersion:1,renderKey:e.renderKey,routeTemplate:e.routeTemplate,selectors:e.selectors,present:e.present,absent:e.absent}}function Ue(e,t){let r=e.split("/").filter(Boolean),n="";for(let o of r)/^\[\[\.\.\.[^\[\]]+\]\]$/.test(o)?n+="(?:/[^/]+)*":/^\[\.\.\.[^\[\]]+\]$/.test(o)?n+="(?:/[^/]+)+":/^\[[^\[\]]+\]$/.test(o)?n+="/[^/]+":n+="/"+o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+(n?n+"/?":"/")+"$").test(t)&&!/[\[\]]/.test(t)}function Me(e,t,r,n,o=J(t,n)){if(!Ue(e.routeTemplate,r))return!1;let a=new Set(e.present),s=!0;for(let i=0;i<e.selectors.length;i++){let u=o(e.selectors[i]);if(a.has(i)&&u>1)throw new Error("IAM render anchor is ambiguous");(a.has(i)?u!==1:u!==0)&&(s=!1),n()}return s}var _=new WeakMap,Z=new WeakSet;function Q(e){Z.add(e)}function He(e){let t=new Set,r=new Set,n,o=0,a=!1,s=()=>{t.size||o||(n?.disconnect(),e.removeEventListener("visibilitychange",u),_.delete(e))};function i(c){if(e.hidden)return;let g=performance.now(),d=new Map,m=new Map,b=()=>{if(performance.now()-g>8)throw Error("IAM page check exceeded its work budget")},M=l=>{b();let f=d.get(l);return f||(f=e.querySelectorAll(l),d.set(l,f)),b(),f},A=J({querySelectorAll:M},b),y={query:M,checkpoint:b,matches(l,f){let p=m.get(f);if(!p){try{p={match:Me(l,e,location.pathname,b,A)}}catch(h){p={error:h}}m.set(f,p)}if("error"in p)throw p.error;return p.match}},x=[],k=[],L=[];for(let l of c)if(t.has(l))try{x.push({job:l,commit:l.prepare(y)})}catch(f){k.push({job:l,error:f})}try{b()}catch(l){for(let f of[...t])f.fail(l);return}for(let{job:l,error:f}of k)t.has(l)&&l.fail(f);for(let{job:l,commit:f}of x)if(t.has(l))try{b(),f(p=>L.push(p))}catch(p){l.fail(p)}for(let l of L)l()}function u(){a||!t.size||e.hidden||(a=!0,queueMicrotask(()=>{a=!1,i([...t])}))}return{begin(){o++},end(){--o===0&&(r.clear(),i([...t])),s()},add(c){return n||(n=new MutationObserver(g=>{let d=m=>Z.has(m)||!!(m.parentNode&&Z.has(m.parentNode));g.some(m=>!d(m.target)&&!(m.type==="childList"&&[...m.addedNodes,...m.removedNodes].length>0&&[...m.addedNodes,...m.removedNodes].every(d)))&&u()}),n.observe(e.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["style","hidden","data-indiana-id","data-indiana-release","data-testid","id","name"]}),e.addEventListener("visibilitychange",u)),t.add(c),o?r.add(c):i([c]),()=>{t.delete(c),r.delete(c),s()}}}}function Se(){let e=_.get(document);return e||(e=He(document),_.set(document,e)),e}function xe(e){return Se().add(e)}function ke(e){let t=Se();t.begin();try{e()}finally{t.end()}}var ze=/^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/,te={revert:function(){}},W=new Map,re=new Set;function We(e){return e==="html"?{childList:!0,subtree:!0,attributes:!0,characterData:!0}:{childList:!1,subtree:!1,attributes:!0,attributeFilter:[e]}}function F(e){var t=W.get(e);return t||(t={element:e,attributes:{}},W.set(e,t)),t}function K(e,t,r,n,o){var a=r(e),s={isDirty:!1,originalValue:a,virtualValue:a,mutations:[],el:e,_positionTimeout:null,observer:new MutationObserver(function(){if(!dt&&!(t==="position"&&s._positionTimeout)){t==="position"&&(s._positionTimeout=setTimeout(function(){s._positionTimeout=null},1e3));var i=r(e);t==="position"&&i.parentNode===s.virtualValue.parentNode&&i.insertBeforeNode===s.virtualValue.insertBeforeNode||i!==s.virtualValue&&(s.originalValue=i,o(s))}}),mutationRunner:o,setValue:n,getCurrentValue:r};return t==="position"&&e.parentNode?s.observer.observe(e.parentNode,{childList:!0,subtree:!0,attributes:!1,characterData:!1}):s.observer.observe(e,We(t)),s}function $(e,t){var r=t.getCurrentValue(t.el);t.virtualValue=e,e&&typeof e!="string"?(!r||e.parentNode!==r.parentNode||e.insertBeforeNode!==r.insertBeforeNode)&&(t.isDirty=!0,Re()):e!==r&&(t.isDirty=!0,Re())}function Fe(e){var t=e.originalValue;e.mutations.forEach(function(r){return t=r.mutate(t)}),$(st(t),e)}function Ke(e){var t=new Set(e.originalValue.split(/\s+/).filter(Boolean));e.mutations.forEach(function(r){return r.mutate(t)}),$(Array.from(t).filter(Boolean).join(" "),e)}function $e(e){var t=e.originalValue;e.mutations.forEach(function(r){return t=r.mutate(t)}),$(t,e)}function Ye(e){var t=e.parentSelector,r=e.insertBeforeSelector,n=document.querySelector(t);if(!n)return null;var o=r?document.querySelector(r):null;return r&&!o?null:{parentNode:n,insertBeforeNode:o}}function _e(e){var t=e.originalValue;e.mutations.forEach(function(r){var n=r.mutate(),o=Ye(n);t=o||t}),$(t,e)}var Ze=function(t){return t.innerHTML},Qe=function(t,r){return t.innerHTML=r};function Te(e){var t=F(e);return t.html||(t.html=K(e,"html",Ze,Qe,Fe)),t.html}var Xe=function(t){return{parentNode:t.parentElement,insertBeforeNode:t.nextElementSibling}},et=function(t,r){r.insertBeforeNode&&!r.parentNode.contains(r.insertBeforeNode)||r.parentNode.insertBefore(t,r.insertBeforeNode)};function Le(e){var t=F(e);return t.position||(t.position=K(e,"position",Xe,et,_e)),t.position}var tt=function(t,r){return r?t.className=r:t.removeAttribute("class")},rt=function(t){return t.className};function Ne(e){var t=F(e);return t.classes||(t.classes=K(e,"class",rt,tt,Ke)),t.classes}var nt=function(t){return function(r){var n;return(n=r.getAttribute(t))!=null?n:null}},ot=function(t){return function(r,n){return n!==null?r.setAttribute(t,n):r.removeAttribute(t)}};function Pe(e,t){var r=F(e);return r.attributes[t]||(r.attributes[t]=K(e,t,nt(t),ot(t),$e)),r.attributes[t]}function it(e,t){var r=W.get(e);if(r)if(t==="html"){var n,o;(n=r.html)==null||(o=n.observer)==null||o.disconnect(),delete r.html}else if(t==="class"){var a,s;(a=r.classes)==null||(s=a.observer)==null||s.disconnect(),delete r.classes}else if(t==="position"){var i,u;(i=r.position)==null||(u=i.observer)==null||u.disconnect(),delete r.position}else{var c,g,d;(c=r.attributes)==null||(g=c[t])==null||(d=g.observer)==null||d.disconnect(),delete r.attributes[t]}}var U;function st(e){return U||(U=document.createElement("div")),U.innerHTML=e,U.innerHTML}function H(e,t,r){if(r.isDirty){r.isDirty=!1;var n=r.virtualValue;r.mutations.length||it(e,t),r.setValue(e,n)}}function at(e,t){e.html&&H(t,"html",e.html),e.classes&&H(t,"class",e.classes),e.position&&H(t,"position",e.position),Object.keys(e.attributes).forEach(function(r){H(t,r,e.attributes[r])})}function Re(){W.forEach(at)}function ut(e,t){var r=null;e.kind==="html"?r=Te(t):e.kind==="class"?r=Ne(t):e.kind==="attribute"?r=Pe(t,e.attribute):e.kind==="position"&&(r=Le(t)),r&&(r.mutations.push(e),r.mutationRunner(r))}function lt(e,t){var r=null;if(e.kind==="html"?r=Te(t):e.kind==="class"?r=Ne(t):e.kind==="attribute"?r=Pe(t,e.attribute):e.kind==="position"&&(r=Le(t)),!!r){var n=r.mutations.indexOf(e);n!==-1&&r.mutations.splice(n,1),r.mutationRunner(r)}}function Oe(e){if(!(e.kind==="position"&&e.elements.size===1)){var t=new Set(e.elements),r=document.querySelectorAll(e.selector);r.forEach(function(n){t.has(n)||(e.elements.add(n),ut(e,n))})}}function ct(e){e.elements.forEach(function(t){return lt(e,t)}),e.elements.clear(),re.delete(e)}function Ie(){re.forEach(Oe)}var dt=!1;var X;function ft(){typeof document>"u"||(X||(X=new MutationObserver(function(){Ie()})),Ie(),X.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}ft();function Y(e){return typeof document>"u"?te:(re.add(e),Oe(e),{revert:function(){ct(e)}})}function ee(e,t){return Y({kind:"html",elements:new Set,mutate:t,selector:e})}function qe(e,t){return Y({kind:"position",elements:new Set,mutate:t,selector:e})}function D(e,t){return Y({kind:"class",elements:new Set,mutate:t,selector:e})}function z(e,t,r){return ze.test(t)?t==="class"||t==="className"?D(e,function(n){var o=r(Array.from(n).join(" "));n.clear(),o&&o.split(/\s+/g).filter(Boolean).forEach(function(a){return n.add(a)})}):Y({kind:"attribute",attribute:t,elements:new Set,mutate:r,selector:e}):te}function pt(e){var t=e.selector,r=e.action,n=e.value,o=e.attribute,a=e.parentSelector,s=e.insertBeforeSelector;if(o==="html"){if(r==="append")return ee(t,function(i){return i+(n??"")});if(r==="set")return ee(t,function(){return n??""})}else if(o==="class"){if(r==="append")return D(t,function(i){n&&i.add(n)});if(r==="remove")return D(t,function(i){n&&i.delete(n)});if(r==="set")return D(t,function(i){i.clear(),n&&i.add(n)})}else if(o==="position"){if(r==="set"&&a)return qe(t,function(){return{insertBeforeSelector:s,parentSelector:a}})}else{if(r==="append")return z(t,o,function(i){return i!==null?i+(n??""):n??""});if(r==="set")return z(t,o,function(){return n??""});if(r==="remove")return z(t,o,function(){return null})}return te}var mt={html:ee,classes:D,attribute:z,position:qe,declarative:pt},ne=mt;import ht from"dompurify";var oe,Be;function gt(e){return(!oe||Be!==window)&&(oe=ht(window),Be=window),oe.sanitize(e,{USE_PROFILES:{html:!0},FORBID_TAGS:["form","input","textarea","select","button","style"]})}function De(e){let t={...e};if(!["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(t.attribute)&&!/^(aria|data)-[a-z0-9_-]+$/.test(t.attribute))throw new Error("Unsupported visual attribute");document.querySelector(t.selector);for(let r of document.querySelectorAll(t.selector))if(["SCRIPT","IFRAME","OBJECT","EMBED","HTML","HEAD"].includes(r.tagName)||r.tagName==="BODY"&&t.attribute==="html")throw new Error("Protected visual target");if(t.attribute==="html"&&(t.value=gt(t.value??"")),["href","src"].includes(t.attribute)&&t.action!=="remove"){let r=new URL(t.value??"",location.href);if(!["https:","http:","mailto:","tel:"].includes(r.protocol)||t.attribute==="src"&&!["https:","http:"].includes(r.protocol))throw new Error("Unsafe visual URL")}return t.parentSelector&&document.querySelector(t.parentSelector),t.insertBeforeSelector&&document.querySelector(t.insertBeforeSelector),t}function Ce(e,t={}){if(e.renderGuard&&!t.requireUniqueTargets)throw new Error("IAM render guard requires the source release fence");if(t.requireUniqueTargets)return yt(e,t);let r=e.domMutations.map(De),n=[],o=!1,a=!1,s,i=()=>{if(!o){o=!0,s?.disconnect();for(let c of n.reverse())c()}},u=()=>{o||a||(!r.length||e.css||t.allowJs&&e.js||r.some(c=>document.querySelector(c.selector)))&&(a=!0,t.onApplied?.())};try{if(e.css){let d=document.createElement("style");t.nonce&&(d.nonce=t.nonce),d.textContent=e.css,document.head.append(d),n.push(()=>d.remove())}for(let d of r){let m=ne.declarative(d);n.push(()=>m.revert())}if(t.allowJs&&e.js){let d=document.createElement("script");t.nonce&&(d.nonce=t.nonce),d.textContent=e.js,document.head.append(d),n.push(()=>d.remove())}let c=performance.now(),g=new WeakMap;s=new MutationObserver(d=>{if(!o){performance.now()-c>1e3&&(c=performance.now(),g=new WeakMap);for(let m of d){let b=(g.get(m.target)??0)+1;if(g.set(m.target,b),b>40){i(),t.onError?.(new Error("Visual changes conflict with repeated page rendering"));return}}u()}}),s.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),u()}catch(c){throw i(),c}return{revert:i,get applied(){return a}}}function yt(e,t){let r=t?.boundVariations??[e],n=new Set,o=new Set,a=[],s=new Map,i=r.flatMap(l=>l.renderGuard?[j(l.renderGuard)]:[]),u=i[0];if(i.some(l=>JSON.stringify(l)!==JSON.stringify(u)))throw new Error("IAM variations use different render states");if(e.js||r.some(l=>l.js))throw Error("IAM scripts cannot execute");if(r.length>20||r.reduce((l,f)=>l+f.css.length,0)>262144)throw Error("IAM target budget");let c=(l,f)=>{for(let h of l.domMutations){if(h.action!=="set"||h.attribute!=="html")throw Error("Unsupported IAM mutation");n.add(h.selector),o.add(h.selector)}if(!l.css)return;let p=document.createElement("style");Q(p),p.media="not all",t?.nonce&&(p.nonce=t.nonce),p.textContent=l.css;try{if(document.head.append(p),!p.sheet)throw Error("IAM CSS is blocked");for(let h of p.sheet.cssRules){if(!("selectorText"in h)||typeof h.selectorText!="string")throw Error("Unsupported IAM style rule");n.add(h.selectorText),f&&a.push({selector:h.selectorText,css:h.cssText})}}finally{p.remove()}};for(let l of r)c(l,!1);if(c(e,!0),n.size>200)throw Error("IAM target budget");let g=e.domMutations.map(De),d=!1,m=!1,b=!1,M={},A=u?JSON.stringify(u):"",y,x="",k=()=>{if(!d){d=!0,M.unsubscribe?.();for(let l of s.values())l.revert();s.clear(),y?.remove(),y=void 0,m=!1}},L=()=>{for(let l of s.values())l.revert();s.clear(),y?.remove(),y=void 0,x="",m=!1};return M.unsubscribe=xe({fail(l){k(),t?.onError?.(l)},prepare(l){if(u&&!l.matches(u,A))return()=>{d||L()};let f=new Map;for(let p of n){let h=l.query(p);if(h.length>1)throw Error("IAM target is ambiguous in this rendered state");if(h.length){if(o.has(p)&&h[0].children.length)throw Error("IAM text target is no longer a leaf");f.set(p,h[0])}l.checkpoint()}return p=>{if(d)return;for(let[E,R]of s)f.get(E)!==R.element&&(R.revert(),s.delete(E));for(let E of new Set(g.map(R=>R.selector))){let R=f.get(E);if(!R||s.has(E))continue;let P=g.filter(N=>N.selector===E).map(N=>ne.declarative(N));s.set(E,{element:R,revert:()=>P.forEach(N=>N.revert())})}let h=a.filter(E=>f.has(E.selector)).map(E=>E.css).join(`
2
- `);h!==x&&(x=h,h?(y||(y=document.createElement("style"),Q(y),t?.nonce&&(y.nonce=t.nonce),document.head.append(y)),y.textContent=h):(y?.remove(),y=void 0)),m=n.size===0||f.size>0,m&&!b&&(b=!0,p(()=>{d||t?.onApplied?.()}))}}}),d&&M.unsubscribe(),{revert:k,get applied(){return m}}}var C=e=>!!e&&typeof e=="object"&&!Array.isArray(e),q=(e,t)=>typeof e=="string"&&e.length<=t,vt=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function bt(e){if(!C(e)||!q(e.css??"",1e5)||!q(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let t=e.domMutations??[];for(let r of t)if(!C(r)||!q(r.selector,2048)||!r.selector||!vt(r.attribute)||!["set","append","remove"].includes(String(r.action))||r.value!==void 0&&!q(r.value,5e4)||r.parentSelector!==void 0&&!q(r.parentSelector,2048)||r.insertBeforeSelector!==void 0&&!q(r.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:t,...e.renderGuard===void 0?{}:{renderGuard:j(e.renderGuard)}}}function Ge(e){if(!C(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!C(e.savedGroups))throw new Error("Invalid visual experiment payload");let t=e.experiments.map(r=>{if(!C(r)||!["key","changeId"].every(n=>typeof r[n]=="string"&&r[n])||!/^[a-f0-9]{64}$/.test(String(r.changeId))||["namespace","status","groups","url"].some(n=>Object.hasOwn(r,n))||r.hashVersion!==void 0&&r.hashVersion!==2||!Array.isArray(r.variations)||r.variations.length<2||r.variations.length>20||r.urlPatterns!==void 0&&!Array.isArray(r.urlPatterns))throw new Error("Invalid visual experiment");return{...r,variations:r.variations.map(bt)}});return{...e,experiments:t}}function Kt(e){let t=ge(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let r=e.fetch??globalThis.fetch.bind(globalThis),n=Ae(r),o=`${t}/api/v1/visual-experiments/${e.environmentId}`,a=me(e.deviceIdCookie??"indiana_did"),s=he(),i=null,u=!1,c=!1,g="",d={...e.attributes??{}},m,b,M=0,A=new Map,y=new Map,x=new Set,k=[],L,l,f;function p(){clearTimeout(l),f?.remove(),f=void 0}function h(w=!1){clearTimeout(L),L=void 0;let V=k.splice(0,20);return V.length?Ve(r,`${o}/events`,JSON.stringify({events:V}),w).catch(I=>e.log?.("Visual exposure not sent",{error:I})):Promise.resolve()}function E(w,V){let I=B(w,V);x.has(I)||e.trackExposures===!1||i?.trackExposures===!1||u||(x.add(I),k.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:a,...s?{sessionId:s}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:w.key,variationKey:V.key}),k.length>=20?h():L??=setTimeout(()=>{h()},1e3))}function R(w){if(!i||u)return;let V=new Set,I={onExperimentViewed:(v,T)=>{V.add(B(v,T))},url:location.href,attributes:{...ve(a,location),...d,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:fe(i.savedGroups),log:e.log},G=new Set;for(let v of i.experiments){let T=v;try{let S=pe(T,I);if(y.set(v.changeId,S),!S.inExperiment)continue;G.add(v.changeId);let ae=JSON.stringify([S.key,S.value]),ue=A.get(v.changeId);if(ue?.signature===ae){V.has(B(T,S))&&w.push(()=>{ue.applied()&&E(T,S)});continue}A.get(v.changeId)?.revert(),A.delete(v.changeId);let le=Ce(S.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(v.condition?.$and)&&v.condition.$and.some(O=>O!==null&&typeof O=="object"&&!Array.isArray(O)&&O.indianaAppManifestRelease===e.appManifestRelease),boundVariations:v.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{V.has(B(T,S))&&E(T,S)},onError:O=>e.log?.("Visual experiment stopped",{experiment:v.key,error:String(O)})});A.set(v.changeId,{signature:ae,revert:le.revert,applied:()=>le.applied})}catch(S){e.log?.("Skipping visual experiment",{experiment:v.key,error:String(S)})}}for(let[v,T]of A)G.has(v)||(T.revert(),A.delete(v));p()}let P=()=>{let w=[];ke(()=>R(w));for(let V of w)V()};async function N(){let w=++M,V;try{V=await n.read(o,we)}catch(G){if(u||w!==M)return!1;throw G}let I=Ge(V);if(I.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return u||w!==M?!1:(i=I,!0)}let Je=()=>{g!==location.href&&(g=location.href,P())},ie=()=>{h(!0)},se=()=>{m||u||(m=ye(Je),addEventListener("pagehide",ie),g=location.href)};return{async start(){if(!(c||u)){c=!0,e.appManifestRelease&&(b=de(e.appManifestRelease)),e.antiFlicker&&(f=document.createElement("style"),e.nonce&&(f.nonce=e.nonce),f.textContent="body { visibility: hidden !important }",document.head.append(f),l=setTimeout(p,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await N()||u)return;se(),P()}finally{p()}}},async refresh(){u||await N()&&(c&&se(),P())},setAttributes(w){d={...w},P()},flush:()=>h(),getResults(){return new Map(y)},get generation(){return i?.generation??null},destroy(){u=!0,M++,n.destroy(),m?.(),b?.destroy(),removeEventListener("pagehide",ie),p();for(let w of A.values())w.revert();A.clear(),h(!0),i=null,y.clear(),x.clear(),d={}}}}export{Kt as createVisualExperiments};
1
+ import{a as pe,b as me,c as he,d as ge,f as be}from"./chunk-YAFMBXIE.js";import"./chunk-AE4CUTUE.js";import"./chunk-S5TVMQRC.js";import"./chunk-RRII2DMC.js";import{h as de,k as fe,m as D}from"./chunk-KQCTDXVD.js";async function ye(e,t,r,n={}){let o=n.message??"Invalid SDK JSON response",a=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||a!==null&&(!/^\d+$/.test(a)||Number(a)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(o);let i=e.body.getReader(),s=[],l=0,u=!1,p=()=>{},d=new Promise((f,y)=>{p=()=>y(Error(o)),r.addEventListener("abort",p,{once:!0}),r.aborted&&p()});try{for(;;){let w=await Promise.race([i.read(),d]);if(w.done){u=!0;break}if(l+=w.value.byteLength,l>t)throw Error(o);s.push(w.value)}let f=new Uint8Array(l),y=0;for(let w of s)f.set(w,y),y+=w.length;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(f))}finally{r.removeEventListener("abort",p),u||i.cancel().catch(()=>{}),i.releaseLock()}}async function ve(e,t){let r=e?.body;if(!r)return;let n=r.getReader(),o=0,a=!1,i,s=new Promise((p,d)=>{i=setTimeout(()=>d(Error("Exposure response timeout")),2e3)}),l=()=>{},u=new Promise((p,d)=>{l=()=>d(t?.reason),t?.addEventListener("abort",l,{once:!0}),t?.aborted&&l()});try{for(;;){let p=await Promise.race([n.read(),s,u]);if(p.done){a=!0;return}if(o+=p.value.byteLength,o>16384)throw Error("Exposure response budget")}}finally{clearTimeout(i),t?.removeEventListener("abort",l),a||n.cancel().catch(()=>{}),n.releaseLock()}}var we=2*1024*1024,Rt=256*1024;async function Ee(e,t,r,n){let o=()=>{},a=new Promise((i,s)=>{o=()=>s(n.reason),n.addEventListener("abort",o,{once:!0}),n.aborted&&o()});try{let i=e(t,{...r,signal:n});return i.then(s=>{n.aborted&&s.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([i,a])}finally{n.removeEventListener("abort",o)}}async function Ae(e,t,r,n=!1){if(new TextEncoder().encode(r).byteLength>65536)throw Error("Exposure request budget");let o=new AbortController,a=setTimeout(()=>o.abort(Error("Exposure request timeout")),5e3);try{let i=await Ee(e,t,{method:"POST",headers:{"Content-Type":"text/plain"},body:r,credentials:"omit",keepalive:n,redirect:"error"},o.signal);await ve(i,o.signal)}finally{clearTimeout(a)}}function Me(e){let t,r=!1;return{async read(n,o){if(r)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let a=new AbortController;t=a;let{signal:i}=a,s=setTimeout(()=>a.abort(Error("Experiment request timeout")),5e3);try{let l=await Ee(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},i),u=await ye(l,o,i);return i.throwIfAborted(),u}finally{clearTimeout(s),t===a&&(t=void 0)}},destroy(){r=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}function C(e,t=()=>{}){let r=new WeakMap,n=0,o=a=>{let i=r.get(a);if(i!==void 0)return i;let s=[],l=a,u=!0;for(;l;){let p=r.get(l);if(p!==void 0){u=p;break}if(++n>8192||s.length>=256)throw Error("IAM render ancestry budget exceeded");if(s.push(l),t(),l.hasAttribute("hidden")||/(?:^|;)\s*display\s*:\s*none\s*(?:!\s*important\s*)?(?:;|$)/i.test(l.getAttribute("style")??"")){u=!1;break}l=l.parentElement}for(let p of s)r.set(p,u);return u};return a=>{let i=0,s=e.querySelectorAll(a);for(let l=0;l<s.length;l++){let u=s[l];if(!u)throw Error("IAM render selection changed");o(u)&&i++,t()}return i}}var ze=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function J(e){if(!ze(e)||Object.keys(e).some(a=>!["schemaVersion","renderKey","routeTemplate","selectors","present","absent"].includes(a))||e.schemaVersion!==1||typeof e.renderKey!="string"||!e.renderKey||e.renderKey.length>256||typeof e.routeTemplate!="string"||!e.routeTemplate.startsWith("/")||e.routeTemplate.length>2048||!Array.isArray(e.selectors)||e.selectors.length>512||e.selectors.some(a=>typeof a!="string"||a.length>512||!/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/.test(a))||!Array.isArray(e.present)||!Array.isArray(e.absent))throw new Error("Invalid IAM render guard");if(e.present.length===0)throw Error("IAM render needs positive source evidence");let t=e.selectors,r=e.present,n=e.absent,o=[...r,...n];if(new Set(t).size!==t.length||o.length!==t.length||new Set(o).size!==o.length||o.some(a=>typeof a!="number"||!Number.isInteger(a)||a<0||a>=t.length))throw new Error("Invalid IAM render signature");return{schemaVersion:1,renderKey:e.renderKey,routeTemplate:e.routeTemplate,selectors:e.selectors,present:e.present,absent:e.absent}}function He(e,t){let r=e.split("/").filter(Boolean),n="";for(let o of r)/^\[\[\.\.\.[^\[\]]+\]\]$/.test(o)?n+="(?:/[^/]+)*":/^\[\.\.\.[^\[\]]+\]$/.test(o)?n+="(?:/[^/]+)+":/^\[[^\[\]]+\]$/.test(o)?n+="/[^/]+":n+="/"+o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+(n?n+"/?":"/")+"$").test(t)&&!/[\[\]]/.test(t)}function Ve(e,t,r,n,o=C(t,n)){if(!He(e.routeTemplate,r))return!1;let a=new Set(e.present),i=!0;for(let s=0;s<e.selectors.length;s++){let l=o(e.selectors[s]);if(a.has(s)&&l>1)throw new Error("IAM render anchor is ambiguous");(a.has(s)?l!==1:l!==0)&&(i=!1),n()}return i}var Y=new WeakMap,Z=new WeakSet;function Q(e){Z.add(e)}function $e(e){let t=new Set,r=new Set,n,o=0,a=!1,i=()=>{t.size||o||(n?.disconnect(),e.removeEventListener("visibilitychange",l),Y.delete(e))};function s(u){if(e.hidden)return;let p=performance.now(),d=new Map,f=new Map,y=()=>{if(performance.now()-p>8)throw Error("IAM page check exceeded its work budget")},w=c=>{y();let h=d.get(c);return h||(h=e.querySelectorAll(c),d.set(c,h)),y(),h},R=C({querySelectorAll:w},y),b={query:w,checkpoint:y,matches(c,h){let m=f.get(h);if(!m){try{m={match:Ve(c,e,location.pathname,y,R)}}catch(g){m={error:g}}f.set(h,m)}if("error"in m)throw m.error;return m.match}},k=[],v=[],M=[];for(let c of u)if(t.has(c))try{k.push({job:c,commit:c.prepare(b)})}catch(h){v.push({job:c,error:h})}try{y()}catch(c){for(let h of[...t])h.fail(c);return}for(let{job:c,error:h}of v)t.has(c)&&c.fail(h);for(let{job:c,commit:h}of k)if(t.has(c))try{y(),h(m=>M.push(m))}catch(m){c.fail(m)}for(let c of M)c()}function l(){a||!t.size||e.hidden||(a=!0,queueMicrotask(()=>{a=!1,s([...t])}))}return{begin(){o++},end(){--o===0&&(r.clear(),s([...t])),i()},add(u){return n||(n=new MutationObserver(p=>{let d=f=>Z.has(f)||!!(f.parentNode&&Z.has(f.parentNode));p.some(f=>!d(f.target)&&!(f.type==="childList"&&[...f.addedNodes,...f.removedNodes].length>0&&[...f.addedNodes,...f.removedNodes].every(d)))&&l()}),n.observe(e.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["style","hidden","data-indiana-id","data-indiana-release","data-testid","id","name"]}),e.addEventListener("visibilitychange",l)),t.add(u),o?r.add(u):s([u]),()=>{t.delete(u),r.delete(u),i()}}}}function Se(){let e=Y.get(document);return e||(e=$e(document),Y.set(document,e)),e}function ke(e){return Se().add(e)}function Re(e){let t=Se();t.begin();try{e()}finally{t.end()}}async function We(e,t,r){let n=new URL(e,t.baseURI),o=t.defaultView?.location.origin,a=/^\/\.well-known\/indiana\/releases\/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})\.json$/.exec(n.pathname)?.[1];if(!a||n.origin!==o||n.search||n.hash||n.username||n.password)throw Error("Invalid IAM release URL");let i=AbortSignal.any([r,AbortSignal.timeout(2e3)]),s=await fetch(n,{credentials:"omit",redirect:"error",cache:"force-cache",signal:i}),l=s.headers.get("content-length");if(!s.ok||!/^application\/json(?:;|$)/i.test(s.headers.get("content-type")??"")||l!==null&&(!/^\d+$/.test(l)||Number(l)>512))throw s.body?.cancel().catch(()=>{}),Error("IAM release is unavailable");let u=s.body?.getReader();if(!u)throw Error("IAM release is unavailable");let p=[],d=0,f=()=>{},y=new Promise((M,c)=>{f=()=>c(Error("IAM release timeout")),i.addEventListener("abort",f,{once:!0}),i.aborted&&f()}),w=!1;try{for(;;){let M=await Promise.race([u.read(),y]);if(M.done){w=!0;break}if(d+=M.value.length,d>512)throw Error("IAM release budget");p.push(M.value)}}finally{i.removeEventListener("abort",f),w||u.cancel().catch(()=>{}),u.releaseLock()}let R=new Uint8Array(d),b=0;for(let M of p)R.set(M,b),b+=M.length;let k=new TextDecoder("utf-8",{fatal:!0}).decode(R),v=JSON.parse(k);if(k.trim()!==JSON.stringify(v))throw Error("Noncanonical IAM release descriptor");if(!v||typeof v!="object"||Array.isArray(v)||Object.keys(v).sort().join(",")!=="format,manifestDigest,releaseId,schemaVersion"||Reflect.get(v,"format")!=="indiana-app-manifest-release"||Reflect.get(v,"schemaVersion")!==2||Reflect.get(v,"releaseId")!==a||!/^[a-f0-9]{64}$/.test(String(Reflect.get(v,"manifestDigest"))))throw Error("Invalid IAM release descriptor");return Reflect.get(v,"manifestDigest")}var xe=new WeakMap;function Ie(e,t=document){if(!/^[a-f0-9]{64}$/.test(e))throw new Error("Invalid IAM manifest digest");let r=xe.get(t);r||(r=new Map,xe.set(t,r));let n="data-indiana-release",o=t.documentElement,a=()=>new Set((o.getAttribute(n)??"").split(/\s+/).filter(Boolean)),i=r.get(e);if(!i){let l=a();i={count:0,owned:!l.has(e)},r.set(e,i),l.add(e),o.setAttribute(n,[...l].join(" "))}i.count++;let s=!1;return{attributes:{indianaAppManifestRelease:e},destroy(){if(!s&&(s=!0,i.count--,!i.count&&(r.delete(e),i.owned))){let l=a();l.delete(e),l.size?o.setAttribute(n,[...l].join(" ")):o.removeAttribute(n)}}}}var Fe=/^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/,te={revert:function(){}},H=new Map,re=new Set;function Ke(e){return e==="html"?{childList:!0,subtree:!0,attributes:!0,characterData:!0}:{childList:!1,subtree:!1,attributes:!0,attributeFilter:[e]}}function $(e){var t=H.get(e);return t||(t={element:e,attributes:{}},H.set(e,t)),t}function W(e,t,r,n,o){var a=r(e),i={isDirty:!1,originalValue:a,virtualValue:a,mutations:[],el:e,_positionTimeout:null,observer:new MutationObserver(function(){if(!mt&&!(t==="position"&&i._positionTimeout)){t==="position"&&(i._positionTimeout=setTimeout(function(){i._positionTimeout=null},1e3));var s=r(e);t==="position"&&s.parentNode===i.virtualValue.parentNode&&s.insertBeforeNode===i.virtualValue.insertBeforeNode||s!==i.virtualValue&&(i.originalValue=s,o(i))}}),mutationRunner:o,setValue:n,getCurrentValue:r};return t==="position"&&e.parentNode?i.observer.observe(e.parentNode,{childList:!0,subtree:!0,attributes:!1,characterData:!1}):i.observer.observe(e,Ke(t)),i}function F(e,t){var r=t.getCurrentValue(t.el);t.virtualValue=e,e&&typeof e!="string"?(!r||e.parentNode!==r.parentNode||e.insertBeforeNode!==r.insertBeforeNode)&&(t.isDirty=!0,Te()):e!==r&&(t.isDirty=!0,Te())}function _e(e){var t=e.originalValue;e.mutations.forEach(function(r){return t=r.mutate(t)}),F(ut(t),e)}function Ye(e){var t=new Set(e.originalValue.split(/\s+/).filter(Boolean));e.mutations.forEach(function(r){return r.mutate(t)}),F(Array.from(t).filter(Boolean).join(" "),e)}function Ze(e){var t=e.originalValue;e.mutations.forEach(function(r){return t=r.mutate(t)}),F(t,e)}function Qe(e){var t=e.parentSelector,r=e.insertBeforeSelector,n=document.querySelector(t);if(!n)return null;var o=r?document.querySelector(r):null;return r&&!o?null:{parentNode:n,insertBeforeNode:o}}function Xe(e){var t=e.originalValue;e.mutations.forEach(function(r){var n=r.mutate(),o=Qe(n);t=o||t}),F(t,e)}var et=function(t){return t.innerHTML},tt=function(t,r){return t.innerHTML=r};function Ne(e){var t=$(e);return t.html||(t.html=W(e,"html",et,tt,_e)),t.html}var rt=function(t){return{parentNode:t.parentElement,insertBeforeNode:t.nextElementSibling}},nt=function(t,r){r.insertBeforeNode&&!r.parentNode.contains(r.insertBeforeNode)||r.parentNode.insertBefore(t,r.insertBeforeNode)};function Pe(e){var t=$(e);return t.position||(t.position=W(e,"position",rt,nt,Xe)),t.position}var ot=function(t,r){return r?t.className=r:t.removeAttribute("class")},it=function(t){return t.className};function Oe(e){var t=$(e);return t.classes||(t.classes=W(e,"class",it,ot,Ye)),t.classes}var st=function(t){return function(r){var n;return(n=r.getAttribute(t))!=null?n:null}},at=function(t){return function(r,n){return n!==null?r.setAttribute(t,n):r.removeAttribute(t)}};function De(e,t){var r=$(e);return r.attributes[t]||(r.attributes[t]=W(e,t,st(t),at(t),Ze)),r.attributes[t]}function lt(e,t){var r=H.get(e);if(r)if(t==="html"){var n,o;(n=r.html)==null||(o=n.observer)==null||o.disconnect(),delete r.html}else if(t==="class"){var a,i;(a=r.classes)==null||(i=a.observer)==null||i.disconnect(),delete r.classes}else if(t==="position"){var s,l;(s=r.position)==null||(l=s.observer)==null||l.disconnect(),delete r.position}else{var u,p,d;(u=r.attributes)==null||(p=u[t])==null||(d=p.observer)==null||d.disconnect(),delete r.attributes[t]}}var U;function ut(e){return U||(U=document.createElement("div")),U.innerHTML=e,U.innerHTML}function G(e,t,r){if(r.isDirty){r.isDirty=!1;var n=r.virtualValue;r.mutations.length||lt(e,t),r.setValue(e,n)}}function ct(e,t){e.html&&G(t,"html",e.html),e.classes&&G(t,"class",e.classes),e.position&&G(t,"position",e.position),Object.keys(e.attributes).forEach(function(r){G(t,r,e.attributes[r])})}function Te(){H.forEach(ct)}function dt(e,t){var r=null;e.kind==="html"?r=Ne(t):e.kind==="class"?r=Oe(t):e.kind==="attribute"?r=De(t,e.attribute):e.kind==="position"&&(r=Pe(t)),r&&(r.mutations.push(e),r.mutationRunner(r))}function ft(e,t){var r=null;if(e.kind==="html"?r=Ne(t):e.kind==="class"?r=Oe(t):e.kind==="attribute"?r=De(t,e.attribute):e.kind==="position"&&(r=Pe(t)),!!r){var n=r.mutations.indexOf(e);n!==-1&&r.mutations.splice(n,1),r.mutationRunner(r)}}function qe(e){if(!(e.kind==="position"&&e.elements.size===1)){var t=new Set(e.elements),r=document.querySelectorAll(e.selector);r.forEach(function(n){t.has(n)||(e.elements.add(n),dt(e,n))})}}function pt(e){e.elements.forEach(function(t){return ft(e,t)}),e.elements.clear(),re.delete(e)}function Le(){re.forEach(qe)}var mt=!1;var X;function ht(){typeof document>"u"||(X||(X=new MutationObserver(function(){Le()})),Le(),X.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}ht();function K(e){return typeof document>"u"?te:(re.add(e),qe(e),{revert:function(){pt(e)}})}function ee(e,t){return K({kind:"html",elements:new Set,mutate:t,selector:e})}function Be(e,t){return K({kind:"position",elements:new Set,mutate:t,selector:e})}function q(e,t){return K({kind:"class",elements:new Set,mutate:t,selector:e})}function z(e,t,r){return Fe.test(t)?t==="class"||t==="className"?q(e,function(n){var o=r(Array.from(n).join(" "));n.clear(),o&&o.split(/\s+/g).filter(Boolean).forEach(function(a){return n.add(a)})}):K({kind:"attribute",attribute:t,elements:new Set,mutate:r,selector:e}):te}function gt(e){var t=e.selector,r=e.action,n=e.value,o=e.attribute,a=e.parentSelector,i=e.insertBeforeSelector;if(o==="html"){if(r==="append")return ee(t,function(s){return s+(n??"")});if(r==="set")return ee(t,function(){return n??""})}else if(o==="class"){if(r==="append")return q(t,function(s){n&&s.add(n)});if(r==="remove")return q(t,function(s){n&&s.delete(n)});if(r==="set")return q(t,function(s){s.clear(),n&&s.add(n)})}else if(o==="position"){if(r==="set"&&a)return Be(t,function(){return{insertBeforeSelector:i,parentSelector:a}})}else{if(r==="append")return z(t,o,function(s){return s!==null?s+(n??""):n??""});if(r==="set")return z(t,o,function(){return n??""});if(r==="remove")return z(t,o,function(){return null})}return te}var bt={html:ee,classes:q,attribute:z,position:Be,declarative:gt},ne=bt;import yt from"dompurify";var oe,je;function vt(e){return(!oe||je!==window)&&(oe=yt(window),je=window),oe.sanitize(e,{USE_PROFILES:{html:!0},FORBID_TAGS:["form","input","textarea","select","button","style"]})}function Ce(e){let t={...e};if(!["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(t.attribute)&&!/^(aria|data)-[a-z0-9_-]+$/.test(t.attribute))throw new Error("Unsupported visual attribute");document.querySelector(t.selector);for(let r of document.querySelectorAll(t.selector))if(["SCRIPT","IFRAME","OBJECT","EMBED","HTML","HEAD"].includes(r.tagName)||r.tagName==="BODY"&&t.attribute==="html")throw new Error("Protected visual target");if(t.attribute==="html"&&(t.value=vt(t.value??"")),["href","src"].includes(t.attribute)&&t.action!=="remove"){let r=new URL(t.value??"",location.href);if(!["https:","http:","mailto:","tel:"].includes(r.protocol)||t.attribute==="src"&&!["https:","http:"].includes(r.protocol))throw new Error("Unsafe visual URL")}return t.parentSelector&&document.querySelector(t.parentSelector),t.insertBeforeSelector&&document.querySelector(t.insertBeforeSelector),t}function Je(e,t={}){if(e.renderGuard&&!t.requireUniqueTargets)throw new Error("IAM render guard requires the source release fence");if(t.requireUniqueTargets)return wt(e,t);let r=e.domMutations.map(Ce),n=[],o=!1,a=!1,i,s=()=>{if(!o){o=!0,i?.disconnect();for(let u of n.reverse())u()}},l=()=>{o||a||(!r.length||e.css||t.allowJs&&e.js||r.some(u=>document.querySelector(u.selector)))&&(a=!0,t.onApplied?.())};try{if(e.css){let d=document.createElement("style");t.nonce&&(d.nonce=t.nonce),d.textContent=e.css,document.head.append(d),n.push(()=>d.remove())}for(let d of r){let f=ne.declarative(d);n.push(()=>f.revert())}if(t.allowJs&&e.js){let d=document.createElement("script");t.nonce&&(d.nonce=t.nonce),d.textContent=e.js,document.head.append(d),n.push(()=>d.remove())}let u=performance.now(),p=new WeakMap;i=new MutationObserver(d=>{if(!o){performance.now()-u>1e3&&(u=performance.now(),p=new WeakMap);for(let f of d){let y=(p.get(f.target)??0)+1;if(p.set(f.target,y),y>40){s(),t.onError?.(new Error("Visual changes conflict with repeated page rendering"));return}}l()}}),i.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),l()}catch(u){throw s(),u}return{revert:s,get applied(){return a}}}function wt(e,t){let r=t?.boundVariations??[e],n=new Set,o=new Set,a=[],i=new Map,s=r.flatMap(c=>c.renderGuard?[J(c.renderGuard)]:[]),l=s[0];if(s.some(c=>JSON.stringify(c)!==JSON.stringify(l)))throw new Error("IAM variations use different render states");if(e.js||r.some(c=>c.js))throw Error("IAM scripts cannot execute");if(r.length>20||r.reduce((c,h)=>c+h.css.length,0)>262144)throw Error("IAM target budget");let u=(c,h)=>{for(let g of c.domMutations){if(g.action!=="set"||g.attribute!=="html")throw Error("Unsupported IAM mutation");n.add(g.selector),o.add(g.selector)}if(!c.css)return;let m=document.createElement("style");Q(m),m.media="not all",t?.nonce&&(m.nonce=t.nonce),m.textContent=c.css;try{if(document.head.append(m),!m.sheet)throw Error("IAM CSS is blocked");for(let g of m.sheet.cssRules){if(!("selectorText"in g)||typeof g.selectorText!="string")throw Error("Unsupported IAM style rule");n.add(g.selectorText),h&&a.push({selector:g.selectorText,css:g.cssText})}}finally{m.remove()}};for(let c of r)u(c,!1);if(u(e,!0),n.size>200)throw Error("IAM target budget");let p=e.domMutations.map(Ce),d=!1,f=!1,y=!1,w={},R=l?JSON.stringify(l):"",b,k="",v=()=>{if(!d){d=!0,w.unsubscribe?.();for(let c of i.values())c.revert();i.clear(),b?.remove(),b=void 0,f=!1}},M=()=>{for(let c of i.values())c.revert();i.clear(),b?.remove(),b=void 0,k="",f=!1};return w.unsubscribe=ke({fail(c){v(),t?.onError?.(c)},prepare(c){if(l&&!c.matches(l,R))return()=>{d||M()};let h=new Map;for(let m of n){let g=c.query(m);if(g.length>1)throw Error("IAM target is ambiguous in this rendered state");if(g.length){if(o.has(m)&&g[0].children.length)throw Error("IAM text target is no longer a leaf");h.set(m,g[0])}c.checkpoint()}return m=>{if(d)return;for(let[E,I]of i)h.get(E)!==I.element&&(I.revert(),i.delete(E));for(let E of new Set(p.map(I=>I.selector))){let I=h.get(E);if(!I||i.has(E))continue;let _=p.filter(T=>T.selector===E).map(T=>ne.declarative(T));i.set(E,{element:I,revert:()=>_.forEach(T=>T.revert())})}let g=a.filter(E=>h.has(E.selector)).map(E=>E.css).join(`
2
+ `);g!==k&&(k=g,g?(b||(b=document.createElement("style"),Q(b),t?.nonce&&(b.nonce=t.nonce),document.head.append(b)),b.textContent=g):(b?.remove(),b=void 0)),f=n.size===0||h.size>0,f&&!y&&(y=!0,m(()=>{d||t?.onApplied?.()}))}}}),d&&w.unsubscribe(),{revert:v,get applied(){return f}}}var B=e=>!!e&&typeof e=="object"&&!Array.isArray(e),O=(e,t)=>typeof e=="string"&&e.length<=t,Et=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function At(e){if(!B(e)||!O(e.css??"",1e5)||!O(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let t=e.domMutations??[];for(let r of t)if(!B(r)||!O(r.selector,2048)||!r.selector||!Et(r.attribute)||!["set","append","remove"].includes(String(r.action))||r.value!==void 0&&!O(r.value,5e4)||r.parentSelector!==void 0&&!O(r.parentSelector,2048)||r.insertBeforeSelector!==void 0&&!O(r.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:t,...e.renderGuard===void 0?{}:{renderGuard:J(e.renderGuard)}}}function Ue(e){if(!B(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!B(e.savedGroups))throw new Error("Invalid visual experiment payload");let t=e.experiments.map(r=>{if(!B(r)||!["key","changeId"].every(n=>typeof r[n]=="string"&&r[n])||!/^[a-f0-9]{64}$/.test(String(r.changeId))||["namespace","status","groups","url"].some(n=>Object.hasOwn(r,n))||r.hashVersion!==void 0&&r.hashVersion!==2||!Array.isArray(r.variations)||r.variations.length<2||r.variations.length>20||r.urlPatterns!==void 0&&!Array.isArray(r.urlPatterns))throw new Error("Invalid visual experiment");return{...r,variations:r.variations.map(At)}});return{...e,experiments:t}}function Xt(e){let t=he(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let r=e.fetch??globalThis.fetch.bind(globalThis),n=Me(r),o=`${t}/api/v1/visual-experiments/${e.environmentId}`,a=e.appManifestRelease?`${o}?iam=${e.appManifestRelease}`:o,i=pe(e.deviceIdCookie??"indiana_did"),s=me(),l=null,u=!1,p=!1,d="",f={...e.attributes??{}},y,w,R=0,b=new Map,k=new Map,v=new Set,M=[],c,h,m;function g(){clearTimeout(h),m?.remove(),m=void 0}function E(V=!1){clearTimeout(c),c=void 0;let S=M.splice(0,20);return S.length?Ae(r,`${o}/events`,JSON.stringify({events:S}),V).catch(L=>e.log?.("Visual exposure not sent",{error:L})):Promise.resolve()}function I(V,S){let L=D(V,S);v.has(L)||e.trackExposures===!1||l?.trackExposures===!1||u||(v.add(L),M.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:i,...s?{sessionId:s}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:V.key,variationKey:S.key}),M.length>=20?E():c??=setTimeout(()=>{E()},1e3))}function _(V){if(!l||u)return;let S=new Set,L={onExperimentViewed:(A,N)=>{S.add(D(A,N))},url:location.href,attributes:{...be(i,location),...f,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:de(l.savedGroups),log:e.log},j=new Set;for(let A of l.experiments){let N=A;try{let x=fe(N,L);if(k.set(A.changeId,x),!x.inExperiment)continue;j.add(A.changeId);let le=JSON.stringify([x.key,x.value]),ue=b.get(A.changeId);if(ue?.signature===le){S.has(D(N,x))&&V.push(()=>{ue.applied()&&I(N,x)});continue}b.get(A.changeId)?.revert(),b.delete(A.changeId);let ce=Je(x.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(A.condition?.$and)&&A.condition.$and.some(P=>P!==null&&typeof P=="object"&&!Array.isArray(P)&&P.indianaAppManifestRelease===e.appManifestRelease),boundVariations:A.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{S.has(D(N,x))&&I(N,x)},onError:P=>e.log?.("Visual experiment stopped",{experiment:A.key,error:String(P)})});b.set(A.changeId,{signature:le,revert:ce.revert,applied:()=>ce.applied})}catch(x){e.log?.("Skipping visual experiment",{experiment:A.key,error:String(x)})}}for(let[A,N]of b)j.has(A)||(N.revert(),b.delete(A));g()}let T=()=>{let V=[];Re(()=>_(V));for(let S of V)S()};async function ie(){let V=++R,S;try{S=await n.read(a,we)}catch(j){if(u||V!==R)return!1;throw j}let L=Ue(S);if(L.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return u||V!==R?!1:(l=L,!0)}let Ge=()=>{d!==location.href&&(d=location.href,T())},se=()=>{E(!0)},ae=()=>{y||u||(y=ge(Ge),addEventListener("pagehide",se),d=location.href)};return{async start(){if(!(p||u)){p=!0,e.appManifestRelease&&(w=Ie(e.appManifestRelease)),e.antiFlicker&&(m=document.createElement("style"),e.nonce&&(m.nonce=e.nonce),m.textContent="body { visibility: hidden !important }",document.head.append(m),h=setTimeout(g,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await ie()||u)return;ae(),T()}finally{g()}}},async refresh(){u||await ie()&&(p&&ae(),T())},setAttributes(V){f={...V},T()},flush:()=>E(),getResults(){return new Map(k)},get generation(){return l?.generation??null},destroy(){u=!0,R++,n.destroy(),y?.(),w?.destroy(),removeEventListener("pagehide",se),g();for(let V of b.values())V.revert();b.clear(),E(!0),l=null,k.clear(),v.clear(),f={}}}}export{Xt as createVisualExperiments,We as loadAppManifestRelease};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tinkerlandai/indiana-sdk",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -58,10 +58,6 @@
58
58
  "./visual": {
59
59
  "types": "./dist/visual.d.ts",
60
60
  "import": "./dist/visual.js"
61
- },
62
- "./iam": {
63
- "types": "./dist/iam.d.ts",
64
- "import": "./dist/iam.js"
65
61
  }
66
62
  },
67
63
  "scripts": {
@@ -81,10 +77,8 @@
81
77
  "devDependencies": {
82
78
  "@indiana/contracts": "workspace:*",
83
79
  "@openrouter/sdk": "^1.4.25",
84
- "@rrweb/types": "2.1.7",
85
80
  "@types/css-tree": "^3.2.0",
86
81
  "ai": "7.0.136",
87
- "rrweb-snapshot": "2.1.7",
88
82
  "tsup": "^8.5.1",
89
83
  "typescript": "^5.9.3",
90
84
  "whatwg-url-minimum": "0.2.0"
@@ -1 +0,0 @@
1
- import{r as g}from"./chunk-U6S6AZM6.js";import{a as u,c as y}from"./chunk-RRII2DMC.js";import{z as h}from"zod";var z=h.enum(["sandbox","live"]),O=h.object({projectId:h.string().min(1),environment:z}).strict();import{z as t}from"zod";var f=t.tuple([t.number().min(0).max(1),t.number().min(0).max(1)]).refine(([n,p])=>n<=p),H=t.strictObject({attribute:t.string().optional(),seed:t.string(),hashVersion:t.literal(2),ranges:t.array(f).max(100)}),E=t.strictObject({id:t.string().min(1).max(255),condition:y,gate:t.boolean().optional()}),C=t.strictObject({key:t.string().optional(),name:t.string().optional(),passthrough:t.boolean().optional()}),k={condition:y.optional(),parentConditions:t.array(E).max(100).optional(),weights:t.array(t.number().min(0).max(1)).max(20).optional(),coverage:t.number().min(0).max(1).optional(),hashAttribute:t.string().optional(),fallbackAttribute:t.string().optional(),hashVersion:t.literal(2).optional(),disableStickyBucketing:t.boolean().optional(),bucketVersion:t.number().int().nonnegative().optional(),minBucketVersion:t.number().int().nonnegative().optional(),filters:t.array(H).max(100).optional(),ranges:t.array(f).max(20).optional(),meta:t.array(C).max(20).optional(),seed:t.string().optional(),name:t.string().optional(),phase:t.string().optional()},b=t.strictObject({...k,key:t.string().min(1).max(255),variations:t.tuple([u,u]).rest(u).refine(n=>n.length<=20),urlPatterns:t.array(t.strictObject({include:t.boolean(),type:t.enum(["regex","simple"]),pattern:t.string()})).max(100).optional(),force:t.number().int().nonnegative().optional(),active:t.boolean().optional(),persistQueryString:t.boolean().optional()}),U=t.strictObject({value:u,variationId:t.number().int(),key:t.string(),name:t.string().optional(),bucket:t.number().optional(),passthrough:t.boolean().optional(),inExperiment:t.boolean(),hashUsed:t.boolean().optional(),hashAttribute:t.string(),hashValue:t.string(),featureId:t.string().nullable(),stickyBucketUsed:t.boolean().optional()}),D=t.strictObject({...k,id:t.string().max(255).optional(),force:u.optional(),variations:t.array(u).min(2).max(20).optional(),key:t.string().optional(),range:f.optional(),tracks:t.array(t.strictObject({experiment:b,result:U})).max(100).optional()}),B=t.strictObject({defaultValue:u.optional(),rules:t.array(D).max(500).optional()}),x=t.record(t.string(),t.union([t.strictObject({type:t.literal("hashed"),attributeKey:t.string(),values:t.array(t.string().regex(/^[a-f0-9]{64}$/))}),t.strictObject({type:t.literal("list"),attributeKey:t.string(),values:t.array(t.union([t.string(),t.number()]))}),t.strictObject({type:t.literal("condition"),condition:y})])),J=t.strictObject({scope:O,generation:t.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:t.iso.datetime({offset:!0}),expiresAt:t.iso.datetime({offset:!0}).nullable(),features:t.record(t.string(),B),savedGroups:x,experiments:t.record(t.uuid(),b)});import{z as a}from"zod";import{z as e}from"zod";import{z as r}from"zod";var M=r.strictObject({schemaVersion:r.literal(1),renderKey:r.string().min(1).max(256),routeTemplate:r.string().startsWith("/").max(2048),selectors:r.array(r.string().regex(/^[a-z][a-z0-9-]*\[data-indiana-id="(?:[^"\\\x00-\x1f]|\\["\\])*"\]$/).max(512)).max(512),present:r.array(r.number().int().min(0).max(511)).min(1).max(512),absent:r.array(r.number().int().min(0).max(511)).max(512)}).superRefine((n,p)=>{let o=[...n.present,...n.absent];(new Set(n.selectors).size!==n.selectors.length||new Set(o).size!==o.length||o.length!==n.selectors.length||o.some(s=>s>=n.selectors.length))&&p.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),w=r.strictObject({renderKey:r.string().min(1).max(256),routeKey:r.string().min(1).max(256),stateKey:r.string().min(1).max(256),documentKey:r.string().min(1).max(256),documentHash:r.string().regex(/^[a-f0-9]{64}$/),compositionKey:r.string().min(1).max(256),entryMode:r.enum(["hard","soft"]),match:r.strictObject({present:r.array(r.number().int().min(0).max(511)).max(512),absent:r.array(r.number().int().min(0).max(511)).max(512)})});import{z as m}from"zod";var N={"enterprise-internal-indiana-test":"indiana-admin-vercel@enterprise-internal-490516.iam.gserviceaccount.com","tinkerland-indiana-prod":"indiana-admin-vercel@tinkerland-indiana.iam.gserviceaccount.com"},v="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",X=m.string().regex(new RegExp(`^${v}/${v}/${v}/manifest\\.json$`)),_="content-length;content-type;host;x-goog-if-generation-match",G=m.strictObject({kind:m.literal("gcs-v4-put"),url:m.url(),bucket:m.enum(["enterprise-internal-indiana-test","tinkerland-indiana-prod"]),objectKey:X,byteLength:m.number().int().min(1).max(8388608),expiresAt:m.iso.datetime(),headers:m.strictObject({"Content-Type":m.literal("application/json"),"x-goog-if-generation-match":m.literal("0")})}).superRefine((n,p)=>{let o=new URL(n.url),s=o.searchParams,j=["X-Goog-Algorithm","X-Goog-Credential","X-Goog-Date","X-Goog-Expires","X-Goog-Signature","X-Goog-SignedHeaders"],l=s.get("X-Goog-Date")??"",R=/^\d{8}T\d{6}Z$/.test(l)?Date.parse(`${l.slice(0,4)}-${l.slice(4,6)}-${l.slice(6,8)}T${l.slice(9,11)}:${l.slice(11,13)}:${l.slice(13,15)}Z`):NaN,d=Number(s.get("X-Goog-Expires"));(o.origin!=="https://storage.googleapis.com"||o.username||o.password||o.hash||o.pathname!==`/${n.bucket}/app-manifests/${n.objectKey}`||[...s.keys()].length!==j.length||j.some($=>s.getAll($).length!==1)||s.get("X-Goog-Algorithm")!=="GOOG4-RSA-SHA256"||s.get("X-Goog-Credential")!==`${N[n.bucket]}/${l.slice(0,8)}/auto/storage/goog4_request`||s.get("X-Goog-SignedHeaders")!==_||!/^[a-f0-9]{512,1024}$/.test(s.get("X-Goog-Signature")??"")||!Number.isFinite(R)||!Number.isInteger(d)||d<1||d>900||R+d*1e3!==Date.parse(n.expiresAt))&&p.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var A=8388608;var i=e.string().min(1).max(256),c=e.string().regex(/^[a-f0-9]{64}$/),me=e.strictObject({versionId:e.uuid(),manifestDigest:c,sourceGraphDigest:c,pageKey:i,stateKey:i,documentKey:i,documentHash:c,elementKey:i.optional(),nodeId:i.optional(),contentHash:c.optional(),renderKey:i.optional(),observed:e.optional(g)}),P=e.strictObject({observed:e.optional(g),pageKey:i,documentKey:i,expectedDocumentHash:c,renderKey:i.optional(),nodeId:i,elementKey:i,expectedContentHash:c,property:e.enum(["text","fontSize","color"]),value:e.union([e.string().max(4e3),e.number().finite()])}),V=e.strictObject({versionId:e.uuid(),manifestDigest:c,sourceGraphDigest:c,pageKey:i,stateKey:i,documentKey:i,documentHash:c,renderKey:i.optional(),observed:e.optional(g),patches:e.array(P.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),le=e.discriminatedUnion("action",[e.strictObject({action:e.literal("register"),requestId:e.uuid(),label:e.string().trim().min(1).max(100),sha256:c,bytes:e.number().int().min(1).max(A),transferBytes:e.number().int().min(1).max(A)}),e.strictObject({action:e.literal("complete"),versionId:e.uuid()}),e.strictObject({action:e.literal("current"),versionId:e.uuid(),expectedCurrent:e.uuid().nullable()}),e.strictObject({action:e.literal("delivery"),enabled:e.boolean()}),e.strictObject({action:e.literal("changes"),versionId:e.uuid(),experimentId:e.uuid(),observed:e.optional(g),variationId:i,changesetId:e.uuid().nullable(),expectedRevision:c.nullable(),editorUrl:e.string().url().max(2048),patches:e.array(P).min(1).max(200)})]),I=e.strictObject({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),label:e.string(),sha256:c,bytes:e.number().int().positive(),objectKey:e.string(),state:e.enum(["uploading","ready","rejected"]),isCurrent:e.boolean(),revision:e.number().int().nonnegative(),createdAt:e.string(),expiresAt:e.string(),readyAt:e.string().nullable(),summary:e.record(e.string(),e.json()),routeTree:e.json().nullable(),validation:e.record(e.string(),e.json())}),ue=e.strictObject({rows:e.array(I).max(100),nextCursor:e.uuid().nullable(),currentId:e.uuid().nullable()}),S=e.strictObject({storedBytes:e.number().int().nonnegative(),reservedBytes:e.number().int().nonnegative(),chargedBytes:e.number().int().nonnegative(),versions:e.number().int().nonnegative(),objects:e.number().int().nonnegative(),orphanObjects:e.number().int().nonnegative(),missingReadyObjects:e.number().int().nonnegative(),unknownObjectSizes:e.number().int().nonnegative(),byteLimit:e.number().int().positive(),versionLimit:e.number().int().positive(),remainingBytes:e.number().int().nonnegative()}),pe=e.strictObject({asOf:e.iso.datetime({offset:!0}),reclamation:e.literal("manual-review-required"),buckets:e.strictObject({source:S,runtime:S,previews:S})}),ge=e.strictObject({asOf:e.iso.datetime({offset:!0}),reviewOnly:e.literal(!0),complete:e.boolean(),issues:e.strictObject({scanLimit:e.boolean(),invalidReferences:e.number().int().nonnegative(),missingVersions:e.number().int().nonnegative()}),totals:e.strictObject({versions:e.number().int().nonnegative(),protected:e.number().int().nonnegative(),reviewCandidates:e.number().int().nonnegative()}),rows:e.array(e.strictObject({versionId:e.uuid(),kind:e.enum(["source","runtime"]),state:e.enum(["uploading","ready","rejected"]),createdAt:e.iso.datetime({offset:!0}),reviewAfter:e.iso.datetime({offset:!0}),reasons:e.array(e.enum(["current","upload-capability","retention-grace","incomplete-inventory","retained-observation","gb","gb-observation","funnel-draft","funnel-draft-observation","funnel-version","funnel-version-observation"])).max(11)})).max(50),nextCursor:e.uuid().nullable()}),de=e.strictObject({version:I,actorId:e.uuid(),claims:e.record(e.string(),e.json())}),ye=e.strictObject({version:I,upload:G.nullable()}),be=e.object({format:e.literal("indiana-route-state-index"),schemaVersion:e.literal(3),routes:e.array(e.object({routeKey:i,path:e.string(),documentKey:i,documentHash:c,initialStateKey:i,initialRenderKey:i})),renders:e.array(w).max(1e3)}).loose().superRefine((n,p)=>{(!n.renders||n.routes.some(o=>!n.renders?.some(s=>s.renderKey===o.initialRenderKey&&s.routeKey===o.routeKey&&s.documentKey===o.documentKey&&s.stateKey===o.initialStateKey&&s.documentHash===o.documentHash&&s.entryMode==="hard")))&&p.addIssue({code:"custom",message:"Incomplete render catalog"})}),he=e.strictObject({rows:e.array(e.object({id:e.uuid(),name:e.string(),status:e.string(),variations:e.array(e.object({id:i,key:i,name:e.string().optional()}).loose())}).loose()),limited:e.boolean()}),fe=e.strictObject({enabled:e.boolean(),allowedOrigins:e.array(e.string())});var T=a.strictObject({selector:a.string().min(1).max(2048),action:a.enum(["set","append","remove"]),attribute:a.string().min(1).max(128).refine(n=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(n)||/^(aria|data)-[a-z0-9_-]+$/.test(n)),value:a.string().max(5e4).optional(),parentSelector:a.string().max(2048).optional(),insertBeforeSelector:a.string().max(2048).optional()}),F=a.strictObject({variation:a.string().min(1).max(128),description:a.string().max(2e3).default(""),css:a.string().max(1e5).default(""),js:a.string().max(1e5).default(""),domMutations:a.array(T).max(200).default([]),iam:V.optional(),renderGuard:M.optional()}),K=F.omit({variation:!0,description:!0,iam:!0}),L=b.omit({variations:!0,active:!0}).extend({changeId:a.string().regex(/^[a-f0-9]{64}$/),variations:a.tuple([K,K]).rest(K).refine(n=>n.length<=20)}),je=a.strictObject({trackExposures:a.boolean(),environmentId:a.uuid(),generation:a.string().regex(/^[a-f0-9]{64}$/),experiments:a.array(L).max(100),savedGroups:x});export{z as a,O as b,b as c,U as d,D as e,B as f,x as g,J as h,me as i,T as j,F as k,K as l,L as m,je as n};