@contentful/optimization-web 0.1.0-alpha

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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +491 -0
  3. package/dist/AutoEntryViewTracking.d.ts +88 -0
  4. package/dist/AutoEntryViewTracking.d.ts.map +1 -0
  5. package/dist/Optimization.d.ts +146 -0
  6. package/dist/Optimization.d.ts.map +1 -0
  7. package/dist/analyzer.html +4 -0
  8. package/dist/builders/EventBuilder.d.ts +42 -0
  9. package/dist/builders/EventBuilder.d.ts.map +1 -0
  10. package/dist/builders/index.d.ts +2 -0
  11. package/dist/builders/index.d.ts.map +1 -0
  12. package/dist/contentful-optimization-web.umd.cjs +2 -0
  13. package/dist/contentful-optimization-web.umd.cjs.map +1 -0
  14. package/dist/global-constants.d.ts +37 -0
  15. package/dist/global-constants.d.ts.map +1 -0
  16. package/dist/handlers/beaconHandler.d.ts +24 -0
  17. package/dist/handlers/beaconHandler.d.ts.map +1 -0
  18. package/dist/handlers/createOnlineChangeListener.d.ts +34 -0
  19. package/dist/handlers/createOnlineChangeListener.d.ts.map +1 -0
  20. package/dist/handlers/createVisibilityChangeListener.d.ts +40 -0
  21. package/dist/handlers/createVisibilityChangeListener.d.ts.map +1 -0
  22. package/dist/handlers/index.d.ts +4 -0
  23. package/dist/handlers/index.d.ts.map +1 -0
  24. package/dist/index.cjs +2 -0
  25. package/dist/index.cjs.map +1 -0
  26. package/dist/index.d.ts +7 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +6244 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/observers/ElementExistenceObserver.d.ts +195 -0
  31. package/dist/observers/ElementExistenceObserver.d.ts.map +1 -0
  32. package/dist/observers/ElementView.d.ts +178 -0
  33. package/dist/observers/ElementView.d.ts.map +1 -0
  34. package/dist/observers/ElementViewObserver.d.ts +164 -0
  35. package/dist/observers/ElementViewObserver.d.ts.map +1 -0
  36. package/dist/observers/index.d.ts +6 -0
  37. package/dist/observers/index.d.ts.map +1 -0
  38. package/dist/storage/LocalStore.d.ts +111 -0
  39. package/dist/storage/LocalStore.d.ts.map +1 -0
  40. package/dist/storage/index.d.ts +3 -0
  41. package/dist/storage/index.d.ts.map +1 -0
  42. package/dist/test/helpers.d.ts +41 -0
  43. package/dist/test/helpers.d.ts.map +1 -0
  44. package/dist/visualizer.html +4687 -0
  45. package/package.json +28 -0
