// @bun
var{defineProperty:C,getOwnPropertyNames:F,getOwnPropertyDescriptor:G}=Object,H=Object.prototype.hasOwnProperty;function I(j){return this[j]}var M=(j)=>{var k=(D??=new WeakMap).get(j),q;if(k)return k;if(k=C({},"__esModule",{value:!0}),j&&typeof j==="object"||typeof j==="function"){for(var w of F(j))if(!H.call(k,w))C(k,w,{get:I.bind(j,w),enumerable:!(q=G(j,w))||q.enumerable})}return D.set(j,k),k},D;var J=(j)=>j;function K(j,k){this[j]=J.bind(null,k)}var N=(j,k)=>{for(var q in k)C(j,q,{get:k[q],enumerable:!0,configurable:!0,set:K.bind(k,q)})};var O=(j,k)=>()=>(j&&(k=j(j=0)),k);class L{registry;policyChecker;expressionEvaluator;constructor(j){this.registry=j.registry,this.policyChecker=j.policyChecker,this.expressionEvaluator=j.expressionEvaluator}async chooseVariant(j){let k=this.registry.get(j.experiment,j.version);if(!k)return null;let q=k.variants.find((w)=>w.id===k.controlVariant);if(!q)throw Error(`Experiment ${k.meta.key} missing control variant ${k.controlVariant}`);switch(k.allocation.type){case"random":return{variant:this.pickByWeight(k,this.randomSeed(j,k.allocation.salt)),reason:"random"};case"sticky":return{variant:this.pickByWeight(k,this.stickySeed(j,k.allocation.attribute,k.allocation.salt)),reason:"sticky"};case"targeted":{let w=await this.evaluateTargeting(k,j,k.allocation.rules);if(w)return{variant:w,reason:"targeted"};if(k.allocation.fallback==="random")return{variant:this.pickByWeight(k,this.randomSeed(j)),reason:"random"};return{variant:q,reason:"control"}}default:return{variant:q,reason:"control"}}}pickByWeight(j,k){let q=j.variants,w=q.reduce((B,E)=>B+(E.weight??1),0),A=k*w,z=0;for(let B of q)if(z+=B.weight??1,A<=z)return B;return q[q.length-1]}randomSeed(j,k=""){let q=j.sessionId??j.userId??j.organizationId??`${Date.now()}-${Math.random()}`;return this.hashToUnitInterval(q+k)}stickySeed(j,k,q=""){let w=j[k];if(!w)return this.randomSeed(j,q);return this.hashToUnitInterval(`${w}-${q}`)}hashToUnitInterval(j){let k=2166136261;for(let w=0;w<j.length;w+=1)k^=j.charCodeAt(w),k=Math.imul(k,16777619);return(k>>>0)%1e6/1e6}async evaluateTargeting(j,k,q){for(let w of q){if(!await this.matchesRule(w,k))continue;let A=j.variants.find((z)=>z.id===w.variantId);if(!A)continue;if(typeof w.percentage==="number"){if(this.randomSeed(k,`rule-${w.variantId}`)>w.percentage)continue}return A}return null}async matchesRule(j,k){if(j.policy&&this.policyChecker){if(!await this.policyChecker(j.policy,k))return!1}if(j.expression){if(this.expressionEvaluator)return Boolean(this.expressionEvaluator(j.expression,k));try{let q=Function("context",`return (${j.expression});`);return Boolean(q(k))}catch(q){return!1}}return!0}}export{L as ExperimentEvaluator};
