@growthbook/edge-utils 0.1.6 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
1
 
2
- export const sdkWrapper = "var _growthbook=function(){\"use strict\";function t(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)t[i]=n[i]}return t}var e=function e(n,i){function r(e,r,s){if(\"undefined\"!=typeof document){\"number\"==typeof(s=t({},i,s)).expires&&(s.expires=new Date(Date.now()+864e5*s.expires)),s.expires&&(s.expires=s.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o=\"\";for(var u in s)s[u]&&(o+=\"; \"+u,!0!==s[u]&&(o+=\"=\"+s[u].split(\";\")[0]));return document.cookie=e+\"=\"+n.write(r,e)+o}}return Object.create({set:r,get:function(t){if(\"undefined\"!=typeof document&&(!arguments.length||t)){for(var e=document.cookie?document.cookie.split(\"; \"):[],i={},r=0;r<e.length;r++){var s=e[r].split(\"=\"),o=s.slice(1).join(\"=\");try{var u=decodeURIComponent(s[0]);if(i[u]=n.read(o,u),t===u)break}catch(t){}}return t?i[t]:i}},remove:function(e,n){r(e,\"\",t({},n,{expires:-1}))},withAttributes:function(n){return e(this.converter,t({},this.attributes,n))},withConverter:function(n){return e(t({},this.converter,n),this.attributes)}},{attributes:{value:Object.freeze(i)},converter:{value:Object.freeze(n)}})}({read:function(t){return\'\"\'===t[0]&&(t=t.slice(1,-1)),t.replace(/(%[\\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:\"/\"});const n={fetch:globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,SubtleCrypto:globalThis.crypto?globalThis.crypto.subtle:void 0,EventSource:globalThis.EventSource};function i(t){let e=2166136261;const n=t.length;for(let i=0;i<n;i++)e^=t.charCodeAt(i),e+=(e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24);return e>>>0}function r(t,e,n){return 2===n?i(i(t+e)+\"\")%1e4/1e4:1===n?i(e+t)%1e3/1e3:null}function s(t,e){return t>=e[0]&&t<e[1]}function o(t){try{const e=t.replace(/([^\\\\])\\//g,\"$1\\\\/\");return new RegExp(e)}catch(t){return void console.error(t)}}function u(t,e){if(!e.length)return!1;let n=!1,i=!1;for(let r=0;r<e.length;r++){const s=c(t,e[r].type,e[r].pattern);if(!1===e[r].include){if(s)return!1}else n=!0,s&&(i=!0)}return i||!n}function c(t,e,n){try{const i=new URL(t,\"https://_\");if(\"regex\"===e){const t=o(n);return!!t&&(t.test(i.href)||t.test(i.href.substring(i.origin.length)))}return\"simple\"===e&&function(t,e){try{const n=new URL(e.replace(/^([^:/?]*)\\./i,\"https://$1.\").replace(/\\*/g,\"_____\"),\"https://_____\"),i=[[t.host,n.host,!1],[t.pathname,n.pathname,!0]];return n.hash&&i.push([t.hash,n.hash,!1]),n.searchParams.forEach(((e,n)=>{i.push([t.searchParams.get(n)||\"\",e,!1])})),!i.some((t=>!function(t,e,n){try{let i=e.replace(/[*.+?^${}()|[\\]\\\\]/g,\"\\\\$&\").replace(/_____/g,\".*\");return n&&(i=\"\\\\/?\"+i.replace(/(^\\/|\\/$)/g,\"\")+\"\\\\/?\"),new RegExp(\"^\"+i+\"$\",\"i\").test(t)}catch(t){return!1}}(t[0],t[1],t[2])))}catch(t){return!1}}(i,n)}catch(t){return!1}}const a=t=>Uint8Array.from(atob(t),(t=>t.charCodeAt(0)));async function h(t,e,i){if(e=e||\"\",!(i=i||globalThis.crypto&&globalThis.crypto.subtle||n.SubtleCrypto))throw new Error(\"No SubtleCrypto implementation found\");try{const n=await i.importKey(\"raw\",a(e),{name:\"AES-CBC\",length:128},!0,[\"encrypt\",\"decrypt\"]),[r,s]=t.split(\".\"),o=await i.decrypt({name:\"AES-CBC\",iv:a(r)},n,a(s));return(new TextDecoder).decode(o)}catch(t){throw new Error(\"Failed to decrypt\")}}function l(t){return\"string\"==typeof t?t:JSON.stringify(t)}function f(t){\"number\"==typeof t&&(t+=\"\"),t&&\"string\"==typeof t||(t=\"0\");const e=t.replace(/(^v|\\+.*$)/g,\"\").split(/[-.]/);return 3===e.length&&e.push(\"~\"),e.map((t=>t.match(/^[0-9]+$/)?t.padStart(5,\" \"):t)).join(\"-\")}function d(t){return\"object\"==typeof t&&null!==t}function w(t){return t.urlPatterns&&t.variations.some((t=>d(t)&&\"urlRedirect\"in t))?\"redirect\":t.variations.some((t=>d(t)&&(t.domMutations||\"js\"in t||\"css\"in t)))?\"visual\":\"unknown\"}async function y(t,e){return new Promise((n=>{let i,r=!1;const s=t=>{r||(r=!0,i&&clearTimeout(i),n(t||null))};e&&(i=setTimeout((()=>s()),e)),t.then((t=>s(t))).catch((()=>s()))}))}const p={staleTTL:6e4,maxAge:144e5,cacheKey:\"gbFeaturesCache\",backgroundSync:!0,maxEntries:10,disableIdleStreams:!1,idleStreamInterval:2e4,disableCache:!1},v=n,m={fetchFeaturesCall:t=>{let{host:e,clientKey:n,headers:i}=t;return v.fetch(\"\".concat(e,\"/api/features/\").concat(n),{headers:i})},fetchRemoteEvalCall:t=>{let{host:e,clientKey:n,payload:i,headers:r}=t;const s={method:\"POST\",headers:{\"Content-Type\":\"application/json\",...r},body:JSON.stringify(i)};return v.fetch(\"\".concat(e,\"/api/eval/\").concat(n),s)},eventSourceCall:t=>{let{host:e,clientKey:n,headers:i}=t;return i?new v.EventSource(\"\".concat(e,\"/sub/\").concat(n),{headers:i}):new v.EventSource(\"\".concat(e,\"/sub/\").concat(n))},startIdleListener:()=>{let t;if(\"undefined\"==typeof window||\"undefined\"==typeof document)return;const e=()=>{\"visible\"===document.visibilityState?(window.clearTimeout(t),A.forEach((t=>{t&&\"idle\"===t.state&&U(t)}))):\"hidden\"===document.visibilityState&&(t=window.setTimeout(C,p.idleStreamInterval))};return document.addEventListener(\"visibilitychange\",e),()=>document.removeEventListener(\"visibilitychange\",e)},stopIdleListener:()=>{}};try{globalThis.localStorage&&(v.localStorage=globalThis.localStorage)}catch(t){}const g=new Map;let b=!1;const k=new Map,S=new Map,A=new Map,_=new Set;function x(t){const e=E(t),n=g.get(e)||new Set;n.add(t),g.set(e,n)}function C(){A.forEach((t=>{t&&(t.state=\"idle\",M(t))}))}async function O(){try{if(!v.localStorage)return;await v.localStorage.setItem(p.cacheKey,JSON.stringify(Array.from(k.entries())))}catch(t){}}function E(t){const[e,n]=t.getApiInfo();return\"\".concat(e,\"||\").concat(n)}function $(t){const e=E(t);if(!t.isRemoteEval())return e;const n=t.getAttributes(),i=t.getCacheKeyAttributes()||Object.keys(t.getAttributes()),r={};i.forEach((t=>{r[t]=n[t]}));const s=t.getForcedVariations(),o=t.getUrl();return\"\".concat(e,\"||\").concat(JSON.stringify({ca:r,fv:s,url:o}))}function R(){const t=Array.from(k.entries()).map((t=>{let[e,n]=t;return{key:e,staleAt:n.staleAt.getTime()}})).sort(((t,e)=>t.staleAt-e.staleAt)),e=Math.min(Math.max(0,k.size-p.maxEntries),k.size);for(let n=0;n<e;n++)k.delete(t[n].key)}function B(t,e,n){const i=n.dateUpdated||\"\",r=new Date(Date.now()+p.staleTTL),s=p.disableCache?void 0:k.get(e);if(s&&i&&s.version===i)return s.staleAt=r,void O();p.disableCache||(k.set(e,{data:n,version:i,staleAt:r,sse:_.has(t)}),R()),O();const o=g.get(t);o&&o.forEach((t=>async function(t,e){await t.setPayload(e||t.getPayload())}(t,n)))}async function F(t){const{apiHost:e,apiRequestHeaders:n}=t.getApiHosts(),i=t.getClientKey(),r=t.isRemoteEval(),s=E(t),o=$(t);let u=S.get(o);return u||(u=(r?m.fetchRemoteEvalCall({host:e,clientKey:i,payload:{attributes:t.getAttributes(),forcedVariations:t.getForcedVariations(),forcedFeatures:Array.from(t.getForcedFeatures().entries()),url:t.getUrl()},headers:n}):m.fetchFeaturesCall({host:e,clientKey:i,headers:n})).then((t=>{if(!t.ok)throw new Error(\"HTTP error: \".concat(t.status));return\"enabled\"===t.headers.get(\"x-sse-support\")&&_.add(s),t.json()})).then((e=>(B(s,o,e),N(t),S.delete(o),{data:e,success:!0,source:\"network\"}))).catch((t=>(S.delete(o),{data:null,source:\"error\",success:!1,error:t}))),S.set(o,u)),u}function N(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=E(t),i=$(t),{streamingHost:r,streamingHostRequestHeaders:s}=t.getApiHosts(),o=t.getClientKey();if(e&&_.add(n),p.backgroundSync&&_.has(n)&&v.EventSource){if(A.has(n))return;const t={src:null,host:r,clientKey:o,headers:s,cb:e=>{try{if(\"features-updated\"===e.type){const t=g.get(n);t&&t.forEach((t=>{F(t)}))}else if(\"features\"===e.type){const t=JSON.parse(e.data);B(n,i,t)}t.errors=0}catch(e){T(t)}},errors:0,state:\"active\"};A.set(n,t),U(t)}}function T(t){if(\"idle\"!==t.state&&(t.errors++,t.errors>3||t.src&&2===t.src.readyState)){const e=Math.pow(3,t.errors-3)*(1e3+1e3*Math.random());M(t),setTimeout((()=>{[\"idle\",\"active\"].includes(t.state)||U(t)}),Math.min(e,3e5))}}function M(t){t.src&&(t.src.onopen=null,t.src.onerror=null,t.src.close(),t.src=null,\"active\"===t.state&&(t.state=\"disabled\"))}function U(t){t.src=m.eventSourceCall({host:t.host,clientKey:t.clientKey,headers:t.headers}),t.state=\"active\",t.src.addEventListener(\"features\",t.cb),t.src.addEventListener(\"features-updated\",t.cb),t.src.onerror=()=>T(t),t.src.onopen=()=>{t.errors=0}}function I(t,e){M(t),A.delete(e)}var V=/^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/,J={revert:function(){}},j=new Map,D=new Set;function P(t){var e=j.get(t);return e||j.set(t,e={element:t,attributes:{}}),e}function K(t,e,n,i,r){var s=n(t),o={isDirty:!1,originalValue:s,virtualValue:s,mutations:[],el:t,t:null,observer:new MutationObserver((function(){if(\"position\"!==e||!o.t){\"position\"===e&&(o.t=setTimeout((function(){o.t=null}),1e3));var i=n(t);\"position\"===e&&i.parentNode===o.virtualValue.parentNode&&i.insertBeforeNode===o.virtualValue.insertBeforeNode||i!==o.virtualValue&&(o.originalValue=i,r(o))}})),mutationRunner:r,setValue:i,getCurrentValue:n};return\"position\"===e&&t.parentNode?o.observer.observe(t.parentNode,{childList:!0,subtree:!0,attributes:!1,characterData:!1}):o.observer.observe(t,function(t){return\"html\"===t?{childList:!0,subtree:!0,attributes:!0,characterData:!0}:{childList:!1,subtree:!1,attributes:!0,attributeFilter:[t]}}(e)),o}function L(t,e){var n=e.getCurrentValue(e.el);e.virtualValue=t,t&&\"string\"!=typeof t?n&&t.parentNode===n.parentNode&&t.insertBeforeNode===n.insertBeforeNode||(e.isDirty=!0,at()):t!==n&&(e.isDirty=!0,at())}function H(t){var e=t.originalValue;t.mutations.forEach((function(t){return e=t.mutate(e)})),L(function(t){return et||(et=document.createElement(\"div\")),et.innerHTML=t,et.innerHTML}(e),t)}function q(t){var e=new Set(t.originalValue.split(/\\s+/).filter(Boolean));t.mutations.forEach((function(t){return t.mutate(e)})),L(Array.from(e).filter(Boolean).join(\" \"),t)}function G(t){var e=t.originalValue;t.mutations.forEach((function(t){return e=t.mutate(e)})),L(e,t)}function z(t){var e=t.originalValue;t.mutations.forEach((function(t){var n=function(t){var e=t.insertBeforeSelector,n=document.querySelector(t.parentSelector);if(!n)return null;var i=e?document.querySelector(e):null;return e&&!i?null:{parentNode:n,insertBeforeNode:i}}(t.mutate());e=n||e})),L(e,t)}var Z=function(t){return t.innerHTML},Q=function(t,e){return t.innerHTML=e};function W(t){var e=P(t);return e.html||(e.html=K(t,\"html\",Z,Q,H)),e.html}var X=function(t){return{parentNode:t.parentElement,insertBeforeNode:t.nextElementSibling}},Y=function(t,e){e.insertBeforeNode&&!e.parentNode.contains(e.insertBeforeNode)||e.parentNode.insertBefore(t,e.insertBeforeNode)};function tt(t){var e=P(t);return e.position||(e.position=K(t,\"position\",X,Y,z)),e.position}var et,nt,it=function(t,e){return e?t.className=e:t.removeAttribute(\"class\")},rt=function(t){return t.className};function st(t){var e=P(t);return e.classes||(e.classes=K(t,\"class\",rt,it,q)),e.classes}function ot(t,e){var n,i=P(t);return i.attributes[e]||(i.attributes[e]=K(t,e,(n=e,function(t){var e;return null!=(e=t.getAttribute(n))?e:null}),function(t){return function(e,n){return null!==n?e.setAttribute(t,n):e.removeAttribute(t)}}(e),G)),i.attributes[e]}function ut(t,e,n){if(n.isDirty){n.isDirty=!1;var i=n.virtualValue;n.mutations.length||function(t,e){var n,i,r=j.get(t);if(r)if(\"html\"===e)null==(n=r.html)||null==(i=n.observer)||i.disconnect(),delete r.html;else if(\"class\"===e){var s,o;null==(s=r.classes)||null==(o=s.observer)||o.disconnect(),delete r.classes}else if(\"position\"===e){var u,c;null==(u=r.position)||null==(c=u.observer)||c.disconnect(),delete r.position}else{var a,h,l;null==(a=r.attributes)||null==(h=a[e])||null==(l=h.observer)||l.disconnect(),delete r.attributes[e]}}(t,e),n.setValue(t,i)}}function ct(t,e){t.html&&ut(e,\"html\",t.html),t.classes&&ut(e,\"class\",t.classes),t.position&&ut(e,\"position\",t.position),Object.keys(t.attributes).forEach((function(n){ut(e,n,t.attributes[n])}))}function at(){j.forEach(ct)}function ht(t){if(\"position\"!==t.kind||1!==t.elements.size){var e=new Set(t.elements);document.querySelectorAll(t.selector).forEach((function(n){e.has(n)||(t.elements.add(n),function(t,e){var n=null;\"html\"===t.kind?n=W(e):\"class\"===t.kind?n=st(e):\"attribute\"===t.kind?n=ot(e,t.attribute):\"position\"===t.kind&&(n=tt(e)),n&&(n.mutations.push(t),n.mutationRunner(n))}(t,n))}))}}function lt(){D.forEach(ht)}function ft(t){return\"undefined\"==typeof document?J:(D.add(t),ht(t),{revert:function(){var e;(e=t).elements.forEach((function(t){return function(t,e){var n=null;if(\"html\"===t.kind?n=W(e):\"class\"===t.kind?n=st(e):\"attribute\"===t.kind?n=ot(e,t.attribute):\"position\"===t.kind&&(n=tt(e)),n){var i=n.mutations.indexOf(t);-1!==i&&n.mutations.splice(i,1),n.mutationRunner(n)}}(e,t)})),e.elements.clear(),D.delete(e)}})}function dt(t,e){return ft({kind:\"html\",elements:new Set,mutate:e,selector:t})}function wt(t,e){return ft({kind:\"class\",elements:new Set,mutate:e,selector:t})}function yt(t,e,n){return V.test(e)?\"class\"===e||\"className\"===e?wt(t,(function(t){var e=n(Array.from(t).join(\" \"));t.clear(),e&&e.split(/\\s+/g).filter(Boolean).forEach((function(e){return t.add(e)}))})):ft({kind:\"attribute\",attribute:e,elements:new Set,mutate:n,selector:t}):J}\"undefined\"!=typeof document&&(nt||(nt=new MutationObserver((function(){lt()}))),lt(),nt.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1,characterData:!1}));const pt={};function vt(t,e,n){n=n||{};for(const[i,r]of Object.entries(e))switch(i){case\"$or\":if(!At(t,r,n))return!1;break;case\"$nor\":if(At(t,r,n))return!1;break;case\"$and\":if(!_t(t,r,n))return!1;break;case\"$not\":if(vt(t,r,n))return!1;break;default:if(!gt(r,mt(t,i),n))return!1}return!0}function mt(t,e){const n=e.split(\".\");let i=t;for(let t=0;t<n.length;t++){if(!i||\"object\"!=typeof i||!(n[t]in i))return null;i=i[n[t]]}return i}function gt(t,e,n){if(\"string\"==typeof t)return e+\"\"===t;if(\"number\"==typeof t)return 1*e===t;if(\"boolean\"==typeof t)return!!e===t;if(null===t)return null===e;if(Array.isArray(t)||!bt(t))return JSON.stringify(e)===JSON.stringify(t);for(const i in t)if(!St(i,e,t[i],n))return!1;return!0}function bt(t){const e=Object.keys(t);return e.length>0&&e.filter((t=>\"$\"===t[0])).length===e.length}function kt(t,e){return Array.isArray(t)?t.some((t=>e.includes(t))):e.includes(t)}function St(t,e,n,i){switch(t){case\"$veq\":return f(e)===f(n);case\"$vne\":return f(e)!==f(n);case\"$vgt\":return f(e)>f(n);case\"$vgte\":return f(e)>=f(n);case\"$vlt\":return f(e)<f(n);case\"$vlte\":return f(e)<=f(n);case\"$eq\":return e===n;case\"$ne\":return e!==n;case\"$lt\":return e<n;case\"$lte\":return e<=n;case\"$gt\":return e>n;case\"$gte\":return e>=n;case\"$exists\":return n?null!=e:null==e;case\"$in\":return!!Array.isArray(n)&&kt(e,n);case\"$inGroup\":return kt(e,i[n]||[]);case\"$notInGroup\":return!kt(e,i[n]||[]);case\"$nin\":return!!Array.isArray(n)&&!kt(e,n);case\"$not\":return!gt(n,e,i);case\"$size\":return!!Array.isArray(e)&&gt(n,e.length,i);case\"$elemMatch\":return function(t,e,n){if(!Array.isArray(t))return!1;const i=bt(e)?t=>gt(e,t,n):t=>vt(t,e,n);for(let e=0;e<t.length;e++)if(t[e]&&i(t[e]))return!0;return!1}(e,n,i);case\"$all\":if(!Array.isArray(e))return!1;for(let t=0;t<n.length;t++){let r=!1;for(let s=0;s<e.length;s++)if(gt(n[t],e[s],i)){r=!0;break}if(!r)return!1}return!0;case\"$regex\":try{return(r=n,pt[r]||(pt[r]=new RegExp(r.replace(/([^\\\\])\\//g,\"$1\\\\/\"))),pt[r]).test(e)}catch(t){return!1}case\"$type\":return function(t){if(null===t)return\"null\";if(Array.isArray(t))return\"array\";const e=typeof t;return[\"string\",\"number\",\"boolean\",\"object\",\"undefined\"].includes(e)?e:\"unknown\"}(e)===n;default:return console.error(\"Unknown operator: \"+t),!1}var r}function At(t,e,n){if(!e.length)return!0;for(let i=0;i<e.length;i++)if(vt(t,e[i],n))return!0;return!1}function _t(t,e,n){for(let i=0;i<e.length;i++)if(!vt(t,e[i],n))return!1;return!0}const xt=\"undefined\"!=typeof window&&\"undefined\"!=typeof document,Ct=function(){let t;try{t=\"1.2.1\"}catch(e){t=\"\"}return t}();class Ot{constructor(t){this.prefix=(t=t||{}).prefix||\"\"}async getAllAssignments(t){const e={};return(await Promise.all(Object.entries(t).map((t=>{let[e,n]=t;return this.getAssignments(e,n)})))).forEach((t=>{if(t){const n=\"\".concat(t.attributeName,\"||\").concat(t.attributeValue);e[n]=t}})),e}getKey(t,e){return\"\".concat(this.prefix).concat(t,\"||\").concat(e)}}window.dataLayer=window.dataLayer||[];const Et=document.currentScript,$t=Et?Et.dataset:{},Rt=window.growthbook_config||{};function Bt(t){const e=(\"; \"+document.cookie).split(\"; \".concat(t,\"=\"));return 2===e.length?e[1].split(\";\")[0]:\"\"}function Ft(){return window.crypto&&crypto.randomUUID?crypto.randomUUID():\"10000000-1000-4000-8000-100000000000\".replace(/[018]/g,(t=>(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)))}const Nt=Rt.uuidCookieName||$t.uuidCookieName||\"gbuuid\",Tt=Rt.uuidKey||$t.uuidKey||\"id\";let Mt,Ut,It=Rt.uuid||$t.uuid||\"\";function Vt(){!function(t,e){const n=new Date;n.setTime(n.getTime()+3456e7),document.cookie=t+\"=\"+e+\";path=/;expires=\"+n.toUTCString()}(Nt,It)}function Jt(){let t={};try{const e=sessionStorage.getItem(\"utm_params\");if(e&&(t=JSON.parse(e)),location.search){const e=new URLSearchParams(location.search);let n=!1;[\"source\",\"medium\",\"campaign\",\"term\",\"content\"].forEach((i=>{const r=\"utm_\".concat(i),s=\"utm\"+i[0].toUpperCase()+i.slice(1);e.has(r)&&(t[s]=e.get(r)||\"\",n=!0)})),n&&sessionStorage.setItem(\"utm_params\",JSON.stringify(t))}}catch(t){}return t}function jt(){if(!window.dataLayer||!window.dataLayer.forEach)return{};const t={};return window.dataLayer.forEach((e=>{e&&\"object\"==typeof e&&!(\"length\"in e)&&(\"event\"in e||Object.keys(e).forEach((n=>{if(\"string\"!=typeof n||n.match(/^(gtm)/))return;const i=e[n];[\"string\",\"number\",\"boolean\"].includes(typeof i)&&(t[n]=i)})))})),t}function Dt(){const t=$t.noAutoAttributes?{}:function(t,e){const n=null==t.noAutoCookies,i=navigator.userAgent,r=i.match(/Edg/)?\"edge\":i.match(/Chrome/)?\"chrome\":i.match(/Firefox/)?\"firefox\":i.match(/Safari/)?\"safari\":\"unknown\",s=function(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return It||(It=Bt(Nt),It||(It=Ft(),t&&Vt(),It))}(n);return(e.persistUuidOnLoad||t.persistUuidOnLoad)&&n&&Vt(),{...jt(),[Tt]:s,url:location.href,path:location.pathname,host:location.host,query:location.search,pageTitle:document&&document.title,deviceType:i.match(/Mobi/)?\"mobile\":\"desktop\",browser:r,...Jt()}}($t,Rt);return Rt.attributes&&Object.assign(t,Rt.attributes),t}function Pt(){var t,e;window.clearTimeout(Mt);let n=null!==(t=null!==(e=Rt.antiFlickerTimeout)&&void 0!==e?e:$t.antiFlickerTimeout?parseInt($t.antiFlickerTimeout):null)&&void 0!==t?t:3500;isFinite(n)||(n=3500);try{if(!document.getElementById(\"gb-anti-flicker-style\")){const t=document.createElement(\"style\");t.setAttribute(\"id\",\"gb-anti-flicker-style\"),t.innerHTML=\".gb-anti-flicker { opacity: 0 !important; pointer-events: none; }\",document.head.appendChild(t)}document.documentElement.classList.add(\"gb-anti-flicker\"),Mt=window.setTimeout(Kt,n)}catch(t){console.error(t)}}function Kt(){window.clearTimeout(Mt);try{document.documentElement.classList.remove(\"gb-anti-flicker\")}catch(t){console.error(t)}}(Rt.antiFlicker||$t.antiFlicker)&&Pt(),\"cookie\"===Rt.useStickyBucketService||\"cookie\"===$t.useStickyBucketService?Ut=new class extends Ot{constructor(t){let{prefix:e=\"gbStickyBuckets__\",jsCookie:n,cookieAttributes:i={expires:180}}=t;super(),this.prefix=e,this.jsCookie=n,this.cookieAttributes=i}async getAssignments(t,e){const n=this.getKey(t,e);let i=null;if(!this.jsCookie)return i;try{const t=this.jsCookie.get(n),e=JSON.parse(t||\"{}\");e.attributeName&&e.attributeValue&&e.assignments&&(i=e)}catch(t){}return i}async saveAssignments(t){const e=this.getKey(t.attributeName,t.attributeValue);if(!this.jsCookie)return;const n=JSON.stringify(t);this.jsCookie.set(e,n,this.cookieAttributes)}}({prefix:Rt.stickyBucketPrefix||$t.stickyBucketPrefix||void 0,jsCookie:e}):\"localStorage\"!==Rt.useStickyBucketService&&\"localStorage\"!==$t.useStickyBucketService||(Ut=new class extends Ot{constructor(t){t=t||{},super(),this.prefix=t.prefix||\"gbStickyBuckets__\";try{this.localStorage=t.localStorage||globalThis.localStorage}catch(t){}}async getAssignments(t,e){const n=this.getKey(t,e);let i=null;if(!this.localStorage)return i;try{const t=await this.localStorage.getItem(n)||\"{}\",e=JSON.parse(t);e.attributeName&&e.attributeValue&&e.assignments&&(i=e)}catch(t){}return i}async saveAssignments(t){const e=this.getKey(t.attributeName,t.attributeValue);if(this.localStorage)try{await this.localStorage.setItem(e,JSON.stringify(t))}catch(t){}}}({prefix:Rt.stickyBucketPrefix||$t.stickyBucketPrefix||void 0}));const Lt=new class{constructor(t){if(t=t||{},this.version=Ct,this.i=this.context=t,this.o=t.renderer||null,this.u=new Set,this.h=new Set,this.l={},this.debug=!!t.debug,this.p=new Set,this.v=[],this.m=0,this.ready=!1,this.g=new Map,this.k=new Map,this.S={},this.A=new Map,this._=new Set,this.C=!1,this.O=\"\",this.$=new Map,this.R=!t.disableExperimentsOnLoad,t.remoteEval){if(t.decryptionKey)throw new Error(\"Encryption is not available for remoteEval\");if(!t.clientKey)throw new Error(\"Missing clientKey\");let e=!1;try{e=!!new URL(t.apiHost||\"\").hostname.match(/growthbook\\.io$/i)}catch(t){}if(e)throw new Error(\"Cannot use remoteEval on GrowthBook Cloud\")}else if(t.cacheKeyAttributes)throw new Error(\"cacheKeyAttributes are only used for remoteEval\");if(t.features&&(this.ready=!0),xt&&t.enableDevMode&&(window._growthbook=this,document.dispatchEvent(new Event(\"gbloaded\"))),t.experiments&&(this.ready=!0,this.B()),this.i.stickyBucketService&&this.i.stickyBucketAssignmentDocs)for(const t in this.i.stickyBucketAssignmentDocs){const e=this.i.stickyBucketAssignmentDocs[t];e&&this.i.stickyBucketService.saveAssignments(e).catch((()=>{}))}this.ready&&this.refreshStickyBuckets(this.getPayload())}async setPayload(t){this.F=t;const e=await this.decryptPayload(t);this.N=e,await this.refreshStickyBuckets(e),e.features&&(this.i.features=e.features),e.savedGroups&&(this.i.savedGroups=e.savedGroups),e.experiments&&(this.i.experiments=e.experiments,this.B()),this.ready=!0,this.T()}initSync(t){this.C=!0;const e=t.payload;if(e.encryptedExperiments||e.encryptedFeatures)throw new Error(\"initSync does not support encrypted payloads\");if(this.i.stickyBucketService&&!this.i.stickyBucketAssignmentDocs)throw new Error(\"initSync requires you to pass stickyBucketAssignmentDocs into the GrowthBook constructor\");if(this.F=e,this.N=e,e.features&&(this.i.features=e.features),e.experiments&&(this.i.experiments=e.experiments,this.B()),this.ready=!0,t.streaming){if(!this.i.clientKey)throw new Error(\"Must specify clientKey to enable streaming\");N(this,!0),x(this)}return this}async init(t){if(this.C=!0,(t=t||{}).cacheSettings&&(Object.assign(p,t.cacheSettings),p.backgroundSync||(_.clear(),A.forEach(I),g.clear(),m.stopIdleListener())),t.payload){if(await this.setPayload(t.payload),t.streaming){if(!this.i.clientKey)throw new Error(\"Must specify clientKey to enable streaming\");N(this,!0),x(this)}return{success:!0,source:\"init\"}}{const{data:e,...n}=await this.M({...t,allowStale:!0});return t.streaming&&x(this),await this.setPayload(e||{}),n}}async loadFeatures(t){this.C=!0,(t=t||{}).autoRefresh&&(this.i.subscribeToChanges=!0);const{data:e}=await this.M({...t,allowStale:!0});await this.setPayload(e||{}),this.U()&&x(this)}async refreshFeatures(t){const e=await this.M({...t||{},allowStale:!1});e.data&&await this.setPayload(e.data)}getApiInfo(){return[this.getApiHosts().apiHost,this.getClientKey()]}getApiHosts(){const t=this.i.apiHost||\"https://cdn.growthbook.io\";return{apiHost:t.replace(/\\/*$/,\"\"),streamingHost:(this.i.streamingHost||t).replace(/\\/*$/,\"\"),apiRequestHeaders:this.i.apiHostRequestHeaders,streamingHostRequestHeaders:this.i.streamingHostRequestHeaders}}getClientKey(){return this.i.clientKey||\"\"}getPayload(){return this.F||{features:this.getFeatures(),experiments:this.getExperiments()}}getDecryptedPayload(){return this.N||this.getPayload()}isRemoteEval(){return this.i.remoteEval||!1}getCacheKeyAttributes(){return this.i.cacheKeyAttributes}async M(t){var e;let{timeout:n,skipCache:i,allowStale:r,streaming:s}=t;if(!this.i.clientKey)throw new Error(\"Missing clientKey\");return async function(t){let{instance:e,timeout:n,skipCache:i,allowStale:r,backgroundSync:s}=t;return s||(p.backgroundSync=!1),async function(t){let{instance:e,allowStale:n,timeout:i,skipCache:r}=t;const s=E(e),o=$(e),u=new Date,c=new Date(u.getTime()-p.maxAge+p.staleTTL);await async function(){if(!b){b=!0;try{if(v.localStorage){const t=await v.localStorage.getItem(p.cacheKey);if(!p.disableCache&&t){const e=JSON.parse(t);e&&Array.isArray(e)&&e.forEach((t=>{let[e,n]=t;k.set(e,{...n,staleAt:new Date(n.staleAt)})})),R()}}}catch(t){}if(!p.disableIdleStreams){const t=m.startIdleListener();t&&(m.stopIdleListener=t)}}}();const a=p.disableCache||r?void 0:k.get(o);return a&&(n||a.staleAt>u)&&a.staleAt>c?(a.sse&&_.add(s),a.staleAt<u?F(e):N(e),{data:a.data,success:!0,source:\"cache\"}):await y(F(e),i)||{data:null,success:!1,source:\"timeout\",error:new Error(\"Timeout\")}}({instance:e,allowStale:r,timeout:n,skipCache:i})}({instance:this,timeout:n,skipCache:i||this.i.disableCache,allowStale:r,backgroundSync:null===(e=null!=s?s:this.i.backgroundSync)||void 0===e||e})}T(){if(this.o)try{this.o()}catch(t){console.error(\"Failed to render\",t)}}setFeatures(t){this.i.features=t,this.ready=!0,this.T()}async setEncryptedFeatures(t,e,n){const i=await h(t,e||this.i.decryptionKey,n);this.setFeatures(JSON.parse(i))}setExperiments(t){this.i.experiments=t,this.ready=!0,this.B()}async setEncryptedExperiments(t,e,n){const i=await h(t,e||this.i.decryptionKey,n);this.setExperiments(JSON.parse(i))}async decryptPayload(t,e,n){if((t={...t}).encryptedFeatures){try{t.features=JSON.parse(await h(t.encryptedFeatures,e||this.i.decryptionKey,n))}catch(t){console.error(t)}delete t.encryptedFeatures}if(t.encryptedExperiments){try{t.experiments=JSON.parse(await h(t.encryptedExperiments,e||this.i.decryptionKey,n))}catch(t){console.error(t)}delete t.encryptedExperiments}if(t.encryptedSavedGroups){try{t.savedGroups=JSON.parse(await h(t.encryptedSavedGroups,e||this.i.decryptionKey,n))}catch(t){console.error(t)}delete t.encryptedSavedGroups}return t}async setAttributes(t){this.i.attributes=t,this.i.stickyBucketService&&await this.refreshStickyBuckets(),this.i.remoteEval?await this.I():(this.T(),this.B())}async updateAttributes(t){return this.setAttributes({...this.i.attributes,...t})}async setAttributeOverrides(t){this.S=t,this.i.stickyBucketService&&await this.refreshStickyBuckets(),this.i.remoteEval?await this.I():(this.T(),this.B())}async setForcedVariations(t){this.i.forcedVariations=t||{},this.i.remoteEval?await this.I():(this.T(),this.B())}setForcedFeatures(t){this.k=t,this.T()}async setURL(t){if(t!==this.i.url){if(this.i.url=t,this.O=\"\",this.i.remoteEval)return await this.I(),void this.B(!0);this.B(!0)}}getAttributes(){return{...this.i.attributes,...this.S}}getForcedVariations(){return this.i.forcedVariations||{}}getForcedFeatures(){return this.k||new Map}getStickyBucketAssignmentDocs(){return this.i.stickyBucketAssignmentDocs||{}}getUrl(){return this.i.url||\"\"}getFeatures(){return this.i.features||{}}getExperiments(){return this.i.experiments||[]}getCompletedChangeIds(){return Array.from(this.h)}subscribe(t){return this.p.add(t),()=>{this.p.delete(t)}}U(){var t;return(null===(t=this.i.backgroundSync)||void 0===t||t)&&this.i.subscribeToChanges}async I(){if(!this.i.remoteEval)return;if(!this.C)return;const t=await this.M({allowStale:!1});t.data&&await this.setPayload(t.data)}getAllResults(){return new Map(this.g)}destroy(){var t;this.p.clear(),this.g.clear(),this.u.clear(),this.h.clear(),this.$.clear(),this.l={},this.v=[],this.F=void 0,this.m&&clearTimeout(this.m),t=this,g.forEach((e=>e.delete(t))),xt&&window._growthbook===this&&delete window._growthbook,this.A.forEach((t=>{t.undo()})),this.A.clear(),this._.clear()}setRenderer(t){this.o=t}forceVariation(t,e){this.i.forcedVariations=this.i.forcedVariations||{},this.i.forcedVariations[t]=e,this.i.remoteEval?this.I():(this.B(),this.T())}run(t){const{result:e}=this.V(t,null);return this.J(t,e),e}triggerExperiment(t){return this._.add(t),this.i.experiments?this.i.experiments.filter((e=>e.key===t)).map((t=>this.j(t))).filter((t=>null!==t)):null}triggerAutoExperiments(){this.R=!0,this.B(!0)}j(t,e){const n=this.A.get(t);if(t.manual&&!this._.has(t.key)&&!n)return null;let i,r;this.D(t)?i=this.P(t,-1,!1,\"\"):(({result:i,trackingCall:r}=this.V(t,null)),this.J(t,i));const s=JSON.stringify(i.value);if(!e&&i.inExperiment&&n&&n.valueHash===s)return i;if(n&&this.K(t),i.inExperiment){const e=w(t);if(\"redirect\"===e&&i.value.urlRedirect&&t.urlPatterns){const e=t.persistQueryString?function(t,e){let n,i;try{n=new URL(t),i=new URL(e)}catch(t){return console.error(\"Unable to merge query strings: \".concat(t)),e}return n.searchParams.forEach(((t,e)=>{i.searchParams.has(e)||i.searchParams.set(e,t)})),i.toString()}(this.L(),i.value.urlRedirect):i.value.urlRedirect;if(u(e,t.urlPatterns))return this.log(\"Skipping redirect because original URL matches redirect URL\",{id:t.key}),i;this.O=e;const{navigate:n,delay:s}=this.H();var o;if(n)if(xt)Promise.all([...r?[y(r,null!==(o=this.i.maxNavigateDelay)&&void 0!==o?o:1e3)]:[],new Promise((t=>{var e;return window.setTimeout(t,null!==(e=this.i.navigateDelay)&&void 0!==e?e:s)}))]).then((()=>{try{n(e)}catch(t){console.error(t)}}));else try{n(e)}catch(t){console.error(t)}}else if(\"visual\"===e){const e=this.i.applyDomChangesCallback?this.i.applyDomChangesCallback(i.value):this.q(i.value);e&&this.A.set(t,{undo:e,valueHash:s})}}return i}K(t){const e=this.A.get(t);e&&(e.undo(),this.A.delete(t))}B(t){if(!this.R)return;const e=this.i.experiments||[],n=new Set(e);this.A.forEach(((t,e)=>{n.has(e)||(t.undo(),this.A.delete(e))}));for(const n of e){const e=this.j(n,t);if(null!=e&&e.inExperiment&&\"redirect\"===w(n))break}}J(t,e){const n=t.key,i=this.g.get(n);i&&i.result.inExperiment===e.inExperiment&&i.result.variationId===e.variationId||(this.g.set(n,{experiment:t,result:e}),this.p.forEach((n=>{try{n(t,e)}catch(t){console.error(t)}})))}G(t,e){if(\"override\"===e.source)return;const n=JSON.stringify(e.value);if(this.l[t]!==n){if(this.l[t]=n,this.i.onFeatureUsage)try{this.i.onFeatureUsage(t,e)}catch(t){}xt&&window.fetch&&(this.v.push({key:t,on:e.on}),this.m||(this.m=window.setTimeout((()=>{this.m=0;const t=[...this.v];this.v=[],this.i.realtimeKey&&window.fetch(\"https://rt.growthbook.io/?key=\".concat(this.i.realtimeKey,\"&events=\").concat(encodeURIComponent(JSON.stringify(t))),{cache:\"no-cache\",mode:\"no-cors\"}).catch((()=>{}))}),this.i.realtimeInterval||2e3)))}}Z(t,e,n,i,r,s){const o={value:e,on:!!e,off:!e,source:n,ruleId:i||\"\"};return r&&(o.experiment=r),s&&(o.experimentResult=s),this.G(t,o),o}isOn(t){return this.evalFeature(t).on}isOff(t){return this.evalFeature(t).off}getFeatureValue(t,e){const n=this.evalFeature(t).value;return null===n?e:n}feature(t){return this.evalFeature(t)}evalFeature(t){return this.W(t)}W(t,e){if((e=e||{evaluatedFeatures:new Set}).evaluatedFeatures.has(t))return this.Z(t,null,\"cyclicPrerequisite\");if(e.evaluatedFeatures.add(t),e.id=t,this.k.has(t))return this.Z(t,this.k.get(t),\"override\");if(!this.i.features||!this.i.features[t])return this.Z(t,null,\"unknownFeature\");const n=this.i.features[t];if(n.rules)t:for(const i of n.rules){if(i.parentConditions)for(const n of i.parentConditions){const i=this.W(n.id,e);if(\"cyclicPrerequisite\"===i.source)return this.Z(t,null,\"cyclicPrerequisite\");if(!vt({value:i.value},n.condition||{})){if(n.gate)return this.Z(t,null,\"prerequisite\");continue t}}if(i.filters&&this.X(i.filters))continue;if(\"force\"in i){if(i.condition&&!this.Y(i.condition))continue;if(!this.tt(i.seed||t,i.hashAttribute,this.i.stickyBucketService&&!i.disableStickyBucketing?i.fallbackAttribute:void 0,i.range,i.coverage,i.hashVersion))continue;return i.tracks&&i.tracks.forEach((t=>{this.et(t.experiment,t.result)})),this.Z(t,i.force,\"force\",i.id)}if(!i.variations)continue;const n={variations:i.variations,key:i.key||t};\"coverage\"in i&&(n.coverage=i.coverage),i.weights&&(n.weights=i.weights),i.hashAttribute&&(n.hashAttribute=i.hashAttribute),i.fallbackAttribute&&(n.fallbackAttribute=i.fallbackAttribute),i.disableStickyBucketing&&(n.disableStickyBucketing=i.disableStickyBucketing),void 0!==i.bucketVersion&&(n.bucketVersion=i.bucketVersion),void 0!==i.minBucketVersion&&(n.minBucketVersion=i.minBucketVersion),i.namespace&&(n.namespace=i.namespace),i.meta&&(n.meta=i.meta),i.ranges&&(n.ranges=i.ranges),i.name&&(n.name=i.name),i.phase&&(n.phase=i.phase),i.seed&&(n.seed=i.seed),i.hashVersion&&(n.hashVersion=i.hashVersion),i.filters&&(n.filters=i.filters),i.condition&&(n.condition=i.condition);const{result:r}=this.V(n,t);if(this.J(n,r),r.inExperiment&&!r.passthrough)return this.Z(t,r.value,\"experiment\",i.id,n,r)}return this.Z(t,void 0===n.defaultValue?null:n.defaultValue,\"defaultValue\")}tt(t,e,n,i,o,u){if(!i&&void 0===o)return!0;if(!i&&0===o)return!1;const{hashValue:c}=this.nt(e,n);if(!c)return!1;const a=r(t,c,u||1);return null!==a&&(i?s(a,i):void 0===o||a<=o)}Y(t){return vt(this.getAttributes(),t,this.i.savedGroups||{})}X(t){return t.some((t=>{const{hashValue:e}=this.nt(t.attribute);if(!e)return!0;const n=r(t.seed,e,t.hashVersion||2);return null===n||!t.ranges.some((t=>s(n,t)))}))}V(t,e){const n=t.key,i=t.variations.length;if(i<2)return{result:this.P(t,-1,!1,e)};if(!1===this.i.enabled)return{result:this.P(t,-1,!1,e)};if((t=this.it(t)).urlPatterns&&!u(this.L(),t.urlPatterns))return{result:this.P(t,-1,!1,e)};const o=function(t,e,n){if(!e)return null;const i=e.split(\"?\")[1];if(!i)return null;const r=i.replace(/#.*/,\"\").split(\"&\").map((t=>t.split(\"=\",2))).filter((e=>{let[n]=e;return n===t})).map((t=>{let[,e]=t;return parseInt(e)}));return r.length>0&&r[0]>=0&&r[0]<n?r[0]:null}(n,this.L(),i);if(null!==o)return{result:this.P(t,o,!1,e)};if(this.i.forcedVariations&&n in this.i.forcedVariations)return{result:this.P(t,this.i.forcedVariations[n],!1,e)};if(\"draft\"===t.status||!1===t.active)return{result:this.P(t,-1,!1,e)};const{hashAttribute:c,hashValue:a}=this.nt(t.hashAttribute,this.i.stickyBucketService&&!t.disableStickyBucketing?t.fallbackAttribute:void 0);if(!a)return{result:this.P(t,-1,!1,e)};let h=-1,f=!1,d=!1;if(this.i.stickyBucketService&&!t.disableStickyBucketing){const{variation:e,versionIsBlocked:n}=this.rt({expKey:t.key,expBucketVersion:t.bucketVersion,expHashAttribute:t.hashAttribute,expFallbackAttribute:t.fallbackAttribute,expMinBucketVersion:t.minBucketVersion,expMeta:t.meta});f=e>=0,h=e,d=!!n}if(!f){if(t.filters){if(this.X(t.filters))return{result:this.P(t,-1,!1,e)}}else if(t.namespace&&!function(t,e){const n=r(\"__\"+e[0],t,1);return null!==n&&n>=e[1]&&n<e[2]}(a,t.namespace))return{result:this.P(t,-1,!1,e)};if(t.include&&!function(t){try{return t()}catch(t){return console.error(t),!1}}(t.include))return{result:this.P(t,-1,!1,e)};if(t.condition&&!this.Y(t.condition))return{result:this.P(t,-1,!1,e)};if(t.parentConditions)for(const n of t.parentConditions){const i=this.W(n.id);if(\"cyclicPrerequisite\"===i.source)return{result:this.P(t,-1,!1,e)};if(!vt({value:i.value},n.condition||{}))return{result:this.P(t,-1,!1,e)}}if(t.groups&&!this.st(t.groups))return{result:this.P(t,-1,!1,e)}}if(t.url&&!this.ot(t.url))return{result:this.P(t,-1,!1,e)};const w=r(t.seed||n,a,t.hashVersion||1);if(null===w)return{result:this.P(t,-1,!1,e)};if(f||(h=function(t,e){for(let n=0;n<e.length;n++)if(s(t,e[n]))return n;return-1}(w,t.ranges||function(t,e,n){(e=void 0===e?1:e)<0?e=0:e>1&&(e=1);const i=(r=t)<=0?[]:new Array(r).fill(1/r);var r;(n=n||i).length!==t&&(n=i);const s=n.reduce(((t,e)=>e+t),0);(s<.99||s>1.01)&&(n=i);let o=0;return n.map((t=>{const n=o;return o+=t,[n,n+e*t]}))}(i,void 0===t.coverage?1:t.coverage,t.weights))),d)return{result:this.P(t,-1,!1,e,void 0,!0)};if(h<0)return{result:this.P(t,-1,!1,e)};if(\"force\"in t)return{result:this.P(t,void 0===t.force?-1:t.force,!1,e)};if(this.i.qaMode)return{result:this.P(t,-1,!1,e)};if(\"stopped\"===t.status)return{result:this.P(t,-1,!1,e)};const y=this.P(t,h,!0,e,w,f);if(this.i.stickyBucketService&&!t.disableStickyBucketing){const{changed:e,key:n,doc:i}=this.ut(c,l(a),{[this.ct(t.key,t.bucketVersion)]:y.key});e&&(this.i.stickyBucketAssignmentDocs=this.i.stickyBucketAssignmentDocs||{},this.i.stickyBucketAssignmentDocs[n]=i,this.i.stickyBucketService.saveAssignments(i))}const p=this.et(t,y);return\"changeId\"in t&&t.changeId&&this.h.add(t.changeId),{result:y,trackingCall:p}}log(t,e){this.debug&&(this.i.log?this.i.log(t,e):console.log(t,e))}getDeferredTrackingCalls(){return Array.from(this.$.values())}setDeferredTrackingCalls(t){this.$=new Map(t.filter((t=>t&&t.experiment&&t.result)).map((t=>[this.ht(t.experiment,t.result),t])))}async fireDeferredTrackingCalls(){if(!this.i.trackingCallback)return;const t=[];this.$.forEach((e=>{e&&e.experiment&&e.result?t.push(this.et(e.experiment,e.result)):console.error(\"Invalid deferred tracking call\",{call:e})})),this.$.clear(),await Promise.all(t)}setTrackingCallback(t){this.i.trackingCallback=t,this.fireDeferredTrackingCalls()}ht(t,e){return e.hashAttribute+e.hashValue+t.key+e.variationId}async et(t,e){const n=this.ht(t,e);if(this.i.trackingCallback){if(!this.u.has(n)){this.u.add(n);try{await this.i.trackingCallback(t,e)}catch(t){console.error(t)}}}else this.$.has(n)||this.$.set(n,{experiment:t,result:e})}it(t){const e=t.key,n=this.i.overrides;return n&&n[e]&&\"string\"==typeof(t=Object.assign({},t,n[e])).url&&(t.url=o(t.url)),t}nt(t,e){let n=t||\"id\",i=\"\";return this.S[n]?i=this.S[n]:this.i.attributes?i=this.i.attributes[n]||\"\":this.i.user&&(i=this.i.user[n]||\"\"),!i&&e&&(this.S[e]?i=this.S[e]:this.i.attributes?i=this.i.attributes[e]||\"\":this.i.user&&(i=this.i.user[e]||\"\"),i&&(n=e)),{hashAttribute:n,hashValue:i}}P(t,e,n,i,r,s){let o=!0;(e<0||e>=t.variations.length)&&(e=0,o=!1);const{hashAttribute:u,hashValue:c}=this.nt(t.hashAttribute,this.i.stickyBucketService&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),a=t.meta?t.meta[e]:{},h={key:a.key||\"\"+e,featureId:i,inExperiment:o,hashUsed:n,variationId:e,value:t.variations[e],hashAttribute:u,hashValue:c,stickyBucketUsed:!!s};return a.name&&(h.name=a.name),void 0!==r&&(h.bucket=r),a.passthrough&&(h.passthrough=a.passthrough),h}L(){return this.i.url||(xt?window.location.href:\"\")}ot(t){const e=this.L();if(!e)return!1;const n=e.replace(/^https?:\\/\\//,\"\").replace(/^[^/]*\\//,\"/\");return!!t.test(e)||!!t.test(n)}st(t){const e=this.i.groups||{};for(let n=0;n<t.length;n++)if(e[t[n]])return!0;return!1}D(t){const e=w(t);if(\"visual\"===e){if(this.i.disableVisualExperiments)return!0;if(this.i.disableJsInjection&&t.variations.some((t=>t.js)))return!0}else{if(\"redirect\"!==e)return!0;if(this.i.disableUrlRedirectExperiments)return!0;try{const e=new URL(this.L());for(const n of t.variations){if(!n||!n.urlRedirect)continue;const t=new URL(n.urlRedirect);if(this.i.disableCrossOriginUrlRedirectExperiments){if(t.protocol!==e.protocol)return!0;if(t.host!==e.host)return!0}}}catch(e){return this.log(\"Error parsing current or redirect URL\",{id:t.key,error:e}),!0}}return!(!t.changeId||!(this.i.blockedChangeIds||[]).includes(t.changeId))}getRedirectUrl(){return this.O}H(){return this.i.navigate?{navigate:this.i.navigate,delay:0}:xt?{navigate:t=>{window.location.replace(t)},delay:100}:{navigate:null,delay:0}}q(t){if(!xt)return;const e=[];if(t.css){const n=document.createElement(\"style\");n.innerHTML=t.css,document.head.appendChild(n),e.push((()=>n.remove()))}if(t.js){const n=document.createElement(\"script\");n.innerHTML=t.js,this.i.jsInjectionNonce&&(n.nonce=this.i.jsInjectionNonce),document.head.appendChild(n),e.push((()=>n.remove()))}return t.domMutations&&t.domMutations.forEach((t=>{e.push(function(t){var e=t.selector,n=t.action,i=t.value,r=t.attribute,s=t.parentSelector,o=t.insertBeforeSelector;if(\"html\"===r){if(\"append\"===n)return dt(e,(function(t){return t+(null!=i?i:\"\")}));if(\"set\"===n)return dt(e,(function(){return null!=i?i:\"\"}))}else if(\"class\"===r){if(\"append\"===n)return wt(e,(function(t){i&&t.add(i)}));if(\"remove\"===n)return wt(e,(function(t){i&&t.delete(i)}));if(\"set\"===n)return wt(e,(function(t){t.clear(),i&&t.add(i)}))}else if(\"position\"===r){if(\"set\"===n&&s)return function(t,e){return ft({kind:\"position\",elements:new Set,mutate:function(){return{insertBeforeSelector:o,parentSelector:s}},selector:t})}(e)}else{if(\"append\"===n)return yt(e,r,(function(t){return null!==t?t+(null!=i?i:\"\"):null!=i?i:\"\"}));if(\"set\"===n)return yt(e,r,(function(){return null!=i?i:\"\"}));if(\"remove\"===n)return yt(e,r,(function(){return null}))}return J}(t).revert)})),()=>{e.forEach((t=>t()))}}lt(t){const e=new Set,n=t&&t.features?t.features:this.getFeatures(),i=t&&t.experiments?t.experiments:this.getExperiments();return Object.keys(n).forEach((t=>{const i=n[t];if(i.rules)for(const t of i.rules)t.variations&&(e.add(t.hashAttribute||\"id\"),t.fallbackAttribute&&e.add(t.fallbackAttribute))})),i.map((t=>{e.add(t.hashAttribute||\"id\"),t.fallbackAttribute&&e.add(t.fallbackAttribute)})),Array.from(e)}async refreshStickyBuckets(t){if(this.i.stickyBucketService){const e=this.ft(t);this.i.stickyBucketAssignmentDocs=await this.i.stickyBucketService.getAllAssignments(e)}}dt(t,e){if(!this.i.stickyBucketAssignmentDocs)return{};const{hashAttribute:n,hashValue:i}=this.nt(t),r=\"\".concat(n,\"||\").concat(l(i)),{hashAttribute:s,hashValue:o}=this.nt(e),u=o?\"\".concat(s,\"||\").concat(l(o)):null,c={};return u&&this.i.stickyBucketAssignmentDocs[u]&&Object.assign(c,this.i.stickyBucketAssignmentDocs[u].assignments||{}),this.i.stickyBucketAssignmentDocs[r]&&Object.assign(c,this.i.stickyBucketAssignmentDocs[r].assignments||{}),c}rt(t){let{expKey:e,expBucketVersion:n,expHashAttribute:i,expFallbackAttribute:r,expMinBucketVersion:s,expMeta:o}=t;n=n||0,s=s||0,i=i||\"id\",o=o||[];const u=this.ct(e,n),c=this.dt(i,r);if(s>0)for(let t=0;t<=s;t++)if(void 0!==c[this.ct(e,t)])return{variation:-1,versionIsBlocked:!0};const a=c[u];if(void 0===a)return{variation:-1};const h=o.findIndex((t=>t.key===a));return h<0?{variation:-1}:{variation:h}}ct(t,e){return e=e||0,\"\".concat(t,\"__\").concat(e)}ft(t){const e={};return this.i.stickyBucketIdentifierAttributes=this.lt(t),this.i.stickyBucketIdentifierAttributes.forEach((t=>{const{hashValue:n}=this.nt(t);e[t]=l(n)})),e}ut(t,e,n){const i=\"\".concat(t,\"||\").concat(e),r=this.i.stickyBucketAssignmentDocs&&this.i.stickyBucketAssignmentDocs[i]&&this.i.stickyBucketAssignmentDocs[i].assignments||{},s={...r,...n};return{key:i,doc:{attributeName:t,attributeValue:e,assignments:s},changed:JSON.stringify(r)!==JSON.stringify(s)}}}({...$t,remoteEval:!!$t.remoteEval,trackingCallback:async(t,e)=>{const n=[],i={experiment_id:t.key,variation_id:e.key};if(Rt.additionalTrackingCallback&&n.push(Promise.resolve(Rt.additionalTrackingCallback(t,e))),window.gtag){let t;const e=new Promise((e=>{t=e}));n.push(e),window.gtag(\"event\",\"experiment_viewed\",{...i,event_callback:t})}if(window.dataLayer){let t;const e=new Promise((e=>{t=e}));n.push(e),window.dataLayer.push({event:\"experiment_viewed\",...i,eventCallback:t})}if(window.analytics&&window.analytics.track){window.analytics.track(\"Experiment Viewed\",i);const t=new Promise((t=>window.setTimeout(t,300)));n.push(t)}await Promise.all(n)},...Rt,attributes:Dt(),stickyBucketService:Ut});Lt.setRenderer((()=>{document.dispatchEvent(new CustomEvent(\"growthbookdata\"))})),Lt.init({payload:Rt.payload,streaming:!(Rt.noStreaming||$t.noStreaming||!1===Rt.backgroundSync),cacheSettings:Rt.cacheSettings}).then((()=>{(Rt.antiFlicker||$t.antiFlicker)&&(Lt.getRedirectUrl()?Pt():Kt())}));let Ht=location.href;setInterval((()=>{location.href!==Ht&&(Ht=location.href,Lt.setURL(Ht),Lt.updateAttributes(Dt()))}),500),document.addEventListener(\"growthbookrefresh\",(()=>{location.href!==Ht&&(Ht=location.href,Lt.setURL(Ht)),Lt.updateAttributes(Dt())})),document.addEventListener(\"growthbookpersist\",(()=>{Vt()}));const qt=t=>{try{t&&t(Lt)}catch(t){console.error(\"Uncaught growthbook_queue error\",t)}};return window.growthbook_queue&&Array.isArray(window.growthbook_queue)&&window.growthbook_queue.forEach((t=>{qt(t)})),window.growthbook_queue={push:t=>{qt(t)}},Lt}();\n//# sourceMappingURL=auto.min.js.map\n";
2
+ export const sdkWrapper = "var _growthbook=function(){\"use strict\";function t(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)t[r]=n[r]}return t}var e=function e(n,r){function i(e,i,s){if(\"undefined\"!=typeof document){\"number\"==typeof(s=t({},r,s)).expires&&(s.expires=new Date(Date.now()+864e5*s.expires)),s.expires&&(s.expires=s.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o=\"\";for(var u in s)s[u]&&(o+=\"; \"+u,!0!==s[u]&&(o+=\"=\"+s[u].split(\";\")[0]));return document.cookie=e+\"=\"+n.write(i,e)+o}}return Object.create({set:i,get:function(t){if(\"undefined\"!=typeof document&&(!arguments.length||t)){for(var e=document.cookie?document.cookie.split(\"; \"):[],r={},i=0;i<e.length;i++){var s=e[i].split(\"=\"),o=s.slice(1).join(\"=\");try{var u=decodeURIComponent(s[0]);if(r[u]=n.read(o,u),t===u)break}catch(t){}}return t?r[t]:r}},remove:function(e,n){i(e,\"\",t({},n,{expires:-1}))},withAttributes:function(n){return e(this.converter,t({},this.attributes,n))},withConverter:function(n){return e(t({},this.converter,n),this.attributes)}},{attributes:{value:Object.freeze(r)},converter:{value:Object.freeze(n)}})}({read:function(t){return\'\"\'===t[0]&&(t=t.slice(1,-1)),t.replace(/(%[\\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:\"/\"}),n=/^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/,r={revert:function(){}},i=new Map,s=new Set;function o(t){var e=i.get(t);return e||i.set(t,e={element:t,attributes:{}}),e}function u(t,e,n,r,i){var s=n(t),o={isDirty:!1,originalValue:s,virtualValue:s,mutations:[],el:t,t:null,observer:new MutationObserver((function(){if(\"position\"!==e||!o.t){\"position\"===e&&(o.t=setTimeout((function(){o.t=null}),1e3));var r=n(t);\"position\"===e&&r.parentNode===o.virtualValue.parentNode&&r.insertBeforeNode===o.virtualValue.insertBeforeNode||r!==o.virtualValue&&(o.originalValue=r,i(o))}})),mutationRunner:i,setValue:r,getCurrentValue:n};return\"position\"===e&&t.parentNode?o.observer.observe(t.parentNode,{childList:!0,subtree:!0,attributes:!1,characterData:!1}):o.observer.observe(t,function(t){return\"html\"===t?{childList:!0,subtree:!0,attributes:!0,characterData:!0}:{childList:!1,subtree:!1,attributes:!0,attributeFilter:[t]}}(e)),o}function c(t,e){var n=e.getCurrentValue(e.el);e.virtualValue=t,t&&\"string\"!=typeof t?n&&t.parentNode===n.parentNode&&t.insertBeforeNode===n.insertBeforeNode||(e.isDirty=!0,_()):t!==n&&(e.isDirty=!0,_())}function a(t){var e=t.originalValue;t.mutations.forEach((function(t){return e=t.mutate(e)})),c(function(t){return g||(g=document.createElement(\"div\")),g.innerHTML=t,g.innerHTML}(e),t)}function l(t){var e=new Set(t.originalValue.split(/\\s+/).filter(Boolean));t.mutations.forEach((function(t){return t.mutate(e)})),c(Array.from(e).filter(Boolean).join(\" \"),t)}function h(t){var e=t.originalValue;t.mutations.forEach((function(t){return e=t.mutate(e)})),c(e,t)}function f(t){var e=t.originalValue;t.mutations.forEach((function(t){var n=function(t){var e=t.insertBeforeSelector,n=document.querySelector(t.parentSelector);if(!n)return null;var r=e?document.querySelector(e):null;return e&&!r?null:{parentNode:n,insertBeforeNode:r}}(t.mutate());e=n||e})),c(e,t)}var d=function(t){return t.innerHTML},w=function(t,e){return t.innerHTML=e};function y(t){var e=o(t);return e.html||(e.html=u(t,\"html\",d,w,a)),e.html}var p=function(t){return{parentNode:t.parentElement,insertBeforeNode:t.nextElementSibling}},m=function(t,e){e.insertBeforeNode&&!e.parentNode.contains(e.insertBeforeNode)||e.parentNode.insertBefore(t,e.insertBeforeNode)};function v(t){var e=o(t);return e.position||(e.position=u(t,\"position\",p,m,f)),e.position}var g,b,k=function(t,e){return e?t.className=e:t.removeAttribute(\"class\")},S=function(t){return t.className};function $(t){var e=o(t);return e.classes||(e.classes=u(t,\"class\",S,k,l)),e.classes}function A(t,e){var n,r=o(t);return r.attributes[e]||(r.attributes[e]=u(t,e,(n=e,function(t){var e;return null!=(e=t.getAttribute(n))?e:null}),function(t){return function(e,n){return null!==n?e.setAttribute(t,n):e.removeAttribute(t)}}(e),h)),r.attributes[e]}function x(t,e,n){if(n.isDirty){n.isDirty=!1;var r=n.virtualValue;n.mutations.length||function(t,e){var n,r,s=i.get(t);if(s)if(\"html\"===e)null==(n=s.html)||null==(r=n.observer)||r.disconnect(),delete s.html;else if(\"class\"===e){var o,u;null==(o=s.classes)||null==(u=o.observer)||u.disconnect(),delete s.classes}else if(\"position\"===e){var c,a;null==(c=s.position)||null==(a=c.observer)||a.disconnect(),delete s.position}else{var l,h,f;null==(l=s.attributes)||null==(h=l[e])||null==(f=h.observer)||f.disconnect(),delete s.attributes[e]}}(t,e),n.setValue(t,r)}}function C(t,e){t.html&&x(e,\"html\",t.html),t.classes&&x(e,\"class\",t.classes),t.position&&x(e,\"position\",t.position),Object.keys(t.attributes).forEach((function(n){x(e,n,t.attributes[n])}))}function _(){i.forEach(C)}function E(t){if(\"position\"!==t.kind||1!==t.elements.size){var e=new Set(t.elements);document.querySelectorAll(t.selector).forEach((function(n){e.has(n)||(t.elements.add(n),function(t,e){var n=null;\"html\"===t.kind?n=y(e):\"class\"===t.kind?n=$(e):\"attribute\"===t.kind?n=A(e,t.attribute):\"position\"===t.kind&&(n=v(e)),n&&(n.mutations.push(t),n.mutationRunner(n))}(t,n))}))}}function O(){s.forEach(E)}function R(t){return\"undefined\"==typeof document?r:(s.add(t),E(t),{revert:function(){var e;(e=t).elements.forEach((function(t){return function(t,e){var n=null;if(\"html\"===t.kind?n=y(e):\"class\"===t.kind?n=$(e):\"attribute\"===t.kind?n=A(e,t.attribute):\"position\"===t.kind&&(n=v(e)),n){var r=n.mutations.indexOf(t);-1!==r&&n.mutations.splice(r,1),n.mutationRunner(n)}}(e,t)})),e.elements.clear(),s.delete(e)}})}function F(t,e){return R({kind:\"html\",elements:new Set,mutate:e,selector:t})}function T(t,e){return R({kind:\"class\",elements:new Set,mutate:e,selector:t})}function B(t,e,i){return n.test(e)?\"class\"===e||\"className\"===e?T(t,(function(t){var e=i(Array.from(t).join(\" \"));t.clear(),e&&e.split(/\\s+/g).filter(Boolean).forEach((function(e){return t.add(e)}))})):R({kind:\"attribute\",attribute:e,elements:new Set,mutate:i,selector:t}):r}\"undefined\"!=typeof document&&(b||(b=new MutationObserver((function(){O()}))),O(),b.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1,characterData:!1}));const N={fetch:globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,SubtleCrypto:globalThis.crypto?globalThis.crypto.subtle:void 0,EventSource:globalThis.EventSource};function U(t){let e=2166136261;const n=t.length;for(let r=0;r<n;r++)e^=t.charCodeAt(r),e+=(e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24);return e>>>0}function M(t,e,n){return 2===n?U(U(t+e)+\"\")%1e4/1e4:1===n?U(e+t)%1e3/1e3:null}function V(t,e){return t>=e[0]&&t<e[1]}function D(t){try{const e=t.replace(/([^\\\\])\\//g,\"$1\\\\/\");return new RegExp(e)}catch(t){return void console.error(t)}}function I(t,e){if(!e.length)return!1;let n=!1,r=!1;for(let i=0;i<e.length;i++){const s=P(t,e[i].type,e[i].pattern);if(!1===e[i].include){if(s)return!1}else n=!0,s&&(r=!0)}return r||!n}function P(t,e,n){try{const r=new URL(t,\"https://_\");if(\"regex\"===e){const t=D(n);return!!t&&(t.test(r.href)||t.test(r.href.substring(r.origin.length)))}return\"simple\"===e&&function(t,e){try{const n=new URL(e.replace(/^([^:/?]*)\\./i,\"https://$1.\").replace(/\\*/g,\"_____\"),\"https://_____\"),r=[[t.host,n.host,!1],[t.pathname,n.pathname,!0]];return n.hash&&r.push([t.hash,n.hash,!1]),n.searchParams.forEach(((e,n)=>{r.push([t.searchParams.get(n)||\"\",e,!1])})),!r.some((t=>!function(t,e,n){try{let r=e.replace(/[*.+?^${}()|[\\]\\\\]/g,\"\\\\$&\").replace(/_____/g,\".*\");return n&&(r=\"\\\\/?\"+r.replace(/(^\\/|\\/$)/g,\"\")+\"\\\\/?\"),new RegExp(\"^\"+r+\"$\",\"i\").test(t)}catch(t){return!1}}(t[0],t[1],t[2])))}catch(t){return!1}}(r,n)}catch(t){return!1}}const j=t=>Uint8Array.from(atob(t),(t=>t.charCodeAt(0)));async function J(t,e,n){if(e=e||\"\",!(n=n||globalThis.crypto&&globalThis.crypto.subtle||N.SubtleCrypto))throw new Error(\"No SubtleCrypto implementation found\");try{const r=await n.importKey(\"raw\",j(e),{name:\"AES-CBC\",length:128},!0,[\"encrypt\",\"decrypt\"]),[i,s]=t.split(\".\"),o=await n.decrypt({name:\"AES-CBC\",iv:j(i)},r,j(s));return(new TextDecoder).decode(o)}catch(t){throw new Error(\"Failed to decrypt\")}}function L(t){return\"string\"==typeof t?t:JSON.stringify(t)}function K(t){\"number\"==typeof t&&(t+=\"\"),t&&\"string\"==typeof t||(t=\"0\");const e=t.replace(/(^v|\\+.*$)/g,\"\").split(/[-.]/);return 3===e.length&&e.push(\"~\"),e.map((t=>t.match(/^[0-9]+$/)?t.padStart(5,\" \"):t)).join(\"-\")}function q(t){return\"object\"==typeof t&&null!==t}function H(t){return t.urlPatterns&&t.variations.some((t=>q(t)&&\"urlRedirect\"in t))?\"redirect\":t.variations.some((t=>q(t)&&(t.domMutations||\"js\"in t||\"css\"in t)))?\"visual\":\"unknown\"}async function G(t,e){return new Promise((n=>{let r,i=!1;const s=t=>{i||(i=!0,r&&clearTimeout(r),n(t||null))};e&&(r=setTimeout((()=>s()),e)),t.then((t=>s(t))).catch((()=>s()))}))}const z={staleTTL:6e4,maxAge:144e5,cacheKey:\"gbFeaturesCache\",backgroundSync:!0,maxEntries:10,disableIdleStreams:!1,idleStreamInterval:2e4,disableCache:!1},Z=N,Q={fetchFeaturesCall:t=>{let{host:e,clientKey:n,headers:r}=t;return Z.fetch(`${e}/api/features/${n}`,{headers:r})},fetchRemoteEvalCall:t=>{let{host:e,clientKey:n,payload:r,headers:i}=t;const s={method:\"POST\",headers:{\"Content-Type\":\"application/json\",...i},body:JSON.stringify(r)};return Z.fetch(`${e}/api/eval/${n}`,s)},eventSourceCall:t=>{let{host:e,clientKey:n,headers:r}=t;return r?new Z.EventSource(`${e}/sub/${n}`,{headers:r}):new Z.EventSource(`${e}/sub/${n}`)},startIdleListener:()=>{let t;if(\"undefined\"==typeof window||\"undefined\"==typeof document)return;const e=()=>{\"visible\"===document.visibilityState?(window.clearTimeout(t),et.forEach((t=>{t&&\"idle\"===t.state&&dt(t)}))):\"hidden\"===document.visibilityState&&(t=window.setTimeout(rt,z.idleStreamInterval))};return document.addEventListener(\"visibilitychange\",e),()=>document.removeEventListener(\"visibilitychange\",e)},stopIdleListener:()=>{}};try{globalThis.localStorage&&(Z.localStorage=globalThis.localStorage)}catch(t){}const W=new Map;let X=!1;const Y=new Map,tt=new Map,et=new Map,nt=new Set;function rt(){et.forEach((t=>{t&&(t.state=\"idle\",ft(t))}))}async function it(){try{if(!Z.localStorage)return;await Z.localStorage.setItem(z.cacheKey,JSON.stringify(Array.from(Y.entries())))}catch(t){}}function st(t){const[e,n]=t.getApiInfo();return`${e}||${n}`}function ot(t){const e=st(t);if(!(\"isRemoteEval\"in t)||!t.isRemoteEval())return e;const n=t.getAttributes(),r=t.getCacheKeyAttributes()||Object.keys(t.getAttributes()),i={};r.forEach((t=>{i[t]=n[t]}));const s=t.getForcedVariations(),o=t.getUrl();return`${e}||${JSON.stringify({ca:i,fv:s,url:o})}`}function ut(){const t=Array.from(Y.entries()).map((t=>{let[e,n]=t;return{key:e,staleAt:n.staleAt.getTime()}})).sort(((t,e)=>t.staleAt-e.staleAt)),e=Math.min(Math.max(0,Y.size-z.maxEntries),Y.size);for(let n=0;n<e;n++)Y.delete(t[n].key)}function ct(t,e,n){const r=n.dateUpdated||\"\",i=new Date(Date.now()+z.staleTTL),s=z.disableCache?void 0:Y.get(e);if(s&&r&&s.version===r)return s.staleAt=i,void it();z.disableCache||(Y.set(e,{data:n,version:r,staleAt:i,sse:nt.has(t)}),ut()),it();const o=W.get(t);o&&o.forEach((t=>async function(t,e){await t.setPayload(e||t.getPayload())}(t,n)))}async function at(t){const{apiHost:e,apiRequestHeaders:n}=t.getApiHosts(),r=t.getClientKey(),i=\"isRemoteEval\"in t&&t.isRemoteEval(),s=st(t),o=ot(t);let u=tt.get(o);return u||(u=(i?Q.fetchRemoteEvalCall({host:e,clientKey:r,payload:{attributes:t.getAttributes(),forcedVariations:t.getForcedVariations(),forcedFeatures:Array.from(t.getForcedFeatures().entries()),url:t.getUrl()},headers:n}):Q.fetchFeaturesCall({host:e,clientKey:r,headers:n})).then((t=>{if(!t.ok)throw new Error(`HTTP error: ${t.status}`);return\"enabled\"===t.headers.get(\"x-sse-support\")&&nt.add(s),t.json()})).then((e=>(ct(s,o,e),lt(t),tt.delete(o),{data:e,success:!0,source:\"network\"}))).catch((t=>(tt.delete(o),{data:null,source:\"error\",success:!1,error:t}))),tt.set(o,u)),u}function lt(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=st(t),r=ot(t),{streamingHost:i,streamingHostRequestHeaders:s}=t.getApiHosts(),o=t.getClientKey();if(e&&nt.add(n),z.backgroundSync&&nt.has(n)&&Z.EventSource){if(et.has(n))return;const t={src:null,host:i,clientKey:o,headers:s,cb:e=>{try{if(\"features-updated\"===e.type){const t=W.get(n);t&&t.forEach((t=>{at(t)}))}else if(\"features\"===e.type){const t=JSON.parse(e.data);ct(n,r,t)}t.errors=0}catch(e){ht(t)}},errors:0,state:\"active\"};et.set(n,t),dt(t)}}function ht(t){if(\"idle\"!==t.state&&(t.errors++,t.errors>3||t.src&&2===t.src.readyState)){const e=Math.pow(3,t.errors-3)*(1e3+1e3*Math.random());ft(t),setTimeout((()=>{[\"idle\",\"active\"].includes(t.state)||dt(t)}),Math.min(e,3e5))}}function ft(t){t.src&&(t.src.onopen=null,t.src.onerror=null,t.src.close(),t.src=null,\"active\"===t.state&&(t.state=\"disabled\"))}function dt(t){t.src=Q.eventSourceCall({host:t.host,clientKey:t.clientKey,headers:t.headers}),t.state=\"active\",t.src.addEventListener(\"features\",t.cb),t.src.addEventListener(\"features-updated\",t.cb),t.src.onerror=()=>ht(t),t.src.onopen=()=>{t.errors=0}}function wt(t,e){ft(t),et.delete(e)}function yt(t,e){if(e.streaming){if(!t.getClientKey())throw new Error(\"Must specify clientKey to enable streaming\");e.payload&&lt(t,!0),function(t){const e=st(t),n=W.get(e)||new Set;n.add(t),W.set(e,n)}(t)}}const pt={};function mt(t,e,n){n=n||{};for(const[r,i]of Object.entries(e))switch(r){case\"$or\":if(!$t(t,i,n))return!1;break;case\"$nor\":if($t(t,i,n))return!1;break;case\"$and\":if(!At(t,i,n))return!1;break;case\"$not\":if(mt(t,i,n))return!1;break;default:if(!gt(i,vt(t,r),n))return!1}return!0}function vt(t,e){const n=e.split(\".\");let r=t;for(let t=0;t<n.length;t++){if(!r||\"object\"!=typeof r||!(n[t]in r))return null;r=r[n[t]]}return r}function gt(t,e,n){if(\"string\"==typeof t)return e+\"\"===t;if(\"number\"==typeof t)return 1*e===t;if(\"boolean\"==typeof t)return!!e===t;if(null===t)return null===e;if(Array.isArray(t)||!bt(t))return JSON.stringify(e)===JSON.stringify(t);for(const r in t)if(!St(r,e,t[r],n))return!1;return!0}function bt(t){const e=Object.keys(t);return e.length>0&&e.filter((t=>\"$\"===t[0])).length===e.length}function kt(t,e){return Array.isArray(t)?t.some((t=>e.includes(t))):e.includes(t)}function St(t,e,n,r){switch(t){case\"$veq\":return K(e)===K(n);case\"$vne\":return K(e)!==K(n);case\"$vgt\":return K(e)>K(n);case\"$vgte\":return K(e)>=K(n);case\"$vlt\":return K(e)<K(n);case\"$vlte\":return K(e)<=K(n);case\"$eq\":return e===n;case\"$ne\":return e!==n;case\"$lt\":return e<n;case\"$lte\":return e<=n;case\"$gt\":return e>n;case\"$gte\":return e>=n;case\"$exists\":return n?null!=e:null==e;case\"$in\":return!!Array.isArray(n)&&kt(e,n);case\"$inGroup\":return kt(e,r[n]||[]);case\"$notInGroup\":return!kt(e,r[n]||[]);case\"$nin\":return!!Array.isArray(n)&&!kt(e,n);case\"$not\":return!gt(n,e,r);case\"$size\":return!!Array.isArray(e)&&gt(n,e.length,r);case\"$elemMatch\":return function(t,e,n){if(!Array.isArray(t))return!1;const r=bt(e)?t=>gt(e,t,n):t=>mt(t,e,n);for(let e=0;e<t.length;e++)if(t[e]&&r(t[e]))return!0;return!1}(e,n,r);case\"$all\":if(!Array.isArray(e))return!1;for(let t=0;t<n.length;t++){let i=!1;for(let s=0;s<e.length;s++)if(gt(n[t],e[s],r)){i=!0;break}if(!i)return!1}return!0;case\"$regex\":try{return(i=n,pt[i]||(pt[i]=new RegExp(i.replace(/([^\\\\])\\//g,\"$1\\\\/\"))),pt[i]).test(e)}catch(t){return!1}case\"$type\":return function(t){if(null===t)return\"null\";if(Array.isArray(t))return\"array\";const e=typeof t;return[\"string\",\"number\",\"boolean\",\"object\",\"undefined\"].includes(e)?e:\"unknown\"}(e)===n;default:return console.error(\"Unknown operator: \"+t),!1}var i}function $t(t,e,n){if(!e.length)return!0;for(let r=0;r<e.length;r++)if(mt(t,e[r],n))return!0;return!1}function At(t,e,n){for(let r=0;r<e.length;r++)if(!mt(t,e[r],n))return!1;return!0}function xt(t,e){if(e.stack.evaluatedFeatures.has(t))return _t(e,t,null,\"cyclicPrerequisite\");e.stack.evaluatedFeatures.add(t),e.stack.id=t;const n=function(t){const e=new Map;return t.global.forcedFeatureValues&&t.global.forcedFeatureValues.forEach(((t,n)=>e.set(n,t))),t.user.forcedFeatureValues&&t.user.forcedFeatureValues.forEach(((t,n)=>e.set(n,t))),e}(e);if(n.has(t))return _t(e,t,n.get(t),\"override\");if(!e.global.features||!e.global.features[t])return _t(e,t,null,\"unknownFeature\");const r=e.global.features[t];if(r.rules)t:for(const n of r.rules){if(n.parentConditions)for(const r of n.parentConditions){const n=xt(r.id,e);if(\"cyclicPrerequisite\"===n.source)return _t(e,t,null,\"cyclicPrerequisite\");if(!mt({value:n.value},r.condition||{})){if(r.gate)return _t(e,t,null,\"prerequisite\");continue t}}if(n.filters&&Ot(n.filters,e))continue;if(\"force\"in n){if(n.condition&&!Et(n.condition,e))continue;if(!Rt(e,n.seed||t,n.hashAttribute,e.user.saveStickyBucketAssignmentDoc&&!n.disableStickyBucketing?n.fallbackAttribute:void 0,n.range,n.coverage,n.hashVersion))continue;return n.tracks&&n.tracks.forEach((t=>{let n=!1;e.global.trackingCallback&&(n=!0,Promise.resolve(e.global.trackingCallback(t.experiment,t.result,e.user)).catch((()=>{}))),e.user.trackingCallback&&(n=!0,Promise.resolve(e.user.trackingCallback(t.experiment,t.result)).catch((()=>{}))),!n&&e.global.saveDeferredTrack&&e.global.saveDeferredTrack({experiment:t.experiment,result:t.result})})),_t(e,t,n.force,\"force\",n.id)}if(!n.variations)continue;const r={variations:n.variations,key:n.key||t};\"coverage\"in n&&(r.coverage=n.coverage),n.weights&&(r.weights=n.weights),n.hashAttribute&&(r.hashAttribute=n.hashAttribute),n.fallbackAttribute&&(r.fallbackAttribute=n.fallbackAttribute),n.disableStickyBucketing&&(r.disableStickyBucketing=n.disableStickyBucketing),void 0!==n.bucketVersion&&(r.bucketVersion=n.bucketVersion),void 0!==n.minBucketVersion&&(r.minBucketVersion=n.minBucketVersion),n.namespace&&(r.namespace=n.namespace),n.meta&&(r.meta=n.meta),n.ranges&&(r.ranges=n.ranges),n.name&&(r.name=n.name),n.phase&&(r.phase=n.phase),n.seed&&(r.seed=n.seed),n.hashVersion&&(r.hashVersion=n.hashVersion),n.filters&&(r.filters=n.filters),n.condition&&(r.condition=n.condition);const{result:i}=Ct(r,t,e);if(e.global.onExperimentEval&&e.global.onExperimentEval(r,i),i.inExperiment&&!i.passthrough)return _t(e,t,i.value,\"experiment\",n.id,r,i)}return _t(e,t,void 0===r.defaultValue?null:r.defaultValue,\"defaultValue\")}function Ct(t,e,n){const r=t.key,i=t.variations.length;if(i<2)return{result:Ft(n,t,-1,!1,e)};if(!1===n.global.enabled||!1===n.user.enabled)return{result:Ft(n,t,-1,!1,e)};if(t=function(t,e){const n=t.key,r=e.global.overrides;return r&&r[n]&&\"string\"==typeof(t=Object.assign({},t,r[n])).url&&(t.url=D(t.url)),t}(t,n),t.urlPatterns&&!I(n.user.url||\"\",t.urlPatterns))return{result:Ft(n,t,-1,!1,e)};const s=function(t,e,n){if(!e)return null;const r=e.split(\"?\")[1];if(!r)return null;const i=r.replace(/#.*/,\"\").split(\"&\").map((t=>t.split(\"=\",2))).filter((e=>{let[n]=e;return n===t})).map((t=>{let[,e]=t;return parseInt(e)}));return i.length>0&&i[0]>=0&&i[0]<n?i[0]:null}(r,n.user.url||\"\",i);if(null!==s)return{result:Ft(n,t,s,!1,e)};const o=function(t){return t.global.forcedVariations&&t.user.forcedVariations?{...t.global.forcedVariations,...t.user.forcedVariations}:t.global.forcedVariations?t.global.forcedVariations:t.user.forcedVariations?t.user.forcedVariations:{}}(n);if(r in o)return{result:Ft(n,t,o[r],!1,e)};if(\"draft\"===t.status||!1===t.active)return{result:Ft(n,t,-1,!1,e)};const{hashAttribute:u,hashValue:c}=Tt(n,t.hashAttribute,n.user.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0);if(!c)return{result:Ft(n,t,-1,!1,e)};let a=-1,l=!1,h=!1;if(n.user.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing){const{variation:e,versionIsBlocked:r}=function(t){let{ctx:e,expKey:n,expBucketVersion:r,expHashAttribute:i,expFallbackAttribute:s,expMinBucketVersion:o,expMeta:u}=t;r=r||0,o=o||0,i=i||\"id\",u=u||[];const c=Bt(n,r),a=function(t,e,n){if(!t.user.stickyBucketAssignmentDocs)return{};const{hashAttribute:r,hashValue:i}=Tt(t,e),s=`${r}||${L(i)}`,{hashAttribute:o,hashValue:u}=Tt(t,n),c=u?`${o}||${L(u)}`:null,a={};return c&&t.user.stickyBucketAssignmentDocs[c]&&Object.assign(a,t.user.stickyBucketAssignmentDocs[c].assignments||{}),t.user.stickyBucketAssignmentDocs[s]&&Object.assign(a,t.user.stickyBucketAssignmentDocs[s].assignments||{}),a}(e,i,s);if(o>0)for(let t=0;t<=o;t++)if(void 0!==a[Bt(n,t)])return{variation:-1,versionIsBlocked:!0};const l=a[c];if(void 0===l)return{variation:-1};const h=u.findIndex((t=>t.key===l));return h<0?{variation:-1}:{variation:h}}({ctx:n,expKey:t.key,expBucketVersion:t.bucketVersion,expHashAttribute:t.hashAttribute,expFallbackAttribute:t.fallbackAttribute,expMinBucketVersion:t.minBucketVersion,expMeta:t.meta});l=e>=0,a=e,h=!!r}if(!l){if(t.filters){if(Ot(t.filters,n))return{result:Ft(n,t,-1,!1,e)}}else if(t.namespace&&!function(t,e){const n=M(\"__\"+e[0],t,1);return null!==n&&n>=e[1]&&n<e[2]}(c,t.namespace))return{result:Ft(n,t,-1,!1,e)};if(t.include&&!function(t){try{return t()}catch(t){return console.error(t),!1}}(t.include))return{result:Ft(n,t,-1,!1,e)};if(t.condition&&!Et(t.condition,n))return{result:Ft(n,t,-1,!1,e)};if(t.parentConditions)for(const r of t.parentConditions){const i=xt(r.id,n);if(\"cyclicPrerequisite\"===i.source)return{result:Ft(n,t,-1,!1,e)};if(!mt({value:i.value},r.condition||{}))return{result:Ft(n,t,-1,!1,e)}}if(t.groups&&!function(t,e){const n=e.global.groups||{};for(let e=0;e<t.length;e++)if(n[t[e]])return!0;return!1}(t.groups,n))return{result:Ft(n,t,-1,!1,e)}}if(t.url&&!function(t,e){const n=e.user.url;if(!n)return!1;const r=n.replace(/^https?:\\/\\//,\"\").replace(/^[^/]*\\//,\"/\");return!!t.test(n)||!!t.test(r)}(t.url,n))return{result:Ft(n,t,-1,!1,e)};const f=M(t.seed||r,c,t.hashVersion||1);if(null===f)return{result:Ft(n,t,-1,!1,e)};if(l||(a=function(t,e){for(let n=0;n<e.length;n++)if(V(t,e[n]))return n;return-1}(f,t.ranges||function(t,e,n){(e=void 0===e?1:e)<0?e=0:e>1&&(e=1);const r=(i=t)<=0?[]:new Array(i).fill(1/i);var i;(n=n||r).length!==t&&(n=r);const s=n.reduce(((t,e)=>e+t),0);(s<.99||s>1.01)&&(n=r);let o=0;return n.map((t=>{const n=o;return o+=t,[n,n+e*t]}))}(i,void 0===t.coverage?1:t.coverage,t.weights))),h)return{result:Ft(n,t,-1,!1,e,void 0,!0)};if(a<0)return{result:Ft(n,t,-1,!1,e)};if(\"force\"in t)return{result:Ft(n,t,void 0===t.force?-1:t.force,!1,e)};if(n.global.qaMode||n.user.qaMode)return{result:Ft(n,t,-1,!1,e)};if(\"stopped\"===t.status)return{result:Ft(n,t,-1,!1,e)};const d=Ft(n,t,a,!0,e,f,l);if(n.user.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing){const{changed:e,key:r,doc:i}=function(t,e,n,r){const i=`${e}||${n}`,s=t.user.stickyBucketAssignmentDocs&&t.user.stickyBucketAssignmentDocs[i]&&t.user.stickyBucketAssignmentDocs[i].assignments||{},o={...s,...r};return{key:i,doc:{attributeName:e,attributeValue:n,assignments:o},changed:JSON.stringify(s)!==JSON.stringify(o)}}(n,u,L(c),{[Bt(t.key,t.bucketVersion)]:d.key});e&&(n.user.stickyBucketAssignmentDocs=n.user.stickyBucketAssignmentDocs||{},n.user.stickyBucketAssignmentDocs[r]=i,n.user.saveStickyBucketAssignmentDoc(i))}const w=[];n.global.trackingCallback&&w.push(Promise.resolve(n.global.trackingCallback(t,d,n.user)).catch((()=>{}))),n.user.trackingCallback&&w.push(Promise.resolve(n.user.trackingCallback(t,d)).catch((()=>{}))),0===w.length&&n.global.saveDeferredTrack&&n.global.saveDeferredTrack({experiment:t,result:d});const y=w.length?1===w.length?w[0]:Promise.all(w).then((()=>{})):void 0;return\"changeId\"in t&&t.changeId&&n.global.recordChangeId&&n.global.recordChangeId(t.changeId),{result:d,trackingCall:y}}function _t(t,e,n,r,i,s,o){const u={value:n,on:!!n,off:!n,source:r,ruleId:i||\"\"};if(s&&(u.experiment=s),o&&(u.experimentResult=o),\"override\"!==r){if(t.global.onFeatureUsage)try{t.global.onFeatureUsage(e,u,t.user)}catch(t){}if(t.user.onFeatureUsage)try{t.user.onFeatureUsage(e,u)}catch(t){}}return u}function Et(t,e){return mt(e.user.attributes||{},t,e.global.savedGroups||{})}function Ot(t,e){return t.some((t=>{const{hashValue:n}=Tt(e,t.attribute);if(!n)return!0;const r=M(t.seed,n,t.hashVersion||2);return null===r||!t.ranges.some((t=>V(r,t)))}))}function Rt(t,e,n,r,i,s,o){if(!i&&void 0===s)return!0;if(!i&&0===s)return!1;const{hashValue:u}=Tt(t,n,r);if(!u)return!1;const c=M(e,u,o||1);return null!==c&&(i?V(c,i):void 0===s||c<=s)}function Ft(t,e,n,r,i,s,o){let u=!0;(n<0||n>=e.variations.length)&&(n=0,u=!1);const{hashAttribute:c,hashValue:a}=Tt(t,e.hashAttribute,t.user.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0),l=e.meta?e.meta[n]:{},h={key:l.key||\"\"+n,featureId:i,inExperiment:u,hashUsed:r,variationId:n,value:e.variations[n],hashAttribute:c,hashValue:a,stickyBucketUsed:!!o};return l.name&&(h.name=l.name),void 0!==s&&(h.bucket=s),l.passthrough&&(h.passthrough=l.passthrough),h}function Tt(t,e,n){let r=e||\"id\",i=\"\";return t.user.attributes&&t.user.attributes[r]&&(i=t.user.attributes[r]),t.user.attributes&&!i&&n&&(t.user.attributes[n]&&(i=t.user.attributes[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function Bt(t,e){return`${t}__${e=e||0}`}const Nt=\"undefined\"!=typeof window&&\"undefined\"!=typeof document,Ut=function(){let t;try{t=\"1.3.1\"}catch(e){t=\"\"}return t}();class Mt{constructor(t){this.prefix=(t=t||{}).prefix||\"\"}async getAllAssignments(t){const e={};return(await Promise.all(Object.entries(t).map((t=>{let[e,n]=t;return this.getAssignments(e,n)})))).forEach((t=>{t&&(e[`${t.attributeName}||${t.attributeValue}`]=t)})),e}getKey(t,e){return`${this.prefix}${t}||${e}`}}window.dataLayer=window.dataLayer||[];const Vt=document.currentScript,Dt=Vt?Vt.dataset:{},It=window.growthbook_config||{};function Pt(t){const e=(\"; \"+document.cookie).split(`; ${t}=`);return 2===e.length?e[1].split(\";\")[0]:\"\"}function jt(){return window.crypto&&crypto.randomUUID?crypto.randomUUID():\"10000000-1000-4000-8000-100000000000\".replace(/[018]/g,(t=>(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)))}const Jt=It.uuidCookieName||Dt.uuidCookieName||\"gbuuid\",Lt=It.uuidKey||Dt.uuidKey||\"id\";let Kt,qt,Ht=It.uuid||Dt.uuid||\"\";function Gt(){!function(t,e){const n=new Date;n.setTime(n.getTime()+3456e7),document.cookie=t+\"=\"+e+\";path=/;expires=\"+n.toUTCString()}(Jt,Ht)}function zt(){let t={};try{const e=sessionStorage.getItem(\"utm_params\");if(e&&(t=JSON.parse(e)),location.search){const e=new URLSearchParams(location.search);let n=!1;[\"source\",\"medium\",\"campaign\",\"term\",\"content\"].forEach((r=>{const i=`utm_${r}`,s=\"utm\"+r[0].toUpperCase()+r.slice(1);e.has(i)&&(t[s]=e.get(i)||\"\",n=!0)})),n&&sessionStorage.setItem(\"utm_params\",JSON.stringify(t))}}catch(t){}return t}function Zt(){if(!window.dataLayer||!window.dataLayer.forEach)return{};const t={};return window.dataLayer.forEach((e=>{e&&\"object\"==typeof e&&!(\"length\"in e)&&(\"event\"in e||Object.keys(e).forEach((n=>{if(\"string\"!=typeof n||n.match(/^(gtm)/))return;const r=e[n];[\"string\",\"number\",\"boolean\"].includes(typeof r)&&(t[n]=r)})))})),t}function Qt(){const t=Dt.noAutoAttributes?{}:function(t,e){const n=null==t.noAutoCookies,r=navigator.userAgent,i=r.match(/Edg/)?\"edge\":r.match(/Chrome/)?\"chrome\":r.match(/Firefox/)?\"firefox\":r.match(/Safari/)?\"safari\":\"unknown\",s=function(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return Ht||(Ht=Pt(Jt),Ht||(Ht=jt(),t&&Gt(),Ht))}(n);return(e.persistUuidOnLoad||t.persistUuidOnLoad)&&n&&Gt(),{...Zt(),[Lt]:s,url:location.href,path:location.pathname,host:location.host,query:location.search,pageTitle:document&&document.title,deviceType:r.match(/Mobi/)?\"mobile\":\"desktop\",browser:i,...zt()}}(Dt,It);return It.attributes&&Object.assign(t,It.attributes),t}function Wt(){window.clearTimeout(Kt);let t=It.antiFlickerTimeout??(Dt.antiFlickerTimeout?parseInt(Dt.antiFlickerTimeout):null)??3500;isFinite(t)||(t=3500);try{if(!document.getElementById(\"gb-anti-flicker-style\")){const t=document.createElement(\"style\");t.setAttribute(\"id\",\"gb-anti-flicker-style\"),t.innerHTML=\".gb-anti-flicker { opacity: 0 !important; pointer-events: none; }\",document.head.appendChild(t)}document.documentElement.classList.add(\"gb-anti-flicker\"),Kt=window.setTimeout(Xt,t)}catch(t){console.error(t)}}function Xt(){window.clearTimeout(Kt);try{document.documentElement.classList.remove(\"gb-anti-flicker\")}catch(t){console.error(t)}}(It.antiFlicker||Dt.antiFlicker)&&Wt(),\"cookie\"===It.useStickyBucketService||\"cookie\"===Dt.useStickyBucketService?qt=new class extends Mt{constructor(t){let{prefix:e=\"gbStickyBuckets__\",jsCookie:n,cookieAttributes:r={expires:180}}=t;super(),this.prefix=e,this.jsCookie=n,this.cookieAttributes=r}async getAssignments(t,e){const n=this.getKey(t,e);let r=null;if(!this.jsCookie)return r;try{const t=this.jsCookie.get(n),e=JSON.parse(t||\"{}\");e.attributeName&&e.attributeValue&&e.assignments&&(r=e)}catch(t){}return r}async saveAssignments(t){const e=this.getKey(t.attributeName,t.attributeValue);if(!this.jsCookie)return;const n=JSON.stringify(t);this.jsCookie.set(e,n,this.cookieAttributes)}}({prefix:It.stickyBucketPrefix||Dt.stickyBucketPrefix||void 0,jsCookie:e}):\"localStorage\"!==It.useStickyBucketService&&\"localStorage\"!==Dt.useStickyBucketService||(qt=new class extends Mt{constructor(t){t=t||{},super(),this.prefix=t.prefix||\"gbStickyBuckets__\";try{this.localStorage=t.localStorage||globalThis.localStorage}catch(t){}}async getAssignments(t,e){const n=this.getKey(t,e);let r=null;if(!this.localStorage)return r;try{const t=await this.localStorage.getItem(n)||\"{}\",e=JSON.parse(t);e.attributeName&&e.attributeValue&&e.assignments&&(r=e)}catch(t){}return r}async saveAssignments(t){const e=this.getKey(t.attributeName,t.attributeValue);if(this.localStorage)try{await this.localStorage.setItem(e,JSON.stringify(t))}catch(t){}}}({prefix:It.stickyBucketPrefix||Dt.stickyBucketPrefix||void 0}));const Yt=new class{constructor(t){if(t=t||{},this.version=Ut,this.i=this.context=t,this.o=t.renderer||null,this.u=new Set,this.l=new Set,this.h={},this.debug=!!t.debug,this.p=new Set,this.ready=!1,this.m=new Map,this.v={},this.g=new Map,this.k=new Set,this.S=!1,this.$=\"\",this.A=new Map,this.C=!t.disableExperimentsOnLoad,this.log=this.log.bind(this),this._=this._.bind(this),this.O=this.O.bind(this),this.R=this.R.bind(this),this.F=this.F.bind(this),this.T=this.T.bind(this),t.remoteEval){if(t.decryptionKey)throw new Error(\"Encryption is not available for remoteEval\");if(!t.clientKey)throw new Error(\"Missing clientKey\");let e=!1;try{e=!!new URL(t.apiHost||\"\").hostname.match(/growthbook\\.io$/i)}catch(t){}if(e)throw new Error(\"Cannot use remoteEval on GrowthBook Cloud\")}else if(t.cacheKeyAttributes)throw new Error(\"cacheKeyAttributes are only used for remoteEval\");if(t.stickyBucketService){const e=t.stickyBucketService;this.B=t=>e.saveAssignments(t)}if(t.features&&(this.ready=!0),Nt&&t.enableDevMode&&(window._growthbook=this,document.dispatchEvent(new Event(\"gbloaded\"))),t.experiments&&(this.ready=!0,this.N()),this.i.stickyBucketService&&this.i.stickyBucketAssignmentDocs)for(const t in this.i.stickyBucketAssignmentDocs){const e=this.i.stickyBucketAssignmentDocs[t];e&&this.i.stickyBucketService.saveAssignments(e).catch((()=>{}))}this.ready&&this.refreshStickyBuckets(this.getPayload())}async setPayload(t){this.U=t;const e=await async function(t,e,n){if((t={...t}).encryptedFeatures){try{t.features=JSON.parse(await J(t.encryptedFeatures,e,n))}catch(t){console.error(t)}delete t.encryptedFeatures}if(t.encryptedExperiments){try{t.experiments=JSON.parse(await J(t.encryptedExperiments,e,n))}catch(t){console.error(t)}delete t.encryptedExperiments}if(t.encryptedSavedGroups){try{t.savedGroups=JSON.parse(await J(t.encryptedSavedGroups,e,n))}catch(t){console.error(t)}delete t.encryptedSavedGroups}return t}(t,this.i.decryptionKey);this.M=e,await this.refreshStickyBuckets(e),e.features&&(this.i.features=e.features),e.savedGroups&&(this.i.savedGroups=e.savedGroups),e.experiments&&(this.i.experiments=e.experiments,this.N()),this.ready=!0,this.V()}initSync(t){this.S=!0;const e=t.payload;if(e.encryptedExperiments||e.encryptedFeatures)throw new Error(\"initSync does not support encrypted payloads\");if(this.i.stickyBucketService&&!this.i.stickyBucketAssignmentDocs)throw new Error(\"initSync requires you to pass stickyBucketAssignmentDocs into the GrowthBook constructor\");return this.U=e,this.M=e,e.features&&(this.i.features=e.features),e.experiments&&(this.i.experiments=e.experiments,this.N()),this.ready=!0,yt(this,t),this}async init(t){if(this.S=!0,(t=t||{}).cacheSettings&&(Object.assign(z,t.cacheSettings),z.backgroundSync||(nt.clear(),et.forEach(wt),W.clear(),Q.stopIdleListener())),t.payload)return await this.setPayload(t.payload),yt(this,t),{success:!0,source:\"init\"};{const{data:e,...n}=await this.D({...t,allowStale:!0});return yt(this,t),await this.setPayload(e||{}),n}}async loadFeatures(t){t=t||{},await this.init({skipCache:t.skipCache,timeout:t.timeout,streaming:(this.i.backgroundSync??!0)&&(t.autoRefresh||this.i.subscribeToChanges)})}async refreshFeatures(t){const e=await this.D({...t||{},allowStale:!1});e.data&&await this.setPayload(e.data)}getApiInfo(){return[this.getApiHosts().apiHost,this.getClientKey()]}getApiHosts(){return function(t){const e=t.apiHost||\"https://cdn.growthbook.io\";return{apiHost:e.replace(/\\/*$/,\"\"),streamingHost:(t.streamingHost||e).replace(/\\/*$/,\"\"),apiRequestHeaders:t.apiHostRequestHeaders,streamingHostRequestHeaders:t.streamingHostRequestHeaders}}(this.i)}getClientKey(){return this.i.clientKey||\"\"}getPayload(){return this.U||{features:this.getFeatures(),experiments:this.getExperiments()}}getDecryptedPayload(){return this.M||this.getPayload()}isRemoteEval(){return this.i.remoteEval||!1}getCacheKeyAttributes(){return this.i.cacheKeyAttributes}async D(t){let{timeout:e,skipCache:n,allowStale:r,streaming:i}=t;if(!this.i.clientKey)throw new Error(\"Missing clientKey\");return async function(t){let{instance:e,timeout:n,skipCache:r,allowStale:i,backgroundSync:s}=t;return s||(z.backgroundSync=!1),async function(t){let{instance:e,allowStale:n,timeout:r,skipCache:i}=t;const s=st(e),o=ot(e),u=new Date,c=new Date(u.getTime()-z.maxAge+z.staleTTL);await async function(){if(!X){X=!0;try{if(Z.localStorage){const t=await Z.localStorage.getItem(z.cacheKey);if(!z.disableCache&&t){const e=JSON.parse(t);e&&Array.isArray(e)&&e.forEach((t=>{let[e,n]=t;Y.set(e,{...n,staleAt:new Date(n.staleAt)})})),ut()}}}catch(t){}if(!z.disableIdleStreams){const t=Q.startIdleListener();t&&(Q.stopIdleListener=t)}}}();const a=z.disableCache||i?void 0:Y.get(o);return a&&(n||a.staleAt>u)&&a.staleAt>c?(a.sse&&nt.add(s),a.staleAt<u?at(e):lt(e),{data:a.data,success:!0,source:\"cache\"}):await G(at(e),r)||{data:null,success:!1,source:\"timeout\",error:new Error(\"Timeout\")}}({instance:e,allowStale:i,timeout:n,skipCache:r})}({instance:this,timeout:e,skipCache:n||this.i.disableCache,allowStale:r,backgroundSync:i??this.i.backgroundSync??!0})}V(){if(this.o)try{this.o()}catch(t){console.error(\"Failed to render\",t)}}setFeatures(t){this.i.features=t,this.ready=!0,this.V()}async setEncryptedFeatures(t,e,n){const r=await J(t,e||this.i.decryptionKey,n);this.setFeatures(JSON.parse(r))}setExperiments(t){this.i.experiments=t,this.ready=!0,this.N()}async setEncryptedExperiments(t,e,n){const r=await J(t,e||this.i.decryptionKey,n);this.setExperiments(JSON.parse(r))}async setAttributes(t){this.i.attributes=t,this.i.stickyBucketService&&await this.refreshStickyBuckets(),this.i.remoteEval?await this.I():(this.V(),this.N())}async updateAttributes(t){return this.setAttributes({...this.i.attributes,...t})}async setAttributeOverrides(t){this.v=t,this.i.stickyBucketService&&await this.refreshStickyBuckets(),this.i.remoteEval?await this.I():(this.V(),this.N())}async setForcedVariations(t){this.i.forcedVariations=t||{},this.i.remoteEval?await this.I():(this.V(),this.N())}setForcedFeatures(t){this.P=t,this.V()}async setURL(t){if(t!==this.i.url){if(this.i.url=t,this.$=\"\",this.i.remoteEval)return await this.I(),void this.N(!0);this.N(!0)}}getAttributes(){return{...this.i.attributes,...this.v}}getForcedVariations(){return this.i.forcedVariations||{}}getForcedFeatures(){return this.P||new Map}getStickyBucketAssignmentDocs(){return this.i.stickyBucketAssignmentDocs||{}}getUrl(){return this.i.url||\"\"}getFeatures(){return this.i.features||{}}getExperiments(){return this.i.experiments||[]}getCompletedChangeIds(){return Array.from(this.l)}subscribe(t){return this.p.add(t),()=>{this.p.delete(t)}}async I(){if(!this.i.remoteEval)return;if(!this.S)return;const t=await this.D({allowStale:!1});t.data&&await this.setPayload(t.data)}getAllResults(){return new Map(this.m)}destroy(){var t;this.p.clear(),this.m.clear(),this.u.clear(),this.l.clear(),this.A.clear(),this.h={},this.U=void 0,this.B=void 0,t=this,W.forEach((e=>e.delete(t))),Nt&&window._growthbook===this&&delete window._growthbook,this.g.forEach((t=>{t.undo()})),this.g.clear(),this.k.clear()}setRenderer(t){this.o=t}forceVariation(t,e){this.i.forcedVariations=this.i.forcedVariations||{},this.i.forcedVariations[t]=e,this.i.remoteEval?this.I():(this.N(),this.V())}run(t){const{result:e}=Ct(t,null,this.j());return this.F(t,e),e}triggerExperiment(t){return this.k.add(t),this.i.experiments?this.i.experiments.filter((e=>e.key===t)).map((t=>this.J(t))).filter((t=>null!==t)):null}triggerAutoExperiments(){this.C=!0,this.N(!0)}j(){return{user:this.L(),global:this.K(),stack:{evaluatedFeatures:new Set}}}L(){return{attributes:this.i.user?{...this.i.user,...this.getAttributes()}:this.getAttributes(),blockedChangeIds:this.i.blockedChangeIds,stickyBucketAssignmentDocs:this.i.stickyBucketAssignmentDocs,url:this.q(),forcedVariations:this.i.forcedVariations,forcedFeatureValues:this.P,saveStickyBucketAssignmentDoc:this.B,trackingCallback:this.i.trackingCallback?this._:void 0,onFeatureUsage:this.i.onFeatureUsage?this.R:void 0}}K(){return{features:this.i.features,experiments:this.i.experiments,log:this.log,enabled:this.i.enabled,qaMode:this.i.qaMode,savedGroups:this.i.savedGroups,groups:this.i.groups,overrides:this.i.overrides,onExperimentEval:this.p.size>0?this.F:void 0,recordChangeId:this.T,saveDeferredTrack:this.O}}J(t,e){const n=this.g.get(t);if(t.manual&&!this.k.has(t.key)&&!n)return null;let r,i;this.H(t)?r=Ft(this.j(),t,-1,!1,\"\"):(({result:r,trackingCall:i}=Ct(t,null,this.j())),this.F(t,r));const s=JSON.stringify(r.value);if(!e&&r.inExperiment&&n&&n.valueHash===s)return r;if(n&&this.G(t),r.inExperiment){const e=H(t);if(\"redirect\"===e&&r.value.urlRedirect&&t.urlPatterns){const e=t.persistQueryString?function(t,e){let n,r;try{n=new URL(t),r=new URL(e)}catch(t){return console.error(`Unable to merge query strings: ${t}`),e}return n.searchParams.forEach(((t,e)=>{r.searchParams.has(e)||r.searchParams.set(e,t)})),r.toString()}(this.q(),r.value.urlRedirect):r.value.urlRedirect;if(I(e,t.urlPatterns))return this.log(\"Skipping redirect because original URL matches redirect URL\",{id:t.key}),r;this.$=e;const{navigate:n,delay:s}=this.Z();if(n)if(Nt)Promise.all([...i?[G(i,this.i.maxNavigateDelay??1e3)]:[],new Promise((t=>window.setTimeout(t,this.i.navigateDelay??s)))]).then((()=>{try{n(e)}catch(t){console.error(t)}}));else try{n(e)}catch(t){console.error(t)}}else if(\"visual\"===e){const e=this.i.applyDomChangesCallback?this.i.applyDomChangesCallback(r.value):this.W(r.value);e&&this.g.set(t,{undo:e,valueHash:s})}}return r}G(t){const e=this.g.get(t);e&&(e.undo(),this.g.delete(t))}N(t){if(!this.C)return;const e=this.i.experiments||[],n=new Set(e);this.g.forEach(((t,e)=>{n.has(e)||(t.undo(),this.g.delete(e))}));for(const n of e){const e=this.J(n,t);if(null!=e&&e.inExperiment&&\"redirect\"===H(n))break}}F(t,e){const n=t.key,r=this.m.get(n);r&&r.result.inExperiment===e.inExperiment&&r.result.variationId===e.variationId||(this.m.set(n,{experiment:t,result:e}),this.p.forEach((n=>{try{n(t,e)}catch(t){console.error(t)}})))}T(t){this.l.add(t)}R(t,e){const n=JSON.stringify(e.value);if(this.h[t]!==n&&(this.h[t]=n,this.i.onFeatureUsage))try{this.i.onFeatureUsage(t,e)}catch(t){}}isOn(t){return this.evalFeature(t).on}isOff(t){return this.evalFeature(t).off}getFeatureValue(t,e){const n=this.evalFeature(t).value;return null===n?e:n}feature(t){return this.evalFeature(t)}evalFeature(t){return xt(t,this.j())}log(t,e){this.debug&&(this.i.log?this.i.log(t,e):console.log(t,e))}getDeferredTrackingCalls(){return Array.from(this.A.values())}setDeferredTrackingCalls(t){this.A=new Map(t.filter((t=>t&&t.experiment&&t.result)).map((t=>[this.X(t.experiment,t.result),t])))}async fireDeferredTrackingCalls(){if(!this.i.trackingCallback)return;const t=[];this.A.forEach((e=>{e&&e.experiment&&e.result?t.push(this._(e.experiment,e.result)):console.error(\"Invalid deferred tracking call\",{call:e})})),this.A.clear(),await Promise.all(t)}setTrackingCallback(t){this.i.trackingCallback=t,this.fireDeferredTrackingCalls()}X(t,e){return e.hashAttribute+e.hashValue+t.key+e.variationId}O(t){this.A.set(this.X(t.experiment,t.result),t)}async _(t,e){if(!this.i.trackingCallback)return;const n=this.X(t,e);if(!this.u.has(n)){this.u.add(n);try{await this.i.trackingCallback(t,e)}catch(t){console.error(t)}}}q(){return this.i.url||(Nt?window.location.href:\"\")}H(t){const e=H(t);if(\"visual\"===e){if(this.i.disableVisualExperiments)return!0;if(this.i.disableJsInjection&&t.variations.some((t=>t.js)))return!0}else{if(\"redirect\"!==e)return!0;if(this.i.disableUrlRedirectExperiments)return!0;try{const e=new URL(this.q());for(const n of t.variations){if(!n||!n.urlRedirect)continue;const t=new URL(n.urlRedirect);if(this.i.disableCrossOriginUrlRedirectExperiments){if(t.protocol!==e.protocol)return!0;if(t.host!==e.host)return!0}}}catch(e){return this.log(\"Error parsing current or redirect URL\",{id:t.key,error:e}),!0}}return!(!t.changeId||!(this.i.blockedChangeIds||[]).includes(t.changeId))}getRedirectUrl(){return this.$}Z(){return this.i.navigate?{navigate:this.i.navigate,delay:0}:Nt?{navigate:t=>{window.location.replace(t)},delay:100}:{navigate:null,delay:0}}W(t){if(!Nt)return;const e=[];if(t.css){const n=document.createElement(\"style\");n.innerHTML=t.css,document.head.appendChild(n),e.push((()=>n.remove()))}if(t.js){const n=document.createElement(\"script\");n.innerHTML=t.js,this.i.jsInjectionNonce&&(n.nonce=this.i.jsInjectionNonce),document.head.appendChild(n),e.push((()=>n.remove()))}return t.domMutations&&t.domMutations.forEach((t=>{e.push(function(t){var e=t.selector,n=t.action,i=t.value,s=t.attribute,o=t.parentSelector,u=t.insertBeforeSelector;if(\"html\"===s){if(\"append\"===n)return F(e,(function(t){return t+(null!=i?i:\"\")}));if(\"set\"===n)return F(e,(function(){return null!=i?i:\"\"}))}else if(\"class\"===s){if(\"append\"===n)return T(e,(function(t){i&&t.add(i)}));if(\"remove\"===n)return T(e,(function(t){i&&t.delete(i)}));if(\"set\"===n)return T(e,(function(t){t.clear(),i&&t.add(i)}))}else if(\"position\"===s){if(\"set\"===n&&o)return function(t,e){return R({kind:\"position\",elements:new Set,mutate:function(){return{insertBeforeSelector:u,parentSelector:o}},selector:t})}(e)}else{if(\"append\"===n)return B(e,s,(function(t){return null!==t?t+(null!=i?i:\"\"):null!=i?i:\"\"}));if(\"set\"===n)return B(e,s,(function(){return null!=i?i:\"\"}));if(\"remove\"===n)return B(e,s,(function(){return null}))}return r}(t).revert)})),()=>{e.forEach((t=>t()))}}async refreshStickyBuckets(t){if(this.i.stickyBucketService){const e=this.j(),n=await async function(t,e,n){const r=function(t,e){const n={};return function(t,e){const n=new Set,r=e&&e.features?e.features:t.global.features||{},i=e&&e.experiments?e.experiments:t.global.experiments||[];return Object.keys(r).forEach((t=>{const e=r[t];if(e.rules)for(const t of e.rules)t.variations&&(n.add(t.hashAttribute||\"id\"),t.fallbackAttribute&&n.add(t.fallbackAttribute))})),i.map((t=>{n.add(t.hashAttribute||\"id\"),t.fallbackAttribute&&n.add(t.fallbackAttribute)})),Array.from(n)}(t,e).forEach((e=>{const{hashValue:r}=Tt(t,e);n[e]=L(r)})),n}(t,n);return e.getAllAssignments(r)}(e,this.i.stickyBucketService,t);this.i.stickyBucketAssignmentDocs=n}}}({...Dt,remoteEval:!!Dt.remoteEval,trackingCallback:async(t,e)=>{const n=[],r={experiment_id:t.key,variation_id:e.key};if(It.additionalTrackingCallback&&n.push(Promise.resolve(It.additionalTrackingCallback(t,e))),window.gtag){let t;const e=new Promise((e=>{t=e}));n.push(e),window.gtag(\"event\",\"experiment_viewed\",{...r,event_callback:t})}if(window.dataLayer){let t;const e=new Promise((e=>{t=e}));n.push(e),window.dataLayer.push({event:\"experiment_viewed\",...r,eventCallback:t})}if(window.analytics&&window.analytics.track){window.analytics.track(\"Experiment Viewed\",r);const t=new Promise((t=>window.setTimeout(t,300)));n.push(t)}await Promise.all(n)},...It,attributes:Qt(),stickyBucketService:qt});Yt.setRenderer((()=>{document.dispatchEvent(new CustomEvent(\"growthbookdata\"))})),Yt.init({payload:It.payload,streaming:!(It.noStreaming||Dt.noStreaming||!1===It.backgroundSync),cacheSettings:It.cacheSettings}).then((()=>{(It.antiFlicker||Dt.antiFlicker)&&(Yt.getRedirectUrl()?Wt():Xt())}));let te=location.href;setInterval((()=>{location.href!==te&&(te=location.href,Yt.setURL(te),Yt.updateAttributes(Qt()))}),500),document.addEventListener(\"growthbookrefresh\",(()=>{location.href!==te&&(te=location.href,Yt.setURL(te)),Yt.updateAttributes(Qt())})),document.addEventListener(\"growthbookpersist\",(()=>{Gt()}));const ee=t=>{try{t&&t(Yt)}catch(t){console.error(\"Uncaught growthbook_queue error\",t)}};return window.growthbook_queue&&Array.isArray(window.growthbook_queue)&&window.growthbook_queue.forEach((t=>{ee(t)})),window.growthbook_queue={push:t=>{ee(t)}},Yt}();\n//# sourceMappingURL=auto.min.js.map\n";
package/src/index.ts CHANGED
@@ -2,6 +2,15 @@ export {
2
2
  Context,
3
3
  Config,
4
4
  Helpers,
5
+ Hooks,
6
+ BaseHookParams,
7
+ OnRouteParams,
8
+ OnUserAttributesParams,
9
+ OnGrowthBookInitParams,
10
+ OnBeforeOriginFetchParams,
11
+ OnOriginFetchParams,
12
+ OnBodyReadyParams,
13
+ OnBeforeResponseParams,
5
14
  ExperimentRunEnvironment,
6
15
  Route,
7
16
  } from "./types";
