@traffical/js-client 0.18.0 → 0.19.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.
@@ -1,3 +1,3 @@
1
- /* @traffical/js-client v0.18.0 */
2
- "use strict";var Traffical=(()=>{var Z=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var ft=Object.prototype.hasOwnProperty;var gt=(r,e,t)=>e in r?Z(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var ht=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),pt=(r,e)=>{for(var t in e)Z(r,t,{get:e[t],enumerable:!0})},mt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of dt(e))!ft.call(r,i)&&i!==t&&Z(r,i,{get:()=>e[i],enumerable:!(n=ut(e,i))||n.enumerable});return r};var yt=r=>mt(Z({},"__esModule",{value:!0}),r);var y=(r,e,t)=>(gt(r,typeof e!="symbol"?e+"":e,t),t);var qe=ht(()=>{});var Pn={};pt(Pn,{TrafficalClient:()=>U,createDOMBindingPlugin:()=>lt,createDebugPlugin:()=>Ve,createRedirectAttributionPlugin:()=>Ne,createRedirectPlugin:()=>Be,destroy:()=>Dn,init:()=>kn,initSync:()=>Sn,instance:()=>Rn});function vt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function ve(r,e,t=""){let n=vt(r),i=r?.length,o=e!==void 0;if(!n||o&&i!==e){let s=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof r}`,f=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return r}function _e(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Fe(r,e){ve(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function F(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ee(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function A(r,e){return r<<32-e|r>>>e}function Ke(r,e={}){let t=(i,o)=>r(o).update(i).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=i=>r(i),Object.assign(t,e),Object.freeze(t)}var $e=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function je(r,e,t){return r&e^~r&t}function He(r,e,t){return r&e^r&t^e&t}var te=class{constructor(e,t,n,i){y(this,"blockLen");y(this,"outputLen");y(this,"canXOF",!1);y(this,"padOffset");y(this,"isLE");y(this,"buffer");y(this,"view");y(this,"finished",!1);y(this,"length",0);y(this,"pos",0);y(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=ee(this.buffer)}update(e){_e(this),ve(e);let{view:t,buffer:n,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=ee(e);for(;i<=o-s;s+=i)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){_e(this),Fe(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,F(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let l=s;l<i;l++)t[l]=0;n.setBigUint64(i-8,BigInt(this.length*8),o),this.process(n,0);let a=ee(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,g=this.get();if(f>g.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<f;l++)a.setUint32(4*l,g[l],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:i,finished:o,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=a,i%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},S=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var _t=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),P=new Uint32Array(64),xe=class extends te{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:i,E:o,F:s,G:a,H:c}=this;return[e,t,n,i,o,s,a,c]}set(e,t,n,i,o,s,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)P[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=P[l-15],u=P[l-2],m=A(p,7)^A(p,18)^p>>>3,b=A(u,17)^A(u,19)^u>>>10;P[l]=b+P[l-7]+m+P[l-16]|0}let{A:n,B:i,C:o,D:s,E:a,F:c,G:f,H:g}=this;for(let l=0;l<64;l++){let p=A(a,6)^A(a,11)^A(a,25),u=g+p+je(a,c,f)+_t[l]+P[l]|0,b=(A(n,2)^A(n,13)^A(n,22))+He(n,i,o)|0;g=f,f=c,c=a,a=s+u|0,s=o,o=i,i=n,n=u+b|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,g=g+this.H|0,this.set(n,i,o,s,a,c,f,g)}roundClean(){F(P)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),F(this.buffer)}},be=class extends xe{constructor(){super(32);y(this,"A",S[0]|0);y(this,"B",S[1]|0);y(this,"C",S[2]|0);y(this,"D",S[3]|0);y(this,"E",S[4]|0);y(this,"F",S[5]|0);y(this,"G",S[6]|0);y(this,"H",S[7]|0)}};var We=Ke(()=>new be,$e(1));var ze=new TextEncoder,Ee="v2";function ne(r){return ze.encode(r).length}function ie(r,e){let t=ne(r),n=ne(e);return`traffical:assignment:${Ee}|u:${t}:${r}|l:${n}:${e}`}function K(r){return We(ze.encode(r))}function $(r){let e=0n;for(let t=0;t<8;t++)e=e<<8n|BigInt(r[t]);return e}function re(r){return $(K(r))}function oe(r,e,t){let n=K(ie(r,e)),i=$(n);return Number(i%BigInt(t))}function Ie(r,e){return r>=e[0]&&r<=e[1]}function se(r,e){for(let t of e)if(Ie(r,t.bucketRange))return t;return null}var xt=1n<<53n,bt=9007199254740992;function B(r,e){if(r.length===0||r.length===1)return 0;let t=re(e),n=Number(t%xt)/bt,i=0;for(let o=0;o<r.length;o++)if(i+=r[o],n<i)return o;return r.length-1}function Te(r,e){let{field:t,op:n,value:i,values:o}=r,s=Tt(e,t);switch(n){case"eq":return s===i;case"neq":return s!==i;case"in":return Array.isArray(o)?o.includes(s):!1;case"nin":return Array.isArray(o)?!o.includes(s):!0;case"gt":return typeof s=="number"&&s>i;case"gte":return typeof s=="number"&&s>=i;case"lt":return typeof s=="number"&&s<i;case"lte":return typeof s=="number"&&s<=i;case"contains":return typeof s=="string"&&typeof i=="string"&&s.includes(i);case"startsWith":return typeof s=="string"&&typeof i=="string"&&s.startsWith(i);case"endsWith":return typeof s=="string"&&typeof i=="string"&&s.endsWith(i);case"regex":if(typeof s!="string"||typeof i!="string")return!1;try{return new RegExp(i).test(s)}catch{return!1}case"exists":return s!=null;case"notExists":return s==null;default:return!1}}function ae(r,e){return r.length===0?!0:r.every(t=>Te(t,e))}function Tt(r,e){let t=e.split("."),n=r;for(let i of t){if(n==null)return;if(typeof n=="object")n=n[i];else return}return n}function Ce(r,e){let t=r.intercept;for(let{key:n,coef:i,missing:o}of r.numeric){let s=e[n];t+=typeof s=="number"?i*s:o}for(let{key:n,values:i,missing:o}of r.categorical){let s=e[n],a=s!=null?String(s):null;t+=a!==null&&a in i?i[a]:o}return t}function we(r,e){if(r.length===0)return[];if(r.length===1)return[1];let t=Math.max(e,1e-10),n=r.map(a=>a/t),i=Math.max(...n),o=n.map(a=>Math.exp(a-i)),s=o.reduce((a,c)=>a+c,0);return o.map(a=>a/s)}function Ae(r,e){if(r.length===0)return[];if(e<=0)return r;let t=r.length,n=1/t,i=Math.min(e,n),o=r.map(a=>Math.max(a,i)),s=o.reduce((a,c)=>a+c,0);return s===0?Array(t).fill(1/t):o.map(a=>a/s)}function ce(r,e,t){let n=r.contextualModel;if(!n||r.allocations.length===0)return null;let i=Ct(n,r.allocations,e),o=we(i,n.gamma),s=Ae(o,n.actionProbabilityFloor),a=`ctx:${t}:${r.id}`,c=B(s,a);return{allocation:r.allocations[c],probability:s[c]}}function Ct(r,e,t){return e.map(n=>{let i=r.coefficients[n.key??n.name];return i?Ce(i,t):r.defaultAllocationScore})}var wt=r=>crypto.getRandomValues(new Uint8Array(r)),At=(r,e,t)=>{let n=(2<<Math.log2(r.length-1))-1,i=-~(1.6*n*e/r.length);return(o=e)=>{let s="";for(;;){let a=t(i),c=i|0;for(;c--;)if(s+=r[a[c]&n]||"",s.length>=o)return s}}},Ge=(r,e=21)=>At(r,e|0,wt);function le(r){let e=new Error(r);return e.source="ulid",e}var ke="0123456789ABCDEFGHJKMNPQRSTVWXYZ",j=ke.length,Xe=Math.pow(2,48)-1,kt=10,St=16;function Rt(r){let e=Math.floor(r()*j);return e===j&&(e=j-1),ke.charAt(e)}function Dt(r,e){if(isNaN(r))throw new Error(r+" must be a number");if(r>Xe)throw le("cannot encode time greater than "+Xe);if(r<0)throw le("time must be positive");if(Number.isInteger(Number(r))===!1)throw le("time must be an integer");let t,n="";for(;e>0;e--)t=r%j,n=ke.charAt(t)+n,r=(r-t)/j;return n}function Pt(r,e){let t="";for(;r>0;r--)t=Rt(e)+t;return t}function Lt(r=!1,e){e||(e=typeof window<"u"?window:null);let t=e&&(e.crypto||e.msCrypto);if(t)return()=>{let n=new Uint8Array(1);return t.getRandomValues(n),n[0]/255};try{let n=qe();return()=>n.randomBytes(1).readUInt8()/255}catch{}if(r){try{console.error("secure crypto unusable, falling back to insecure Math.random()!")}catch{}return()=>Math.random()}throw le("secure crypto unusable, insecure Math.random not allowed")}function Ot(r){return r||(r=Lt()),function(t){return isNaN(t)&&(t=Date.now()),Dt(t,kt)+Pt(St,r)}}var Je=Ot();var Mt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Bt=8,ui=Ge(Mt,Bt);function H(r){return`${r}_${Je()}`}function N(){return H("dec")}function Se(){return H("exp")}function Re(){return H("trk")}function De(){return H("asn")}function Nt(r,e){let t=new Set;for(let i of e)if(i.contextLogging?.allowedFields)for(let o of i.contextLogging.allowedFields)t.add(o);if(t.size===0)return;let n={};for(let i of t)i in r&&(n[i]=r[i]);return Object.keys(n).length>0?n:void 0}function Vt(r,e){let t=[];for(let n of r){let i=e[n];if(i==null)return null;t.push(String(i))}return t.join("_")}function Qe(r){if(r<=0)return[];let e=1/r;return Array(r).fill(e)}function Ut(r,e,t,n){let i=r.entityState?.[e];if(!i)return Qe(n);let o=i.entities[t];if(o&&o.weights.length===n)return o.weights;let s=i._global;return s&&s.weights.length===n?s.weights:Qe(n)}function Ft(r,e,t,n){let i=e.entityConfig;if(!i)return null;let o=Vt(i.entityKeys,t);if(!o)return null;let s,a;if(i.dynamicAllocations){let l=i.dynamicAllocations.countKey,p=t[l];if(typeof p!="number"||p<=0)return null;a=Math.floor(p),s=Array.from({length:a},(u,m)=>({id:`${e.id}_dynamic_${m}`,name:String(m),bucketRange:[0,0],overrides:{}}))}else s=e.allocations,a=s.length;if(a===0)return null;let c=Ut(r,e.id,o,a),f=`${o}:${n}:${e.id}`,g=B(c,f);return{allocation:s[g],weight:c[g],entityId:o}}function W(r,e){let t=e[r.hashing.unitKey];return t==null?null:String(t)}function ue(r){return r?.hashing?.unitKey??null}function de(r,e){return r?r.parameters.find(n=>n.key===e)?.layerId??null:null}function Ye(r,e,t,n){let i={...t},o=[],s=[];if(!r)return{assignments:i,unitKeyValue:"",layers:o,matchedPolicies:s};let a=W(r,e)??"",c=new Set(Object.keys(t)),f=r.parameters.filter(l=>c.has(l.key));for(let l of f)l.key in i&&(i[l.key]=l.default);let g=new Map;for(let l of f){let p=g.get(l.layerId)||[];p.push(l),g.set(l.layerId,p)}for(let l of r.layers){let p=g.get(l.id),u=p&&p.length>0,m=l.unitKey,b=m!=null;if(b&&String(m).trim()===""){o.push({layerId:l.id,bucket:-1,...u?{}:{attributionOnly:!0}});continue}let _=b?String(e[m]??""):a;if(!_){o.push({layerId:l.id,bucket:-1,...b?{unitKey:m,unitKeyValue:""}:{},...u?{}:{attributionOnly:!0}});continue}let T=oe(_,l.id,r.hashing.bucketCount),w,E,D,d;for(let h of l.policies)if(h.state==="running"){if(h.eligibleBucketRange){let{start:x,end:I}=h.eligibleBucketRange;if(T<x||T>I)continue}if(ae(h.conditions,e)){if(h.contextualModel){let x=ce(h,e,_);if(x){if(w=h,E=x.allocation,D=x.probability,d=h.contextualModel.generatedAt??h.contextualModel.modelVersion,s.push(h),u)for(let[I,k]of Object.entries(x.allocation.overrides))I in i&&(i[I]=k);break}}if(h.entityConfig&&h.entityConfig.resolutionMode==="bundle"){let x=Ft(r,h,e,_);if(x){if(w=h,E=x.allocation,D=x.weight,s.push(h),u&&!h.entityConfig.dynamicAllocations)for(let[I,k]of Object.entries(x.allocation.overrides))I in i&&(i[I]=k);break}}else if(h.entityConfig&&h.entityConfig.resolutionMode==="edge"){let x=n?.edgeResults?.get(h.id);if(x){if(w=h,s.push(h),h.entityConfig.dynamicAllocations)E={id:`${h.id}_dynamic_${x.allocationIndex}`,name:String(x.allocationIndex),bucketRange:[0,0],overrides:{}};else if(h.allocations[x.allocationIndex]&&(E=h.allocations[x.allocationIndex],u&&E))for(let[I,k]of Object.entries(E.overrides))I in i&&(i[I]=k);break}continue}else{let x=se(T,h.allocations);if(x){if(w=h,E=x,h.kind==="adaptive"){let[I,k]=x.bucketRange;D=(k-I+1)/r.hashing.bucketCount}if(s.push(h),u)for(let[I,k]of Object.entries(x.overrides))I in i&&(i[I]=k);break}}}}o.push({layerId:l.id,bucket:T,policyId:w?.id,policyKey:w?.key,allocationId:E?.id,allocationName:E?.name,allocationKey:E?.key,...D!==void 0&&D>0&&D<=1?{probability:D}:{},...d!==void 0?{modelVersion:d}:{},...b?{unitKey:m,unitKeyValue:_}:{},...u?{}:{attributionOnly:!0}})}return{assignments:i,unitKeyValue:a,layers:o,matchedPolicies:s}}function fe(r,e,t,n){return Ye(r,e,t,n).assignments}function ge(r,e,t,n){let{assignments:i,unitKeyValue:o,layers:s,matchedPolicies:a}=Ye(r,e,t,n),c=Nt(e,a);return{decisionId:N(),assignments:i,metadata:{timestamp:new Date().toISOString(),unitKeyValue:o,layers:s,filteredContext:c,...r?.version?{configVersion:r.version}:{}}}}var M=class r{constructor(e={}){y(this,"_seen",new Map);y(this,"_ttlMs");y(this,"_maxEntries");y(this,"_lastCleanup",Date.now());this._ttlMs=e.ttlMs??36e5,this._maxEntries=e.maxEntries??1e4}static hashAssignments(e){let t=Object.keys(e).sort(),n=[];for(let i of t){let o=e[i],s=typeof o=="object"?JSON.stringify(o):String(o);n.push(`${i}=${s}`)}return n.join("|")}static createKey(e,t){return`${e}:${t}`}checkAndMark(e,t){let n=r.createKey(e,t),i=Date.now(),o=this._seen.get(n);return o!==void 0&&i-o<this._ttlMs?!1:(this._seen.set(n,i),this._maybeCleanup(i),!0)}wouldBeNew(e,t){let n=r.createKey(e,t),i=Date.now(),o=this._seen.get(n);return o===void 0?!0:i-o>=this._ttlMs}clear(){this._seen.clear()}get size(){return this._seen.size}_maybeCleanup(e){(e-this._lastCleanup>this._ttlMs*.2||this._seen.size>this._maxEntries)&&(this._lastCleanup=e,this._cleanup(e))}_cleanup(e){let t=[];for(let[n,i]of this._seen.entries())e-i>=this._ttlMs&&t.push(n);for(let n of t)this._seen.delete(n);if(this._seen.size>this._maxEntries){let i=Array.from(this._seen.entries()).sort((o,s)=>o[1]-s[1]).slice(0,this._seen.size-this._maxEntries);for(let[o]of i)this._seen.delete(o)}}};var Ze={resolutionErrors:0,droppedAssignmentLogs:0,droppedEventLogs:0,rejectedBundles:0,sideEffectErrors:0,lastError:null};function nn(r){return r instanceof Error?r:typeof r=="string"?new Error(r):new Error("An unknown error occurred")}var V=class{constructor(e={}){y(this,"_onResolutionError");y(this,"_onError");y(this,"_seen",new Set);y(this,"_counters",{...Ze});this._onResolutionError=e.onResolutionError??"default",this._onError=e.onError}get throwsOnResolutionError(){return this._onResolutionError==="throw"}resolve(e,t,n){try{return t()}catch(i){if(this._counters.resolutionErrors++,this._report(e,i),this._onResolutionError==="throw")throw i;return n()}}async resolveAsync(e,t,n){try{return await t()}catch(i){if(this._counters.resolutionErrors++,this._report(e,i),this._onResolutionError==="throw")throw i;return n()}}sideEffect(e,t,n){try{n()}catch(i){this._countSideEffect(t),this._report(e,i)}}async sideEffectAsync(e,t,n){try{await n()}catch(i){this._countSideEffect(t),this._report(e,i)}}recordRejectedBundle(e,t,n){this._counters.rejectedBundles++,this._report(e,new Error(t?`${t}: ${n}`:n))}getDiagnostics(){return{...this._counters}}reset(){Object.assign(this._counters,Ze,{lastError:null}),this._seen.clear()}_countSideEffect(e){switch(e){case"assignmentLog":this._counters.droppedAssignmentLogs++;break;case"eventLog":this._counters.droppedEventLogs++;break;case"bundleRejected":this._counters.rejectedBundles++;break;default:this._counters.sideEffectErrors++}}_report(e,t){let n=nn(t);this._counters.lastError={tag:e,name:n.name,message:n.message};let i=`${e}:${n.name}:${n.message}`;if(!this._seen.has(i)&&(this._seen.add(i),console.warn(`[Traffical] Contained error in ${e}:`,n.message),!!this._onError))try{this._onError(e,n)}catch{}}};function v(r,e){return{ok:!1,path:r,reason:e}}function L(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function R(r){return typeof r=="string"&&r.length>0}function z(r){if(!L(r))return v("","bundle is not an object");let e=r.hashing;if(!L(e))return v("hashing","missing or not an object");if(!R(e.unitKey))return v("hashing.unitKey","missing or not a non-empty string");if(typeof e.bucketCount!="number"||!Number.isInteger(e.bucketCount)||e.bucketCount<1)return v("hashing.bucketCount","not an integer >= 1");if(!Array.isArray(r.parameters))return v("parameters","not an array");for(let t=0;t<r.parameters.length;t++){let n=r.parameters[t],i=`parameters[${t}]`;if(!L(n))return v(i,"not an object");if(!R(n.key))return v(`${i}.key`,"missing or not a non-empty string");if(!R(n.layerId))return v(`${i}.layerId`,"missing or not a non-empty string");if(!("default"in n))return v(`${i}.default`,"missing")}if(!Array.isArray(r.layers))return v("layers","not an array");for(let t=0;t<r.layers.length;t++){let n=r.layers[t],i=`layers[${t}]`;if(!L(n))return v(i,"not an object");if(!R(n.id))return v(`${i}.id`,"missing or not a non-empty string");if(n.unitKey!==void 0&&typeof n.unitKey!="string")return v(`${i}.unitKey`,"present but not a string");if(!Array.isArray(n.policies))return v(`${i}.policies`,"not an array");for(let o=0;o<n.policies.length;o++){let s=n.policies[o],a=`${i}.policies[${o}]`;if(!L(s))return v(a,"not an object");if(!R(s.id))return v(`${a}.id`,"missing or not a non-empty string");if(!R(s.state))return v(`${a}.state`,"missing or not a non-empty string");if(!Array.isArray(s.allocations))return v(`${a}.allocations`,"not an array");if(!Array.isArray(s.conditions))return v(`${a}.conditions`,"not an array");for(let c=0;c<s.conditions.length;c++){let f=s.conditions[c],g=`${a}.conditions[${c}]`;if(!L(f))return v(g,"not an object");if(!R(f.field))return v(`${g}.field`,"missing or not a non-empty string");if(!R(f.op))return v(`${g}.op`,"missing or not a non-empty string")}for(let c=0;c<s.allocations.length;c++){let f=s.allocations[c],g=`${a}.allocations[${c}]`;if(!L(f))return v(g,"not an object");if(!R(f.name))return v(`${g}.name`,"missing or not a non-empty string");let l=f.bucketRange;if(!Array.isArray(l)||l.length!==2)return v(`${g}.bucketRange`,"not a 2-element array");let[p,u]=l;if(typeof p!="number"||typeof u!="number"||!Number.isInteger(p)||!Number.isInteger(u))return v(`${g}.bucketRange`,"bounds are not integers");if(p<0||u<p)return v(`${g}.bucketRange`,"bounds are negative or inverted");if(f.overrides!==void 0&&!L(f.overrides))return v(`${g}.overrides`,"present but not an object")}}}return{ok:!0}}var G=class{constructor(e){y(this,"config");y(this,"defaultTimeout");this.config=e,this.defaultTimeout=e.defaultTimeoutMs??5e3}async resolve(e){try{let t=new AbortController,n=setTimeout(()=>t.abort(),this.defaultTimeout),i=`${this.config.baseUrl}/v1/resolve`,o=await fetch(i,{method:"POST",headers:this._headers(),body:JSON.stringify({context:e.context,env:e.env??this.config.env,parameters:e.parameters}),signal:t.signal});return clearTimeout(n),o.ok?await o.json():(console.warn(`[Traffical] Resolve failed: ${o.status} ${o.statusText}`),null)}catch(t){return t instanceof Error&&t.name==="AbortError"?console.warn(`[Traffical] Resolve timed out after ${this.defaultTimeout}ms`):console.warn("[Traffical] Resolve error:",t),null}}async decideEntity(e,t){let n=t??Math.min(this.defaultTimeout,100);try{let i=new AbortController,o=setTimeout(()=>i.abort(),n),s=`${this.config.baseUrl}/v1/decide/${e.policyId}`,a=await fetch(s,{method:"POST",headers:this._headers(),body:JSON.stringify({entityId:e.entityId,unitKeyValue:e.unitKeyValue,allocationCount:e.allocationCount,context:e.context}),signal:i.signal});return clearTimeout(o),a.ok?await a.json():(console.warn(`[Traffical] Edge decide failed: ${a.status} ${a.statusText}`),null)}catch(i){return i instanceof Error&&i.name==="AbortError"?console.warn(`[Traffical] Edge decide timed out after ${n}ms`):console.warn("[Traffical] Edge decide error:",i),null}}async decideEntityBatch(e,t){if(e.length===0)return[];if(e.length===1)return[await this.decideEntity(e[0],t)];let n=t??Math.min(this.defaultTimeout,200);try{let i=new AbortController,o=setTimeout(()=>i.abort(),n),s=`${this.config.baseUrl}/v1/decide/batch`,a=await fetch(s,{method:"POST",headers:this._headers(),body:JSON.stringify({requests:e}),signal:i.signal});return clearTimeout(o),a.ok?(await a.json()).responses:(console.warn(`[Traffical] Edge batch decide failed: ${a.status} ${a.statusText}`),e.map(()=>null))}catch(i){return i instanceof Error&&i.name==="AbortError"?console.warn(`[Traffical] Edge batch decide timed out after ${n}ms`):console.warn("[Traffical] Edge batch decide error:",i),e.map(()=>null)}}_headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"X-Org-Id":this.config.orgId,"X-Project-Id":this.config.projectId,"X-Env":this.config.env}}};function Pe(r,e,t,n,i){let o=[];for(let a of e){let c=t[a];if(c==null)return null;o.push(String(c))}let s=o.join("_");return{policyId:r,entityId:s,unitKeyValue:n,allocationCount:i,context:t}}var q="failed_events";var he=class{constructor(e){this._queue=[];this._flushTimer=null;this._isFlushing=!1;this._isDisabled=!1;this._droppedCount=0;this._endpoint=e.endpoint,this._apiKey=e.apiKey,this._storage=e.storage,this._batchSize=e.batchSize??10,this._flushIntervalMs=e.flushIntervalMs??3e4,this._requestTimeoutMs=e.requestTimeoutMs??1e4,this._maxQueueSize=e.maxQueueSize??1e3,this._onError=e.onError,this._onSchemaWarnings=e.onSchemaWarnings,this._lifecycleProvider=e.lifecycleProvider,this._setupListeners(),this._retryFailedEvents(),this._startFlushTimer()}log(e){this._isDisabled||(this._queue.length>=this._maxQueueSize&&(this._queue.shift(),this._droppedCount++),this._queue.push(e),this._queue.length>=this._batchSize&&this.flush())}async flush(){if(this._isFlushing||this._isDisabled||this._queue.length===0)return;this._isFlushing=!0;let e=[...this._queue];this._queue=[];try{let t=await this._sendEvents(e);if(t>=200&&t<300)return;if(t===401){this._disable();return}if(t===429||t>=500){this._persistFailedEvents(e),this._onError?.(new Error(`HTTP ${t}: event delivery failed, will retry`));return}this._onError?.(new Error(`HTTP ${t}: batch rejected, dropping ${e.length} events`))}catch(t){this._persistFailedEvents(e),this._onError?.(t instanceof Error?t:new Error(String(t)))}finally{this._isFlushing=!1}}_disable(){this._isDisabled||(this._isDisabled=!0,this._queue=[],this._storage.remove(q),console.warn("[Traffical] API key rejected (HTTP 401); event delivery disabled for this client"))}get droppedCount(){return this._droppedCount}get isDisabled(){return this._isDisabled}flushBeacon(){if(this._queue.length===0)return!0;if(typeof fetch>"u")return this.flush(),!1;let e=[...this._queue];return this._queue=[],fetch(this._endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this._apiKey}`},body:JSON.stringify({events:e}),keepalive:!0}).catch(()=>{this._persistFailedEvents(e)}),!0}get queueSize(){return this._queue.length}destroy(){this._flushTimer&&(clearInterval(this._flushTimer),this._flushTimer=null),this._removeListeners()}async _sendEvents(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this._requestTimeoutMs),i;try{i=await fetch(this._endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this._apiKey}`},body:JSON.stringify({events:e}),signal:t.signal})}finally{clearTimeout(n)}if(!i.ok)return i.status;if(this._onSchemaWarnings)try{let o=await i.json();o.schemaWarnings&&o.schemaWarnings.length>0&&this._onSchemaWarnings(o.schemaWarnings)}catch{}return i.status}_persistFailedEvents(e){let n=[...this._storage.get(q)??[],...e].slice(-100);this._storage.set(q,n)}_retryFailedEvents(){let e=this._storage.get(q);!e||e.length===0||(this._storage.remove(q),this._queue.push(...e))}_startFlushTimer(){this._flushIntervalMs<=0||(this._flushTimer=setInterval(()=>{this.flush().catch(()=>{})},this._flushIntervalMs))}_setupListeners(){this._lifecycleProvider&&(this._visibilityCallback=e=>{e==="background"?this._lifecycleProvider?.isUnloading()?this.flushBeacon():this.flush().catch(()=>{}):this._retryFailedEvents()},this._lifecycleProvider.onVisibilityChange(this._visibilityCallback))}_removeListeners(){this._lifecycleProvider&&this._visibilityCallback&&(this._lifecycleProvider.removeVisibilityListener(this._visibilityCallback),this._visibilityCallback=void 0)}};var X="exposure_dedup";var J=class r{constructor(e){this._storage=e.storage,this._sessionTtlMs=e.sessionTtlMs??18e5,this._seen=new Set,this._sessionStart=Date.now(),this._restore()}static createKey(e,t,n){return`${e}:${t}:${n}`}shouldTrack(e){return this._isSessionExpired()&&this._resetSession(),this._seen.has(e)?!1:(this._seen.add(e),this._persist(),!0)}checkAndMark(e,t,n){let i=r.createKey(e,t,n);return this.shouldTrack(i)}clear(){this._seen.clear(),this._storage.remove(X)}get size(){return this._seen.size}_isSessionExpired(){return Date.now()-this._sessionStart>this._sessionTtlMs}_resetSession(){this._seen.clear(),this._sessionStart=Date.now(),this._storage.remove(X)}_persist(){let e={seen:Array.from(this._seen),sessionStart:this._sessionStart};this._storage.set(X,e,this._sessionTtlMs)}_restore(){let e=this._storage.get(X);if(!e)return;if(Date.now()-e.sessionStart>this._sessionTtlMs){this._storage.remove(X);return}this._seen=new Set(e.seen),this._sessionStart=e.sessionStart}};var Q="stable_id",on="traffical_sid";var pe=class{constructor(e){this._cachedId=null;this._storage=e.storage,this._useCookieFallback=e.useCookieFallback??!0,this._cookieName=e.cookieName??on}getId(){if(this._cachedId)return this._cachedId;let e=this._storage.get(Q);return e?(this._cachedId=e,e):this._useCookieFallback&&(e=this._getCookie(),e)?(this._storage.set(Q,e),this._cachedId=e,e):(e=this._generateId(),this._persist(e),this._cachedId=e,e)}setId(e){this._persist(e),this._cachedId=e}clear(){this._storage.remove(Q),this._useCookieFallback&&this._deleteCookie(),this._cachedId=null}hasId(){return this._storage.get(Q)!==null||this._getCookie()!==null}_persist(e){this._storage.set(Q,e),this._useCookieFallback&&this._setCookie(e)}_generateId(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}_getCookie(){if(typeof document>"u")return null;try{let e=document.cookie.split(";");for(let t of e){let[n,i]=t.trim().split("=");if(n===this._cookieName&&i)return decodeURIComponent(i)}}catch{}return null}_setCookie(e){if(!(typeof document>"u"))try{document.cookie=`${this._cookieName}=${encodeURIComponent(e)}; max-age=31536000; path=/; SameSite=Lax`}catch{}}_deleteCookie(){if(!(typeof document>"u"))try{document.cookie=`${this._cookieName}=; max-age=0; path=/`}catch{}}};var Y="traffical:",Le=class{constructor(){this._available=this._checkAvailability()}get(e){if(!this._available)return null;try{let t=localStorage.getItem(Y+e);if(!t)return null;let n=JSON.parse(t);return n.expiresAt&&Date.now()>n.expiresAt?(this.remove(e),null):n.value}catch{return null}}set(e,t,n){if(this._available)try{let i={value:t,...n&&{expiresAt:Date.now()+n}};localStorage.setItem(Y+e,JSON.stringify(i))}catch{}}remove(e){if(this._available)try{localStorage.removeItem(Y+e)}catch{}}clear(){if(this._available)try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n?.startsWith(Y)&&e.push(n)}e.forEach(t=>localStorage.removeItem(t))}catch{}}_checkAvailability(){try{let e=Y+"__test__";return localStorage.setItem(e,"test"),localStorage.removeItem(e),!0}catch{return!1}}},Oe=class{constructor(){this._store=new Map}get(e){let t=this._store.get(e);return t?t.expiresAt&&Date.now()>t.expiresAt?(this.remove(e),null):t.value:null}set(e,t,n){this._store.set(e,{value:t,...n&&{expiresAt:Date.now()+n}})}remove(e){this._store.delete(e)}clear(){this._store.clear()}};function nt(){let r=new Le;return r.get("__check__")!==null||sn()?r:new Oe}function sn(){try{let r="__traffical_storage_test__";return localStorage.setItem(r,"test"),localStorage.removeItem(r),!0}catch{return!1}}var O="0.18.0";var an="js-client";function Me(r,e){let t=new M({ttlMs:r.deduplicationTtlMs});return{name:"decision-tracking",onDecision(n){if(r.disabled)return;let i=n.metadata.unitKeyValue;if(!i)return;let o=M.hashAssignments(n.assignments);if(!t.checkAndMark(i,o))return;let s={type:"decision",id:n.decisionId,orgId:e.orgId,projectId:e.projectId,env:e.env,unitKey:i,timestamp:n.metadata.timestamp,assignments:n.assignments,layers:n.metadata.layers,context:n.metadata.filteredContext,configVersion:n.metadata.configVersion??e.getConfigVersion?.()??void 0,sdkName:an,sdkVersion:O};e.log(s)},onDestroy(){t.clear()}}}var cn="traffical_rdr";function ln(r,e,t){if(!(typeof document>"u"))try{document.cookie=`${r}=${encodeURIComponent(e)}; max-age=${t}; path=/; SameSite=Lax`}catch{}}function Be(r={}){let e=r.parameterKey??"redirect.url",t=r.compareMode??"pathname",n=r.cookieName??cn;return{name:"redirect",onInitialize(i){typeof window>"u"||i.decide({context:{},defaults:{[e]:""}})},onBeforeDecision(i){return typeof window>"u"?i:{"url.pathname":window.location.pathname,...i}},onDecision(i){let o=i.assignments[e];if(typeof o!="string"||!o)return;let s=t==="href"?window.location.href:window.location.pathname;if(o===s)return;let a=i.metadata.layers.find(c=>c.policyId&&c.allocationName);a&&ln(n,JSON.stringify({l:a.layerId,p:a.policyId,a:a.allocationName,ts:Date.now()}),86400),window.location.replace(o)}}}var un="traffical_rdr";function dn(r){if(typeof document>"u")return null;try{for(let e of document.cookie.split(";")){let[t,n]=e.trim().split("=");if(t===r&&n)return decodeURIComponent(n)}}catch{}return null}function fn(r,e){let t=dn(r);if(!t)return null;try{let n=JSON.parse(t);return Date.now()-n.ts>e?null:{layerId:n.l,policyId:n.p,allocationName:n.a}}catch{return null}}function Ne(r={}){let e=r.cookieName??un,t=r.expiryMs??864e5;function n(i){let o=fn(e,t);if(!o)return;i.attribution=i.attribution??[],i.attribution.some(a=>a.layerId===o.layerId&&a.policyId===o.policyId)||i.attribution.push(o)}return{name:"redirect-attribution",onTrack(i){return n(i),!0},onExposure(i){return n(i),!0}}}var me=[],it={};function gn(){if(typeof window>"u")return{version:1,instances:it,subscribe:()=>()=>{}};if(!window.__TRAFFICAL_DEBUG__){let r={version:1,instances:it,subscribe(e){return me.push(e),()=>{me=me.filter(t=>t!==e)}}};window.__TRAFFICAL_DEBUG__=r}return window.__TRAFFICAL_DEBUG__}function rt(r){for(let e of me)try{e(r)}catch{}}var hn=0,pn=Symbol.for("@openfeature/web-sdk/api");function mn(){let r=globalThis[pn];return r&&typeof r.getContext=="function"&&typeof r.setContext=="function"?r:null}function yn(){return`traffical_${Date.now().toString(36)}_${(++hn).toString(36)}`}function vn(){return`evt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}var _n="traffical-debug";function Ve(r={}){let e=r.instanceId??yn(),t=r.maxEvents??500,n=null,i=null,o={},s=[],a=null,c=null,f={},g=null,l=null,p=[],u=[],m=[];function b(){return{ready:n?.isInitialized===!0,stableId:n?.getStableId?.()??null,effectiveUnitKey:c,configVersion:n?.getConfigVersion?.()??null,assignments:{...o},layers:[...s],lastDecisionId:a,overrides:n?.getOverrides?.()??{},contextOverrides:{...f},lastContext:g?{...g}:null}}function _(){let d=b();for(let h of u)try{h(d)}catch{}}function T(d,h){let x={id:vn(),type:d,timestamp:Date.now(),data:h};p.push(x),p.length>t&&p.splice(0,p.length-t);for(let I of m)try{I(x)}catch{}}function w(){if(!n)return;try{n.decide({context:g?{...g}:{},defaults:l?{...l}:{}})}catch{}let d=mn();if(d)try{d.setContext({...d.getContext()}).catch(()=>{})}catch{}}let E={id:e,meta:{orgId:"",projectId:"",env:"",sdkVersion:O},getState:b,subscribe(d){return u.push(d),()=>{u=u.filter(h=>h!==d)}},getEvents(d){return d!==void 0?p.slice(-d):[...p]},onEvent(d){return m.push(d),()=>{m=m.filter(h=>h!==d)}},getConfigBundle(){return i},setUnitKey(d){n?.identify?n.identify(d):n?.setStableId&&n.setStableId(d),_()},setOverride(d,h){n?.applyOverrides&&n.applyOverrides({[d]:h}),_(),w()},clearOverride(d){if(n?.getOverrides&&n?.applyOverrides){let h=n.getOverrides();delete h[d],n.clearOverrides?.(),n.applyOverrides(h)}_(),w()},clearAllOverrides(){n?.clearOverrides?.(),_(),w()},getOverrides(){return n?.getOverrides?.()??{}},setContextOverrides(d){f={...d},_(),w()},getContextOverrides(){return{...f}},reDecide(){w()},async refresh(){n?.refreshConfig&&await n.refreshConfig()}};return{name:_n,onInitialize(d){n=d,i&&(E.meta.orgId=i.orgId,E.meta.projectId=i.projectId,E.meta.env=i.env);let h=gn();h.instances[e]=E,rt({type:"register",instanceId:e}),_()},onConfigUpdate(d){i=d,E.meta.orgId=d.orgId,E.meta.projectId=d.projectId,E.meta.env=d.env,_()},onBeforeDecision(d){if(g={...d},Object.keys(f).length!==0)return{...d,...f}},onDecision(d){l={...d.assignments},o={...d.assignments},s=d.metadata?.layers?[...d.metadata.layers]:[],a=d.decisionId,d.metadata?.unitKeyValue&&(c=d.metadata.unitKeyValue),T("decision",d),_()},onResolve(d){o={...d},_()},onExposure(d){return T("exposure",d),!0},onTrack(d){return T("track",d),!0},onDestroy(){let d=typeof window<"u"?window.__TRAFFICAL_DEBUG__:null;d&&(delete d.instances[e],rt({type:"unregister",instanceId:e})),u=[],m=[],f={},g=null,l=null,n=null}}}var ye=class{constructor(){this._plugins=[]}register(e){let t="plugin"in e?e.plugin:e,n="priority"in e?e.priority??0:0;return this._plugins.some(i=>i.plugin.name===t.name)?(console.warn(`[Traffical] Plugin "${t.name}" already registered, skipping.`),!1):(this._plugins.push({plugin:t,priority:n}),this._plugins.sort((i,o)=>o.priority-i.priority),!0)}unregister(e){let t=this._plugins.findIndex(n=>n.plugin.name===e);return t===-1?!1:(this._plugins.splice(t,1),!0)}get(e){return this._plugins.find(t=>t.plugin.name===e)?.plugin}getAll(){return this._plugins.map(e=>e.plugin)}async runInitialize(e){for(let{plugin:t}of this._plugins)if(t.onInitialize)try{await t.onInitialize(e)}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onInitialize error:`,n)}}runConfigUpdate(e){for(let{plugin:t}of this._plugins)if(t.onConfigUpdate)try{t.onConfigUpdate(e)}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onConfigUpdate error:`,n)}}runBeforeDecision(e){let t=e;for(let{plugin:n}of this._plugins)if(n.onBeforeDecision)try{let i=n.onBeforeDecision(t);i&&(t=i)}catch(i){console.warn(`[Traffical] Plugin "${n.name}" onBeforeDecision error:`,i)}return t}runDecision(e){for(let{plugin:t}of this._plugins)if(t.onDecision)try{t.onDecision(e)}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onDecision error:`,n)}}runResolve(e){for(let{plugin:t}of this._plugins)if(t.onResolve)try{t.onResolve(e)}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onResolve error:`,n)}}runExposure(e){for(let{plugin:t}of this._plugins)if(t.onExposure)try{if(t.onExposure(e)===!1)return!1}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onExposure error:`,n)}return!0}runTrack(e){for(let{plugin:t}of this._plugins)if(t.onTrack)try{if(t.onTrack(e)===!1)return!1}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onTrack error:`,n)}return!0}runDestroy(){for(let{plugin:e}of this._plugins)if(e.onDestroy)try{e.onDestroy()}catch(t){console.warn(`[Traffical] Plugin "${e.name}" onDestroy error:`,t)}}clear(){this._plugins=[]}};function ot(){let r=[],e=!1;function t(s){for(let a of r)a(s)}let n=()=>{e=!0,t("background")},i=()=>{typeof document<"u"&&t(document.visibilityState==="hidden"?"background":"foreground")},o=()=>{e=!0,t("background")};return typeof window<"u"&&(window.addEventListener("pagehide",n),window.addEventListener("beforeunload",o)),typeof document<"u"&&document.addEventListener("visibilitychange",i),{onVisibilityChange(s){r.push(s)},removeVisibilityListener(s){let a=r.indexOf(s);a!==-1&&r.splice(a,1)},isUnloading(){return e}}}var Ue="js-client";function st(r,e){if(e!==void 0)return{context:r,defaults:e};let t=r;return{context:t.context,defaults:t.defaults}}var xn="https://sdk.traffical.io",bn=6e4,En=1e4,In=3e5,Tn=3e5,Cn=100,wn=.1;function An(r){let e=r*wn;return r+(Math.random()*2-1)*e}var U=class{constructor(e){this._state={bundle:null,etag:null,lastFetchTime:0,lastOfflineWarning:0,lastMalformedWarning:0,refreshTimer:null,isInitialized:!1,serverResponse:null,cachedEdgeResults:null};this._decisionCache=new Map;this._cumulativeAttribution=new Map;this._identityListeners=[];this._overrideListeners=[];this._overrides={};this._lastResolveContextKey=null;this._readyPromise=new Promise(e=>{this._readyResolve=e});let t=e.evaluationMode??"bundle";this._options={orgId:e.orgId,projectId:e.projectId,env:e.env,apiKey:e.apiKey,baseUrl:e.baseUrl??xn,localConfig:e.localConfig,refreshIntervalMs:e.refreshIntervalMs??bn,attributionMode:e.attributionMode??"cumulative",evaluationMode:t},this._requestTimeoutMs=e.configTimeoutMs??e.requestTimeoutMs??En;let n={baseUrl:this._options.baseUrl,orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,apiKey:this._options.apiKey,defaultTimeoutMs:e.resolveTimeoutMs??e.requestTimeoutMs};if(this._decisionClient=new G(n),this._errorPolicy=new V({onResolutionError:e.onResolutionError,onError:e.onError??e.errorBoundary?.onError}),this._storage=e.storage??nt(),this._lifecycleProvider=e.lifecycleProvider??ot(),!e.onSchemaWarnings)try{typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="development"&&(e.onSchemaWarnings=o=>{for(let s of o)console.warn(`[Traffical] Schema warning for "${s.event}":`,s.violations.map(a=>`${a.path}: ${a.message}`).join(", "))})}catch{}if(this._eventLogger=new he({endpoint:`${this._options.baseUrl}/v1/events/batch`,apiKey:e.apiKey,storage:this._storage,lifecycleProvider:this._lifecycleProvider,batchSize:e.batchSize??e.eventBatchSize,flushIntervalMs:e.flushIntervalMs??e.eventFlushIntervalMs,maxQueueSize:e.eventMaxQueueSize,requestTimeoutMs:e.eventsTimeoutMs??e.requestTimeoutMs,onError:i=>{console.warn("[Traffical] Event logging error:",i.message)},onSchemaWarnings:e.onSchemaWarnings}),this._exposureDedup=new J({storage:this._storage,sessionTtlMs:e.exposureSessionTtlMs}),this._stableId=new pe({storage:this._storage}),this._plugins=new ye,this._assignmentLogger=e.assignmentLogger,this._byoEventLogger=e.eventLogger,this._disableCloudEvents=e.disableCloudEvents??!1,this._assignmentLoggerDedup=e.deduplicateAssignmentLogger!==!1&&e.assignmentLogger?new J({storage:this._storage,sessionTtlMs:e.exposureSessionTtlMs}):null,e.trackDecisions!==!1&&(!this._disableCloudEvents||this._byoEventLogger)&&this._plugins.register({plugin:Me({deduplicationTtlMs:e.decisionDeduplicationTtlMs},{orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,log:i=>this._dispatchEvent(i),getConfigVersion:()=>this.getConfigVersion()}),priority:100}),e.plugins)for(let i of e.plugins)this._plugins.register(i);if(this._options.localConfig){let i=z(this._options.localConfig);i.ok?(this._state.bundle=this._options.localConfig,this._plugins.runConfigUpdate(this._options.localConfig)):(this._errorPolicy.recordRejectedBundle("localConfig",i.path,i.reason),this._options.localConfig=void 0)}if(typeof window<"u"){let i=window;i.__TRAFFICAL_INSTANCES__??(i.__TRAFFICAL_INSTANCES__=[]),i.__TRAFFICAL_INSTANCES__.push(this)}}async initialize(){await this._errorPolicy.sideEffectAsync("initialize","other",async()=>{this._options.evaluationMode==="server"?await this._fetchServerResolve():await this._fetchConfig(),this._startBackgroundRefresh(),this._state.isInitialized=!0,await this._plugins.runInitialize(this)}),this._readyResolve()}get isInitialized(){return this._state.isInitialized}async waitForReady(){return this._readyPromise}async close(){if(this._state.refreshTimer&&(clearInterval(this._state.refreshTimer),this._state.refreshTimer=null),this._lifecycleProvider.isUnloading()?this._eventLogger.flushBeacon():await this._eventLogger.flush().catch(()=>{}),this._eventLogger.destroy(),this._plugins.runDestroy(),this._identityListeners=[],this._overrideListeners=[],this._overrides={},typeof window<"u"){let t=window.__TRAFFICAL_INSTANCES__;if(t){let n=t.indexOf(this);n!==-1&&t.splice(n,1)}}}destroy(){if(this._state.refreshTimer&&(clearInterval(this._state.refreshTimer),this._state.refreshTimer=null),this._lifecycleProvider.isUnloading()?this._eventLogger.flushBeacon():this._eventLogger.flush().catch(()=>{}),this._eventLogger.destroy(),this._plugins.runDestroy(),this._identityListeners=[],this._overrideListeners=[],this._overrides={},typeof window<"u"){let t=window.__TRAFFICAL_INSTANCES__;if(t){let n=t.indexOf(this);n!==-1&&t.splice(n,1)}}}async refreshConfig(){await this._errorPolicy.sideEffectAsync("refreshConfig","other",async()=>{this._options.evaluationMode==="server"?await this._fetchServerResolve():await this._fetchConfig()})}getConfigVersion(){return this._state.serverResponse?.stateVersion??this._state.bundle?.version??null}getUnitKeyField(){return ue(this._getEffectiveBundle())}getParameterLayerId(e){return de(this._getEffectiveBundle(),e)}getDiagnostics(){return this._errorPolicy.getDiagnostics()}getParams(e,t){let{context:n,defaults:i}=st(e,t);return this._errorPolicy.resolve("getParams",()=>{if(this._options.evaluationMode==="server"&&this._state.serverResponse){this._maybeResolveForContext(n);let c={...i};for(let[f,g]of Object.entries(this._state.serverResponse.assignments))f in c&&(c[f]=g);return this._plugins.runResolve(c),this._applyOverridesToResult(c),c}let o=this._getEffectiveBundle(),s=this._enrichContext(n),a=fe(o,s,i);return this._plugins.runResolve(a),this._applyOverridesToResult(a),a},()=>({...i}))}decide(e,t){let{context:n,defaults:i}=st(e,t),o=this._errorPolicy.resolve("decide",()=>{if(this._options.evaluationMode==="server"&&this._state.serverResponse){this._maybeResolveForContext(n);let g=this._state.serverResponse,l={...i};for(let[u,m]of Object.entries(g.assignments))u in l&&(l[u]=m);let p={decisionId:N(),assignments:l,metadata:{...g.metadata,configVersion:g.stateVersion}};return this._cacheDecision(p),this._updateCumulativeAttribution(p),this._plugins.runDecision(p),this._applyOverridesToResult(p.assignments),p.metadata.reason=g.metadata.layers?.some(u=>u.policyId)?"resolved":"default",p}let s=this._getEffectiveBundle(),a=this._enrichContext(n);a=this._plugins.runBeforeDecision(a);let c=this._state.cachedEdgeResults??void 0,f=ge(s,a,i,c);return this._cacheDecision(f),this._updateCumulativeAttribution(f),this._plugins.runDecision(f),this._applyOverridesToResult(f.assignments),f.metadata.reason=s?f.metadata.layers.some(g=>g.policyId)?"resolved":"default":"no-bundle",f},()=>({decisionId:N(),assignments:{...i},metadata:{timestamp:new Date().toISOString(),unitKeyValue:"",layers:[],reason:"error"}}));return this._emitAssignmentLogEntries(o,"decision"),o}trackExposure(e){this._emitAssignmentLogEntries(e,"exposure"),this._errorPolicy.resolve("trackExposure",()=>{let t=e.metadata.unitKeyValue;if(!t)return;let n=e.metadata.configVersion??this.getConfigVersion()??void 0,i=[];for(let s of e.metadata.layers)!s.policyId||!s.allocationName||s.attributionOnly||!this._exposureDedup.checkAndMark(t,s.policyId,s.allocationName)||i.push(s);if(i.length===0)return;let o={type:"exposure",id:Se(),decisionId:e.decisionId,orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,unitKey:t,timestamp:new Date().toISOString(),assignments:e.assignments,layers:i,context:e.metadata.filteredContext,configVersion:n,sdkName:Ue,sdkVersion:O};this._plugins.runExposure(o)&&this._dispatchEvent(o)},()=>{})}track(e,t,n){this._errorPolicy.resolve("track",()=>{let i=n?.unitKey??this._stableId.getId(),o=typeof n?.value=="number"?n.value:typeof t?.value=="number"?t.value:void 0,s=this._buildAttribution(i,n?.decisionId),a=n?.decisionId,c={type:"track",id:Re(),orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,unitKey:i,timestamp:new Date().toISOString(),event:e,value:o,values:n?.values,properties:t,decisionId:a,attribution:s,eventTimestamp:n?.eventTimestamp,sdkName:Ue,sdkVersion:O};this._plugins.runTrack(c)&&this._dispatchEvent(c)},()=>{})}async flushEvents(){await this._errorPolicy.sideEffectAsync("flushEvents","other",async()=>{await this._eventLogger.flush()})}use(e){if(!this._plugins.register(e))return this;if(this._state.isInitialized){try{e.onInitialize?.(this)}catch(n){console.warn(`[Traffical] Plugin "${e.name}" late onInitialize error:`,n)}if(this._state.bundle)try{e.onConfigUpdate?.(this._state.bundle)}catch(n){console.warn(`[Traffical] Plugin "${e.name}" late onConfigUpdate error:`,n)}}return this}getPlugin(e){return this._plugins.get(e)}getStableId(){return this._stableId.getId()}setStableId(e){this._stableId.setId(e)}identify(e){this._stableId.setId(e);for(let t of this._identityListeners)try{t(e)}catch{}}onIdentityChange(e){return this._identityListeners.push(e),()=>{this._identityListeners=this._identityListeners.filter(t=>t!==e)}}onOverridesChange(e){return this._overrideListeners.push(e),()=>{this._overrideListeners=this._overrideListeners.filter(t=>t!==e)}}applyOverrides(e){Object.assign(this._overrides,e),this._notifyOverrideListeners()}clearOverrides(){this._overrides={},this._notifyOverrideListeners()}getOverrides(){return{...this._overrides}}_notifyOverrideListeners(){let e={...this._overrides};for(let t of this._overrideListeners)try{t(e)}catch{}}_dispatchEvent(e){if(this._byoEventLogger)try{this._byoEventLogger(e)}catch{}this._disableCloudEvents||this._eventLogger.log(e)}_emitAssignmentLogEntries(e,t){if(!this._assignmentLogger)return;let n=e.metadata.unitKeyValue;if(!n)return;let i=e.metadata.configVersion??this.getConfigVersion()??void 0;for(let o of e.metadata.layers){if(!o.policyId||!o.allocationName||this._assignmentLoggerDedup&&!this._assignmentLoggerDedup.checkAndMark(n,o.policyId,`${o.allocationName}:${t}`))continue;let s=o.policyId,a=o.allocationName;this._errorPolicy.sideEffect("assignmentLogger","assignmentLog",()=>this._assignmentLogger({unitKey:n,policyId:s,policyKey:o.policyKey,allocationName:a,allocationKey:o.allocationKey,timestamp:e.metadata.timestamp,layerId:o.layerId,allocationId:o.allocationId,orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,sdkName:Ue,sdkVersion:O,properties:e.metadata.filteredContext,type:t,decisionId:e.decisionId,anonymousId:this._stableId.getId(),id:De(),bucket:o.bucket>=0?o.bucket:void 0,probability:o.probability,modelVersion:o.modelVersion,configVersion:i}))}}_applyOverridesToResult(e){let t=Object.keys(this._overrides);if(t.length!==0)for(let n of t)n in e&&(e[n]=this._overrides[n])}_getEffectiveBundle(){return this._state.bundle??this._options.localConfig??null}_enrichContext(e){let n=this._getEffectiveBundle()?.hashing?.unitKey??"userId";return e[n]?e:{...e,[n]:this._stableId.getId()}}async _fetchConfig(){let e=`${this._options.baseUrl}/v1/config/${encodeURIComponent(this._options.projectId)}?env=${encodeURIComponent(this._options.env)}`,t={"Content-Type":"application/json",Authorization:`Bearer ${this._options.apiKey}`};this._state.etag&&(t["If-None-Match"]=this._state.etag);let n=new AbortController,i=setTimeout(()=>n.abort(),this._requestTimeoutMs);try{let o=await fetch(e,{method:"GET",headers:t,signal:n.signal});if(o.status===304){this._state.lastFetchTime=Date.now();return}if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);let s=await o.json(),a=o.headers.get("ETag"),c=z(s);if(!c.ok){this._errorPolicy.recordRejectedBundle("fetchConfig",c.path,c.reason),this._logMalformedBundleWarning();return}if(this._state.bundle=s,this._state.etag=a,this._state.lastFetchTime=Date.now(),this._findEdgePolicies(s).length>0){let f=await this._prefetchEdgeResults(s,this._enrichContext({}));this._state.cachedEdgeResults=f}else this._state.cachedEdgeResults=null;this._plugins.runConfigUpdate(s)}catch(o){this._logOfflineWarning(o)}finally{clearTimeout(i)}}_startBackgroundRefresh(){let e=this._options.evaluationMode==="server"?this._state.serverResponse?.suggestedRefreshMs??this._options.refreshIntervalMs:this._options.refreshIntervalMs;if(e<=0)return;let t=()=>{this._state.refreshTimer=setTimeout(()=>{t(),this._options.evaluationMode==="server"?this._fetchServerResolve().catch(()=>{}):this._fetchConfig().catch(()=>{})},An(e))};t()}_maybeResolveForContext(e){let t=this._enrichContext(e),n;try{n=JSON.stringify(t)}catch{n=""}n!==this._lastResolveContextKey&&(this._lastResolveContextKey=n,this._fetchServerResolve(t))}async _fetchServerResolve(e){if(this._decisionClient)try{let t=e??this._enrichContext({}),n=await this._decisionClient.resolve({context:t});n&&(this._state.serverResponse=n,this._state.lastFetchTime=Date.now())}catch(t){this._logOfflineWarning(t)}}_findEdgePolicies(e){let t=[];for(let n of e.layers)for(let i of n.policies)i.state==="running"&&i.entityConfig?.resolutionMode==="edge"&&t.push(i);return t}async _prefetchEdgeResults(e,t){if(!this._decisionClient)return{};let n=this._findEdgePolicies(e);if(n.length===0)return{};let i=W(e,t);if(!i)return{};let o=n.map(s=>{if(!s.entityConfig)return null;let a=s.entityConfig.dynamicAllocations?typeof t[s.entityConfig.dynamicAllocations.countKey]=="number"?Math.floor(t[s.entityConfig.dynamicAllocations.countKey]):0:s.allocations.length;return Pe(s.id,s.entityConfig.entityKeys,t,i,a||void 0)}).filter(s=>s!==null);if(o.length===0)return{};try{let s=await this._decisionClient.decideEntityBatch(o),a=new Map;for(let c=0;c<o.length;c++){let f=s[c];f&&a.set(o[c].policyId,{allocationIndex:f.allocationIndex,entityId:o[c].entityId})}return a.size>0?{edgeResults:a}:{}}catch{return{}}}_logOfflineWarning(e){let t=Date.now();t-this._state.lastOfflineWarning>In&&(console.warn(`[Traffical] Failed to fetch config: ${e instanceof Error?e.message:String(e)}. Using ${this._state.bundle?"cached":"local"} config.`),this._state.lastOfflineWarning=t)}_logMalformedBundleWarning(){let e=Date.now();e-this._state.lastMalformedWarning>Tn&&(console.warn(`[Traffical] Discarded malformed config bundle (invalid hashing/shape). Using ${this._state.bundle?"cached":"local"} config.`),this._state.lastMalformedWarning=e)}_cacheDecision(e){if(this._decisionCache.size>=Cn){let t=this._decisionCache.keys().next().value;t&&this._decisionCache.delete(t)}this._decisionCache.set(e.decisionId,e)}_updateCumulativeAttribution(e){let t=e.metadata.unitKeyValue;if(!t)return;let n=this._cumulativeAttribution.get(t);n||(n=new Map,this._cumulativeAttribution.set(t,n));for(let i of e.metadata.layers){if(!i.policyId||!i.allocationName)continue;let o=`${i.layerId}:${i.policyId}`;n.set(o,{layerId:i.layerId,policyId:i.policyId,allocationName:i.allocationName})}}_buildAttribution(e,t){if(this._options.attributionMode==="decision"){if(!t)return;let i=this._decisionCache.get(t);return i?i.metadata.layers.filter(o=>o.policyId&&o.allocationName).map(o=>({layerId:o.layerId,policyId:o.policyId,allocationName:o.allocationName})):void 0}let n=this._cumulativeAttribution.get(e);return n&&n.size>0?Array.from(n.values()):void 0}};async function at(r){let e=new U(r);return await e.initialize(),e}function ct(r){return new U(r)}function lt(r={}){let e={observeMutations:r.observeMutations??!0,debounceMs:r.debounceMs??100},t=[],n={},i=null,o=null;function s(u,m){try{return new RegExp(u).test(m)}catch{return m===u}}function a(u,m,b){if(m==="innerHTML")u.innerHTML=b;else if(m==="textContent")u.textContent=b;else if(m==="src"&&"src"in u)u.src=b;else if(m==="href"&&"href"in u)u.href=b;else if(m.startsWith("style.")){let _=m.slice(6);u.style[_]=b}else u.setAttribute(m,b)}function c(u,m){let b=String(m);try{let _=document.querySelectorAll(u.selector);for(let T of _)a(T,u.property,b)}catch(_){console.warn(`[Traffical DOM Binding] Failed to apply binding for ${u.parameterKey}:`,_)}}function f(u,m=!1){n=u;let b=typeof window<"u"?window.location.pathname:"";for(let _ of t){if(!m&&!s(_.urlPattern,b))continue;let T=u[_.parameterKey];T!==void 0&&c(_,T)}}function g(){o&&clearTimeout(o),o=setTimeout(()=>{f(n)},e.debounceMs)}function l(){i||typeof MutationObserver>"u"||typeof document>"u"||(i=new MutationObserver(()=>{g()}),i.observe(document.body,{childList:!0,subtree:!0}))}function p(){i&&(i.disconnect(),i=null),o&&(clearTimeout(o),o=null)}return{name:"dom-binding",onInitialize(){e.observeMutations&&l()},onConfigUpdate(u){t=u.domBindings??[]},onResolve(u){f(u)},onDecision(u){f(u.assignments)},onDestroy(){p(),t=[],n={}},applyBindings(u){f(u||n)},getBindings(){return t}}}var C=null;async function kn(r){return C?(console.warn("[Traffical] Client already initialized. Returning existing instance."),C):(C=await at(r),C)}function Sn(r){return C?(console.warn("[Traffical] Client already initialized. Returning existing instance."),C):(C=ct(r),C.initialize().catch(e=>{console.warn("[Traffical] Initialization error:",e)}),C)}function Rn(){return C}function Dn(){C&&(C.destroy(),C=null)}return yt(Pn);})();
1
+ /* @traffical/js-client v0.19.0 */
2
+ "use strict";var Traffical=(()=>{var ee=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var yt=Object.getOwnPropertyNames;var _t=Object.prototype.hasOwnProperty;var bt=(r,e,t)=>e in r?ee(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var vt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),xt=(r,e)=>{for(var t in e)ee(r,t,{get:e[t],enumerable:!0})},Et=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of yt(e))!_t.call(r,i)&&i!==t&&ee(r,i,{get:()=>e[i],enumerable:!(n=mt(e,i))||n.enumerable});return r};var Tt=r=>Et(ee({},"__esModule",{value:!0}),r);var y=(r,e,t)=>(bt(r,typeof e!="symbol"?e+"":e,t),t);var Qe=vt(()=>{});var Hn={};xt(Hn,{AUTO_ATTRIBUTE_KEYS:()=>Z,TrafficalClient:()=>$,autoAttributesPlugin:()=>_e,createAutoAttributesPlugin:()=>Ke,createDOMBindingPlugin:()=>pt,createDebugPlugin:()=>Fe,createRedirectAttributionPlugin:()=>Ve,createRedirectPlugin:()=>$e,destroy:()=>jn,init:()=>Vn,initSync:()=>Kn,instance:()=>Fn});function It(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function xe(r,e,t=""){let n=It(r),i=r?.length,o=e!==void 0;if(!n||o&&i!==e){let s=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof r}`,u=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return r}function Ee(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function He(r,e){xe(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function V(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function te(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function C(r,e){return r<<32-e|r>>>e}function We(r,e={}){let t=(i,o)=>r(o).update(i).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=i=>r(i),Object.assign(t,e),Object.freeze(t)}var ze=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Ge(r,e,t){return r&e^~r&t}function qe(r,e,t){return r&e^r&t^e&t}var ne=class{constructor(e,t,n,i){y(this,"blockLen");y(this,"outputLen");y(this,"canXOF",!1);y(this,"padOffset");y(this,"isLE");y(this,"buffer");y(this,"view");y(this,"finished",!1);y(this,"length",0);y(this,"pos",0);y(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=te(this.buffer)}update(e){Ee(this),xe(e);let{view:t,buffer:n,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=te(e);for(;i<=o-s;s+=i)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ee(this),He(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,V(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let l=s;l<i;l++)t[l]=0;n.setBigUint64(i-8,BigInt(this.length*8),o),this.process(n,0);let a=te(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,g=this.get();if(u>g.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,g[l],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:i,finished:o,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=a,i%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},k=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var At=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),D=new Uint32Array(64),Te=class extends ne{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:i,E:o,F:s,G:a,H:c}=this;return[e,t,n,i,o,s,a,c]}set(e,t,n,i,o,s,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)D[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=D[l-15],d=D[l-2],m=C(p,7)^C(p,18)^p>>>3,x=C(d,17)^C(d,19)^d>>>10;D[l]=x+D[l-7]+m+D[l-16]|0}let{A:n,B:i,C:o,D:s,E:a,F:c,G:u,H:g}=this;for(let l=0;l<64;l++){let p=C(a,6)^C(a,11)^C(a,25),d=g+p+Ge(a,c,u)+At[l]+D[l]|0,x=(C(n,2)^C(n,13)^C(n,22))+qe(n,i,o)|0;g=u,u=c,c=a,a=s+d|0,s=o,o=i,i=n,n=d+x|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,g=g+this.H|0,this.set(n,i,o,s,a,c,u,g)}roundClean(){V(D)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),V(this.buffer)}},Ie=class extends Te{constructor(){super(32);y(this,"A",k[0]|0);y(this,"B",k[1]|0);y(this,"C",k[2]|0);y(this,"D",k[3]|0);y(this,"E",k[4]|0);y(this,"F",k[5]|0);y(this,"G",k[6]|0);y(this,"H",k[7]|0)}};var Xe=We(()=>new Ie,ze(1));var Je=new TextEncoder,Ae="v2";function re(r){return Je.encode(r).length}function ie(r,e){let t=re(r),n=re(e);return`traffical:assignment:${Ae}|u:${t}:${r}|l:${n}:${e}`}function K(r){return Xe(Je.encode(r))}function F(r){let e=0n;for(let t=0;t<8;t++)e=e<<8n|BigInt(r[t]);return e}function oe(r){return F(K(r))}function se(r,e,t){let n=K(ie(r,e)),i=F(n);return Number(i%BigInt(t))}function we(r,e){return r>=e[0]&&r<=e[1]}function ae(r,e){for(let t of e)if(we(r,t.bucketRange))return t;return null}var wt=1n<<53n,Ct=9007199254740992;function B(r,e){if(r.length===0||r.length===1)return 0;let t=oe(e),n=Number(t%wt)/Ct,i=0;for(let o=0;o<r.length;o++)if(i+=r[o],n<i)return o;return r.length-1}function Ce(r,e){let{field:t,op:n,value:i,values:o}=r,s=le(e,t);switch(n){case"eq":return s===i;case"neq":return s!==i;case"in":return Array.isArray(o)?o.includes(s):!1;case"nin":return Array.isArray(o)?!o.includes(s):!0;case"gt":return typeof s=="number"&&s>i;case"gte":return typeof s=="number"&&s>=i;case"lt":return typeof s=="number"&&s<i;case"lte":return typeof s=="number"&&s<=i;case"contains":return typeof s=="string"&&typeof i=="string"&&s.includes(i);case"startsWith":return typeof s=="string"&&typeof i=="string"&&s.startsWith(i);case"endsWith":return typeof s=="string"&&typeof i=="string"&&s.endsWith(i);case"regex":if(typeof s!="string"||typeof i!="string")return!1;try{return new RegExp(i).test(s)}catch{return!1}case"exists":return s!=null;case"notExists":return s==null;default:return!1}}function ce(r,e){return r.length===0?!0:r.every(t=>Ce(t,e))}function le(r,e){if(r!==null&&typeof r=="object"&&Object.prototype.hasOwnProperty.call(r,e))return r[e];let t=e.split("."),n=r;for(let i of t){if(n==null)return;if(typeof n=="object")n=n[i];else return}return n}function Se(r,e){let t=r.intercept;for(let{key:n,coef:i,missing:o}of r.numeric){let s=e[n];t+=typeof s=="number"?i*s:o}for(let{key:n,values:i,missing:o}of r.categorical){let s=e[n],a=s!=null?String(s):null;t+=a!==null&&a in i?i[a]:o}return t}function ke(r,e){if(r.length===0)return[];if(r.length===1)return[1];let t=Math.max(e,1e-10),n=r.map(a=>a/t),i=Math.max(...n),o=n.map(a=>Math.exp(a-i)),s=o.reduce((a,c)=>a+c,0);return o.map(a=>a/s)}function Pe(r,e){if(r.length===0)return[];if(e<=0)return r;let t=r.length,n=1/t,i=Math.min(e,n),o=r.map(a=>Math.max(a,i)),s=o.reduce((a,c)=>a+c,0);return s===0?Array(t).fill(1/t):o.map(a=>a/s)}function ue(r,e,t){let n=r.contextualModel;if(!n||r.allocations.length===0)return null;let i=Pt(n,r.allocations,e),o=ke(i,n.gamma),s=Pe(o,n.actionProbabilityFloor),a=`ctx:${t}:${r.id}`,c=B(s,a);return{allocation:r.allocations[c],probability:s[c]}}function Pt(r,e,t){return e.map(n=>{let i=r.coefficients[n.key??n.name];return i?Se(i,t):r.defaultAllocationScore})}var Rt=r=>crypto.getRandomValues(new Uint8Array(r)),Dt=(r,e,t)=>{let n=(2<<Math.log2(r.length-1))-1,i=-~(1.6*n*e/r.length);return(o=e)=>{let s="";for(;;){let a=t(i),c=i|0;for(;c--;)if(s+=r[a[c]&n]||"",s.length>=o)return s}}},Ye=(r,e=21)=>Dt(r,e|0,Rt);function de(r){let e=new Error(r);return e.source="ulid",e}var Re="0123456789ABCDEFGHJKMNPQRSTVWXYZ",j=Re.length,Ze=Math.pow(2,48)-1,Ot=10,Lt=16;function Mt(r){let e=Math.floor(r()*j);return e===j&&(e=j-1),Re.charAt(e)}function Bt(r,e){if(isNaN(r))throw new Error(r+" must be a number");if(r>Ze)throw de("cannot encode time greater than "+Ze);if(r<0)throw de("time must be positive");if(Number.isInteger(Number(r))===!1)throw de("time must be an integer");let t,n="";for(;e>0;e--)t=r%j,n=Re.charAt(t)+n,r=(r-t)/j;return n}function Nt(r,e){let t="";for(;r>0;r--)t=Mt(e)+t;return t}function Ut(r=!1,e){e||(e=typeof window<"u"?window:null);let t=e&&(e.crypto||e.msCrypto);if(t)return()=>{let n=new Uint8Array(1);return t.getRandomValues(n),n[0]/255};try{let n=Qe();return()=>n.randomBytes(1).readUInt8()/255}catch{}if(r){try{console.error("secure crypto unusable, falling back to insecure Math.random()!")}catch{}return()=>Math.random()}throw de("secure crypto unusable, insecure Math.random not allowed")}function $t(r){return r||(r=Ut()),function(t){return isNaN(t)&&(t=Date.now()),Bt(t,Ot)+Nt(Lt,r)}}var et=$t();var Vt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Kt=8,Er=Ye(Vt,Kt);function H(r){return`${r}_${et()}`}function N(){return H("dec")}function De(){return H("exp")}function Oe(){return H("trk")}function Le(){return H("asn")}function Ft(r,e){let t=new Set;for(let i of e)if(i.contextLogging?.allowedFields)for(let o of i.contextLogging.allowedFields)t.add(o);if(t.size===0)return;let n={};for(let i of t){let o=le(r,i);o!==void 0&&(n[i]=o)}return Object.keys(n).length>0?n:void 0}function jt(r,e){let t=[];for(let n of r){let i=e[n];if(i==null)return null;t.push(String(i))}return t.join("_")}function tt(r){if(r<=0)return[];let e=1/r;return Array(r).fill(e)}function Ht(r,e,t,n){let i=r.entityState?.[e];if(!i)return tt(n);let o=i.entities[t];if(o&&o.weights.length===n)return o.weights;let s=i._global;return s&&s.weights.length===n?s.weights:tt(n)}function Wt(r,e,t,n){let i=e.entityConfig;if(!i)return null;let o=jt(i.entityKeys,t);if(!o)return null;let s,a;if(i.dynamicAllocations){let l=i.dynamicAllocations.countKey,p=t[l];if(typeof p!="number"||p<=0)return null;a=Math.floor(p),s=Array.from({length:a},(d,m)=>({id:`${e.id}_dynamic_${m}`,name:String(m),bucketRange:[0,0],overrides:{}}))}else s=e.allocations,a=s.length;if(a===0)return null;let c=Ht(r,e.id,o,a),u=`${o}:${n}:${e.id}`,g=B(c,u);return{allocation:s[g],weight:c[g],entityId:o}}function W(r,e){let t=e[r.hashing.unitKey];return t==null?null:String(t)}function fe(r){return r?.hashing?.unitKey??null}function ge(r,e){return r?r.parameters.find(n=>n.key===e)?.layerId??null:null}function nt(r,e,t,n){let i={...t},o=[],s=[];if(!r)return{assignments:i,unitKeyValue:"",layers:o,matchedPolicies:s};let a=W(r,e)??"",c=new Set(Object.keys(t)),u=r.parameters.filter(l=>c.has(l.key));for(let l of u)l.key in i&&(i[l.key]=l.default);let g=new Map;for(let l of u){let p=g.get(l.layerId)||[];p.push(l),g.set(l.layerId,p)}for(let l of r.layers){let p=g.get(l.id),d=p&&p.length>0,m=l.unitKey,x=m!=null;if(x&&String(m).trim()===""){o.push({layerId:l.id,bucket:-1,...d?{}:{attributionOnly:!0}});continue}let b=x?String(e[m]??""):a;if(!b){o.push({layerId:l.id,bucket:-1,...x?{unitKey:m,unitKeyValue:""}:{},...d?{}:{attributionOnly:!0}});continue}let I=se(b,l.id,r.hashing.bucketCount),w,E,R,f;for(let h of l.policies)if(h.state==="running"){if(h.eligibleBucketRange){let{start:v,end:T}=h.eligibleBucketRange;if(I<v||I>T)continue}if(ce(h.conditions,e)){if(h.contextualModel){let v=ue(h,e,b);if(v){if(w=h,E=v.allocation,R=v.probability,f=h.contextualModel.generatedAt??h.contextualModel.modelVersion,s.push(h),d)for(let[T,S]of Object.entries(v.allocation.overrides))T in i&&(i[T]=S);break}}if(h.entityConfig&&h.entityConfig.resolutionMode==="bundle"){let v=Wt(r,h,e,b);if(v){if(w=h,E=v.allocation,R=v.weight,s.push(h),d&&!h.entityConfig.dynamicAllocations)for(let[T,S]of Object.entries(v.allocation.overrides))T in i&&(i[T]=S);break}}else if(h.entityConfig&&h.entityConfig.resolutionMode==="edge"){let v=n?.edgeResults?.get(h.id);if(v){if(w=h,s.push(h),h.entityConfig.dynamicAllocations)E={id:`${h.id}_dynamic_${v.allocationIndex}`,name:String(v.allocationIndex),bucketRange:[0,0],overrides:{}};else if(h.allocations[v.allocationIndex]&&(E=h.allocations[v.allocationIndex],d&&E))for(let[T,S]of Object.entries(E.overrides))T in i&&(i[T]=S);break}continue}else{let v=ae(I,h.allocations);if(v){if(w=h,E=v,h.kind==="adaptive"){let[T,S]=v.bucketRange;R=(S-T+1)/r.hashing.bucketCount}if(s.push(h),d)for(let[T,S]of Object.entries(v.overrides))T in i&&(i[T]=S);break}}}}o.push({layerId:l.id,bucket:I,policyId:w?.id,policyKey:w?.key,allocationId:E?.id,allocationName:E?.name,allocationKey:E?.key,...R!==void 0&&R>0&&R<=1?{probability:R}:{},...f!==void 0?{modelVersion:f}:{},...x?{unitKey:m,unitKeyValue:b}:{},...d?{}:{attributionOnly:!0}})}return{assignments:i,unitKeyValue:a,layers:o,matchedPolicies:s}}function he(r,e,t,n){return nt(r,e,t,n).assignments}function pe(r,e,t,n){let{assignments:i,unitKeyValue:o,layers:s,matchedPolicies:a}=nt(r,e,t,n),c=Ft(e,a);return{decisionId:N(),assignments:i,metadata:{timestamp:new Date().toISOString(),unitKeyValue:o,layers:s,filteredContext:c,...r?.version?{configVersion:r.version}:{}}}}var M=class r{constructor(e={}){y(this,"_seen",new Map);y(this,"_ttlMs");y(this,"_maxEntries");y(this,"_lastCleanup",Date.now());this._ttlMs=e.ttlMs??36e5,this._maxEntries=e.maxEntries??1e4}static hashAssignments(e){let t=Object.keys(e).sort(),n=[];for(let i of t){let o=e[i],s=typeof o=="object"?JSON.stringify(o):String(o);n.push(`${i}=${s}`)}return n.join("|")}static createKey(e,t){return`${e}:${t}`}checkAndMark(e,t){let n=r.createKey(e,t),i=Date.now(),o=this._seen.get(n);return o!==void 0&&i-o<this._ttlMs?!1:(this._seen.set(n,i),this._maybeCleanup(i),!0)}wouldBeNew(e,t){let n=r.createKey(e,t),i=Date.now(),o=this._seen.get(n);return o===void 0?!0:i-o>=this._ttlMs}clear(){this._seen.clear()}get size(){return this._seen.size}_maybeCleanup(e){(e-this._lastCleanup>this._ttlMs*.2||this._seen.size>this._maxEntries)&&(this._lastCleanup=e,this._cleanup(e))}_cleanup(e){let t=[];for(let[n,i]of this._seen.entries())e-i>=this._ttlMs&&t.push(n);for(let n of t)this._seen.delete(n);if(this._seen.size>this._maxEntries){let i=Array.from(this._seen.entries()).sort((o,s)=>o[1]-s[1]).slice(0,this._seen.size-this._maxEntries);for(let[o]of i)this._seen.delete(o)}}};var rt={resolutionErrors:0,droppedAssignmentLogs:0,droppedEventLogs:0,rejectedBundles:0,sideEffectErrors:0,lastError:null};function cn(r){return r instanceof Error?r:typeof r=="string"?new Error(r):new Error("An unknown error occurred")}var U=class{constructor(e={}){y(this,"_onResolutionError");y(this,"_onError");y(this,"_seen",new Set);y(this,"_counters",{...rt});this._onResolutionError=e.onResolutionError??"default",this._onError=e.onError}get throwsOnResolutionError(){return this._onResolutionError==="throw"}resolve(e,t,n){try{return t()}catch(i){if(this._counters.resolutionErrors++,this._report(e,i),this._onResolutionError==="throw")throw i;return n()}}async resolveAsync(e,t,n){try{return await t()}catch(i){if(this._counters.resolutionErrors++,this._report(e,i),this._onResolutionError==="throw")throw i;return n()}}sideEffect(e,t,n){try{n()}catch(i){this._countSideEffect(t),this._report(e,i)}}async sideEffectAsync(e,t,n){try{await n()}catch(i){this._countSideEffect(t),this._report(e,i)}}recordRejectedBundle(e,t,n){this._counters.rejectedBundles++,this._report(e,new Error(t?`${t}: ${n}`:n))}getDiagnostics(){return{...this._counters}}reset(){Object.assign(this._counters,rt,{lastError:null}),this._seen.clear()}_countSideEffect(e){switch(e){case"assignmentLog":this._counters.droppedAssignmentLogs++;break;case"eventLog":this._counters.droppedEventLogs++;break;case"bundleRejected":this._counters.rejectedBundles++;break;default:this._counters.sideEffectErrors++}}_report(e,t){let n=cn(t);this._counters.lastError={tag:e,name:n.name,message:n.message};let i=`${e}:${n.name}:${n.message}`;if(!this._seen.has(i)&&(this._seen.add(i),console.warn(`[Traffical] Contained error in ${e}:`,n.message),!!this._onError))try{this._onError(e,n)}catch{}}};function _(r,e){return{ok:!1,path:r,reason:e}}function O(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function P(r){return typeof r=="string"&&r.length>0}function z(r){if(!O(r))return _("","bundle is not an object");let e=r.hashing;if(!O(e))return _("hashing","missing or not an object");if(!P(e.unitKey))return _("hashing.unitKey","missing or not a non-empty string");if(typeof e.bucketCount!="number"||!Number.isInteger(e.bucketCount)||e.bucketCount<1)return _("hashing.bucketCount","not an integer >= 1");if(!Array.isArray(r.parameters))return _("parameters","not an array");for(let t=0;t<r.parameters.length;t++){let n=r.parameters[t],i=`parameters[${t}]`;if(!O(n))return _(i,"not an object");if(!P(n.key))return _(`${i}.key`,"missing or not a non-empty string");if(!P(n.layerId))return _(`${i}.layerId`,"missing or not a non-empty string");if(!("default"in n))return _(`${i}.default`,"missing")}if(!Array.isArray(r.layers))return _("layers","not an array");for(let t=0;t<r.layers.length;t++){let n=r.layers[t],i=`layers[${t}]`;if(!O(n))return _(i,"not an object");if(!P(n.id))return _(`${i}.id`,"missing or not a non-empty string");if(n.unitKey!==void 0&&typeof n.unitKey!="string")return _(`${i}.unitKey`,"present but not a string");if(!Array.isArray(n.policies))return _(`${i}.policies`,"not an array");for(let o=0;o<n.policies.length;o++){let s=n.policies[o],a=`${i}.policies[${o}]`;if(!O(s))return _(a,"not an object");if(!P(s.id))return _(`${a}.id`,"missing or not a non-empty string");if(!P(s.state))return _(`${a}.state`,"missing or not a non-empty string");if(!Array.isArray(s.allocations))return _(`${a}.allocations`,"not an array");if(!Array.isArray(s.conditions))return _(`${a}.conditions`,"not an array");for(let c=0;c<s.conditions.length;c++){let u=s.conditions[c],g=`${a}.conditions[${c}]`;if(!O(u))return _(g,"not an object");if(!P(u.field))return _(`${g}.field`,"missing or not a non-empty string");if(!P(u.op))return _(`${g}.op`,"missing or not a non-empty string")}for(let c=0;c<s.allocations.length;c++){let u=s.allocations[c],g=`${a}.allocations[${c}]`;if(!O(u))return _(g,"not an object");if(!P(u.name))return _(`${g}.name`,"missing or not a non-empty string");let l=u.bucketRange;if(!Array.isArray(l)||l.length!==2)return _(`${g}.bucketRange`,"not a 2-element array");let[p,d]=l;if(typeof p!="number"||typeof d!="number"||!Number.isInteger(p)||!Number.isInteger(d))return _(`${g}.bucketRange`,"bounds are not integers");if(p<0||d<p)return _(`${g}.bucketRange`,"bounds are negative or inverted");if(u.overrides!==void 0&&!O(u.overrides))return _(`${g}.overrides`,"present but not an object")}}}return{ok:!0}}var G=class{constructor(e){y(this,"config");y(this,"defaultTimeout");this.config=e,this.defaultTimeout=e.defaultTimeoutMs??5e3}async resolve(e){try{let t=new AbortController,n=setTimeout(()=>t.abort(),this.defaultTimeout),i=`${this.config.baseUrl}/v1/resolve`,o=await fetch(i,{method:"POST",headers:this._headers(),body:JSON.stringify({context:e.context,env:e.env??this.config.env,parameters:e.parameters}),signal:t.signal});return clearTimeout(n),o.ok?await o.json():(console.warn(`[Traffical] Resolve failed: ${o.status} ${o.statusText}`),null)}catch(t){return t instanceof Error&&t.name==="AbortError"?console.warn(`[Traffical] Resolve timed out after ${this.defaultTimeout}ms`):console.warn("[Traffical] Resolve error:",t),null}}async decideEntity(e,t){let n=t??Math.min(this.defaultTimeout,100);try{let i=new AbortController,o=setTimeout(()=>i.abort(),n),s=`${this.config.baseUrl}/v1/decide/${e.policyId}`,a=await fetch(s,{method:"POST",headers:this._headers(),body:JSON.stringify({entityId:e.entityId,unitKeyValue:e.unitKeyValue,allocationCount:e.allocationCount,context:e.context}),signal:i.signal});return clearTimeout(o),a.ok?await a.json():(console.warn(`[Traffical] Edge decide failed: ${a.status} ${a.statusText}`),null)}catch(i){return i instanceof Error&&i.name==="AbortError"?console.warn(`[Traffical] Edge decide timed out after ${n}ms`):console.warn("[Traffical] Edge decide error:",i),null}}async decideEntityBatch(e,t){if(e.length===0)return[];if(e.length===1)return[await this.decideEntity(e[0],t)];let n=t??Math.min(this.defaultTimeout,200);try{let i=new AbortController,o=setTimeout(()=>i.abort(),n),s=`${this.config.baseUrl}/v1/decide/batch`,a=await fetch(s,{method:"POST",headers:this._headers(),body:JSON.stringify({requests:e}),signal:i.signal});return clearTimeout(o),a.ok?(await a.json()).responses:(console.warn(`[Traffical] Edge batch decide failed: ${a.status} ${a.statusText}`),e.map(()=>null))}catch(i){return i instanceof Error&&i.name==="AbortError"?console.warn(`[Traffical] Edge batch decide timed out after ${n}ms`):console.warn("[Traffical] Edge batch decide error:",i),e.map(()=>null)}}_headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"X-Org-Id":this.config.orgId,"X-Project-Id":this.config.projectId,"X-Env":this.config.env}}};function Me(r,e,t,n,i){let o=[];for(let a of e){let c=t[a];if(c==null)return null;o.push(String(c))}let s=o.join("_");return{policyId:r,entityId:s,unitKeyValue:n,allocationCount:i,context:t}}var q="failed_events";var me=class{constructor(e){this._queue=[];this._flushTimer=null;this._isFlushing=!1;this._isDisabled=!1;this._droppedCount=0;this._endpoint=e.endpoint,this._apiKey=e.apiKey,this._storage=e.storage,this._batchSize=e.batchSize??10,this._flushIntervalMs=e.flushIntervalMs??3e4,this._requestTimeoutMs=e.requestTimeoutMs??1e4,this._maxQueueSize=e.maxQueueSize??1e3,this._onError=e.onError,this._onSchemaWarnings=e.onSchemaWarnings,this._lifecycleProvider=e.lifecycleProvider,this._setupListeners(),this._retryFailedEvents(),this._startFlushTimer()}log(e){this._isDisabled||(this._queue.length>=this._maxQueueSize&&(this._queue.shift(),this._droppedCount++),this._queue.push(e),this._queue.length>=this._batchSize&&this.flush())}async flush(){if(this._isFlushing||this._isDisabled||this._queue.length===0)return;this._isFlushing=!0;let e=[...this._queue];this._queue=[];try{let t=await this._sendEvents(e);if(t>=200&&t<300)return;if(t===401){this._disable();return}if(t===429||t>=500){this._persistFailedEvents(e),this._onError?.(new Error(`HTTP ${t}: event delivery failed, will retry`));return}this._onError?.(new Error(`HTTP ${t}: batch rejected, dropping ${e.length} events`))}catch(t){this._persistFailedEvents(e),this._onError?.(t instanceof Error?t:new Error(String(t)))}finally{this._isFlushing=!1}}_disable(){this._isDisabled||(this._isDisabled=!0,this._queue=[],this._storage.remove(q),console.warn("[Traffical] API key rejected (HTTP 401); event delivery disabled for this client"))}get droppedCount(){return this._droppedCount}get isDisabled(){return this._isDisabled}flushBeacon(){if(this._queue.length===0)return!0;if(typeof fetch>"u")return this.flush(),!1;let e=[...this._queue];return this._queue=[],fetch(this._endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this._apiKey}`},body:JSON.stringify({events:e}),keepalive:!0}).catch(()=>{this._persistFailedEvents(e)}),!0}get queueSize(){return this._queue.length}destroy(){this._flushTimer&&(clearInterval(this._flushTimer),this._flushTimer=null),this._removeListeners()}async _sendEvents(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this._requestTimeoutMs),i;try{i=await fetch(this._endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this._apiKey}`},body:JSON.stringify({events:e}),signal:t.signal})}finally{clearTimeout(n)}if(!i.ok)return i.status;if(this._onSchemaWarnings)try{let o=await i.json();o.schemaWarnings&&o.schemaWarnings.length>0&&this._onSchemaWarnings(o.schemaWarnings)}catch{}return i.status}_persistFailedEvents(e){let n=[...this._storage.get(q)??[],...e].slice(-100);this._storage.set(q,n)}_retryFailedEvents(){let e=this._storage.get(q);!e||e.length===0||(this._storage.remove(q),this._queue.push(...e))}_startFlushTimer(){this._flushIntervalMs<=0||(this._flushTimer=setInterval(()=>{this.flush().catch(()=>{})},this._flushIntervalMs))}_setupListeners(){this._lifecycleProvider&&(this._visibilityCallback=e=>{e==="background"?this._lifecycleProvider?.isUnloading()?this.flushBeacon():this.flush().catch(()=>{}):this._retryFailedEvents()},this._lifecycleProvider.onVisibilityChange(this._visibilityCallback))}_removeListeners(){this._lifecycleProvider&&this._visibilityCallback&&(this._lifecycleProvider.removeVisibilityListener(this._visibilityCallback),this._visibilityCallback=void 0)}};var X="exposure_dedup";var J=class r{constructor(e){this._storage=e.storage,this._sessionTtlMs=e.sessionTtlMs??18e5,this._seen=new Set,this._sessionStart=Date.now(),this._restore()}static createKey(e,t,n){return`${e}:${t}:${n}`}shouldTrack(e){return this._isSessionExpired()&&this._resetSession(),this._seen.has(e)?!1:(this._seen.add(e),this._persist(),!0)}checkAndMark(e,t,n){let i=r.createKey(e,t,n);return this.shouldTrack(i)}clear(){this._seen.clear(),this._storage.remove(X)}get size(){return this._seen.size}_isSessionExpired(){return Date.now()-this._sessionStart>this._sessionTtlMs}_resetSession(){this._seen.clear(),this._sessionStart=Date.now(),this._storage.remove(X)}_persist(){let e={seen:Array.from(this._seen),sessionStart:this._sessionStart};this._storage.set(X,e,this._sessionTtlMs)}_restore(){let e=this._storage.get(X);if(!e)return;if(Date.now()-e.sessionStart>this._sessionTtlMs){this._storage.remove(X);return}this._seen=new Set(e.seen),this._sessionStart=e.sessionStart}};var Y="stable_id",un="traffical_sid";var ye=class{constructor(e){this._cachedId=null;this._storage=e.storage,this._useCookieFallback=e.useCookieFallback??!0,this._cookieName=e.cookieName??un}getId(){if(this._cachedId)return this._cachedId;let e=this._storage.get(Y);return e?(this._cachedId=e,e):this._useCookieFallback&&(e=this._getCookie(),e)?(this._storage.set(Y,e),this._cachedId=e,e):(e=this._generateId(),this._persist(e),this._cachedId=e,e)}setId(e){this._persist(e),this._cachedId=e}clear(){this._storage.remove(Y),this._useCookieFallback&&this._deleteCookie(),this._cachedId=null}hasId(){return this._storage.get(Y)!==null||this._getCookie()!==null}_persist(e){this._storage.set(Y,e),this._useCookieFallback&&this._setCookie(e)}_generateId(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}_getCookie(){if(typeof document>"u")return null;try{let e=document.cookie.split(";");for(let t of e){let[n,i]=t.trim().split("=");if(n===this._cookieName&&i)return decodeURIComponent(i)}}catch{}return null}_setCookie(e){if(!(typeof document>"u"))try{document.cookie=`${this._cookieName}=${encodeURIComponent(e)}; max-age=31536000; path=/; SameSite=Lax`}catch{}}_deleteCookie(){if(!(typeof document>"u"))try{document.cookie=`${this._cookieName}=; max-age=0; path=/`}catch{}}};var Q="traffical:",Be=class{constructor(){this._available=this._checkAvailability()}get(e){if(!this._available)return null;try{let t=localStorage.getItem(Q+e);if(!t)return null;let n=JSON.parse(t);return n.expiresAt&&Date.now()>n.expiresAt?(this.remove(e),null):n.value}catch{return null}}set(e,t,n){if(this._available)try{let i={value:t,...n&&{expiresAt:Date.now()+n}};localStorage.setItem(Q+e,JSON.stringify(i))}catch{}}remove(e){if(this._available)try{localStorage.removeItem(Q+e)}catch{}}clear(){if(this._available)try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n?.startsWith(Q)&&e.push(n)}e.forEach(t=>localStorage.removeItem(t))}catch{}}_checkAvailability(){try{let e=Q+"__test__";return localStorage.setItem(e,"test"),localStorage.removeItem(e),!0}catch{return!1}}},Ne=class{constructor(){this._store=new Map}get(e){let t=this._store.get(e);return t?t.expiresAt&&Date.now()>t.expiresAt?(this.remove(e),null):t.value:null}set(e,t,n){this._store.set(e,{value:t,...n&&{expiresAt:Date.now()+n}})}remove(e){this._store.delete(e)}clear(){this._store.clear()}};function st(){let r=new Be;return r.get("__check__")!==null||dn()?r:new Ne}function dn(){try{let r="__traffical_storage_test__";return localStorage.setItem(r,"test"),localStorage.removeItem(r),!0}catch{return!1}}var L="0.19.0";var fn="js-client";function Ue(r,e){let t=new M({ttlMs:r.deduplicationTtlMs});return{name:"decision-tracking",onDecision(n){if(r.disabled)return;let i=n.metadata.unitKeyValue;if(!i)return;let o=M.hashAssignments(n.assignments);if(!t.checkAndMark(i,o))return;let s={type:"decision",id:n.decisionId,orgId:e.orgId,projectId:e.projectId,env:e.env,unitKey:i,timestamp:n.metadata.timestamp,assignments:n.assignments,layers:n.metadata.layers,context:n.metadata.filteredContext,configVersion:n.metadata.configVersion??e.getConfigVersion?.()??void 0,sdkName:fn,sdkVersion:L};e.log(s)},onDestroy(){t.clear()}}}var gn="traffical_rdr";function hn(r,e,t){if(!(typeof document>"u"))try{document.cookie=`${r}=${encodeURIComponent(e)}; max-age=${t}; path=/; SameSite=Lax`}catch{}}function $e(r={}){let e=r.parameterKey??"redirect.url",t=r.compareMode??"pathname",n=r.cookieName??gn;return{name:"redirect",onInitialize(i){typeof window>"u"||i.decide({context:{},defaults:{[e]:""}})},onBeforeDecision(i){return typeof window>"u"?i:{"url.pathname":window.location.pathname,...i}},onDecision(i){let o=i.assignments[e];if(typeof o!="string"||!o)return;let s=t==="href"?window.location.href:window.location.pathname;if(o===s)return;let a=i.metadata.layers.find(c=>c.policyId&&c.allocationName);a&&hn(n,JSON.stringify({l:a.layerId,p:a.policyId,a:a.allocationName,ts:Date.now()}),86400),window.location.replace(o)}}}var pn="traffical_rdr";function mn(r){if(typeof document>"u")return null;try{for(let e of document.cookie.split(";")){let[t,n]=e.trim().split("=");if(t===r&&n)return decodeURIComponent(n)}}catch{}return null}function yn(r,e){let t=mn(r);if(!t)return null;try{let n=JSON.parse(t);return Date.now()-n.ts>e?null:{layerId:n.l,policyId:n.p,allocationName:n.a}}catch{return null}}function Ve(r={}){let e=r.cookieName??pn,t=r.expiryMs??864e5;function n(i){let o=yn(e,t);if(!o)return;i.attribution=i.attribution??[],i.attribution.some(a=>a.layerId===o.layerId&&a.policyId===o.policyId)||i.attribution.push(o)}return{name:"redirect-attribution",onTrack(i){return n(i),!0},onExposure(i){return n(i),!0}}}var Z=["$browser","$os","$device_type","$url","$host","$path","$query","$referrer","$page_title","$utm_source","$utm_medium","$utm_campaign","$utm_term","$utm_content","$locale","$timezone"],at="traffical:utm",ct=["$utm_source","$utm_medium","$utm_campaign","$utm_term","$utm_content"];function _n(r){return/\bEdg(?:e|A|iOS)?\//.test(r)?"edge":/\bOPR\/|\bOpera\b/.test(r)?"other":/\bFirefox\/|\bFxiOS\//.test(r)?"firefox":/\bChrome\/|\bCriOS\/|\bChromium\//.test(r)?"chrome":/\bSafari\//.test(r)&&/\bVersion\/|\bMobile\//.test(r)?"safari":"other"}function bn(r,e=0){return/\b(?:iPhone|iPad|iPod)\b/.test(r)||/\bMacintosh\b/.test(r)&&e>1?"ios":/\bAndroid\b/.test(r)?"android":/\bWindows\b/.test(r)?"windows":/\bMac OS X\b|\bMacintosh\b/.test(r)?"macos":/\bCrOS\b|\bLinux\b|\bX11\b/.test(r)?"linux":"other"}function vn(r,e){if(/\biPad\b/.test(r)||/\bMacintosh\b/.test(r)&&(e.maxTouchPoints??0)>1)return"tablet";if(/\biPhone\b|\biPod\b/.test(r))return"mobile";if(/\bAndroid\b/.test(r))return/\bMobile\b/.test(r)?"mobile":"tablet";if(/\bMobi\b/.test(r))return"mobile";if(e.coarsePointer){if(e.width<768)return"mobile";if(e.width<1024)return"tablet"}return"desktop"}function xn(r){try{let e=r.sessionStorage?.getItem(at);if(!e)return null;let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n={};for(let i of ct){let o=t[i];typeof o=="string"&&o&&(n[i]=o)}return Object.keys(n).length?n:null}catch{return null}}function En(r,e){try{r.sessionStorage?.setItem(at,JSON.stringify(e))}catch{}}function Tn(r){let e={},t;try{t=new URLSearchParams(r)}catch{return e}for(let n of ct){let i=t.get(n.slice(1));i&&(e[n]=i)}return e}function In(r,e){let t=r.navigator,n=r.location,i=r.document,o=t?.userAgent??"",s=typeof t?.maxTouchPoints=="number"?t.maxTouchPoints:0,a=!1;try{a=typeof r.matchMedia=="function"&&r.matchMedia("(pointer: coarse)").matches}catch{}let c=typeof r.innerWidth=="number"&&r.innerWidth>0?r.innerWidth:1024,u=n?.search??"",g=Tn(u);e&&(Object.keys(g).length?En(r,g):g=xn(r)??{});let l=t?.language||void 0,p;try{p=Intl.DateTimeFormat().resolvedOptions().timeZone||void 0}catch{p=void 0}if(l===void 0)try{l=Intl.DateTimeFormat().resolvedOptions().locale||void 0}catch{l=void 0}let d=u.startsWith("?")?u.slice(1):u;return{$browser:_n(o),$os:bn(o,s),$device_type:vn(o,{coarsePointer:a,width:c,maxTouchPoints:s}),$url:n?.href||void 0,$host:n?.host||void 0,$path:n?.pathname||void 0,$query:d||void 0,$referrer:i?.referrer||void 0,$page_title:i?.title||void 0,$utm_source:g.$utm_source,$utm_medium:g.$utm_medium,$utm_campaign:g.$utm_campaign,$utm_term:g.$utm_term,$utm_content:g.$utm_content,$locale:l,$timezone:p}}function _e(r={}){let e=r.persistUtm??!0,t=new Set(r.include?r.include.filter(n=>Z.includes(n)):Z);for(let n of r.exclude??[])t.delete(n);return{name:"auto-attributes",onBeforeDecision(n){if(typeof window>"u")return n;let i;try{i=In(window,e)}catch{return n}let o={};for(let s of t){let a=i[s];a!==void 0&&(o[s]=a)}return{...o,...n}}}}var Ke=_e;var be=[],lt={};function An(){if(typeof window>"u")return{version:1,instances:lt,subscribe:()=>()=>{}};if(!window.__TRAFFICAL_DEBUG__){let r={version:1,instances:lt,subscribe(e){return be.push(e),()=>{be=be.filter(t=>t!==e)}}};window.__TRAFFICAL_DEBUG__=r}return window.__TRAFFICAL_DEBUG__}function ut(r){for(let e of be)try{e(r)}catch{}}var wn=0,Cn=Symbol.for("@openfeature/web-sdk/api");function Sn(){let r=globalThis[Cn];return r&&typeof r.getContext=="function"&&typeof r.setContext=="function"?r:null}function kn(){return`traffical_${Date.now().toString(36)}_${(++wn).toString(36)}`}function Pn(){return`evt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}var Rn="traffical-debug";function Fe(r={}){let e=r.instanceId??kn(),t=r.maxEvents??500,n=null,i=null,o={},s=[],a=null,c=null,u={},g=null,l=null,p=[],d=[],m=[];function x(){return{ready:n?.isInitialized===!0,stableId:n?.getStableId?.()??null,effectiveUnitKey:c,configVersion:n?.getConfigVersion?.()??null,assignments:{...o},layers:[...s],lastDecisionId:a,overrides:n?.getOverrides?.()??{},contextOverrides:{...u},lastContext:g?{...g}:null}}function b(){let f=x();for(let h of d)try{h(f)}catch{}}function I(f,h){let v={id:Pn(),type:f,timestamp:Date.now(),data:h};p.push(v),p.length>t&&p.splice(0,p.length-t);for(let T of m)try{T(v)}catch{}}function w(){if(!n)return;try{n.decide({context:g?{...g}:{},defaults:l?{...l}:{}})}catch{}let f=Sn();if(f)try{f.setContext({...f.getContext()}).catch(()=>{})}catch{}}let E={id:e,meta:{orgId:"",projectId:"",env:"",sdkVersion:L},getState:x,subscribe(f){return d.push(f),()=>{d=d.filter(h=>h!==f)}},getEvents(f){return f!==void 0?p.slice(-f):[...p]},onEvent(f){return m.push(f),()=>{m=m.filter(h=>h!==f)}},getConfigBundle(){return i},setUnitKey(f){n?.identify?n.identify(f):n?.setStableId&&n.setStableId(f),b()},setOverride(f,h){n?.applyOverrides&&n.applyOverrides({[f]:h}),b(),w()},clearOverride(f){if(n?.getOverrides&&n?.applyOverrides){let h=n.getOverrides();delete h[f],n.clearOverrides?.(),n.applyOverrides(h)}b(),w()},clearAllOverrides(){n?.clearOverrides?.(),b(),w()},getOverrides(){return n?.getOverrides?.()??{}},setContextOverrides(f){u={...f},b(),w()},getContextOverrides(){return{...u}},reDecide(){w()},async refresh(){n?.refreshConfig&&await n.refreshConfig()}};return{name:Rn,onInitialize(f){n=f,i&&(E.meta.orgId=i.orgId,E.meta.projectId=i.projectId,E.meta.env=i.env);let h=An();h.instances[e]=E,ut({type:"register",instanceId:e}),b()},onConfigUpdate(f){i=f,E.meta.orgId=f.orgId,E.meta.projectId=f.projectId,E.meta.env=f.env,b()},onBeforeDecision(f){if(g={...f},Object.keys(u).length!==0)return{...f,...u}},onDecision(f){l={...f.assignments},o={...f.assignments},s=f.metadata?.layers?[...f.metadata.layers]:[],a=f.decisionId,f.metadata?.unitKeyValue&&(c=f.metadata.unitKeyValue),I("decision",f),b()},onResolve(f){o={...f},b()},onExposure(f){return I("exposure",f),!0},onTrack(f){return I("track",f),!0},onDestroy(){let f=typeof window<"u"?window.__TRAFFICAL_DEBUG__:null;f&&(delete f.instances[e],ut({type:"unregister",instanceId:e})),d=[],m=[],u={},g=null,l=null,n=null}}}var ve=class{constructor(){this._plugins=[]}register(e){let t="plugin"in e?e.plugin:e,n="priority"in e?e.priority??0:0;return this._plugins.some(i=>i.plugin.name===t.name)?(console.warn(`[Traffical] Plugin "${t.name}" already registered, skipping.`),!1):(this._plugins.push({plugin:t,priority:n}),this._plugins.sort((i,o)=>o.priority-i.priority),!0)}unregister(e){let t=this._plugins.findIndex(n=>n.plugin.name===e);return t===-1?!1:(this._plugins.splice(t,1),!0)}get(e){return this._plugins.find(t=>t.plugin.name===e)?.plugin}getAll(){return this._plugins.map(e=>e.plugin)}async runInitialize(e){for(let{plugin:t}of this._plugins)if(t.onInitialize)try{await t.onInitialize(e)}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onInitialize error:`,n)}}runConfigUpdate(e){for(let{plugin:t}of this._plugins)if(t.onConfigUpdate)try{t.onConfigUpdate(e)}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onConfigUpdate error:`,n)}}runBeforeDecision(e){let t=e;for(let{plugin:n}of this._plugins)if(n.onBeforeDecision)try{let i=n.onBeforeDecision(t);i&&(t=i)}catch(i){console.warn(`[Traffical] Plugin "${n.name}" onBeforeDecision error:`,i)}return t}runDecision(e){for(let{plugin:t}of this._plugins)if(t.onDecision)try{t.onDecision(e)}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onDecision error:`,n)}}runResolve(e){for(let{plugin:t}of this._plugins)if(t.onResolve)try{t.onResolve(e)}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onResolve error:`,n)}}runExposure(e){for(let{plugin:t}of this._plugins)if(t.onExposure)try{if(t.onExposure(e)===!1)return!1}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onExposure error:`,n)}return!0}runTrack(e){for(let{plugin:t}of this._plugins)if(t.onTrack)try{if(t.onTrack(e)===!1)return!1}catch(n){console.warn(`[Traffical] Plugin "${t.name}" onTrack error:`,n)}return!0}runDestroy(){for(let{plugin:e}of this._plugins)if(e.onDestroy)try{e.onDestroy()}catch(t){console.warn(`[Traffical] Plugin "${e.name}" onDestroy error:`,t)}}clear(){this._plugins=[]}};function dt(){let r=[],e=!1;function t(s){for(let a of r)a(s)}let n=()=>{e=!0,t("background")},i=()=>{typeof document<"u"&&t(document.visibilityState==="hidden"?"background":"foreground")},o=()=>{e=!0,t("background")};return typeof window<"u"&&(window.addEventListener("pagehide",n),window.addEventListener("beforeunload",o)),typeof document<"u"&&document.addEventListener("visibilitychange",i),{onVisibilityChange(s){r.push(s)},removeVisibilityListener(s){let a=r.indexOf(s);a!==-1&&r.splice(a,1)},isUnloading(){return e}}}var je="js-client";function ft(r,e){if(e!==void 0)return{context:r,defaults:e};let t=r;return{context:t.context,defaults:t.defaults}}var Dn="https://sdk.traffical.io",On=6e4,Ln=1e4,Mn=3e5,Bn=3e5,Nn=100,Un=.1;function $n(r){let e=r*Un;return r+(Math.random()*2-1)*e}var $=class{constructor(e){this._state={bundle:null,etag:null,lastFetchTime:0,lastOfflineWarning:0,lastMalformedWarning:0,refreshTimer:null,isInitialized:!1,serverResponse:null,cachedEdgeResults:null};this._decisionCache=new Map;this._cumulativeAttribution=new Map;this._identityListeners=[];this._overrideListeners=[];this._overrides={};this._lastResolveContextKey=null;this._readyPromise=new Promise(e=>{this._readyResolve=e});let t=e.evaluationMode??"bundle";this._options={orgId:e.orgId,projectId:e.projectId,env:e.env,apiKey:e.apiKey,baseUrl:e.baseUrl??Dn,localConfig:e.localConfig,refreshIntervalMs:e.refreshIntervalMs??On,attributionMode:e.attributionMode??"cumulative",evaluationMode:t},this._requestTimeoutMs=e.configTimeoutMs??e.requestTimeoutMs??Ln;let n={baseUrl:this._options.baseUrl,orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,apiKey:this._options.apiKey,defaultTimeoutMs:e.resolveTimeoutMs??e.requestTimeoutMs};if(this._decisionClient=new G(n),this._errorPolicy=new U({onResolutionError:e.onResolutionError,onError:e.onError??e.errorBoundary?.onError}),this._storage=e.storage??st(),this._lifecycleProvider=e.lifecycleProvider??dt(),!e.onSchemaWarnings)try{typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="development"&&(e.onSchemaWarnings=o=>{for(let s of o)console.warn(`[Traffical] Schema warning for "${s.event}":`,s.violations.map(a=>`${a.path}: ${a.message}`).join(", "))})}catch{}if(this._eventLogger=new me({endpoint:`${this._options.baseUrl}/v1/events/batch`,apiKey:e.apiKey,storage:this._storage,lifecycleProvider:this._lifecycleProvider,batchSize:e.batchSize??e.eventBatchSize,flushIntervalMs:e.flushIntervalMs??e.eventFlushIntervalMs,maxQueueSize:e.eventMaxQueueSize,requestTimeoutMs:e.eventsTimeoutMs??e.requestTimeoutMs,onError:i=>{console.warn("[Traffical] Event logging error:",i.message)},onSchemaWarnings:e.onSchemaWarnings}),this._exposureDedup=new J({storage:this._storage,sessionTtlMs:e.exposureSessionTtlMs}),this._stableId=new ye({storage:this._storage}),this._plugins=new ve,this._assignmentLogger=e.assignmentLogger,this._byoEventLogger=e.eventLogger,this._disableCloudEvents=e.disableCloudEvents??!1,this._assignmentLoggerDedup=e.deduplicateAssignmentLogger!==!1&&e.assignmentLogger?new J({storage:this._storage,sessionTtlMs:e.exposureSessionTtlMs}):null,e.trackDecisions!==!1&&(!this._disableCloudEvents||this._byoEventLogger)&&this._plugins.register({plugin:Ue({deduplicationTtlMs:e.decisionDeduplicationTtlMs},{orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,log:i=>this._dispatchEvent(i),getConfigVersion:()=>this.getConfigVersion()}),priority:100}),e.plugins)for(let i of e.plugins)this._plugins.register(i);if(this._options.localConfig){let i=z(this._options.localConfig);i.ok?(this._state.bundle=this._options.localConfig,this._plugins.runConfigUpdate(this._options.localConfig)):(this._errorPolicy.recordRejectedBundle("localConfig",i.path,i.reason),this._options.localConfig=void 0)}if(typeof window<"u"){let i=window;i.__TRAFFICAL_INSTANCES__??(i.__TRAFFICAL_INSTANCES__=[]),i.__TRAFFICAL_INSTANCES__.push(this)}}async initialize(){await this._errorPolicy.sideEffectAsync("initialize","other",async()=>{this._options.evaluationMode==="server"?await this._fetchServerResolve():await this._fetchConfig(),this._startBackgroundRefresh(),this._state.isInitialized=!0,await this._plugins.runInitialize(this)}),this._readyResolve()}get isInitialized(){return this._state.isInitialized}async waitForReady(){return this._readyPromise}async close(){if(this._state.refreshTimer&&(clearInterval(this._state.refreshTimer),this._state.refreshTimer=null),this._lifecycleProvider.isUnloading()?this._eventLogger.flushBeacon():await this._eventLogger.flush().catch(()=>{}),this._eventLogger.destroy(),this._plugins.runDestroy(),this._identityListeners=[],this._overrideListeners=[],this._overrides={},typeof window<"u"){let t=window.__TRAFFICAL_INSTANCES__;if(t){let n=t.indexOf(this);n!==-1&&t.splice(n,1)}}}destroy(){if(this._state.refreshTimer&&(clearInterval(this._state.refreshTimer),this._state.refreshTimer=null),this._lifecycleProvider.isUnloading()?this._eventLogger.flushBeacon():this._eventLogger.flush().catch(()=>{}),this._eventLogger.destroy(),this._plugins.runDestroy(),this._identityListeners=[],this._overrideListeners=[],this._overrides={},typeof window<"u"){let t=window.__TRAFFICAL_INSTANCES__;if(t){let n=t.indexOf(this);n!==-1&&t.splice(n,1)}}}async refreshConfig(){await this._errorPolicy.sideEffectAsync("refreshConfig","other",async()=>{this._options.evaluationMode==="server"?await this._fetchServerResolve():await this._fetchConfig()})}getConfigVersion(){return this._state.serverResponse?.stateVersion??this._state.bundle?.version??null}getUnitKeyField(){return fe(this._getEffectiveBundle())}getParameterLayerId(e){return ge(this._getEffectiveBundle(),e)}getDiagnostics(){return this._errorPolicy.getDiagnostics()}getParams(e,t){let{context:n,defaults:i}=ft(e,t);return this._errorPolicy.resolve("getParams",()=>{if(this._options.evaluationMode==="server"&&this._state.serverResponse){this._maybeResolveForContext(n);let c={...i};for(let[u,g]of Object.entries(this._state.serverResponse.assignments))u in c&&(c[u]=g);return this._plugins.runResolve(c),this._applyOverridesToResult(c),c}let o=this._getEffectiveBundle(),s=this._enrichContext(n),a=he(o,s,i);return this._plugins.runResolve(a),this._applyOverridesToResult(a),a},()=>({...i}))}decide(e,t){let{context:n,defaults:i}=ft(e,t),o=this._errorPolicy.resolve("decide",()=>{if(this._options.evaluationMode==="server"&&this._state.serverResponse){this._maybeResolveForContext(n);let g=this._state.serverResponse,l={...i};for(let[d,m]of Object.entries(g.assignments))d in l&&(l[d]=m);let p={decisionId:N(),assignments:l,metadata:{...g.metadata,configVersion:g.stateVersion}};return this._cacheDecision(p),this._updateCumulativeAttribution(p),this._plugins.runDecision(p),this._applyOverridesToResult(p.assignments),p.metadata.reason=g.metadata.layers?.some(d=>d.policyId)?"resolved":"default",p}let s=this._getEffectiveBundle(),a=this._enrichContext(n);a=this._plugins.runBeforeDecision(a);let c=this._state.cachedEdgeResults??void 0,u=pe(s,a,i,c);return this._cacheDecision(u),this._updateCumulativeAttribution(u),this._plugins.runDecision(u),this._applyOverridesToResult(u.assignments),u.metadata.reason=s?u.metadata.layers.some(g=>g.policyId)?"resolved":"default":"no-bundle",u},()=>({decisionId:N(),assignments:{...i},metadata:{timestamp:new Date().toISOString(),unitKeyValue:"",layers:[],reason:"error"}}));return this._emitAssignmentLogEntries(o,"decision"),o}trackExposure(e){this._emitAssignmentLogEntries(e,"exposure"),this._errorPolicy.resolve("trackExposure",()=>{let t=e.metadata.unitKeyValue;if(!t)return;let n=e.metadata.configVersion??this.getConfigVersion()??void 0,i=[];for(let s of e.metadata.layers)!s.policyId||!s.allocationName||s.attributionOnly||!this._exposureDedup.checkAndMark(t,s.policyId,s.allocationName)||i.push(s);if(i.length===0)return;let o={type:"exposure",id:De(),decisionId:e.decisionId,orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,unitKey:t,timestamp:new Date().toISOString(),assignments:e.assignments,layers:i,context:e.metadata.filteredContext,configVersion:n,sdkName:je,sdkVersion:L};this._plugins.runExposure(o)&&this._dispatchEvent(o)},()=>{})}track(e,t,n){this._errorPolicy.resolve("track",()=>{let i=n?.unitKey??this._stableId.getId(),o=typeof n?.value=="number"?n.value:typeof t?.value=="number"?t.value:void 0,s=this._buildAttribution(i,n?.decisionId),a=n?.decisionId,c={type:"track",id:Oe(),orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,unitKey:i,timestamp:new Date().toISOString(),event:e,value:o,values:n?.values,properties:t,decisionId:a,attribution:s,eventTimestamp:n?.eventTimestamp,sdkName:je,sdkVersion:L};this._plugins.runTrack(c)&&this._dispatchEvent(c)},()=>{})}async flushEvents(){await this._errorPolicy.sideEffectAsync("flushEvents","other",async()=>{await this._eventLogger.flush()})}use(e){if(!this._plugins.register(e))return this;if(this._state.isInitialized){try{e.onInitialize?.(this)}catch(n){console.warn(`[Traffical] Plugin "${e.name}" late onInitialize error:`,n)}if(this._state.bundle)try{e.onConfigUpdate?.(this._state.bundle)}catch(n){console.warn(`[Traffical] Plugin "${e.name}" late onConfigUpdate error:`,n)}}return this}getPlugin(e){return this._plugins.get(e)}getStableId(){return this._stableId.getId()}setStableId(e){this._stableId.setId(e)}identify(e){this._stableId.setId(e);for(let t of this._identityListeners)try{t(e)}catch{}}onIdentityChange(e){return this._identityListeners.push(e),()=>{this._identityListeners=this._identityListeners.filter(t=>t!==e)}}onOverridesChange(e){return this._overrideListeners.push(e),()=>{this._overrideListeners=this._overrideListeners.filter(t=>t!==e)}}applyOverrides(e){Object.assign(this._overrides,e),this._notifyOverrideListeners()}clearOverrides(){this._overrides={},this._notifyOverrideListeners()}getOverrides(){return{...this._overrides}}_notifyOverrideListeners(){let e={...this._overrides};for(let t of this._overrideListeners)try{t(e)}catch{}}_dispatchEvent(e){if(this._byoEventLogger)try{this._byoEventLogger(e)}catch{}this._disableCloudEvents||this._eventLogger.log(e)}_emitAssignmentLogEntries(e,t){if(!this._assignmentLogger)return;let n=e.metadata.unitKeyValue;if(!n)return;let i=e.metadata.configVersion??this.getConfigVersion()??void 0;for(let o of e.metadata.layers){if(!o.policyId||!o.allocationName||this._assignmentLoggerDedup&&!this._assignmentLoggerDedup.checkAndMark(n,o.policyId,`${o.allocationName}:${t}`))continue;let s=o.policyId,a=o.allocationName;this._errorPolicy.sideEffect("assignmentLogger","assignmentLog",()=>this._assignmentLogger({unitKey:n,policyId:s,policyKey:o.policyKey,allocationName:a,allocationKey:o.allocationKey,timestamp:e.metadata.timestamp,layerId:o.layerId,allocationId:o.allocationId,orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,sdkName:je,sdkVersion:L,properties:e.metadata.filteredContext,type:t,decisionId:e.decisionId,anonymousId:this._stableId.getId(),id:Le(),bucket:o.bucket>=0?o.bucket:void 0,probability:o.probability,modelVersion:o.modelVersion,configVersion:i}))}}_applyOverridesToResult(e){let t=Object.keys(this._overrides);if(t.length!==0)for(let n of t)n in e&&(e[n]=this._overrides[n])}_getEffectiveBundle(){return this._state.bundle??this._options.localConfig??null}_enrichContext(e){let n=this._getEffectiveBundle()?.hashing?.unitKey??"userId";return e[n]?e:{...e,[n]:this._stableId.getId()}}async _fetchConfig(){let e=`${this._options.baseUrl}/v1/config/${encodeURIComponent(this._options.projectId)}?env=${encodeURIComponent(this._options.env)}`,t={"Content-Type":"application/json",Authorization:`Bearer ${this._options.apiKey}`};this._state.etag&&(t["If-None-Match"]=this._state.etag);let n=new AbortController,i=setTimeout(()=>n.abort(),this._requestTimeoutMs);try{let o=await fetch(e,{method:"GET",headers:t,signal:n.signal});if(o.status===304){this._state.lastFetchTime=Date.now();return}if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);let s=await o.json(),a=o.headers.get("ETag"),c=z(s);if(!c.ok){this._errorPolicy.recordRejectedBundle("fetchConfig",c.path,c.reason),this._logMalformedBundleWarning();return}if(this._state.bundle=s,this._state.etag=a,this._state.lastFetchTime=Date.now(),this._findEdgePolicies(s).length>0){let u=await this._prefetchEdgeResults(s,this._enrichContext({}));this._state.cachedEdgeResults=u}else this._state.cachedEdgeResults=null;this._plugins.runConfigUpdate(s)}catch(o){this._logOfflineWarning(o)}finally{clearTimeout(i)}}_startBackgroundRefresh(){let e=this._options.evaluationMode==="server"?this._state.serverResponse?.suggestedRefreshMs??this._options.refreshIntervalMs:this._options.refreshIntervalMs;if(e<=0)return;let t=()=>{this._state.refreshTimer=setTimeout(()=>{t(),this._options.evaluationMode==="server"?this._fetchServerResolve().catch(()=>{}):this._fetchConfig().catch(()=>{})},$n(e))};t()}_maybeResolveForContext(e){let t=this._enrichContext(e),n;try{n=JSON.stringify(t)}catch{n=""}n!==this._lastResolveContextKey&&(this._lastResolveContextKey=n,this._fetchServerResolve(t))}async _fetchServerResolve(e){if(this._decisionClient)try{let t=e??this._enrichContext({}),n=await this._decisionClient.resolve({context:t});n&&(this._state.serverResponse=n,this._state.lastFetchTime=Date.now())}catch(t){this._logOfflineWarning(t)}}_findEdgePolicies(e){let t=[];for(let n of e.layers)for(let i of n.policies)i.state==="running"&&i.entityConfig?.resolutionMode==="edge"&&t.push(i);return t}async _prefetchEdgeResults(e,t){if(!this._decisionClient)return{};let n=this._findEdgePolicies(e);if(n.length===0)return{};let i=W(e,t);if(!i)return{};let o=n.map(s=>{if(!s.entityConfig)return null;let a=s.entityConfig.dynamicAllocations?typeof t[s.entityConfig.dynamicAllocations.countKey]=="number"?Math.floor(t[s.entityConfig.dynamicAllocations.countKey]):0:s.allocations.length;return Me(s.id,s.entityConfig.entityKeys,t,i,a||void 0)}).filter(s=>s!==null);if(o.length===0)return{};try{let s=await this._decisionClient.decideEntityBatch(o),a=new Map;for(let c=0;c<o.length;c++){let u=s[c];u&&a.set(o[c].policyId,{allocationIndex:u.allocationIndex,entityId:o[c].entityId})}return a.size>0?{edgeResults:a}:{}}catch{return{}}}_logOfflineWarning(e){let t=Date.now();t-this._state.lastOfflineWarning>Mn&&(console.warn(`[Traffical] Failed to fetch config: ${e instanceof Error?e.message:String(e)}. Using ${this._state.bundle?"cached":"local"} config.`),this._state.lastOfflineWarning=t)}_logMalformedBundleWarning(){let e=Date.now();e-this._state.lastMalformedWarning>Bn&&(console.warn(`[Traffical] Discarded malformed config bundle (invalid hashing/shape). Using ${this._state.bundle?"cached":"local"} config.`),this._state.lastMalformedWarning=e)}_cacheDecision(e){if(this._decisionCache.size>=Nn){let t=this._decisionCache.keys().next().value;t&&this._decisionCache.delete(t)}this._decisionCache.set(e.decisionId,e)}_updateCumulativeAttribution(e){let t=e.metadata.unitKeyValue;if(!t)return;let n=this._cumulativeAttribution.get(t);n||(n=new Map,this._cumulativeAttribution.set(t,n));for(let i of e.metadata.layers){if(!i.policyId||!i.allocationName)continue;let o=`${i.layerId}:${i.policyId}`;n.set(o,{layerId:i.layerId,policyId:i.policyId,allocationName:i.allocationName})}}_buildAttribution(e,t){if(this._options.attributionMode==="decision"){if(!t)return;let i=this._decisionCache.get(t);return i?i.metadata.layers.filter(o=>o.policyId&&o.allocationName).map(o=>({layerId:o.layerId,policyId:o.policyId,allocationName:o.allocationName})):void 0}let n=this._cumulativeAttribution.get(e);return n&&n.size>0?Array.from(n.values()):void 0}};async function gt(r){let e=new $(r);return await e.initialize(),e}function ht(r){return new $(r)}function pt(r={}){let e={observeMutations:r.observeMutations??!0,debounceMs:r.debounceMs??100},t=[],n={},i=null,o=null;function s(d,m){try{return new RegExp(d).test(m)}catch{return m===d}}function a(d,m,x){if(m==="innerHTML")d.innerHTML=x;else if(m==="textContent")d.textContent=x;else if(m==="src"&&"src"in d)d.src=x;else if(m==="href"&&"href"in d)d.href=x;else if(m.startsWith("style.")){let b=m.slice(6);d.style[b]=x}else d.setAttribute(m,x)}function c(d,m){let x=String(m);try{let b=document.querySelectorAll(d.selector);for(let I of b)a(I,d.property,x)}catch(b){console.warn(`[Traffical DOM Binding] Failed to apply binding for ${d.parameterKey}:`,b)}}function u(d,m=!1){n=d;let x=typeof window<"u"?window.location.pathname:"";for(let b of t){if(!m&&!s(b.urlPattern,x))continue;let I=d[b.parameterKey];I!==void 0&&c(b,I)}}function g(){o&&clearTimeout(o),o=setTimeout(()=>{u(n)},e.debounceMs)}function l(){i||typeof MutationObserver>"u"||typeof document>"u"||(i=new MutationObserver(()=>{g()}),i.observe(document.body,{childList:!0,subtree:!0}))}function p(){i&&(i.disconnect(),i=null),o&&(clearTimeout(o),o=null)}return{name:"dom-binding",onInitialize(){e.observeMutations&&l()},onConfigUpdate(d){t=d.domBindings??[]},onResolve(d){u(d)},onDecision(d){u(d.assignments)},onDestroy(){p(),t=[],n={}},applyBindings(d){u(d||n)},getBindings(){return t}}}var A=null;async function Vn(r){return A?(console.warn("[Traffical] Client already initialized. Returning existing instance."),A):(A=await gt(r),A)}function Kn(r){return A?(console.warn("[Traffical] Client already initialized. Returning existing instance."),A):(A=ht(r),A.initialize().catch(e=>{console.warn("[Traffical] Initialization error:",e)}),A)}function Fn(){return A}function jn(){A&&(A.destroy(),A=null)}return Tt(Hn);})();
3
3
  //# sourceMappingURL=traffical.min.js.map