@@ -0,0 +1,2 @@
1
+ (function(ze,J){typeof exports=="object"&&typeof module<"u"?module.exports=J():typeof define=="function"&&define.amd?define(J):(ze=typeof globalThis<"u"?globalThis:ze||self,ze.Optimization=J())})(this,function(){"use strict";var ze=Symbol.for("preact-signals");function J(){if(Q>1)Q--;else{for(var t,e=!1;ke!==void 0;){var n=ke;for(ke=void 0,ft++;n!==void 0;){var r=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&tn(n))try{n.c()}catch(i){e||(t=i,e=!0)}n=r}}if(ft=0,Q--,e)throw t}}function Te(t){if(Q>0)return t();Q++;try{return t()}finally{J()}}var v=void 0;function Yt(t){var e=v;v=void 0;try{return t()}finally{v=e}}var ke=void 0,Q=0,ft=0,qe=0;function en(t){if(v!==void 0){var e=t.n;if(e===void 0||e.t!==v)return e={i:0,S:t,p:v.s,n:void 0,t:v,e:void 0,x:void 0,r:e},v.s!==void 0&&(v.s.n=e),v.s=e,t.n=e,32&v.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=v.s,e.n=void 0,v.s.n=e,v.s=e),e}}function I(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}I.prototype.brand=ze,I.prototype.h=function(){return!0},I.prototype.S=function(t){var e=this,n=this.t;n!==t&&t.e===void 0&&(t.x=n,this.t=t,n!==void 0?n.e=t:Yt(function(){var r;(r=e.W)==null||r.call(e)}))},I.prototype.U=function(t){var e=this;if(this.t!==void 0){var n=t.e,r=t.x;n!==void 0&&(n.x=r,t.e=void 0),r!==void 0&&(r.e=n,t.x=void 0),t===this.t&&(this.t=r,r===void 0&&Yt(function(){var i;(i=e.Z)==null||i.call(e)}))}},I.prototype.subscribe=function(t){var e=this;return V(function(){var n=e.value,r=v;v=void 0;try{t(n)}finally{v=r}},{name:"sub"})},I.prototype.valueOf=function(){return this.value},I.prototype.toString=function(){return this.value+""},I.prototype.toJSON=function(){return this.value},I.prototype.peek=function(){var t=v;v=void 0;try{return this.value}finally{v=t}},Object.defineProperty(I.prototype,"value",{get:function(){var t=en(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(ft>100)throw new Error("Cycle detected");this.v=t,this.i++,qe++,Q++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{J()}}}});function fe(t,e){return new I(t,e)}function tn(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}function nn(t){for(var e=t.s;e!==void 0;e=e.n){var n=e.S.n;if(n!==void 0&&(e.r=n),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}function rn(t){for(var e=t.s,n=void 0;e!==void 0;){var r=e.p;e.i===-1?(e.S.U(e),r!==void 0&&(r.n=e.n),e.n!==void 0&&(e.n.p=r)):n=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=r}t.s=n}function ne(t,e){I.call(this,void 0),this.x=t,this.s=void 0,this.g=qe-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}ne.prototype=new I,ne.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===qe))return!0;if(this.g=qe,this.f|=1,this.i>0&&!tn(this))return this.f&=-2,!0;var t=v;try{nn(this),v=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return v=t,rn(this),this.f&=-2,!0},ne.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}I.prototype.S.call(this,t)},ne.prototype.U=function(t){if(this.t!==void 0&&(I.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}},ne.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}},Object.defineProperty(ne.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=en(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function Or(t,e){return new ne(t,e)}function on(t){var e=t.u;if(t.u=void 0,typeof e=="function"){Q++;var n=v;v=void 0;try{e()}catch(r){throw t.f&=-2,t.f|=8,pt(t),r}finally{v=n,J()}}}function pt(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,on(t)}function Mr(t){if(v!==this)throw new Error("Out-of-order effect");rn(this),v=t,this.f&=-2,8&this.f&&pt(this),J()}function pe(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}pe.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}},pe.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,on(this),nn(this),Q++;var t=v;return v=this,Mr.bind(this,t)},pe.prototype.N=function(){2&this.f||(this.f|=2,this.o=ke,ke=this)},pe.prototype.d=function(){this.f|=8,1&this.f||pt(this)},pe.prototype.dispose=function(){this.d()};function V(t,e){var n=new pe(t,e);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}const ht={resolve(t){return t?t.reduce((e,{key:n,value:r})=>{const i=typeof r=="object"&&r!==null&&"value"in r&&typeof r.value=="object"?r.value:r;return e[n]=i,e},{}):{}}};function p(t,e,n){function r(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(const d in s.prototype)d in a||Object.defineProperty(a,d,{value:s.prototype[d].bind(a)});a._zod.constr=s,a._zod.def=c}const i=n?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:t});function s(a){var c;const u=n?.Parent?new o:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(const d of u._zod.deferred)d();return u}return Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}class he extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class xr extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const Vr={};function ge(t){return Vr}function Nr(t){const e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,i])=>e.indexOf(+r)===-1).map(([r,i])=>i)}function Lr(t,e){return typeof e=="bigint"?e.toString():e}function sn(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function an(t){return t==null}function gt(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}const cn=Symbol("evaluating");function w(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==cn)return r===void 0&&(r=cn,r=n()),r},set(i){Object.defineProperty(t,e,{value:i})},configurable:!0})}function vt(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function un(...t){const e={};for(const n of t){const r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}const ln="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function He(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function yt(t){if(He(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(He(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function jr(t){return yt(t)?{...t}:t}const Ur=new Set(["string","number","symbol"]);function mt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bt(t,e,n){const r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function C(t){return{}}function Zr(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function Br(t,e){if(!yt(e))throw new Error("Invalid input to extend: expected a plain object");const n=t._zod.def.checks;if(n&&n.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const i=un(t._zod.def,{get shape(){const o={...t._zod.def.shape,...e};return vt(this,"shape",o),o},checks:[]});return bt(t,i)}function Dr(t,e,n){const r=un(e._zod.def,{get shape(){const i=e._zod.def.shape,o={...i};for(const s in i)o[s]=t?new t({type:"optional",innerType:i[s]}):i[s];return vt(this,"shape",o),o},checks:[]});return bt(e,r)}function Ae(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function ve(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function Ke(t){return typeof t=="string"?t:t?.message}function ye(t,e,n){const r={...t,path:t.path??[]};if(!t.message){const i=Ke(t.inst?._zod.def?.error?.(t))??Ke(e?.error?.(t))??Ke(n.customError?.(t))??Ke(n.localeError?.(t))??"Invalid input";r.message=i}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function dn(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Fr(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const fn=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Lr,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},qr=p("$ZodError",fn),We=p("$ZodError",fn,{Parent:Error}),Hr=(t=>(e,n,r,i)=>{const o=r?Object.assign(r,{async:!1}):{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new he;if(s.issues.length){const a=new(i?.Err??t)(s.issues.map(c=>ye(c,o,ge())));throw ln(a,i?.callee),a}return s.value})(We),Kr=(t=>async(e,n,r,i)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const a=new(i?.Err??t)(s.issues.map(c=>ye(c,o,ge())));throw ln(a,i?.callee),a}return s.value})(We),pn=(t=>(e,n,r)=>{const i=r?{...r,async:!1}:{async:!1},o=e._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new he;return o.issues.length?{success:!1,error:new(t??qr)(o.issues.map(s=>ye(s,i,ge())))}:{success:!0,data:o.value}})(We),hn=(t=>async(e,n,r)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let o=e._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(s=>ye(s,i,ge())))}:{success:!0,data:o.value}})(We),Wr="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function Gr(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Jr(t){const e=Gr({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${e}(?:${n.join("|")})`;return new RegExp(`^${Wr}T(?:${r})$`)}const Qr=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Xr=/^-?\d+(?:\.\d+)?/i,Yr=/true|false/i,ei=/null/i,Ge=p("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),ti=p("$ZodCheckMinLength",(t,e)=>{var n;Ge.init(t,e),(n=t._zod.def).when??(n.when=r=>{const i=r.value;return!an(i)&&i.length!==void 0}),t._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const i=r.value;if(i.length>=e.minimum)return;const s=dn(i);r.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),ni=p("$ZodCheckLengthEquals",(t,e)=>{var n;Ge.init(t,e),(n=t._zod.def).when??(n.when=r=>{const i=r.value;return!an(i)&&i.length!==void 0}),t._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),t._zod.check=r=>{const i=r.value,o=i.length;if(o===e.length)return;const s=dn(i),a=o>e.length;r.issues.push({origin:s,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),ri=p("$ZodCheckStringFormat",(t,e)=>{var n,r;Ge.init(t,e),t._zod.onattach.push(i=>{const o=i._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),ii={major:4,minor:1,patch:5},z=p("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=ii;const r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(const i of r)for(const o of i._zod.onattach)o(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const i=(s,a,c)=>{let u=Ae(s),d;for(const m of a){if(m._zod.def.when){if(!m._zod.def.when(s))continue}else if(u)continue;const _=s.issues.length,S=m._zod.check(s);if(S instanceof Promise&&c?.async===!1)throw new he;if(d||S instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await S,s.issues.length!==_&&(u||(u=Ae(s,_)))});else{if(s.issues.length===_)continue;u||(u=Ae(s,_))}}return d?d.then(()=>s):s},o=(s,a,c)=>{if(Ae(s))return s.aborted=!0,s;const u=i(a,r,c);if(u instanceof Promise){if(c.async===!1)throw new he;return u.then(d=>t._zod.parse(d,c))}return t._zod.parse(u,c)};t._zod.run=(s,a)=>{if(a.skipChecks)return t._zod.parse(s,a);if(a.direction==="backward"){const u=t._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(d=>o(d,s,a)):o(u,s,a)}const c=t._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new he;return c.then(u=>i(u,r,a))}return i(c,r,a)}}t["~standard"]={validate:i=>{try{const o=pn(t,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return hn(t,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),gn=p("$ZodString",(t,e)=>{z.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Qr(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),vn=p("$ZodStringFormat",(t,e)=>{ri.init(t,e),gn.init(t,e)}),oi=p("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Jr(e)),vn.init(t,e)}),si=p("$ZodNumber",(t,e)=>{z.init(t,e),t._zod.pattern=t._zod.bag.pattern??Xr,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}const i=n.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;const o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:t,...o?{received:o}:{}}),n}}),ai=p("$ZodBoolean",(t,e)=>{z.init(t,e),t._zod.pattern=Yr,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:t}),n}}),ci=p("$ZodNull",(t,e)=>{z.init(t,e),t._zod.pattern=ei,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{const i=n.value;return i===null||n.issues.push({expected:"null",code:"invalid_type",input:i,inst:t}),n}}),ui=p("$ZodAny",(t,e)=>{z.init(t,e),t._zod.parse=n=>n}),li=p("$ZodUnknown",(t,e)=>{z.init(t,e),t._zod.parse=n=>n});function yn(t,e,n){t.issues.length&&e.issues.push(...ve(n,t.issues)),e.value[n]=t.value}const di=p("$ZodArray",(t,e)=>{z.init(t,e),t._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:t}),n;n.value=Array(i.length);const o=[];for(let s=0;s<i.length;s++){const a=i[s],c=e.element._zod.run({value:a,issues:[]},r);c instanceof Promise?o.push(c.then(u=>yn(u,n,s))):yn(c,n,s)}return o.length?Promise.all(o).then(()=>n):n}});function Je(t,e,n,r){t.issues.length&&e.issues.push(...ve(n,t.issues)),t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function fi(t){const e=Object.keys(t.shape);for(const r of e)if(!t.shape[r]._zod.traits.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=Zr(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function pi(t,e,n,r,i,o){const s=[],a=i.keySet,c=i.catchall._zod,u=c.def.type;for(const d of Object.keys(e)){if(a.has(d))continue;if(u==="never"){s.push(d);continue}const m=c.run({value:e[d],issues:[]},r);m instanceof Promise?t.push(m.then(_=>Je(_,n,d,e))):Je(m,n,d,e)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:o}),t.length?Promise.all(t).then(()=>n):n}const hi=p("$ZodObject",(t,e)=>{z.init(t,e);const n=sn(()=>fi(e));w(t._zod,"propValues",()=>{const s=e.shape,a={};for(const c in s){const u=s[c]._zod;if(u.values){a[c]??(a[c]=new Set);for(const d of u.values)a[c].add(d)}}return a});const r=He,i=e.catchall;let o;t._zod.parse=(s,a)=>{o??(o=n.value);const c=s.value;if(!r(c))return s.issues.push({expected:"object",code:"invalid_type",input:c,inst:t}),s;s.value={};const u=[],d=o.shape;for(const m of o.keys){const S=d[m]._zod.run({value:c[m],issues:[]},a);S instanceof Promise?u.push(S.then(b=>Je(b,s,m,c))):Je(S,s,m,c)}return i?pi(u,c,s,a,n.value,t):u.length?Promise.all(u).then(()=>s):s}});function mn(t,e,n,r){for(const o of t)if(o.issues.length===0)return e.value=o.value,e;const i=t.filter(o=>!Ae(o));return i.length===1?(e.value=i[0].value,i[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(o=>o.issues.map(s=>ye(s,r,ge())))}),e)}const bn=p("$ZodUnion",(t,e)=>{z.init(t,e),w(t._zod,"optin",()=>e.options.some(i=>i._zod.optin==="optional")?"optional":void 0),w(t._zod,"optout",()=>e.options.some(i=>i._zod.optout==="optional")?"optional":void 0),w(t._zod,"values",()=>{if(e.options.every(i=>i._zod.values))return new Set(e.options.flatMap(i=>Array.from(i._zod.values)))}),w(t._zod,"pattern",()=>{if(e.options.every(i=>i._zod.pattern)){const i=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${i.map(o=>gt(o.source)).join("|")})$`)}});const n=e.options.length===1,r=e.options[0]._zod.run;t._zod.parse=(i,o)=>{if(n)return r(i,o);let s=!1;const a=[];for(const c of e.options){const u=c._zod.run({value:i.value,issues:[]},o);if(u instanceof Promise)a.push(u),s=!0;else{if(u.issues.length===0)return u;a.push(u)}}return s?Promise.all(a).then(c=>mn(c,i,t,o)):mn(a,i,t,o)}}),gi=p("$ZodDiscriminatedUnion",(t,e)=>{bn.init(t,e);const n=t._zod.parse;w(t._zod,"propValues",()=>{const i={};for(const o of e.options){const s=o._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(const[a,c]of Object.entries(s)){i[a]||(i[a]=new Set);for(const u of c)i[a].add(u)}}return i});const r=sn(()=>{const i=e.options,o=new Map;for(const s of i){const a=s._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(const c of a){if(o.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);o.set(c,s)}}return o});t._zod.parse=(i,o)=>{const s=i.value;if(!He(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),i;const a=r.value.get(s?.[e.discriminator]);return a?a._zod.run(i,o):e.unionFallback?n(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,input:s,path:[e.discriminator],inst:t}),i)}}),vi=p("$ZodRecord",(t,e)=>{z.init(t,e),t._zod.parse=(n,r)=>{const i=n.value;if(!yt(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),n;const o=[];if(e.keyType._zod.values){const s=e.keyType._zod.values;n.value={};for(const c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){const u=e.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?o.push(u.then(d=>{d.issues.length&&n.issues.push(...ve(c,d.issues)),n.value[c]=d.value})):(u.issues.length&&n.issues.push(...ve(c,u.issues)),n.value[c]=u.value)}let a;for(const c in i)s.has(c)||(a=a??[],a.push(c));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:a})}else{n.value={};for(const s of Reflect.ownKeys(i)){if(s==="__proto__")continue;const a=e.keyType._zod.run({value:s,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(u=>ye(u,r,ge())),input:s,path:[s],inst:t}),n.value[a.value]=a.value;continue}const c=e.valueType._zod.run({value:i[s],issues:[]},r);c instanceof Promise?o.push(c.then(u=>{u.issues.length&&n.issues.push(...ve(s,u.issues)),n.value[a.value]=u.value})):(c.issues.length&&n.issues.push(...ve(s,c.issues)),n.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>n):n}}),yi=p("$ZodEnum",(t,e)=>{z.init(t,e);const n=Nr(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(i=>Ur.has(typeof i)).map(i=>typeof i=="string"?mt(i):i.toString()).join("|")})$`),t._zod.parse=(i,o)=>{const s=i.value;return r.has(s)||i.issues.push({code:"invalid_value",values:n,input:s,inst:t}),i}}),mi=p("$ZodLiteral",(t,e)=>{if(z.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?mt(n):n?mt(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,r)=>{const i=n.value;return t._zod.values.has(i)||n.issues.push({code:"invalid_value",values:e.values,input:i,inst:t}),n}}),bi=p("$ZodTransform",(t,e)=>{z.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new xr(t.constructor.name);const i=e.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(s=>(n.value=s,n));if(i instanceof Promise)throw new he;return n.value=i,n}});function _n(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}const _i=p("$ZodOptional",(t,e)=>{z.init(t,e),t._zod.optin="optional",t._zod.optout="optional",w(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),w(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${gt(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>{if(e.innerType._zod.optin==="optional"){const i=e.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>_n(o,n.value)):_n(i,n.value)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),wi=p("$ZodNullable",(t,e)=>{z.init(t,e),w(t._zod,"optin",()=>e.innerType._zod.optin),w(t._zod,"optout",()=>e.innerType._zod.optout),w(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${gt(n.source)}|null)$`):void 0}),w(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),Ei=p("$ZodPrefault",(t,e)=>{z.init(t,e),t._zod.optin="optional",w(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),Si=p("$ZodPipe",(t,e)=>{z.init(t,e),w(t._zod,"values",()=>e.in._zod.values),w(t._zod,"optin",()=>e.in._zod.optin),w(t._zod,"optout",()=>e.out._zod.optout),w(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if(r.direction==="backward"){const o=e.out._zod.run(n,r);return o instanceof Promise?o.then(s=>Qe(s,e.in,r)):Qe(o,e.in,r)}const i=e.in._zod.run(n,r);return i instanceof Promise?i.then(o=>Qe(o,e.out,r)):Qe(i,e.out,r)}});function Qe(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},n)}const zi=p("$ZodLazy",(t,e)=>{z.init(t,e),w(t._zod,"innerType",()=>e.getter()),w(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),w(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),w(t._zod,"optin",()=>t._zod.innerType._zod.optin??void 0),w(t._zod,"optout",()=>t._zod.innerType._zod.optout??void 0),t._zod.parse=(n,r)=>t._zod.innerType._zod.run(n,r)}),Ti=p("$ZodCustom",(t,e)=>{Ge.init(t,e),z.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{const r=n.value,i=e.fn(r);if(i instanceof Promise)return i.then(o=>wn(o,n,r,t));wn(i,n,r,t)}});function wn(t,e,n,r){if(!t){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),e.issues.push(Fr(i))}}function ki(t,e){return new t({type:"string",...C()})}function Ai(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...C()})}function $i(t,e){return new t({type:"number",checks:[],...C()})}function Pi(t,e){return new t({type:"boolean",...C()})}function Ii(t,e){return new t({type:"null",...C()})}function Ci(t){return new t({type:"any"})}function Ri(t){return new t({type:"unknown"})}function Oi(t,e){return new ti({check:"min_length",...C(),minimum:t})}function Mi(t,e){return new ni({check:"length_equals",...C(),length:t})}function xi(t,e,n){const r=C();return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}const T=p("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");z.init(t,e),t.def=e,t.type=e.type,t.parse=(n,r)=>Hr(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>pn(t,n,r),t.parseAsync=async(n,r)=>Kr(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>hn(t,n,r),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>bt(t,n,r),t.brand=()=>t,t.register=(n,r)=>(n.add(t,r),t)}),En=p("ZodMiniString",(t,e)=>{gn.init(t,e),T.init(t,e)});function l(t){return ki(En)}const Vi=p("ZodMiniStringFormat",(t,e)=>{vn.init(t,e),En.init(t,e)}),Ni=p("ZodMiniNumber",(t,e)=>{si.init(t,e),T.init(t,e)});function A(t){return $i(Ni)}const Li=p("ZodMiniBoolean",(t,e)=>{ai.init(t,e),T.init(t,e)});function D(t){return Pi(Li)}const ji=p("ZodMiniNull",(t,e)=>{ci.init(t,e),T.init(t,e)});function _t(t){return Ii(ji)}const Ui=p("ZodMiniAny",(t,e)=>{ui.init(t,e),T.init(t,e)});function Sn(){return Ci(Ui)}const Zi=p("ZodMiniUnknown",(t,e)=>{li.init(t,e),T.init(t,e)});function Bi(){return Ri(Zi)}const Di=p("ZodMiniArray",(t,e)=>{di.init(t,e),T.init(t,e)});function $(t,e){return new Di({type:"array",element:t,...C()})}const Fi=p("ZodMiniObject",(t,e)=>{hi.init(t,e),T.init(t,e),w(t,"shape",()=>e.shape)});function h(t,e){const n={type:"object",get shape(){return vt(this,"shape",{...t}),this.shape},...C()};return new Fi(n)}function g(t,e){return Br(t,e)}function qi(t,e){return Dr(Tn,t)}function $e(t,e){return t.clone({...t._zod.def,catchall:e})}const Hi=p("ZodMiniUnion",(t,e)=>{bn.init(t,e),T.init(t,e)});function X(t,e){return new Hi({type:"union",options:t,...C()})}const Ki=p("ZodMiniDiscriminatedUnion",(t,e)=>{gi.init(t,e),T.init(t,e)});function Pe(t,e,n){return new Ki({type:"union",options:e,discriminator:t,...C()})}const Wi=p("ZodMiniRecord",(t,e)=>{vi.init(t,e),T.init(t,e)});function re(t,e,n){return new Wi({type:"record",keyType:t,valueType:e,...C()})}const Gi=p("ZodMiniEnum",(t,e)=>{yi.init(t,e),T.init(t,e),t.options=Object.values(e.entries)});function zn(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Gi({type:"enum",entries:n,...C()})}const Ji=p("ZodMiniLiteral",(t,e)=>{mi.init(t,e),T.init(t,e)});function y(t,e){return new Ji({type:"literal",values:Array.isArray(t)?t:[t],...C()})}const Qi=p("ZodMiniTransform",(t,e)=>{bi.init(t,e),T.init(t,e)});function Xi(t){return new Qi({type:"transform",transform:t})}const Tn=p("ZodMiniOptional",(t,e)=>{_i.init(t,e),T.init(t,e)});function f(t){return new Tn({type:"optional",innerType:t})}const Yi=p("ZodMiniNullable",(t,e)=>{wi.init(t,e),T.init(t,e)});function Xe(t){return new Yi({type:"nullable",innerType:t})}const eo=p("ZodMiniPrefault",(t,e)=>{Ei.init(t,e),T.init(t,e)});function H(t,e){return new eo({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():jr(e)}})}const to=p("ZodMiniPipe",(t,e)=>{Si.init(t,e),T.init(t,e)});function no(t,e){return new to({type:"pipe",in:t,out:e})}const ro=p("ZodMiniLazy",(t,e)=>{zi.init(t,e),T.init(t,e)});function io(t){return new ro({type:"lazy",getter:t})}const oo=p("ZodMiniCustom",(t,e)=>{Ti.init(t,e),T.init(t,e)});function so(t,e){return xi(oo,()=>!0)}function K(){const t=io(()=>X([l(),A(),D(),_t(),$(t),re(l(),t)]));return t}const ao=p("$ZodISODateTime",(t,e)=>{oi.init(t,e),Vi.init(t,e)});function wt(t){return Ai(ao)}const Ye=$e(h({}),K()),co=h({sys:h({type:y("Link"),linkType:l(),id:l()})}),uo=h({sys:h({type:y("Link"),linkType:y("ContentType"),id:l()})}),lo=h({sys:h({type:y("Link"),linkType:y("Environment"),id:l()})}),fo=h({sys:h({type:y("Link"),linkType:y("Space"),id:l()})}),po=h({sys:h({type:y("Link"),linkType:y("Tag"),id:l()})}),kn=h({type:y("Entry"),contentType:uo,publishedVersion:A(),id:l(),createdAt:Sn(),updatedAt:Sn(),locale:f(l()),revision:A(),space:fo,environment:lo}),Ie=h({fields:Ye,metadata:$e(h({tags:$(po)}),K()),sys:kn});function ho(t){return Ie.safeParse(t).success}const go=g(Ye,{nt_audience_id:l(),nt_name:f(l()),nt_description:f(l())}),vo=g(Ie,{fields:go}),yo=g(Ie,{fields:h({nt_name:l(),nt_fallback:f(l()),nt_mergetag_id:l()}),sys:g(kn,{contentType:h({sys:h({type:y("Link"),linkType:y("ContentType"),id:y("nt_mergetag")})})})}),Et=h({id:l(),hidden:H(D(),!1)});function mo(t){return Et.safeParse(t).success}const bo=h({type:f(y("EntryReplacement")),baseline:Et,variants:$(Et)});function _o(t){return t.type==="EntryReplacement"||t.type===void 0}const An=h({value:X([l(),D(),_t(),A(),re(l(),K())])}),wo=zn(["Boolean","Number","Object","String"]),Eo=h({type:y("InlineVariable"),key:l(),valueType:wo,baseline:An,variants:$(An)}),So=Pe("type",[bo,Eo]),zo=$(So),To=h({distribution:f(H($(A()),[.5,.5])),traffic:f(H(A(),0)),components:f(H(zo,[{type:"EntryReplacement",baseline:{id:""},variants:[{id:""}]}])),sticky:f(H(D(),!1))}),ko=X([y("nt_experiment"),y("nt_personalization")]),Ao=g(Ye,{nt_name:l(),nt_description:f(Xe(l())),nt_type:ko,nt_config:no(f(H(Xe(To),null)),Xi(t=>t??{traffic:0,distribution:[.5,.5],components:[],sticky:!1})),nt_audience:f(Xe(vo)),nt_variants:f(H($(so()),[])),nt_experience_id:l()}),$n=g(Ie,{fields:Ao});function et(t){return $n.safeParse(t).success}const $o=$(X([co,$n])),Po=g(Ie,{fields:g(Ye,{nt_experiences:$o})});function St(t){return Po.safeParse(t).success}const Io=f(h({name:l(),version:l()})),Pn=h({name:f(l()),source:f(l()),medium:f(l()),term:f(l()),content:f(l())}),Co=X([y("mobile"),y("server"),y("web")]),Ro=re(l(),l()),Oo=2,Mo=h({latitude:A(),longitude:A()}),zt=h({coordinates:f(Mo),city:f(l()),postalCode:f(l()),region:f(l()),regionCode:f(l()),country:f(l()),countryCode:f(l().check(Mi(Oo))),continent:f(l()),timezone:f(l())}),xo=h({name:l(),version:l()}),me=$e(h({path:l(),query:Ro,referrer:l(),search:l(),title:f(l()),url:l()}),K()),tt=re(l(),K()),Tt=$e(h({name:l()}),K()),kt=re(l(),K()),Vo=h({id:l(),isReturningVisitor:D(),landingPage:me,count:A(),activeSessionLength:A(),averageSessionLength:A()}),nt=h({id:l(),stableId:l(),random:A(),audiences:$(l()),traits:kt,location:zt,session:Vo}),No=$e(h({id:l()}),K()),In=h({data:h(),message:l(),error:Xe(D())}),Lo=h({profiles:f($(nt))}),jo=g(In,{data:Lo}),Uo=["Variable"],Cn=h({key:l(),type:X([zn(Uo),l()]),meta:h({experienceId:l(),variantIndex:A()})}),Zo=X([l(),D(),_t(),A(),re(l(),K())]);g(Cn,{type:l(),value:Bi()});const Bo=g(Cn,{type:y("Variable"),value:Zo}),Do=Pe("type",[Bo]),Rn=$(Do),At=h({app:Io,campaign:Pn,gdpr:h({isConsentGiven:D()}),library:xo,locale:l(),location:f(zt),userAgent:f(l())}),ie=h({channel:Co,context:g(At,{page:f(me),screen:f(Tt)}),messageId:l(),originalTimestamp:wt(),sentAt:wt(),timestamp:wt(),userId:f(l())}),On=g(ie,{type:y("alias")}),$t=g(ie,{type:y("component"),componentType:X([y("Entry"),y("Variable")]),componentId:l(),experienceId:f(l()),variantIndex:A()}),Mn=g(ie,{type:y("group")}),xn=g(ie,{type:y("identify"),traits:kt}),Vn=g(At,{page:me}),Nn=g(ie,{type:y("page"),name:f(l()),properties:me,context:Vn}),Ln=g(At,{screen:Tt}),jn=g(ie,{type:y("screen"),name:l(),properties:f(tt),context:Ln}),Un=g(ie,{type:y("track"),event:l(),properties:tt}),oe={anonymousId:l()},Fo=Pe("type",[g(On,oe),g($t,oe),g(Mn,oe),g(xn,oe),g(Nn,oe),g(jn,oe),g(Un,oe)]);$(Fo);const Zn=Pe("type",[On,$t,Mn,xn,Nn,jn,Un]),rt=$(Zn),qo=h({features:f($(l()))});h({events:rt.check(Oi(1)),options:f(qo)});const Ho=h({experienceId:l(),variantIndex:A(),variants:re(l(),l()),sticky:f(H(D(),!1))}),Bn=$(Ho),Ko=h({profile:nt,experiences:Bn,changes:Rn}),Pt=g(In,{data:Ko}),Dn=Pe("type",[$t]),Wo=$(Dn),Go=h({profile:No,events:Wo}),Jo=$(Go);var It=[],Qo=t=>new RegExp(t.replace(/\*/g,".*")+"$"),Xo=t=>{It=t.split(/[\s,]+/).map(Qo)},be=(t,e,n,...r)=>{for(let i=It.length;i--;)if(It[i].test(t))return e({name:t,level:n,messages:r})},Yo=t=>{let e="";const n=console[t.level==="fatal"?"error":t.level];t.name&&(e+=`[${t.name}] `),typeof t.messages[0]=="object"?n(e,...t.messages):n(e+t.messages.shift(),...t.messages)},Fn=(t,e)=>({fatal:be.bind(0,t,e=e||Yo,"fatal"),error:be.bind(0,t,e,"error"),warn:be.bind(0,t,e,"warn"),debug:be.bind(0,t,e,"debug"),info:be.bind(0,t,e,"info"),log:be.bind(0,t,e,"log")}),_e=Fn("");_e.fatal,_e.error,_e.warn,_e.debug,_e.info,_e.log;class es{name="@contentful/optimization";PREFIX_PARTS=["Ctfl","O10n"];DELIMITER=":";diary;sinks=[];constructor(){this.diary=Fn(this.name,this.onLogEvent.bind(this)),Xo(this.name)}assembleLocationPrefix(e){return`[${[...this.PREFIX_PARTS,e].join(this.DELIMITER)}]`}addSink(e){this.sinks=[...this.sinks.filter(n=>n.name!==e.name),e]}removeSink(e){this.sinks=this.sinks.filter(n=>n.name!==e)}removeSinks(){this.sinks=[]}debug(e,n,...r){this.diary.debug(`${this.assembleLocationPrefix(e)} ${n}`,...r)}info(e,n,...r){this.diary.info(`${this.assembleLocationPrefix(e)} ${n}`,...r)}log(e,n,...r){this.diary.log(`${this.assembleLocationPrefix(e)} ${n}`,...r)}warn(e,n,...r){this.diary.warn(`${this.assembleLocationPrefix(e)} ${n}`,...r)}error(e,n,...r){this.diary.error(`${this.assembleLocationPrefix(e)} ${n}`,...r)}fatal(e,n,...r){this.diary.fatal(`${this.assembleLocationPrefix(e)} ${n}`,...r)}onLogEvent(e){this.sinks.forEach(n=>{n.ingest(e)})}}const se=new es;function R(t){return{debug:(e,...n)=>{se.debug(t,e,...n)},info:(e,...n)=>{se.info(t,e,...n)},log:(e,...n)=>{se.log(t,e,...n)},warn:(e,...n)=>{se.warn(t,e,...n)},error:(e,...n)=>{se.error(t,e,...n)},fatal:(e,...n)=>{se.fatal(t,e,...n)}}}class ts{}var we={fatal:60,error:50,warn:40,info:30,debug:20,log:10},ns=(t,e)=>e in we&&t in we?we[e]===we[t]?0:we[e]<we[t]?1:-1:0;const rs={debug:(...t)=>{console.debug(...t)},info:(...t)=>{console.info(...t)},log:(...t)=>{console.log(...t)},warn:(...t)=>{console.warn(...t)},error:(...t)=>{console.error(...t)},fatal:(...t)=>{console.error(...t)}},is=0;class os extends ts{name="ConsoleLogSink";verbosity;constructor(e){super(),this.verbosity=e??"error"}ingest(e){ns(this.verbosity,e.level)>is||rs[e.level](...e.messages)}}function ss(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ct={},Rt,qn;function as(){if(qn)return Rt;qn=1;function t(e,n){typeof n=="boolean"&&(n={forever:n}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=n||{},this._maxRetryTime=n&&n.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return Rt=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},t.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var n=new Date().getTime();if(e&&n-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);else return!1;var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},r),this._options.unref&&this._timer.unref(),!0},t.prototype.attempt=function(e,n){this._fn=e,n&&(n.timeout&&(this._operationTimeout=n.timeout),n.cb&&(this._operationTimeoutCb=n.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},t.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},t.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},n=null,r=0,i=0;i<this._errors.length;i++){var o=this._errors[i],s=o.message,a=(e[s]||0)+1;e[s]=a,a>=r&&(n=o,r=a)}return n},Rt}var Hn;function cs(){return Hn||(Hn=1,function(t){var e=as();t.operation=function(n){var r=t.timeouts(n);return new e(r,{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},t.timeouts=function(n){if(n instanceof Array)return[].concat(n);var r={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var i in n)r[i]=n[i];if(r.minTimeout>r.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var o=[],s=0;s<r.retries;s++)o.push(this.createTimeout(s,r));return n&&n.forever&&!o.length&&o.push(this.createTimeout(s,r)),o.sort(function(a,c){return a-c}),o},t.createTimeout=function(n,r){var i=r.randomize?Math.random()+1:1,o=Math.round(i*Math.max(r.minTimeout,1)*Math.pow(r.factor,n));return o=Math.min(o,r.maxTimeout),o},t.wrap=function(n,r,i){if(r instanceof Array&&(i=r,r=null),!i){i=[];for(var o in n)typeof n[o]=="function"&&i.push(o)}for(var s=0;s<i.length;s++){var a=i[s],c=n[a];n[a]=(function(d){var m=t.operation(r),_=Array.prototype.slice.call(arguments,1),S=_.pop();_.push(function(b){m.retry(b)||(b&&(arguments[0]=m.mainError()),S.apply(this,arguments))}),m.attempt(function(){d.apply(n,_)})}).bind(n,c),n[a].options=r}}}(Ct)),Ct}var Ot,Kn;function us(){return Kn||(Kn=1,Ot=cs()),Ot}var ls=us();const ds=ss(ls),fs=Object.prototype.toString,ps=t=>fs.call(t)==="[object Error]",hs=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function gs(t){return t&&ps(t)&&t.name==="TypeError"&&typeof t.message=="string"?t.message==="Load failed"?t.stack===void 0:hs.has(t.message):!1}class vs extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const Wn=(t,e,n)=>{const r=n.retries-(e-1);return t.attemptNumber=e,t.retriesLeft=r,t};async function ys(t,e){return new Promise((n,r)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;const i=ds.operation(e),o=()=>{i.stop(),r(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",o,{once:!0});const s=()=>{e.signal?.removeEventListener("abort",o),i.stop()};i.attempt(async a=>{try{const c=await t(a);s(),n(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof vs)throw c.originalError;if(c instanceof TypeError&&!gs(c))throw c;if(Wn(c,a,e),await e.shouldRetry(c)||(i.stop(),r(c)),await e.onFailedAttempt(c),!i.retry(c))throw i.mainError()}catch(u){Wn(u,a,e),s(),r(u)}}})})}const Mt=R("ApiClient:Retry"),ms=0,bs=1,xt=503,_s=500;class it extends Error{status;constructor(e,n=_s){super(e),Object.setPrototypeOf(this,it.prototype),this.status=n}}function ws({apiName:t="Optimization",controller:e,fetchMethod:n=fetch,init:r,url:i}){return async()=>{try{const o=await n(i,r);if(o.status===xt)throw new it(`${t} API request to "${i.toString()}" failed with status: "[${o.status}] ${o.statusText}".`,xt);if(!o.ok){const s=new Error(`Request to "${i.toString()}" failed with status: [${o.status}] ${o.statusText} - traceparent: ${o.headers.get("traceparent")}`);Mt.error("Request failed with non-OK status:",s),e.abort();return}return Mt.debug(`Response from "${i.toString()}":`,o),o}catch(o){if(o instanceof it&&o.status===xt)throw o;Mt.error(`Request to "${i.toString()}" failed:`,o),e.abort()}}}function Es({apiName:t="Optimization",fetchMethod:e=fetch,intervalTimeout:n=ms,onFailedAttempt:r,retries:i=bs}={}){return async(o,s)=>{const a=new AbortController;let c;try{c=await ys(ws({apiName:t,controller:a,fetchMethod:e,init:s,url:o}),{minTimeout:n,onFailedAttempt:u=>r?.({...u,apiName:t}),retries:i,signal:a.signal})}catch(u){if(!(u instanceof Error)||u.name!=="AbortError")throw u}if(!c)throw new Error(`${t} API request to "${o.toString()}" may not be retried.`);return c}}const Ss=R("ApiClient:Timeout"),zs=3e3;function Ts({apiName:t="Optimization",fetchMethod:e=fetch,onRequestTimeout:n,requestTimeout:r=zs}={}){return async(i,o)=>{const s=new AbortController,a=setTimeout(()=>{typeof n=="function"?n({apiName:t}):Ss.error(`Request to "${i.toString()}" timed out`,new Error("Request timeout")),s.abort()},r),c=await e(i,{...o,signal:s.signal});return clearTimeout(a),c}}const Gn=R("ApiClient:Fetch");function ks(t){try{const e=Ts(t);return Es({...t,fetchMethod:e})}catch(e){throw e instanceof Error&&(e.name==="AbortError"?Gn.warn("Request aborted due to network issues. This request may not be retried."):Gn.error("Request failed:",e)),e}}const As={create:ks},Jn=R("ApiClient"),$s="main";class Qn{name;clientId;environment;fetch;constructor(e,{fetchOptions:n,clientId:r,environment:i}){this.clientId=r,this.environment=i??$s,this.name=e,this.fetch=As.create({...n??{},apiName:e})}logRequestError(e,{requestName:n}){e instanceof Error&&(e.name==="AbortError"?Jn.warn(`[${this.name}] "${n}" request aborted due to network issues. This request may not be retried.`):Jn.error(`[${this.name}] "${n}" request failed:`,e))}}const L=R("ApiClient:Experience"),Ps="https://experience.ninetailed.co/";class Is extends Qn{baseUrl;enabledFeatures;ip;locale;plainText;preflight;constructor(e){super("Experience",e);const{baseUrl:n,enabledFeatures:r,ip:i,locale:o,plainText:s,preflight:a}=e;this.baseUrl=n||Ps,this.enabledFeatures=r,this.ip=i,this.locale=o,this.plainText=s,this.preflight=a}async getProfile(e,n={}){if(!e)throw new Error("Valid profile ID required.");const r="Get Profile";L.info(`Sending "${r}" request`);try{const i=await this.fetch(this.constructUrl(`v2/organizations/${this.clientId}/environments/${this.environment}/profiles/${e}`,n),{method:"GET"}),{data:{changes:o,experiences:s,profile:a}}=Pt.parse(await i.json()),c={changes:o,personalizations:s,profile:a};return L.debug(`"${r}" request successfully completed`),c}catch(i){throw this.logRequestError(i,{requestName:r}),i}}async makeProfileMutationRequest({url:e,body:n,options:r}){return await this.fetch(this.constructUrl(e,r),{method:"POST",headers:this.constructHeaders(r),body:JSON.stringify(n),keepalive:!0})}async createProfile({events:e},n={}){const r="Create Profile";L.info(`Sending "${r}" request`);const i={events:rt.parse(e),options:this.constructBodyOptions(n)};L.debug(`"${r}" request body:`,i);try{const o=await this.makeProfileMutationRequest({url:`v2/organizations/${this.clientId}/environments/${this.environment}/profiles`,body:i,options:n}),{data:{changes:s,experiences:a,profile:c}}=Pt.parse(await o.json()),u={changes:s,personalizations:a,profile:c};return L.debug(`"${r}" request successfully completed`),u}catch(o){throw this.logRequestError(o,{requestName:r}),o}}async updateProfile({profileId:e,events:n},r={}){if(!e)throw new Error("Valid profile ID required.");const i="Update Profile";L.info(`Sending "${i}" request`);const o={events:rt.parse(n),options:this.constructBodyOptions(r)};L.debug(`"${i}" request body:`,o);try{const s=await this.makeProfileMutationRequest({url:`v2/organizations/${this.clientId}/environments/${this.environment}/profiles/${e}`,body:o,options:r}),{data:{changes:a,experiences:c,profile:u}}=Pt.parse(await s.json()),d={changes:a,personalizations:c,profile:u};return L.debug(`"${i}" request successfully completed`),d}catch(s){throw this.logRequestError(s,{requestName:i}),s}}async upsertProfile({profileId:e,events:n},r){return e?await this.updateProfile({profileId:e,events:n},r):await this.createProfile({events:n},r)}async upsertManyProfiles({events:e},n={}){const r="Upsert Many Profiles";L.info(`Sending "${r}" request`);const i={events:rt.parse(e),options:this.constructBodyOptions(n)};L.debug(`"${r}" request body:`,i);try{const o=await this.makeProfileMutationRequest({url:`v2/organizations/${this.clientId}/environments/${this.environment}/events`,body:i,options:{plainText:!1,...n}}),{data:{profiles:s}}=jo.parse(await o.json());return L.debug(`"${r}" request successfully completed`),s}catch(o){throw this.logRequestError(o,{requestName:r}),o}}constructUrl(e,n){const r=new URL(e,this.baseUrl),i=n.locale??this.locale,o=n.preflight??this.preflight;return i&&r.searchParams.set("locale",i),o&&r.searchParams.set("type","preflight"),r.toString()}constructHeaders({ip:e=this.ip,plainText:n=this.plainText}){const r=new Map;return e&&r.set("X-Force-IP",e),n??this.plainText??!0?r.set("Content-Type","text/plain"):r.set("Content-Type","application/json"),Object.fromEntries(r)}constructBodyOptions=({enabledFeatures:e=this.enabledFeatures})=>{const n={};return e&&Array.isArray(e)&&e.length>0?n.features=e:n.features=["ip-enrichment","location"],n}}const Ce=R("ApiClient:Insights"),Cs="https://ingest.insights.ninetailed.co/";class Rs extends Qn{baseUrl;beaconHandler;constructor(e){super("Insights",e);const{baseUrl:n,beaconHandler:r}=e;this.baseUrl=n??Cs,this.beaconHandler=r}async sendBatchEvents(e,n={}){const{beaconHandler:r=this.beaconHandler}=n,i=new URL(`v1/organizations/${this.clientId}/environments/${this.environment}/events`,this.baseUrl),o=Jo.parse(e);if(typeof r=="function"){if(Ce.debug("Queueing events via beaconHandler"),r(i,o))return!0;Ce.warn("beaconHandler failed to queue events; events will be emitted immediately via fetch")}const s="Event Batches";Ce.info(`Sending "${s}" request`),Ce.debug(`"${s}" request body:`,o);try{return await this.fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),keepalive:!0}),Ce.debug(`"${s}" request successfully completed`),!0}catch(a){return this.logRequestError(a,{requestName:s}),!1}}}class Os{config;experience;insights;constructor(e){const{personalization:n,analytics:r,...i}=e;this.config=i,this.experience=new Is({...i,...n}),this.insights=new Rs({...i,...r})}}function Ms(){}function Xn(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Yn(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const xs="[object RegExp]",Vs="[object String]",Ns="[object Number]",Ls="[object Boolean]",er="[object Arguments]",js="[object Symbol]",Us="[object Date]",Zs="[object Map]",Bs="[object Set]",Ds="[object Array]",Fs="[object Function]",qs="[object ArrayBuffer]",Vt="[object Object]",Hs="[object Error]",Ks="[object DataView]",Ws="[object Uint8Array]",Gs="[object Uint8ClampedArray]",Js="[object Uint16Array]",Qs="[object Uint32Array]",Xs="[object BigUint64Array]",Ys="[object Int8Array]",ea="[object Int16Array]",ta="[object Int32Array]",na="[object BigInt64Array]",ra="[object Float32Array]",ia="[object Float64Array]";function ot(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function st(t){return t==="__proto__"}function Ee(t,e){const n=Object.keys(e);for(let r=0;r<n.length;r++){const i=n[r];if(st(i))continue;const o=e[i],s=t[i];Array.isArray(o)?Array.isArray(s)?t[i]=Ee(s,o):t[i]=Ee([],o):ot(o)?ot(s)?t[i]=Ee(s,o):t[i]=Ee({},o):(s===void 0||o!==void 0)&&(t[i]=o)}return t}function oa(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function sa(t,e,n){return Re(t,e,void 0,void 0,void 0,void 0,n)}function Re(t,e,n,r,i,o,s){const a=s(t,e,n,r,i,o);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Oe(t,e,o,s)}return Oe(t,e,o,s)}function Oe(t,e,n,r){if(Object.is(t,e))return!0;let i=Yn(t),o=Yn(e);if(i===er&&(i=Vt),o===er&&(o=Vt),i!==o)return!1;switch(i){case Vs:return t.toString()===e.toString();case Ns:{const c=t.valueOf(),u=e.valueOf();return oa(c,u)}case Ls:case Us:case js:return Object.is(t.valueOf(),e.valueOf());case xs:return t.source===e.source&&t.flags===e.flags;case Fs:return t===e}n=n??new Map;const s=n.get(t),a=n.get(e);if(s!=null&&a!=null)return s===e;n.set(t,e),n.set(e,t);try{switch(i){case Zs:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!Re(u,e.get(c),c,t,e,n,r))return!1;return!0}case Bs:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let d=0;d<c.length;d++){const m=c[d],_=u.findIndex(S=>Re(m,S,void 0,t,e,n,r));if(_===-1)return!1;u.splice(_,1)}return!0}case Ds:case Ws:case Gs:case Js:case Qs:case Xs:case Ys:case ea:case ta:case na:case ra:case ia:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!Re(t[c],e[c],c,t,e,n,r))return!1;return!0}case qs:return t.byteLength!==e.byteLength?!1:Oe(new Uint8Array(t),new Uint8Array(e),n,r);case Ks:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Oe(new Uint8Array(t),new Uint8Array(e),n,r);case Hs:return t.name===e.name&&t.message===e.message;case Vt:{if(!(Oe(t.constructor,e.constructor,n,r)||ot(t)&&ot(e)))return!1;const u=[...Object.keys(t),...Xn(t)],d=[...Object.keys(e),...Xn(e)];if(u.length!==d.length)return!1;for(let m=0;m<u.length;m++){const _=u[m],S=t[_];if(!Object.hasOwn(e,_))return!1;const b=e[_];if(!Re(S,b,_,t,e,n,r))return!1}return!0}default:return!1}}finally{n.delete(t),n.delete(e)}}function Nt(t,e){return sa(t,e,Ms)}const Me=h({campaign:f(Pn),locale:f(l()),location:f(zt),page:f(me),screen:f(Tt),userAgent:f(l())}),aa=g(Me,{componentId:l(),experienceId:f(l()),variantIndex:f(A()),sticky:f(D())}),ca=g(Me,{traits:f(kt),userId:l()}),ua=g(Me,{properties:f(qi(me))}),la=g(Me,{name:l(),properties:tt}),da=g(Me,{event:l(),properties:f(H(tt,{}))}),tr={path:"",query:{},referrer:"",search:"",title:"",url:""};class fa{app;channel;library;getLocale;getPageProperties;getUserAgent;constructor(e){const{app:n,channel:r,library:i,getLocale:o,getPageProperties:s,getUserAgent:a}=e;this.app=n,this.channel=r,this.library=i,this.getLocale=o??(()=>"en-US"),this.getPageProperties=s??(()=>tr),this.getUserAgent=a??(()=>{})}buildUniversalEventProperties({campaign:e={},locale:n,location:r,page:i,screen:o,userAgent:s}){const a=new Date().toISOString();return{channel:this.channel,context:{app:this.app,campaign:e,gdpr:{isConsentGiven:!0},library:this.library,locale:n??this.getLocale()??"en-US",location:r,page:i??this.getPageProperties(),screen:o,userAgent:s??this.getUserAgent()},messageId:crypto.randomUUID(),originalTimestamp:a,sentAt:a,timestamp:a}}buildComponentView(e){const{componentId:n,experienceId:r,variantIndex:i,...o}=aa.parse(e);return{...this.buildUniversalEventProperties(o),type:"component",componentType:"Entry",componentId:n,experienceId:r,variantIndex:i??0}}buildFlagView(e){return{...this.buildComponentView(e),componentType:"Variable"}}buildIdentify(e){const{traits:n={},userId:r,...i}=ca.parse(e);return{...this.buildUniversalEventProperties(i),type:"identify",traits:n,userId:r}}buildPageView(e={}){const{properties:n={},...r}=ua.parse(e),i=this.getPageProperties(),o=Ee({...i,title:i.title??tr.title},n),{context:{screen:s,...a},...c}=this.buildUniversalEventProperties(r),u=Vn.parse(a);return{...c,context:u,type:"page",properties:o}}buildScreenView(e){const{name:n,properties:r,...i}=la.parse(e),{context:{page:o,...s},...a}=this.buildUniversalEventProperties(i),c=Ln.parse(s);return{...a,context:c,type:"screen",name:n,properties:r}}buildTrack(e){const{event:n,properties:r={},...i}=da.parse(e);return{...this.buildUniversalEventProperties(i),type:"track",event:n,properties:r}}}function pa(t){switch(typeof t){case"number":case"symbol":return!1;case"string":return t.includes(".")||t.includes("[")||t.includes("]")}}function ha(t){return typeof t=="string"||typeof t=="symbol"?t:Object.is(t?.valueOf?.(),-0)?"-0":String(t)}function ga(t){const e=[],n=t.length;if(n===0)return e;let r=0,i="",o="",s=!1;for(t.charCodeAt(0)===46&&(e.push(""),r++);r<n;){const a=t[r];o?a==="\\"&&r+1<n?(r++,i+=t[r]):a===o?o="":i+=a:s?a==='"'||a==="'"?o=a:a==="]"?(s=!1,e.push(i),i=""):i+=a:a==="["?(s=!0,i&&(e.push(i),i="")):a==="."?i&&(e.push(i),i=""):i+=a,r++}return i&&e.push(i),e}function Lt(t,e,n){if(t==null)return n;switch(typeof e){case"string":{if(st(e))return n;const r=t[e];return r===void 0?pa(e)?Lt(t,ga(e),n):n:r}case"number":case"symbol":{typeof e=="number"&&(e=ha(e));const r=t[e];return r===void 0?n:r}default:{if(Array.isArray(e))return va(t,e,n);if(Object.is(e?.valueOf(),-0)?e="-0":e=String(e),st(e))return n;const r=t[e];return r===void 0?n:r}}}function va(t,e,n){if(e.length===0)return n;let r=t;for(let i=0;i<e.length;i++){if(r==null||st(e[i]))return n;r=r[e[i]]}return r===void 0?n:r}const nr=R("Personalization"),rr="Could not resolve Merge Tag value:",xe={isMergeTagEntry(t){return yo.safeParse(t).success},normalizeSelectors(t){return t.split("_").map((e,n,r)=>{const i=r.slice(0,n).join("."),o=r.slice(n).join("_");return[i,o].filter(s=>s!=="").join(".")})},getValueFromProfile(t,e){const r=xe.normalizeSelectors(t).find(o=>Lt(e,o));if(!r)return;const i=Lt(e,r);if(!(!i||typeof i!="string"&&typeof i!="number"&&typeof i!="boolean"))return`${i}`},resolve(t,e){if(!xe.isMergeTagEntry(t)){nr.warn(`${rr} supplied entry is not a Merge Tag entry`);return}const{fields:{nt_fallback:n}}=t;return nt.safeParse(e).success?xe.getValueFromProfile(t.fields.nt_mergetag_id,e)??n:(nr.warn(`${rr} no valid profile`),n)}},Y=R("Personalization"),Ve="Could not resolve personalized entry variant:",Se={getPersonalizationEntry({personalizedEntry:t,selectedPersonalizations:e},n=!1){return!n&&(!e.length||!St(t))?void 0:t.fields.nt_experiences.filter(i=>et(i)).find(i=>e.some(({experienceId:o})=>o===i.fields.nt_experience_id))},getSelectedPersonalization({personalizationEntry:t,selectedPersonalizations:e},n=!1){return!n&&(!e.length||!et(t))?void 0:e.find(({experienceId:i})=>i===t.fields.nt_experience_id)},getSelectedVariant({personalizedEntry:t,personalizationEntry:e,selectedVariantIndex:n},r=!1){if(!r&&(!St(t)||!et(e)))return;const i=e.fields.nt_config?.components?.filter(o=>_o(o)&&!o.baseline.hidden).find(o=>o.baseline.id===t.sys.id)?.variants;if(i?.length)return i.at(n-1)},getSelectedVariantEntry({personalizationEntry:t,selectedVariant:e},n=!1){if(!n&&(!et(t)||!mo(e)))return;const r=t.fields.nt_variants?.find(i=>i.sys.id===e.id);return ho(r)?r:void 0},resolve(t,e){if(Y.debug(`Resolving personalized entry for baseline entry ${t.sys.id}`),!e?.length)return Y.warn(`${Ve} no selectedPersonalizations exist for the current profile`),{entry:t};if(!St(t))return Y.warn(`${Ve} entry ${t.sys.id} is not personalized`),{entry:t};const n=Se.getPersonalizationEntry({personalizedEntry:t,selectedPersonalizations:e},!0);if(!n)return Y.warn(`${Ve} could not find a personalization entry for ${t.sys.id}`),{entry:t};const r=Se.getSelectedPersonalization({personalizationEntry:n,selectedPersonalizations:e},!0),i=r?.variantIndex??0;if(i===0)return Y.debug(`Resolved personalization entry for entry ${t.sys.id} is baseline`),{entry:t};const o=Se.getSelectedVariant({personalizedEntry:t,personalizationEntry:n,selectedVariantIndex:i},!0);if(!o)return Y.warn(`${Ve} could not find a valid replacement variant entry for ${t.sys.id}`),{entry:t};const s=Se.getSelectedVariantEntry({personalizationEntry:n,selectedVariant:o},!0);if(s)Y.debug(`Entry ${t.sys.id} has been resolved to variant entry ${s.sys.id}`);else return Y.warn(`${Ve} could not find a valid replacement variant entry for ${t.sys.id}`),{entry:t};return{entry:s,personalization:r}}},ee=fe(),j=fe(),W=fe(),jt=Or(()=>ht.resolve(ee.value??[])),Ne=fe(!0),F=fe(),k=fe();function U(t){return{subscribe(e){return{unsubscribe:V(()=>{e(t.value)})}}}}const Le={changes:ee,consent:j,event:W,flags:jt,online:Ne,personalizations:F,profile:k},at=t=>typeof t=="function",ya=t=>typeof t=="string"?t:typeof t=="symbol"?t.description??String(t):String(t),ma=t=>typeof t=="string"||typeof t=="symbol",ba=t=>Object.prototype.toString.call(t)==="[object AsyncFunction]";function q(t,e){return function(n,r){const i=ya(r.name);r.addInitializer(function(){const s=Reflect.get(this,r.name);if(!at(s))return;const a=s,c=ba(a),u=b=>{const{[t]:B}=b;if(!at(B))throw new TypeError(`@guardedBy expects predicate "${String(t)}" to be a synchronous function.`);return B},d=(b,B)=>{const x=!!u(b).call(b,i,B);return e?.invert===!0?!x:x},m=(b,B)=>{const{onBlocked:P}=e??{};if(P!==void 0){if(at(P)){P.call(b,i,B);return}if(ma(P)){const{[P]:x}=b;at(x)&&x.call(b,i,B)}}},_=()=>c?Promise.resolve(void 0):void 0,S=function(...b){return d(this,b)?a.call(this,...b):(m(this,b),_())};Reflect.set(this,r.name,S)})}}class _a{#e;constructor(e){const n=new Map;e&&Object.entries(e).map(([r,i])=>n.set(r.length?r:void 0,new Set(i))),this.#e=n}isPresent(e,n){return this.#e.get(e)?.has(n)??!1}addValue(e,n){const r=this.#e.get(e);r?r.add(n):this.#e.set(e,new Set([n]))}removeValue(e,n){this.#e.get(e)?.delete(n)}reset(e){e!==void 0?this.#e.get(e)?.clear():this.#e.clear()}}const wa=["page","identify"];class ir{allowedEventTypes;builder;api;duplicationDetector;interceptors;constructor(e){const{api:n,builder:r,config:i,interceptors:o}=e;this.allowedEventTypes=i?.allowedEventTypes??wa,this.api=n,this.builder=r,this.duplicationDetector=new _a(i?.preventedComponentEvents),this.interceptors=o}}class Ea extends ir{}var Sa=Object.create,or=Object.defineProperty,za=Object.getOwnPropertyDescriptor,sr=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),ar=t=>{throw TypeError(t)},cr=(t,e,n)=>e in t?or(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ta=t=>[,,,Sa(t?.[sr("metadata")]??null)],ur=["class","method","getter","setter","accessor","field","value","get","set"],lr=t=>t!==void 0&&typeof t!="function"?ar("Function expected"):t,ka=(t,e,n,r,i)=>({kind:ur[t],name:e,metadata:r,addInitializer:o=>n._?ar("Already initialized"):i.push(lr(o||null))}),Aa=(t,e)=>cr(e,sr("metadata"),t[3]),$a=(t,e,n,r)=>{for(var i=0,o=t[e>>1],s=o&&o.length;i<s;i++)o[i].call(n);return r},dr=(t,e,n,r,i,o)=>{for(var s,a,c,u,d=e&7,m=!1,_=!1,S=2,b=ur[d+5],B=t[S]||(t[S]=[]),P=(i=i.prototype,za(i,n)),x=r.length-1;x>=0;x--)c=ka(d,n,a={},t[3],B),c.static=m,c.private=_,u=c.access={has:de=>n in de},u.get=de=>de[n],s=(0,r[x])(P[b],c),a._=1,lr(s)&&(P[b]=s);return P&&or(i,n,P),i},fr=(t,e,n)=>cr(t,typeof e!="symbol"?e+"":e,n),pr,hr,Ut,je;const G=R("Analytics"),Pa=25;class ct extends(Ut=Ea,hr=[q("isNotDuplicated",{onBlocked:"onBlockedByDuplication"}),q("hasConsent",{onBlocked:"onBlockedByConsent"})],pr=[q("isNotDuplicated",{onBlocked:"onBlockedByDuplication"}),q("hasConsent",{onBlocked:"onBlockedByConsent"})],Ut){constructor(e){const{api:n,builder:r,config:i,interceptors:o}=e;super({api:n,builder:r,config:i,interceptors:o}),$a(je,5,this),fr(this,"queue",new Map),fr(this,"states",{eventStream:U(W),profile:U(k)});const{defaults:s}=i??{};if(s?.profile!==void 0){const{profile:a}=s;k.value=a}V(()=>{const a=k.value?.id;G.info(`Analytics ${j.value?"will":"will not"} be collected due to consent (${j.value})`),G.debug(`Profile ${a&&`with ID ${a}`} has been ${a?"set":"cleared"}`)}),V(()=>{Ne.value&&this.flush()})}reset(){Te(()=>{W.value=void 0,k.value=void 0})}hasConsent(e){return!!j.value||(this.allowedEventTypes??[]).includes(e==="trackComponentView"||e==="trackFlagView"?"component":e)}onBlockedByConsent(e,n){G.warn(`Event "${e}" was blocked due to lack of consent; payload: ${JSON.stringify(n)}`)}isNotDuplicated(e,n){const[{componentId:r},i]=n,o=this.duplicationDetector.isPresent(i,r);return o||this.duplicationDetector.addValue(i,r),!o}onBlockedByDuplication(e,n){const r=e==="trackFlagView"?"flag":"component";G.debug(`Duplicate "${r} view" event detected, skipping; payload: ${JSON.stringify(n)}`)}async trackComponentView(e,n=""){G.info(`Processing "component view" event for ${e.componentId}`),await this.enqueueEvent(this.builder.buildComponentView(e))}async trackFlagView(e,n=""){G.debug(`Processing "flag view" event for ${e.componentId}`),await this.enqueueEvent(this.builder.buildFlagView(e))}async enqueueEvent(e){const{value:n}=k;if(!n){G.warn("Attempting to emit an event without an Optimization profile");return}const r=await this.interceptors.event.run(e),i=Dn.parse(r);G.debug(`Queueing ${i.type} event for profile ${n.id}`,i);const o=this.queue.get(n);W.value=i,o?o.push(i):this.queue.set(n,[i]),await this.flushMaxEvents()}async flushMaxEvents(){this.queue.values().toArray().flat().length>=Pa&&await this.flush()}async flush(){G.debug("Flushing event queue");const e=[];if(this.queue.forEach((r,i)=>e.push({profile:i,events:r})),!e.length)return;await this.api.insights.sendBatchEvents(e)&&this.queue.clear()}}je=Ta(Ut),dr(je,1,"trackComponentView",hr,ct),dr(je,1,"trackFlagView",pr,ct),Aa(je,ct);const Ia="0.1.0-alpha",ut="ctfl-opt-aid";class gr{interceptors=new Map;nextId=0;add(e){const{nextId:n}=this;return this.nextId+=1,this.interceptors.set(n,e),n}remove(e){return this.interceptors.delete(e)}clear(){this.interceptors.clear()}count(){return this.interceptors.size}async run(e){const n=Array.from(this.interceptors.values());let r=e;for(const i of n)r=await i(r);return r}}class Ca{api;eventBuilder;config;interceptors={event:new gr,state:new gr};constructor(e){this.config=e;const{analytics:n,personalization:r,eventBuilder:i,logLevel:o,environment:s,clientId:a}=e;se.addSink(new os(o));const c={...n,...r,clientId:a,environment:s};this.api=new Os(c),this.eventBuilder=new fa(i??{channel:"server",library:{name:"Optimization Core",version:Ia}})}getCustomFlag(e,n){return this.personalization.getCustomFlag(e,n)}personalizeEntry(e,n){return this.personalization.personalizeEntry(e,n)}getMergeTagValue(e,n){return this.personalization.getMergeTagValue(e,n)}async identify(e){return await this.personalization.identify(e)}async page(e){return await this.personalization.page(e)}async screen(e){return await this.personalization.screen(e)}async track(e){return await this.personalization.track(e)}async trackComponentView(e,n){if(e.sticky)return await this.personalization.trackComponentView(e,n);await this.analytics.trackComponentView(e,n)}async trackFlagView(e,n){await this.analytics.trackFlagView(e,n)}}class Ra extends ir{flagsResolver=ht;mergeTagValueResolver=xe;personalizedEntryResolver=Se;getCustomFlag(e,n){return ht.resolve(n)[e]}personalizeEntry(e,n){return Se.resolve(e,n)}getMergeTagValue(e,n){return xe.resolve(e,n)}}var Oa=Object.create,vr=Object.defineProperty,Ma=Object.getOwnPropertyDescriptor,yr=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),mr=t=>{throw TypeError(t)},br=(t,e,n)=>e in t?vr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,xa=t=>[,,,Oa(t?.[yr("metadata")]??null)],_r=["class","method","getter","setter","accessor","field","value","get","set"],wr=t=>t!==void 0&&typeof t!="function"?mr("Function expected"):t,Va=(t,e,n,r,i)=>({kind:_r[t],name:e,metadata:r,addInitializer:o=>n._?mr("Already initialized"):i.push(wr(o||null))}),Na=(t,e)=>br(e,yr("metadata"),t[3]),La=(t,e,n,r)=>{for(var i=0,o=t[e>>1],s=o&&o.length;i<s;i++)o[i].call(n);return r},Ue=(t,e,n,r,i,o)=>{for(var s,a,c,u,d=e&7,m=!1,_=!1,S=2,b=_r[d+5],B=t[S]||(t[S]=[]),P=(i=i.prototype,Ma(i,n)),x=r.length-1;x>=0;x--)c=Va(d,n,a={},t[3],B),c.static=m,c.private=_,u=c.access={has:de=>n in de},u.get=de=>de[n],s=(0,r[x])(P[b],c),a._=1,wr(s)&&(P[b]=s);return P&&vr(i,n,P),i},Zt=(t,e,n)=>br(t,typeof e!="symbol"?e+"":e,n),Er,Sr,zr,Tr,kr,Bt,te;const O=R("Personalization");class ae extends(Bt=Ra,kr=[q("hasConsent",{onBlocked:"onBlockedByConsent"})],Tr=[q("hasConsent",{onBlocked:"onBlockedByConsent"})],zr=[q("hasConsent",{onBlocked:"onBlockedByConsent"})],Sr=[q("hasConsent",{onBlocked:"onBlockedByConsent"})],Er=[q("isNotDuplicated",{onBlocked:"onBlockedByDuplication"}),q("hasConsent",{onBlocked:"onBlockedByConsent"})],Bt){constructor(e){const{api:n,builder:r,config:i,interceptors:o}=e;super({api:n,builder:r,config:i,interceptors:o}),La(te,5,this),Zt(this,"offlineQueue",new Set),Zt(this,"states",{eventStream:U(W),flags:U(jt),profile:U(k),personalizations:U(F)}),Zt(this,"getAnonymousId");const{defaults:s,getAnonymousId:a}=i??{};if(s){const{changes:c,personalizations:u,profile:d}=s;Te(()=>{ee.value=c,F.value=u,k.value=d})}if(s?.consent!==void 0){const{consent:c}=s;j.value=c}this.getAnonymousId=a??(()=>{}),V(()=>{O.debug(`Profile ${k.value&&`with ID ${k.value.id}`} has been ${k.value?"set":"cleared"}`)}),V(()=>{O.debug(`Variants have been ${F.value?.length?"populated":"cleared"}`)}),V(()=>{O.info(`Personalization ${j.value?"will":"will not"} take effect due to consent (${j.value})`)}),V(()=>{Ne.value&&this.flush()})}reset(){Te(()=>{ee.value=void 0,W.value=void 0,k.value=void 0,F.value=void 0})}getCustomFlag(e,n=ee.value){return super.getCustomFlag(e,n)}personalizeEntry(e,n=F.value){return super.personalizeEntry(e,n)}getMergeTagValue(e,n=k.value){return super.getMergeTagValue(e,n)}hasConsent(e){return!!j.value||(this.allowedEventTypes??[]).includes(e==="trackComponentView"||e==="trackFlagView"?"component":e)}onBlockedByConsent(e,n){O.warn(`Event "${e}" was blocked due to lack of consent; payload: ${JSON.stringify(n)}`)}isNotDuplicated(e,n){const[{componentId:r},i]=n,o=this.duplicationDetector.isPresent(i,r);return o||this.duplicationDetector.addValue(i,r),!o}onBlockedByDuplication(e,n){O.debug(`Duplicate "component view" event detected, skipping; payload: ${JSON.stringify(n)}`)}async identify(e){O.info('Sending "identify" event');const n=this.builder.buildIdentify(e);return await this.sendOrEnqueueEvent(n)}async page(e){O.info('Sending "page" event');const n=this.builder.buildPageView(e);return await this.sendOrEnqueueEvent(n)}async screen(e){O.info(`Sending "screen" event for "${e.name}"`);const n=this.builder.buildScreenView(e);return await this.sendOrEnqueueEvent(n)}async track(e){O.info(`Sending "track" event "${e.event}"`);const n=this.builder.buildTrack(e);return await this.sendOrEnqueueEvent(n)}async trackComponentView(e,n=""){O.info(`Sending "track personalization" event for ${e.componentId}`);const r=this.builder.buildComponentView(e);return await this.sendOrEnqueueEvent(r)}async sendOrEnqueueEvent(e){const n=await this.interceptors.event.run(e),r=Zn.parse(n);if(W.value=r,Ne.value)return await this.upsertProfile([r]);O.debug(`Queueing ${r.type} event`,r),this.offlineQueue.add(r)}async flush(){this.offlineQueue.size!==0&&(O.debug("Flushing offline event queue"),await this.upsertProfile(Array.from(this.offlineQueue)),this.offlineQueue.clear())}async upsertProfile(e){const n=this.getAnonymousId();n&&O.debug(`Anonymous ID found: ${n}`);const r=await this.api.experience.upsertProfile({profileId:n??k.value?.id,events:e});return await this.updateOutputSignals(r),r}async updateOutputSignals(e){const n=await this.interceptors.state.run(e),{changes:r,personalizations:i,profile:o}=n;Te(()=>{Nt(ee.value,r)||(ee.value=r),Nt(k.value,o)||(k.value=o),Nt(F.value,i)||(F.value=i)})}}te=xa(Bt),Ue(te,1,"identify",kr,ae),Ue(te,1,"page",Tr,ae),Ue(te,1,"screen",zr,ae),Ue(te,1,"track",Sr,ae),Ue(te,1,"trackComponentView",Er,ae),Na(te,ae);class ja extends Ca{analytics;personalization;constructor(e){super(e);const{allowedEventTypes:n,defaults:r,getAnonymousId:i,preventedComponentEvents:o}=e;if(r?.consent!==void 0){const{consent:s}=r;j.value=s}this.analytics=new ct({api:this.api,builder:this.eventBuilder,config:{allowedEventTypes:n,preventedComponentEvents:o,defaults:{consent:r?.consent,profile:r?.profile}},interceptors:this.interceptors}),this.personalization=new ae({api:this.api,builder:this.eventBuilder,config:{allowedEventTypes:n,getAnonymousId:i,preventedComponentEvents:o,defaults:{consent:r?.consent,changes:r?.changes,profile:r?.profile,personalizations:r?.personalizations}},interceptors:this.interceptors})}get states(){return{consent:U(j),eventStream:U(W),flags:U(jt),personalizations:U(F),profile:U(k)}}reset(){Te(()=>{W.value=void 0,ee.value=void 0,k.value=void 0,F.value=void 0})}async flush(){await this.analytics.flush(),await this.personalization.flush()}consent(e){j.value=e}online(e){Ne.value=e}registerPreviewPanel(e){e.signals=Le}}/*! js-cookie v3.0.5 | MIT */function lt(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 Ua={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)}};function Dt(t,e){function n(i,o,s){if(!(typeof document>"u")){s=lt({},e,s),typeof s.expires=="number"&&(s.expires=new Date(Date.now()+s.expires*864e5)),s.expires&&(s.expires=s.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var c in s)s[c]&&(a+="; "+c,s[c]!==!0&&(a+="="+s[c].split(";")[0]));return document.cookie=i+"="+t.write(o,i)+a}}function r(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var o=document.cookie?document.cookie.split("; "):[],s={},a=0;a<o.length;a++){var c=o[a].split("="),u=c.slice(1).join("=");try{var d=decodeURIComponent(c[0]);if(s[d]=t.read(u,d),i===d)break}catch{}}return i?s[i]:s}}return Object.create({set:n,get:r,remove:function(i,o){n(i,"",lt({},o,{expires:-1}))},withAttributes:function(i){return Dt(this.converter,lt({},this.attributes,i))},withConverter:function(i){return Dt(lt({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var dt=Dt(Ua,{path:"/"});const Ft=R("Web:AutoTracking");function Ze(t){if(!(typeof HTMLElement<"u"&&typeof SVGElement<"u")||!t||t.nodeType!==1||!("dataset"in t)||!t.dataset||typeof t.dataset!="object"||!("ctflEntryId"in t.dataset))return!1;const{dataset:{ctflEntryId:n}}=t;return typeof n=="string"&&n.trim().length>0}function Ar(t){return!t||typeof t!="object"?!1:"entryId"in t&&typeof t.entryId=="string"&&!!t.entryId.trim().length}function Za(t){return(t?.trim().toLowerCase()??"")==="true"}function Ba(t){if(t===void 0||!/^\d+$/.test(t))return;const e=Number(t);return Number.isSafeInteger(e)?e:void 0}const Da=t=>async(e,n)=>{if(!Ar(n.data)&&!Ze(e))return;let r,i,o,s,a;if(Ar(n.data))({data:{duplicationScope:r,entryId:i,personalizationId:o,sticky:s,variantIndex:a}}=n);else if(Ze(e)){({dataset:{ctflDuplicationScope:r,ctflEntryId:i,ctflPersonalizationId:o}}=e);const{dataset:{ctflSticky:c,ctflVariantIndex:u}}=e;s=Za(c),a=Ba(u)}if(!i){Ft.warn("No entry data found in entry view observer callback; please add data attributes or observe with data info");return}await t.trackComponentView({componentId:i,experienceId:o,sticky:s,variantIndex:a},r)};function $r(t){if(Ze(t))return t;const e=t.querySelector("[data-ctfl-entry-id]")??void 0;return Ze(e)?e:void 0}const Fa=(t,e=!1)=>({onRemoved:n=>{n.forEach(r=>{const i=$r(r);!i||!t.getStats(i)||(Ft.info("Auto-unobserving element (remove):",i),t.unobserve(i))})},onAdded:e?n=>{n.forEach(r=>{const i=$r(r);i&&(Ft.info("Auto-observing element (add):",i),t.observe(i))})}:void 0}),qa=R("Web:EventBuilder");function Ha(t){return new URL(t).searchParams.entries().reduce((e,[n,r])=>(e[n]=r,e),{})}function Ka(){const{languages:t,language:e}=navigator;return t[0]??e}function Wa(){try{const t=new URL(window.location.href),{referrer:e,title:n}=document;return{hash:window.location.hash,height:window.innerHeight,path:t.pathname,query:Ha(t),referrer:e,search:t.search,title:n,url:t.toString(),width:window.innerWidth}}catch(t){return t instanceof Error&&qa.error("Failed to get page properties:",t),{path:"",query:{},referrer:"",search:"",title:"",url:""}}}function Ga(){return navigator.userAgent}const Ja="0.1.0-alpha",M=typeof window<"u"&&typeof document<"u"&&typeof document.addEventListener=="function";function Qa(t,e){const n=new Blob([JSON.stringify(e)],{type:"text/plain"});return window.navigator.sendBeacon(t,n)}const Xa=R("Web:Network");function Ya(t){if(!M)return()=>{};const e=i=>{(async()=>{try{await t(i)}catch(o){Xa.error("Error in online state callback:",o)}})()},n=()=>{e(!0)},r=()=>{e(!1)};return window.addEventListener("online",n),window.addEventListener("offline",r),e(typeof navigator.onLine=="boolean"?navigator.onLine:!0),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}const ec=R("Web:Visibility");function tc(t){if(!M)return()=>{};let e=!1;const n=a=>{e||(e=!0,(async()=>{try{await t(a)}catch(c){ec.error("Error handling page visibility change:",c)}})())},r=()=>{e=!1},i=a=>{document.visibilityState==="hidden"?n(a):r()},o=a=>{n(a)},s=()=>{r()};return document.addEventListener("visibilitychange",i),window.addEventListener("pagehide",o),window.addEventListener("pageshow",s),()=>{document.removeEventListener("visibilitychange",i),window.removeEventListener("pagehide",o),window.removeEventListener("pageshow",s)}}const Be=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),De=()=>M?document.visibilityState==="visible":!0,ce={DWELL_MS:1e3,RATIO:.1,MAX_RETRIES:2,BACKOFF_MS:300,MULTIPLIER:2,JITTER_DIVISOR:2,SWEEP_INTERVAL_MS:3e4},nc=t=>t+Math.floor(Math.random()*Math.max(1,Math.floor(t/ce.JITTER_DIVISOR))),N={n:(t,e)=>typeof t=="number"?t:e,clamp01:(t,e)=>Math.min(1,Math.max(0,N.n(t,e))),nonNeg:(t,e)=>Math.max(0,N.n(t,e)),atLeast1:(t,e)=>Math.max(1,N.n(t,e))},ue=t=>{t.fireTimer!==null&&(clearTimeout(t.fireTimer),t.fireTimer=null)},le=t=>{t.retryTimer!==null&&(clearTimeout(t.retryTimer),t.retryTimer=null),t.retryScheduledAt=null},qt=t=>{if(t.ref&&typeof t.ref.deref=="function"){const e=t.ref.deref();if(e)return e}return t.strongRef??null},Pr=100,Ir=250,rc=16,ic=1,oc=M&&typeof MutationObserver<"u",Cr=M&&typeof window.requestIdleCallback=="function",sc=M&&typeof window.cancelIdleCallback=="function";class Z{observer;root;idleTimeoutMs;maxChunk;onChange;onAdded;onRemoved;onError;pendingRecords=[];scheduled=!1;idleHandle=null;disconnected=!1;constructor(e={}){const{root:n,idleTimeoutMs:r=Pr,maxChunk:i=Ir,onChange:o,onAdded:s,onRemoved:a,onError:c}=e;this.root=Z.isNode(n)?n:M?document:null,this.idleTimeoutMs=Z.sanitizeInt(r,Pr,rc),this.maxChunk=Z.sanitizeInt(i,Ir,ic),this.onChange=o,this.onAdded=s,this.onRemoved=a,this.onError=c,oc&&this.root&&(this.observer=new MutationObserver(u=>{for(const d of u)(d.addedNodes.length>0||d.removedNodes.length>0)&&this.pendingRecords.push(d);this.pendingRecords.length>0&&this.scheduleProcess()}),this.observer.observe(this.root,{childList:!0,subtree:!0}))}isActive(){return!!this.observer&&!this.disconnected}disconnect(){this.disconnected||(this.disconnected=!0,this.observer?.disconnect(),this.pendingRecords=[],this.idleHandle!==null&&(Z.cancelIdle(this.idleHandle),this.idleHandle=null),this.scheduled=!1)}flush(){this.isActive()&&(this.idleHandle!==null&&(Z.cancelIdle(this.idleHandle),this.idleHandle=null),!(!this.scheduled&&this.pendingRecords.length===0)&&(this.scheduled=!1,this.processNow()))}scheduleProcess(){if(!this.isActive()||this.scheduled)return;this.scheduled=!0;const e=()=>{this.idleHandle=null,this.scheduled=!1,this.processNow()};this.idleHandle=Cr?window.requestIdleCallback(e,{timeout:this.idleTimeoutMs}):window.setTimeout(e,this.idleTimeoutMs)}processNow(){if(!this.isActive()||this.pendingRecords.length===0)return;const e=this.drainPending(),{addedNodes:n,removedNodes:r}=Z.coalesce(e),{added:i,removed:o}=Z.toElementSets(n,r);i.size===0&&o.size===0||(this.deliverAggregate(i,o,e),this.deliverPerKind(o,i))}static isNode(e){return M&&typeof Node<"u"&&e instanceof Node}static sanitizeInt(e,n,r){if(typeof e!="number"||!Number.isFinite(e))return n;const i=Math.trunc(e);return i>=r?i:r}static coalesce(e){const n=new Set,r=new Set;for(const i of e){for(const o of i.addedNodes)r.delete(o)||n.add(o);for(const o of i.removedNodes)n.delete(o)||r.add(o)}return{addedNodes:n,removedNodes:r}}static toElementSets(e,n){const r=Z.flattenElements(e,!0),i=Z.flattenElements(n,!1);return{added:r,removed:i}}static flattenElements(e,n){const r=new Set;for(const i of e){if(i instanceof Element){(!n||i.isConnected)&&r.add(i),i.querySelectorAll("*").forEach(o=>{(!n||o.isConnected)&&r.add(o)});continue}i instanceof DocumentFragment&&i.querySelectorAll("*").forEach(o=>{(!n||o.isConnected)&&r.add(o)})}return r}static cancelIdle(e){sc?window.cancelIdleCallback(e):M&&window.clearTimeout(e)}drainPending(){const{pendingRecords:e}=this;return this.pendingRecords=[],e}deliverAggregate(e,n,r){if(!this.onChange)return;const i={added:e,removed:n,records:r};this.safeCall(()=>this.onChange?.(i))}deliverPerKind(e,n){const r=e.size>0?[...e]:[],i=n.size>0?[...n]:[];this.onRemoved&&r.length>0&&this.dispatchChunked(r,this.onRemoved),this.onAdded&&i.length>0&&this.dispatchChunked(i,this.onAdded)}dispatchChunked(e,n){if(!this.isActive()||e.length===0)return;if(e.length<=this.maxChunk){this.safeCall(()=>n(e));return}let r=0;const i=()=>{if(!this.isActive())return;const o=Math.min(e.length,r+this.maxChunk),s=e.slice(r,o);r=o,this.safeCall(()=>n(s)),r<e.length&&(Cr?window.requestIdleCallback(i,{timeout:this.idleTimeoutMs}):M&&window.setTimeout(i,this.idleTimeoutMs))};i()}safeCall(e){try{const n=e();Promise.resolve(n).catch(r=>{this.onError?.(r)})}catch(n){this.onError?.(n)}}}class Fe{callback;opts;io;states=new WeakMap;activeStates=new Set;boundVisibilityHandler=null;sweepInterval=null;constructor(e,n){this.callback=e,this.opts=Fe.initOptions(n),this.io=new IntersectionObserver(r=>{this.onIntersect(r)},{root:this.opts.root??null,rootMargin:this.opts.rootMargin,threshold:this.opts.minVisibleRatio===0?[0]:[0,this.opts.minVisibleRatio]}),M&&(this.boundVisibilityHandler=()=>{this.onPageVisibilityChange()},document.addEventListener("visibilitychange",this.boundVisibilityHandler))}observe(e,n){let r=this.states.get(e);r||(r=this.createState(e,n),this.states.set(e,r),this.activeStates.add(r),this.ensureSweeper()),this.io.observe(e)}unobserve(e){this.io.unobserve(e);const n=this.states.get(e);n&&(ue(n),le(n),n.done=!0,this.activeStates.delete(n),n.strongRef===e&&(n.strongRef=null),this.states.delete(e),this.maybeStopSweeper())}disconnect(){this.io.disconnect();for(const e of this.activeStates)ue(e),le(e),e.done=!0,e.strongRef=null;this.activeStates.clear(),M&&this.boundVisibilityHandler&&(document.removeEventListener("visibilitychange",this.boundVisibilityHandler),this.boundVisibilityHandler=null),this.stopSweeper()}getStats(e){const n=this.states.get(e);return n?{accumulatedMs:n.accumulatedMs,visibleSince:n.visibleSince,attempts:n.attempts,done:n.done,inFlight:n.inFlight,pendingRetry:n.pendingRetry,lastKnownVisible:n.lastKnownVisible}:null}static initOptions(e){return{dwellTimeMs:N.nonNeg(e?.dwellTimeMs,ce.DWELL_MS),minVisibleRatio:N.clamp01(e?.minVisibleRatio,ce.RATIO),root:e?.root??null,rootMargin:e?.rootMargin??"0px",maxRetries:N.nonNeg(e?.maxRetries,ce.MAX_RETRIES),retryBackoffMs:N.nonNeg(e?.retryBackoffMs,ce.BACKOFF_MS),backoffMultiplier:N.atLeast1(e?.backoffMultiplier,ce.MULTIPLIER)}}createState(e,n){const r={dwellTimeMs:N.nonNeg(n?.dwellTimeMs,this.opts.dwellTimeMs),maxRetries:N.nonNeg(n?.maxRetries,this.opts.maxRetries),retryBackoffMs:N.nonNeg(n?.retryBackoffMs,this.opts.retryBackoffMs),backoffMultiplier:N.atLeast1(n?.backoffMultiplier,this.opts.backoffMultiplier)},i=typeof WeakRef=="function";return{ref:i?new WeakRef(e):null,strongRef:i?null:e,opts:r,data:n?.data,accumulatedMs:0,visibleSince:null,fireTimer:null,retryTimer:null,retryScheduledAt:null,retryDelayMs:null,pendingRetry:!1,attempts:0,done:!1,inFlight:!1,lastKnownVisible:!1}}onPageVisibilityChange(){const e=Be(),n=!De();for(const r of this.activeStates)n?Fe.onHidden(r,e):this.onResume(r,e);this.sweepOrphans()}static onHidden(e,n){if(!e.done&&(e.visibleSince!==null&&(e.accumulatedMs+=n-e.visibleSince,e.visibleSince=null),ue(e),e.retryTimer!==null)){const r=e.retryScheduledAt?n-e.retryScheduledAt:0,i=e.retryDelayMs!==null?Math.max(0,e.retryDelayMs-r):null;le(e),i!==null&&(e.pendingRetry=!0,e.retryDelayMs=i,e.retryScheduledAt=null)}}onResume(e,n){e.done||(e.lastKnownVisible&&e.visibleSince===null&&(e.visibleSince=n,this.scheduleFireIfDue(e,n)),e.pendingRetry&&!e.inFlight&&e.lastKnownVisible&&e.retryDelayMs!==null&&this.scheduleRetry(e,e.retryDelayMs))}onIntersect(e){const n=Be();for(const r of e){const i=this.states.get(r.target);if(!i||i.done)continue;r.isIntersecting&&r.intersectionRatio>=this.opts.minVisibleRatio&&De()?this.onVisible(i,n):Fe.onNotVisible(i,n)}this.sweepOrphans()}onVisible(e,n){if(e.lastKnownVisible=!0,e.visibleSince===null){e.visibleSince=n,e.attempts=0,e.pendingRetry&&!e.inFlight&&e.retryDelayMs!==null?this.scheduleRetry(e,e.retryDelayMs):this.scheduleFireIfDue(e,n);return}!e.pendingRetry&&e.fireTimer===null&&!e.inFlight&&this.scheduleFireIfDue(e,n)}static onNotVisible(e,n){e.lastKnownVisible=!1,e.visibleSince!==null&&(e.accumulatedMs+=n-e.visibleSince,e.visibleSince=null),ue(e),(e.pendingRetry||e.retryTimer!==null)&&(le(e),e.pendingRetry=!1,e.attempts=0)}scheduleFireIfDue(e,n){if(e.done||e.inFlight||e.fireTimer!==null||e.pendingRetry)return;const r=e.accumulatedMs+(e.visibleSince!==null?n-e.visibleSince:0),i=e.opts.dwellTimeMs-r;if(i<=0){this.trigger(e);return}e.fireTimer=setTimeout(()=>{!e.done&&e.lastKnownVisible&&De()?this.trigger(e):ue(e)},Math.ceil(i))}scheduleRetry(e,n){e.pendingRetry=!0,e.retryDelayMs=Math.max(0,Math.ceil(n)),!(!De()||!e.lastKnownVisible||e.done||e.inFlight)&&(e.retryScheduledAt=Be(),e.retryTimer=setTimeout(()=>{e.retryTimer=null,e.retryScheduledAt=null,this.attemptCallback(e)},e.retryDelayMs))}trigger(e){if(e.done||e.inFlight)return;const n=Be(),r=e.accumulatedMs+(e.visibleSince!==null?n-e.visibleSince:0);le(e),e.pendingRetry=!1,ue(e),this.attemptCallback(e,r)}async attemptCallback(e,n){if(e.done||e.inFlight)return;const r=qt(e);if(!r){this.finalizeDroppedState(e);return}const i=e.attempts+1;e.attempts=i,e.inFlight=!0;const o=n??e.accumulatedMs+(e.visibleSince!==null?Be()-e.visibleSince:0);try{await this.callback(r,{totalVisibleMs:o,attempts:i,data:e.data}),this.onAttemptSuccess(e,r)}catch{this.onAttemptFailure(e)}}onAttemptSuccess(e,n){e.inFlight=!1,e.done=!0,this.safeAutoUnobserve(n,e)}onAttemptFailure(e){if(e.inFlight=!1,e.attempts>e.opts.maxRetries){this.onRetriesExceeded(e);return}const n=e.opts.retryBackoffMs*Math.pow(e.opts.backoffMultiplier,e.attempts-1),r=nc(n);if(!e.lastKnownVisible||!De()){e.pendingRetry=!0,e.retryDelayMs=Math.ceil(r),e.retryScheduledAt=null;return}this.scheduleRetry(e,r)}onRetriesExceeded(e){le(e),e.pendingRetry=!1,e.done=!0;const n=qt(e);n?this.safeAutoUnobserve(n,e):this.finalizeDroppedState(e)}finalizeDroppedState(e){ue(e),le(e),e.done=!0,this.activeStates.delete(e),e.strongRef&&(this.states.delete(e.strongRef),e.strongRef=null),this.maybeStopSweeper()}safeAutoUnobserve(e,n){try{this.unobserve(e)}catch{this.activeStates.delete(n),n.strongRef===e&&(this.states.delete(e),n.strongRef=null),n.done=!0,this.maybeStopSweeper()}}ensureSweeper(){this.sweepInterval===null&&(this.sweepInterval=setInterval(()=>{this.sweepOrphans()},ce.SWEEP_INTERVAL_MS))}stopSweeper(){this.sweepInterval!==null&&(clearInterval(this.sweepInterval),this.sweepInterval=null)}maybeStopSweeper(){this.activeStates.size===0&&this.stopSweeper()}sweepOrphans(){if(M){for(const e of Array.from(this.activeStates)){const n=qt(e);if(!n){this.finalizeDroppedState(e);continue}(typeof n.isConnected=="boolean"?n.isConnected:document.contains(n))||this.safeAutoUnobserve(n,e)}this.maybeStopSweeper()}}}const Ht="__ctfl_opt_anonymous_id__",Kt="__ctfl_opt_consent__",Wt="__ctfl_opt_changes__",Gt="__ctfl_opt_debug__",Jt="__ctfl_opt_profile__",Qt="__ctfl_opt_personalizations__",E={reset(t={resetConsent:!1,resetDebug:!1}){t.resetConsent&&localStorage.removeItem(Kt),t.resetDebug&&localStorage.removeItem(Gt),localStorage.removeItem(Ht),localStorage.removeItem(Wt),localStorage.removeItem(Jt),localStorage.removeItem(Qt)},get anonymousId(){return localStorage.getItem(Ht)??void 0},set anonymousId(t){E.setCache(Ht,t)},get consent(){switch(localStorage.getItem(Kt)){case"accepted":return!0;case"denied":return!1}},set consent(t){const e=t?"accepted":"denied";E.setCache(Kt,t===void 0?void 0:e)},get debug(){const t=localStorage.getItem(Gt);return t?t==="true":void 0},set debug(t){E.setCache(Gt,t)},get changes(){return E.getCache(Wt,Rn)},set changes(t){E.setCache(Wt,t)},get profile(){return E.getCache(Jt,nt)},set profile(t){E.setCache(Jt,t)},get personalizations(){return E.getCache(Qt,Bn)},set personalizations(t){E.setCache(Qt,t)},getCache(t,e){const n=localStorage.getItem(t);if(!n)return;const r=e.safeParse(JSON.parse(n));if(r.success)return r.data},setCache(t,e){e===void 0?localStorage.removeItem(t):localStorage.setItem(t,typeof e=="string"?e:JSON.stringify(e))}},Xt=R("Web:SDK"),ac=365;function cc({app:t,defaults:e,logLevel:n,...r}){const{consent:i=E.consent,profile:o=E.profile,changes:s=E.changes,personalizations:a=E.personalizations}=e??{};return Ee({analytics:{beaconHandler:Qa},defaults:{consent:i,changes:s,profile:o,personalizations:a},eventBuilder:{app:t,channel:"web",library:{name:"Optimization Web API",version:Ja},getLocale:Ka,getPageProperties:Wa,getUserAgent:Ga},getAnonymousId:()=>E.anonymousId,logLevel:E.debug?"debug":n},r)}class Rr extends ja{elementViewObserver=void 0;elementExistenceObserver=void 0;autoTrackEntryViews=!1;cookieAttributes=void 0;constructor(e){if(typeof window<"u"&&window.optimization)throw new Error("Optimization is already initialized");const{autoTrackEntryViews:n,...r}=e,i=cc(r);super(i);const o=dt.get(ut);this.cookieAttributes={domain:i.cookie?.domain,expires:i.cookie?.expires??ac},this.autoTrackEntryViews=!0,Ya(s=>{this.online(s)}),tc(async()=>{await this.flush()}),V(()=>{const{changes:{value:s}}=Le;E.changes=s}),V(()=>{const{consent:{value:s}}=Le;this.autoTrackEntryViews&&(s?this.startAutoTrackingEntryViews():this.stopAutoTrackingEntryViews()),E.consent=s}),V(()=>{const{profile:{value:s}}=Le;E.profile=s,this.setAnonymousId(s?.id)}),V(()=>{const{personalizations:{value:s}}=Le;E.personalizations=s}),o&&o!==E.anonymousId&&(this.reset(),this.setAnonymousId(o)),typeof window<"u"&&(window.optimization??=this)}setAnonymousId(e){if(!e){dt.remove(ut),E.anonymousId=void 0;return}dt.set(ut,e,this.cookieAttributes),E.anonymousId=e}startAutoTrackingEntryViews(e){this.autoTrackEntryViews=!0,this.elementViewObserver=new Fe(Da(this)),this.elementExistenceObserver=new Z(Fa(this.elementViewObserver,!0)),document.querySelectorAll("[data-ctfl-entry-id]").forEach(r=>{Ze(r)&&(Xt.info("Auto-observing element (init):",r),this.elementViewObserver?.observe(r,{...e}))})}stopAutoTrackingEntryViews(){this.elementExistenceObserver?.disconnect(),this.elementViewObserver?.disconnect()}trackEntryViewForElement(e,n){Xt.info("Manually observing element:",e),this.elementViewObserver?.observe(e,n)}untrackEntryViewForElement(e){Xt.info("Manually unobserving element:",e),this.elementViewObserver?.unobserve(e)}reset(){this.stopAutoTrackingEntryViews(),dt.remove(ut),E.reset(),super.reset()}}return typeof window<"u"&&(window.Optimization??=Rr),Rr});
2
+ //# sourceMappingURL=contentful-optimization-web.umd.cjs.map