@uniformdev/context 17.7.1-alpha.34 → 18.0.1-alpha.3
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/LICENSE.txt +1 -1
- package/dist/api/api.d.ts +8 -8
- package/dist/api/api.js +558 -2
- package/dist/api/api.mjs +507 -2
- package/dist/cli/cli.d.ts +3 -3
- package/dist/cli/cli.js +21381 -81
- package/dist/cli/cli.mjs +21377 -81
- package/dist/{contextTypes-1907a553.d.ts → contextTypes-defd0c5d.d.ts} +62 -62
- package/dist/index.d.ts +10 -10
- package/dist/index.esm.js +1842 -3
- package/dist/index.js +1907 -3
- package/dist/index.mjs +1842 -3
- package/dist/{types-cb64a6b4.d.ts → types-1c9fdbd2.d.ts} +75 -75
- package/dist/{v2-manifest.swagger-200ca5ee.d.ts → v2-manifest.swagger-74a3dcac.d.ts} +0 -0
- package/package.json +5 -5
package/dist/index.js
CHANGED
@@ -1,3 +1,1907 @@
|
|
1
|
-
"use strict";var Pe=Object.create;var F=Object.defineProperty;var we=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var Oe=Object.getPrototypeOf,Ue=Object.prototype.hasOwnProperty;var $e=(e,t,i)=>t in e?F(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;var Ae=(e,t)=>{for(var i in t)F(e,i,{get:t[i],enumerable:!0})},Wt=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Re(t))!Ue.call(e,n)&&n!==i&&F(e,n,{get:()=>t[n],enumerable:!(r=we(t,n))||r.enumerable});return e};var $=(e,t,i)=>(i=e!=null?Pe(Oe(e)):{},Wt(t||!e||!e.__esModule?F(i,"default",{value:e,enumerable:!0}):i,e)),Ne=e=>Wt(F({},"__esModule",{value:!0}),e);var y=(e,t,i)=>($e(e,typeof t!="symbol"?t+"":t,i),i),Ct=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)};var a=(e,t,i)=>(Ct(e,t,"read from private field"),i?i.call(e):t.get(e)),d=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},p=(e,t,i,r)=>(Ct(e,t,"write to private field"),r?r.call(e,i):t.set(e,i),i);var v=(e,t,i)=>(Ct(e,t,"access private method"),i);var Ze={};Ae(Ze,{Context:()=>jt,CookieTransitionDataStore:()=>Nt,EdgeNodeTagName:()=>Ke,EdgeTransitionDataStore:()=>Gt,GroupCriteriaEvaluator:()=>A,ManifestInstance:()=>B,SERVER_STATE_ID:()=>ne,ScriptType:()=>xe,TransitionDataStore:()=>N,UNIFORM_DEFAULT_COOKIE_NAME:()=>ce,VisitorDataStore:()=>tt,computeAggregateDimensions:()=>xt,cookieEvaluator:()=>bt,createConsoleLogDrain:()=>Ee,createDebugConsoleLogDrain:()=>ke,createLinearDecay:()=>je,currentPageEvaluator:()=>Et,emptyVisitorData:()=>M,enableConsoleLogDrain:()=>Be,enableContextDevTools:()=>Qe,enableDebugConsoleLogDrain:()=>We,evaluateVariantMatch:()=>Pt,eventEvaluator:()=>Vt,explainStringMatch:()=>P,explainStringMatchCriteria:()=>lt,getEnrichmentVectorKey:()=>W,isStringMatch:()=>x,pageViewCountDimension:()=>ct,pageViewCountEvaluator:()=>dt,parseQuickConnect:()=>Xe,personalizeVariations:()=>wt,queryStringEvaluator:()=>Tt,quirkEvaluator:()=>kt,serializeQuickConnect:()=>Ye,testVariations:()=>ft});module.exports=Ne(Ze);function xt(e,t){let i={...e};for(let r in t){let n=Yt(e,r,t,new Set([r]));n!==0&&(i[r]=n)}return i}function Yt(e,t,i,r){var s;let n=0;for(let o of i[t].inputs){let u=(s=e[o.dim])!=null?s:0;if(!u&&i[o.dim]){if(r.has(o.dim))continue;let l=new Set(r);l.add(o.dim),u=Yt(e,o.dim,i,l)}if(u!==0)if(o.sign==="c"){n=0;break}else o.sign==="-"?n-=u:n+=u}return n}var at="_";var K,H,ut=class{constructor(t,i,r){d(this,K,void 0);d(this,H,void 0);y(this,"signal");this.signal=t,p(this,K,i),p(this,H,r)}computeSignal(t,i){if(t.scores[this.signal.id]>=this.signal.cap&&this.signal.dur!=="t")return;let n=a(this,K).evaluate(t,this.signal.crit,i,this.signal,a(this,H)),s=this.signal.dur==="s"||this.signal.dur==="t"?"modscoreS":"modscore";if(!!n.changed){if(n.result)i.push({type:s,data:{dimension:this.signal.id,delta:this.signal.str}});else if(this.signal.dur==="t"){let o=t.visitor.sessionScores[this.signal.id];o&&i.push({type:s,data:{dimension:this.signal.id,delta:-o}})}}}};K=new WeakMap,H=new WeakMap;var E,J,O,B=class{constructor({manifest:t,evaluator:i=new A({}),onLogMessage:r=()=>{}}){y(this,"data");d(this,E,void 0);d(this,J,void 0);d(this,O,void 0);var n,s,o;p(this,E,(n=t.project)!=null?n:{}),this.data=t,p(this,J,Object.entries((o=(s=a(this,E).pz)==null?void 0:s.sig)!=null?o:[]).map(([u,c])=>new ut({...c,id:u},i,r))),p(this,O,r)}rollForControlGroup(){var t,i;return Math.random()<((i=(t=a(this,E).pz)==null?void 0:t.control)!=null?i:0)}getTest(t){var i;return(i=a(this,E).test)==null?void 0:i[t]}computeSignals(t){let i=[];a(this,O).call(this,["debug",200,"GROUP"]);try{a(this,J).forEach(r=>{a(this,O).call(this,["debug",201,"GROUP",r.signal]);try{r.computeSignal(t,i)}finally{a(this,O).call(this,["debug",201,"ENDGROUP"])}})}finally{a(this,O).call(this,["debug",200,"ENDGROUP"])}return i}computeAggregateDimensions(t){var i,r;return xt(t,(r=(i=a(this,E).pz)==null?void 0:i.agg)!=null?r:{})}getDimensionByKey(t){var r,n,s,o;let i=t.indexOf(at);return i<=0?(n=(r=a(this,E).pz)==null?void 0:r.sig)==null?void 0:n[t]:(o=(s=a(this,E).pz)==null?void 0:s.enr)==null?void 0:o[t.substring(0,i)]}};E=new WeakMap,J=new WeakMap,O=new WeakMap;var Mt=require("dequal/lite");function x(e,t){var o,u,c,l,f,m;let i=(o=t==null?void 0:t.op)!=null?o:"=";if(t.op==="*")return e!==null&&typeof e!="undefined";if(t.op==="!*")return e===null||typeof e=="undefined";if(!("rhs"in t))throw new Error(`Match expression is required for match type ${i}`);let r=(u=t.cs)!=null?u:!1,n=(r?e!=null?e:"":Xt(e)).toString(),s=(r?t.rhs:Xt(t.rhs)).toString();switch(i){case"=":return n===s;case"!=":return n!==s;case"~":return(c=n.includes(s))!=null?c:!1;case"!~":return!((l=n.includes(s))==null||l);case"//":return new RegExp(t.rhs.toString(),r?"":"i").test((f=e==null?void 0:e.toString())!=null?f:"");case"!//":return!new RegExp(t.rhs.toString(),r?"":"i").test((m=e==null?void 0:e.toString())!=null?m:"");default:throw new Error(`Unknown match type ${i}.`)}}function P(e,t){return`'${("cs"in t?t.cs:!1)?e:e==null?void 0:e.toString().toUpperCase()}' ${lt(t)}`}function lt(e){return"rhs"in e?`${e.op} '${e.cs?e.rhs:e.rhs.toString().toUpperCase()}'`:`${e.op==="*"?"exists":"does not exist"}`}function Xt(e){var t,i;return(i=(t=e==null?void 0:e.toString())==null?void 0:t.toUpperCase())!=null?i:""}var bt=({update:e,criteria:t,onLogMessage:i})=>{var u,c;if(t.type!=="CK")return{result:!1,changed:!1};let r=!(0,Mt.dequal)(Zt(e.state.cookies),Zt((u=e.previousState)==null?void 0:u.cookies)),n=(c=e.state.cookies)==null?void 0:c[t.cookieName],o={result:x(n,t.match),changed:r};return i==null||i(["debug",203,{criteria:t,result:o,explanation:P(n,t.match)}]),o};function Zt(e){if(!e)return;if(!e.ufvd)return e;let{ufvd:t,...i}=e;return i}var Et=({update:e,criteria:t,onLogMessage:i})=>{var u,c,l;if(t.type!=="PV")return{result:!1,changed:!1};let r=(u=e.state.url)==null?void 0:u.pathname,n=!e.previousState||(r==null?void 0:r.toString())!==((l=(c=e.previousState.url)==null?void 0:c.pathname)==null?void 0:l.toString()),o={result:x(r,t.path),changed:n};return i==null||i(["debug",203,{criteria:t,result:o,explanation:P(r,t.path)}]),o};var Vt=({update:e,criteria:t,onLogMessage:i})=>{var s,o,u;if(t.type!=="EVT")return{result:!1,changed:!1};let r=(o=(s=e.state.events)==null?void 0:s.some(c=>x(c.event,t.event)))!=null?o:!1,n={result:r,changed:r};return i==null||i(["debug",203,{criteria:t,result:n,explanation:`'${(u=e.state.events)==null?void 0:u.join("', '")}' ${lt(t.event)}`}]),n};function W(e,t){return`${e}${at}${t}`}function Lt(e,t){var r;if(typeof e=="undefined"||e===null)return!1;let i=Number(e);if(isNaN(i))return!1;switch((r=t==null?void 0:t.op)!=null?r:"="){case"=":return i===t.rhs;case"!=":return i!==t.rhs;case">":return i>t.rhs;case"<":return i<t.rhs;default:return console.warn(`Unknown match type ${t.op} is false.`),!1}}function te(e,t){return`${e} ${Ge(t)}`}function Ge(e){return`${e.op} ${e.rhs}`}var ct=W("$pvc","v"),dt=({update:e,criteria:t,commands:i,onLogMessage:r})=>{var l,f;if(t.type!=="PVC")return{result:!1,changed:!1};let n=Boolean(e.state.url&&(!e.previousState||((l=e.state.url)==null?void 0:l.toString())!==((f=e.previousState.url)==null?void 0:f.toString()))),o=(e.visitor.sessionScores[ct]||0)+1,u={result:!1,changed:n},c=i.some(m=>m.type==="modscoreS"&&m.data.dimension===ct);return n&&!c&&i.push({type:"modscoreS",data:{dimension:ct,delta:1}}),Lt(o,t.match)&&(u.result=!0),r==null||r(["debug",203,{criteria:t,result:u,explanation:te(o,t.match)}]),u};dt.alwaysExecute=!0;var Tt=({update:e,criteria:t,onLogMessage:i})=>{var u,c,l,f,m;if(t.type!=="QS")return{result:!1,changed:!1};let r=!e.previousState||((c=(u=e.state.url)==null?void 0:u.searchParams)==null?void 0:c.toString())!==((f=(l=e.previousState.url)==null?void 0:l.searchParams)==null?void 0:f.toString()),n=(m=e.state.url)==null?void 0:m.searchParams.get(t.queryName),o={result:x(n,t.match),changed:r};return i==null||i(["debug",203,{criteria:t,result:o,explanation:P(n,t.match)}]),o};var kt=({update:e,criteria:t,signal:i,onLogMessage:r})=>{var f;if(t.type!=="QK")return{result:!1,changed:!1};if(typeof document=="undefined"&&e.scores[i.id]>0)return{result:!0,changed:!1};let n=e.visitor.quirks[t.key],s=(f=e.state.quirks)==null?void 0:f[t.key],o=s!=null?s:n,u=Boolean(s&&n!==s),l={result:x(o,t.match),changed:u};return r==null||r(["debug",203,{criteria:t,result:l,explanation:P(o,t.match)}]),l};var Y,A=class{constructor(t){d(this,Y,void 0);p(this,Y,t)}evaluate(t,i,r,n,s){let o=i.clauses.length>1;o&&(s==null||s(["debug",202,"GROUP",i]));try{let u=!(i.op==="&"||!i.op),c=null,l=!1;for(let m of i.clauses){let S;if(m.type==="G")S=this.evaluate(t,m,r,n,s);else{let C=a(this,Y)[m.type];if(c&&!C.alwaysExecute)continue;if(!C)throw new Error(`${m.type} signal criteria not registered`);S=C({update:t,criteria:m,commands:r,signal:n,onLogMessage:s})}S.changed&&(l=!0),!c&&S.result===u&&(c={result:u,changed:l})}let f=c!=null?c:{result:!u,changed:l};return o&&(s==null||s(["debug",204,f])),f}finally{o&&(s==null||s(["debug",202,"ENDGROUP"]))}}};Y=new WeakMap;function Pt(e,t,i,r){r==null||r(["info",301,"GROUP",{id:e,op:t==null?void 0:t.op}]);let n;try{t!=null&&t.crit?!t.op||t.op==="&"?n=t.crit.every(s=>ee(s,i,r)):n=t.crit.some(s=>ee(s,i,r)):(r==null||r(["info",302,{matched:!0,description:"default variation"}]),n=!0),r==null||r(["info",303,n])}finally{r==null||r(["info",301,"ENDGROUP"])}return n}function ee(e,t,i){var u,c;let{op:r,l:n}=e,s=(u=t[n])!=null?u:0;if(r==="+"){let l=Math.max(...Object.values(t))===s&&s>0;return i==null||i(["info",302,{matched:l,description:`${e.l} has the highest score`}]),l}else if(r==="-"){let l=Math.min(...Object.values(t))===s&&s>0;return i==null||i(["info",302,{matched:l,description:`${e.l} has the lowest non-zero score`}]),l}let o;if(e.rDim?o=t[e.rDim]||0:o=parseInt(e.r,10),isNaN(o))return i==null||i(["info",302,{matched:!1,description:`${(c=e.rDim)!=null?c:e.r} has no score value`}]),!1;if(r===">"){let l=s>o;return q(i,l,e,s,o),l}else if(r===">="){let l=s>=o;return q(i,l,e,s,o),l}else if(r==="<"){let l=s<o;return q(i,l,e,s,o),l}else if(r==="<="){let l=s<=o;return q(i,l,e,s,o),l}else if(r==="="){let l=s===o;return q(i,l,e,s,o),l}else if(r==="!="){let l=s!==o;return q(i,l,e,s,o),l}else throw new Error(`Unknown op: ${r}`)}function q(e,t,i,r,n){e==null||e(["info",302,{matched:t,description:`${i.l}[${r}] ${i.op} ${i.rDim?`${i.rDim}[${n}]`:i.r}`}])}function wt({name:e,context:t,variations:i,take:r=1,onLogMessage:n}){var s,o,u;n==null||n(["info",300,"GROUP",{name:e,take:r}]);try{let c=(s=t.storage.data.controlGroup)!=null?s:!1,l=[],f=!1,m=t.scores;for(let S of i){if(l.length===r)break;if(!((o=S.pz)!=null&&o.crit.length)){n==null||n(["info",301,"GROUP",{id:S.id,op:(u=S.pz)==null?void 0:u.op}]),n==null||n(["info",302,{matched:!0,description:"default variation"}]),n==null||n(["info",303,!0]),n==null||n(["info",301,"ENDGROUP"]),l.push(S);continue}c||Pt(S.id,S.pz,m,n)&&(f=!0,l.push(S))}return{personalized:f,variations:l}}finally{n==null||n(["info",300,"ENDGROUP"])}}var ze=e=>{let{values:t,total:i,missingDistribution:r}=e.reduce((n,s)=>(s.testDistribution?n.total+=s.testDistribution:++n.missingDistribution,n.values.push(s.testDistribution),n),{values:[],total:0,missingDistribution:0});if(i>100)throw new Error(`Total distribution ${i} is over the maximum 100.`);if(i<100){let s=(100-i)/r;t.forEach((o,u)=>{typeof o=="undefined"&&(t[u]=s)})}return t},ft=({name:e,context:t,variations:i,onLogMessage:r})=>{r==null||r(["info",400,"GROUP",e]);try{let n,s=t.getTestVariantId(e);if(s===null)return r==null||r(["error",401,e]),{result:void 0,variantAssigned:!1};if(s&&(n=i.find(o=>o.id===s),n||r==null||r(["warn",402,{missingVariant:s,variants:i.map(o=>o.id)}])),!n){let o=ze(i),u=Math.floor(Math.random()*100),c=0;n=i.find((l,f)=>{let m=o[f];if(u>c&&u<=c+m)return l;c+=m}),n&&(r==null||r(["info",403,n.id]),t.setTestVariantId(e,n.id))}return n&&(r==null||r(["info",404,n.id])),{result:n,variantAssigned:!s}}finally{r==null||r(["info",400,"ENDGROUP"])}};var pt=$(require("js-cookie"));var ie=require("dequal/lite"),re=$(require("mitt"));var ne="__UNIFORM_DATA__",U,X,j,N=class{constructor({initialData:t}){d(this,U,void 0);d(this,X,void 0);d(this,j,(0,re.default)());y(this,"events",{on:a(this,j).on,off:a(this,j).off});t&&(p(this,U,t),p(this,X,t))}get data(){return a(this,U)}get initialData(){return a(this,X)}updateData(t,i){return p(this,U,i),this.handleUpdateData(t,i)}async delete(t){p(this,U,void 0),await this.handleDelete(t)}signalAsyncDataUpdate(t){(0,ie.dequal)(this.data,t)||(p(this,U,t),a(this,j).emit("dataUpdatedAsync",t))}getClientTransitionState(){if(typeof document=="undefined")return;let t=document.getElementById(ne);return t!=null&&t.textContent?JSON.parse(t.textContent):void 0}};U=new WeakMap,X=new WeakMap,j=new WeakMap;var Rt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",oe=Rt.split(""),se=new Array(123);for(let e=0;e<Rt.length;e++)se[Rt.charCodeAt(e)]=e;var Ot=e=>{if(e<0)return`-${Ot(-e)}`;let t=e>>>0,i=e/4294967296>>>0,r="";for(;i>0;)r=oe[63&t]+r,t>>>=6,t|=(63&i)<<26,i>>>=6;let n="";do n=oe[63&t]+n,t>>>=6;while(t>0);return n+r},ae=e=>{let t=0,i=e.charAt(0)==="-"?1:0;for(let r=i;r<e.length;r++)t=t*64+se[e.charCodeAt(r)];return i?-t:t};var Ut=typeof document=="undefined",ce="ufvd",G,Z,Nt=class extends N{constructor({serverCookieValue:i,cookieName:r=ce,cookieAttributes:n={sameSite:"lax"}}){super({initialData:Ut?Ie(i):void 0});d(this,G,void 0);d(this,Z,void 0);p(this,G,r),p(this,Z,n)}handleDelete(){return Ut||pt.default.remove(a(this,G)),Promise.resolve()}async handleUpdateData(i,r){Ut||(r.consent?pt.default.set(a(this,G),qe(r),a(this,Z)):pt.default.remove(a(this,G)))}};G=new WeakMap,Z=new WeakMap;var de="~",fe="!",pe="-";function Ie(e){if(!e)return;let t=e.split(de);if(t.length>3)return;let[i,r,n]=t;return{consent:!0,sessionScores:ue($t(r)),scores:ue($t(n)),tests:$t(i)}}function $t(e){return e.split(fe).map(i=>i.split(pe)).reduce((i,r)=>(r.length<2||(i[r[0]]=r.slice(1).join("-")),i),{})}function ue(e){return Object.entries(e).reduce((t,[i,r])=>(t[i]=ae(r),t),{})}function qe(e){return[At(e.tests),At(le(e.sessionScores)),At(le(e.scores))].join(de)}function le(e){return Object.entries(e).reduce((t,[i,r])=>(t[i]=Ot(r),t),{})}function At(e){return Object.entries(e).map(t=>t.join(pe)).join(fe)}var mt,me,Gt=class extends N{constructor({serverCookieValue:i,visitorIdCookieName:r="ufvi",...n}){super(n);d(this,mt);n.initialData||v(this,mt,me).call(this).catch(s=>{console.error(s)})}handleDelete(i){throw new Error("Method not implemented.")}async handleUpdateData(i){let r=await new Promise(n=>{setTimeout(()=>{n(void 0)},2e3)});r&&this.signalAsyncDataUpdate(r)}};mt=new WeakSet,me=async function(){let i=await new Promise(r=>{setTimeout(()=>{r(void 0)},2e3)});i&&this.signalAsyncDataUpdate(i)};function je(e){let{gracePeriod:t=864e5,decayRate:i=1/30,decayCap:r=.95}=e!=null?e:{};return function({now:s,lastUpd:o,scores:u,sessionScores:c,onLogMessage:l}){if(typeof o!="number")return!1;let m=s-o-t;if(m<=0)return!1;let S=m/864e5,C=1-Math.min(r,S*i);return C<=0?!1:(he(u,C),he(c,C),l==null||l(["info",140,`linear decay factor ${C.toPrecision(6)}`]),!0)}}function he(e,t){for(let i in e)i.startsWith("$")||(e[i]*=t)}var M=()=>({quirks:{},scores:{},sessionScores:{},tests:{},consent:!1,controlGroup:!1});var L=require("dequal/lite"),Se=$(require("mitt"));var ge=$(require("rfdc"));var _e=(0,ge.default)();function ve(e,t,i){let r=t?_e(t):M();return e.forEach(n=>{var s,o;switch(n.type){case"consent":r.consent=n.data;break;case"setquirk":r.quirks[n.data.key]=n.data.value;break;case"settest":r.tests[n.data.test]=n.data.variant;break;case"modscore":if(i)break;let u=Number(n.data.delta);if(isNaN(u))throw new Error("Non-number delta received");let c=(s=r.scores[n.data.dimension])!=null?s:0;r.scores[n.data.dimension]=c+u;break;case"modscoreS":if(i)break;let l=Number(n.data.delta);if(isNaN(l))throw new Error("Non-number delta received");let f=(o=r.sessionScores[n.data.dimension])!=null?o:0;r.sessionScores[n.data.dimension]=f+l;break;case"identify":break;case"setcontrol":r.controlGroup=n.data;break;default:throw new Error("Unknown command")}}),r}var ht=class{constructor(){y(this,"inMemoryFallback",{});y(this,"hasLocalStorageObject",typeof localStorage!="undefined")}get(t){let i=this.inMemoryFallback[t];if(!this.hasLocalStorageObject||i)return i;try{let r=localStorage.getItem(t);return r?JSON.parse(r):void 0}catch(r){return i}}set(t,i,r){if(this.inMemoryFallback[t]=i,!(!this.hasLocalStorageObject||!r))try{localStorage.setItem(t,JSON.stringify(i))}catch(n){console.warn(n)}}delete(t,i){i||delete this.inMemoryFallback[t];try{localStorage.removeItem(t)}catch(r){}}};var gt="ufvisitor",V,I,_,g,b,w,R,z,vt,ye,St,De,et,zt,it,It,tt=class{constructor(t){d(this,b);d(this,R);d(this,vt);d(this,St);d(this,et);d(this,it);d(this,V,(0,Se.default)());d(this,I,new ht);d(this,_,void 0);d(this,g,void 0);y(this,"events",{on:a(this,V).on,off:a(this,V).off});if(p(this,g,t),a(this,b,w)||v(this,R,z).call(this,v(this,it,It).call(this),!0),t.transitionStore){let i=t.transitionStore.getClientTransitionState();i&&t.onServerTransitionReceived&&t.onServerTransitionReceived(i),t.transitionStore.events.on("dataUpdatedAsync",n=>{v(this,R,z).call(this,{...a(this,b,w).visitorData,...n})});let r=t.transitionStore.data;r&&v(this,R,z).call(this,{...a(this,b,w).visitorData,...r},!0)}}get data(){var i,r;let t=a(this,b,w);if(v(this,St,De).call(this,t)){let{sessionScores:n,...s}=t.visitorData;return v(this,R,z).call(this,{...s,sessionScores:{}}),(r=(i=a(this,g)).onLogMessage)==null||r.call(i,["info",120]),a(this,b,w).visitorData}return t.visitorData}get decayEnabled(){return!!a(this,g).decay}get options(){return a(this,g)}async updateData(t){var r,n,s,o;if(t.length===0)return;(n=(r=a(this,g)).onLogMessage)==null||n.call(r,["debug",101,t]);let i=ve(t,this.data,(s=a(this,b,w))==null?void 0:s.visitorData.controlGroup);t.some(u=>u.type==="consent"&&!u.data)&&a(this,I).delete(gt,!0),v(this,R,z).call(this,i),await((o=a(this,g).transitionStore)==null?void 0:o.updateData(t,a(this,b,w).visitorData))}async delete(t){var i,r,n,s,o;(r=(i=a(this,g)).onLogMessage)==null||r.call(i,["info",103,"GROUP",t]);try{a(this,I).delete(gt,!1),await((n=a(this,g).transitionStore)==null?void 0:n.delete(t)),v(this,R,z).call(this,v(this,it,It).call(this))}finally{(o=(s=a(this,g)).onLogMessage)==null||o.call(s,["info",103,"ENDGROUP"])}}};V=new WeakMap,I=new WeakMap,_=new WeakMap,g=new WeakMap,b=new WeakSet,w=function(){return a(this,I).get(gt)},R=new WeakSet,z=function(t,i=!1){var f,m,S,C,st,Kt,Ht,Bt,Jt;let r=a(this,b,w),n=Date.now();t.controlGroup?(t.scores={},t.sessionScores={}):(v(this,et,zt).call(this,t.scores),v(this,et,zt).call(this,t.sessionScores),(m=(f=a(this,g)).decay)==null||m.call(f,{now:n,lastUpd:r==null?void 0:r.updated,scores:t.scores,sessionScores:t.sessionScores,onLogMessage:a(this,g).onLogMessage}));let s=!(0,L.dequal)(r==null?void 0:r.visitorData.scores,t.scores),o=!(0,L.dequal)(r==null?void 0:r.visitorData.sessionScores,t.sessionScores),u=!(0,L.dequal)(r==null?void 0:r.visitorData.quirks,t.quirks),c=!(0,L.dequal)(r==null?void 0:r.visitorData.tests,t.tests),l={updated:n,visitorData:t};v(this,vt,ye).call(this),a(this,I).set(gt,l,!!t.consent),(C=(S=a(this,g)).onLogMessage)==null||C.call(S,["debug",102,t]),i||((s||o)&&a(this,V).emit("scoresUpdated",t),u&&a(this,V).emit("quirksUpdated",t),c&&a(this,V).emit("testsUpdated",t),((st=r==null?void 0:r.visitorData)==null?void 0:st.consent)!==t.consent&&a(this,V).emit("consentUpdated",t),((Kt=r==null?void 0:r.visitorData)==null?void 0:Kt.controlGroup)!==t.controlGroup&&(a(this,V).emit("controlGroupUpdated",t),(Jt=(Bt=a(this,g)).onLogMessage)==null||Jt.call(Bt,["debug",104,(Ht=t.controlGroup)!=null?Ht:!1])))},vt=new WeakSet,ye=function(){typeof document=="undefined"||!a(this,g).visitLifespan||(a(this,_)&&window.clearTimeout(a(this,_)),p(this,_,window.setTimeout(()=>{this.data},a(this,g).visitLifespan+50)))},St=new WeakSet,De=function(t){let i=a(this,g).visitLifespan;return i?t.updated+i<Date.now():!1},et=new WeakSet,zt=function(t){var i,r;if(!!a(this,g).manifest)for(let n in t){let s=t[n],o=a(this,g).manifest.getDimensionByKey(n);!o||s>o.cap&&((r=(i=a(this,g)).onLogMessage)==null||r.call(i,["debug",110,{dim:n,score:s,cap:o.cap}]),t[n]=o.cap)}},it=new WeakSet,It=function(){var t,i,r;return{...M(),consent:(t=a(this,g).defaultConsent)!=null?t:!1,controlGroup:(r=(i=a(this,g).manifest)==null?void 0:i.rollForControlGroup())!=null?r:!1}};var qt=require("dequal/lite"),Ce=$(require("mitt"));var D,T,k,rt,h,nt,_t,Q,yt,ot,Qt,jt=class{constructor(t){d(this,nt);d(this,Q);d(this,ot);y(this,"manifest");d(this,D,void 0);d(this,T,{});d(this,k,void 0);d(this,rt,{});d(this,h,(0,Ce.default)());y(this,"events",{on:a(this,h).on,off:a(this,h).off});y(this,"storage");var n,s;let{manifest:i,...r}=t;p(this,k,{}),(n=t.plugins)==null||n.forEach(o=>{!o.logDrain||a(this,h).on("log",o.logDrain)}),a(this,h).emit("log",["info",1,"GROUP"]);try{this.manifest=new B({onLogMessage:o=>a(this,h).emit("log",o),manifest:i,evaluator:new A({CK:bt,QS:Tt,QK:kt,PVC:dt,EVT:Vt,PV:Et})}),this.storage=new tt({...r,manifest:this.manifest,onServerTransitionReceived:o=>{p(this,D,o),o.ssv&&(p(this,T,o.ssv),a(this,h).emit("log",["debug",130,o]))},onLogMessage:o=>a(this,h).emit("log",o)}),this.storage.events.on("scoresUpdated",v(this,Q,yt).bind(this)),a(this,D)||v(this,Q,yt).call(this,this.storage.data),this.storage.events.on("quirksUpdated",o=>{let u=this.manifest.computeSignals({scores:a(this,T),state:a(this,k),previousState:a(this,k),visitor:this.storage.data});this.storage.updateData(u),a(this,h).emit("quirksUpdated",o.quirks),a(this,h).emit("log",["info",4,o.quirks])}),(s=t.plugins)==null||s.forEach(o=>{!o.init||o.init(this)})}finally{a(this,h).emit("log",["info",1,"ENDGROUP"])}}get scores(){return a(this,T)}get quirks(){var t,i;return(i=(t=a(this,D))==null?void 0:t.quirks)!=null?i:this.storage.data.quirks}async update(t){var n,s,o;let i=[],r={};if((n=a(this,D))!=null&&n.quirks&&(t={...t,quirks:{...a(this,D).quirks,...t.quirks||{}}}),(s=a(this,D))!=null&&s.tests){let u=Object.entries(a(this,D).tests);if(u.length>0){let c=[];u.forEach(([l,f])=>{this.storage.data.tests[l]||(c.push([l,f]),r[l]=f)}),i.push(...c.map(([l,f])=>({type:"settest",data:{test:l,variant:f}})))}}try{a(this,h).emit("log",["info",2,"GROUP",{...t,url:(o=t.url)==null?void 0:o.toString()}]),t.quirks&&i.push(...Object.entries(t.quirks).map(([u,c])=>({type:"setquirk",data:{key:u,value:c}}))),t.enrichments&&t.enrichments.forEach(u=>{let c=W(u.cat,u.key);this.manifest.getDimensionByKey(c)?i.push({type:"modscore",data:{dimension:c,delta:u.str}}):a(this,h).emit("log",["warn",5,u])}),i.push(...this.manifest.computeSignals({state:t,previousState:a(this,k),visitor:this.storage.data,scores:a(this,D)?v(this,ot,Qt).call(this,this.storage.data):a(this,T)})),p(this,k,{...a(this,k),...t}),await this.storage.updateData(i),a(this,D)&&(v(this,Q,yt).call(this,this.storage.data),Object.entries(r).forEach(([u,c])=>{v(this,nt,_t).call(this,{name:u,variantId:c,variantAssigned:!0})}),p(this,D,void 0),a(this,h).emit("log",["debug",131]))}finally{a(this,h).emit("log",["info",2,"ENDGROUP"])}}getTestVariantId(t){var r,n,s,o;let i=this.manifest.getTest(t);return i?(o=(s=i.wv)!=null?s:(n=(r=a(this,D))==null?void 0:r.tests)==null?void 0:n[t])!=null?o:this.storage.data.tests[t]:(a(this,h).emit("log",["warn",401,t]),null)}setTestVariantId(t,i){this.storage.updateData([{type:"settest",data:{test:t,variant:i}}])}log(...t){a(this,h).emit("log",t)}test(t){var r,n;let i=ft({...t,context:this,onLogMessage:s=>a(this,h).emit("log",s)});return v(this,nt,_t).call(this,{name:t.name,variantId:(n=(r=i.result)==null?void 0:r.id)!=null?n:void 0,variantAssigned:i.variantAssigned}),i}personalize(t){let i=wt({...t,context:this,onLogMessage:s=>a(this,h).emit("log",s)}),r=a(this,rt)[t.name],n={name:t.name,variantIds:i.variations.map(s=>{var o;return(o=s.id)!=null?o:"Unknown"}),control:this.storage.data.controlGroup,changed:!0};return r&&(0,qt.dequal)(n.variantIds,r)&&(n.changed=!1),a(this,h).emit("personalizationResult",n),a(this,rt)[t.name]=n.variantIds,i}async forget(t){p(this,k,{}),await this.storage.delete(t)}getServerToClientTransitionState(){let t={quirks:this.storage.data.quirks,ssv:a(this,T),tests:{}},i=this.storage.data.tests;return Object.entries(i).map(([r,n])=>{var s,o,u;((u=(o=(s=this.storage.options.transitionStore)==null?void 0:s.initialData)==null?void 0:o.tests)==null?void 0:u[r])!==i[r]&&t.tests&&(t.tests[r]=n)}),t}};D=new WeakMap,T=new WeakMap,k=new WeakMap,rt=new WeakMap,h=new WeakMap,nt=new WeakSet,_t=function(t){a(this,h).emit("testResult",t)},Q=new WeakSet,yt=function(t){let i=v(this,ot,Qt).call(this,t);!(0,qt.dequal)(i,a(this,T))&&(p(this,T,i),a(this,h).emit("scoresUpdated",i),a(this,h).emit("log",["info",3,i]))},ot=new WeakSet,Qt=function(t){var r;let i={...t.scores};for(let n in t.sessionScores)i[n]=((r=i[n])!=null?r:0)+t.sessionScores[n];return i=this.manifest.computeAggregateDimensions(i),i};var Ft=typeof top!="undefined";function Qe(){return{logDrain:e=>{!Ft||top==null||top.postMessage({type:"uniform:context:log",message:e},window.location.origin)},init:e=>{let t=[],i=[],r=()=>{!Ft||top==null||top.postMessage({type:"uniform:context:data",data:{scores:e.scores,data:e.storage.data,manifest:e.manifest.data,personalizations:t,tests:i}},window.location.origin)},n=o=>{!o.changed||t.push(o)},s=o=>{!o.variantAssigned||i.push(o)};if(Ft){window.__UNIFORM_DEVTOOLS_CONTEXT_INSTANCE__=e;try{top==null||top.addEventListener("message",async o=>{if(!o.data)return;let u=o.data;await Fe(u,e)})}catch(o){console.warn("Unable to initialize Uniform Context DevTools because it is in a cross-domain iframe.",o)}top==null||top.postMessage({type:"uniform:context:hello",uiVersion:2},window.location.origin),r()}return e.events.on("personalizationResult",n),e.events.on("testResult",s),e.events.on("scoresUpdated",r),e.storage.events.on("*",r),()=>{e.events.off("scoresUpdated",r),e.storage.events.off("*",r),e.events.off("personalizationResult",n),e.events.off("testResult",s)}}}}async function Fe(e,t){e.type==="uniform-in:context:update"&&e.newData&&await t.update(e.newData),e.type==="uniform-in:context:commands"&&e.commands&&Array.isArray(e.commands)&&await t.storage.updateData(e.commands),e.type==="uniform-in:context:forget"&&await t.forget(!1)}var xe=(u=>(u.ListStart="nesi-list-start",u.ListEnd="nesi-list-end",u.ListItem="nesi-list-item-html",u.ListItemSettings="nesi-list-item-settings",u.TestStart="nesi-test-start",u.TestEnd="nesi-test-end",u.Unknown="unknown",u))(xe||{}),Ke="nesitag";var be=$(require("rfdc"));function Dt(e,t){if(e==="none")return!1;switch(t){case"debug":return e==="debug";case"info":return e==="info"||e==="debug";case"warn":return e==="warn"||e==="info"||e==="debug";case"error":return e==="debug"||"info";default:return!1}}var He=(0,be.default)();function Ee(e){return([t,...i])=>{if(!Dt(e,t))return;let[r,...n]=i;console[t](`\u{1F94B} [${t}] Uniform event ID ${r}
|
2
|
-
|
3
|
-
|
1
|
+
"use strict";
|
2
|
+
var __create = Object.create;
|
3
|
+
var __defProp = Object.defineProperty;
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
8
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
9
|
+
var __export = (target, all) => {
|
10
|
+
for (var name in all)
|
11
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
12
|
+
};
|
13
|
+
var __copyProps = (to, from, except, desc) => {
|
14
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
15
|
+
for (let key of __getOwnPropNames(from))
|
16
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
17
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
18
|
+
}
|
19
|
+
return to;
|
20
|
+
};
|
21
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
22
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
23
|
+
mod
|
24
|
+
));
|
25
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
26
|
+
var __publicField = (obj, key, value) => {
|
27
|
+
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
28
|
+
return value;
|
29
|
+
};
|
30
|
+
var __accessCheck = (obj, member, msg) => {
|
31
|
+
if (!member.has(obj))
|
32
|
+
throw TypeError("Cannot " + msg);
|
33
|
+
};
|
34
|
+
var __privateGet = (obj, member, getter) => {
|
35
|
+
__accessCheck(obj, member, "read from private field");
|
36
|
+
return getter ? getter.call(obj) : member.get(obj);
|
37
|
+
};
|
38
|
+
var __privateAdd = (obj, member, value) => {
|
39
|
+
if (member.has(obj))
|
40
|
+
throw TypeError("Cannot add the same private member more than once");
|
41
|
+
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
42
|
+
};
|
43
|
+
var __privateSet = (obj, member, value, setter) => {
|
44
|
+
__accessCheck(obj, member, "write to private field");
|
45
|
+
setter ? setter.call(obj, value) : member.set(obj, value);
|
46
|
+
return value;
|
47
|
+
};
|
48
|
+
var __privateMethod = (obj, member, method) => {
|
49
|
+
__accessCheck(obj, member, "access private method");
|
50
|
+
return method;
|
51
|
+
};
|
52
|
+
|
53
|
+
// src/index.ts
|
54
|
+
var src_exports = {};
|
55
|
+
__export(src_exports, {
|
56
|
+
Context: () => Context,
|
57
|
+
CookieTransitionDataStore: () => CookieTransitionDataStore,
|
58
|
+
EdgeNodeTagName: () => EdgeNodeTagName,
|
59
|
+
EdgeTransitionDataStore: () => EdgeTransitionDataStore,
|
60
|
+
GroupCriteriaEvaluator: () => GroupCriteriaEvaluator,
|
61
|
+
ManifestInstance: () => ManifestInstance,
|
62
|
+
SERVER_STATE_ID: () => SERVER_STATE_ID,
|
63
|
+
ScriptType: () => ScriptType,
|
64
|
+
TransitionDataStore: () => TransitionDataStore,
|
65
|
+
UNIFORM_DEFAULT_COOKIE_NAME: () => UNIFORM_DEFAULT_COOKIE_NAME,
|
66
|
+
VisitorDataStore: () => VisitorDataStore,
|
67
|
+
computeAggregateDimensions: () => computeAggregateDimensions,
|
68
|
+
cookieEvaluator: () => cookieEvaluator,
|
69
|
+
createConsoleLogDrain: () => createConsoleLogDrain,
|
70
|
+
createDebugConsoleLogDrain: () => createDebugConsoleLogDrain,
|
71
|
+
createLinearDecay: () => createLinearDecay,
|
72
|
+
currentPageEvaluator: () => currentPageEvaluator,
|
73
|
+
emptyVisitorData: () => emptyVisitorData,
|
74
|
+
enableConsoleLogDrain: () => enableConsoleLogDrain,
|
75
|
+
enableContextDevTools: () => enableContextDevTools,
|
76
|
+
enableDebugConsoleLogDrain: () => enableDebugConsoleLogDrain,
|
77
|
+
evaluateVariantMatch: () => evaluateVariantMatch,
|
78
|
+
eventEvaluator: () => eventEvaluator,
|
79
|
+
explainStringMatch: () => explainStringMatch,
|
80
|
+
explainStringMatchCriteria: () => explainStringMatchCriteria,
|
81
|
+
getEnrichmentVectorKey: () => getEnrichmentVectorKey,
|
82
|
+
isStringMatch: () => isStringMatch,
|
83
|
+
pageViewCountDimension: () => pageViewCountDimension,
|
84
|
+
pageViewCountEvaluator: () => pageViewCountEvaluator,
|
85
|
+
parseQuickConnect: () => parseQuickConnect,
|
86
|
+
personalizeVariations: () => personalizeVariations,
|
87
|
+
queryStringEvaluator: () => queryStringEvaluator,
|
88
|
+
quirkEvaluator: () => quirkEvaluator,
|
89
|
+
serializeQuickConnect: () => serializeQuickConnect,
|
90
|
+
testVariations: () => testVariations
|
91
|
+
});
|
92
|
+
module.exports = __toCommonJS(src_exports);
|
93
|
+
|
94
|
+
// src/manifest/aggregates/computeAggregateDimensions.ts
|
95
|
+
function computeAggregateDimensions(primitiveScores, aggregates) {
|
96
|
+
const result = { ...primitiveScores };
|
97
|
+
for (const aggregateDimension in aggregates) {
|
98
|
+
const aggregateScore = computeAggregateDimension(
|
99
|
+
primitiveScores,
|
100
|
+
aggregateDimension,
|
101
|
+
aggregates,
|
102
|
+
/* @__PURE__ */ new Set([aggregateDimension])
|
103
|
+
);
|
104
|
+
if (aggregateScore !== 0) {
|
105
|
+
result[aggregateDimension] = aggregateScore;
|
106
|
+
}
|
107
|
+
}
|
108
|
+
return result;
|
109
|
+
}
|
110
|
+
function computeAggregateDimension(primitiveScores, aggregateDimension, allAggregates, visitedDimensions) {
|
111
|
+
var _a;
|
112
|
+
let aggregateScore = 0;
|
113
|
+
for (const input of allAggregates[aggregateDimension].inputs) {
|
114
|
+
let currentScore = (_a = primitiveScores[input.dim]) != null ? _a : 0;
|
115
|
+
if (!currentScore) {
|
116
|
+
const aggRef = allAggregates[input.dim];
|
117
|
+
if (aggRef) {
|
118
|
+
if (visitedDimensions.has(input.dim)) {
|
119
|
+
continue;
|
120
|
+
}
|
121
|
+
const newVisited = new Set(visitedDimensions);
|
122
|
+
newVisited.add(input.dim);
|
123
|
+
currentScore = computeAggregateDimension(primitiveScores, input.dim, allAggregates, newVisited);
|
124
|
+
}
|
125
|
+
}
|
126
|
+
if (currentScore !== 0) {
|
127
|
+
if (input.sign === "c") {
|
128
|
+
aggregateScore = 0;
|
129
|
+
break;
|
130
|
+
} else if (input.sign === "-") {
|
131
|
+
aggregateScore -= currentScore;
|
132
|
+
} else {
|
133
|
+
aggregateScore += currentScore;
|
134
|
+
}
|
135
|
+
}
|
136
|
+
}
|
137
|
+
return aggregateScore;
|
138
|
+
}
|
139
|
+
|
140
|
+
// src/manifest/constants.ts
|
141
|
+
var ENR_SEPARATOR = "_";
|
142
|
+
|
143
|
+
// src/manifest/signals/SignalInstance.ts
|
144
|
+
var _evaluator, _onLogMessage;
|
145
|
+
var SignalInstance = class {
|
146
|
+
constructor(data, evaluator, onLogMessage) {
|
147
|
+
__privateAdd(this, _evaluator, void 0);
|
148
|
+
__privateAdd(this, _onLogMessage, void 0);
|
149
|
+
__publicField(this, "signal");
|
150
|
+
this.signal = data;
|
151
|
+
__privateSet(this, _evaluator, evaluator);
|
152
|
+
__privateSet(this, _onLogMessage, onLogMessage);
|
153
|
+
}
|
154
|
+
computeSignal(update, commands) {
|
155
|
+
const isAtCap = update.scores[this.signal.id] >= this.signal.cap;
|
156
|
+
if (isAtCap && this.signal.dur !== "t") {
|
157
|
+
return;
|
158
|
+
}
|
159
|
+
const criteriaMatchUpdate = __privateGet(this, _evaluator).evaluate(
|
160
|
+
update,
|
161
|
+
this.signal.crit,
|
162
|
+
commands,
|
163
|
+
this.signal,
|
164
|
+
__privateGet(this, _onLogMessage)
|
165
|
+
);
|
166
|
+
const scoreCommand = this.signal.dur === "s" || this.signal.dur === "t" ? "modscoreS" : "modscore";
|
167
|
+
if (!criteriaMatchUpdate.changed) {
|
168
|
+
return;
|
169
|
+
}
|
170
|
+
if (criteriaMatchUpdate.result) {
|
171
|
+
commands.push({
|
172
|
+
type: scoreCommand,
|
173
|
+
data: { dimension: this.signal.id, delta: this.signal.str }
|
174
|
+
});
|
175
|
+
} else if (this.signal.dur === "t") {
|
176
|
+
const sessionScore = update.visitor.sessionScores[this.signal.id];
|
177
|
+
if (sessionScore) {
|
178
|
+
commands.push({
|
179
|
+
type: scoreCommand,
|
180
|
+
data: { dimension: this.signal.id, delta: -sessionScore }
|
181
|
+
});
|
182
|
+
}
|
183
|
+
}
|
184
|
+
}
|
185
|
+
};
|
186
|
+
_evaluator = new WeakMap();
|
187
|
+
_onLogMessage = new WeakMap();
|
188
|
+
|
189
|
+
// src/manifest/ManifestInstance.ts
|
190
|
+
var _mf, _signalInstances, _onLogMessage2;
|
191
|
+
var ManifestInstance = class {
|
192
|
+
constructor({
|
193
|
+
manifest,
|
194
|
+
evaluator = new GroupCriteriaEvaluator({}),
|
195
|
+
onLogMessage = () => {
|
196
|
+
}
|
197
|
+
}) {
|
198
|
+
__publicField(this, "data");
|
199
|
+
__privateAdd(this, _mf, void 0);
|
200
|
+
__privateAdd(this, _signalInstances, void 0);
|
201
|
+
__privateAdd(this, _onLogMessage2, void 0);
|
202
|
+
var _a, _b, _c;
|
203
|
+
__privateSet(this, _mf, (_a = manifest.project) != null ? _a : {});
|
204
|
+
this.data = manifest;
|
205
|
+
__privateSet(this, _signalInstances, Object.entries((_c = (_b = __privateGet(this, _mf).pz) == null ? void 0 : _b.sig) != null ? _c : []).map(
|
206
|
+
([id, signal]) => new SignalInstance({ ...signal, id }, evaluator, onLogMessage)
|
207
|
+
));
|
208
|
+
__privateSet(this, _onLogMessage2, onLogMessage);
|
209
|
+
}
|
210
|
+
rollForControlGroup() {
|
211
|
+
var _a, _b;
|
212
|
+
return Math.random() < ((_b = (_a = __privateGet(this, _mf).pz) == null ? void 0 : _a.control) != null ? _b : 0);
|
213
|
+
}
|
214
|
+
getTest(name) {
|
215
|
+
var _a;
|
216
|
+
return (_a = __privateGet(this, _mf).test) == null ? void 0 : _a[name];
|
217
|
+
}
|
218
|
+
computeSignals(update) {
|
219
|
+
const commands = [];
|
220
|
+
__privateGet(this, _onLogMessage2).call(this, ["debug", 200, "GROUP"]);
|
221
|
+
try {
|
222
|
+
__privateGet(this, _signalInstances).forEach((signal) => {
|
223
|
+
__privateGet(this, _onLogMessage2).call(this, ["debug", 201, "GROUP", signal.signal]);
|
224
|
+
try {
|
225
|
+
signal.computeSignal(update, commands);
|
226
|
+
} finally {
|
227
|
+
__privateGet(this, _onLogMessage2).call(this, ["debug", 201, "ENDGROUP"]);
|
228
|
+
}
|
229
|
+
});
|
230
|
+
} finally {
|
231
|
+
__privateGet(this, _onLogMessage2).call(this, ["debug", 200, "ENDGROUP"]);
|
232
|
+
}
|
233
|
+
return commands;
|
234
|
+
}
|
235
|
+
computeAggregateDimensions(primitiveScores) {
|
236
|
+
var _a, _b;
|
237
|
+
return computeAggregateDimensions(primitiveScores, (_b = (_a = __privateGet(this, _mf).pz) == null ? void 0 : _a.agg) != null ? _b : {});
|
238
|
+
}
|
239
|
+
getDimensionByKey(scoreKey) {
|
240
|
+
var _a, _b, _c, _d;
|
241
|
+
const enrichmentIndex = scoreKey.indexOf(ENR_SEPARATOR);
|
242
|
+
if (enrichmentIndex <= 0) {
|
243
|
+
return (_b = (_a = __privateGet(this, _mf).pz) == null ? void 0 : _a.sig) == null ? void 0 : _b[scoreKey];
|
244
|
+
}
|
245
|
+
return (_d = (_c = __privateGet(this, _mf).pz) == null ? void 0 : _c.enr) == null ? void 0 : _d[scoreKey.substring(0, enrichmentIndex)];
|
246
|
+
}
|
247
|
+
};
|
248
|
+
_mf = new WeakMap();
|
249
|
+
_signalInstances = new WeakMap();
|
250
|
+
_onLogMessage2 = new WeakMap();
|
251
|
+
|
252
|
+
// src/manifest/signals/criteria/evaluators/cookieEvaluator.ts
|
253
|
+
var import_lite = require("dequal/lite");
|
254
|
+
|
255
|
+
// src/manifest/signals/criteria/util/isStringMatch.ts
|
256
|
+
function isStringMatch(lhs, match) {
|
257
|
+
var _a, _b, _c, _d, _e, _f;
|
258
|
+
const type = (_a = match == null ? void 0 : match.op) != null ? _a : "=";
|
259
|
+
if (match.op === "*") {
|
260
|
+
return lhs !== null && typeof lhs !== "undefined";
|
261
|
+
}
|
262
|
+
if (match.op === "!*") {
|
263
|
+
return lhs === null || typeof lhs === "undefined";
|
264
|
+
}
|
265
|
+
if (!("rhs" in match)) {
|
266
|
+
throw new Error(`Match expression is required for match type ${type}`);
|
267
|
+
}
|
268
|
+
const caseSensitive = (_b = match.cs) != null ? _b : false;
|
269
|
+
const localRhs = (caseSensitive ? lhs != null ? lhs : "" : caseDesensitize(lhs)).toString();
|
270
|
+
const localLhs = (caseSensitive ? match.rhs : caseDesensitize(match.rhs)).toString();
|
271
|
+
switch (type) {
|
272
|
+
case "=":
|
273
|
+
return localRhs === localLhs;
|
274
|
+
case "!=":
|
275
|
+
return localRhs !== localLhs;
|
276
|
+
case "~":
|
277
|
+
return (_c = localRhs.includes(localLhs)) != null ? _c : false;
|
278
|
+
case "!~":
|
279
|
+
return !((_d = localRhs.includes(localLhs)) != null ? _d : true);
|
280
|
+
case "//":
|
281
|
+
return new RegExp(match.rhs.toString(), caseSensitive ? "" : "i").test((_e = lhs == null ? void 0 : lhs.toString()) != null ? _e : "");
|
282
|
+
case "!//":
|
283
|
+
return !new RegExp(match.rhs.toString(), caseSensitive ? "" : "i").test((_f = lhs == null ? void 0 : lhs.toString()) != null ? _f : "");
|
284
|
+
default:
|
285
|
+
throw new Error(`Unknown match type ${type}.`);
|
286
|
+
}
|
287
|
+
}
|
288
|
+
function explainStringMatch(lhs, match) {
|
289
|
+
const cs = "cs" in match ? match.cs : false;
|
290
|
+
return `'${cs ? lhs : lhs == null ? void 0 : lhs.toString().toUpperCase()}' ${explainStringMatchCriteria(match)}`;
|
291
|
+
}
|
292
|
+
function explainStringMatchCriteria(match) {
|
293
|
+
if ("rhs" in match) {
|
294
|
+
return `${match.op} '${match.cs ? match.rhs : match.rhs.toString().toUpperCase()}'`;
|
295
|
+
}
|
296
|
+
return `${match.op === "*" ? "exists" : "does not exist"}`;
|
297
|
+
}
|
298
|
+
function caseDesensitize(value) {
|
299
|
+
var _a, _b;
|
300
|
+
return (_b = (_a = value == null ? void 0 : value.toString()) == null ? void 0 : _a.toUpperCase()) != null ? _b : "";
|
301
|
+
}
|
302
|
+
|
303
|
+
// src/manifest/signals/criteria/evaluators/cookieEvaluator.ts
|
304
|
+
var cookieEvaluator = ({ update, criteria, onLogMessage }) => {
|
305
|
+
var _a, _b;
|
306
|
+
if (criteria.type !== "CK") {
|
307
|
+
return { result: false, changed: false };
|
308
|
+
}
|
309
|
+
const changed = !(0, import_lite.dequal)(cleanCookies(update.state.cookies), cleanCookies((_a = update.previousState) == null ? void 0 : _a.cookies));
|
310
|
+
const value = (_b = update.state.cookies) == null ? void 0 : _b[criteria.cookieName];
|
311
|
+
const result = isStringMatch(value, criteria.match);
|
312
|
+
const finalResult = { result, changed };
|
313
|
+
onLogMessage == null ? void 0 : onLogMessage([
|
314
|
+
"debug",
|
315
|
+
203,
|
316
|
+
{ criteria, result: finalResult, explanation: explainStringMatch(value, criteria.match) }
|
317
|
+
]);
|
318
|
+
return finalResult;
|
319
|
+
};
|
320
|
+
function cleanCookies(cookie) {
|
321
|
+
if (!cookie) {
|
322
|
+
return void 0;
|
323
|
+
}
|
324
|
+
if (!cookie.ufvd) {
|
325
|
+
return cookie;
|
326
|
+
}
|
327
|
+
const { ufvd, ...rest } = cookie;
|
328
|
+
return rest;
|
329
|
+
}
|
330
|
+
|
331
|
+
// src/manifest/signals/criteria/evaluators/currentPageEvaluator.ts
|
332
|
+
var currentPageEvaluator = ({ update, criteria, onLogMessage }) => {
|
333
|
+
var _a, _b, _c;
|
334
|
+
if (criteria.type !== "PV") {
|
335
|
+
return { result: false, changed: false };
|
336
|
+
}
|
337
|
+
const value = (_a = update.state.url) == null ? void 0 : _a.pathname;
|
338
|
+
const hasUrlChanged = !update.previousState || (value == null ? void 0 : value.toString()) !== ((_c = (_b = update.previousState.url) == null ? void 0 : _b.pathname) == null ? void 0 : _c.toString());
|
339
|
+
const result = isStringMatch(value, criteria.path);
|
340
|
+
const finalResult = { result, changed: hasUrlChanged };
|
341
|
+
onLogMessage == null ? void 0 : onLogMessage([
|
342
|
+
"debug",
|
343
|
+
203,
|
344
|
+
{ criteria, result: finalResult, explanation: explainStringMatch(value, criteria.path) }
|
345
|
+
]);
|
346
|
+
return finalResult;
|
347
|
+
};
|
348
|
+
|
349
|
+
// src/manifest/signals/criteria/evaluators/eventEvaluator.ts
|
350
|
+
var eventEvaluator = ({ update, criteria, onLogMessage }) => {
|
351
|
+
var _a, _b, _c;
|
352
|
+
if (criteria.type !== "EVT") {
|
353
|
+
return { result: false, changed: false };
|
354
|
+
}
|
355
|
+
const result = (_b = (_a = update.state.events) == null ? void 0 : _a.some((event) => isStringMatch(event.event, criteria.event))) != null ? _b : false;
|
356
|
+
const finalResult = { result, changed: result };
|
357
|
+
onLogMessage == null ? void 0 : onLogMessage([
|
358
|
+
"debug",
|
359
|
+
203,
|
360
|
+
{
|
361
|
+
criteria,
|
362
|
+
result: finalResult,
|
363
|
+
explanation: `'${(_c = update.state.events) == null ? void 0 : _c.join("', '")}' ${explainStringMatchCriteria(criteria.event)}`
|
364
|
+
}
|
365
|
+
]);
|
366
|
+
return finalResult;
|
367
|
+
};
|
368
|
+
|
369
|
+
// src/manifest/utils/getEnrichmentVectorKey.ts
|
370
|
+
function getEnrichmentVectorKey(category, value) {
|
371
|
+
return `${category}${ENR_SEPARATOR}${value}`;
|
372
|
+
}
|
373
|
+
|
374
|
+
// src/manifest/signals/criteria/util/isNumberMatch.ts
|
375
|
+
function isNumberMatch(lhs, match) {
|
376
|
+
var _a;
|
377
|
+
if (typeof lhs === "undefined" || lhs === null) {
|
378
|
+
return false;
|
379
|
+
}
|
380
|
+
const lhsValue = Number(lhs);
|
381
|
+
if (isNaN(lhsValue)) {
|
382
|
+
return false;
|
383
|
+
}
|
384
|
+
switch ((_a = match == null ? void 0 : match.op) != null ? _a : "=") {
|
385
|
+
case "=":
|
386
|
+
return lhsValue === match.rhs;
|
387
|
+
case "!=":
|
388
|
+
return lhsValue !== match.rhs;
|
389
|
+
case ">":
|
390
|
+
return lhsValue > match.rhs;
|
391
|
+
case "<":
|
392
|
+
return lhsValue < match.rhs;
|
393
|
+
default:
|
394
|
+
console.warn(`Unknown match type ${match.op} is false.`);
|
395
|
+
return false;
|
396
|
+
}
|
397
|
+
}
|
398
|
+
function explainNumberMatch(lhs, match) {
|
399
|
+
return `${lhs} ${explainNumberMatchCriteria(match)}`;
|
400
|
+
}
|
401
|
+
function explainNumberMatchCriteria(match) {
|
402
|
+
return `${match.op} ${match.rhs}`;
|
403
|
+
}
|
404
|
+
|
405
|
+
// src/manifest/signals/criteria/evaluators/pageViewCountEvaluator.ts
|
406
|
+
var pageViewCountDimension = getEnrichmentVectorKey("$pvc", "v");
|
407
|
+
var pageViewCountEvaluator = ({ update, criteria, commands, onLogMessage }) => {
|
408
|
+
var _a, _b;
|
409
|
+
if (criteria.type !== "PVC") {
|
410
|
+
return { result: false, changed: false };
|
411
|
+
}
|
412
|
+
const hasUrlChanged = Boolean(
|
413
|
+
update.state.url && (!update.previousState || ((_a = update.state.url) == null ? void 0 : _a.toString()) !== ((_b = update.previousState.url) == null ? void 0 : _b.toString()))
|
414
|
+
);
|
415
|
+
const existingValueNumber = update.visitor.sessionScores[pageViewCountDimension] || 0;
|
416
|
+
const updatedCount = existingValueNumber + 1;
|
417
|
+
const finalResult = { result: false, changed: hasUrlChanged };
|
418
|
+
const hasExistingPageViewIncrementCommand = commands.some(
|
419
|
+
(c) => c.type === "modscoreS" && c.data.dimension === pageViewCountDimension
|
420
|
+
);
|
421
|
+
if (hasUrlChanged && !hasExistingPageViewIncrementCommand) {
|
422
|
+
commands.push({
|
423
|
+
type: "modscoreS",
|
424
|
+
data: {
|
425
|
+
dimension: pageViewCountDimension,
|
426
|
+
delta: 1
|
427
|
+
}
|
428
|
+
});
|
429
|
+
}
|
430
|
+
if (isNumberMatch(updatedCount, criteria.match)) {
|
431
|
+
finalResult.result = true;
|
432
|
+
}
|
433
|
+
onLogMessage == null ? void 0 : onLogMessage([
|
434
|
+
"debug",
|
435
|
+
203,
|
436
|
+
{ criteria, result: finalResult, explanation: explainNumberMatch(updatedCount, criteria.match) }
|
437
|
+
]);
|
438
|
+
return finalResult;
|
439
|
+
};
|
440
|
+
pageViewCountEvaluator.alwaysExecute = true;
|
441
|
+
|
442
|
+
// src/manifest/signals/criteria/evaluators/queryStringEvaluator.ts
|
443
|
+
var queryStringEvaluator = ({ update, criteria, onLogMessage }) => {
|
444
|
+
var _a, _b, _c, _d, _e;
|
445
|
+
if (criteria.type !== "QS") {
|
446
|
+
return { result: false, changed: false };
|
447
|
+
}
|
448
|
+
const hasQueryChanged = !update.previousState || ((_b = (_a = update.state.url) == null ? void 0 : _a.searchParams) == null ? void 0 : _b.toString()) !== ((_d = (_c = update.previousState.url) == null ? void 0 : _c.searchParams) == null ? void 0 : _d.toString());
|
449
|
+
const value = (_e = update.state.url) == null ? void 0 : _e.searchParams.get(criteria.queryName);
|
450
|
+
const result = isStringMatch(value, criteria.match);
|
451
|
+
const finalResult = { result, changed: hasQueryChanged };
|
452
|
+
onLogMessage == null ? void 0 : onLogMessage([
|
453
|
+
"debug",
|
454
|
+
203,
|
455
|
+
{ criteria, result: finalResult, explanation: explainStringMatch(value, criteria.match) }
|
456
|
+
]);
|
457
|
+
return finalResult;
|
458
|
+
};
|
459
|
+
|
460
|
+
// src/manifest/signals/criteria/evaluators/quirkEvaluator.ts
|
461
|
+
var quirkEvaluator = ({ update, criteria, signal, onLogMessage }) => {
|
462
|
+
var _a;
|
463
|
+
if (criteria.type !== "QK") {
|
464
|
+
return { result: false, changed: false };
|
465
|
+
}
|
466
|
+
if (typeof document === "undefined" && update.scores[signal.id] > 0) {
|
467
|
+
return { result: true, changed: false };
|
468
|
+
}
|
469
|
+
const visitorValue = update.visitor.quirks[criteria.key];
|
470
|
+
const updateValue = (_a = update.state.quirks) == null ? void 0 : _a[criteria.key];
|
471
|
+
const value = updateValue != null ? updateValue : visitorValue;
|
472
|
+
const changed = Boolean(updateValue && visitorValue !== updateValue);
|
473
|
+
const result = isStringMatch(value, criteria.match);
|
474
|
+
const finalResult = { result, changed };
|
475
|
+
onLogMessage == null ? void 0 : onLogMessage([
|
476
|
+
"debug",
|
477
|
+
203,
|
478
|
+
{ criteria, result: finalResult, explanation: explainStringMatch(value, criteria.match) }
|
479
|
+
]);
|
480
|
+
return finalResult;
|
481
|
+
};
|
482
|
+
|
483
|
+
// src/manifest/signals/criteria/GroupCriteriaEvaluator.ts
|
484
|
+
var _evaluators;
|
485
|
+
var GroupCriteriaEvaluator = class {
|
486
|
+
constructor(criteriaEvaluators) {
|
487
|
+
__privateAdd(this, _evaluators, void 0);
|
488
|
+
__privateSet(this, _evaluators, criteriaEvaluators);
|
489
|
+
}
|
490
|
+
evaluate(update, crit, commands, signal, onLogMessage) {
|
491
|
+
const hasMultipleClauses = crit.clauses.length > 1;
|
492
|
+
if (hasMultipleClauses) {
|
493
|
+
onLogMessage == null ? void 0 : onLogMessage(["debug", 202, "GROUP", crit]);
|
494
|
+
}
|
495
|
+
try {
|
496
|
+
const earlyExitEvaluatorResult = crit.op === "&" || !crit.op ? false : true;
|
497
|
+
let earlyExitResult = null;
|
498
|
+
let isAnyChanged = false;
|
499
|
+
for (const criteria of crit.clauses) {
|
500
|
+
let result;
|
501
|
+
if (criteria.type === "G") {
|
502
|
+
result = this.evaluate(update, criteria, commands, signal, onLogMessage);
|
503
|
+
} else {
|
504
|
+
const evaluator = __privateGet(this, _evaluators)[criteria.type];
|
505
|
+
if (earlyExitResult && !evaluator.alwaysExecute) {
|
506
|
+
continue;
|
507
|
+
}
|
508
|
+
if (!evaluator) {
|
509
|
+
throw new Error(`${criteria.type} signal criteria not registered`);
|
510
|
+
}
|
511
|
+
result = evaluator({ update, criteria, commands, signal, onLogMessage });
|
512
|
+
}
|
513
|
+
if (result.changed) {
|
514
|
+
isAnyChanged = true;
|
515
|
+
}
|
516
|
+
if (!earlyExitResult && result.result === earlyExitEvaluatorResult) {
|
517
|
+
earlyExitResult = { result: earlyExitEvaluatorResult, changed: isAnyChanged };
|
518
|
+
}
|
519
|
+
}
|
520
|
+
const finalResult = earlyExitResult != null ? earlyExitResult : { result: !earlyExitEvaluatorResult, changed: isAnyChanged };
|
521
|
+
if (hasMultipleClauses) {
|
522
|
+
onLogMessage == null ? void 0 : onLogMessage(["debug", 204, finalResult]);
|
523
|
+
}
|
524
|
+
return finalResult;
|
525
|
+
} finally {
|
526
|
+
if (hasMultipleClauses) {
|
527
|
+
onLogMessage == null ? void 0 : onLogMessage(["debug", 202, "ENDGROUP"]);
|
528
|
+
}
|
529
|
+
}
|
530
|
+
}
|
531
|
+
};
|
532
|
+
_evaluators = new WeakMap();
|
533
|
+
|
534
|
+
// src/placement/criteria/evaluateVariantMatch.ts
|
535
|
+
function evaluateVariantMatch(variantId, match, vec, onLogMessage) {
|
536
|
+
onLogMessage == null ? void 0 : onLogMessage(["info", 301, "GROUP", { id: variantId, op: match == null ? void 0 : match.op }]);
|
537
|
+
let result;
|
538
|
+
try {
|
539
|
+
if (!(match == null ? void 0 : match.crit)) {
|
540
|
+
onLogMessage == null ? void 0 : onLogMessage(["info", 302, { matched: true, description: "default variation" }]);
|
541
|
+
result = true;
|
542
|
+
} else if (!match.op || match.op === "&") {
|
543
|
+
result = match.crit.every((c) => evaluateDimensionMatch(c, vec, onLogMessage));
|
544
|
+
} else {
|
545
|
+
result = match.crit.some((c) => evaluateDimensionMatch(c, vec, onLogMessage));
|
546
|
+
}
|
547
|
+
onLogMessage == null ? void 0 : onLogMessage(["info", 303, result]);
|
548
|
+
} finally {
|
549
|
+
onLogMessage == null ? void 0 : onLogMessage(["info", 301, "ENDGROUP"]);
|
550
|
+
}
|
551
|
+
return result;
|
552
|
+
}
|
553
|
+
function evaluateDimensionMatch(crit, vec, onLogMessage) {
|
554
|
+
var _a, _b;
|
555
|
+
const { op, l: lhs } = crit;
|
556
|
+
const lhsScore = (_a = vec[lhs]) != null ? _a : 0;
|
557
|
+
if (op === "+") {
|
558
|
+
const result = Math.max(...Object.values(vec)) === lhsScore && lhsScore > 0;
|
559
|
+
onLogMessage == null ? void 0 : onLogMessage([
|
560
|
+
"info",
|
561
|
+
302,
|
562
|
+
{
|
563
|
+
matched: result,
|
564
|
+
description: `${crit.l} has the highest score`
|
565
|
+
}
|
566
|
+
]);
|
567
|
+
return result;
|
568
|
+
} else if (op === "-") {
|
569
|
+
const result = Math.min(...Object.values(vec)) === lhsScore && lhsScore > 0;
|
570
|
+
onLogMessage == null ? void 0 : onLogMessage([
|
571
|
+
"info",
|
572
|
+
302,
|
573
|
+
{
|
574
|
+
matched: result,
|
575
|
+
description: `${crit.l} has the lowest non-zero score`
|
576
|
+
}
|
577
|
+
]);
|
578
|
+
return result;
|
579
|
+
}
|
580
|
+
let rhsScore;
|
581
|
+
if (crit.rDim) {
|
582
|
+
rhsScore = vec[crit.rDim] || 0;
|
583
|
+
} else {
|
584
|
+
rhsScore = parseInt(crit.r, 10);
|
585
|
+
}
|
586
|
+
if (isNaN(rhsScore)) {
|
587
|
+
onLogMessage == null ? void 0 : onLogMessage([
|
588
|
+
"info",
|
589
|
+
302,
|
590
|
+
{
|
591
|
+
matched: false,
|
592
|
+
description: `${(_b = crit.rDim) != null ? _b : crit.r} has no score value`
|
593
|
+
}
|
594
|
+
]);
|
595
|
+
return false;
|
596
|
+
}
|
597
|
+
if (op === ">") {
|
598
|
+
const result = lhsScore > rhsScore;
|
599
|
+
explain(onLogMessage, result, crit, lhsScore, rhsScore);
|
600
|
+
return result;
|
601
|
+
} else if (op === ">=") {
|
602
|
+
const result = lhsScore >= rhsScore;
|
603
|
+
explain(onLogMessage, result, crit, lhsScore, rhsScore);
|
604
|
+
return result;
|
605
|
+
} else if (op === "<") {
|
606
|
+
const result = lhsScore < rhsScore;
|
607
|
+
explain(onLogMessage, result, crit, lhsScore, rhsScore);
|
608
|
+
return result;
|
609
|
+
} else if (op === "<=") {
|
610
|
+
const result = lhsScore <= rhsScore;
|
611
|
+
explain(onLogMessage, result, crit, lhsScore, rhsScore);
|
612
|
+
return result;
|
613
|
+
} else if (op === "=") {
|
614
|
+
const result = lhsScore === rhsScore;
|
615
|
+
explain(onLogMessage, result, crit, lhsScore, rhsScore);
|
616
|
+
return result;
|
617
|
+
} else if (op === "!=") {
|
618
|
+
const result = lhsScore !== rhsScore;
|
619
|
+
explain(onLogMessage, result, crit, lhsScore, rhsScore);
|
620
|
+
return result;
|
621
|
+
} else {
|
622
|
+
throw new Error(`Unknown op: ${op}`);
|
623
|
+
}
|
624
|
+
}
|
625
|
+
function explain(onLogMessage, result, crit, lhsScore, rhsScore) {
|
626
|
+
onLogMessage == null ? void 0 : onLogMessage([
|
627
|
+
"info",
|
628
|
+
302,
|
629
|
+
{
|
630
|
+
matched: result,
|
631
|
+
description: `${crit.l}[${lhsScore}] ${crit.op} ${crit.rDim ? `${crit.rDim}[${rhsScore}]` : crit.r}`
|
632
|
+
}
|
633
|
+
]);
|
634
|
+
}
|
635
|
+
|
636
|
+
// src/placement/personalize.ts
|
637
|
+
function personalizeVariations({
|
638
|
+
name,
|
639
|
+
context,
|
640
|
+
variations,
|
641
|
+
take = 1,
|
642
|
+
onLogMessage
|
643
|
+
}) {
|
644
|
+
var _a, _b, _c;
|
645
|
+
onLogMessage == null ? void 0 : onLogMessage(["info", 300, "GROUP", { name, take }]);
|
646
|
+
try {
|
647
|
+
const control = (_a = context.storage.data.controlGroup) != null ? _a : false;
|
648
|
+
const results = [];
|
649
|
+
let personalized = false;
|
650
|
+
const scores = context.scores;
|
651
|
+
for (const variant of variations) {
|
652
|
+
if (results.length === take) {
|
653
|
+
break;
|
654
|
+
}
|
655
|
+
if (!((_b = variant.pz) == null ? void 0 : _b.crit.length)) {
|
656
|
+
onLogMessage == null ? void 0 : onLogMessage(["info", 301, "GROUP", { id: variant.id, op: (_c = variant.pz) == null ? void 0 : _c.op }]);
|
657
|
+
onLogMessage == null ? void 0 : onLogMessage(["info", 302, { matched: true, description: "default variation" }]);
|
658
|
+
onLogMessage == null ? void 0 : onLogMessage(["info", 303, true]);
|
659
|
+
onLogMessage == null ? void 0 : onLogMessage(["info", 301, "ENDGROUP"]);
|
660
|
+
results.push(variant);
|
661
|
+
continue;
|
662
|
+
}
|
663
|
+
if (control) {
|
664
|
+
continue;
|
665
|
+
}
|
666
|
+
if (evaluateVariantMatch(variant.id, variant.pz, scores, onLogMessage)) {
|
667
|
+
personalized = true;
|
668
|
+
results.push(variant);
|
669
|
+
}
|
670
|
+
}
|
671
|
+
return {
|
672
|
+
personalized,
|
673
|
+
variations: results
|
674
|
+
};
|
675
|
+
} finally {
|
676
|
+
onLogMessage == null ? void 0 : onLogMessage(["info", 300, "ENDGROUP"]);
|
677
|
+
}
|
678
|
+
}
|
679
|
+
|
680
|
+
// src/placement/test.ts
|
681
|
+
var normalizeVariationDistributions = (variations) => {
|
682
|
+
const { values, total, missingDistribution } = variations.reduce(
|
683
|
+
(previous, current) => {
|
684
|
+
if (current.testDistribution) {
|
685
|
+
previous.total += current.testDistribution;
|
686
|
+
} else {
|
687
|
+
++previous.missingDistribution;
|
688
|
+
}
|
689
|
+
previous.values.push(current.testDistribution);
|
690
|
+
return previous;
|
691
|
+
},
|
692
|
+
{
|
693
|
+
values: [],
|
694
|
+
total: 0,
|
695
|
+
missingDistribution: 0
|
696
|
+
}
|
697
|
+
);
|
698
|
+
if (total > 100) {
|
699
|
+
throw new Error(`Total distribution ${total} is over the maximum 100.`);
|
700
|
+
} else if (total < 100) {
|
701
|
+
const remainder = 100 - total;
|
702
|
+
const missingSlice = remainder / missingDistribution;
|
703
|
+
values.forEach((value, index) => {
|
704
|
+
if (typeof value === "undefined") {
|
705
|
+
values[index] = missingSlice;
|
706
|
+
}
|
707
|
+
});
|
708
|
+
}
|
709
|
+
return values;
|
710
|
+
};
|
711
|
+
var testVariations = ({
|
712
|
+
name,
|
713
|
+
context,
|
714
|
+
variations,
|
715
|
+
onLogMessage
|
716
|
+
}) => {
|
717
|
+
onLogMessage == null ? void 0 : onLogMessage(["info", 400, "GROUP", name]);
|
718
|
+
try {
|
719
|
+
let selectedVariant;
|
720
|
+
const selectedVariantId = context.getTestVariantId(name);
|
721
|
+
if (selectedVariantId === null) {
|
722
|
+
onLogMessage == null ? void 0 : onLogMessage(["error", 401, name]);
|
723
|
+
return { result: void 0, variantAssigned: false };
|
724
|
+
}
|
725
|
+
if (selectedVariantId) {
|
726
|
+
selectedVariant = variations.find((variation) => variation.id === selectedVariantId);
|
727
|
+
if (!selectedVariant) {
|
728
|
+
onLogMessage == null ? void 0 : onLogMessage([
|
729
|
+
"warn",
|
730
|
+
402,
|
731
|
+
{ missingVariant: selectedVariantId, variants: variations.map((v) => v.id) }
|
732
|
+
]);
|
733
|
+
}
|
734
|
+
}
|
735
|
+
if (!selectedVariant) {
|
736
|
+
const distributions = normalizeVariationDistributions(variations);
|
737
|
+
const random = Math.floor(Math.random() * 100);
|
738
|
+
let distributionOffset = 0;
|
739
|
+
selectedVariant = variations.find((variant, index) => {
|
740
|
+
const distribution = distributions[index];
|
741
|
+
if (random > distributionOffset && random <= distributionOffset + distribution) {
|
742
|
+
return variant;
|
743
|
+
}
|
744
|
+
distributionOffset += distribution;
|
745
|
+
});
|
746
|
+
if (selectedVariant) {
|
747
|
+
onLogMessage == null ? void 0 : onLogMessage(["info", 403, selectedVariant.id]);
|
748
|
+
context.setTestVariantId(name, selectedVariant.id);
|
749
|
+
}
|
750
|
+
}
|
751
|
+
if (selectedVariant) {
|
752
|
+
onLogMessage == null ? void 0 : onLogMessage(["info", 404, selectedVariant.id]);
|
753
|
+
}
|
754
|
+
return {
|
755
|
+
result: selectedVariant,
|
756
|
+
variantAssigned: !selectedVariantId
|
757
|
+
};
|
758
|
+
} finally {
|
759
|
+
onLogMessage == null ? void 0 : onLogMessage(["info", 400, "ENDGROUP"]);
|
760
|
+
}
|
761
|
+
};
|
762
|
+
|
763
|
+
// src/storage/CookieTransitionDataStore.ts
|
764
|
+
var import_js_cookie = __toESM(require("js-cookie"));
|
765
|
+
|
766
|
+
// src/storage/TransitionDataStore.ts
|
767
|
+
var import_lite2 = require("dequal/lite");
|
768
|
+
var import_mitt = __toESM(require("mitt"));
|
769
|
+
var SERVER_STATE_ID = "__UNIFORM_DATA__";
|
770
|
+
var _data, _initialData, _mitt;
|
771
|
+
var TransitionDataStore = class {
|
772
|
+
constructor({ initialData }) {
|
773
|
+
__privateAdd(this, _data, void 0);
|
774
|
+
__privateAdd(this, _initialData, void 0);
|
775
|
+
__privateAdd(this, _mitt, (0, import_mitt.default)());
|
776
|
+
__publicField(this, "events", {
|
777
|
+
on: __privateGet(this, _mitt).on,
|
778
|
+
off: __privateGet(this, _mitt).off
|
779
|
+
});
|
780
|
+
if (initialData) {
|
781
|
+
__privateSet(this, _data, initialData);
|
782
|
+
__privateSet(this, _initialData, initialData);
|
783
|
+
}
|
784
|
+
}
|
785
|
+
get data() {
|
786
|
+
return __privateGet(this, _data);
|
787
|
+
}
|
788
|
+
get initialData() {
|
789
|
+
return __privateGet(this, _initialData);
|
790
|
+
}
|
791
|
+
updateData(commands, computedValue) {
|
792
|
+
__privateSet(this, _data, computedValue);
|
793
|
+
return this.handleUpdateData(commands, computedValue);
|
794
|
+
}
|
795
|
+
async delete(fromAllDevices) {
|
796
|
+
__privateSet(this, _data, void 0);
|
797
|
+
await this.handleDelete(fromAllDevices);
|
798
|
+
}
|
799
|
+
signalAsyncDataUpdate(newScores) {
|
800
|
+
if ((0, import_lite2.dequal)(this.data, newScores)) {
|
801
|
+
return;
|
802
|
+
}
|
803
|
+
__privateSet(this, _data, newScores);
|
804
|
+
__privateGet(this, _mitt).emit("dataUpdatedAsync", newScores);
|
805
|
+
}
|
806
|
+
getClientTransitionState() {
|
807
|
+
if (typeof document === "undefined") {
|
808
|
+
return;
|
809
|
+
}
|
810
|
+
const matchesElement = document.getElementById(SERVER_STATE_ID);
|
811
|
+
return (matchesElement == null ? void 0 : matchesElement.textContent) ? JSON.parse(matchesElement.textContent) : void 0;
|
812
|
+
}
|
813
|
+
};
|
814
|
+
_data = new WeakMap();
|
815
|
+
_initialData = new WeakMap();
|
816
|
+
_mitt = new WeakMap();
|
817
|
+
|
818
|
+
// src/storage/util/numberToBase64.ts
|
819
|
+
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
820
|
+
var b2s = alphabet.split("");
|
821
|
+
var s2b = new Array(123);
|
822
|
+
for (let i = 0; i < alphabet.length; i++) {
|
823
|
+
s2b[alphabet.charCodeAt(i)] = i;
|
824
|
+
}
|
825
|
+
var ntob = (number) => {
|
826
|
+
if (number < 0)
|
827
|
+
return `-${ntob(-number)}`;
|
828
|
+
let lo = number >>> 0;
|
829
|
+
let hi = number / 4294967296 >>> 0;
|
830
|
+
let right = "";
|
831
|
+
while (hi > 0) {
|
832
|
+
right = b2s[63 & lo] + right;
|
833
|
+
lo >>>= 6;
|
834
|
+
lo |= (63 & hi) << 26;
|
835
|
+
hi >>>= 6;
|
836
|
+
}
|
837
|
+
let left = "";
|
838
|
+
do {
|
839
|
+
left = b2s[63 & lo] + left;
|
840
|
+
lo >>>= 6;
|
841
|
+
} while (lo > 0);
|
842
|
+
return left + right;
|
843
|
+
};
|
844
|
+
var bton = (base64) => {
|
845
|
+
let number = 0;
|
846
|
+
const sign = base64.charAt(0) === "-" ? 1 : 0;
|
847
|
+
for (let i = sign; i < base64.length; i++) {
|
848
|
+
number = number * 64 + s2b[base64.charCodeAt(i)];
|
849
|
+
}
|
850
|
+
return sign ? -number : number;
|
851
|
+
};
|
852
|
+
|
853
|
+
// src/storage/CookieTransitionDataStore.ts
|
854
|
+
var ssr = typeof document === "undefined";
|
855
|
+
var UNIFORM_DEFAULT_COOKIE_NAME = "ufvd";
|
856
|
+
var _cookieName, _cookieAttributes;
|
857
|
+
var CookieTransitionDataStore = class extends TransitionDataStore {
|
858
|
+
constructor({
|
859
|
+
serverCookieValue,
|
860
|
+
cookieName = UNIFORM_DEFAULT_COOKIE_NAME,
|
861
|
+
cookieAttributes = { sameSite: "lax" }
|
862
|
+
}) {
|
863
|
+
super({
|
864
|
+
initialData: ssr ? parseScoreCookie(serverCookieValue) : void 0
|
865
|
+
});
|
866
|
+
__privateAdd(this, _cookieName, void 0);
|
867
|
+
__privateAdd(this, _cookieAttributes, void 0);
|
868
|
+
__privateSet(this, _cookieName, cookieName);
|
869
|
+
__privateSet(this, _cookieAttributes, cookieAttributes);
|
870
|
+
}
|
871
|
+
handleDelete() {
|
872
|
+
if (ssr)
|
873
|
+
return Promise.resolve();
|
874
|
+
import_js_cookie.default.remove(__privateGet(this, _cookieName));
|
875
|
+
return Promise.resolve();
|
876
|
+
}
|
877
|
+
async handleUpdateData(_, computedValue) {
|
878
|
+
if (ssr)
|
879
|
+
return;
|
880
|
+
if (computedValue.consent) {
|
881
|
+
import_js_cookie.default.set(__privateGet(this, _cookieName), serializeCookie(computedValue), __privateGet(this, _cookieAttributes));
|
882
|
+
} else {
|
883
|
+
import_js_cookie.default.remove(__privateGet(this, _cookieName));
|
884
|
+
}
|
885
|
+
}
|
886
|
+
};
|
887
|
+
_cookieName = new WeakMap();
|
888
|
+
_cookieAttributes = new WeakMap();
|
889
|
+
var TYPE_SEP = "~";
|
890
|
+
var PAIR_SEP = "!";
|
891
|
+
var KV_SEP = "-";
|
892
|
+
function parseScoreCookie(cookieValue) {
|
893
|
+
if (!cookieValue)
|
894
|
+
return;
|
895
|
+
const types = cookieValue.split(TYPE_SEP);
|
896
|
+
if (types.length > 3)
|
897
|
+
return;
|
898
|
+
const [abTestData, sessionScores, visitorScores] = types;
|
899
|
+
return {
|
900
|
+
consent: true,
|
901
|
+
sessionScores: decodeCookieType(parseCookieType(sessionScores)),
|
902
|
+
scores: decodeCookieType(parseCookieType(visitorScores)),
|
903
|
+
tests: parseCookieType(abTestData)
|
904
|
+
};
|
905
|
+
}
|
906
|
+
function parseCookieType(type) {
|
907
|
+
const pairs = type.split(PAIR_SEP).map((pair) => pair.split(KV_SEP));
|
908
|
+
return pairs.reduce((acc, cur) => {
|
909
|
+
if (cur.length < 2)
|
910
|
+
return acc;
|
911
|
+
acc[cur[0]] = cur.slice(1).join("-");
|
912
|
+
return acc;
|
913
|
+
}, {});
|
914
|
+
}
|
915
|
+
function decodeCookieType(type) {
|
916
|
+
return Object.entries(type).reduce((acc, [key, value]) => {
|
917
|
+
acc[key] = bton(value);
|
918
|
+
return acc;
|
919
|
+
}, {});
|
920
|
+
}
|
921
|
+
function serializeCookie(data) {
|
922
|
+
return [
|
923
|
+
serializeCookieType(data.tests),
|
924
|
+
serializeCookieType(encodeCookieType(data.sessionScores)),
|
925
|
+
serializeCookieType(encodeCookieType(data.scores))
|
926
|
+
].join(TYPE_SEP);
|
927
|
+
}
|
928
|
+
function encodeCookieType(type) {
|
929
|
+
return Object.entries(type).reduce((acc, [key, value]) => {
|
930
|
+
acc[key] = ntob(value);
|
931
|
+
return acc;
|
932
|
+
}, {});
|
933
|
+
}
|
934
|
+
function serializeCookieType(type) {
|
935
|
+
return Object.entries(type).map((kv) => kv.join(KV_SEP)).join(PAIR_SEP);
|
936
|
+
}
|
937
|
+
|
938
|
+
// src/storage/EdgeTransitionDataStore.ts
|
939
|
+
var _fetchData, fetchData_fn;
|
940
|
+
var EdgeTransitionDataStore = class extends TransitionDataStore {
|
941
|
+
constructor({ serverCookieValue, visitorIdCookieName = "ufvi", ...base }) {
|
942
|
+
super(base);
|
943
|
+
__privateAdd(this, _fetchData);
|
944
|
+
if (!base.initialData) {
|
945
|
+
__privateMethod(this, _fetchData, fetchData_fn).call(this).catch((err) => {
|
946
|
+
console.error(err);
|
947
|
+
});
|
948
|
+
}
|
949
|
+
}
|
950
|
+
handleDelete(fromAllDevices) {
|
951
|
+
throw new Error("Method not implemented.");
|
952
|
+
}
|
953
|
+
async handleUpdateData(commands) {
|
954
|
+
const commandResults = await new Promise((resolve) => {
|
955
|
+
setTimeout(() => {
|
956
|
+
resolve(void 0);
|
957
|
+
}, 2e3);
|
958
|
+
});
|
959
|
+
if (commandResults) {
|
960
|
+
this.signalAsyncDataUpdate(commandResults);
|
961
|
+
}
|
962
|
+
}
|
963
|
+
};
|
964
|
+
_fetchData = new WeakSet();
|
965
|
+
fetchData_fn = async function() {
|
966
|
+
const serviceData = await new Promise((resolve) => {
|
967
|
+
setTimeout(() => {
|
968
|
+
resolve(void 0);
|
969
|
+
}, 2e3);
|
970
|
+
});
|
971
|
+
if (serviceData) {
|
972
|
+
this.signalAsyncDataUpdate(serviceData);
|
973
|
+
}
|
974
|
+
};
|
975
|
+
|
976
|
+
// src/storage/linearDecay.ts
|
977
|
+
function createLinearDecay(options) {
|
978
|
+
const { gracePeriod = 864e5, decayRate = 1 / 30, decayCap = 0.95 } = options != null ? options : {};
|
979
|
+
return function linearDecay({ now, lastUpd, scores, sessionScores, onLogMessage }) {
|
980
|
+
if (typeof lastUpd !== "number") {
|
981
|
+
return false;
|
982
|
+
}
|
983
|
+
const timeSinceLastUpdate = now - lastUpd;
|
984
|
+
const timeSinceGracePeriod = timeSinceLastUpdate - gracePeriod;
|
985
|
+
if (timeSinceGracePeriod <= 0) {
|
986
|
+
return false;
|
987
|
+
}
|
988
|
+
const timeSinceGracePeriodInDays = timeSinceGracePeriod / 864e5;
|
989
|
+
const decayFactor = 1 - Math.min(decayCap, timeSinceGracePeriodInDays * decayRate);
|
990
|
+
if (decayFactor <= 0) {
|
991
|
+
return false;
|
992
|
+
}
|
993
|
+
decayVector(scores, decayFactor);
|
994
|
+
decayVector(sessionScores, decayFactor);
|
995
|
+
onLogMessage == null ? void 0 : onLogMessage(["info", 140, `linear decay factor ${decayFactor.toPrecision(6)}`]);
|
996
|
+
return true;
|
997
|
+
};
|
998
|
+
}
|
999
|
+
function decayVector(vector, decay) {
|
1000
|
+
for (const key in vector) {
|
1001
|
+
if (key.startsWith("$")) {
|
1002
|
+
continue;
|
1003
|
+
}
|
1004
|
+
vector[key] *= decay;
|
1005
|
+
}
|
1006
|
+
}
|
1007
|
+
|
1008
|
+
// src/types.ts
|
1009
|
+
var emptyVisitorData = () => ({
|
1010
|
+
quirks: {},
|
1011
|
+
scores: {},
|
1012
|
+
sessionScores: {},
|
1013
|
+
tests: {},
|
1014
|
+
consent: false,
|
1015
|
+
controlGroup: false
|
1016
|
+
});
|
1017
|
+
|
1018
|
+
// src/storage/VisitorDataStore.ts
|
1019
|
+
var import_lite3 = require("dequal/lite");
|
1020
|
+
var import_mitt2 = __toESM(require("mitt"));
|
1021
|
+
|
1022
|
+
// src/storage/util/applyCommandsToData.ts
|
1023
|
+
var import_rfdc = __toESM(require("rfdc"));
|
1024
|
+
var clone = (0, import_rfdc.default)();
|
1025
|
+
function applyCommandsToData(commands, state, inControlGroup) {
|
1026
|
+
const newData = state ? clone(state) : emptyVisitorData();
|
1027
|
+
commands.forEach((command) => {
|
1028
|
+
var _a, _b;
|
1029
|
+
switch (command.type) {
|
1030
|
+
case "consent":
|
1031
|
+
newData.consent = command.data;
|
1032
|
+
break;
|
1033
|
+
case "setquirk":
|
1034
|
+
newData.quirks[command.data.key] = command.data.value;
|
1035
|
+
break;
|
1036
|
+
case "settest":
|
1037
|
+
newData.tests[command.data.test] = command.data.variant;
|
1038
|
+
break;
|
1039
|
+
case "modscore":
|
1040
|
+
if (inControlGroup)
|
1041
|
+
break;
|
1042
|
+
const delta = Number(command.data.delta);
|
1043
|
+
if (isNaN(delta)) {
|
1044
|
+
throw new Error("Non-number delta received");
|
1045
|
+
}
|
1046
|
+
const existing = (_a = newData.scores[command.data.dimension]) != null ? _a : 0;
|
1047
|
+
newData.scores[command.data.dimension] = existing + delta;
|
1048
|
+
break;
|
1049
|
+
case "modscoreS":
|
1050
|
+
if (inControlGroup)
|
1051
|
+
break;
|
1052
|
+
const deltaS = Number(command.data.delta);
|
1053
|
+
if (isNaN(deltaS)) {
|
1054
|
+
throw new Error("Non-number delta received");
|
1055
|
+
}
|
1056
|
+
const existingS = (_b = newData.sessionScores[command.data.dimension]) != null ? _b : 0;
|
1057
|
+
newData.sessionScores[command.data.dimension] = existingS + deltaS;
|
1058
|
+
break;
|
1059
|
+
case "identify":
|
1060
|
+
break;
|
1061
|
+
case "setcontrol":
|
1062
|
+
newData.controlGroup = command.data;
|
1063
|
+
break;
|
1064
|
+
default:
|
1065
|
+
throw new Error(`Unknown command`);
|
1066
|
+
}
|
1067
|
+
});
|
1068
|
+
return newData;
|
1069
|
+
}
|
1070
|
+
|
1071
|
+
// src/storage/util/LocalStorage.ts
|
1072
|
+
var LocalStorage = class {
|
1073
|
+
constructor() {
|
1074
|
+
__publicField(this, "inMemoryFallback", {});
|
1075
|
+
__publicField(this, "hasLocalStorageObject", typeof localStorage !== "undefined");
|
1076
|
+
}
|
1077
|
+
get(key) {
|
1078
|
+
const fallbackValue = this.inMemoryFallback[key];
|
1079
|
+
if (!this.hasLocalStorageObject || fallbackValue) {
|
1080
|
+
return fallbackValue;
|
1081
|
+
}
|
1082
|
+
try {
|
1083
|
+
const value = localStorage.getItem(key);
|
1084
|
+
return value ? JSON.parse(value) : void 0;
|
1085
|
+
} catch (e) {
|
1086
|
+
return fallbackValue;
|
1087
|
+
}
|
1088
|
+
}
|
1089
|
+
set(key, value, storageConsent) {
|
1090
|
+
this.inMemoryFallback[key] = value;
|
1091
|
+
if (!this.hasLocalStorageObject || !storageConsent) {
|
1092
|
+
return;
|
1093
|
+
}
|
1094
|
+
try {
|
1095
|
+
localStorage.setItem(key, JSON.stringify(value));
|
1096
|
+
} catch (e) {
|
1097
|
+
console.warn(e);
|
1098
|
+
}
|
1099
|
+
}
|
1100
|
+
delete(key, leaveInMemory) {
|
1101
|
+
if (!leaveInMemory) {
|
1102
|
+
delete this.inMemoryFallback[key];
|
1103
|
+
}
|
1104
|
+
try {
|
1105
|
+
localStorage.removeItem(key);
|
1106
|
+
} catch (e) {
|
1107
|
+
}
|
1108
|
+
}
|
1109
|
+
};
|
1110
|
+
|
1111
|
+
// src/storage/VisitorDataStore.ts
|
1112
|
+
var STORAGE_KEY = "ufvisitor";
|
1113
|
+
var _mitt2, _persist, _visitTimeout, _options, _currentData, currentData_get, _replaceData, replaceData_fn, _setVisitTimeout, setVisitTimeout_fn, _isExpired, isExpired_fn, _handleCaps, handleCaps_fn, _defaultData, defaultData_fn;
|
1114
|
+
var VisitorDataStore = class {
|
1115
|
+
constructor(options) {
|
1116
|
+
__privateAdd(this, _currentData);
|
1117
|
+
__privateAdd(this, _replaceData);
|
1118
|
+
__privateAdd(this, _setVisitTimeout);
|
1119
|
+
__privateAdd(this, _isExpired);
|
1120
|
+
__privateAdd(this, _handleCaps);
|
1121
|
+
__privateAdd(this, _defaultData);
|
1122
|
+
__privateAdd(this, _mitt2, (0, import_mitt2.default)());
|
1123
|
+
__privateAdd(this, _persist, new LocalStorage());
|
1124
|
+
__privateAdd(this, _visitTimeout, void 0);
|
1125
|
+
__privateAdd(this, _options, void 0);
|
1126
|
+
__publicField(this, "events", {
|
1127
|
+
on: __privateGet(this, _mitt2).on,
|
1128
|
+
off: __privateGet(this, _mitt2).off
|
1129
|
+
});
|
1130
|
+
__privateSet(this, _options, options);
|
1131
|
+
if (!__privateGet(this, _currentData, currentData_get)) {
|
1132
|
+
__privateMethod(this, _replaceData, replaceData_fn).call(this, __privateMethod(this, _defaultData, defaultData_fn).call(this), true);
|
1133
|
+
}
|
1134
|
+
if (options.transitionStore) {
|
1135
|
+
const serverToClientTransitionState = options.transitionStore.getClientTransitionState();
|
1136
|
+
if (serverToClientTransitionState && options.onServerTransitionReceived) {
|
1137
|
+
options.onServerTransitionReceived(serverToClientTransitionState);
|
1138
|
+
}
|
1139
|
+
options.transitionStore.events.on("dataUpdatedAsync", (data) => {
|
1140
|
+
__privateMethod(this, _replaceData, replaceData_fn).call(this, {
|
1141
|
+
...__privateGet(this, _currentData, currentData_get).visitorData,
|
1142
|
+
...data
|
1143
|
+
});
|
1144
|
+
});
|
1145
|
+
const transitionData = options.transitionStore.data;
|
1146
|
+
if (transitionData) {
|
1147
|
+
__privateMethod(this, _replaceData, replaceData_fn).call(this, { ...__privateGet(this, _currentData, currentData_get).visitorData, ...transitionData }, true);
|
1148
|
+
}
|
1149
|
+
}
|
1150
|
+
}
|
1151
|
+
get data() {
|
1152
|
+
var _a, _b;
|
1153
|
+
const data = __privateGet(this, _currentData, currentData_get);
|
1154
|
+
if (__privateMethod(this, _isExpired, isExpired_fn).call(this, data)) {
|
1155
|
+
const { sessionScores, ...newData } = data.visitorData;
|
1156
|
+
__privateMethod(this, _replaceData, replaceData_fn).call(this, { ...newData, sessionScores: {} });
|
1157
|
+
(_b = (_a = __privateGet(this, _options)).onLogMessage) == null ? void 0 : _b.call(_a, ["info", 120]);
|
1158
|
+
return __privateGet(this, _currentData, currentData_get).visitorData;
|
1159
|
+
}
|
1160
|
+
return data.visitorData;
|
1161
|
+
}
|
1162
|
+
get decayEnabled() {
|
1163
|
+
return !!__privateGet(this, _options).decay;
|
1164
|
+
}
|
1165
|
+
get options() {
|
1166
|
+
return __privateGet(this, _options);
|
1167
|
+
}
|
1168
|
+
async updateData(commands) {
|
1169
|
+
var _a, _b, _c, _d;
|
1170
|
+
if (commands.length === 0) {
|
1171
|
+
return;
|
1172
|
+
}
|
1173
|
+
(_b = (_a = __privateGet(this, _options)).onLogMessage) == null ? void 0 : _b.call(_a, ["debug", 101, commands]);
|
1174
|
+
const newData = applyCommandsToData(commands, this.data, (_c = __privateGet(this, _currentData, currentData_get)) == null ? void 0 : _c.visitorData.controlGroup);
|
1175
|
+
if (commands.some((c) => c.type === "consent" && !c.data)) {
|
1176
|
+
__privateGet(this, _persist).delete(STORAGE_KEY, true);
|
1177
|
+
}
|
1178
|
+
__privateMethod(this, _replaceData, replaceData_fn).call(this, newData);
|
1179
|
+
await ((_d = __privateGet(this, _options).transitionStore) == null ? void 0 : _d.updateData(commands, __privateGet(this, _currentData, currentData_get).visitorData));
|
1180
|
+
}
|
1181
|
+
async delete(fromAllDevices) {
|
1182
|
+
var _a, _b, _c, _d, _e;
|
1183
|
+
(_b = (_a = __privateGet(this, _options)).onLogMessage) == null ? void 0 : _b.call(_a, ["info", 103, "GROUP", fromAllDevices]);
|
1184
|
+
try {
|
1185
|
+
__privateGet(this, _persist).delete(STORAGE_KEY, false);
|
1186
|
+
await ((_c = __privateGet(this, _options).transitionStore) == null ? void 0 : _c.delete(fromAllDevices));
|
1187
|
+
__privateMethod(this, _replaceData, replaceData_fn).call(this, __privateMethod(this, _defaultData, defaultData_fn).call(this));
|
1188
|
+
} finally {
|
1189
|
+
(_e = (_d = __privateGet(this, _options)).onLogMessage) == null ? void 0 : _e.call(_d, ["info", 103, "ENDGROUP"]);
|
1190
|
+
}
|
1191
|
+
}
|
1192
|
+
};
|
1193
|
+
_mitt2 = new WeakMap();
|
1194
|
+
_persist = new WeakMap();
|
1195
|
+
_visitTimeout = new WeakMap();
|
1196
|
+
_options = new WeakMap();
|
1197
|
+
_currentData = new WeakSet();
|
1198
|
+
currentData_get = function() {
|
1199
|
+
return __privateGet(this, _persist).get(STORAGE_KEY);
|
1200
|
+
};
|
1201
|
+
_replaceData = new WeakSet();
|
1202
|
+
replaceData_fn = function(data, quiet = false) {
|
1203
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
|
1204
|
+
const oldData = __privateGet(this, _currentData, currentData_get);
|
1205
|
+
const now = Date.now();
|
1206
|
+
if (data.controlGroup) {
|
1207
|
+
data.scores = {};
|
1208
|
+
data.sessionScores = {};
|
1209
|
+
} else {
|
1210
|
+
__privateMethod(this, _handleCaps, handleCaps_fn).call(this, data.scores);
|
1211
|
+
__privateMethod(this, _handleCaps, handleCaps_fn).call(this, data.sessionScores);
|
1212
|
+
(_b = (_a = __privateGet(this, _options)).decay) == null ? void 0 : _b.call(_a, {
|
1213
|
+
now,
|
1214
|
+
lastUpd: oldData == null ? void 0 : oldData.updated,
|
1215
|
+
scores: data.scores,
|
1216
|
+
sessionScores: data.sessionScores,
|
1217
|
+
onLogMessage: __privateGet(this, _options).onLogMessage
|
1218
|
+
});
|
1219
|
+
}
|
1220
|
+
const haveScoresChanged = !(0, import_lite3.dequal)(oldData == null ? void 0 : oldData.visitorData.scores, data.scores);
|
1221
|
+
const haveSessionScoresChanged = !(0, import_lite3.dequal)(oldData == null ? void 0 : oldData.visitorData.sessionScores, data.sessionScores);
|
1222
|
+
const haveQuirksChanged = !(0, import_lite3.dequal)(oldData == null ? void 0 : oldData.visitorData.quirks, data.quirks);
|
1223
|
+
const haveTestsChanged = !(0, import_lite3.dequal)(oldData == null ? void 0 : oldData.visitorData.tests, data.tests);
|
1224
|
+
const updatedData = {
|
1225
|
+
updated: now,
|
1226
|
+
visitorData: data
|
1227
|
+
};
|
1228
|
+
__privateMethod(this, _setVisitTimeout, setVisitTimeout_fn).call(this);
|
1229
|
+
__privateGet(this, _persist).set(STORAGE_KEY, updatedData, !!data.consent);
|
1230
|
+
(_d = (_c = __privateGet(this, _options)).onLogMessage) == null ? void 0 : _d.call(_c, ["debug", 102, data]);
|
1231
|
+
if (!quiet) {
|
1232
|
+
if (haveScoresChanged || haveSessionScoresChanged) {
|
1233
|
+
__privateGet(this, _mitt2).emit("scoresUpdated", data);
|
1234
|
+
}
|
1235
|
+
if (haveQuirksChanged) {
|
1236
|
+
__privateGet(this, _mitt2).emit("quirksUpdated", data);
|
1237
|
+
}
|
1238
|
+
if (haveTestsChanged) {
|
1239
|
+
__privateGet(this, _mitt2).emit("testsUpdated", data);
|
1240
|
+
}
|
1241
|
+
if (((_e = oldData == null ? void 0 : oldData.visitorData) == null ? void 0 : _e.consent) !== data.consent) {
|
1242
|
+
__privateGet(this, _mitt2).emit("consentUpdated", data);
|
1243
|
+
}
|
1244
|
+
if (((_f = oldData == null ? void 0 : oldData.visitorData) == null ? void 0 : _f.controlGroup) !== data.controlGroup) {
|
1245
|
+
__privateGet(this, _mitt2).emit("controlGroupUpdated", data);
|
1246
|
+
(_i = (_h = __privateGet(this, _options)).onLogMessage) == null ? void 0 : _i.call(_h, ["debug", 104, (_g = data.controlGroup) != null ? _g : false]);
|
1247
|
+
}
|
1248
|
+
}
|
1249
|
+
};
|
1250
|
+
_setVisitTimeout = new WeakSet();
|
1251
|
+
setVisitTimeout_fn = function() {
|
1252
|
+
if (typeof document === "undefined" || !__privateGet(this, _options).visitLifespan) {
|
1253
|
+
return;
|
1254
|
+
}
|
1255
|
+
if (__privateGet(this, _visitTimeout)) {
|
1256
|
+
window.clearTimeout(__privateGet(this, _visitTimeout));
|
1257
|
+
}
|
1258
|
+
__privateSet(this, _visitTimeout, window.setTimeout(() => {
|
1259
|
+
this.data;
|
1260
|
+
}, __privateGet(this, _options).visitLifespan + 50));
|
1261
|
+
};
|
1262
|
+
_isExpired = new WeakSet();
|
1263
|
+
isExpired_fn = function(data) {
|
1264
|
+
const expires = __privateGet(this, _options).visitLifespan;
|
1265
|
+
return expires ? data.updated + expires < Date.now() : false;
|
1266
|
+
};
|
1267
|
+
_handleCaps = new WeakSet();
|
1268
|
+
handleCaps_fn = function(scores) {
|
1269
|
+
var _a, _b;
|
1270
|
+
if (!__privateGet(this, _options).manifest) {
|
1271
|
+
return;
|
1272
|
+
}
|
1273
|
+
for (const dim in scores) {
|
1274
|
+
const score = scores[dim];
|
1275
|
+
const dimDef = __privateGet(this, _options).manifest.getDimensionByKey(dim);
|
1276
|
+
if (!dimDef) {
|
1277
|
+
continue;
|
1278
|
+
}
|
1279
|
+
if (score > dimDef.cap) {
|
1280
|
+
(_b = (_a = __privateGet(this, _options)).onLogMessage) == null ? void 0 : _b.call(_a, ["debug", 110, { dim, score, cap: dimDef.cap }]);
|
1281
|
+
scores[dim] = dimDef.cap;
|
1282
|
+
}
|
1283
|
+
}
|
1284
|
+
};
|
1285
|
+
_defaultData = new WeakSet();
|
1286
|
+
defaultData_fn = function() {
|
1287
|
+
var _a, _b, _c;
|
1288
|
+
return {
|
1289
|
+
...emptyVisitorData(),
|
1290
|
+
consent: (_a = __privateGet(this, _options).defaultConsent) != null ? _a : false,
|
1291
|
+
controlGroup: (_c = (_b = __privateGet(this, _options).manifest) == null ? void 0 : _b.rollForControlGroup()) != null ? _c : false
|
1292
|
+
};
|
1293
|
+
};
|
1294
|
+
|
1295
|
+
// src/Context.ts
|
1296
|
+
var import_lite4 = require("dequal/lite");
|
1297
|
+
var import_mitt3 = __toESM(require("mitt"));
|
1298
|
+
var _serverTransitionState, _scores, _state, _pzCache, _mitt3, _emitTest, emitTest_fn, _updateComputedScores, updateComputedScores_fn, _calculateScores, calculateScores_fn;
|
1299
|
+
var Context = class {
|
1300
|
+
constructor(options) {
|
1301
|
+
__privateAdd(this, _emitTest);
|
1302
|
+
__privateAdd(this, _updateComputedScores);
|
1303
|
+
__privateAdd(this, _calculateScores);
|
1304
|
+
__publicField(this, "manifest");
|
1305
|
+
__privateAdd(this, _serverTransitionState, void 0);
|
1306
|
+
__privateAdd(this, _scores, {});
|
1307
|
+
__privateAdd(this, _state, void 0);
|
1308
|
+
__privateAdd(this, _pzCache, {});
|
1309
|
+
__privateAdd(this, _mitt3, (0, import_mitt3.default)());
|
1310
|
+
__publicField(this, "events", {
|
1311
|
+
on: __privateGet(this, _mitt3).on,
|
1312
|
+
off: __privateGet(this, _mitt3).off
|
1313
|
+
});
|
1314
|
+
__publicField(this, "storage");
|
1315
|
+
var _a, _b;
|
1316
|
+
const { manifest, ...storageOptions } = options;
|
1317
|
+
__privateSet(this, _state, {});
|
1318
|
+
(_a = options.plugins) == null ? void 0 : _a.forEach((plugin) => {
|
1319
|
+
if (!plugin.logDrain) {
|
1320
|
+
return;
|
1321
|
+
}
|
1322
|
+
__privateGet(this, _mitt3).on("log", plugin.logDrain);
|
1323
|
+
});
|
1324
|
+
__privateGet(this, _mitt3).emit("log", ["info", 1, "GROUP"]);
|
1325
|
+
try {
|
1326
|
+
this.manifest = new ManifestInstance({
|
1327
|
+
onLogMessage: (message) => __privateGet(this, _mitt3).emit("log", message),
|
1328
|
+
manifest,
|
1329
|
+
evaluator: new GroupCriteriaEvaluator({
|
1330
|
+
CK: cookieEvaluator,
|
1331
|
+
QS: queryStringEvaluator,
|
1332
|
+
QK: quirkEvaluator,
|
1333
|
+
PVC: pageViewCountEvaluator,
|
1334
|
+
EVT: eventEvaluator,
|
1335
|
+
PV: currentPageEvaluator
|
1336
|
+
})
|
1337
|
+
});
|
1338
|
+
this.storage = new VisitorDataStore({
|
1339
|
+
...storageOptions,
|
1340
|
+
manifest: this.manifest,
|
1341
|
+
onServerTransitionReceived: (state) => {
|
1342
|
+
__privateSet(this, _serverTransitionState, state);
|
1343
|
+
if (state.ssv) {
|
1344
|
+
__privateSet(this, _scores, state.ssv);
|
1345
|
+
__privateGet(this, _mitt3).emit("log", ["debug", 130, state]);
|
1346
|
+
}
|
1347
|
+
},
|
1348
|
+
onLogMessage: (message) => __privateGet(this, _mitt3).emit("log", message)
|
1349
|
+
});
|
1350
|
+
this.storage.events.on("scoresUpdated", __privateMethod(this, _updateComputedScores, updateComputedScores_fn).bind(this));
|
1351
|
+
if (!__privateGet(this, _serverTransitionState)) {
|
1352
|
+
__privateMethod(this, _updateComputedScores, updateComputedScores_fn).call(this, this.storage.data);
|
1353
|
+
}
|
1354
|
+
this.storage.events.on("quirksUpdated", (quirks) => {
|
1355
|
+
const updates = this.manifest.computeSignals({
|
1356
|
+
scores: __privateGet(this, _scores),
|
1357
|
+
state: __privateGet(this, _state),
|
1358
|
+
previousState: __privateGet(this, _state),
|
1359
|
+
visitor: this.storage.data
|
1360
|
+
});
|
1361
|
+
this.storage.updateData(updates);
|
1362
|
+
__privateGet(this, _mitt3).emit("quirksUpdated", quirks.quirks);
|
1363
|
+
__privateGet(this, _mitt3).emit("log", ["info", 4, quirks.quirks]);
|
1364
|
+
});
|
1365
|
+
(_b = options.plugins) == null ? void 0 : _b.forEach((plugin) => {
|
1366
|
+
if (!plugin.init) {
|
1367
|
+
return;
|
1368
|
+
}
|
1369
|
+
plugin.init(this);
|
1370
|
+
});
|
1371
|
+
} finally {
|
1372
|
+
__privateGet(this, _mitt3).emit("log", ["info", 1, "ENDGROUP"]);
|
1373
|
+
}
|
1374
|
+
}
|
1375
|
+
get scores() {
|
1376
|
+
return __privateGet(this, _scores);
|
1377
|
+
}
|
1378
|
+
get quirks() {
|
1379
|
+
var _a, _b;
|
1380
|
+
return (_b = (_a = __privateGet(this, _serverTransitionState)) == null ? void 0 : _a.quirks) != null ? _b : this.storage.data.quirks;
|
1381
|
+
}
|
1382
|
+
async update(newData) {
|
1383
|
+
var _a, _b, _c;
|
1384
|
+
const commands = [];
|
1385
|
+
const newServerSideTests = {};
|
1386
|
+
if ((_a = __privateGet(this, _serverTransitionState)) == null ? void 0 : _a.quirks) {
|
1387
|
+
newData = {
|
1388
|
+
...newData,
|
1389
|
+
quirks: {
|
1390
|
+
...__privateGet(this, _serverTransitionState).quirks,
|
1391
|
+
...newData.quirks || {}
|
1392
|
+
}
|
1393
|
+
};
|
1394
|
+
}
|
1395
|
+
if ((_b = __privateGet(this, _serverTransitionState)) == null ? void 0 : _b.tests) {
|
1396
|
+
const testEntries = Object.entries(__privateGet(this, _serverTransitionState).tests);
|
1397
|
+
if (testEntries.length > 0) {
|
1398
|
+
const validTests = [];
|
1399
|
+
testEntries.forEach(([testName, testVariantId]) => {
|
1400
|
+
if (!this.storage.data.tests[testName]) {
|
1401
|
+
validTests.push([testName, testVariantId]);
|
1402
|
+
newServerSideTests[testName] = testVariantId;
|
1403
|
+
}
|
1404
|
+
});
|
1405
|
+
commands.push(
|
1406
|
+
...validTests.map(([key, value]) => ({
|
1407
|
+
type: "settest",
|
1408
|
+
data: { test: key, variant: value }
|
1409
|
+
}))
|
1410
|
+
);
|
1411
|
+
}
|
1412
|
+
}
|
1413
|
+
try {
|
1414
|
+
__privateGet(this, _mitt3).emit("log", [
|
1415
|
+
"info",
|
1416
|
+
2,
|
1417
|
+
"GROUP",
|
1418
|
+
{
|
1419
|
+
...newData,
|
1420
|
+
url: (_c = newData.url) == null ? void 0 : _c.toString()
|
1421
|
+
}
|
1422
|
+
]);
|
1423
|
+
if (newData.quirks) {
|
1424
|
+
commands.push(
|
1425
|
+
...Object.entries(newData.quirks).map(([key, value]) => ({
|
1426
|
+
type: "setquirk",
|
1427
|
+
data: { key, value }
|
1428
|
+
}))
|
1429
|
+
);
|
1430
|
+
}
|
1431
|
+
if (newData.enrichments) {
|
1432
|
+
newData.enrichments.forEach((enrichment) => {
|
1433
|
+
const dimension = getEnrichmentVectorKey(enrichment.cat, enrichment.key);
|
1434
|
+
const dimData = this.manifest.getDimensionByKey(dimension);
|
1435
|
+
if (dimData) {
|
1436
|
+
commands.push({
|
1437
|
+
type: "modscore",
|
1438
|
+
data: {
|
1439
|
+
dimension,
|
1440
|
+
delta: enrichment.str
|
1441
|
+
}
|
1442
|
+
});
|
1443
|
+
} else {
|
1444
|
+
__privateGet(this, _mitt3).emit("log", ["warn", 5, enrichment]);
|
1445
|
+
}
|
1446
|
+
});
|
1447
|
+
}
|
1448
|
+
commands.push(
|
1449
|
+
...this.manifest.computeSignals({
|
1450
|
+
state: newData,
|
1451
|
+
previousState: __privateGet(this, _state),
|
1452
|
+
visitor: this.storage.data,
|
1453
|
+
scores: __privateGet(this, _serverTransitionState) ? __privateMethod(this, _calculateScores, calculateScores_fn).call(this, this.storage.data) : __privateGet(this, _scores)
|
1454
|
+
})
|
1455
|
+
);
|
1456
|
+
__privateSet(this, _state, {
|
1457
|
+
...__privateGet(this, _state),
|
1458
|
+
...newData
|
1459
|
+
});
|
1460
|
+
await this.storage.updateData(commands);
|
1461
|
+
if (__privateGet(this, _serverTransitionState)) {
|
1462
|
+
__privateMethod(this, _updateComputedScores, updateComputedScores_fn).call(this, this.storage.data);
|
1463
|
+
Object.entries(newServerSideTests).forEach(([testName, testVariantId]) => {
|
1464
|
+
__privateMethod(this, _emitTest, emitTest_fn).call(this, {
|
1465
|
+
name: testName,
|
1466
|
+
variantId: testVariantId,
|
1467
|
+
variantAssigned: true
|
1468
|
+
});
|
1469
|
+
});
|
1470
|
+
__privateSet(this, _serverTransitionState, void 0);
|
1471
|
+
__privateGet(this, _mitt3).emit("log", ["debug", 131]);
|
1472
|
+
}
|
1473
|
+
} finally {
|
1474
|
+
__privateGet(this, _mitt3).emit("log", ["info", 2, "ENDGROUP"]);
|
1475
|
+
}
|
1476
|
+
}
|
1477
|
+
getTestVariantId(testName) {
|
1478
|
+
var _a, _b, _c, _d;
|
1479
|
+
const definition = this.manifest.getTest(testName);
|
1480
|
+
if (!definition) {
|
1481
|
+
__privateGet(this, _mitt3).emit("log", ["warn", 401, testName]);
|
1482
|
+
return null;
|
1483
|
+
}
|
1484
|
+
return (_d = (_c = definition.wv) != null ? _c : (_b = (_a = __privateGet(this, _serverTransitionState)) == null ? void 0 : _a.tests) == null ? void 0 : _b[testName]) != null ? _d : this.storage.data.tests[testName];
|
1485
|
+
}
|
1486
|
+
setTestVariantId(testName, variantId) {
|
1487
|
+
this.storage.updateData([
|
1488
|
+
{
|
1489
|
+
type: "settest",
|
1490
|
+
data: {
|
1491
|
+
test: testName,
|
1492
|
+
variant: variantId
|
1493
|
+
}
|
1494
|
+
}
|
1495
|
+
]);
|
1496
|
+
}
|
1497
|
+
log(...message) {
|
1498
|
+
__privateGet(this, _mitt3).emit("log", message);
|
1499
|
+
}
|
1500
|
+
test(options) {
|
1501
|
+
var _a, _b;
|
1502
|
+
const value = testVariations({
|
1503
|
+
...options,
|
1504
|
+
context: this,
|
1505
|
+
onLogMessage: (message) => __privateGet(this, _mitt3).emit("log", message)
|
1506
|
+
});
|
1507
|
+
__privateMethod(this, _emitTest, emitTest_fn).call(this, {
|
1508
|
+
name: options.name,
|
1509
|
+
variantId: (_b = (_a = value.result) == null ? void 0 : _a.id) != null ? _b : void 0,
|
1510
|
+
variantAssigned: value.variantAssigned
|
1511
|
+
});
|
1512
|
+
return value;
|
1513
|
+
}
|
1514
|
+
personalize(options) {
|
1515
|
+
const value = personalizeVariations({
|
1516
|
+
...options,
|
1517
|
+
context: this,
|
1518
|
+
onLogMessage: (message) => __privateGet(this, _mitt3).emit("log", message)
|
1519
|
+
});
|
1520
|
+
const previousPlacement = __privateGet(this, _pzCache)[options.name];
|
1521
|
+
const eventData = {
|
1522
|
+
name: options.name,
|
1523
|
+
variantIds: value.variations.map((variation) => {
|
1524
|
+
var _a;
|
1525
|
+
return (_a = variation.id) != null ? _a : "Unknown";
|
1526
|
+
}),
|
1527
|
+
control: this.storage.data.controlGroup,
|
1528
|
+
changed: true
|
1529
|
+
};
|
1530
|
+
if (previousPlacement && (0, import_lite4.dequal)(eventData.variantIds, previousPlacement)) {
|
1531
|
+
eventData.changed = false;
|
1532
|
+
}
|
1533
|
+
__privateGet(this, _mitt3).emit("personalizationResult", eventData);
|
1534
|
+
__privateGet(this, _pzCache)[options.name] = eventData.variantIds;
|
1535
|
+
return value;
|
1536
|
+
}
|
1537
|
+
async forget(fromAllDevices) {
|
1538
|
+
__privateSet(this, _state, {});
|
1539
|
+
await this.storage.delete(fromAllDevices);
|
1540
|
+
}
|
1541
|
+
getServerToClientTransitionState() {
|
1542
|
+
const transitionState = {
|
1543
|
+
quirks: this.storage.data.quirks,
|
1544
|
+
ssv: __privateGet(this, _scores),
|
1545
|
+
tests: {}
|
1546
|
+
};
|
1547
|
+
const allTests = this.storage.data.tests;
|
1548
|
+
Object.entries(allTests).map(([testName, testValue]) => {
|
1549
|
+
var _a, _b, _c;
|
1550
|
+
if (((_c = (_b = (_a = this.storage.options.transitionStore) == null ? void 0 : _a.initialData) == null ? void 0 : _b.tests) == null ? void 0 : _c[testName]) !== allTests[testName] && transitionState.tests) {
|
1551
|
+
transitionState.tests[testName] = testValue;
|
1552
|
+
}
|
1553
|
+
});
|
1554
|
+
return transitionState;
|
1555
|
+
}
|
1556
|
+
};
|
1557
|
+
_serverTransitionState = new WeakMap();
|
1558
|
+
_scores = new WeakMap();
|
1559
|
+
_state = new WeakMap();
|
1560
|
+
_pzCache = new WeakMap();
|
1561
|
+
_mitt3 = new WeakMap();
|
1562
|
+
_emitTest = new WeakSet();
|
1563
|
+
emitTest_fn = function(event) {
|
1564
|
+
__privateGet(this, _mitt3).emit("testResult", event);
|
1565
|
+
};
|
1566
|
+
_updateComputedScores = new WeakSet();
|
1567
|
+
updateComputedScores_fn = function(newData) {
|
1568
|
+
const newScores = __privateMethod(this, _calculateScores, calculateScores_fn).call(this, newData);
|
1569
|
+
const newScoresHaveChanged = !(0, import_lite4.dequal)(newScores, __privateGet(this, _scores));
|
1570
|
+
if (newScoresHaveChanged) {
|
1571
|
+
__privateSet(this, _scores, newScores);
|
1572
|
+
__privateGet(this, _mitt3).emit("scoresUpdated", newScores);
|
1573
|
+
__privateGet(this, _mitt3).emit("log", ["info", 3, newScores]);
|
1574
|
+
}
|
1575
|
+
};
|
1576
|
+
_calculateScores = new WeakSet();
|
1577
|
+
calculateScores_fn = function(newData) {
|
1578
|
+
var _a;
|
1579
|
+
let newScores = { ...newData.scores };
|
1580
|
+
for (const session in newData.sessionScores) {
|
1581
|
+
newScores[session] = ((_a = newScores[session]) != null ? _a : 0) + newData.sessionScores[session];
|
1582
|
+
}
|
1583
|
+
newScores = this.manifest.computeAggregateDimensions(newScores);
|
1584
|
+
return newScores;
|
1585
|
+
};
|
1586
|
+
|
1587
|
+
// src/devTools/enableContextDevTools.ts
|
1588
|
+
var isBrowser = typeof top !== "undefined";
|
1589
|
+
function enableContextDevTools() {
|
1590
|
+
return {
|
1591
|
+
logDrain: (message) => {
|
1592
|
+
if (!isBrowser) {
|
1593
|
+
return;
|
1594
|
+
}
|
1595
|
+
top == null ? void 0 : top.postMessage(
|
1596
|
+
{
|
1597
|
+
type: "uniform:context:log",
|
1598
|
+
message
|
1599
|
+
},
|
1600
|
+
window.location.origin
|
1601
|
+
);
|
1602
|
+
},
|
1603
|
+
init: (context) => {
|
1604
|
+
const personalizations = [];
|
1605
|
+
const tests = [];
|
1606
|
+
const onContextDataUpdated = () => {
|
1607
|
+
if (!isBrowser) {
|
1608
|
+
return;
|
1609
|
+
}
|
1610
|
+
top == null ? void 0 : top.postMessage(
|
1611
|
+
{
|
1612
|
+
type: "uniform:context:data",
|
1613
|
+
data: {
|
1614
|
+
scores: context.scores,
|
1615
|
+
data: context.storage.data,
|
1616
|
+
manifest: context.manifest.data,
|
1617
|
+
personalizations,
|
1618
|
+
tests
|
1619
|
+
}
|
1620
|
+
},
|
1621
|
+
window.location.origin
|
1622
|
+
);
|
1623
|
+
};
|
1624
|
+
const onPersonalizationResult = (e) => {
|
1625
|
+
if (!e.changed)
|
1626
|
+
return;
|
1627
|
+
personalizations.push(e);
|
1628
|
+
};
|
1629
|
+
const onTestResult = (e) => {
|
1630
|
+
if (!e.variantAssigned)
|
1631
|
+
return;
|
1632
|
+
tests.push(e);
|
1633
|
+
};
|
1634
|
+
if (isBrowser) {
|
1635
|
+
window.__UNIFORM_DEVTOOLS_CONTEXT_INSTANCE__ = context;
|
1636
|
+
try {
|
1637
|
+
top == null ? void 0 : top.addEventListener("message", async (event) => {
|
1638
|
+
if (!event.data) {
|
1639
|
+
return;
|
1640
|
+
}
|
1641
|
+
const message = event.data;
|
1642
|
+
await handleMessageFromDevTools(message, context);
|
1643
|
+
});
|
1644
|
+
} catch (e) {
|
1645
|
+
console.warn(
|
1646
|
+
"Unable to initialize Uniform Context DevTools because it is in a cross-domain iframe.",
|
1647
|
+
e
|
1648
|
+
);
|
1649
|
+
}
|
1650
|
+
top == null ? void 0 : top.postMessage(
|
1651
|
+
{
|
1652
|
+
type: "uniform:context:hello",
|
1653
|
+
uiVersion: 2
|
1654
|
+
},
|
1655
|
+
window.location.origin
|
1656
|
+
);
|
1657
|
+
onContextDataUpdated();
|
1658
|
+
}
|
1659
|
+
context.events.on("personalizationResult", onPersonalizationResult);
|
1660
|
+
context.events.on("testResult", onTestResult);
|
1661
|
+
context.events.on("scoresUpdated", onContextDataUpdated);
|
1662
|
+
context.storage.events.on("*", onContextDataUpdated);
|
1663
|
+
return () => {
|
1664
|
+
context.events.off("scoresUpdated", onContextDataUpdated);
|
1665
|
+
context.storage.events.off("*", onContextDataUpdated);
|
1666
|
+
context.events.off("personalizationResult", onPersonalizationResult);
|
1667
|
+
context.events.off("testResult", onTestResult);
|
1668
|
+
};
|
1669
|
+
}
|
1670
|
+
};
|
1671
|
+
}
|
1672
|
+
async function handleMessageFromDevTools(message, context) {
|
1673
|
+
if (message.type === "uniform-in:context:update" && message.newData) {
|
1674
|
+
await context.update(message.newData);
|
1675
|
+
}
|
1676
|
+
if (message.type === "uniform-in:context:commands" && message.commands && Array.isArray(message.commands)) {
|
1677
|
+
await context.storage.updateData(message.commands);
|
1678
|
+
}
|
1679
|
+
if (message.type === "uniform-in:context:forget") {
|
1680
|
+
await context.forget(false);
|
1681
|
+
}
|
1682
|
+
}
|
1683
|
+
|
1684
|
+
// src/edge/index.ts
|
1685
|
+
var ScriptType = /* @__PURE__ */ ((ScriptType2) => {
|
1686
|
+
ScriptType2["ListStart"] = "nesi-list-start";
|
1687
|
+
ScriptType2["ListEnd"] = "nesi-list-end";
|
1688
|
+
ScriptType2["ListItem"] = "nesi-list-item-html";
|
1689
|
+
ScriptType2["ListItemSettings"] = "nesi-list-item-settings";
|
1690
|
+
ScriptType2["TestStart"] = "nesi-test-start";
|
1691
|
+
ScriptType2["TestEnd"] = "nesi-test-end";
|
1692
|
+
ScriptType2["Unknown"] = "unknown";
|
1693
|
+
return ScriptType2;
|
1694
|
+
})(ScriptType || {});
|
1695
|
+
var EdgeNodeTagName = "nesitag";
|
1696
|
+
|
1697
|
+
// src/logging/enableConsoleLogDrain.ts
|
1698
|
+
var import_rfdc2 = __toESM(require("rfdc"));
|
1699
|
+
|
1700
|
+
// src/logging/isEnabled.ts
|
1701
|
+
function isEnabled(level, severity) {
|
1702
|
+
if (level === "none") {
|
1703
|
+
return false;
|
1704
|
+
}
|
1705
|
+
switch (severity) {
|
1706
|
+
case "debug":
|
1707
|
+
return level === "debug";
|
1708
|
+
case "info":
|
1709
|
+
return level === "info" || level === "debug";
|
1710
|
+
case "warn":
|
1711
|
+
return level === "warn" || level === "info" || level === "debug";
|
1712
|
+
case "error":
|
1713
|
+
return level === "debug" || "info";
|
1714
|
+
default:
|
1715
|
+
return false;
|
1716
|
+
}
|
1717
|
+
}
|
1718
|
+
|
1719
|
+
// src/logging/enableConsoleLogDrain.ts
|
1720
|
+
var dc = (0, import_rfdc2.default)();
|
1721
|
+
function createConsoleLogDrain(level) {
|
1722
|
+
return ([severity, ...other]) => {
|
1723
|
+
if (!isEnabled(level, severity)) {
|
1724
|
+
return;
|
1725
|
+
}
|
1726
|
+
const [id, ...params] = other;
|
1727
|
+
console[severity](`\u{1F94B} [${severity}] Uniform event ID ${id}
|
1728
|
+
`, ...params.map(dc));
|
1729
|
+
};
|
1730
|
+
}
|
1731
|
+
function enableConsoleLogDrain(level) {
|
1732
|
+
const consoleLogDrain = createConsoleLogDrain(level);
|
1733
|
+
return {
|
1734
|
+
logDrain: consoleLogDrain
|
1735
|
+
};
|
1736
|
+
}
|
1737
|
+
|
1738
|
+
// src/logging/enableDebugConsoleLogDrain.ts
|
1739
|
+
var import_rfdc3 = __toESM(require("rfdc"));
|
1740
|
+
|
1741
|
+
// src/logging/messageContent.ts
|
1742
|
+
var messageContent = {
|
1743
|
+
1: () => ["context", "initializing Uniform Context"],
|
1744
|
+
2: (update) => ["context", "received update()", update],
|
1745
|
+
3: (scores) => ["context", "new score vector", scores],
|
1746
|
+
4: (quirks) => ["context", "updated quirks", quirks],
|
1747
|
+
5: (enrichment) => ["context", "ignored enrichment update for unknown enrichment category", enrichment.cat],
|
1748
|
+
101: (commands) => ["storage", "received update commands", commands],
|
1749
|
+
102: (data) => ["storage", "data was updated", data],
|
1750
|
+
103: (fromAllDevices) => [
|
1751
|
+
"storage",
|
1752
|
+
`deleting visitor data ${fromAllDevices ? "from all devices" : "from this device"}`
|
1753
|
+
],
|
1754
|
+
104: (isControl) => [
|
1755
|
+
"context",
|
1756
|
+
isControl ? "Visitor assigned to personalization control group" : "Visitor assigned to personalization experiment group"
|
1757
|
+
],
|
1758
|
+
110: ({ dim, cap, score }) => ["storage", `${dim} score ${score} exceeded cap ${cap}. Rounded down.`],
|
1759
|
+
120: () => ["storage", "visitor data expired and was cleared"],
|
1760
|
+
130: (data) => [
|
1761
|
+
"storage",
|
1762
|
+
"server to client transition score data was loaded; it will persist until the next update event occurs",
|
1763
|
+
data
|
1764
|
+
],
|
1765
|
+
131: () => ["storage", "server to client transition data was discarded"],
|
1766
|
+
140: (decayMessage) => ["storage", `score decay was applied: ${decayMessage}`],
|
1767
|
+
200: () => ["signals", "evaluating signals"],
|
1768
|
+
201: (signal) => ["signals", `evaluating signal ${signal.id} (${signal.dur})`],
|
1769
|
+
202: (group) => ["signals", group.op === "|" ? "OR" : "AND"],
|
1770
|
+
203: ({ criteria, result, explanation }) => [
|
1771
|
+
"signals",
|
1772
|
+
`${criteria.type}: ${explanation} is ${result.result} [${result.changed ? "CHANGED" : "unchanged"}]`
|
1773
|
+
],
|
1774
|
+
204: (result) => [
|
1775
|
+
"signals",
|
1776
|
+
`group result: ${result.result} [${result.changed ? "CHANGED" : "unchanged"}]`
|
1777
|
+
],
|
1778
|
+
300: (placement) => ["personalization", `executing personalization '${placement.name}'`],
|
1779
|
+
301: ({ id, op }) => ["personalization", `testing variation ${id} (${op === "|" ? "OR" : "AND"})`],
|
1780
|
+
302: ({ matched, description }) => ["personalization", `${description} is ${matched}`],
|
1781
|
+
303: (selected) => ["personalization", selected ? "selected variation" : "did not select variation"],
|
1782
|
+
400: (name) => ["testing", `executing A/B test '${name}'`],
|
1783
|
+
401: (testName) => ["testing", `${testName} is not registered in the manifest; it will not be run.`],
|
1784
|
+
402: ({ missingVariant, variants }) => [
|
1785
|
+
"testing",
|
1786
|
+
`test variation '${missingVariant}' previously assigned to the visitor for this test no longer exists as a variant. It will be removed. This may indicate changing test variations after publishing a test, which will make results invalid. Known variants: ${variants.join(
|
1787
|
+
", "
|
1788
|
+
)}`
|
1789
|
+
],
|
1790
|
+
403: (variant) => ["testing", `assigned new test variant '${variant}'`],
|
1791
|
+
404: (variant) => ["testing", `displaying variation '${variant}'`],
|
1792
|
+
700: () => [
|
1793
|
+
"gtag",
|
1794
|
+
"gtag is not defined, skipping analytics event emission. Ensure you have added the gtag script to your page."
|
1795
|
+
],
|
1796
|
+
701: () => ["gtag", "enabled gtag event signal redirection"]
|
1797
|
+
};
|
1798
|
+
|
1799
|
+
// src/logging/enableDebugConsoleLogDrain.ts
|
1800
|
+
var dc2 = (0, import_rfdc3.default)();
|
1801
|
+
function createDebugConsoleLogDrain(level, options) {
|
1802
|
+
const isServer = typeof document === "undefined";
|
1803
|
+
const { enableOnServer = false } = options != null ? options : {};
|
1804
|
+
return ([severity, ...other]) => {
|
1805
|
+
if (!isEnabled(level, severity) || isServer && !enableOnServer) {
|
1806
|
+
return;
|
1807
|
+
}
|
1808
|
+
const [id, ...params] = other;
|
1809
|
+
let consoleFunc = console[severity];
|
1810
|
+
if (params[0] === "GROUP") {
|
1811
|
+
params.shift();
|
1812
|
+
consoleFunc = console.groupCollapsed;
|
1813
|
+
}
|
1814
|
+
if (params[0] === "ENDGROUP") {
|
1815
|
+
console.groupEnd();
|
1816
|
+
return;
|
1817
|
+
}
|
1818
|
+
const messageFunc = messageContent[id];
|
1819
|
+
let icon = "";
|
1820
|
+
switch (severity) {
|
1821
|
+
case "debug":
|
1822
|
+
icon = "\u{1F41E}";
|
1823
|
+
break;
|
1824
|
+
case "info":
|
1825
|
+
icon = "\u{1F4AC}";
|
1826
|
+
break;
|
1827
|
+
case "warn":
|
1828
|
+
icon = "\u26A0\uFE0F";
|
1829
|
+
break;
|
1830
|
+
case "error":
|
1831
|
+
icon = "\u{1F4A5}";
|
1832
|
+
break;
|
1833
|
+
}
|
1834
|
+
const messagePrefix = icon;
|
1835
|
+
if (!messageFunc) {
|
1836
|
+
consoleFunc(
|
1837
|
+
`${messagePrefix} unknown event ID ${id}. Log messages data may be older than Uniform Context package.`,
|
1838
|
+
...params
|
1839
|
+
);
|
1840
|
+
return;
|
1841
|
+
}
|
1842
|
+
const [category, messageBody, ...outParams] = messageFunc(...params);
|
1843
|
+
consoleFunc(`${messagePrefix}[${category}] ${messageBody}
|
1844
|
+
`, ...outParams.map(dc2));
|
1845
|
+
};
|
1846
|
+
}
|
1847
|
+
function enableDebugConsoleLogDrain(level, options) {
|
1848
|
+
const debugConsoleLogDrain = createDebugConsoleLogDrain(level, options);
|
1849
|
+
return { logDrain: debugConsoleLogDrain };
|
1850
|
+
}
|
1851
|
+
|
1852
|
+
// src/quickconnect/quickconnect.ts
|
1853
|
+
function serializeQuickConnect(config) {
|
1854
|
+
return `${config.apiKey}|${config.projectId}${config.apiHost ? `|${config.apiHost}` : ""}`;
|
1855
|
+
}
|
1856
|
+
function parseQuickConnect(serialized) {
|
1857
|
+
const [apiKey, projectId, apiHost] = serialized.split("|");
|
1858
|
+
if (!apiKey.startsWith("uf")) {
|
1859
|
+
throw new Error("Invalid API key");
|
1860
|
+
}
|
1861
|
+
if (!/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/i.test(projectId)) {
|
1862
|
+
throw new Error("Invalid project ID");
|
1863
|
+
}
|
1864
|
+
return {
|
1865
|
+
apiKey,
|
1866
|
+
projectId,
|
1867
|
+
apiHost: apiHost || "https://uniform.app"
|
1868
|
+
};
|
1869
|
+
}
|
1870
|
+
// Annotate the CommonJS export names for ESM import in node:
|
1871
|
+
0 && (module.exports = {
|
1872
|
+
Context,
|
1873
|
+
CookieTransitionDataStore,
|
1874
|
+
EdgeNodeTagName,
|
1875
|
+
EdgeTransitionDataStore,
|
1876
|
+
GroupCriteriaEvaluator,
|
1877
|
+
ManifestInstance,
|
1878
|
+
SERVER_STATE_ID,
|
1879
|
+
ScriptType,
|
1880
|
+
TransitionDataStore,
|
1881
|
+
UNIFORM_DEFAULT_COOKIE_NAME,
|
1882
|
+
VisitorDataStore,
|
1883
|
+
computeAggregateDimensions,
|
1884
|
+
cookieEvaluator,
|
1885
|
+
createConsoleLogDrain,
|
1886
|
+
createDebugConsoleLogDrain,
|
1887
|
+
createLinearDecay,
|
1888
|
+
currentPageEvaluator,
|
1889
|
+
emptyVisitorData,
|
1890
|
+
enableConsoleLogDrain,
|
1891
|
+
enableContextDevTools,
|
1892
|
+
enableDebugConsoleLogDrain,
|
1893
|
+
evaluateVariantMatch,
|
1894
|
+
eventEvaluator,
|
1895
|
+
explainStringMatch,
|
1896
|
+
explainStringMatchCriteria,
|
1897
|
+
getEnrichmentVectorKey,
|
1898
|
+
isStringMatch,
|
1899
|
+
pageViewCountDimension,
|
1900
|
+
pageViewCountEvaluator,
|
1901
|
+
parseQuickConnect,
|
1902
|
+
personalizeVariations,
|
1903
|
+
queryStringEvaluator,
|
1904
|
+
quirkEvaluator,
|
1905
|
+
serializeQuickConnect,
|
1906
|
+
testVariations
|
1907
|
+
});
|