package/src/inject.ts CHANGED
@@ -10,9 +10,10 @@ import {
10
10
  import { sdkWrapper } from "./generated/sdkWrapper";
11
11
  import { Context } from "./types";
12
12
 
13
- export function injectScript({
13
+ export function injectScript<Req, Res>({
14
14
  context,
15
15
  body,
16
+ setBody,
16
17
  nonce,
17
18
  growthbook,
18
19
  attributes,
@@ -20,8 +21,9 @@ export function injectScript({
20
21
  url,
21
22
  oldUrl,
22
23
  }: {
23
- context: Context;
24
+ context: Context<Req, Res>;
24
25
  body: string;
26
+ setBody: (s: string) => void;
25
27
  nonce?: string;
26
28
  growthbook: GrowthBook;
27
29
  attributes: Attributes;
@@ -29,7 +31,7 @@ export function injectScript({
29
31
  url: string;
30
32
  oldUrl: string;
31
33
  }) {
32
- if (context.config.disableInjections) return body;
34
+ if (context.config.disableInjections) return;
33
35
 
34
36
  const sdkPayload = growthbook.getPayload();
35
37
  const experiments = growthbook.getExperiments();
@@ -138,10 +140,11 @@ ${
138
140
  body += scriptTag;
139
141
  }
140
142
 
141
- return body;
143
+ setBody(body);
144
+ return;
142
145
  }
143
146
 
144
- export function getCspInfo(context: Context): {
147
+ export function getCspInfo<Req, Res>(context: Context<Req, Res>): {
145
148
  csp?: string;
146
149
  nonce?: string;
147
150
  } {
@@ -166,13 +169,13 @@ export function getCspInfo(context: Context): {
166
169
  return { csp, nonce };
167
170
  }
168
171
 
169
- function getBlockedExperiments({
172
+ function getBlockedExperiments<Req, Res>({
170
173
  context,
171
174
  experiments,
172
175
  completedChangeIds,
173
176
  preRedirectChangeIds,
174
177
  }: {
175
- context: Context;
178
+ context: Context<Req, Res>;
176
179
  experiments: AutoExperiment[];
177
180
  completedChangeIds: string[];
178
181
  preRedirectChangeIds: string[];
package/src/redirect.ts CHANGED
@@ -2,18 +2,18 @@ import { GrowthBook } from "@growthbook/growthbook";
2
2
  import { Context } from "./types";
3
3
  import { getUserAttributes } from "./attributes";
4
4
 
5
- export default async function redirect({
5
+ export default async function redirect<Req, Res>({
6
6
  context,
7
7
  req,
8
- setCookie,
8
+ setRespCookie,
9
9
  growthbook,
10
10
  previousUrl,
11
11
  resetDomChanges,
12
12
  setPreRedirectChangeIds,
13
13
  }: {
14
- context: Context;
15
- req: unknown;
16
- setCookie: (key: string, value: string) => void;
14
+ context: Context<Req, Res>;
15
+ req: Req;
16
+ setRespCookie: (key: string, value: string) => void;
17
17
  growthbook: GrowthBook;
18
18
  previousUrl: string;
19
19
  resetDomChanges: () => void;
@@ -41,7 +41,7 @@ export default async function redirect({
41
41
 
42
42
  // update attributes and change the URL to trigger the experiment
43
43
  await growthbook.setAttributes(
44
- getUserAttributes(context, req, newUrl, setCookie),
44
+ getUserAttributes(context, req, newUrl, setRespCookie),
45
45
  );
46
46
  await growthbook.setURL(newUrl);
47
47
 
package/src/routing.ts CHANGED
@@ -1,8 +1,14 @@
1
1
  import { isURLTargeted } from "@growthbook/growthbook";
2
2
  import { Context, Route } from "./types";
3
3
 
4
- export function getRoute(context: Context, url: string): Route {
5
- const routes = context.config.routes || [];
4
+ const defaultRoute: Route = {
5
+ pattern: "*",
6
+ type: "simple",
7
+ behavior: "intercept",
8
+ };
9
+
10
+ export function getRoute<Req, Res>(context: Context<Req, Res>, url: string): Route {
11
+ const routes = [...(context.config.routes || []), defaultRoute];
6
12
  for (const route of routes) {
7
13
  route.type = route.type ?? "simple";
8
14
  route.behavior = route.behavior ?? "intercept";
@@ -36,9 +42,5 @@ export function getRoute(context: Context, url: string): Route {
36
42
  }
37
43
  }
38
44
  // Default route is intercept & process
39
- return {
40
- pattern: "*",
41
- type: "simple",
42
- behavior: "intercept",
43
- };
45
+ return defaultRoute;
44
46
  }
package/src/types.ts CHANGED
@@ -1,27 +1,34 @@
1
1
  /* eslint-disable @typescript-eslint/no-explicit-any */
2
2
 
3
3
  import {
4
+ GrowthBook,
4
5
  Attributes,
5
6
  FeatureApiResponse,
6
7
  LocalStorageCompat,
7
8
  StickyBucketService,
8
- TrackingCallback,
9
+ TrackingCallback
9
10
  } from "@growthbook/growthbook";
11
+ import { HTMLElement } from "node-html-parser";
10
12
 
11
- export interface Context<Req = unknown, Res = unknown> {
13
+ export interface Context<Req, Res> {
12
14
  config: Config;
13
15
  helpers: Helpers<Req, Res>;
16
+ hooks: Hooks<Req, Res>;
14
17
  }
15
18
 
16
19
  export interface Config {
17
20
  proxyTarget: string;
21
+ followRedirects: boolean;
18
22
  forwardProxyHeaders: boolean;
23
+ useDefaultContentType: boolean;
24
+ processTextHtmlOnly: boolean;
19
25
  environment: string;
20
26
  maxPayloadSize?: string;
21
27
  routes?: Route[];
22
28
 
23
29
  runVisualEditorExperiments: ExperimentRunEnvironment; // default: everywhere
24
30
  disableJsInjection: boolean;
31
+ alwaysParseDOM: boolean;
25
32
 
26
33
  runUrlRedirectExperiments: ExperimentRunEnvironment; // default: browser
27
34
  runCrossOriginUrlRedirectExperiments: ExperimentRunEnvironment; // default: browser
@@ -72,10 +79,10 @@ export type ExperimentRunEnvironment =
72
79
  | "skip";
73
80
 
74
81
  export interface Helpers<Req, Res> {
75
- getRequestURL?: (req: Req) => string;
76
- getRequestMethod?: (req: Req) => string;
82
+ getRequestURL: (req: Req) => string;
83
+ getRequestMethod: (req: Req) => string;
77
84
  getRequestHeader?: (req: Req, key: string) => string | undefined;
78
- sendResponse?: (
85
+ sendResponse: (
79
86
  ctx: Context<Req, Res>,
80
87
  res?: Res,
81
88
  headers?: Record<string, any>,
@@ -83,8 +90,8 @@ export interface Helpers<Req, Res> {
83
90
  cookies?: Record<string, string>,
84
91
  status?: number,
85
92
  ) => unknown;
86
- fetch?: (ctx: Context<Req, Res>, url: string) => Promise<Res>;
87
- proxyRequest?: (
93
+ fetch: (ctx: Context<Req, Res>, url: string, req: Req) => Promise<Res>;
94
+ proxyRequest: (
88
95
  ctx: Context<Req, Res>,
89
96
  req: Req,
90
97
  res?: Res,
@@ -94,6 +101,52 @@ export interface Helpers<Req, Res> {
94
101
  setCookie?: (res: Res, key: string, value: string) => void;
95
102
  }
96
103
 
104
+ export type BaseHookParams<Req, Res> = {
105
+ context: Context<Req, Res>;
106
+ req: Req;
107
+ res?: Res;
108
+ next?: any;
109
+ requestUrl: string;
110
+ originUrl: string;
111
+ };
112
+ export type OnRouteParams<Req, Res> = BaseHookParams<Req, Res> & {
113
+ route: Route;
114
+ };
115
+ export type OnUserAttributesParams<Req, Res> = OnRouteParams<Req, Res> & {
116
+ attributes: Attributes;
117
+ };
118
+ export type OnGrowthBookInitParams<Req, Res> = OnUserAttributesParams<Req, Res> & {
119
+ growthbook: GrowthBook;
120
+ };
121
+ export type OnBeforeOriginFetchParams<Req, Res> = OnGrowthBookInitParams<Req, Res> & {
122
+ redirectRequestUrl: string;
123
+ };
124
+ export type OnOriginFetchParams<Req, Res> = OnBeforeOriginFetchParams<Req, Res> & {
125
+ originResponse: Res | undefined;
126
+ originStatus: number;
127
+ };
128
+ export type OnBodyReadyParams<Req, Res> = OnOriginFetchParams<Req, Res> & {
129
+ originHeaders: Record<string, string | undefined>;
130
+ resHeaders: Record<string, string | undefined>;
131
+ body: string;
132
+ setBody: (s: string) => void;
133
+ root?: HTMLElement;
134
+ };
135
+ export type OnBeforeResponseParams<Req, Res> = Omit<OnBodyReadyParams<Req, Res>, "root">;
136
+
137
+ type HookReturn<Res> = Res | undefined | void;
138
+
139
+ export interface Hooks<Req, Res> {
140
+ onRequest?: (params: BaseHookParams<Req, Res>) => Promise<HookReturn<Res>> | HookReturn<Res>;
141
+ onRoute?: (params: OnRouteParams<Req, Res>) => Promise<HookReturn<Res>> | HookReturn<Res>;
142
+ onUserAttributes?: (params: OnUserAttributesParams<Req, Res>) => Promise<HookReturn<Res>> | HookReturn<Res>;
143
+ onGrowthbookInit?: (params: OnGrowthBookInitParams<Req, Res> ) => Promise<HookReturn<Res>> | HookReturn<Res>;
144
+ onBeforeOriginFetch?: (params: OnBeforeOriginFetchParams<Req, Res>) => Promise<HookReturn<Res>> | HookReturn<Res>;
145
+ onOriginFetch?: (params: OnOriginFetchParams<Req, Res>) => Promise<HookReturn<Res>> | HookReturn<Res>;
146
+ onBodyReady?: (params: OnBodyReadyParams<Req, Res>) => Promise<HookReturn<Res>> | HookReturn<Res>;
147
+ onBeforeResponse?: (params: OnBeforeResponseParams<Req, Res>) => Promise<HookReturn<Res>> | HookReturn<Res>;
148
+ }
149
+
97
150
  export type Route = {
98
151
  pattern: string;
99
152
  type?: "regex" | "simple";