@traffical/js-client 0.2.7 → 0.4.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.
- package/dist/client.d.ts +21 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +164 -12
- package/dist/client.js.map +1 -1
- package/dist/event-logger.d.ts +5 -3
- package/dist/event-logger.d.ts.map +1 -1
- package/dist/event-logger.js +20 -24
- package/dist/event-logger.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/lifecycle.d.ts +10 -0
- package/dist/lifecycle.d.ts.map +1 -0
- package/dist/lifecycle.js +42 -0
- package/dist/lifecycle.js.map +1 -0
- package/dist/traffical.min.js +2 -2
- package/dist/traffical.min.js.map +4 -4
- package/package.json +3 -2
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
export function createBrowserLifecycleProvider() {
|
|
2
|
+
const listeners = [];
|
|
3
|
+
let unloading = false;
|
|
4
|
+
function notify(state) {
|
|
5
|
+
for (const cb of listeners)
|
|
6
|
+
cb(state);
|
|
7
|
+
}
|
|
8
|
+
const onPageHide = () => {
|
|
9
|
+
unloading = true;
|
|
10
|
+
notify("background");
|
|
11
|
+
};
|
|
12
|
+
const onVisibilityChange = () => {
|
|
13
|
+
if (typeof document !== "undefined") {
|
|
14
|
+
notify(document.visibilityState === "hidden" ? "background" : "foreground");
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
const onBeforeUnload = () => {
|
|
18
|
+
unloading = true;
|
|
19
|
+
notify("background");
|
|
20
|
+
};
|
|
21
|
+
if (typeof window !== "undefined") {
|
|
22
|
+
window.addEventListener("pagehide", onPageHide);
|
|
23
|
+
window.addEventListener("beforeunload", onBeforeUnload);
|
|
24
|
+
}
|
|
25
|
+
if (typeof document !== "undefined") {
|
|
26
|
+
document.addEventListener("visibilitychange", onVisibilityChange);
|
|
27
|
+
}
|
|
28
|
+
return {
|
|
29
|
+
onVisibilityChange(callback) {
|
|
30
|
+
listeners.push(callback);
|
|
31
|
+
},
|
|
32
|
+
removeVisibilityListener(callback) {
|
|
33
|
+
const idx = listeners.indexOf(callback);
|
|
34
|
+
if (idx !== -1)
|
|
35
|
+
listeners.splice(idx, 1);
|
|
36
|
+
},
|
|
37
|
+
isUnloading() {
|
|
38
|
+
return unloading;
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=lifecycle.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lifecycle.js","sourceRoot":"","sources":["../src/lifecycle.ts"],"names":[],"mappings":"AAUA,MAAM,UAAU,8BAA8B;IAC5C,MAAM,SAAS,GAAyB,EAAE,CAAC;IAC3C,IAAI,SAAS,GAAG,KAAK,CAAC;IAEtB,SAAS,MAAM,CAAC,KAAsB;QACpC,KAAK,MAAM,EAAE,IAAI,SAAS;YAAE,EAAE,CAAC,KAAK,CAAC,CAAC;IACxC,CAAC;IAED,MAAM,UAAU,GAAG,GAAS,EAAE;QAC5B,SAAS,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,YAAY,CAAC,CAAC;IACvB,CAAC,CAAC;IAEF,MAAM,kBAAkB,GAAG,GAAS,EAAE;QACpC,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE,CAAC;YACpC,MAAM,CAAC,QAAQ,CAAC,eAAe,KAAK,QAAQ,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;QAC9E,CAAC;IACH,CAAC,CAAC;IAEF,MAAM,cAAc,GAAG,GAAS,EAAE;QAChC,SAAS,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,YAAY,CAAC,CAAC;IACvB,CAAC,CAAC;IAEF,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAClC,MAAM,CAAC,gBAAgB,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;QAChD,MAAM,CAAC,gBAAgB,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;IAC1D,CAAC;IACD,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE,CAAC;QACpC,QAAQ,CAAC,gBAAgB,CAAC,kBAAkB,EAAE,kBAAkB,CAAC,CAAC;IACpE,CAAC;IAED,OAAO;QACL,kBAAkB,CAAC,QAA4B;YAC7C,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC3B,CAAC;QACD,wBAAwB,CAAC,QAA4B;YACnD,MAAM,GAAG,GAAG,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;YACxC,IAAI,GAAG,KAAK,CAAC,CAAC;gBAAE,SAAS,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;QAC3C,CAAC;QACD,WAAW;YACT,OAAO,SAAS,CAAC;QACnB,CAAC;KACF,CAAC;AACJ,CAAC"}
|
package/dist/traffical.min.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
/* @traffical/js-client v0.
|
|
2
|
-
"use strict";var Traffical=(()=>{var D=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var ge=Object.prototype.hasOwnProperty;var pe=(i,e,t)=>e in i?D(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var he=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),_e=(i,e)=>{for(var t in e)D(i,t,{get:e[t],enumerable:!0})},me=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of fe(e))!ge.call(i,r)&&r!==t&&D(i,r,{get:()=>e[r],enumerable:!(n=de(e,r))||n.enumerable});return i};var ye=i=>me(D({},"__esModule",{value:!0}),i);var E=(i,e,t)=>(pe(i,typeof e!="symbol"?e+"":e,t),t);var ee=he(()=>{});var ft={};_e(ft,{TrafficalClient:()=>x,createDOMBindingPlugin:()=>ue,destroy:()=>dt,init:()=>lt,initSync:()=>ct,instance:()=>ut});function I(i){let e=2166136261;for(let t=0;t<i.length;t++)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function A(i,e,t){let n=`${i}:${e}`;return I(n)%t}function z(i,e){return i>=e[0]&&i<=e[1]}function P(i,e){for(let t of e)if(z(i,t.bucketRange))return t;return null}function W(i,e){let{field:t,op:n,value:r,values:o}=i,s=Ee(e,t);switch(n){case"eq":return s===r;case"neq":return s!==r;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>r;case"gte":return typeof s=="number"&&s>=r;case"lt":return typeof s=="number"&&s<r;case"lte":return typeof s=="number"&&s<=r;case"contains":return typeof s=="string"&&typeof r=="string"&&s.includes(r);case"startsWith":return typeof s=="string"&&typeof r=="string"&&s.startsWith(r);case"endsWith":return typeof s=="string"&&typeof r=="string"&&s.endsWith(r);case"regex":if(typeof s!="string"||typeof r!="string")return!1;try{return new RegExp(r).test(s)}catch{return!1}case"exists":return s!=null;case"notExists":return s==null;default:return!1}}function M(i,e){return i.length===0?!0:i.every(t=>W(t,e))}function Ee(i,e){let t=e.split("."),n=i;for(let r of t){if(n==null)return;if(typeof n=="object")n=n[r];else return}return n}var Ie=i=>crypto.getRandomValues(new Uint8Array(i)),xe=(i,e,t)=>{let n=(2<<Math.log2(i.length-1))-1,r=-~(1.6*n*e/i.length);return(o=e)=>{let s="";for(;;){let d=t(r),h=r|0;for(;h--;)if(s+=i[d[h]&n]||"",s.length>=o)return s}}},Q=(i,e=21)=>xe(i,e|0,Ie);function O(i){let e=new Error(i);return e.source="ulid",e}var H="0123456789ABCDEFGHJKMNPQRSTVWXYZ",b=H.length,te=Math.pow(2,48)-1,be=10,ke=16;function Se(i){let e=Math.floor(i()*b);return e===b&&(e=b-1),H.charAt(e)}function we(i,e){if(isNaN(i))throw new Error(i+" must be a number");if(i>te)throw O("cannot encode time greater than "+te);if(i<0)throw O("time must be positive");if(Number.isInteger(Number(i))===!1)throw O("time must be an integer");let t,n="";for(;e>0;e--)t=i%b,n=H.charAt(t)+n,i=(i-t)/b;return n}function Ce(i,e){let t="";for(;i>0;i--)t=Se(e)+t;return t}function De(i=!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=ee();return()=>n.randomBytes(1).readUInt8()/255}catch{}if(i){try{console.error("secure crypto unusable, falling back to insecure Math.random()!")}catch{}return()=>Math.random()}throw O("secure crypto unusable, insecure Math.random not allowed")}function Ae(i){return i||(i=De()),function(t){return isNaN(t)&&(t=Date.now()),we(t,be)+Ce(ke,i)}}var ne=Ae();var Pe="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Me=8,wt=Q(Pe,Me);function B(i){return`${i}_${ne()}`}function k(){return B("dec")}function q(){return B("exp")}function X(){return B("trk")}function Oe(i,e){let t=new Set;for(let r of e)if(r.contextLogging?.allowedFields)for(let o of r.contextLogging.allowedFields)t.add(o);if(t.size===0)return;let n={};for(let r of t)r in i&&(n[r]=i[r]);return Object.keys(n).length>0?n:void 0}function Be(i,e){let t=[];for(let n of i){let r=e[n];if(r==null)return null;t.push(String(r))}return t.join("_")}function Re(i,e){if(i.length===0||i.length===1)return 0;let n=I(e)%1e4/1e4,r=0;for(let o=0;o<i.length;o++)if(r+=i[o],n<r)return o;return i.length-1}function re(i){if(i<=0)return[];let e=1/i;return Array(i).fill(e)}function Ne(i,e,t,n){let r=i.entityState?.[e];if(!r)return re(n);let o=r.entities[t];if(o&&o.weights.length===n)return o.weights;let s=r._global;return s&&s.weights.length===n?s.weights:re(n)}function Ke(i,e,t,n){let r=e.entityConfig;if(!r)return null;let o=Be(r.entityKeys,t);if(!o)return null;let s,d;if(r.dynamicAllocations){let m=r.dynamicAllocations.countKey,y=t[m];if(typeof y!="number"||y<=0)return null;d=Math.floor(y),s=Array.from({length:d},(a,c)=>({id:`${e.id}_dynamic_${c}`,name:String(c),bucketRange:[0,0],overrides:{}}))}else s=e.allocations,d=s.length;if(d===0)return null;let h=Ne(i,e.id,o,d),_=`${o}:${n}:${e.id}`,u=Re(h,_);return{allocation:s[u],entityId:o}}function G(i,e){let t=e[i.hashing.unitKey];return t==null?null:String(t)}function ie(i,e,t){let n={...t},r=[],o=[];if(!i)return{assignments:n,unitKeyValue:"",layers:r,matchedPolicies:o};let s=G(i,e);if(!s)return{assignments:n,unitKeyValue:"",layers:r,matchedPolicies:o};let d=new Set(Object.keys(t)),h=i.parameters.filter(u=>d.has(u.key));for(let u of h)u.key in n&&(n[u.key]=u.default);let _=new Map;for(let u of h){let m=_.get(u.layerId)||[];m.push(u),_.set(u.layerId,m)}for(let u of i.layers){let m=_.get(u.id),y=m&&m.length>0,a=A(s,u.id,i.hashing.bucketCount),c,f;for(let l of u.policies)if(l.state==="running"){if(l.eligibleBucketRange){let{start:g,end:v}=l.eligibleBucketRange;if(a<g||a>v)continue}if(M(l.conditions,e))if(l.entityConfig&&l.entityConfig.resolutionMode==="bundle"){let g=Ke(i,l,e,s);if(g){if(c=l,f=g.allocation,o.push(l),y&&!l.entityConfig.dynamicAllocations)for(let[v,j]of Object.entries(g.allocation.overrides))v in n&&(n[v]=j);break}}else{if(l.entityConfig&&l.entityConfig.resolutionMode==="edge")continue;{let g=P(a,l.allocations);if(g){if(c=l,f=g,o.push(l),y)for(let[v,j]of Object.entries(g.overrides))v in n&&(n[v]=j);break}}}}r.push({layerId:u.id,bucket:a,policyId:c?.id,allocationId:f?.id,allocationName:f?.name,...y?{}:{attributionOnly:!0}})}return{assignments:n,unitKeyValue:s,layers:r,matchedPolicies:o}}function R(i,e,t){return ie(i,e,t).assignments}function N(i,e,t){let{assignments:n,unitKeyValue:r,layers:o,matchedPolicies:s}=ie(i,e,t),d=Oe(e,s);return{decisionId:k(),assignments:n,metadata:{timestamp:new Date().toISOString(),unitKeyValue:r,layers:o,filteredContext:d}}}var T=class i{constructor(e={}){E(this,"_seen",new Map);E(this,"_ttlMs");E(this,"_maxEntries");E(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 r of t){let o=e[r],s=typeof o=="object"?JSON.stringify(o):String(o);n.push(`${r}=${s}`)}return n.join("|")}static createKey(e,t){return`${e}:${t}`}checkAndMark(e,t){let n=i.createKey(e,t),r=Date.now(),o=this._seen.get(n);return o!==void 0&&r-o<this._ttlMs?!1:(this._seen.set(n,r),this._maybeCleanup(r),!0)}wouldBeNew(e,t){let n=i.createKey(e,t),r=Date.now(),o=this._seen.get(n);return o===void 0?!0:r-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,r]of this._seen.entries())e-r>=this._ttlMs&&t.push(n);for(let n of t)this._seen.delete(n);if(this._seen.size>this._maxEntries){let r=Array.from(this._seen.entries()).sort((o,s)=>o[1]-s[1]).slice(0,this._seen.size-this._maxEntries);for(let[o]of r)this._seen.delete(o)}}};var K=class{constructor(e={}){this._seen=new Set;this._lastError=null;this._options=e}capture(e,t,n){try{return t()}catch(r){return this._onError(e,r),n}}async captureAsync(e,t,n){try{return await t()}catch(r){return this._onError(e,r),n}}async swallow(e,t){try{await t()}catch(n){this._onError(e,n)}}getLastError(){let e=this._lastError;return this._lastError=null,e}clearSeen(){this._seen.clear()}_onError(e,t){let n=this._resolveError(t);this._lastError=n;let r=`${e}:${n.name}:${n.message}`;this._seen.has(r)||(this._seen.add(r),console.warn(`[Traffical] Error in ${e}:`,n.message),this._options.onError?.(e,n),this._options.reportErrors&&this._options.errorEndpoint&&this._reportError(e,n).catch(()=>{}))}async _reportError(e,t){if(this._options.errorEndpoint)try{await fetch(this._options.errorEndpoint,{method:"POST",headers:{"Content-Type":"application/json",...this._options.sdkKey&&{"X-Traffical-Key":this._options.sdkKey}},body:JSON.stringify({tag:e,error:t.name,message:t.message,stack:t.stack,timestamp:new Date().toISOString(),sdk:"@traffical/js-client",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})})}catch{}}_resolveError(e){return e instanceof Error?e:typeof e=="string"?new Error(e):new Error("An unknown error occurred")}};var L="failed_events";var F=class{constructor(e){this._queue=[];this._flushTimer=null;this._isFlushing=!1;this._onPageHide=()=>{this.flushBeacon()};this._onVisibilityChange=()=>{document.visibilityState==="hidden"&&this.flushBeacon()};this._onBeforeUnload=()=>{this.flushBeacon()};this._endpoint=e.endpoint,this._apiKey=e.apiKey,this._storage=e.storage,this._batchSize=e.batchSize??10,this._flushIntervalMs=e.flushIntervalMs??3e4,this._onError=e.onError,this._setupListeners(),this._retryFailedEvents(),this._startFlushTimer()}log(e){this._queue.push(e),this._queue.length>=this._batchSize&&this.flush()}async flush(){if(this._isFlushing||this._queue.length===0)return;this._isFlushing=!0;let e=[...this._queue];this._queue=[];try{await this._sendEvents(e)}catch(t){this._persistFailedEvents(e),this._onError?.(t instanceof Error?t:new Error(String(t)))}finally{this._isFlushing=!1}}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=await fetch(this._endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this._apiKey}`},body:JSON.stringify({events:e})});if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`)}_persistFailedEvents(e){let n=[...this._storage.get(L)??[],...e].slice(-100);this._storage.set(L,n)}_retryFailedEvents(){let e=this._storage.get(L);!e||e.length===0||(this._storage.remove(L),this._queue.push(...e))}_startFlushTimer(){this._flushIntervalMs<=0||(this._flushTimer=setInterval(()=>{this.flush().catch(()=>{})},this._flushIntervalMs))}_setupListeners(){typeof window>"u"||(window.addEventListener("pagehide",this._onPageHide),document.addEventListener("visibilitychange",this._onVisibilityChange),window.addEventListener("beforeunload",this._onBeforeUnload))}_removeListeners(){typeof window>"u"||(window.removeEventListener("pagehide",this._onPageHide),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("beforeunload",this._onBeforeUnload))}};var S="exposure_dedup";var $=class i{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 r=i.createKey(e,t,n);return this.shouldTrack(r)}clear(){this._seen.clear(),this._storage.remove(S)}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(S)}_persist(){let e={seen:Array.from(this._seen),sessionStart:this._sessionStart};this._storage.set(S,e,this._sessionTtlMs)}_restore(){let e=this._storage.get(S);if(!e)return;if(Date.now()-e.sessionStart>this._sessionTtlMs){this._storage.remove(S);return}this._seen=new Set(e.seen),this._sessionStart=e.sessionStart}};var w="stable_id",et="traffical_sid";var V=class{constructor(e){this._cachedId=null;this._storage=e.storage,this._useCookieFallback=e.useCookieFallback??!0,this._cookieName=e.cookieName??et}getId(){if(this._cachedId)return this._cachedId;let e=this._storage.get(w);return e?(this._cachedId=e,e):this._useCookieFallback&&(e=this._getCookie(),e)?(this._storage.set(w,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(w),this._useCookieFallback&&this._deleteCookie(),this._cachedId=null}hasId(){return this._storage.get(w)!==null||this._getCookie()!==null}_persist(e){this._storage.set(w,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,r]=t.trim().split("=");if(n===this._cookieName&&r)return decodeURIComponent(r)}}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 C="traffical:",J=class{constructor(){this._available=this._checkAvailability()}get(e){if(!this._available)return null;try{let t=localStorage.getItem(C+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 r={value:t,...n&&{expiresAt:Date.now()+n}};localStorage.setItem(C+e,JSON.stringify(r))}catch{}}remove(e){if(this._available)try{localStorage.removeItem(C+e)}catch{}}clear(){if(this._available)try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n?.startsWith(C)&&e.push(n)}e.forEach(t=>localStorage.removeItem(t))}catch{}}_checkAvailability(){try{let e=C+"__test__";return localStorage.setItem(e,"test"),localStorage.removeItem(e),!0}catch{return!1}}},Y=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 oe(){let i=new J;return i.get("__check__")!==null||tt()?i:new Y}function tt(){try{let i="__traffical_storage_test__";return localStorage.setItem(i,"test"),localStorage.removeItem(i),!0}catch{return!1}}var nt="js-client",rt="0.1.0";function Z(i,e){let t=new T({ttlMs:i.deduplicationTtlMs});return{name:"decision-tracking",onDecision(n){if(i.disabled)return;let r=n.metadata.unitKeyValue;if(!r)return;let o=T.hashAssignments(n.assignments);if(!t.checkAndMark(r,o))return;let s={type:"decision",id:n.decisionId,orgId:e.orgId,projectId:e.projectId,env:e.env,unitKey:r,timestamp:n.metadata.timestamp,assignments:n.assignments,layers:n.metadata.layers,context:n.metadata.filteredContext,sdkName:nt,sdkVersion:rt};e.log(s)},onDestroy(){t.clear()}}}var U=class{constructor(){this._plugins=[]}register(e){let t="plugin"in e?e.plugin:e,n="priority"in e?e.priority??0:0;if(this._plugins.some(r=>r.plugin.name===t.name)){console.warn(`[Traffical] Plugin "${t.name}" already registered, skipping.`);return}this._plugins.push({plugin:t,priority:n}),this._plugins.sort((r,o)=>o.priority-r.priority)}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(){for(let{plugin:e}of this._plugins)if(e.onInitialize)try{await e.onInitialize()}catch(t){console.warn(`[Traffical] Plugin "${e.name}" onInitialize error:`,t)}}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 r=n.onBeforeDecision(t);r&&(t=r)}catch(r){console.warn(`[Traffical] Plugin "${n.name}" onBeforeDecision error:`,r)}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=[]}};var se="js-client",ae="0.1.0",it="https://sdk.traffical.io",ot=6e4,st=3e5,at=100,x=class{constructor(e){this._state={bundle:null,etag:null,lastFetchTime:0,lastOfflineWarning:0,refreshTimer:null,isInitialized:!1};this._decisionCache=new Map;this._cumulativeAttribution=new Map;if(this._options={orgId:e.orgId,projectId:e.projectId,env:e.env,apiKey:e.apiKey,baseUrl:e.baseUrl??it,localConfig:e.localConfig,refreshIntervalMs:e.refreshIntervalMs??ot,attributionMode:e.attributionMode??"cumulative"},this._errorBoundary=new K(e.errorBoundary),this._storage=e.storage??oe(),this._eventLogger=new F({endpoint:`${this._options.baseUrl}/v1/events/batch`,apiKey:e.apiKey,storage:this._storage,batchSize:e.eventBatchSize,flushIntervalMs:e.eventFlushIntervalMs,onError:t=>{console.warn("[Traffical] Event logging error:",t.message)}}),this._exposureDedup=new $({storage:this._storage,sessionTtlMs:e.exposureSessionTtlMs}),this._stableId=new V({storage:this._storage}),this._plugins=new U,e.trackDecisions!==!1&&this._plugins.register({plugin:Z({deduplicationTtlMs:e.decisionDeduplicationTtlMs},{orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,log:t=>this._eventLogger.log(t)}),priority:100}),e.plugins)for(let t of e.plugins)this._plugins.register(t);this._options.localConfig&&(this._state.bundle=this._options.localConfig,this._plugins.runConfigUpdate(this._options.localConfig))}async initialize(){await this._errorBoundary.captureAsync("initialize",async()=>{await this._fetchConfig(),this._startBackgroundRefresh(),this._state.isInitialized=!0,await this._plugins.runInitialize()},void 0)}get isInitialized(){return this._state.isInitialized}destroy(){this._state.refreshTimer&&(clearInterval(this._state.refreshTimer),this._state.refreshTimer=null),this._eventLogger.flushBeacon(),this._eventLogger.destroy(),this._plugins.runDestroy()}async refreshConfig(){await this._errorBoundary.swallow("refreshConfig",async()=>{await this._fetchConfig()})}getConfigVersion(){return this._state.bundle?.version??null}getParams(e){return this._errorBoundary.capture("getParams",()=>{let t=this._getEffectiveBundle(),n=this._enrichContext(e.context),r=R(t,n,e.defaults);return this._plugins.runResolve(r),r},e.defaults)}decide(e){return this._errorBoundary.capture("decide",()=>{let t=this._getEffectiveBundle(),n=this._enrichContext(e.context);n=this._plugins.runBeforeDecision(n);let r=N(t,n,e.defaults);return this._cacheDecision(r),this._updateCumulativeAttribution(r),this._plugins.runDecision(r),r},{decisionId:k(),assignments:e.defaults,metadata:{timestamp:new Date().toISOString(),unitKeyValue:"",layers:[]}})}trackExposure(e){this._errorBoundary.capture("trackExposure",()=>{let t=e.metadata.unitKeyValue;if(t)for(let n of e.metadata.layers){if(!n.policyId||!n.allocationName||n.attributionOnly||!this._exposureDedup.checkAndMark(t,n.policyId,n.allocationName))continue;let o={type:"exposure",id:q(),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:e.metadata.layers,context:e.metadata.filteredContext,sdkName:se,sdkVersion:ae};this._plugins.runExposure(o)&&this._eventLogger.log(o)}},void 0)}track(e,t,n){this._errorBoundary.capture("track",()=>{let r=n?.unitKey??this._stableId.getId(),o=typeof t?.value=="number"?t.value:void 0,s=this._buildAttribution(r,n?.decisionId),d=n?.decisionId,h={type:"track",id:X(),orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,unitKey:r,timestamp:new Date().toISOString(),event:e,value:o,properties:t,decisionId:d,attribution:s,sdkName:se,sdkVersion:ae};this._plugins.runTrack(h)&&this._eventLogger.log(h)},void 0)}async flushEvents(){await this._errorBoundary.swallow("flushEvents",async()=>{await this._eventLogger.flush()})}use(e){return this._plugins.register(e),this}getPlugin(e){return this._plugins.get(e)}getStableId(){return this._stableId.getId()}setStableId(e){this._stableId.setId(e)}_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/${this._options.projectId}?env=${this._options.env}`,t={"Content-Type":"application/json",Authorization:`Bearer ${this._options.apiKey}`};this._state.etag&&(t["If-None-Match"]=this._state.etag);try{let n=await fetch(e,{method:"GET",headers:t});if(n.status===304){this._state.lastFetchTime=Date.now();return}if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);let r=await n.json(),o=n.headers.get("ETag");this._state.bundle=r,this._state.etag=o,this._state.lastFetchTime=Date.now(),this._plugins.runConfigUpdate(r)}catch(n){this._logOfflineWarning(n)}}_startBackgroundRefresh(){this._options.refreshIntervalMs<=0||(this._state.refreshTimer=setInterval(()=>{this._fetchConfig().catch(()=>{})},this._options.refreshIntervalMs))}_logOfflineWarning(e){let t=Date.now();t-this._state.lastOfflineWarning>st&&(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)}_cacheDecision(e){if(this._decisionCache.size>=at){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 r of e.metadata.layers){if(!r.policyId||!r.allocationName)continue;let o=`${r.layerId}:${r.policyId}`;n.set(o,{layerId:r.layerId,policyId:r.policyId,allocationName:r.allocationName})}}_buildAttribution(e,t){if(this._options.attributionMode==="decision"){if(!t)return;let r=this._decisionCache.get(t);return r?r.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 le(i){let e=new x(i);return await e.initialize(),e}function ce(i){return new x(i)}function ue(i={}){let e={observeMutations:i.observeMutations??!0,debounceMs:i.debounceMs??100},t=[],n={},r=null,o=null;function s(a,c){try{return new RegExp(a).test(c)}catch{return c===a}}function d(a,c,f){if(c==="innerHTML")a.innerHTML=f;else if(c==="textContent")a.textContent=f;else if(c==="src"&&"src"in a)a.src=f;else if(c==="href"&&"href"in a)a.href=f;else if(c.startsWith("style.")){let l=c.slice(6);a.style[l]=f}else a.setAttribute(c,f)}function h(a,c){let f=String(c);try{let l=document.querySelectorAll(a.selector);for(let g of l)d(g,a.property,f)}catch(l){console.warn(`[Traffical DOM Binding] Failed to apply binding for ${a.parameterKey}:`,l)}}function _(a,c=!1){n=a;let f=typeof window<"u"?window.location.pathname:"";for(let l of t){if(!c&&!s(l.urlPattern,f))continue;let g=a[l.parameterKey];g!==void 0&&h(l,g)}}function u(){o&&clearTimeout(o),o=setTimeout(()=>{_(n)},e.debounceMs)}function m(){r||typeof MutationObserver>"u"||typeof document>"u"||(r=new MutationObserver(()=>{u()}),r.observe(document.body,{childList:!0,subtree:!0}))}function y(){r&&(r.disconnect(),r=null),o&&(clearTimeout(o),o=null)}return{name:"dom-binding",onInitialize(){e.observeMutations&&m()},onConfigUpdate(a){t=a.domBindings??[]},onResolve(a){_(a)},onDecision(a){_(a.assignments)},onDestroy(){y(),t=[],n={}},applyBindings(a){_(a||n)},getBindings(){return t}}}var p=null;async function lt(i){return p?(console.warn("[Traffical] Client already initialized. Returning existing instance."),p):(p=await le(i),p)}function ct(i){return p?(console.warn("[Traffical] Client already initialized. Returning existing instance."),p):(p=ce(i),p.initialize().catch(e=>{console.warn("[Traffical] Initialization error:",e)}),p)}function ut(){return p}function dt(){p&&(p.destroy(),p=null)}return ye(ft);})();
|
|
1
|
+
/* @traffical/js-client v0.4.0 */
|
|
2
|
+
"use strict";var Traffical=(()=>{var R=Object.defineProperty;var pe=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var ye=Object.prototype.hasOwnProperty;var ve=(r,e,t)=>e in r?R(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var me=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),be=(r,e)=>{for(var t in e)R(r,t,{get:e[t],enumerable:!0})},Te=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of _e(e))!ye.call(r,i)&&i!==t&&R(r,i,{get:()=>e[i],enumerable:!(n=pe(e,i))||n.enumerable});return r};var Ie=r=>Te(R({},"__esModule",{value:!0}),r);var T=(r,e,t)=>(ve(r,typeof e!="symbol"?e+"":e,t),t);var ie=me(()=>{});var ht={};be(ht,{TrafficalClient:()=>x,createDOMBindingPlugin:()=>he,destroy:()=>gt,init:()=>ut,initSync:()=>dt,instance:()=>ft});function E(r){let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function O(r,e,t){let n=`${r}:${e}`;return E(n)%t}function q(r,e){return r>=e[0]&&r<=e[1]}function B(r,e){for(let t of e)if(q(r,t.bucketRange))return t;return null}function X(r,e){let{field:t,op:n,value:i,values:o}=r,s=ke(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 N(r,e){return r.length===0?!0:r.every(t=>X(t,e))}function ke(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}var Ce=r=>crypto.getRandomValues(new Uint8Array(r)),Se=(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}}},ne=(r,e=21)=>Se(r,e|0,Ce);function L(r){let e=new Error(r);return e.source="ulid",e}var G="0123456789ABCDEFGHJKMNPQRSTVWXYZ",C=G.length,re=Math.pow(2,48)-1,we=10,Pe=16;function De(r){let e=Math.floor(r()*C);return e===C&&(e=C-1),G.charAt(e)}function Me(r,e){if(isNaN(r))throw new Error(r+" must be a number");if(r>re)throw L("cannot encode time greater than "+re);if(r<0)throw L("time must be positive");if(Number.isInteger(Number(r))===!1)throw L("time must be an integer");let t,n="";for(;e>0;e--)t=r%C,n=G.charAt(t)+n,r=(r-t)/C;return n}function Ae(r,e){let t="";for(;r>0;r--)t=De(e)+t;return t}function Re(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=ie();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 L("secure crypto unusable, insecure Math.random not allowed")}function Oe(r){return r||(r=Re()),function(t){return isNaN(t)&&(t=Date.now()),Me(t,we)+Ae(Pe,r)}}var oe=Oe();var Be="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ne=8,Pt=ne(Be,Ne);function K(r){return`${r}_${oe()}`}function S(){return K("dec")}function J(){return K("exp")}function Y(){return K("trk")}function Le(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 Ke(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 Ve(r,e){if(r.length===0||r.length===1)return 0;let n=E(e)%1e4/1e4,i=0;for(let o=0;o<r.length;o++)if(i+=r[o],n<i)return o;return r.length-1}function se(r){if(r<=0)return[];let e=1/r;return Array(r).fill(e)}function $e(r,e,t,n){let i=r.entityState?.[e];if(!i)return se(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:se(n)}function Fe(r,e,t,n){let i=e.entityConfig;if(!i)return null;let o=Ke(i.entityKeys,t);if(!o)return null;let s,a;if(i.dynamicAllocations){let f=i.dynamicAllocations.countKey,v=t[f];if(typeof v!="number"||v<=0)return null;a=Math.floor(v),s=Array.from({length:a},(l,d)=>({id:`${e.id}_dynamic_${d}`,name:String(d),bucketRange:[0,0],overrides:{}}))}else s=e.allocations,a=s.length;if(a===0)return null;let c=$e(r,e.id,o,a),h=`${o}:${n}:${e.id}`,b=Ve(c,h);return{allocation:s[b],entityId:o}}function w(r,e){let t=e[r.hashing.unitKey];return t==null?null:String(t)}function ae(r,e,t,n){let i={...t},o=[],s=[];if(!r)return{assignments:i,unitKeyValue:"",layers:o,matchedPolicies:s};let a=w(r,e);if(!a)return{assignments:i,unitKeyValue:"",layers:o,matchedPolicies:s};let c=new Set(Object.keys(t)),h=r.parameters.filter(f=>c.has(f.key));for(let f of h)f.key in i&&(i[f.key]=f.default);let b=new Map;for(let f of h){let v=b.get(f.layerId)||[];v.push(f),b.set(f.layerId,v)}for(let f of r.layers){let v=b.get(f.id),l=v&&v.length>0,d=O(a,f.id,r.hashing.bucketCount),p,g;for(let u of f.policies)if(u.state==="running"){if(u.eligibleBucketRange){let{start:_,end:m}=u.eligibleBucketRange;if(d<_||d>m)continue}if(N(u.conditions,e))if(u.entityConfig&&u.entityConfig.resolutionMode==="bundle"){let _=Fe(r,u,e,a);if(_){if(p=u,g=_.allocation,s.push(u),l&&!u.entityConfig.dynamicAllocations)for(let[m,k]of Object.entries(_.allocation.overrides))m in i&&(i[m]=k);break}}else if(u.entityConfig&&u.entityConfig.resolutionMode==="edge"){let _=n?.edgeResults?.get(u.id);if(_){if(p=u,s.push(u),u.entityConfig.dynamicAllocations)g={id:`${u.id}_dynamic_${_.allocationIndex}`,name:String(_.allocationIndex),bucketRange:[0,0],overrides:{}};else if(u.allocations[_.allocationIndex]&&(g=u.allocations[_.allocationIndex],l&&g))for(let[m,k]of Object.entries(g.overrides))m in i&&(i[m]=k);break}continue}else{let _=B(d,u.allocations);if(_){if(p=u,g=_,s.push(u),l)for(let[m,k]of Object.entries(_.overrides))m in i&&(i[m]=k);break}}}o.push({layerId:f.id,bucket:d,policyId:p?.id,allocationId:g?.id,allocationName:g?.name,...l?{}:{attributionOnly:!0}})}return{assignments:i,unitKeyValue:a,layers:o,matchedPolicies:s}}function V(r,e,t,n){return ae(r,e,t,n).assignments}function $(r,e,t,n){let{assignments:i,unitKeyValue:o,layers:s,matchedPolicies:a}=ae(r,e,t,n),c=Le(e,a);return{decisionId:S(),assignments:i,metadata:{timestamp:new Date().toISOString(),unitKeyValue:o,layers:s,filteredContext:c}}}var I=class r{constructor(e={}){T(this,"_seen",new Map);T(this,"_ttlMs");T(this,"_maxEntries");T(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 P=class{constructor(e){T(this,"config");T(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 Z(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 F=class{constructor(e={}){this._seen=new Set;this._lastError=null;this._options=e}capture(e,t,n){try{return t()}catch(i){return this._onError(e,i),n}}async captureAsync(e,t,n){try{return await t()}catch(i){return this._onError(e,i),n}}async swallow(e,t){try{await t()}catch(n){this._onError(e,n)}}getLastError(){let e=this._lastError;return this._lastError=null,e}clearSeen(){this._seen.clear()}_onError(e,t){let n=this._resolveError(t);this._lastError=n;let i=`${e}:${n.name}:${n.message}`;this._seen.has(i)||(this._seen.add(i),console.warn(`[Traffical] Error in ${e}:`,n.message),this._options.onError?.(e,n),this._options.reportErrors&&this._options.errorEndpoint&&this._reportError(e,n).catch(()=>{}))}async _reportError(e,t){if(this._options.errorEndpoint)try{await fetch(this._options.errorEndpoint,{method:"POST",headers:{"Content-Type":"application/json",...this._options.sdkKey&&{"X-Traffical-Key":this._options.sdkKey}},body:JSON.stringify({tag:e,error:t.name,message:t.message,stack:t.stack,timestamp:new Date().toISOString(),sdk:"@traffical/js-client",userAgent:typeof navigator<"u"?navigator.userAgent:void 0})})}catch{}}_resolveError(e){return e instanceof Error?e:typeof e=="string"?new Error(e):new Error("An unknown error occurred")}};var U="failed_events";var j=class{constructor(e){this._queue=[];this._flushTimer=null;this._isFlushing=!1;this._endpoint=e.endpoint,this._apiKey=e.apiKey,this._storage=e.storage,this._batchSize=e.batchSize??10,this._flushIntervalMs=e.flushIntervalMs??3e4,this._onError=e.onError,this._lifecycleProvider=e.lifecycleProvider,this._setupListeners(),this._retryFailedEvents(),this._startFlushTimer()}log(e){this._queue.push(e),this._queue.length>=this._batchSize&&this.flush()}async flush(){if(this._isFlushing||this._queue.length===0)return;this._isFlushing=!0;let e=[...this._queue];this._queue=[];try{await this._sendEvents(e)}catch(t){this._persistFailedEvents(e),this._onError?.(t instanceof Error?t:new Error(String(t)))}finally{this._isFlushing=!1}}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=await fetch(this._endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this._apiKey}`},body:JSON.stringify({events:e})});if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`)}_persistFailedEvents(e){let n=[...this._storage.get(U)??[],...e].slice(-100);this._storage.set(U,n)}_retryFailedEvents(){let e=this._storage.get(U);!e||e.length===0||(this._storage.remove(U),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 D="exposure_dedup";var z=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(D)}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(D)}_persist(){let e={seen:Array.from(this._seen),sessionStart:this._sessionStart};this._storage.set(D,e,this._sessionTtlMs)}_restore(){let e=this._storage.get(D);if(!e)return;if(Date.now()-e.sessionStart>this._sessionTtlMs){this._storage.remove(D);return}this._seen=new Set(e.seen),this._sessionStart=e.sessionStart}};var M="stable_id",nt="traffical_sid";var W=class{constructor(e){this._cachedId=null;this._storage=e.storage,this._useCookieFallback=e.useCookieFallback??!0,this._cookieName=e.cookieName??nt}getId(){if(this._cachedId)return this._cachedId;let e=this._storage.get(M);return e?(this._cachedId=e,e):this._useCookieFallback&&(e=this._getCookie(),e)?(this._storage.set(M,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(M),this._useCookieFallback&&this._deleteCookie(),this._cachedId=null}hasId(){return this._storage.get(M)!==null||this._getCookie()!==null}_persist(e){this._storage.set(M,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 A="traffical:",Q=class{constructor(){this._available=this._checkAvailability()}get(e){if(!this._available)return null;try{let t=localStorage.getItem(A+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(A+e,JSON.stringify(i))}catch{}}remove(e){if(this._available)try{localStorage.removeItem(A+e)}catch{}}clear(){if(this._available)try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n?.startsWith(A)&&e.push(n)}e.forEach(t=>localStorage.removeItem(t))}catch{}}_checkAvailability(){try{let e=A+"__test__";return localStorage.setItem(e,"test"),localStorage.removeItem(e),!0}catch{return!1}}},ee=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 le(){let r=new Q;return r.get("__check__")!==null||it()?r:new ee}function it(){try{let r="__traffical_storage_test__";return localStorage.setItem(r,"test"),localStorage.removeItem(r),!0}catch{return!1}}var rt="js-client",ot="0.1.0";function te(r,e){let t=new I({ttlMs:r.deduplicationTtlMs});return{name:"decision-tracking",onDecision(n){if(r.disabled)return;let i=n.metadata.unitKeyValue;if(!i)return;let o=I.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,sdkName:rt,sdkVersion:ot};e.log(s)},onDestroy(){t.clear()}}}var H=class{constructor(){this._plugins=[]}register(e){let t="plugin"in e?e.plugin:e,n="priority"in e?e.priority??0:0;if(this._plugins.some(i=>i.plugin.name===t.name)){console.warn(`[Traffical] Plugin "${t.name}" already registered, skipping.`);return}this._plugins.push({plugin:t,priority:n}),this._plugins.sort((i,o)=>o.priority-i.priority)}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(){for(let{plugin:e}of this._plugins)if(e.onInitialize)try{await e.onInitialize()}catch(t){console.warn(`[Traffical] Plugin "${e.name}" onInitialize error:`,t)}}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 ce(){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",de="0.1.0",st="https://sdk.traffical.io",at=6e4,lt=3e5,ct=100,x=class{constructor(e){this._state={bundle:null,etag:null,lastFetchTime:0,lastOfflineWarning:0,refreshTimer:null,isInitialized:!1,serverResponse:null,cachedEdgeResults:null};this._decisionCache=new Map;this._cumulativeAttribution=new Map;let t=e.evaluationMode??"bundle";this._options={orgId:e.orgId,projectId:e.projectId,env:e.env,apiKey:e.apiKey,baseUrl:e.baseUrl??st,localConfig:e.localConfig,refreshIntervalMs:e.refreshIntervalMs??at,attributionMode:e.attributionMode??"cumulative",evaluationMode:t};let n={baseUrl:this._options.baseUrl,orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,apiKey:this._options.apiKey};if(this._decisionClient=new P(n),this._errorBoundary=new F(e.errorBoundary),this._storage=e.storage??le(),this._lifecycleProvider=e.lifecycleProvider??ce(),this._eventLogger=new j({endpoint:`${this._options.baseUrl}/v1/events/batch`,apiKey:e.apiKey,storage:this._storage,lifecycleProvider:this._lifecycleProvider,batchSize:e.eventBatchSize,flushIntervalMs:e.eventFlushIntervalMs,onError:i=>{console.warn("[Traffical] Event logging error:",i.message)}}),this._exposureDedup=new z({storage:this._storage,sessionTtlMs:e.exposureSessionTtlMs}),this._stableId=new W({storage:this._storage}),this._plugins=new H,e.trackDecisions!==!1&&this._plugins.register({plugin:te({deduplicationTtlMs:e.decisionDeduplicationTtlMs},{orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,log:i=>this._eventLogger.log(i)}),priority:100}),e.plugins)for(let i of e.plugins)this._plugins.register(i);this._options.localConfig&&(this._state.bundle=this._options.localConfig,this._plugins.runConfigUpdate(this._options.localConfig))}async initialize(){await this._errorBoundary.captureAsync("initialize",async()=>{this._options.evaluationMode==="server"?await this._fetchServerResolve():await this._fetchConfig(),this._startBackgroundRefresh(),this._state.isInitialized=!0,await this._plugins.runInitialize()},void 0)}get isInitialized(){return this._state.isInitialized}destroy(){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()}async refreshConfig(){await this._errorBoundary.swallow("refreshConfig",async()=>{this._options.evaluationMode==="server"?await this._fetchServerResolve():await this._fetchConfig()})}getConfigVersion(){return this._state.serverResponse?.stateVersion??this._state.bundle?.version??null}getParams(e){return this._errorBoundary.capture("getParams",()=>{if(this._options.evaluationMode==="server"&&this._state.serverResponse){let o={...e.defaults};for(let[s,a]of Object.entries(this._state.serverResponse.assignments))s in o&&(o[s]=a);return this._plugins.runResolve(o),o}let t=this._getEffectiveBundle(),n=this._enrichContext(e.context),i=V(t,n,e.defaults);return this._plugins.runResolve(i),i},e.defaults)}decide(e){return this._errorBoundary.capture("decide",()=>{if(this._options.evaluationMode==="server"&&this._state.serverResponse){let s=this._state.serverResponse,a={...e.defaults};for(let[h,b]of Object.entries(s.assignments))h in a&&(a[h]=b);let c={decisionId:s.decisionId,assignments:a,metadata:s.metadata};return this._cacheDecision(c),this._updateCumulativeAttribution(c),this._plugins.runDecision(c),c}let t=this._getEffectiveBundle(),n=this._enrichContext(e.context);n=this._plugins.runBeforeDecision(n);let i=this._state.cachedEdgeResults??void 0,o=$(t,n,e.defaults,i);return this._cacheDecision(o),this._updateCumulativeAttribution(o),this._plugins.runDecision(o),o},{decisionId:S(),assignments:e.defaults,metadata:{timestamp:new Date().toISOString(),unitKeyValue:"",layers:[]}})}trackExposure(e){this._errorBoundary.capture("trackExposure",()=>{let t=e.metadata.unitKeyValue;if(t)for(let n of e.metadata.layers){if(!n.policyId||!n.allocationName||n.attributionOnly||!this._exposureDedup.checkAndMark(t,n.policyId,n.allocationName))continue;let o={type:"exposure",id:J(),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:e.metadata.layers,context:e.metadata.filteredContext,sdkName:ue,sdkVersion:de};this._plugins.runExposure(o)&&this._eventLogger.log(o)}},void 0)}track(e,t,n){this._errorBoundary.capture("track",()=>{let i=n?.unitKey??this._stableId.getId(),o=typeof t?.value=="number"?t.value:void 0,s=this._buildAttribution(i,n?.decisionId),a=n?.decisionId,c={type:"track",id:Y(),orgId:this._options.orgId,projectId:this._options.projectId,env:this._options.env,unitKey:i,timestamp:new Date().toISOString(),event:e,value:o,properties:t,decisionId:a,attribution:s,sdkName:ue,sdkVersion:de};this._plugins.runTrack(c)&&this._eventLogger.log(c)},void 0)}async flushEvents(){await this._errorBoundary.swallow("flushEvents",async()=>{await this._eventLogger.flush()})}use(e){return this._plugins.register(e),this}getPlugin(e){return this._plugins.get(e)}getStableId(){return this._stableId.getId()}setStableId(e){this._stableId.setId(e)}_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/${this._options.projectId}?env=${this._options.env}`,t={"Content-Type":"application/json",Authorization:`Bearer ${this._options.apiKey}`};this._state.etag&&(t["If-None-Match"]=this._state.etag);try{let n=await fetch(e,{method:"GET",headers:t});if(n.status===304){this._state.lastFetchTime=Date.now();return}if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);let i=await n.json(),o=n.headers.get("ETag");if(this._state.bundle=i,this._state.etag=o,this._state.lastFetchTime=Date.now(),this._findEdgePolicies(i).length>0){let s=await this._prefetchEdgeResults(i,this._enrichContext({}));this._state.cachedEdgeResults=s}else this._state.cachedEdgeResults=null;this._plugins.runConfigUpdate(i)}catch(n){this._logOfflineWarning(n)}}_startBackgroundRefresh(){let e=this._options.evaluationMode==="server"?this._state.serverResponse?.suggestedRefreshMs??this._options.refreshIntervalMs:this._options.refreshIntervalMs;e<=0||(this._state.refreshTimer=setInterval(()=>{this._options.evaluationMode==="server"?this._fetchServerResolve().catch(()=>{}):this._fetchConfig().catch(()=>{})},e))}async _fetchServerResolve(){if(this._decisionClient)try{let e=this._enrichContext({}),t=await this._decisionClient.resolve({context:e});t&&(this._state.serverResponse=t,this._state.lastFetchTime=Date.now())}catch(e){this._logOfflineWarning(e)}}_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 Z(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 h=s[c];h&&a.set(o[c].policyId,{allocationIndex:h.allocationIndex,entityId:o[c].entityId})}return a.size>0?{edgeResults:a}:{}}catch{return{}}}_logOfflineWarning(e){let t=Date.now();t-this._state.lastOfflineWarning>lt&&(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)}_cacheDecision(e){if(this._decisionCache.size>=ct){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 fe(r){let e=new x(r);return await e.initialize(),e}function ge(r){return new x(r)}function he(r={}){let e={observeMutations:r.observeMutations??!0,debounceMs:r.debounceMs??100},t=[],n={},i=null,o=null;function s(l,d){try{return new RegExp(l).test(d)}catch{return d===l}}function a(l,d,p){if(d==="innerHTML")l.innerHTML=p;else if(d==="textContent")l.textContent=p;else if(d==="src"&&"src"in l)l.src=p;else if(d==="href"&&"href"in l)l.href=p;else if(d.startsWith("style.")){let g=d.slice(6);l.style[g]=p}else l.setAttribute(d,p)}function c(l,d){let p=String(d);try{let g=document.querySelectorAll(l.selector);for(let u of g)a(u,l.property,p)}catch(g){console.warn(`[Traffical DOM Binding] Failed to apply binding for ${l.parameterKey}:`,g)}}function h(l,d=!1){n=l;let p=typeof window<"u"?window.location.pathname:"";for(let g of t){if(!d&&!s(g.urlPattern,p))continue;let u=l[g.parameterKey];u!==void 0&&c(g,u)}}function b(){o&&clearTimeout(o),o=setTimeout(()=>{h(n)},e.debounceMs)}function f(){i||typeof MutationObserver>"u"||typeof document>"u"||(i=new MutationObserver(()=>{b()}),i.observe(document.body,{childList:!0,subtree:!0}))}function v(){i&&(i.disconnect(),i=null),o&&(clearTimeout(o),o=null)}return{name:"dom-binding",onInitialize(){e.observeMutations&&f()},onConfigUpdate(l){t=l.domBindings??[]},onResolve(l){h(l)},onDecision(l){h(l.assignments)},onDestroy(){v(),t=[],n={}},applyBindings(l){h(l||n)},getBindings(){return t}}}var y=null;async function ut(r){return y?(console.warn("[Traffical] Client already initialized. Returning existing instance."),y):(y=await fe(r),y)}function dt(r){return y?(console.warn("[Traffical] Client already initialized. Returning existing instance."),y):(y=ge(r),y.initialize().catch(e=>{console.warn("[Traffical] Initialization error:",e)}),y)}function ft(){return y}function gt(){y&&(y.destroy(),y=null)}return Ie(ht);})();
|
|
3
3
|
//# sourceMappingURL=traffical.min.js.map
|