@syntrologie/runtime-sdk 2.8.0-canary.64 → 2.8.0-canary.65

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.
@@ -165,7 +165,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
165
165
  s.textContent = '.${e} { ${a} }';
166
166
  document.head.appendChild(s);
167
167
  document.documentElement.className += ' ${e}';
168
- })();`}function Zf(t,e,a="first-match"){for(let r of e){let n=t.getFeatureValue?.(r,null);if(!n||typeof n!="object")continue;let o=n,i=o.tiles&&o.tiles.length>0,s=o.actions&&o.actions.length>0;if(i||s)return{tiles:o.tiles??[],actions:o.actions??[],fetchedAt:o.fetchedAt??new Date().toISOString(),...o.schemaVersion&&{schemaVersion:o.schemaVersion},...o.configVersion&&{configVersion:o.configVersion},...o.canvasTitle&&{canvasTitle:o.canvasTitle},...o.theme&&{theme:o.theme},...o.launcher&&{launcher:o.launcher},...o.meta&&{meta:o.meta}}}return null}var ty=!1;function N1(){if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("syntro_debug")==="true"}catch{return!1}}function ay(t){if(N1()){ty=!0;return}ty=t??!1}function iP(){return N1()?!0:ty}function K(t,e,a){iP()&&(a!==void 0?console.log(`[${t}]`,e,a):console.log(`[${t}]`,e))}function na(t,e,a){a!==void 0?console.warn(`[${t}]`,e,a):console.warn(`[${t}]`,e)}function Xf(t,e,a){a!==void 0?console.error(`[${t}]`,e,a):console.error(`[${t}]`,e)}var ry="2.8.0-canary.64";var eo="2.0";var sP=["api.syntrologie.com","cdn.syntrologie.com","localhost","127.0.0.1"];function lP(t){try{let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(console.warn("[SmartCanvas] Config URI must use HTTPS:",t),!1):sP.some(n=>e.hostname===n)?!0:(console.warn("[SmartCanvas] Config URI host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid config URI:",t),!1}}function uP(t){if(typeof window>"u")return!1;try{return new URL(t).origin===window.location.origin}catch{return!1}}var F1="syntro_config_cache",cP=1440*60*1e3;function H1(){try{return typeof localStorage<"u"&&localStorage!==null}catch{return!1}}function dP(t,e){if(H1())try{let a={config:t,timestamp:Date.now(),sdkVersion:e};localStorage.setItem(F1,JSON.stringify(a))}catch{}}function fP(t){if(!H1())return null;try{let e=localStorage.getItem(F1);if(!e)return null;let a=JSON.parse(e);return!a.config||typeof a.timestamp!="number"||!a.sdkVersion||a.sdkVersion!==t||Date.now()-a.timestamp>cP?null:a.config}catch{return null}}var ny=({configUri:t,experiments:e,featureKey:a})=>{if(t)return t;if(e&&a){let r=e.getFeatureValue?.(a,null);if(r)return r}};function pP(t,e,a){if(e){let r=t.getFeatureValue?.(e,null);if(r&&typeof r=="object"){let n=r.variant_flags;if(n&&n.length>0)return n}}if(t.getAllFeatures){let r=t.getAllFeatures();return a?Object.keys(r).filter(n=>n.startsWith(a)):Object.keys(r)}return[]}var Cs=({configUri:t,experiments:e,featureKey:a,credentials:r,configFeatureKey:n,manifestKey:o,variantFlagPrefix:i,sdkVersion:s})=>async()=>{if(e&&n){let c=e.getFeatureValue?.(n,null);if(c&&typeof c=="object")return K("SmartCanvas Config","Resolved config directly from feature flag",c),c}if(e&&(o||i||e.getAllFeatures)){let c=pP(e,o,i);if(c.length>0){let d=Zf(e,c);if(d)return K("SmartCanvas Config","Resolved config from variant flags",d),d}}let l=ny({configUri:t,experiments:e,featureKey:a});if(!l)return K("SmartCanvas Config","No config available \u2014 returning empty config"),{tiles:[],actions:[],fetchedAt:new Date().toISOString()};if(!lP(l))throw new Error(`SmartCanvas: config URI not allowed: ${l}`);let u=r??(uP(l)?"include":"omit");try{let c=await fetch(l,{credentials:u,headers:{"X-SDK-Version":ry,"X-SDK-Schema-Version":eo}});if(!c.ok)throw new Error(`SmartCanvas: failed to fetch config (${c.status})`);let d=await c.json();return K("SmartCanvas Config","Fetched config from URI",d),s&&dP(d,s),d}catch(c){if(s){let d=fP(s);if(d)return K("SmartCanvas Config","Serving config from offline cache"),d}throw c}};var hP=["cdn.syntrologie.com","api.syntrologie.com","dev-api.syntrologie.com","localhost","127.0.0.1",".syntrologie.com"];function U1(t){if(typeof window>"u")return null;let a=new URLSearchParams(window.location.search).get(t);if(!a)return null;try{let r=a.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(r))}catch(r){return na("Syntro Runtime",`Failed to decode ${t}:`,r),null}}var ws,Ls;function Su(){if(ws==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.token)ws={token:t.token,api_base:t.apiBase||""},console.log(`[DIAG] getEditorSource: from __SYNTRO_EDITOR_PARAMS__ (token=${ws.token.slice(0,15)}...)`);else{let e=U1("editor_source");e&&(ws=e),console.log(`[DIAG] getEditorSource: from URL param \u2192 ${e?`token=${e.token?.slice(0,15)}...`:"NULL"}`),!e&&typeof window<"u"&&console.log(`[DIAG] getEditorSource: URL search = ${window.location.search.slice(0,200)}`)}}return ws??null}function Kf(){if(Ls==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.mode)Ls={mode:t.mode,audit_session_id:t.auditSessionId,syntro_token:t.syntroToken,workspace_id:t.workspaceId},console.log(`[DIAG] getEditorConf: from __SYNTRO_EDITOR_PARAMS__ (mode=${Ls.mode})`);else{let e=U1("editor_conf");e&&(Ls=e),console.log(`[DIAG] getEditorConf: from URL param \u2192 ${e?`mode=${e.mode}`:"NULL"}`)}}return Ls??null}function mP(t){K("Syntro Runtime","Validating editor URL:",t);try{if(t.startsWith("/"))return K("Syntro Runtime","\u2713 Relative URL allowed (same-origin):",t),!0;let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(na("Syntro Runtime","\u274C Editor URL must use HTTPS:",t),!1):hP.some(n=>n.startsWith(".")?e.hostname.endsWith(n)||e.hostname===n.slice(1):e.hostname===n)?(K("Syntro Runtime","\u2713 Editor URL validated"),!0):(na("Syntro Runtime","\u274C Editor URL host not in allowlist:",e.hostname),!1)}catch(e){return na("Syntro Runtime",`\u274C Invalid editor URL: ${t}`,e),!1}}var Yf=()=>{let t=Kf();return!Su()?.token||!t?.mode?null:t.mode};function gP(){return Su()?.token??null}function vP(){return Su()?.api_base??null}var bu=null,z1=async t=>{if(K("Syntro Runtime","====== LOAD EDITOR SDK ======"),typeof window>"u"){K("Syntro Runtime","Not in browser - skipping editor SDK load");return}if(window.SyntroEditor){K("Syntro Runtime","Editor SDK already loaded (window.SyntroEditor exists)");return}if(bu)return K("Syntro Runtime","Editor SDK load already in progress, waiting..."),bu;let e=typeof t=="string"?{editorUrl:t}:t??{};if(e.editorUrl==="skip"){K("Syntro Runtime",'editorUrl="skip" \u2014 deferring to caller'),K("Syntro Runtime","================================");return}let a=vP(),n=(a?`${a}/api/editor/sdk/editor-sdk.js`:null)||e.editorUrl;if(!n){na("Syntro Runtime","\u274C No editor SDK URL available (no api_base, no editorUrl option)"),K("Syntro Runtime","================================");return}let o=gP();if(!o){na("Syntro Runtime","\u274C No token found in editor_source."),K("Syntro Runtime","================================");return}let i=`${n}?token=${encodeURIComponent(o)}`;if(K("Syntro Runtime","Editor URL:",i),K("Syntro Runtime","Options:",{hasIntegrity:!!e.integrity,hasEditorUrl:!!n,hasApiBase:!!a,tokenPrefix:`${o.slice(0,10)}...`}),!mP(n)){console.error("[Syntro Runtime] \u274C BLOCKED: Editor from untrusted URL:",n),K("Syntro Runtime","================================");return}return K("Syntro Runtime","\u2713 URL validated, injecting script tag..."),bu=new Promise((s,l)=>{let u=document.createElement("script");u.src=i,u.async=!0,e.integrity&&(u.integrity=e.integrity,u.crossOrigin="anonymous",K("Syntro Runtime","SRI integrity check enabled")),u.onload=()=>{K("Syntro Runtime","\u2713 Editor SDK script loaded successfully"),K("Syntro Runtime","================================"),s()},u.onerror=c=>{console.error("[Syntro Runtime] \u274C Failed to load Editor SDK:",c),console.error("[Syntro Runtime] URL attempted:",i),K("Syntro Runtime","================================"),bu=null,l(c)},document.head.appendChild(u),K("Syntro Runtime","Script tag appended to <head>")}),bu};var yP=new Set(["tag_name","$el_text"]);function xP(t){return yP.has(t)||t.startsWith("attr__")}function q1(t,e){return t.equals!==void 0?e===t.equals:t.contains!==void 0?typeof e=="string"&&e.includes(t.contains):!1}function bP(t){let{events:e,match:a}=t;return r=>{if(!e.includes(r.name))return!1;if(a){for(let[n,o]of Object.entries(a))if(xP(n)){let i=r.props?.elements;if(!i||!i.some(l=>q1(o,l[n])))return!1}else if(!q1(o,r.props?.[n]))return!1}return!0}}function V1(t,e){for(let a of t.rules)for(let r of a.conditions)if(r.type==="event_count"&&r.key){let n=r.counter,o=n?bP(n):()=>!0,i=typeof r.withinMs=="number";e.register(r.key,o,i)}}function Qf(t,e,a){for(let r of t){let n=r.props;if(!n)continue;let o=n.actions;if(o)for(let i of o)i.triggerWhen?.type==="rules"&&V1(i.triggerWhen,e)}if(a)for(let r of a){let n=r;n.triggerWhen?.type==="rules"&&V1(n.triggerWhen,e)}}var Sr=null;function j1(t){Sr&&Sr!==t?t.appendChild(Sr):Sr=t;let e=t.getRootNode();e instanceof ShadowRoot&&SP(e)}function G1(){return Sr||(Sr=document.createElement("div"),Sr.id="syntro-overlays",Object.assign(Sr.style,{position:"fixed",inset:"0",zIndex:"2147483645",pointerEvents:"none"}),document.body.appendChild(Sr)),Sr}var $1=!1;function SP(t){if($1)return;let e=`
168
+ })();`}function Zf(t,e,a="first-match"){for(let r of e){let n=t.getFeatureValue?.(r,null);if(!n||typeof n!="object")continue;let o=n,i=o.tiles&&o.tiles.length>0,s=o.actions&&o.actions.length>0;if(i||s)return{tiles:o.tiles??[],actions:o.actions??[],fetchedAt:o.fetchedAt??new Date().toISOString(),...o.schemaVersion&&{schemaVersion:o.schemaVersion},...o.configVersion&&{configVersion:o.configVersion},...o.canvasTitle&&{canvasTitle:o.canvasTitle},...o.theme&&{theme:o.theme},...o.launcher&&{launcher:o.launcher},...o.meta&&{meta:o.meta}}}return null}var ty=!1;function N1(){if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("syntro_debug")==="true"}catch{return!1}}function ay(t){if(N1()){ty=!0;return}ty=t??!1}function iP(){return N1()?!0:ty}function K(t,e,a){iP()&&(a!==void 0?console.log(`[${t}]`,e,a):console.log(`[${t}]`,e))}function na(t,e,a){a!==void 0?console.warn(`[${t}]`,e,a):console.warn(`[${t}]`,e)}function Xf(t,e,a){a!==void 0?console.error(`[${t}]`,e,a):console.error(`[${t}]`,e)}var ry="2.8.0-canary.65";var eo="2.0";var sP=["api.syntrologie.com","cdn.syntrologie.com","localhost","127.0.0.1"];function lP(t){try{let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(console.warn("[SmartCanvas] Config URI must use HTTPS:",t),!1):sP.some(n=>e.hostname===n)?!0:(console.warn("[SmartCanvas] Config URI host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid config URI:",t),!1}}function uP(t){if(typeof window>"u")return!1;try{return new URL(t).origin===window.location.origin}catch{return!1}}var F1="syntro_config_cache",cP=1440*60*1e3;function H1(){try{return typeof localStorage<"u"&&localStorage!==null}catch{return!1}}function dP(t,e){if(H1())try{let a={config:t,timestamp:Date.now(),sdkVersion:e};localStorage.setItem(F1,JSON.stringify(a))}catch{}}function fP(t){if(!H1())return null;try{let e=localStorage.getItem(F1);if(!e)return null;let a=JSON.parse(e);return!a.config||typeof a.timestamp!="number"||!a.sdkVersion||a.sdkVersion!==t||Date.now()-a.timestamp>cP?null:a.config}catch{return null}}var ny=({configUri:t,experiments:e,featureKey:a})=>{if(t)return t;if(e&&a){let r=e.getFeatureValue?.(a,null);if(r)return r}};function pP(t,e,a){if(e){let r=t.getFeatureValue?.(e,null);if(r&&typeof r=="object"){let n=r.variant_flags;if(n&&n.length>0)return n}}if(t.getAllFeatures){let r=t.getAllFeatures();return a?Object.keys(r).filter(n=>n.startsWith(a)):Object.keys(r)}return[]}var Cs=({configUri:t,experiments:e,featureKey:a,credentials:r,configFeatureKey:n,manifestKey:o,variantFlagPrefix:i,sdkVersion:s})=>async()=>{if(e&&n){let c=e.getFeatureValue?.(n,null);if(c&&typeof c=="object")return K("SmartCanvas Config","Resolved config directly from feature flag",c),c}if(e&&(o||i||e.getAllFeatures)){let c=pP(e,o,i);if(c.length>0){let d=Zf(e,c);if(d)return K("SmartCanvas Config","Resolved config from variant flags",d),d}}let l=ny({configUri:t,experiments:e,featureKey:a});if(!l)return K("SmartCanvas Config","No config available \u2014 returning empty config"),{tiles:[],actions:[],fetchedAt:new Date().toISOString()};if(!lP(l))throw new Error(`SmartCanvas: config URI not allowed: ${l}`);let u=r??(uP(l)?"include":"omit");try{let c=await fetch(l,{credentials:u,headers:{"X-SDK-Version":ry,"X-SDK-Schema-Version":eo}});if(!c.ok)throw new Error(`SmartCanvas: failed to fetch config (${c.status})`);let d=await c.json();return K("SmartCanvas Config","Fetched config from URI",d),s&&dP(d,s),d}catch(c){if(s){let d=fP(s);if(d)return K("SmartCanvas Config","Serving config from offline cache"),d}throw c}};var hP=["cdn.syntrologie.com","api.syntrologie.com","dev-api.syntrologie.com","localhost","127.0.0.1",".syntrologie.com"];function U1(t){if(typeof window>"u")return null;let a=new URLSearchParams(window.location.search).get(t);if(!a)return null;try{let r=a.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(r))}catch(r){return na("Syntro Runtime",`Failed to decode ${t}:`,r),null}}var ws,Ls;function Su(){if(ws==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.token)ws={token:t.token,api_base:t.apiBase||""},console.log(`[DIAG] getEditorSource: from __SYNTRO_EDITOR_PARAMS__ (token=${ws.token.slice(0,15)}...)`);else{let e=U1("editor_source");e&&(ws=e),console.log(`[DIAG] getEditorSource: from URL param \u2192 ${e?`token=${e.token?.slice(0,15)}...`:"NULL"}`),!e&&typeof window<"u"&&console.log(`[DIAG] getEditorSource: URL search = ${window.location.search.slice(0,200)}`)}}return ws??null}function Kf(){if(Ls==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.mode)Ls={mode:t.mode,audit_session_id:t.auditSessionId,syntro_token:t.syntroToken,workspace_id:t.workspaceId},console.log(`[DIAG] getEditorConf: from __SYNTRO_EDITOR_PARAMS__ (mode=${Ls.mode})`);else{let e=U1("editor_conf");e&&(Ls=e),console.log(`[DIAG] getEditorConf: from URL param \u2192 ${e?`mode=${e.mode}`:"NULL"}`)}}return Ls??null}function mP(t){K("Syntro Runtime","Validating editor URL:",t);try{if(t.startsWith("/"))return K("Syntro Runtime","\u2713 Relative URL allowed (same-origin):",t),!0;let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(na("Syntro Runtime","\u274C Editor URL must use HTTPS:",t),!1):hP.some(n=>n.startsWith(".")?e.hostname.endsWith(n)||e.hostname===n.slice(1):e.hostname===n)?(K("Syntro Runtime","\u2713 Editor URL validated"),!0):(na("Syntro Runtime","\u274C Editor URL host not in allowlist:",e.hostname),!1)}catch(e){return na("Syntro Runtime",`\u274C Invalid editor URL: ${t}`,e),!1}}var Yf=()=>{let t=Kf();return!Su()?.token||!t?.mode?null:t.mode};function gP(){return Su()?.token??null}function vP(){return Su()?.api_base??null}var bu=null,z1=async t=>{if(K("Syntro Runtime","====== LOAD EDITOR SDK ======"),typeof window>"u"){K("Syntro Runtime","Not in browser - skipping editor SDK load");return}if(window.SyntroEditor){K("Syntro Runtime","Editor SDK already loaded (window.SyntroEditor exists)");return}if(bu)return K("Syntro Runtime","Editor SDK load already in progress, waiting..."),bu;let e=typeof t=="string"?{editorUrl:t}:t??{};if(e.editorUrl==="skip"){K("Syntro Runtime",'editorUrl="skip" \u2014 deferring to caller'),K("Syntro Runtime","================================");return}let a=vP(),n=(a?`${a}/api/editor/sdk/editor-sdk.js`:null)||e.editorUrl;if(!n){na("Syntro Runtime","\u274C No editor SDK URL available (no api_base, no editorUrl option)"),K("Syntro Runtime","================================");return}let o=gP();if(!o){na("Syntro Runtime","\u274C No token found in editor_source."),K("Syntro Runtime","================================");return}let i=`${n}?token=${encodeURIComponent(o)}`;if(K("Syntro Runtime","Editor URL:",i),K("Syntro Runtime","Options:",{hasIntegrity:!!e.integrity,hasEditorUrl:!!n,hasApiBase:!!a,tokenPrefix:`${o.slice(0,10)}...`}),!mP(n)){console.error("[Syntro Runtime] \u274C BLOCKED: Editor from untrusted URL:",n),K("Syntro Runtime","================================");return}return K("Syntro Runtime","\u2713 URL validated, injecting script tag..."),bu=new Promise((s,l)=>{let u=document.createElement("script");u.src=i,u.async=!0,e.integrity&&(u.integrity=e.integrity,u.crossOrigin="anonymous",K("Syntro Runtime","SRI integrity check enabled")),u.onload=()=>{K("Syntro Runtime","\u2713 Editor SDK script loaded successfully"),K("Syntro Runtime","================================"),s()},u.onerror=c=>{console.error("[Syntro Runtime] \u274C Failed to load Editor SDK:",c),console.error("[Syntro Runtime] URL attempted:",i),K("Syntro Runtime","================================"),bu=null,l(c)},document.head.appendChild(u),K("Syntro Runtime","Script tag appended to <head>")}),bu};var yP=new Set(["tag_name","$el_text"]);function xP(t){return yP.has(t)||t.startsWith("attr__")}function q1(t,e){return t.equals!==void 0?e===t.equals:t.contains!==void 0?typeof e=="string"&&e.includes(t.contains):!1}function bP(t){let{events:e,match:a}=t;return r=>{if(!e.includes(r.name))return!1;if(a){for(let[n,o]of Object.entries(a))if(xP(n)){let i=r.props?.elements;if(!i||!i.some(l=>q1(o,l[n])))return!1}else if(!q1(o,r.props?.[n]))return!1}return!0}}function V1(t,e){for(let a of t.rules)for(let r of a.conditions)if(r.type==="event_count"&&r.key){let n=r.counter,o=n?bP(n):()=>!0,i=typeof r.withinMs=="number";e.register(r.key,o,i)}}function Qf(t,e,a){for(let r of t){let n=r.props;if(!n)continue;let o=n.actions;if(o)for(let i of o)i.triggerWhen?.type==="rules"&&V1(i.triggerWhen,e)}if(a)for(let r of a){let n=r;n.triggerWhen?.type==="rules"&&V1(n.triggerWhen,e)}}var Sr=null;function j1(t){Sr&&Sr!==t?t.appendChild(Sr):Sr=t;let e=t.getRootNode();e instanceof ShadowRoot&&SP(e)}function G1(){return Sr||(Sr=document.createElement("div"),Sr.id="syntro-overlays",Object.assign(Sr.style,{position:"fixed",inset:"0",zIndex:"2147483645",pointerEvents:"none"}),document.body.appendChild(Sr)),Sr}var $1=!1;function SP(t){if($1)return;let e=`
169
169
  :host {
170
170
  --syntro-surface: var(--sc-overlay-background, #0f1318);
171
171
  --syntro-fg: var(--sc-overlay-text-color, #cbd0d7);
@@ -495,12 +495,12 @@ ${l}
495
495
  *, *::before, *::after {
496
496
  box-sizing: border-box;
497
497
  }
498
- `,Ua,oo,io,tn,an,so,rn,Ay=class extends HTMLElement{constructor(){super();Cn(this,Ua);Cn(this,oo);Cn(this,io);Cn(this,tn);Cn(this,an);Cn(this,so,null);Cn(this,rn,null);fr(this,Ua,this.attachShadow({mode:"open",delegatesFocus:!0})),fr(this,oo,document.createElement("div")),ye(this,oo).setAttribute("part","mount"),ye(this,Ua).appendChild(ye(this,oo)),fr(this,io,document.createElement("div")),ye(this,io).id="portalRoot",ye(this,Ua).appendChild(ye(this,io)),fr(this,tn,document.createElement("div")),ye(this,tn).id="overlayContainer",Object.assign(ye(this,tn).style,{position:"fixed",inset:"0",zIndex:"2147483645",pointerEvents:"none"}),ye(this,Ua).appendChild(ye(this,tn)),fr(this,an,W1()),this.applyBaseStyles()}connectedCallback(){this.style.setProperty("font-family","inherit")}disconnectedCallback(){ye(this,so)?.unmount(),fr(this,so,null)}getMountNode(){return ye(this,oo)}getController(){return ye(this,an)}getPortalRoot(){return ye(this,io)}getOverlayContainer(){return ye(this,tn)}getShadowRoot(){return ye(this,Ua)}open(){ye(this,an).setOpen(!0)}close(){ye(this,an).setOpen(!1)}toggle(){ye(this,an).toggle()}setOverrideFetcher(a){ye(this,rn)&&(fr(this,rn,{...ye(this,rn),fetcher:a}),this.render())}mountReactApp(a){fr(this,rn,a),this.render()}render(){!this.isConnected||!ye(this,rn)||(ye(this,so)||fr(this,so,(0,SI.createRoot)(ye(this,oo))),ye(this,so).render((0,Ey.jsx)(X1,{shadowRoot:ye(this,Ua),portalRoot:ye(this,io),overlayContainer:ye(this,tn),children:(0,Ey.jsx)(yI,{...ye(this,rn),controller:ye(this,an),canvasHost:this})})))}applyBaseStyles(){if(ye(this,Ua).adoptedStyleSheets!==void 0){let a=new CSSStyleSheet;a.replaceSync(bI),ye(this,Ua).adoptedStyleSheets=[a]}else{let a=document.createElement("style");a.textContent=bI,ye(this,Ua).appendChild(a)}}};Ua=new WeakMap,oo=new WeakMap,io=new WeakMap,tn=new WeakMap,an=new WeakMap,so=new WeakMap,rn=new WeakMap;var _I=()=>{typeof window>"u"||customElements.get(xI)||customElements.define(xI,Ay)};var Ty=async(t={})=>{if(typeof window>"u"||typeof document>"u")throw new Error("SmartCanvas can only be created in a browser-like environment");let e=null;if(t.antiFlicker){let b=typeof t.antiFlicker=="object"?t.antiFlicker:{};e=P1(b)}let a=null,r=null,n=null,{runtime:o}=t;async function i(b){!o?.actions||b.length===0||(n?.isApplied()&&await n.revertAll(),n=await o.actions.applyBatch(b))}async function s(){n?.isApplied()&&(await n.revertAll(),n=null)}if(t.fetcher)try{r=t.fetcher,console.log("[SmartCanvas] Fetching initial config...");let b=await t.fetcher();a=b,console.log("[SmartCanvas] Config fetched:",`tiles=${b.tiles?.length??0},`,`actions=${b.actions?.length??0},`,`theme=${b.theme?.mode??"default"}`),b.actions?.length&&console.log("[SmartCanvas] Actions to apply:",b.actions.map((g,m)=>`[${m}] ${g.kind}${g.anchorId?` anchor="${g.anchorId.selector}"`:""}${g.label?` "${g.label}"`:""}`).join(", ")),b.actions&&b.actions.length>0&&o?.actions&&(await i(b.actions),console.log("[SmartCanvas] Initial actions applied successfully")),b.tiles&&o?.accumulator&&Qf(b.tiles,o.accumulator,b.actions)}catch(b){console.error("[SmartCanvas] Error fetching/applying initial config:",b)}e&&e();let l=Yf();_I();let u=document.createElement("smart-canvas");if(j1(u.getOverlayContainer()),t.tokens)for(let[b,g]of Object.entries(t.tokens))u.style.setProperty(b,g);let c=()=>{let b=t.target??document.body;b&&b.appendChild(u)};document.body?c():document.addEventListener("DOMContentLoaded",c,{once:!0}),l&&(console.log(`[SmartCanvas] Loading editor SDK for ${l} mode`),z1(t.editorUrl).catch(console.error));let d=t.integrations?.experiments,f=t.integrations?.telemetry,h=t.fetcher??Cs({configUri:t.configUri,experiments:d,featureKey:t.configUriFeatureKey,credentials:t.fetchCredentials});r||(r=h);let S={fetcher:h,pollIntervalMs:t.pollIntervalMs,experiments:d,telemetry:f,runtime:o,overlayFetcher:t.overlayFetcher,overlayConfigUri:t.overlayConfigUri,overlayConfigFeatureKey:t.overlayConfigFeatureKey,overlayFetchCredentials:t.overlayFetchCredentials,configUri:t.configUri,configUriFeatureKey:t.configUriFeatureKey,fetchCredentials:t.fetchCredentials,initialBatchHandle:n,workspaceTheme:t.workspaceTheme};u.mountReactApp(S),t.defaultOpen&&u.open();let x={el:u,open:()=>u.open(),close:()=>u.close(),destroy:()=>{s(),u.remove()},setTokens:b=>{for(let[g,m]of Object.entries(b))u.style.setProperty(g,m)},getConfig:async()=>{if(r)try{let b=await r();return a=b,b}catch(b){console.error("[SmartCanvas] Error fetching config:",b)}return a??{tiles:[],actions:[],fetchedAt:""}},setEnabled:async b=>{b?a&&await i(a.actions):await s()},setOverrideFetcher:b=>{r=b,u.setOverrideFetcher(b),o?.accumulator&&b().then(g=>{g?.tiles&&Qf(g.tiles,o.accumulator,g.actions)}).catch(()=>{})},registerTelemetryProperties:b=>{f?.register?.(b)},getSessionId:()=>f?.getSessionId?.(),startSessionRecording:()=>{f?.startSessionRecording?.()},track:(b,g)=>f?.track?(f.track(b,g),!0):!1,runtime:o};if(typeof window<"u"){let b=window.SynOS;b&&(b.handle=x)}return x};typeof window<"u"&&(window.SmartCanvas={async create(t){return Ty(t)}});var uo=Y(Ye(),1);var lo=Y(Ae(),1);function c$({tiles:t,intervalMs:e=7e3,telemetry:a}){let[r,n]=(0,uo.useState)(0),o=(0,uo.useMemo)(()=>[...t].sort((i,s)=>(i.priority??0)-(s.priority??0)),[t]);return(0,uo.useEffect)(()=>{a?.trackCanvasOpened("wheel")},[a]),(0,uo.useEffect)(()=>{if(o.length<=1)return;let i=setInterval(()=>{n(s=>(s+1)%o.length)},e);return()=>clearInterval(i)},[o,e]),(0,uo.useEffect)(()=>{let i=o[r];i&&a?.trackRectangleViewed(i.id,"wheel")},[r,o,a]),o.length?(0,lo.jsxs)("div",{style:{position:"relative",overflow:"hidden",borderRadius:"1.5rem",border:"var(--sc-tile-border)",background:"var(--sc-tile-background)",padding:"1.5rem",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)"},"data-shadow-canvas-id":"wheel",children:[(0,lo.jsx)("div",{style:{display:"flex",transition:"transform 700ms ease-out",transform:`translateX(-${r*100}%)`,width:`${o.length*100}%`},children:o.map(i=>(0,lo.jsx)("div",{style:{width:"100%",flexShrink:0,padding:"0 1rem"},children:(0,lo.jsx)(Uu,{config:i,surface:"wheel",telemetry:a})},i.id))}),(0,lo.jsx)("div",{style:{marginTop:"1rem",display:"flex",justifyContent:"center",gap:"0.5rem"},children:o.map((i,s)=>(0,lo.jsx)("button",{type:"button",style:{height:"0.5rem",width:"1.5rem",borderRadius:"9999px",background:s===r?"var(--sc-color-primary)":"var(--sc-tile-text-color)",border:"none",cursor:"pointer",padding:0},onClick:()=>n(s)},i.id))})]}):null}function zu(t){let e=t.split(".");return{major:parseInt(e[0]||"0",10),minor:parseInt(e[1]||"0",10)}}function p$(t){let e=[],a=[];if(!t||typeof t!="object")return{valid:!1,errors:["Config must be an object"],warnings:e};let r=t;if(r.tiles||a.push("Config missing required field: tiles"),r.actions||a.push("Config missing required field: actions"),r.fetchedAt||a.push("Config missing required field: fetchedAt"),a.length>0)return{valid:!1,errors:a,warnings:e};let n=r.schemaVersion||"1.0",o=zu(n),i=zu(eo);return o.major>i.major&&e.push(`Config schema v${n} is newer than SDK v${eo}. Some features may not work. Update SDK to latest version.`),o.major<i.major||!r.schemaVersion?(e.push(`Config schema v${n} is older than SDK v${eo}. Migrating config to current version.`),{valid:!0,warnings:e,errors:a,migratedConfig:xN(r,n)}):{valid:!0,warnings:e,errors:a}}function xN(t,e){let a={...t};return zu(e).major===1&&(a=bN(a)),a.schemaVersion=eo,a}function bN(t){let e={schemaVersion:"2.0",tiles:[],actions:t.actions||[],fetchedAt:t.fetchedAt||new Date().toISOString()};return t.tiles&&Array.isArray(t.tiles)&&(e.tiles=t.tiles.map(a=>{let r={...a};return a.experiment&&delete r.experiment,r})),t.configVersion&&(e.configVersion=t.configVersion),t.canvasTitle&&(e.canvasTitle=t.canvasTitle),t.theme&&(e.theme=t.theme),t.launcher&&(e.launcher=t.launcher),e}function h$(t){if(!t||typeof t!="object")return!1;let e=t,a=e.schemaVersion||"1.0",r=zu(a),n=zu(eo);return r.major<n.major||!e.schemaVersion}var wI={fetch:globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,SubtleCrypto:globalThis.crypto?globalThis.crypto.subtle:void 0,EventSource:globalThis.EventSource};function LI(){return wI}function Ry(t){let e=2166136261,a=t.length;for(let r=0;r<a;r++)e^=t.charCodeAt(r),e+=(e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24);return e>>>0}function qu(t,e,a){return a===2?Ry(Ry(t+e)+"")%1e4/1e4:a===1?Ry(e+t)%1e3/1e3:null}function SN(t){return t<=0?[]:new Array(t).fill(1/t)}function fp(t,e){return t>=e[0]&&t<e[1]}function kI(t,e){let a=qu("__"+e[0],t,1);return a===null?!1:a>=e[1]&&a<e[2]}function II(t,e){for(let a=0;a<e.length;a++)if(fp(t,e[a]))return a;return-1}function Oy(t){try{let e=t.replace(/([^\\])\//g,"$1\\/");return new RegExp(e)}catch(e){console.error(e);return}}function pp(t,e){if(!e.length)return!1;let a=!1,r=!1;for(let n=0;n<e.length;n++){let o=wN(t,e[n].type,e[n].pattern);if(e[n].include===!1){if(o)return!1}else a=!0,o&&(r=!0)}return r||!a}function _N(t,e,a){try{let r=e.replace(/[*.+?^${}()|[\]\\]/g,"\\$&").replace(/_____/g,".*");return a&&(r="\\/?"+r.replace(/(^\/|\/$)/g,"")+"\\/?"),new RegExp("^"+r+"$","i").test(t)}catch{return!1}}function CN(t,e){try{let a=new URL(e.replace(/^([^:/?]*)\./i,"https://$1.").replace(/\*/g,"_____"),"https://_____"),r=[[t.host,a.host,!1],[t.pathname,a.pathname,!0]];return a.hash&&r.push([t.hash,a.hash,!1]),a.searchParams.forEach((n,o)=>{r.push([t.searchParams.get(o)||"",n,!1])}),!r.some(n=>!_N(n[0],n[1],n[2]))}catch{return!1}}function wN(t,e,a){try{let r=new URL(t,"https://_");if(e==="regex"){let n=Oy(a);return n?n.test(r.href)||n.test(r.href.substring(r.origin.length)):!1}else if(e==="simple")return CN(r,a);return!1}catch{return!1}}function AI(t,e,a){e=e===void 0?1:e,e<0?e=0:e>1&&(e=1);let r=SN(t);a=a||r,a.length!==t&&(a=r);let n=a.reduce((i,s)=>s+i,0);(n<.99||n>1.01)&&(a=r);let o=0;return a.map(i=>{let s=o;return o+=i,[s,s+e*i]})}function EI(t,e,a){if(!e)return null;let r=e.split("?")[1];if(!r)return null;let n=r.replace(/#.*/,"").split("&").map(o=>o.split("=",2)).filter(([o])=>o===t).map(([,o])=>parseInt(o));return n.length>0&&n[0]>=0&&n[0]<a?n[0]:null}function TI(t){try{return t()}catch(e){return console.error(e),!1}}var My=t=>Uint8Array.from(atob(t),e=>e.charCodeAt(0));async function ni(t,e,a){if(e=e||"",a=a||globalThis.crypto&&globalThis.crypto.subtle||wI.SubtleCrypto,!a)throw new Error("No SubtleCrypto implementation found");try{let r=await a.importKey("raw",My(e),{name:"AES-CBC",length:128},!0,["encrypt","decrypt"]),[n,o]=t.split("."),i=await a.decrypt({name:"AES-CBC",iv:My(n)},r,My(o));return new TextDecoder().decode(i)}catch{throw new Error("Failed to decrypt")}}function Vu(t){return typeof t=="string"?t:JSON.stringify(t)}function wa(t){typeof t=="number"&&(t=t+""),(!t||typeof t!="string")&&(t="0");let e=t.replace(/(^v|\+.*$)/g,"").split(/[-.]/);return e.length===3&&e.push("~"),e.map(a=>a.match(/^[0-9]+$/)?a.padStart(5," "):a).join("-")}function RI(){let t;try{t="1.6.4"}catch{t=""}return t}function MI(t,e){let a,r;try{a=new URL(t),r=new URL(e)}catch(n){return console.error(`Unable to merge query strings: ${n}`),e}return a.searchParams.forEach((n,o)=>{r.searchParams.has(o)||r.searchParams.set(o,n)}),r.toString()}function CI(t){return typeof t=="object"&&t!==null}function hp(t){return t.urlPatterns&&t.variations.some(e=>CI(e)&&"urlRedirect"in e)?"redirect":t.variations.some(e=>CI(e)&&(e.domMutations||"js"in e||"css"in e))?"visual":"unknown"}async function mp(t,e){return new Promise(a=>{let r=!1,n,o=i=>{r||(r=!0,n&&clearTimeout(n),a(i||null))};e&&(n=setTimeout(()=>o(),e)),t.then(i=>o(i)).catch(()=>o())})}var Ft={staleTTL:1e3*60,maxAge:1e3*60*60*4,cacheKey:"gbFeaturesCache",backgroundSync:!0,maxEntries:10,disableIdleStreams:!1,idleStreamInterval:2e4,disableCache:!1},_r=LI(),Es={fetchFeaturesCall:({host:t,clientKey:e,headers:a})=>_r.fetch(`${t}/api/features/${e}`,{headers:a}),fetchRemoteEvalCall:({host:t,clientKey:e,payload:a,headers:r})=>{let n={method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify(a)};return _r.fetch(`${t}/api/eval/${e}`,n)},eventSourceCall:({host:t,clientKey:e,headers:a})=>a?new _r.EventSource(`${t}/sub/${e}`,{headers:a}):new _r.EventSource(`${t}/sub/${e}`),startIdleListener:()=>{let t;if(!(typeof window<"u"&&typeof document<"u"))return;let a=()=>{document.visibilityState==="visible"?(window.clearTimeout(t),IN()):document.visibilityState==="hidden"&&(t=window.setTimeout(kN,Ft.idleStreamInterval))};return document.addEventListener("visibilitychange",a),()=>document.removeEventListener("visibilitychange",a)},stopIdleListener:()=>{}};try{globalThis.localStorage&&(_r.localStorage=globalThis.localStorage)}catch{}var Ts=new Map,OI=!1,nn=new Map,gp=new Map,Rs=new Map,Ms=new Set;function BI(t){Object.assign(Ft,t),Ft.backgroundSync||Hy()}async function PI({instance:t,timeout:e,skipCache:a,allowStale:r,backgroundSync:n}){return n||(Ft.backgroundSync=!1),AN({instance:t,allowStale:r,timeout:e,skipCache:a})}function LN(t){let e=$u(t),a=Ts.get(e)||new Set;a.add(t),Ts.set(e,a)}function NI(t){Ts.forEach(e=>e.delete(t))}function kN(){Rs.forEach(t=>{t&&(t.state="idle",Ny(t))})}function IN(){Rs.forEach(t=>{t&&t.state==="idle"&&Fy(t)})}async function DI(){try{if(!_r.localStorage)return;await _r.localStorage.setItem(Ft.cacheKey,JSON.stringify(Array.from(nn.entries())))}catch{}}async function AN({instance:t,allowStale:e,timeout:a,skipCache:r}){let n=$u(t),o=By(t),i=new Date,s=new Date(i.getTime()-Ft.maxAge+Ft.staleTTL);await EN();let l=!Ft.disableCache&&!r?nn.get(o):void 0;return l&&(e||l.staleAt>i)&&l.staleAt>s?(l.sse&&Ms.add(n),l.staleAt<i?Dy(t):Py(t),{data:l.data,success:!0,source:"cache"}):await mp(Dy(t),a)||{data:null,success:!1,source:"timeout",error:new Error("Timeout")}}function $u(t){let[e,a]=t.getApiInfo();return`${e}||${a}`}function By(t){let e=$u(t);if(!("isRemoteEval"in t)||!t.isRemoteEval())return e;let a=t.getAttributes(),r=t.getCacheKeyAttributes()||Object.keys(t.getAttributes()),n={};r.forEach(s=>{n[s]=a[s]});let o=t.getForcedVariations(),i=t.getUrl();return`${e}||${JSON.stringify({ca:n,fv:o,url:i})}`}async function EN(){if(!OI){OI=!0;try{if(_r.localStorage){let t=await _r.localStorage.getItem(Ft.cacheKey);if(!Ft.disableCache&&t){let e=JSON.parse(t);e&&Array.isArray(e)&&e.forEach(([a,r])=>{nn.set(a,{...r,staleAt:new Date(r.staleAt)})}),FI()}}}catch{}if(!Ft.disableIdleStreams){let t=Es.startIdleListener();t&&(Es.stopIdleListener=t)}}}function FI(){let t=Array.from(nn.entries()).map(([a,r])=>({key:a,staleAt:r.staleAt.getTime()})).sort((a,r)=>a.staleAt-r.staleAt),e=Math.min(Math.max(0,nn.size-Ft.maxEntries),nn.size);for(let a=0;a<e;a++)nn.delete(t[a].key)}function HI(t,e,a){let r=a.dateUpdated||"",n=new Date(Date.now()+Ft.staleTTL),o=Ft.disableCache?void 0:nn.get(e);if(o&&r&&o.version===r){o.staleAt=n,DI();return}Ft.disableCache||(nn.set(e,{data:a,version:r,staleAt:n,sse:Ms.has(t)}),FI()),DI();let i=Ts.get(t);i&&i.forEach(s=>TN(s,a))}async function TN(t,e){await t.setPayload(e||t.getPayload())}async function Dy(t){let{apiHost:e,apiRequestHeaders:a}=t.getApiHosts(),r=t.getClientKey(),n="isRemoteEval"in t&&t.isRemoteEval(),o=$u(t),i=By(t),s=gp.get(i);return s||(s=(n?Es.fetchRemoteEvalCall({host:e,clientKey:r,payload:{attributes:t.getAttributes(),forcedVariations:t.getForcedVariations(),forcedFeatures:Array.from(t.getForcedFeatures().entries()),url:t.getUrl()},headers:a}):Es.fetchFeaturesCall({host:e,clientKey:r,headers:a})).then(u=>{if(!u.ok)throw new Error(`HTTP error: ${u.status}`);return u.headers.get("x-sse-support")==="enabled"&&Ms.add(o),u.json()}).then(u=>(HI(o,i,u),Py(t),gp.delete(i),{data:u,success:!0,source:"network"})).catch(u=>(gp.delete(i),{data:null,source:"error",success:!1,error:u})),gp.set(i,s)),s}function Py(t,e=!1){let a=$u(t),r=By(t),{streamingHost:n,streamingHostRequestHeaders:o}=t.getApiHosts(),i=t.getClientKey();if(e&&Ms.add(a),Ft.backgroundSync&&Ms.has(a)&&_r.EventSource){if(Rs.has(a))return;let s={src:null,host:n,clientKey:i,headers:o,cb:l=>{try{if(l.type==="features-updated"){let u=Ts.get(a);u&&u.forEach(c=>{Dy(c)})}else if(l.type==="features"){let u=JSON.parse(l.data);HI(a,r,u)}s.errors=0}catch{UI(s)}},errors:0,state:"active"};Rs.set(a,s),Fy(s)}}function UI(t){if(t.state!=="idle"&&(t.errors++,t.errors>3||t.src&&t.src.readyState===2)){let e=Math.pow(3,t.errors-3)*(1e3+Math.random()*1e3);Ny(t),setTimeout(()=>{["idle","active"].includes(t.state)||Fy(t)},Math.min(e,3e5))}}function Ny(t){t.src&&(t.src.onopen=null,t.src.onerror=null,t.src.close(),t.src=null,t.state==="active"&&(t.state="disabled"))}function Fy(t){t.src=Es.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=()=>UI(t),t.src.onopen=()=>{t.errors=0}}function RN(t,e){Ny(t),Rs.delete(e)}function Hy(){Ms.clear(),Rs.forEach(RN),Ts.clear(),Es.stopIdleListener()}function vp(t,e){if(e.streaming){if(!t.getClientKey())throw new Error("Must specify clientKey to enable streaming");e.payload&&Py(t,!0),LN(t)}}var MN=/^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/,qy={revert:function(){}},Sp=new Map,Vy=new Set;function ON(t){return t==="html"?{childList:!0,subtree:!0,attributes:!0,characterData:!0}:{childList:!1,subtree:!1,attributes:!0,attributeFilter:[t]}}function _p(t){var e=Sp.get(t);return e||(e={element:t,attributes:{}},Sp.set(t,e)),e}function Cp(t,e,a,r,n){var o=a(t),i={isDirty:!1,originalValue:o,virtualValue:o,mutations:[],el:t,_positionTimeout:null,observer:new MutationObserver(function(){if(!(e==="position"&&i._positionTimeout)){e==="position"&&(i._positionTimeout=setTimeout(function(){i._positionTimeout=null},1e3));var s=a(t);e==="position"&&s.parentNode===i.virtualValue.parentNode&&s.insertBeforeNode===i.virtualValue.insertBeforeNode||s!==i.virtualValue&&(i.originalValue=s,n(i))}}),mutationRunner:n,setValue:r,getCurrentValue:a};return e==="position"&&t.parentNode?i.observer.observe(t.parentNode,{childList:!0,subtree:!0,attributes:!1,characterData:!1}):i.observer.observe(t,ON(e)),i}function wp(t,e){var a=e.getCurrentValue(e.el);e.virtualValue=t,t&&typeof t!="string"?(!a||t.parentNode!==a.parentNode||t.insertBeforeNode!==a.insertBeforeNode)&&(e.isDirty=!0,zI()):t!==a&&(e.isDirty=!0,zI())}function DN(t){var e=t.originalValue;t.mutations.forEach(function(a){return e=a.mutate(e)}),wp(ZN(e),t)}function BN(t){var e=new Set(t.originalValue.split(/\s+/).filter(Boolean));t.mutations.forEach(function(a){return a.mutate(e)}),wp(Array.from(e).filter(Boolean).join(" "),t)}function PN(t){var e=t.originalValue;t.mutations.forEach(function(a){return e=a.mutate(e)}),wp(e,t)}function NN(t){var e=t.parentSelector,a=t.insertBeforeSelector,r=document.querySelector(e);if(!r)return null;var n=a?document.querySelector(a):null;return a&&!n?null:{parentNode:r,insertBeforeNode:n}}function FN(t){var e=t.originalValue;t.mutations.forEach(function(a){var r=a.mutate(),n=NN(r);e=n||e}),wp(e,t)}var HN=function(e){return e.innerHTML},UN=function(e,a){return e.innerHTML=a};function VI(t){var e=_p(t);return e.html||(e.html=Cp(t,"html",HN,UN,DN)),e.html}var zN=function(e){return{parentNode:e.parentElement,insertBeforeNode:e.nextElementSibling}},qN=function(e,a){a.insertBeforeNode&&!a.parentNode.contains(a.insertBeforeNode)||a.parentNode.insertBefore(e,a.insertBeforeNode)};function $I(t){var e=_p(t);return e.position||(e.position=Cp(t,"position",zN,qN,FN)),e.position}var VN=function(e,a){return a?e.className=a:e.removeAttribute("class")},$N=function(e){return e.className};function jI(t){var e=_p(t);return e.classes||(e.classes=Cp(t,"class",$N,VN,BN)),e.classes}var jN=function(e){return function(a){var r;return(r=a.getAttribute(e))!=null?r:null}},GN=function(e){return function(a,r){return r!==null?a.setAttribute(e,r):a.removeAttribute(e)}};function GI(t,e){var a=_p(t);return a.attributes[e]||(a.attributes[e]=Cp(t,e,jN(e),GN(e),PN)),a.attributes[e]}function WN(t,e){var a=Sp.get(t);if(a)if(e==="html"){var r,n;(r=a.html)==null||(n=r.observer)==null||n.disconnect(),delete a.html}else if(e==="class"){var o,i;(o=a.classes)==null||(i=o.observer)==null||i.disconnect(),delete a.classes}else if(e==="position"){var s,l;(s=a.position)==null||(l=s.observer)==null||l.disconnect(),delete a.position}else{var u,c,d;(u=a.attributes)==null||(c=u[e])==null||(d=c.observer)==null||d.disconnect(),delete a.attributes[e]}}var yp;function ZN(t){return yp||(yp=document.createElement("div")),yp.innerHTML=t,yp.innerHTML}function xp(t,e,a){if(a.isDirty){a.isDirty=!1;var r=a.virtualValue;a.mutations.length||WN(t,e),a.setValue(t,r)}}function XN(t,e){t.html&&xp(e,"html",t.html),t.classes&&xp(e,"class",t.classes),t.position&&xp(e,"position",t.position),Object.keys(t.attributes).forEach(function(a){xp(e,a,t.attributes[a])})}function zI(){Sp.forEach(XN)}function KN(t,e){var a=null;t.kind==="html"?a=VI(e):t.kind==="class"?a=jI(e):t.kind==="attribute"?a=GI(e,t.attribute):t.kind==="position"&&(a=$I(e)),a&&(a.mutations.push(t),a.mutationRunner(a))}function YN(t,e){var a=null;if(t.kind==="html"?a=VI(e):t.kind==="class"?a=jI(e):t.kind==="attribute"?a=GI(e,t.attribute):t.kind==="position"&&(a=$I(e)),!!a){var r=a.mutations.indexOf(t);r!==-1&&a.mutations.splice(r,1),a.mutationRunner(a)}}function WI(t){if(!(t.kind==="position"&&t.elements.size===1)){var e=new Set(t.elements),a=document.querySelectorAll(t.selector);a.forEach(function(r){e.has(r)||(t.elements.add(r),KN(t,r))})}}function QN(t){t.elements.forEach(function(e){return YN(t,e)}),t.elements.clear(),Vy.delete(t)}function qI(){Vy.forEach(WI)}var Uy;function JN(){typeof document>"u"||(Uy||(Uy=new MutationObserver(function(){qI()})),qI(),Uy.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}JN();function Lp(t){return typeof document>"u"?qy:(Vy.add(t),WI(t),{revert:function(){QN(t)}})}function zy(t,e){return Lp({kind:"html",elements:new Set,mutate:e,selector:t})}function ZI(t,e){return Lp({kind:"position",elements:new Set,mutate:e,selector:t})}function ju(t,e){return Lp({kind:"class",elements:new Set,mutate:e,selector:t})}function bp(t,e,a){return MN.test(e)?e==="class"||e==="className"?ju(t,function(r){var n=a(Array.from(r).join(" "));r.clear(),n&&n.split(/\s+/g).filter(Boolean).forEach(function(o){return r.add(o)})}):Lp({kind:"attribute",attribute:e,elements:new Set,mutate:a,selector:t}):qy}function eF(t){var e=t.selector,a=t.action,r=t.value,n=t.attribute,o=t.parentSelector,i=t.insertBeforeSelector;if(n==="html"){if(a==="append")return zy(e,function(s){return s+(r??"")});if(a==="set")return zy(e,function(){return r??""})}else if(n==="class"){if(a==="append")return ju(e,function(s){r&&s.add(r)});if(a==="remove")return ju(e,function(s){r&&s.delete(r)});if(a==="set")return ju(e,function(s){s.clear(),r&&s.add(r)})}else if(n==="position"){if(a==="set"&&o)return ZI(e,function(){return{insertBeforeSelector:i,parentSelector:o}})}else{if(a==="append")return bp(e,n,function(s){return s!==null?s+(r??""):r??""});if(a==="set")return bp(e,n,function(){return r??""});if(a==="remove")return bp(e,n,function(){return null})}return qy}var tF={html:zy,classes:ju,attribute:bp,position:ZI,declarative:eF},XI=tF;var $y={};function co(t,e,a){a=a||{};for(let[r,n]of Object.entries(e))switch(r){case"$or":if(!QI(t,n,a))return!1;break;case"$nor":if(QI(t,n,a))return!1;break;case"$and":if(!iF(t,n,a))return!1;break;case"$not":if(co(t,n,a))return!1;break;default:if(!Gu(n,aF(t,r),a))return!1}return!0}function aF(t,e){let a=e.split("."),r=t;for(let n=0;n<a.length;n++)if(r&&typeof r=="object"&&a[n]in r)r=r[a[n]];else return null;return r}function KI(t,e=!1){let a=`${t}${e?"/i":""}`;return $y[a]||($y[a]=new RegExp(t.replace(/([^\\])\//g,"$1\\/"),e?"i":void 0)),$y[a]}function Gu(t,e,a,r=!1){if(typeof t=="string")return r?String(e).toLowerCase()===t.toLowerCase():e+""===t;if(typeof t=="number")return e*1===t;if(typeof t=="boolean")return e!==null&&!!e===t;if(t===null)return e===null;if(Array.isArray(t)||!JI(t))return JSON.stringify(e)===JSON.stringify(t);for(let n in t)if(!oF(n,e,t[n],a))return!1;return!0}function JI(t){let e=Object.keys(t);return e.length>0&&e.filter(a=>a[0]==="$").length===e.length}function rF(t){if(t===null)return"null";if(Array.isArray(t))return"array";let e=typeof t;return["string","number","boolean","object","undefined"].includes(e)?e:"unknown"}function nF(t,e,a){if(!Array.isArray(t))return!1;let r=JI(e)?n=>Gu(e,n,a):n=>co(n,e,a);for(let n=0;n<t.length;n++)if(t[n]&&r(t[n]))return!0;return!1}function Os(t,e,a=!1){if(a){let r=n=>typeof n=="string"?n.toLowerCase():n;return Array.isArray(t)?t.some(n=>e.some(o=>r(n)===r(o))):e.some(n=>r(t)===r(n))}return Array.isArray(t)?t.some(r=>e.includes(r)):e.includes(t)}function YI(t,e,a,r=!1){if(!Array.isArray(t))return!1;for(let n=0;n<e.length;n++){let o=!1;for(let i=0;i<t.length;i++)if(Gu(e[n],t[i],a,r)){o=!0;break}if(!o)return!1}return!0}function oF(t,e,a,r){switch(t){case"$veq":return wa(e)===wa(a);case"$vne":return wa(e)!==wa(a);case"$vgt":return wa(e)>wa(a);case"$vgte":return wa(e)>=wa(a);case"$vlt":return wa(e)<wa(a);case"$vlte":return wa(e)<=wa(a);case"$eq":return e===a;case"$ne":return e!==a;case"$lt":return e<a;case"$lte":return e<=a;case"$gt":return e>a;case"$gte":return e>=a;case"$exists":return a?e!=null:e==null;case"$in":return Array.isArray(a)?Os(e,a):!1;case"$ini":return Array.isArray(a)?Os(e,a,!0):!1;case"$inGroup":return Os(e,r[a]||[]);case"$notInGroup":return!Os(e,r[a]||[]);case"$nin":return Array.isArray(a)?!Os(e,a):!1;case"$nini":return Array.isArray(a)?!Os(e,a,!0):!1;case"$not":return!Gu(a,e,r);case"$size":return Array.isArray(e)?Gu(a,e.length,r):!1;case"$elemMatch":return nF(e,a,r);case"$all":return Array.isArray(a)?YI(e,a,r):!1;case"$alli":return Array.isArray(a)?YI(e,a,r,!0):!1;case"$regex":try{return KI(a).test(e)}catch{return!1}case"$regexi":try{return KI(a,!0).test(e)}catch{return!1}case"$type":return rF(e)===a;default:return console.error("Unknown operator: "+t),!1}}function QI(t,e,a){if(!e.length)return!0;for(let r=0;r<e.length;r++)if(co(t,e[r],a))return!0;return!1}function iF(t,e,a){for(let r=0;r<e.length;r++)if(!co(t,e[r],a))return!1;return!0}var sF="Feature Evaluated",lF="Experiment Viewed";function uF(t){let e=new Map;return t.global.forcedFeatureValues&&t.global.forcedFeatureValues.forEach((a,r)=>e.set(r,a)),t.user.forcedFeatureValues&&t.user.forcedFeatureValues.forEach((a,r)=>e.set(r,a)),e}function cF(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:{}}async function Ds(t){try{await t()}catch{}}function eA(t,e,a){if(t.user.trackedExperiments){let n=Ap(e,a);if(t.user.trackedExperiments.has(n))return[];t.user.trackedExperiments.add(n)}t.user.enableDevMode&&t.user.devLogs&&t.user.devLogs.push({experiment:e,result:a,timestamp:Date.now().toString(),logType:"experiment"});let r=[];if(t.global.trackingCallback){let n=t.global.trackingCallback;r.push(Ds(()=>n(e,a,t.user)))}if(t.user.trackingCallback){let n=t.user.trackingCallback;r.push(Ds(()=>n(e,a)))}if(t.global.eventLogger){let n=t.global.eventLogger;r.push(Ds(()=>n(lF,{experimentId:e.key,variationId:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue},t.user)))}return r}function dF(t,e,a){if(t.user.trackedFeatureUsage){let r=JSON.stringify(a.value);if(t.user.trackedFeatureUsage[e]===r)return;t.user.trackedFeatureUsage[e]=r,t.user.enableDevMode&&t.user.devLogs&&t.user.devLogs.push({featureKey:e,result:a,timestamp:Date.now().toString(),logType:"feature"})}if(t.global.onFeatureUsage){let r=t.global.onFeatureUsage;Ds(()=>r(e,a,t.user))}if(t.user.onFeatureUsage){let r=t.user.onFeatureUsage;Ds(()=>r(e,a))}if(t.global.eventLogger){let r=t.global.eventLogger;Ds(()=>r(sF,{feature:e,source:a.source,value:a.value,ruleId:a.source==="defaultValue"?"$default":a.ruleId||"",variationId:a.experimentResult?a.experimentResult.key:""},t.user))}}function kp(t,e){if(e.stack.evaluatedFeatures.has(t))return fo(e,t,null,"cyclicPrerequisite");e.stack.evaluatedFeatures.add(t),e.stack.id=t;let a=uF(e);if(a.has(t))return fo(e,t,a.get(t),"override");if(!e.global.features||!e.global.features[t])return fo(e,t,null,"unknownFeature");let r=e.global.features[t];if(r.rules){let n=new Set(e.stack.evaluatedFeatures);e:for(let o of r.rules){if(o.parentConditions)for(let l of o.parentConditions){e.stack.evaluatedFeatures=new Set(n);let u=kp(l.id,e);if(u.source==="cyclicPrerequisite")return fo(e,t,null,"cyclicPrerequisite");let c={value:u.value};if(!co(c,l.condition||{})){if(l.gate)return fo(e,t,null,"prerequisite");continue e}}if(o.filters&&rA(o.filters,e))continue;if("force"in o){if(o.condition&&!aA(o.condition,e)||!fF(e,o.seed||t,o.hashAttribute,e.user.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion))continue;return o.tracks&&o.tracks.forEach(l=>{!eA(e,l.experiment,l.result).length&&e.global.saveDeferredTrack&&e.global.saveDeferredTrack({experiment:l.experiment,result:l.result})}),fo(e,t,o.force,"force",o.id)}if(!o.variations)continue;let i={variations:o.variations,key:o.key||t};"coverage"in o&&(i.coverage=o.coverage),o.weights&&(i.weights=o.weights),o.hashAttribute&&(i.hashAttribute=o.hashAttribute),o.fallbackAttribute&&(i.fallbackAttribute=o.fallbackAttribute),o.disableStickyBucketing&&(i.disableStickyBucketing=o.disableStickyBucketing),o.bucketVersion!==void 0&&(i.bucketVersion=o.bucketVersion),o.minBucketVersion!==void 0&&(i.minBucketVersion=o.minBucketVersion),o.namespace&&(i.namespace=o.namespace),o.meta&&(i.meta=o.meta),o.ranges&&(i.ranges=o.ranges),o.name&&(i.name=o.name),o.phase&&(i.phase=o.phase),o.seed&&(i.seed=o.seed),o.hashVersion&&(i.hashVersion=o.hashVersion),o.filters&&(i.filters=o.filters),o.condition&&(i.condition=o.condition);let{result:s}=Ip(i,t,e);if(e.global.onExperimentEval&&e.global.onExperimentEval(i,s),s.inExperiment&&!s.passthrough)return fo(e,t,s.value,"experiment",o.id,i,s)}}return fo(e,t,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function Ip(t,e,a){let r=t.key,n=t.variations.length;if(n<2)return{result:Ze(a,t,-1,!1,e)};if(a.global.enabled===!1||a.user.enabled===!1)return{result:Ze(a,t,-1,!1,e)};if(t=pF(t,a),t.urlPatterns&&!pp(a.user.url||"",t.urlPatterns))return{result:Ze(a,t,-1,!1,e)};let o=EI(r,a.user.url||"",n);if(o!==null)return{result:Ze(a,t,o,!1,e)};let i=cF(a);if(r in i){let b=i[r];return{result:Ze(a,t,b,!1,e)}}if(t.status==="draft"||t.active===!1)return{result:Ze(a,t,-1,!1,e)};let{hashAttribute:s,hashValue:l}=oi(a,t.hashAttribute,a.user.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0);if(!l)return{result:Ze(a,t,-1,!1,e)};let u=-1,c=!1,d=!1;if(a.user.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing){let{variation:b,versionIsBlocked:g}=gF({ctx:a,expKey:t.key,expBucketVersion:t.bucketVersion,expHashAttribute:t.hashAttribute,expFallbackAttribute:t.fallbackAttribute,expMinBucketVersion:t.minBucketVersion,expMeta:t.meta});c=b>=0,u=b,d=!!g}if(!c){if(t.filters){if(rA(t.filters,a))return{result:Ze(a,t,-1,!1,e)}}else if(t.namespace&&!kI(l,t.namespace))return{result:Ze(a,t,-1,!1,e)};if(t.include&&!TI(t.include))return{result:Ze(a,t,-1,!1,e)};if(t.condition&&!aA(t.condition,a))return{result:Ze(a,t,-1,!1,e)};if(t.parentConditions){let b=new Set(a.stack.evaluatedFeatures);for(let g of t.parentConditions){a.stack.evaluatedFeatures=new Set(b);let m=kp(g.id,a);if(m.source==="cyclicPrerequisite")return{result:Ze(a,t,-1,!1,e)};let y={value:m.value};if(!co(y,g.condition||{}))return{result:Ze(a,t,-1,!1,e)}}}if(t.groups&&!mF(t.groups,a))return{result:Ze(a,t,-1,!1,e)}}if(t.url&&!hF(t.url,a))return{result:Ze(a,t,-1,!1,e)};let f=qu(t.seed||r,l,t.hashVersion||1);if(f===null)return{result:Ze(a,t,-1,!1,e)};if(!c){let b=t.ranges||AI(n,t.coverage===void 0?1:t.coverage,t.weights);u=II(f,b)}if(d)return{result:Ze(a,t,-1,!1,e,void 0,!0)};if(u<0)return{result:Ze(a,t,-1,!1,e)};if("force"in t)return{result:Ze(a,t,t.force===void 0?-1:t.force,!1,e)};if(a.global.qaMode||a.user.qaMode)return{result:Ze(a,t,-1,!1,e)};if(t.status==="stopped")return{result:Ze(a,t,-1,!1,e)};let h=Ze(a,t,u,!0,e,f,c);if(a.user.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing){let{changed:b,key:g,doc:m}=yF(a,s,Vu(l),{[jy(t.key,t.bucketVersion)]:h.key});b&&(a.user.stickyBucketAssignmentDocs=a.user.stickyBucketAssignmentDocs||{},a.user.stickyBucketAssignmentDocs[g]=m,a.user.saveStickyBucketAssignmentDoc(m))}let S=eA(a,t,h);S.length===0&&a.global.saveDeferredTrack&&a.global.saveDeferredTrack({experiment:t,result:h});let x=S.length?S.length===1?S[0]:Promise.all(S).then(()=>{}):void 0;return"changeId"in t&&t.changeId&&a.global.recordChangeId&&a.global.recordChangeId(t.changeId),{result:h,trackingCall:x}}function fo(t,e,a,r,n,o,i){let s={value:a,on:!!a,off:!a,source:r,ruleId:n||""};return o&&(s.experiment=o),i&&(s.experimentResult=i),r!=="override"&&dF(t,e,s),s}function tA(t){return{...t.user.attributes,...t.user.attributeOverrides}}function aA(t,e){return co(tA(e),t,e.global.savedGroups||{})}function rA(t,e){return t.some(a=>{let{hashValue:r}=oi(e,a.attribute);if(!r)return!0;let n=qu(a.seed,r,a.hashVersion||2);return n===null?!0:!a.ranges.some(o=>fp(n,o))})}function fF(t,e,a,r,n,o,i){if(!n&&o===void 0)return!0;if(!n&&o===0)return!1;let{hashValue:s}=oi(t,a,r);if(!s)return!1;let l=qu(e,s,i||1);return l===null?!1:n?fp(l,n):o!==void 0?l<=o:!0}function Ze(t,e,a,r,n,o,i){let s=!0;(a<0||a>=e.variations.length)&&(a=0,s=!1);let{hashAttribute:l,hashValue:u}=oi(t,e.hashAttribute,t.user.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0),c=e.meta?e.meta[a]:{},d={key:c.key||""+a,featureId:n,inExperiment:s,hashUsed:r,variationId:a,value:e.variations[a],hashAttribute:l,hashValue:u,stickyBucketUsed:!!i};return c.name&&(d.name=c.name),o!==void 0&&(d.bucket=o),c.passthrough&&(d.passthrough=c.passthrough),d}function pF(t,e){let a=t.key,r=e.global.overrides;return r&&r[a]&&(t=Object.assign({},t,r[a]),typeof t.url=="string"&&(t.url=Oy(t.url))),t}function oi(t,e,a){let r=e||"id",n="",o=tA(t);return o[r]&&(n=o[r]),!n&&a&&(o[a]&&(n=o[a]),n&&(r=a)),{hashAttribute:r,hashValue:n}}function hF(t,e){let a=e.user.url;if(!a)return!1;let r=a.replace(/^https?:\/\//,"").replace(/^[^/]*\//,"/");return!!(t.test(a)||t.test(r))}function mF(t,e){let a=e.global.groups||{};for(let r=0;r<t.length;r++)if(a[t[r]])return!0;return!1}function gF({ctx:t,expKey:e,expBucketVersion:a,expHashAttribute:r,expFallbackAttribute:n,expMinBucketVersion:o,expMeta:i}){a=a||0,o=o||0,r=r||"id",i=i||[];let s=jy(e,a),l=vF(t,r,n);if(o>0)for(let d=0;d<o;d++){let f=jy(e,d);if(l[f]!==void 0)return{variation:-1,versionIsBlocked:!0}}let u=l[s];if(u===void 0)return{variation:-1};let c=i.findIndex(d=>d.key===u);return c<0?{variation:-1}:{variation:c}}function jy(t,e){return e=e||0,`${t}__${e}`}function Gy(t,e){return`${t}||${e}`}function vF(t,e,a){if(!t.user.stickyBucketAssignmentDocs)return{};let{hashAttribute:r,hashValue:n}=oi(t,e),o=Gy(r,Vu(n)),{hashAttribute:i,hashValue:s}=oi(t,a),l=s?Gy(i,Vu(s)):null,u={};return l&&t.user.stickyBucketAssignmentDocs[l]&&Object.assign(u,t.user.stickyBucketAssignmentDocs[l].assignments||{}),t.user.stickyBucketAssignmentDocs[o]&&Object.assign(u,t.user.stickyBucketAssignmentDocs[o].assignments||{}),u}function yF(t,e,a,r){let n=Gy(e,a),o=t.user.stickyBucketAssignmentDocs&&t.user.stickyBucketAssignmentDocs[n]?t.user.stickyBucketAssignmentDocs[n].assignments||{}:{},i={...o,...r},s=JSON.stringify(o)!==JSON.stringify(i);return{key:n,doc:{attributeName:e,attributeValue:a,assignments:i},changed:s}}function xF(t,e){let a=new Set,r=e&&e.features?e.features:t.global.features||{},n=e&&e.experiments?e.experiments:t.global.experiments||[];return Object.keys(r).forEach(o=>{let i=r[o];if(i.rules)for(let s of i.rules)s.variations&&(a.add(s.hashAttribute||"id"),s.fallbackAttribute&&a.add(s.fallbackAttribute))}),n.map(o=>{a.add(o.hashAttribute||"id"),o.fallbackAttribute&&a.add(o.fallbackAttribute)}),Array.from(a)}async function nA(t,e,a){let r=Wy(t,a);return e.getAllAssignments(r)}function Wy(t,e){let a={};return xF(t,e).forEach(n=>{let{hashValue:o}=oi(t,n);a[n]=Vu(o)}),a}async function oA(t,e,a){if(t={...t},t.encryptedFeatures){try{t.features=JSON.parse(await ni(t.encryptedFeatures,e,a))}catch(r){console.error(r)}delete t.encryptedFeatures}if(t.encryptedExperiments){try{t.experiments=JSON.parse(await ni(t.encryptedExperiments,e,a))}catch(r){console.error(r)}delete t.encryptedExperiments}if(t.encryptedSavedGroups){try{t.savedGroups=JSON.parse(await ni(t.encryptedSavedGroups,e,a))}catch(r){console.error(r)}delete t.encryptedSavedGroups}return t}function iA(t){let e=t.apiHost||"https://cdn.growthbook.io";return{apiHost:e.replace(/\/*$/,""),streamingHost:(t.streamingHost||e).replace(/\/*$/,""),apiRequestHeaders:t.apiHostRequestHeaders,streamingHostRequestHeaders:t.streamingHostRequestHeaders}}function Ap(t,e){return e.hashAttribute+e.hashValue+t.key+e.variationId}var Bs=typeof window<"u"&&typeof document<"u",bF=RI(),Wu=class{constructor(e){if(e=e||{},this.version=bF,this._options=this.context=e,this._renderer=e.renderer||null,this._trackedExperiments=new Set,this._completedChangeIds=new Set,this._trackedFeatures={},this.debug=!!e.debug,this._subscriptions=new Set,this.ready=!1,this._assigned=new Map,this._activeAutoExperiments=new Map,this._triggeredExpKeys=new Set,this._initialized=!1,this._redirectedUrl="",this._deferredTrackingCalls=new Map,this._autoExperimentsAllowed=!e.disableExperimentsOnLoad,this._destroyCallbacks=[],this.logs=[],this.log=this.log.bind(this),this._saveDeferredTrack=this._saveDeferredTrack.bind(this),this._onExperimentEval=this._onExperimentEval.bind(this),this._fireSubscriptions=this._fireSubscriptions.bind(this),this._recordChangedId=this._recordChangedId.bind(this),e.remoteEval){if(e.decryptionKey)throw new Error("Encryption is not available for remoteEval");if(!e.clientKey)throw new Error("Missing clientKey");let a=!1;try{a=!!new URL(e.apiHost||"").hostname.match(/growthbook\.io$/i)}catch{}if(a)throw new Error("Cannot use remoteEval on GrowthBook Cloud")}else if(e.cacheKeyAttributes)throw new Error("cacheKeyAttributes are only used for remoteEval");if(e.stickyBucketService){let a=e.stickyBucketService;this._saveStickyBucketAssignmentDoc=r=>a.saveAssignments(r)}if(e.plugins)for(let a of e.plugins)a(this);if(e.features&&(this.ready=!0),Bs&&e.enableDevMode&&(window._growthbook=this,document.dispatchEvent(new Event("gbloaded"))),e.experiments&&(this.ready=!0,this._updateAllAutoExperiments()),this._options.stickyBucketService&&this._options.stickyBucketAssignmentDocs)for(let a in this._options.stickyBucketAssignmentDocs){let r=this._options.stickyBucketAssignmentDocs[a];r&&this._options.stickyBucketService.saveAssignments(r).catch(()=>{})}this.ready&&this.refreshStickyBuckets(this.getPayload())}async setPayload(e){this._payload=e;let a=await oA(e,this._options.decryptionKey);this._decryptedPayload=a,await this.refreshStickyBuckets(a),a.features&&(this._options.features=a.features),a.savedGroups&&(this._options.savedGroups=a.savedGroups),a.experiments&&(this._options.experiments=a.experiments,this._updateAllAutoExperiments()),this.ready=!0,this._render()}initSync(e){this._initialized=!0;let a=e.payload;if(a.encryptedExperiments||a.encryptedFeatures)throw new Error("initSync does not support encrypted payloads");return this._options.stickyBucketService&&!this._options.stickyBucketAssignmentDocs&&(this._options.stickyBucketAssignmentDocs=this.generateStickyBucketAssignmentDocsSync(this._options.stickyBucketService,a)),this._payload=a,this._decryptedPayload=a,a.features&&(this._options.features=a.features),a.experiments&&(this._options.experiments=a.experiments,this._updateAllAutoExperiments()),this.ready=!0,vp(this,e),this}async init(e){if(this._initialized=!0,e=e||{},e.cacheSettings&&BI(e.cacheSettings),e.payload)return await this.setPayload(e.payload),vp(this,e),{success:!0,source:"init"};{let{data:a,...r}=await this._refresh({...e,allowStale:!0});return vp(this,e),await this.setPayload(a||{}),r}}async loadFeatures(e){e=e||{},await this.init({skipCache:e.skipCache,timeout:e.timeout,streaming:(this._options.backgroundSync??!0)&&(e.autoRefresh||this._options.subscribeToChanges)})}async refreshFeatures(e){let a=await this._refresh({...e||{},allowStale:!1});a.data&&await this.setPayload(a.data)}getApiInfo(){return[this.getApiHosts().apiHost,this.getClientKey()]}getApiHosts(){return iA(this._options)}getClientKey(){return this._options.clientKey||""}getPayload(){return this._payload||{features:this.getFeatures(),experiments:this.getExperiments()}}getDecryptedPayload(){return this._decryptedPayload||this.getPayload()}isRemoteEval(){return this._options.remoteEval||!1}getCacheKeyAttributes(){return this._options.cacheKeyAttributes}async _refresh({timeout:e,skipCache:a,allowStale:r,streaming:n}){if(!this._options.clientKey)throw new Error("Missing clientKey");return PI({instance:this,timeout:e,skipCache:a||this._options.disableCache,allowStale:r,backgroundSync:n??this._options.backgroundSync??!0})}_render(){if(this._renderer)try{this._renderer()}catch(e){console.error("Failed to render",e)}}setFeatures(e){this._options.features=e,this.ready=!0,this._render()}async setEncryptedFeatures(e,a,r){let n=await ni(e,a||this._options.decryptionKey,r);this.setFeatures(JSON.parse(n))}setExperiments(e){this._options.experiments=e,this.ready=!0,this._updateAllAutoExperiments()}async setEncryptedExperiments(e,a,r){let n=await ni(e,a||this._options.decryptionKey,r);this.setExperiments(JSON.parse(n))}async setAttributes(e){if(this._options.attributes=e,this._options.stickyBucketService&&await this.refreshStickyBuckets(),this._options.remoteEval){await this._refreshForRemoteEval();return}this._render(),this._updateAllAutoExperiments()}async updateAttributes(e){return this.setAttributes({...this._options.attributes,...e})}async setAttributeOverrides(e){if(this._options.attributeOverrides=e,this._options.stickyBucketService&&await this.refreshStickyBuckets(),this._options.remoteEval){await this._refreshForRemoteEval();return}this._render(),this._updateAllAutoExperiments()}async setForcedVariations(e){if(this._options.forcedVariations=e||{},this._options.remoteEval){await this._refreshForRemoteEval();return}this._render(),this._updateAllAutoExperiments()}setForcedFeatures(e){this._options.forcedFeatureValues=e,this._render()}async setURL(e){if(e!==this._options.url){if(this._options.url=e,this._redirectedUrl="",this._options.remoteEval){await this._refreshForRemoteEval(),this._updateAllAutoExperiments(!0);return}this._updateAllAutoExperiments(!0)}}getAttributes(){return{...this._options.attributes,...this._options.attributeOverrides}}getForcedVariations(){return this._options.forcedVariations||{}}getForcedFeatures(){return this._options.forcedFeatureValues||new Map}getStickyBucketAssignmentDocs(){return this._options.stickyBucketAssignmentDocs||{}}getUrl(){return this._options.url||""}getFeatures(){return this._options.features||{}}getExperiments(){return this._options.experiments||[]}getCompletedChangeIds(){return Array.from(this._completedChangeIds)}subscribe(e){return this._subscriptions.add(e),()=>{this._subscriptions.delete(e)}}async _refreshForRemoteEval(){if(!this._options.remoteEval||!this._initialized)return;let e=await this._refresh({allowStale:!1});e.data&&await this.setPayload(e.data)}getAllResults(){return new Map(this._assigned)}onDestroy(e){this._destroyCallbacks.push(e)}isDestroyed(){return!!this._destroyed}destroy(e){e=e||{},this._destroyed=!0,this._destroyCallbacks.forEach(a=>{try{a()}catch(r){console.error(r)}}),this._subscriptions.clear(),this._assigned.clear(),this._trackedExperiments.clear(),this._completedChangeIds.clear(),this._deferredTrackingCalls.clear(),this._trackedFeatures={},this._destroyCallbacks=[],this._payload=void 0,this._saveStickyBucketAssignmentDoc=void 0,NI(this),e.destroyAllStreams&&Hy(),this.logs=[],Bs&&window._growthbook===this&&delete window._growthbook,this._activeAutoExperiments.forEach(a=>{a.undo()}),this._activeAutoExperiments.clear(),this._triggeredExpKeys.clear()}setRenderer(e){this._renderer=e}forceVariation(e,a){if(this._options.forcedVariations=this._options.forcedVariations||{},this._options.forcedVariations[e]=a,this._options.remoteEval){this._refreshForRemoteEval();return}this._updateAllAutoExperiments(),this._render()}run(e){let{result:a}=Ip(e,null,this._getEvalContext());return this._onExperimentEval(e,a),a}triggerExperiment(e){return this._triggeredExpKeys.add(e),this._options.experiments?this._options.experiments.filter(r=>r.key===e).map(r=>this._runAutoExperiment(r)).filter(r=>r!==null):null}triggerAutoExperiments(){this._autoExperimentsAllowed=!0,this._updateAllAutoExperiments(!0)}_getEvalContext(){return{user:this._getUserContext(),global:this._getGlobalContext(),stack:{evaluatedFeatures:new Set}}}_getUserContext(){return{attributes:this._options.user?{...this._options.user,...this._options.attributes}:this._options.attributes,enableDevMode:this._options.enableDevMode,blockedChangeIds:this._options.blockedChangeIds,stickyBucketAssignmentDocs:this._options.stickyBucketAssignmentDocs,url:this._getContextUrl(),forcedVariations:this._options.forcedVariations,forcedFeatureValues:this._options.forcedFeatureValues,attributeOverrides:this._options.attributeOverrides,saveStickyBucketAssignmentDoc:this._saveStickyBucketAssignmentDoc,trackingCallback:this._options.trackingCallback,onFeatureUsage:this._options.onFeatureUsage,devLogs:this.logs,trackedExperiments:this._trackedExperiments,trackedFeatureUsage:this._trackedFeatures}}_getGlobalContext(){return{features:this._options.features,experiments:this._options.experiments,log:this.log,enabled:this._options.enabled,qaMode:this._options.qaMode,savedGroups:this._options.savedGroups,groups:this._options.groups,overrides:this._options.overrides,onExperimentEval:this._onExperimentEval,recordChangeId:this._recordChangedId,saveDeferredTrack:this._saveDeferredTrack,eventLogger:this._options.eventLogger}}_runAutoExperiment(e,a){let r=this._activeAutoExperiments.get(e);if(e.manual&&!this._triggeredExpKeys.has(e.key)&&!r)return null;let n=this._isAutoExperimentBlockedByContext(e),o,i;n?o=Ze(this._getEvalContext(),e,-1,!1,""):({result:o,trackingCall:i}=Ip(e,null,this._getEvalContext()),this._onExperimentEval(e,o));let s=JSON.stringify(o.value);if(!a&&o.inExperiment&&r&&r.valueHash===s)return o;if(r&&this._undoActiveAutoExperiment(e),o.inExperiment){let l=hp(e);if(l==="redirect"&&o.value.urlRedirect&&e.urlPatterns){let u=e.persistQueryString?MI(this._getContextUrl(),o.value.urlRedirect):o.value.urlRedirect;if(pp(u,e.urlPatterns))return this.log("Skipping redirect because original URL matches redirect URL",{id:e.key}),o;this._redirectedUrl=u;let{navigate:c,delay:d}=this._getNavigateFunction();if(c)if(Bs)Promise.all([...i?[mp(i,this._options.maxNavigateDelay??1e3)]:[],new Promise(f=>window.setTimeout(f,this._options.navigateDelay??d))]).then(()=>{try{c(u)}catch(f){console.error(f)}});else try{c(u)}catch(f){console.error(f)}}else if(l==="visual"){let u=this._options.applyDomChangesCallback?this._options.applyDomChangesCallback(o.value):this._applyDOMChanges(o.value);u&&this._activeAutoExperiments.set(e,{undo:u,valueHash:s})}}return o}_undoActiveAutoExperiment(e){let a=this._activeAutoExperiments.get(e);a&&(a.undo(),this._activeAutoExperiments.delete(e))}_updateAllAutoExperiments(e){if(!this._autoExperimentsAllowed)return;let a=this._options.experiments||[],r=new Set(a);this._activeAutoExperiments.forEach((n,o)=>{r.has(o)||(n.undo(),this._activeAutoExperiments.delete(o))});for(let n of a){let o=this._runAutoExperiment(n,e);if(o&&o.inExperiment&&hp(n)==="redirect")break}}_onExperimentEval(e,a){let r=this._assigned.get(e.key);this._assigned.set(e.key,{experiment:e,result:a}),this._subscriptions.size>0&&this._fireSubscriptions(e,a,r)}_fireSubscriptions(e,a,r){(!r||r.result.inExperiment!==a.inExperiment||r.result.variationId!==a.variationId)&&this._subscriptions.forEach(n=>{try{n(e,a)}catch(o){console.error(o)}})}_recordChangedId(e){this._completedChangeIds.add(e)}isOn(e){return this.evalFeature(e).on}isOff(e){return this.evalFeature(e).off}getFeatureValue(e,a){let r=this.evalFeature(e).value;return r===null?a:r}feature(e){return this.evalFeature(e)}evalFeature(e){return kp(e,this._getEvalContext())}log(e,a){this.debug&&(this._options.log?this._options.log(e,a):console.log(e,a))}getDeferredTrackingCalls(){return Array.from(this._deferredTrackingCalls.values())}setDeferredTrackingCalls(e){this._deferredTrackingCalls=new Map(e.filter(a=>a&&a.experiment&&a.result).map(a=>[Ap(a.experiment,a.result),a]))}async fireDeferredTrackingCalls(){if(!this._options.trackingCallback)return;let e=[];this._deferredTrackingCalls.forEach(a=>{!a||!a.experiment||!a.result?console.error("Invalid deferred tracking call",{call:a}):e.push(this._options.trackingCallback(a.experiment,a.result))}),this._deferredTrackingCalls.clear(),await Promise.all(e)}setTrackingCallback(e){this._options.trackingCallback=e,this.fireDeferredTrackingCalls()}setEventLogger(e){this._options.eventLogger=e}async logEvent(e,a){if(this._destroyed){console.error("Cannot log event to destroyed GrowthBook instance");return}if(this._options.enableDevMode&&this.logs.push({eventName:e,properties:a,timestamp:Date.now().toString(),logType:"event"}),this._options.eventLogger)try{await this._options.eventLogger(e,a||{},this._getUserContext())}catch(r){console.error(r)}else console.error("No event logger configured")}_saveDeferredTrack(e){this._deferredTrackingCalls.set(Ap(e.experiment,e.result),e)}_getContextUrl(){return this._options.url||(Bs?window.location.href:"")}_isAutoExperimentBlockedByContext(e){let a=hp(e);if(a==="visual"){if(this._options.disableVisualExperiments||this._options.disableJsInjection&&e.variations.some(r=>r.js))return!0}else if(a==="redirect"){if(this._options.disableUrlRedirectExperiments)return!0;try{let r=new URL(this._getContextUrl());for(let n of e.variations){if(!n||!n.urlRedirect)continue;let o=new URL(n.urlRedirect);if(this._options.disableCrossOriginUrlRedirectExperiments&&(o.protocol!==r.protocol||o.host!==r.host))return!0}}catch(r){return this.log("Error parsing current or redirect URL",{id:e.key,error:r}),!0}}else return!0;return!!(e.changeId&&(this._options.blockedChangeIds||[]).includes(e.changeId))}getRedirectUrl(){return this._redirectedUrl}_getNavigateFunction(){return this._options.navigate?{navigate:this._options.navigate,delay:0}:Bs?{navigate:e=>{window.location.replace(e)},delay:100}:{navigate:null,delay:0}}_applyDOMChanges(e){if(!Bs)return;let a=[];if(e.css){let r=document.createElement("style");r.innerHTML=e.css,document.head.appendChild(r),a.push(()=>r.remove())}if(e.js){let r=document.createElement("script");r.innerHTML=e.js,this._options.jsInjectionNonce&&(r.nonce=this._options.jsInjectionNonce),document.head.appendChild(r),a.push(()=>r.remove())}return e.domMutations&&e.domMutations.forEach(r=>{a.push(XI.declarative(r).revert)}),()=>{a.forEach(r=>r())}}async refreshStickyBuckets(e){if(this._options.stickyBucketService){let a=this._getEvalContext(),r=await nA(a,this._options.stickyBucketService,e);this._options.stickyBucketAssignmentDocs=r}}generateStickyBucketAssignmentDocsSync(e,a){if(!("getAllAssignmentsSync"in e)){console.error("generating StickyBucketAssignmentDocs docs requires StickyBucketServiceSync");return}let r=this._getEvalContext(),n=Wy(r,a);return e.getAllAssignmentsSync(n)}inDevMode(){return!!this._options.enableDevMode}};var SF="https://experiment.syntrologie.com",Zy=class{constructor(e={}){B(this,"gb");B(this,"featureListeners",new Set);if(e.client)this.gb=e.client;else{let a=e.onExperimentViewed?(r,n)=>{e.onExperimentViewed(r.key,n.variationId,typeof n.value=="string"?n.value:`variation_${n.variationId}`)}:void 0;this.gb=new Wu({...e,apiHost:e.apiHost??SF,enableDevMode:e.enableDevMode??!0,trackingCallback:a}),e.autoInit&&this.gb.init({streaming:!0})}}get _internal(){return this.gb}async refreshFeatures(){await this.gb.loadFeatures()}setAttributes(e){this.gb.setAttributes({...this.gb.getAttributes(),...e})}setForcedVariations(e){this.gb.setForcedVariations(e)}getFeatureValue(e,a){return this.gb.getFeatureValue(e,a)}getAllFeatures(){let e=this.gb.getFeatures(),a={};for(let r of Object.keys(e))a[r]=this.gb.getFeatureValue(r,null);return a}shouldRenderRectangle(e){return!0}onFeaturesChanged(e){return this.featureListeners.add(e),this.featureListeners.size===1&&this.gb.setRenderer(()=>{for(let a of this.featureListeners)a()}),()=>{this.featureListeners.delete(e),this.featureListeners.size===0&&this.gb.setRenderer(null)}}};function Xy(t={}){return new Zy(t)}var sA="syntro_session_metrics",Ep=class{constructor(e={}){B(this,"metrics",new Map);B(this,"experiments");B(this,"attributePrefix");B(this,"onMetricChange");this.experiments=e.experiments,this.attributePrefix=e.attributePrefix??"session_",this.onMetricChange=e.onMetricChange,this.loadFromStorage()}increment(e,a=1){let n=(this.metrics.get(e)??0)+a;return this.metrics.set(e,n),this.saveToStorage(),this.updateExperimentAttributes(e,n),this.onMetricChange?.(e,n),n}set(e,a){this.metrics.set(e,a),this.saveToStorage(),this.updateExperimentAttributes(e,a),this.onMetricChange?.(e,a)}get(e){return this.metrics.get(e)??0}meetsThreshold(e,a){return this.get(e)>=a}getAll(){return Object.fromEntries(this.metrics)}reset(e){this.metrics.delete(e),this.saveToStorage(),this.updateExperimentAttributes(e,0),this.onMetricChange?.(e,0)}resetAll(){let e=Array.from(this.metrics.keys());this.metrics.clear(),this.saveToStorage();let a={};for(let r of e)a[`${this.attributePrefix}${r}`]=0,this.onMetricChange?.(r,0);this.experiments?.setAttributes?.(a)}setExperiments(e){this.experiments=e,this.syncAllToExperiments()}updateExperimentAttributes(e,a){if(!this.experiments?.setAttributes)return;let r=`${this.attributePrefix}${e}`;this.experiments.setAttributes({[r]:a})}syncAllToExperiments(){if(!this.experiments?.setAttributes)return;let e={};for(let[a,r]of this.metrics)e[`${this.attributePrefix}${a}`]=r;this.experiments.setAttributes(e)}loadFromStorage(){if(!(typeof window>"u"||typeof sessionStorage>"u"))try{let e=sessionStorage.getItem(sA);if(e){let a=JSON.parse(e);for(let[r,n]of Object.entries(a))this.metrics.set(r,n.count)}}catch(e){console.warn("[SessionMetricTracker] Failed to load from sessionStorage:",e)}}saveToStorage(){if(!(typeof window>"u"||typeof sessionStorage>"u"))try{let e={};for(let[a,r]of this.metrics)e[a]={count:r,lastUpdated:Date.now()};sessionStorage.setItem(sA,JSON.stringify(e))}catch(e){console.warn("[SessionMetricTracker] Failed to save to sessionStorage:",e)}}};function Ky(t={}){return new Ep(t)}var p={};$R(p,{BRAND:()=>WF,DIRTY:()=>ii,EMPTY_PATH:()=>LF,INVALID:()=>J,NEVER:()=>RH,OK:()=>Ht,ParseStatus:()=>Ot,Schema:()=>le,ZodAny:()=>mo,ZodArray:()=>un,ZodBigInt:()=>li,ZodBoolean:()=>ui,ZodBranded:()=>Xu,ZodCatch:()=>bi,ZodDate:()=>ci,ZodDefault:()=>xi,ZodDiscriminatedUnion:()=>Mp,ZodEffects:()=>Va,ZodEnum:()=>vi,ZodError:()=>sa,ZodFirstPartyTypeKind:()=>ee,ZodFunction:()=>Dp,ZodIntersection:()=>hi,ZodIssueCode:()=>P,ZodLazy:()=>mi,ZodLiteral:()=>gi,ZodMap:()=>zs,ZodNaN:()=>Vs,ZodNativeEnum:()=>yi,ZodNever:()=>ur,ZodNull:()=>fi,ZodNullable:()=>Lr,ZodNumber:()=>si,ZodObject:()=>la,ZodOptional:()=>za,ZodParsedType:()=>G,ZodPipeline:()=>Ku,ZodPromise:()=>go,ZodReadonly:()=>Si,ZodRecord:()=>Op,ZodSchema:()=>le,ZodSet:()=>qs,ZodString:()=>ho,ZodSymbol:()=>Hs,ZodTransformer:()=>Va,ZodTuple:()=>wr,ZodType:()=>le,ZodUndefined:()=>di,ZodUnion:()=>pi,ZodUnknown:()=>ln,ZodVoid:()=>Us,addIssueToContext:()=>z,any:()=>aH,array:()=>iH,bigint:()=>YF,boolean:()=>yA,coerce:()=>TH,custom:()=>mA,date:()=>QF,datetimeRegex:()=>pA,defaultErrorMap:()=>on,discriminatedUnion:()=>cH,effect:()=>_H,enum:()=>xH,function:()=>gH,getErrorMap:()=>Ps,getParsedType:()=>Cr,instanceof:()=>XF,intersection:()=>dH,isAborted:()=>Tp,isAsync:()=>Ns,isDirty:()=>Rp,isValid:()=>po,late:()=>ZF,lazy:()=>vH,literal:()=>yH,makeIssue:()=>Zu,map:()=>hH,nan:()=>KF,nativeEnum:()=>bH,never:()=>nH,null:()=>tH,nullable:()=>wH,number:()=>vA,object:()=>sH,objectUtil:()=>Yy,oboolean:()=>EH,onumber:()=>AH,optional:()=>CH,ostring:()=>IH,pipeline:()=>kH,preprocess:()=>LH,promise:()=>SH,quotelessJson:()=>_F,record:()=>pH,set:()=>mH,setErrorMap:()=>wF,strictObject:()=>lH,string:()=>gA,symbol:()=>JF,transformer:()=>_H,tuple:()=>fH,undefined:()=>eH,union:()=>uH,unknown:()=>rH,util:()=>pe,void:()=>oH});var pe;(function(t){t.assertEqual=n=>{};function e(n){}t.assertIs=e;function a(n){throw new Error}t.assertNever=a,t.arrayToEnum=n=>{let o={};for(let i of n)o[i]=i;return o},t.getValidEnumValues=n=>{let o=t.objectKeys(n).filter(s=>typeof n[n[s]]!="number"),i={};for(let s of o)i[s]=n[s];return t.objectValues(i)},t.objectValues=n=>t.objectKeys(n).map(function(o){return n[o]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let o=[];for(let i in n)Object.prototype.hasOwnProperty.call(n,i)&&o.push(i);return o},t.find=(n,o)=>{for(let i of n)if(o(i))return i},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function r(n,o=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=r,t.jsonStringifyReplacer=(n,o)=>typeof o=="bigint"?o.toString():o})(pe||(pe={}));var Yy;(function(t){t.mergeShapes=(e,a)=>({...e,...a})})(Yy||(Yy={}));var G=pe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Cr=t=>{switch(typeof t){case"undefined":return G.undefined;case"string":return G.string;case"number":return Number.isNaN(t)?G.nan:G.number;case"boolean":return G.boolean;case"function":return G.function;case"bigint":return G.bigint;case"symbol":return G.symbol;case"object":return Array.isArray(t)?G.array:t===null?G.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?G.promise:typeof Map<"u"&&t instanceof Map?G.map:typeof Set<"u"&&t instanceof Set?G.set:typeof Date<"u"&&t instanceof Date?G.date:G.object;default:return G.unknown}};var P=pe.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),_F=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),sa=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let a=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,a):this.__proto__=a,this.name="ZodError",this.issues=e}format(e){let a=e||function(o){return o.message},r={_errors:[]},n=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)r._errors.push(a(i));else{let s=r,l=0;for(;l<i.path.length;){let u=i.path[l];l===i.path.length-1?(s[u]=s[u]||{_errors:[]},s[u]._errors.push(a(i))):s[u]=s[u]||{_errors:[]},s=s[u],l++}}};return n(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,pe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=a=>a.message){let a={},r=[];for(let n of this.issues)if(n.path.length>0){let o=n.path[0];a[o]=a[o]||[],a[o].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:a}}get formErrors(){return this.flatten()}};sa.create=t=>new sa(t);var CF=(t,e)=>{let a;switch(t.code){case P.invalid_type:t.received===G.undefined?a="Required":a=`Expected ${t.expected}, received ${t.received}`;break;case P.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(t.expected,pe.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:a=`Unrecognized key(s) in object: ${pe.joinValues(t.keys,", ")}`;break;case P.invalid_union:a="Invalid input";break;case P.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${pe.joinValues(t.options)}`;break;case P.invalid_enum_value:a=`Invalid enum value. Expected ${pe.joinValues(t.options)}, received '${t.received}'`;break;case P.invalid_arguments:a="Invalid function arguments";break;case P.invalid_return_type:a="Invalid function return type";break;case P.invalid_date:a="Invalid date";break;case P.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(a=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(a=`${a} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?a=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?a=`Invalid input: must end with "${t.validation.endsWith}"`:pe.assertNever(t.validation):t.validation!=="regex"?a=`Invalid ${t.validation}`:a="Invalid";break;case P.too_small:t.type==="array"?a=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?a=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?a=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?a=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?a=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:a="Invalid input";break;case P.too_big:t.type==="array"?a=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?a=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?a=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?a=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?a=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:a="Invalid input";break;case P.custom:a="Invalid input";break;case P.invalid_intersection_types:a="Intersection results could not be merged";break;case P.not_multiple_of:a=`Number must be a multiple of ${t.multipleOf}`;break;case P.not_finite:a="Number must be finite";break;default:a=e.defaultError,pe.assertNever(t)}return{message:a}},on=CF;var lA=on;function wF(t){lA=t}function Ps(){return lA}var Zu=t=>{let{data:e,path:a,errorMaps:r,issueData:n}=t,o=[...a,...n.path||[]],i={...n,path:o};if(n.message!==void 0)return{...n,path:o,message:n.message};let s="",l=r.filter(u=>!!u).slice().reverse();for(let u of l)s=u(i,{data:e,defaultError:s}).message;return{...n,path:o,message:s}},LF=[];function z(t,e){let a=Ps(),r=Zu({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,a,a===on?void 0:on].filter(n=>!!n)});t.common.issues.push(r)}var Ot=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,a){let r=[];for(let n of a){if(n.status==="aborted")return J;n.status==="dirty"&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,a){let r=[];for(let n of a){let o=await n.key,i=await n.value;r.push({key:o,value:i})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,a){let r={};for(let n of a){let{key:o,value:i}=n;if(o.status==="aborted"||i.status==="aborted")return J;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(r[o.value]=i.value)}return{status:e.value,value:r}}},J=Object.freeze({status:"aborted"}),ii=t=>({status:"dirty",value:t}),Ht=t=>({status:"valid",value:t}),Tp=t=>t.status==="aborted",Rp=t=>t.status==="dirty",po=t=>t.status==="valid",Ns=t=>typeof Promise<"u"&&t instanceof Promise;var X;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(X||(X={}));var qa=class{constructor(e,a,r,n){this._cachedPath=[],this.parent=e,this.data=a,this._path=r,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},uA=(t,e)=>{if(po(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let a=new sa(t.common.issues);return this._error=a,this._error}}};function se(t){if(!t)return{};let{errorMap:e,invalid_type_error:a,required_error:r,description:n}=t;if(e&&(a||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(i,s)=>{let{message:l}=t;return i.code==="invalid_enum_value"?{message:l??s.defaultError}:typeof s.data>"u"?{message:l??r??s.defaultError}:i.code!=="invalid_type"?{message:s.defaultError}:{message:l??a??s.defaultError}},description:n}}var le=class{get description(){return this._def.description}_getType(e){return Cr(e.data)}_getOrReturnCtx(e,a){return a||{common:e.parent.common,data:e.data,parsedType:Cr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ot,ctx:{common:e.parent.common,data:e.data,parsedType:Cr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let a=this._parse(e);if(Ns(a))throw new Error("Synchronous parse encountered promise.");return a}_parseAsync(e){let a=this._parse(e);return Promise.resolve(a)}parse(e,a){let r=this.safeParse(e,a);if(r.success)return r.data;throw r.error}safeParse(e,a){let r={common:{issues:[],async:a?.async??!1,contextualErrorMap:a?.errorMap},path:a?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Cr(e)},n=this._parseSync({data:e,path:r.path,parent:r});return uA(r,n)}"~validate"(e){let a={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Cr(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:a});return po(r)?{value:r.value}:{issues:a.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),a.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:a}).then(r=>po(r)?{value:r.value}:{issues:a.common.issues})}async parseAsync(e,a){let r=await this.safeParseAsync(e,a);if(r.success)return r.data;throw r.error}async safeParseAsync(e,a){let r={common:{issues:[],contextualErrorMap:a?.errorMap,async:!0},path:a?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Cr(e)},n=this._parse({data:e,path:r.path,parent:r}),o=await(Ns(n)?n:Promise.resolve(n));return uA(r,o)}refine(e,a){let r=n=>typeof a=="string"||typeof a>"u"?{message:a}:typeof a=="function"?a(n):a;return this._refinement((n,o)=>{let i=e(n),s=()=>o.addIssue({code:P.custom,...r(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(s(),!1)):i?!0:(s(),!1)})}refinement(e,a){return this._refinement((r,n)=>e(r)?!0:(n.addIssue(typeof a=="function"?a(r,n):a),!1))}_refinement(e){return new Va({schema:this,typeName:ee.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:a=>this["~validate"](a)}}optional(){return za.create(this,this._def)}nullable(){return Lr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return un.create(this)}promise(){return go.create(this,this._def)}or(e){return pi.create([this,e],this._def)}and(e){return hi.create(this,e,this._def)}transform(e){return new Va({...se(this._def),schema:this,typeName:ee.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let a=typeof e=="function"?e:()=>e;return new xi({...se(this._def),innerType:this,defaultValue:a,typeName:ee.ZodDefault})}brand(){return new Xu({typeName:ee.ZodBranded,type:this,...se(this._def)})}catch(e){let a=typeof e=="function"?e:()=>e;return new bi({...se(this._def),innerType:this,catchValue:a,typeName:ee.ZodCatch})}describe(e){let a=this.constructor;return new a({...this._def,description:e})}pipe(e){return Ku.create(this,e)}readonly(){return Si.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},kF=/^c[^\s-]{8,}$/i,IF=/^[0-9a-z]+$/,AF=/^[0-9A-HJKMNP-TV-Z]{26}$/i,EF=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,TF=/^[a-z0-9_-]{21}$/i,RF=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,MF=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,OF=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,DF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Qy,BF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,PF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,NF=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,FF=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,HF=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,UF=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dA="((\\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])))",zF=new RegExp(`^${dA}$`);function fA(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let a=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${a}`}function qF(t){return new RegExp(`^${fA(t)}$`)}function pA(t){let e=`${dA}T${fA(t)}`,a=[];return a.push(t.local?"Z?":"Z"),t.offset&&a.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${a.join("|")})`,new RegExp(`^${e}$`)}function VF(t,e){return!!((e==="v4"||!e)&&BF.test(t)||(e==="v6"||!e)&&NF.test(t))}function $F(t,e){if(!RF.test(t))return!1;try{let[a]=t.split(".");if(!a)return!1;let r=a.replace(/-/g,"+").replace(/_/g,"/").padEnd(a.length+(4-a.length%4)%4,"="),n=JSON.parse(atob(r));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function jF(t,e){return!!((e==="v4"||!e)&&PF.test(t)||(e==="v6"||!e)&&FF.test(t))}var ho=class t extends le{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==G.string){let o=this._getOrReturnCtx(e);return z(o,{code:P.invalid_type,expected:G.string,received:o.parsedType}),J}let r=new Ot,n;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(n=this._getOrReturnCtx(e,n),z(n,{code:P.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")e.data.length>o.value&&(n=this._getOrReturnCtx(e,n),z(n,{code:P.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let i=e.data.length>o.value,s=e.data.length<o.value;(i||s)&&(n=this._getOrReturnCtx(e,n),i?z(n,{code:P.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):s&&z(n,{code:P.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")OF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"email",code:P.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Qy||(Qy=new RegExp(DF,"u")),Qy.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"emoji",code:P.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")EF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"uuid",code:P.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")TF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"nanoid",code:P.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")kF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"cuid",code:P.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")IF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"cuid2",code:P.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")AF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"ulid",code:P.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),z(n,{validation:"url",code:P.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"regex",code:P.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(n=this._getOrReturnCtx(e,n),z(n,{code:P.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(n=this._getOrReturnCtx(e,n),z(n,{code:P.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(n=this._getOrReturnCtx(e,n),z(n,{code:P.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?pA(o).test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:P.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?zF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:P.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?qF(o).test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:P.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?MF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"duration",code:P.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?VF(e.data,o.version)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"ip",code:P.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?$F(e.data,o.alg)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"jwt",code:P.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?jF(e.data,o.version)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"cidr",code:P.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?HF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"base64",code:P.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?UF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"base64url",code:P.invalid_string,message:o.message}),r.dirty()):pe.assertNever(o);return{status:r.value,value:e.data}}_regex(e,a,r){return this.refinement(n=>e.test(n),{validation:a,code:P.invalid_string,...X.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...X.errToObj(e)})}url(e){return this._addCheck({kind:"url",...X.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...X.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...X.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...X.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...X.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...X.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...X.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...X.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...X.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...X.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...X.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...X.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...X.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...X.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...X.errToObj(e)})}regex(e,a){return this._addCheck({kind:"regex",regex:e,...X.errToObj(a)})}includes(e,a){return this._addCheck({kind:"includes",value:e,position:a?.position,...X.errToObj(a?.message)})}startsWith(e,a){return this._addCheck({kind:"startsWith",value:e,...X.errToObj(a)})}endsWith(e,a){return this._addCheck({kind:"endsWith",value:e,...X.errToObj(a)})}min(e,a){return this._addCheck({kind:"min",value:e,...X.errToObj(a)})}max(e,a){return this._addCheck({kind:"max",value:e,...X.errToObj(a)})}length(e,a){return this._addCheck({kind:"length",value:e,...X.errToObj(a)})}nonempty(e){return this.min(1,X.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e}get maxLength(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.value<e)&&(e=a.value);return e}};ho.create=t=>new ho({checks:[],typeName:ee.ZodString,coerce:t?.coerce??!1,...se(t)});function GF(t,e){let a=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,n=a>r?a:r,o=Number.parseInt(t.toFixed(n).replace(".","")),i=Number.parseInt(e.toFixed(n).replace(".",""));return o%i/10**n}var si=class t extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==G.number){let o=this._getOrReturnCtx(e);return z(o,{code:P.invalid_type,expected:G.number,received:o.parsedType}),J}let r,n=new Ot;for(let o of this._def.checks)o.kind==="int"?pe.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),z(r,{code:P.invalid_type,expected:"integer",received:"float",message:o.message}),n.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),z(r,{code:P.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),z(r,{code:P.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()):o.kind==="multipleOf"?GF(e.data,o.value)!==0&&(r=this._getOrReturnCtx(e,r),z(r,{code:P.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),z(r,{code:P.not_finite,message:o.message}),n.dirty()):pe.assertNever(o);return{status:n.value,value:e.data}}gte(e,a){return this.setLimit("min",e,!0,X.toString(a))}gt(e,a){return this.setLimit("min",e,!1,X.toString(a))}lte(e,a){return this.setLimit("max",e,!0,X.toString(a))}lt(e,a){return this.setLimit("max",e,!1,X.toString(a))}setLimit(e,a,r,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:a,inclusive:r,message:X.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:X.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:X.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:X.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:X.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:X.toString(e)})}multipleOf(e,a){return this._addCheck({kind:"multipleOf",value:e,message:X.toString(a)})}finite(e){return this._addCheck({kind:"finite",message:X.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:X.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:X.toString(e)})}get minValue(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e}get maxValue(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.value<e)&&(e=a.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&pe.isInteger(e.value))}get isFinite(){let e=null,a=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(a===null||r.value>a)&&(a=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(a)&&Number.isFinite(e)}};si.create=t=>new si({checks:[],typeName:ee.ZodNumber,coerce:t?.coerce||!1,...se(t)});var li=class t extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==G.bigint)return this._getInvalidInput(e);let r,n=new Ot;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),z(r,{code:P.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),n.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),z(r,{code:P.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),n.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),z(r,{code:P.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()):pe.assertNever(o);return{status:n.value,value:e.data}}_getInvalidInput(e){let a=this._getOrReturnCtx(e);return z(a,{code:P.invalid_type,expected:G.bigint,received:a.parsedType}),J}gte(e,a){return this.setLimit("min",e,!0,X.toString(a))}gt(e,a){return this.setLimit("min",e,!1,X.toString(a))}lte(e,a){return this.setLimit("max",e,!0,X.toString(a))}lt(e,a){return this.setLimit("max",e,!1,X.toString(a))}setLimit(e,a,r,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:a,inclusive:r,message:X.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:X.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:X.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:X.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:X.toString(e)})}multipleOf(e,a){return this._addCheck({kind:"multipleOf",value:e,message:X.toString(a)})}get minValue(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e}get maxValue(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.value<e)&&(e=a.value);return e}};li.create=t=>new li({checks:[],typeName:ee.ZodBigInt,coerce:t?.coerce??!1,...se(t)});var ui=class extends le{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==G.boolean){let r=this._getOrReturnCtx(e);return z(r,{code:P.invalid_type,expected:G.boolean,received:r.parsedType}),J}return Ht(e.data)}};ui.create=t=>new ui({typeName:ee.ZodBoolean,coerce:t?.coerce||!1,...se(t)});var ci=class t extends le{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==G.date){let o=this._getOrReturnCtx(e);return z(o,{code:P.invalid_type,expected:G.date,received:o.parsedType}),J}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return z(o,{code:P.invalid_date}),J}let r=new Ot,n;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(n=this._getOrReturnCtx(e,n),z(n,{code:P.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(n=this._getOrReturnCtx(e,n),z(n,{code:P.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):pe.assertNever(o);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,a){return this._addCheck({kind:"min",value:e.getTime(),message:X.toString(a)})}max(e,a){return this._addCheck({kind:"max",value:e.getTime(),message:X.toString(a)})}get minDate(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.value<e)&&(e=a.value);return e!=null?new Date(e):null}};ci.create=t=>new ci({checks:[],coerce:t?.coerce||!1,typeName:ee.ZodDate,...se(t)});var Hs=class extends le{_parse(e){if(this._getType(e)!==G.symbol){let r=this._getOrReturnCtx(e);return z(r,{code:P.invalid_type,expected:G.symbol,received:r.parsedType}),J}return Ht(e.data)}};Hs.create=t=>new Hs({typeName:ee.ZodSymbol,...se(t)});var di=class extends le{_parse(e){if(this._getType(e)!==G.undefined){let r=this._getOrReturnCtx(e);return z(r,{code:P.invalid_type,expected:G.undefined,received:r.parsedType}),J}return Ht(e.data)}};di.create=t=>new di({typeName:ee.ZodUndefined,...se(t)});var fi=class extends le{_parse(e){if(this._getType(e)!==G.null){let r=this._getOrReturnCtx(e);return z(r,{code:P.invalid_type,expected:G.null,received:r.parsedType}),J}return Ht(e.data)}};fi.create=t=>new fi({typeName:ee.ZodNull,...se(t)});var mo=class extends le{constructor(){super(...arguments),this._any=!0}_parse(e){return Ht(e.data)}};mo.create=t=>new mo({typeName:ee.ZodAny,...se(t)});var ln=class extends le{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ht(e.data)}};ln.create=t=>new ln({typeName:ee.ZodUnknown,...se(t)});var ur=class extends le{_parse(e){let a=this._getOrReturnCtx(e);return z(a,{code:P.invalid_type,expected:G.never,received:a.parsedType}),J}};ur.create=t=>new ur({typeName:ee.ZodNever,...se(t)});var Us=class extends le{_parse(e){if(this._getType(e)!==G.undefined){let r=this._getOrReturnCtx(e);return z(r,{code:P.invalid_type,expected:G.void,received:r.parsedType}),J}return Ht(e.data)}};Us.create=t=>new Us({typeName:ee.ZodVoid,...se(t)});var un=class t extends le{_parse(e){let{ctx:a,status:r}=this._processInputParams(e),n=this._def;if(a.parsedType!==G.array)return z(a,{code:P.invalid_type,expected:G.array,received:a.parsedType}),J;if(n.exactLength!==null){let i=a.data.length>n.exactLength.value,s=a.data.length<n.exactLength.value;(i||s)&&(z(a,{code:i?P.too_big:P.too_small,minimum:s?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(n.minLength!==null&&a.data.length<n.minLength.value&&(z(a,{code:P.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),n.maxLength!==null&&a.data.length>n.maxLength.value&&(z(a,{code:P.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),a.common.async)return Promise.all([...a.data].map((i,s)=>n.type._parseAsync(new qa(a,i,a.path,s)))).then(i=>Ot.mergeArray(r,i));let o=[...a.data].map((i,s)=>n.type._parseSync(new qa(a,i,a.path,s)));return Ot.mergeArray(r,o)}get element(){return this._def.type}min(e,a){return new t({...this._def,minLength:{value:e,message:X.toString(a)}})}max(e,a){return new t({...this._def,maxLength:{value:e,message:X.toString(a)}})}length(e,a){return new t({...this._def,exactLength:{value:e,message:X.toString(a)}})}nonempty(e){return this.min(1,e)}};un.create=(t,e)=>new un({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ee.ZodArray,...se(e)});function Fs(t){if(t instanceof la){let e={};for(let a in t.shape){let r=t.shape[a];e[a]=za.create(Fs(r))}return new la({...t._def,shape:()=>e})}else return t instanceof un?new un({...t._def,type:Fs(t.element)}):t instanceof za?za.create(Fs(t.unwrap())):t instanceof Lr?Lr.create(Fs(t.unwrap())):t instanceof wr?wr.create(t.items.map(e=>Fs(e))):t}var la=class t extends le{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),a=pe.objectKeys(e);return this._cached={shape:e,keys:a},this._cached}_parse(e){if(this._getType(e)!==G.object){let u=this._getOrReturnCtx(e);return z(u,{code:P.invalid_type,expected:G.object,received:u.parsedType}),J}let{status:r,ctx:n}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof ur&&this._def.unknownKeys==="strip"))for(let u in n.data)i.includes(u)||s.push(u);let l=[];for(let u of i){let c=o[u],d=n.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new qa(n,d,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof ur){let u=this._def.unknownKeys;if(u==="passthrough")for(let c of s)l.push({key:{status:"valid",value:c},value:{status:"valid",value:n.data[c]}});else if(u==="strict")s.length>0&&(z(n,{code:P.unrecognized_keys,keys:s}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let c of s){let d=n.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new qa(n,d,n.path,c)),alwaysSet:c in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let u=[];for(let c of l){let d=await c.key,f=await c.value;u.push({key:d,value:f,alwaysSet:c.alwaysSet})}return u}).then(u=>Ot.mergeObjectSync(r,u)):Ot.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return X.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(a,r)=>{let n=this._def.errorMap?.(a,r).message??r.defaultError;return a.code==="unrecognized_keys"?{message:X.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ee.ZodObject})}setKey(e,a){return this.augment({[e]:a})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let a={};for(let r of pe.objectKeys(e))e[r]&&this.shape[r]&&(a[r]=this.shape[r]);return new t({...this._def,shape:()=>a})}omit(e){let a={};for(let r of pe.objectKeys(this.shape))e[r]||(a[r]=this.shape[r]);return new t({...this._def,shape:()=>a})}deepPartial(){return Fs(this)}partial(e){let a={};for(let r of pe.objectKeys(this.shape)){let n=this.shape[r];e&&!e[r]?a[r]=n:a[r]=n.optional()}return new t({...this._def,shape:()=>a})}required(e){let a={};for(let r of pe.objectKeys(this.shape))if(e&&!e[r])a[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof za;)o=o._def.innerType;a[r]=o}return new t({...this._def,shape:()=>a})}keyof(){return hA(pe.objectKeys(this.shape))}};la.create=(t,e)=>new la({shape:()=>t,unknownKeys:"strip",catchall:ur.create(),typeName:ee.ZodObject,...se(e)});la.strictCreate=(t,e)=>new la({shape:()=>t,unknownKeys:"strict",catchall:ur.create(),typeName:ee.ZodObject,...se(e)});la.lazycreate=(t,e)=>new la({shape:t,unknownKeys:"strip",catchall:ur.create(),typeName:ee.ZodObject,...se(e)});var pi=class extends le{_parse(e){let{ctx:a}=this._processInputParams(e),r=this._def.options;function n(o){for(let s of o)if(s.result.status==="valid")return s.result;for(let s of o)if(s.result.status==="dirty")return a.common.issues.push(...s.ctx.common.issues),s.result;let i=o.map(s=>new sa(s.ctx.common.issues));return z(a,{code:P.invalid_union,unionErrors:i}),J}if(a.common.async)return Promise.all(r.map(async o=>{let i={...a,common:{...a.common,issues:[]},parent:null};return{result:await o._parseAsync({data:a.data,path:a.path,parent:i}),ctx:i}})).then(n);{let o,i=[];for(let l of r){let u={...a,common:{...a.common,issues:[]},parent:null},c=l._parseSync({data:a.data,path:a.path,parent:u});if(c.status==="valid")return c;c.status==="dirty"&&!o&&(o={result:c,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(o)return a.common.issues.push(...o.ctx.common.issues),o.result;let s=i.map(l=>new sa(l));return z(a,{code:P.invalid_union,unionErrors:s}),J}}get options(){return this._def.options}};pi.create=(t,e)=>new pi({options:t,typeName:ee.ZodUnion,...se(e)});var sn=t=>t instanceof mi?sn(t.schema):t instanceof Va?sn(t.innerType()):t instanceof gi?[t.value]:t instanceof vi?t.options:t instanceof yi?pe.objectValues(t.enum):t instanceof xi?sn(t._def.innerType):t instanceof di?[void 0]:t instanceof fi?[null]:t instanceof za?[void 0,...sn(t.unwrap())]:t instanceof Lr?[null,...sn(t.unwrap())]:t instanceof Xu||t instanceof Si?sn(t.unwrap()):t instanceof bi?sn(t._def.innerType):[],Mp=class t extends le{_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==G.object)return z(a,{code:P.invalid_type,expected:G.object,received:a.parsedType}),J;let r=this.discriminator,n=a.data[r],o=this.optionsMap.get(n);return o?a.common.async?o._parseAsync({data:a.data,path:a.path,parent:a}):o._parseSync({data:a.data,path:a.path,parent:a}):(z(a,{code:P.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),J)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,a,r){let n=new Map;for(let o of a){let i=sn(o.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of i){if(n.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,o)}}return new t({typeName:ee.ZodDiscriminatedUnion,discriminator:e,options:a,optionsMap:n,...se(r)})}};function Jy(t,e){let a=Cr(t),r=Cr(e);if(t===e)return{valid:!0,data:t};if(a===G.object&&r===G.object){let n=pe.objectKeys(e),o=pe.objectKeys(t).filter(s=>n.indexOf(s)!==-1),i={...t,...e};for(let s of o){let l=Jy(t[s],e[s]);if(!l.valid)return{valid:!1};i[s]=l.data}return{valid:!0,data:i}}else if(a===G.array&&r===G.array){if(t.length!==e.length)return{valid:!1};let n=[];for(let o=0;o<t.length;o++){let i=t[o],s=e[o],l=Jy(i,s);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return a===G.date&&r===G.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var hi=class extends le{_parse(e){let{status:a,ctx:r}=this._processInputParams(e),n=(o,i)=>{if(Tp(o)||Tp(i))return J;let s=Jy(o.value,i.value);return s.valid?((Rp(o)||Rp(i))&&a.dirty(),{status:a.value,value:s.data}):(z(r,{code:P.invalid_intersection_types}),J)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>n(o,i)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};hi.create=(t,e,a)=>new hi({left:t,right:e,typeName:ee.ZodIntersection,...se(a)});var wr=class t extends le{_parse(e){let{status:a,ctx:r}=this._processInputParams(e);if(r.parsedType!==G.array)return z(r,{code:P.invalid_type,expected:G.array,received:r.parsedType}),J;if(r.data.length<this._def.items.length)return z(r,{code:P.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&r.data.length>this._def.items.length&&(z(r,{code:P.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),a.dirty());let o=[...r.data].map((i,s)=>{let l=this._def.items[s]||this._def.rest;return l?l._parse(new qa(r,i,r.path,s)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>Ot.mergeArray(a,i)):Ot.mergeArray(a,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};wr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new wr({items:t,typeName:ee.ZodTuple,rest:null,...se(e)})};var Op=class t extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:a,ctx:r}=this._processInputParams(e);if(r.parsedType!==G.object)return z(r,{code:P.invalid_type,expected:G.object,received:r.parsedType}),J;let n=[],o=this._def.keyType,i=this._def.valueType;for(let s in r.data)n.push({key:o._parse(new qa(r,s,r.path,s)),value:i._parse(new qa(r,r.data[s],r.path,s)),alwaysSet:s in r.data});return r.common.async?Ot.mergeObjectAsync(a,n):Ot.mergeObjectSync(a,n)}get element(){return this._def.valueType}static create(e,a,r){return a instanceof le?new t({keyType:e,valueType:a,typeName:ee.ZodRecord,...se(r)}):new t({keyType:ho.create(),valueType:e,typeName:ee.ZodRecord,...se(a)})}},zs=class extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:a,ctx:r}=this._processInputParams(e);if(r.parsedType!==G.map)return z(r,{code:P.invalid_type,expected:G.map,received:r.parsedType}),J;let n=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([s,l],u)=>({key:n._parse(new qa(r,s,r.path,[u,"key"])),value:o._parse(new qa(r,l,r.path,[u,"value"]))}));if(r.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let l of i){let u=await l.key,c=await l.value;if(u.status==="aborted"||c.status==="aborted")return J;(u.status==="dirty"||c.status==="dirty")&&a.dirty(),s.set(u.value,c.value)}return{status:a.value,value:s}})}else{let s=new Map;for(let l of i){let u=l.key,c=l.value;if(u.status==="aborted"||c.status==="aborted")return J;(u.status==="dirty"||c.status==="dirty")&&a.dirty(),s.set(u.value,c.value)}return{status:a.value,value:s}}}};zs.create=(t,e,a)=>new zs({valueType:e,keyType:t,typeName:ee.ZodMap,...se(a)});var qs=class t extends le{_parse(e){let{status:a,ctx:r}=this._processInputParams(e);if(r.parsedType!==G.set)return z(r,{code:P.invalid_type,expected:G.set,received:r.parsedType}),J;let n=this._def;n.minSize!==null&&r.data.size<n.minSize.value&&(z(r,{code:P.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),a.dirty()),n.maxSize!==null&&r.data.size>n.maxSize.value&&(z(r,{code:P.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),a.dirty());let o=this._def.valueType;function i(l){let u=new Set;for(let c of l){if(c.status==="aborted")return J;c.status==="dirty"&&a.dirty(),u.add(c.value)}return{status:a.value,value:u}}let s=[...r.data.values()].map((l,u)=>o._parse(new qa(r,l,r.path,u)));return r.common.async?Promise.all(s).then(l=>i(l)):i(s)}min(e,a){return new t({...this._def,minSize:{value:e,message:X.toString(a)}})}max(e,a){return new t({...this._def,maxSize:{value:e,message:X.toString(a)}})}size(e,a){return this.min(e,a).max(e,a)}nonempty(e){return this.min(1,e)}};qs.create=(t,e)=>new qs({valueType:t,minSize:null,maxSize:null,typeName:ee.ZodSet,...se(e)});var Dp=class t extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==G.function)return z(a,{code:P.invalid_type,expected:G.function,received:a.parsedType}),J;function r(s,l){return Zu({data:s,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,Ps(),on].filter(u=>!!u),issueData:{code:P.invalid_arguments,argumentsError:l}})}function n(s,l){return Zu({data:s,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,Ps(),on].filter(u=>!!u),issueData:{code:P.invalid_return_type,returnTypeError:l}})}let o={errorMap:a.common.contextualErrorMap},i=a.data;if(this._def.returns instanceof go){let s=this;return Ht(async function(...l){let u=new sa([]),c=await s._def.args.parseAsync(l,o).catch(h=>{throw u.addIssue(r(l,h)),u}),d=await Reflect.apply(i,this,c);return await s._def.returns._def.type.parseAsync(d,o).catch(h=>{throw u.addIssue(n(d,h)),u})})}else{let s=this;return Ht(function(...l){let u=s._def.args.safeParse(l,o);if(!u.success)throw new sa([r(l,u.error)]);let c=Reflect.apply(i,this,u.data),d=s._def.returns.safeParse(c,o);if(!d.success)throw new sa([n(c,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:wr.create(e).rest(ln.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,a,r){return new t({args:e||wr.create([]).rest(ln.create()),returns:a||ln.create(),typeName:ee.ZodFunction,...se(r)})}},mi=class extends le{get schema(){return this._def.getter()}_parse(e){let{ctx:a}=this._processInputParams(e);return this._def.getter()._parse({data:a.data,path:a.path,parent:a})}};mi.create=(t,e)=>new mi({getter:t,typeName:ee.ZodLazy,...se(e)});var gi=class extends le{_parse(e){if(e.data!==this._def.value){let a=this._getOrReturnCtx(e);return z(a,{received:a.data,code:P.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}};gi.create=(t,e)=>new gi({value:t,typeName:ee.ZodLiteral,...se(e)});function hA(t,e){return new vi({values:t,typeName:ee.ZodEnum,...se(e)})}var vi=class t extends le{_parse(e){if(typeof e.data!="string"){let a=this._getOrReturnCtx(e),r=this._def.values;return z(a,{expected:pe.joinValues(r),received:a.parsedType,code:P.invalid_type}),J}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let a=this._getOrReturnCtx(e),r=this._def.values;return z(a,{received:a.data,code:P.invalid_enum_value,options:r}),J}return Ht(e.data)}get options(){return this._def.values}get enum(){let e={};for(let a of this._def.values)e[a]=a;return e}get Values(){let e={};for(let a of this._def.values)e[a]=a;return e}get Enum(){let e={};for(let a of this._def.values)e[a]=a;return e}extract(e,a=this._def){return t.create(e,{...this._def,...a})}exclude(e,a=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...a})}};vi.create=hA;var yi=class extends le{_parse(e){let a=pe.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==G.string&&r.parsedType!==G.number){let n=pe.objectValues(a);return z(r,{expected:pe.joinValues(n),received:r.parsedType,code:P.invalid_type}),J}if(this._cache||(this._cache=new Set(pe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=pe.objectValues(a);return z(r,{received:r.data,code:P.invalid_enum_value,options:n}),J}return Ht(e.data)}get enum(){return this._def.values}};yi.create=(t,e)=>new yi({values:t,typeName:ee.ZodNativeEnum,...se(e)});var go=class extends le{unwrap(){return this._def.type}_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==G.promise&&a.common.async===!1)return z(a,{code:P.invalid_type,expected:G.promise,received:a.parsedType}),J;let r=a.parsedType===G.promise?a.data:Promise.resolve(a.data);return Ht(r.then(n=>this._def.type.parseAsync(n,{path:a.path,errorMap:a.common.contextualErrorMap})))}};go.create=(t,e)=>new go({type:t,typeName:ee.ZodPromise,...se(e)});var Va=class extends le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ee.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:a,ctx:r}=this._processInputParams(e),n=this._def.effect||null,o={addIssue:i=>{z(r,i),i.fatal?a.abort():a.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),n.type==="preprocess"){let i=n.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async s=>{if(a.value==="aborted")return J;let l=await this._def.schema._parseAsync({data:s,path:r.path,parent:r});return l.status==="aborted"?J:l.status==="dirty"?ii(l.value):a.value==="dirty"?ii(l.value):l});{if(a.value==="aborted")return J;let s=this._def.schema._parseSync({data:i,path:r.path,parent:r});return s.status==="aborted"?J:s.status==="dirty"?ii(s.value):a.value==="dirty"?ii(s.value):s}}if(n.type==="refinement"){let i=s=>{let l=n.refinement(s,o);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?J:(s.status==="dirty"&&a.dirty(),i(s.value),{status:a.value,value:s.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>s.status==="aborted"?J:(s.status==="dirty"&&a.dirty(),i(s.value).then(()=>({status:a.value,value:s.value}))))}if(n.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!po(i))return J;let s=n.transform(i.value,o);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:a.value,value:s}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>po(i)?Promise.resolve(n.transform(i.value,o)).then(s=>({status:a.value,value:s})):J);pe.assertNever(n)}};Va.create=(t,e,a)=>new Va({schema:t,typeName:ee.ZodEffects,effect:e,...se(a)});Va.createWithPreprocess=(t,e,a)=>new Va({schema:e,effect:{type:"preprocess",transform:t},typeName:ee.ZodEffects,...se(a)});var za=class extends le{_parse(e){return this._getType(e)===G.undefined?Ht(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};za.create=(t,e)=>new za({innerType:t,typeName:ee.ZodOptional,...se(e)});var Lr=class extends le{_parse(e){return this._getType(e)===G.null?Ht(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Lr.create=(t,e)=>new Lr({innerType:t,typeName:ee.ZodNullable,...se(e)});var xi=class extends le{_parse(e){let{ctx:a}=this._processInputParams(e),r=a.data;return a.parsedType===G.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:a.path,parent:a})}removeDefault(){return this._def.innerType}};xi.create=(t,e)=>new xi({innerType:t,typeName:ee.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...se(e)});var bi=class extends le{_parse(e){let{ctx:a}=this._processInputParams(e),r={...a,common:{...a.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Ns(n)?n.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new sa(r.common.issues)},input:r.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new sa(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};bi.create=(t,e)=>new bi({innerType:t,typeName:ee.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...se(e)});var Vs=class extends le{_parse(e){if(this._getType(e)!==G.nan){let r=this._getOrReturnCtx(e);return z(r,{code:P.invalid_type,expected:G.nan,received:r.parsedType}),J}return{status:"valid",value:e.data}}};Vs.create=t=>new Vs({typeName:ee.ZodNaN,...se(t)});var WF=Symbol("zod_brand"),Xu=class extends le{_parse(e){let{ctx:a}=this._processInputParams(e),r=a.data;return this._def.type._parse({data:r,path:a.path,parent:a})}unwrap(){return this._def.type}},Ku=class t extends le{_parse(e){let{status:a,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?J:o.status==="dirty"?(a.dirty(),ii(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return n.status==="aborted"?J:n.status==="dirty"?(a.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,a){return new t({in:e,out:a,typeName:ee.ZodPipeline})}},Si=class extends le{_parse(e){let a=this._def.innerType._parse(e),r=n=>(po(n)&&(n.value=Object.freeze(n.value)),n);return Ns(a)?a.then(n=>r(n)):r(a)}unwrap(){return this._def.innerType}};Si.create=(t,e)=>new Si({innerType:t,typeName:ee.ZodReadonly,...se(e)});function cA(t,e){let a=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof a=="string"?{message:a}:a}function mA(t,e={},a){return t?mo.create().superRefine((r,n)=>{let o=t(r);if(o instanceof Promise)return o.then(i=>{if(!i){let s=cA(e,r),l=s.fatal??a??!0;n.addIssue({code:"custom",...s,fatal:l})}});if(!o){let i=cA(e,r),s=i.fatal??a??!0;n.addIssue({code:"custom",...i,fatal:s})}}):mo.create()}var ZF={object:la.lazycreate},ee;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(ee||(ee={}));var XF=(t,e={message:`Input not instance of ${t.name}`})=>mA(a=>a instanceof t,e),gA=ho.create,vA=si.create,KF=Vs.create,YF=li.create,yA=ui.create,QF=ci.create,JF=Hs.create,eH=di.create,tH=fi.create,aH=mo.create,rH=ln.create,nH=ur.create,oH=Us.create,iH=un.create,sH=la.create,lH=la.strictCreate,uH=pi.create,cH=Mp.create,dH=hi.create,fH=wr.create,pH=Op.create,hH=zs.create,mH=qs.create,gH=Dp.create,vH=mi.create,yH=gi.create,xH=vi.create,bH=yi.create,SH=go.create,_H=Va.create,CH=za.create,wH=Lr.create,LH=Va.createWithPreprocess,kH=Ku.create,IH=()=>gA().optional(),AH=()=>vA().optional(),EH=()=>yA().optional(),TH={string:(t=>ho.create({...t,coerce:!0})),number:(t=>si.create({...t,coerce:!0})),boolean:(t=>ui.create({...t,coerce:!0})),bigint:(t=>li.create({...t,coerce:!0})),date:(t=>ci.create({...t,coerce:!0}))};var RH=J;var xA=p.union([p.object({type:p.literal("data"),key:p.string(),value:p.string().optional()}),p.object({type:p.literal("css"),value:p.string()}),p.object({type:p.literal("aria"),role:p.string().optional(),label:p.string().optional()}),p.object({type:p.literal("shadow-css"),value:p.string()}),p.object({type:p.literal("ref"),el:p.any()})]),MH=p.object({kind:p.literal("tooltip"),id:p.string(),anchor:xA,content:p.object({title:p.string().optional(),body:p.string()}),placement:p.enum(["top","bottom","left","right","auto"]).optional(),offsetPx:p.number().optional(),blocking:p.boolean().optional(),trigger:p.enum(["immediate","hover","click"]).optional(),dismiss:p.object({onEsc:p.boolean().optional(),closeButton:p.boolean().optional(),timeoutMs:p.number().optional()}).optional()}),OH=p.object({kind:p.literal("highlight"),id:p.string(),anchor:xA,copy:p.string().optional(),ring:p.object({paddingPx:p.number().optional(),radiusPx:p.number().optional()}).optional(),scrim:p.object({opacity:p.number().optional()}).optional(),ringColor:p.string().optional(),blocking:p.boolean().optional(),dismiss:p.object({onClickOutside:p.boolean().optional(),onEsc:p.boolean().optional(),timeoutMs:p.number().optional()}).optional()}),ex=p.object({id:p.string(),version:p.number(),routes:p.array(p.string()).optional(),steps:p.array(p.union([MH,OH]))});function m8(t){return ex.parse(t)}var x8=({configUri:t,experiments:e,featureKey:a="smart-canvas-overlay-uri",credentials:r="include"}={})=>async()=>{let n=ny({configUri:t,experiments:e,featureKey:a});if(!n)throw new Error("SmartCanvas overlays: recipe URI missing (env + feature unset).");let o=await fetch(n,{credentials:r});if(!o.ok)throw new Error(`SmartCanvas overlays: failed to fetch recipe (${o.status})`);let i=await o.json();return ex.parse(i)};var Bp=Y(Ye(),1),bA=Y(ol(),1);function S8({element:t,children:e}){let[a,r]=(0,Bp.useState)(null);return(0,Bp.useLayoutEffect)(()=>{if(!t){r(null);return}return r(t.getMountNode()),()=>r(null)},[t]),a?(0,bA.createPortal)(e,a):null}function DH(){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e="";for(let a=0;a<16;a++)e+=t[Math.floor(Math.random()*t.length)];return e}var tx=class{constructor(){B(this,"sessionId");this.sessionId=DH(),console.log(`[Syntro Telemetry] Using noop adapter (no telemetry configured). sessionId=${this.sessionId}`)}trackCanvasOpened(e){}trackCanvasClosed(e){}trackRectangleViewed(e,a){}trackAction(e,a,r){}register(e){}getSessionId(){return this.sessionId}startSessionRecording(){}trackExperiment(e,a,r){}setPersonProperties(e){}setPersonPropertiesOnce(e){}getDistinctId(){return"demo-user"}getAllFeatureFlags(){return{}}getSegmentFlags(){return{}}track(e,a){}};function ax(){return new tx}var T=typeof window<"u"?window:void 0,Pt=typeof globalThis<"u"?globalThis:T;typeof self>"u"&&(Pt.self=Pt),typeof File>"u"&&(Pt.File=function(){});var gE=Array.prototype,SA=gE.forEach,_A=gE.indexOf,ka=Pt?.navigator,q=Pt?.document,Bt=Pt?.location,bx=Pt?.fetch,Sx=Pt!=null&&Pt.XMLHttpRequest&&"withCredentials"in new Pt.XMLHttpRequest?Pt.XMLHttpRequest:void 0,CA=Pt?.AbortController,ua=ka?.userAgent,Q=T??{},fn={DEBUG:!1,LIB_VERSION:"1.341.0"};function wA(t,e,a,r,n,o,i){try{var s=t[o](i),l=s.value}catch(u){return void a(u)}s.done?e(l):Promise.resolve(l).then(r,n)}function Zs(t){return function(){var e=this,a=arguments;return new Promise((function(r,n){var o=t.apply(e,a);function i(l){wA(o,r,n,i,s,"next",l)}function s(l){wA(o,r,n,i,s,"throw",l)}i(void 0)}))}}function j(){return j=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var a=arguments[e];for(var r in a)({}).hasOwnProperty.call(a,r)&&(t[r]=a[r])}return t},j.apply(null,arguments)}function vE(t,e){if(t==null)return{};var a={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;a[r]=t[r]}return a}var BH=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],LA=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var a=t.toLowerCase();return BH.concat(e).some((r=>{var n=r.toLowerCase();return a.indexOf(n)!==-1}))},PH=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"];function he(t,e){return t.indexOf(e)!==-1}var dh=function(t){return t.trim()},_x=function(t){return t.replace(/^\$/,"")},NH=Array.isArray,yE=Object.prototype,xE=yE.hasOwnProperty,fh=yE.toString,Ce=NH||function(t){return fh.call(t)==="[object Array]"},_o=t=>typeof t=="function",gt=t=>t===Object(t)&&!Ce(t),Xs=t=>{if(gt(t)){for(var e in t)if(xE.call(t,e))return!1;return!0}return!1},V=t=>t===void 0,vt=t=>fh.call(t)=="[object String]",Cx=t=>vt(t)&&t.trim().length===0,cr=t=>t===null,ge=t=>V(t)||cr(t),yn=t=>fh.call(t)=="[object Number]"&&t==t,Gs=t=>yn(t)&&t>0,vn=t=>fh.call(t)==="[object Boolean]",FH=t=>t instanceof FormData,HH=t=>he(PH,t);function wx(t){return t===null||typeof t!="object"}function Vp(t,e){return Object.prototype.toString.call(t)==="[object "+e+"]"}function bE(t){return!V(Event)&&(function(e,a){try{return e instanceof a}catch{return!1}})(t,Event)}var UH=[!0,"true",1,"1","yes"],rx=t=>he(UH,t),zH=[!1,"false",0,"0","no"];function Ir(t,e,a,r,n){return e>a&&(r.warn("min cannot be greater than max."),e=a),yn(t)?t>a?(r.warn(" cannot be greater than max: "+a+". Using max value instead."),a):t<e?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+a+", fallback: "+n),Ir(n||a,e,a,r))}var Lx=class{constructor(e){this.t={},this.i=e.i,this.o=Ir(e.bucketSize,0,100,e.h),this.m=Ir(e.refillRate,0,this.o,e.h),this.$=Ir(e.refillInterval,0,864e5,e.h)}S(e,a){var r=a-e.lastAccess,n=Math.floor(r/this.$);if(n>0){var o=n*this.m;e.tokens=Math.min(e.tokens+o,this.o),e.lastAccess=e.lastAccess+n*this.$}}consumeRateLimit(e){var a,r=Date.now(),n=String(e),o=this.t[n];return o?this.S(o,r):(o={tokens:this.o,lastAccess:r},this.t[n]=o),o.tokens===0||(o.tokens--,o.tokens===0&&((a=this.i)==null||a.call(this,e)),o.tokens===0)}stop(){this.t={}}},$a="Mobile",$p="iOS",gn="Android",vc="Tablet",SE=gn+" "+vc,_E="iPad",CE="Apple",wE=CE+" Watch",yc="Safari",Js="BlackBerry",LE="Samsung",kE=LE+"Browser",IE=LE+" Internet",Li="Chrome",qH=Li+" OS",AE=Li+" "+$p,Ob="Internet Explorer",EE=Ob+" "+$a,Db="Opera",VH=Db+" Mini",Bb="Edge",TE="Microsoft "+Bb,Ys="Firefox",RE=Ys+" "+$p,xc="Nintendo",bc="PlayStation",Qs="Xbox",ME=gn+" "+$a,OE=$a+" "+yc,ic="Windows",kx=ic+" Phone",kA="Nokia",Ix="Ouya",DE="Generic",$H=DE+" "+$a.toLowerCase(),BE=DE+" "+vc.toLowerCase(),Ax="Konqueror",Wt="(\\d+(\\.\\d+)?)",nx=new RegExp("Version/"+Wt),jH=new RegExp(Qs,"i"),GH=new RegExp(bc+" \\w+","i"),WH=new RegExp(xc+" \\w+","i"),Pb=new RegExp(Js+"|PlayBook|BB10","i"),ZH={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},Pp,IA,ox,XH=(t,e)=>e&&he(e,CE)||(function(a){return he(a,yc)&&!he(a,Li)&&!he(a,gn)})(t),PE=function(t,e){return e=e||"",he(t," OPR/")&&he(t,"Mini")?VH:he(t," OPR/")?Db:Pb.test(t)?Js:he(t,"IE"+$a)||he(t,"WPDesktop")?EE:he(t,kE)?IE:he(t,Bb)||he(t,"Edg/")?TE:he(t,"FBIOS")?"Facebook "+$a:he(t,"UCWEB")||he(t,"UCBrowser")?"UC Browser":he(t,"CriOS")?AE:he(t,"CrMo")||he(t,Li)?Li:he(t,gn)&&he(t,yc)?ME:he(t,"FxiOS")?RE:he(t.toLowerCase(),Ax.toLowerCase())?Ax:XH(t,e)?he(t,$a)?OE:yc:he(t,Ys)?Ys:he(t,"MSIE")||he(t,"Trident/")?Ob:he(t,"Gecko")?Ys:""},KH={[EE]:[new RegExp("rv:"+Wt)],[TE]:[new RegExp(Bb+"?\\/"+Wt)],[Li]:[new RegExp("("+Li+"|CrMo)\\/"+Wt)],[AE]:[new RegExp("CriOS\\/"+Wt)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Wt)],[yc]:[nx],[OE]:[nx],[Db]:[new RegExp("(Opera|OPR)\\/"+Wt)],[Ys]:[new RegExp(Ys+"\\/"+Wt)],[RE]:[new RegExp("FxiOS\\/"+Wt)],[Ax]:[new RegExp("Konqueror[:/]?"+Wt,"i")],[Js]:[new RegExp(Js+" "+Wt),nx],[ME]:[new RegExp("android\\s"+Wt,"i")],[IE]:[new RegExp(kE+"\\/"+Wt)],[Ob]:[new RegExp("(rv:|MSIE )"+Wt)],Mozilla:[new RegExp("rv:"+Wt)]},YH=function(t,e){var a=PE(t,e),r=KH[a];if(V(r))return null;for(var n=0;n<r.length;n++){var o=r[n],i=t.match(o);if(i)return parseFloat(i[i.length-2])}return null},AA=[[new RegExp(Qs+"; "+Qs+" (.*?)[);]","i"),t=>[Qs,t&&t[1]||""]],[new RegExp(xc,"i"),[xc,""]],[new RegExp(bc,"i"),[bc,""]],[Pb,[Js,""]],[new RegExp(ic,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[kx,""];if(new RegExp($a).test(e)&&!/IEMobile\b/.test(e))return[ic+" "+$a,""];var a=/Windows NT ([0-9.]+)/i.exec(e);if(a&&a[1]){var r=a[1],n=ZH[r]||"";return/arm/i.test(e)&&(n="RT"),[ic,n]}return[ic,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){var e=[t[3],t[4],t[5]||"0"];return[$p,e.join(".")]}return[$p,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=V(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+gn+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+gn+")","i"),t=>{if(t&&t[2]){var e=[t[2],t[3],t[4]||"0"];return[gn,e.join(".")]}return[gn,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];if(t&&t[1]){var a=[t[1],t[2],t[3]||"0"];e[1]=a.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[qH,""]],[/Linux|debian/i,["Linux",""]]],EA=function(t){return WH.test(t)?xc:GH.test(t)?bc:jH.test(t)?Qs:new RegExp(Ix,"i").test(t)?Ix:new RegExp("("+kx+"|WPDesktop)","i").test(t)?kx:/iPad/.test(t)?_E:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?wE:Pb.test(t)?Js:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(kA,"i").test(t)?kA:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp($a).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?gn:SE:new RegExp("(pda|"+$a+")","i").test(t)?$H:new RegExp(vc,"i").test(t)&&!new RegExp(vc+" pc","i").test(t)?BE:""},QH=t=>t instanceof Error;function JH(t){var e=globalThis._posthogChunkIds;if(e){var a=Object.keys(e);return ox&&a.length===IA||(IA=a.length,ox=a.reduce(((r,n)=>{Pp||(Pp={});var o=Pp[n];if(o)r[o[0]]=o[1];else for(var i=t(n),s=i.length-1;s>=0;s--){var l=i[s],u=l?.filename,c=e[n];if(u&&c){r[u]=c,Pp[n]=[u,c];break}}return r}),{})),ox}}var Ex=class{constructor(e,a,r){r===void 0&&(r=[]),this.coercers=e,this.stackParser=a,this.modifiers=r}buildFromUnknown(e,a){a===void 0&&(a={});var r=a&&a.mechanism||{handled:!0,type:"generic"},n=this.buildCoercingContext(r,a,0).apply(e),o=this.buildParsingContext(),i=this.parseStacktrace(n,o);return{$exception_list:this.convertToExceptionList(i,r),$exception_level:"error"}}modifyFrames(e){var a=this;return Zs((function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&Ce(r.stacktrace.frames)&&(r.stacktrace.frames=yield a.applyModifiers(r.stacktrace.frames));return e}))()}coerceFallback(e){var a;return{type:"Error",value:"Unknown error",stack:(a=e.syntheticException)==null?void 0:a.stack,synthetic:!0}}parseStacktrace(e,a){var r,n;return e.cause!=null&&(r=this.parseStacktrace(e.cause,a)),e.stack!=""&&e.stack!=null&&(n=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?1:0),a.chunkIdMap)),j({},e,{cause:r,stack:n})}applyChunkIds(e,a){return e.map((r=>(r.filename&&a&&(r.chunk_id=a[r.filename]),r)))}applyCoercers(e,a){for(var r of this.coercers)if(r.match(e))return r.coerce(e,a);return this.coerceFallback(a)}applyModifiers(e){var a=this;return Zs((function*(){var r=e;for(var n of a.modifiers)r=yield n(r);return r}))()}convertToExceptionList(e,a){var r,n,o,i={type:e.type,value:e.value,mechanism:{type:(r=a.type)!==null&&r!==void 0?r:"generic",handled:(n=a.handled)===null||n===void 0||n,synthetic:(o=e.synthetic)!==null&&o!==void 0&&o}};e.stack&&(i.stacktrace={type:"raw",frames:e.stack});var s=[i];return e.cause!=null&&s.push(...this.convertToExceptionList(e.cause,j({},a,{handled:!0}))),s}buildParsingContext(){return{chunkIdMap:JH(this.stackParser)}}buildCoercingContext(e,a,r){r===void 0&&(r=0);var n=(o,i)=>{if(i<=4){var s=this.buildCoercingContext(e,a,i);return this.applyCoercers(o,s)}};return j({},a,{syntheticException:r==0?a.syntheticException:void 0,mechanism:e,apply:o=>n(o,r),next:o=>n(o,r+1)})}},el="?";function Tx(t,e,a,r,n){var o={platform:t,filename:e,function:a==="<anonymous>"?el:a,in_app:!0};return V(r)||(o.lineno=r),V(n)||(o.colno=n),o}var NE=(t,e)=>{var a=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return a||r?[t.indexOf("@")!==-1?t.split("@")[0]:el,a?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},e3=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,t3=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,a3=/\((\S*)(?::(\d+))(?::(\d+))\)/,r3=(t,e)=>{var a=e3.exec(t);if(a){var[,r,n,o]=a;return Tx(e,r,el,+n,+o)}var i=t3.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var s=a3.exec(i[2]);s&&(i[2]=s[1],i[3]=s[2],i[4]=s[3])}var[l,u]=NE(i[1]||el,i[2]);return Tx(e,u,l,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},n3=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,o3=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,i3=(t,e)=>{var a=n3.exec(t);if(a){if(a[3]&&a[3].indexOf(" > eval")>-1){var r=o3.exec(a[3]);r&&(a[1]=a[1]||"eval",a[3]=r[1],a[4]=r[2],a[5]="")}var n=a[3],o=a[1]||el;return[o,n]=NE(o,n),Tx(e,n,o,a[4]?+a[4]:void 0,a[5]?+a[5]:void 0)}},TA=/\(error: (.*)\)/,RA=50;function s3(){return(function(t){for(var e=arguments.length,a=new Array(e>1?e-1:0),r=1;r<e;r++)a[r-1]=arguments[r];return function(n,o){o===void 0&&(o=0);for(var i=[],s=n.split(`
499
- `),l=o;l<s.length;l++){var u=s[l];if(!(u.length>1024)){var c=TA.test(u)?u.replace(TA,"$1"):u;if(!c.match(/\S*Error: /)){for(var d of a){var f=d(c,t);if(f){i.push(f);break}}if(i.length>=RA)break}}}return(function(h){if(!h.length)return[];var S=Array.from(h);return S.reverse(),S.slice(0,RA).map((x=>{return j({},x,{filename:x.filename||(b=S,b[b.length-1]||{}).filename,function:x.function||el});var b}))})(i)}})("web:javascript",r3,i3)}var Rx=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,a){var r=vt(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?a.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var a=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?a+": "+e.message:a}isDOMException(e){return Vp(e,"DOMException")}isDOMError(e){return Vp(e,"DOMError")}},Mx=class{match(e){return(a=>a instanceof Error)(e)}coerce(e,a){return{type:this.getType(e),value:this.getMessage(e,a),stack:this.getStack(e),cause:e.cause?a.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,a){var r=e.message;return r.error&&typeof r.error.message=="string"?String(r.error.message):String(r)}getStack(e){return e.stacktrace||e.stack||void 0}},Ox=class{constructor(){}match(e){return Vp(e,"ErrorEvent")&&e.error!=null}coerce(e,a){var r,n=a.apply(e.error);return n||{type:"ErrorEvent",value:e.message,stack:(r=a.syntheticException)==null?void 0:r.stack,synthetic:!0}}},l3=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,Dx=class{match(e){return typeof e=="string"}coerce(e,a){var r,[n,o]=this.getInfos(e);return{type:n??"Error",value:o??e,stack:(r=a.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(e){var a="Error",r=e,n=e.match(l3);return n&&(a=n[1],r=n[2]),[a,r]}},u3=["fatal","error","warning","log","info","debug"];function FE(t,e){e===void 0&&(e=40);var a=Object.keys(t);if(a.sort(),!a.length)return"[object has no keys]";for(var r=a.length;r>0;r--){var n=a.slice(0,r).join(", ");if(!(n.length>e))return r===a.length||n.length<=e?n:n.slice(0,e)+"..."}return""}var Bx=class{match(e){return typeof e=="object"&&e!==null}coerce(e,a){var r,n=this.getErrorPropertyFromObject(e);return n?a.apply(n):{type:this.getType(e),value:this.getValue(e),stack:(r=a.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return bE(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var a="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(a+=" with message: '"+e.message+"'"),a}if("message"in e&&typeof e.message=="string")return e.message;var r=this.getObjectClassName(e);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+FE(e)}isSeverityLevel(e){return vt(e)&&!Cx(e)&&u3.indexOf(e)>=0}getErrorPropertyFromObject(e){for(var a in e)if(Object.prototype.hasOwnProperty.call(e,a)){var r=e[a];if(QH(r))return r}}getObjectClassName(e){try{var a=Object.getPrototypeOf(e);return a?a.constructor.name:void 0}catch{return}}},Px=class{match(e){return bE(e)}coerce(e,a){var r,n=e.constructor.name;return{type:n,value:n+" captured as exception with keys: "+FE(e),stack:(r=a.syntheticException)==null?void 0:r.stack,synthetic:!0}}},Nx=class{match(e){return wx(e)}coerce(e,a){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(r=a.syntheticException)==null?void 0:r.stack,synthetic:!0}}},Fx=class{match(e){return Vp(e,"PromiseRejectionEvent")}coerce(e,a){var r,n=this.getUnhandledRejectionReason(e);return wx(n)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(n),stack:(r=a.syntheticException)==null?void 0:r.stack,synthetic:!0}:a.apply(n)}getUnhandledRejectionReason(e){if(wx(e))return e;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch{}return e}},HE=function(t,e){var{debugEnabled:a}=e===void 0?{}:e,r={k:function(n){if(T&&(fn.DEBUG||Q.POSTHOG_DEBUG||a)&&!V(T.console)&&T.console){for(var o=("__rrweb_original__"in T.console[n])?T.console[n].__rrweb_original__:T.console[n],i=arguments.length,s=new Array(i>1?i-1:0),l=1;l<i;l++)s[l-1]=arguments[l];o(t,...s)}},info:function(){for(var n=arguments.length,o=new Array(n),i=0;i<n;i++)o[i]=arguments[i];r.k("log",...o)},warn:function(){for(var n=arguments.length,o=new Array(n),i=0;i<n;i++)o[i]=arguments[i];r.k("warn",...o)},error:function(){for(var n=arguments.length,o=new Array(n),i=0;i<n;i++)o[i]=arguments[i];r.k("error",...o)},critical:function(){for(var n=arguments.length,o=new Array(n),i=0;i<n;i++)o[i]=arguments[i];console.error(t,...o)},uninitializedWarning:n=>{r.error("You must initialize PostHog before calling "+n)},createLogger:(n,o)=>HE(t+" "+n,o)};return r},$=HE("[PostHog.js]"),et=$.createLogger,c3=et("[ExternalScriptsLoader]"),MA=(t,e,a)=>{if(t.config.disable_external_dependency_loading)return c3.warn(e+" was requested but loading of external scripts is disabled."),a("Loading of external scripts is disabled");var r=q?.querySelectorAll("script");if(r){for(var n,o=function(){if(r[i].src===e){var l=r[i];return l.__posthog_loading_callback_fired?{v:a()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,a(void 0,u)})),l.onerror=u=>a(u),{v:void 0})}},i=0;i<r.length;i++)if(n=o())return n.v}var s=()=>{if(!q)return a("document not found");var l=q.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,a(void 0,d)},l.onerror=d=>a(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return a("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")q.head.appendChild(l);else{var u,c=q.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):q.body.appendChild(l)}};q!=null&&q.body?s():q?.addEventListener("DOMContentLoaded",s)};Q.__PosthogExtensions__=Q.__PosthogExtensions__||{},Q.__PosthogExtensions__.loadExternalDependency=(t,e,a)=>{var r="/static/"+e+".js?v="+t.version;if(e==="remote-config"&&(r="/array/"+t.config.token+"/config.js"),e==="toolbar"){var n=3e5;r=r+"&t="+Math.floor(Date.now()/n)*n}var o=t.requestRouter.endpointFor("assets",r);MA(t,o,a)},Q.__PosthogExtensions__.loadSiteApp=(t,e,a)=>{var r=t.requestRouter.endpointFor("api",e);MA(t,r,a)};var jp={};function Co(t,e,a){if(Ce(t)){if(SA&&t.forEach===SA)t.forEach(e,a);else if("length"in t&&t.length===+t.length){for(var r=0,n=t.length;r<n;r++)if(r in t&&e.call(a,t[r],r)===jp)return}}}function Be(t,e,a){if(!ge(t)){if(Ce(t))return Co(t,e,a);if(FH(t)){for(var r of t.entries())if(e.call(a,r[1],r[0])===jp)return}else for(var n in t)if(xE.call(t,n)&&e.call(a,t[n],n)===jp)return}}var ot=function(t){for(var e=arguments.length,a=new Array(e>1?e-1:0),r=1;r<e;r++)a[r-1]=arguments[r];return Co(a,(function(n){for(var o in n)n[o]!==void 0&&(t[o]=n[o])})),t},al=function(t){for(var e=arguments.length,a=new Array(e>1?e-1:0),r=1;r<e;r++)a[r-1]=arguments[r];return Co(a,(function(n){Co(n,(function(o){t.push(o)}))})),t};function zp(t){for(var e=Object.keys(t),a=e.length,r=new Array(a);a--;)r[a]=[e[a],t[e[a]]];return r}var OA=function(t){try{return t()}catch{return}},d3=function(t){return function(){try{for(var e=arguments.length,a=new Array(e),r=0;r<e;r++)a[r]=arguments[r];return t.apply(this,a)}catch(n){$.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),$.critical(n)}}},Nb=function(t){var e={};return Be(t,(function(a,r){(vt(a)&&a.length>0||yn(a))&&(e[r]=a)})),e};function f3(t,e){return a=t,r=o=>vt(o)&&!cr(e)?o.slice(0,e):o,n=new Set,(function o(i,s){return i!==Object(i)?r?r(i,s):i:n.has(i)?void 0:(n.add(i),Ce(i)?(l=[],Co(i,(u=>{l.push(o(u))}))):(l={},Be(i,((u,c)=>{n.has(u)||(l[c]=o(u,c))}))),l);var l})(a);var a,r,n}var p3=["herokuapp.com","vercel.app","netlify.app"];function h3(t){var e=t?.hostname;if(!vt(e))return!1;var a=e.split(".").slice(-2).join(".");for(var r of p3)if(a===r)return!1;return!0}function UE(t,e){for(var a=0;a<t.length;a++)if(e(t[a]))return t[a]}function ft(t,e,a,r){var{capture:n=!1,passive:o=!0}=r??{};t?.addEventListener(e,a,{capture:n,passive:o})}var zE="$people_distinct_id",sc="__alias",lc="__timers",DA="$autocapture_disabled_server_side",Hx="$heatmaps_enabled_server_side",BA="$exception_capture_enabled_server_side",Ux="$error_tracking_suppression_rules",PA="$error_tracking_capture_extension_exceptions",NA="$web_vitals_enabled_server_side",qE="$dead_clicks_enabled_server_side",FA="$product_tours_enabled_server_side",HA="$web_vitals_allowed_metrics",ix="$session_recording_remote_config",Gp="$sesid",VE="$session_is_sampled",Ks="$enabled_feature_flags",uc="$early_access_features",zx="$feature_flag_details",cc="$stored_person_properties",wi="$stored_group_properties",qx="$surveys",Wp="$flag_call_reported",pn="$user_state",Vx="$client_session_props",$x="$capture_rate_limit",jx="$initial_campaign_params",Gx="$initial_referrer_info",Zp="$initial_person_info",Xp="$epp",$E="__POSTHOG_TOOLBAR__",Yu="$posthog_cookieless",m3=[zE,sc,"__cmpns",lc,"$session_recording_enabled_server_side",Hx,Gp,Ks,Ux,pn,uc,zx,wi,cc,qx,Wp,Vx,$x,jx,Gx,Xp,Zp,"$conversations_widget_session_id","$conversations_ticket_id","$conversations_widget_state","$conversations_user_traits"];function UA(t){return t instanceof Element&&(t.id===$E||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function ph(t){return!!t&&t.nodeType===1}function wo(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function jE(t){return!!t&&t.nodeType===3}function GE(t){return!!t&&t.nodeType===11}function Fb(t){return t?dh(t).split(/\s+/):[]}function zA(t){var e=T?.location.href;return!!(e&&t&&t.some((a=>e.match(a))))}function Kp(t){var e="";switch(typeof t.className){case"string":e=t.className;break;case"object":e=(t.className&&"baseVal"in t.className?t.className.baseVal:null)||t.getAttribute("class")||"";break;default:e=""}return Fb(e)}function WE(t){return ge(t)?null:dh(t).split(/(\s+)/).filter((e=>Sc(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Cc(t){var e="";return Wx(t)&&!QE(t)&&t.childNodes&&t.childNodes.length&&Be(t.childNodes,(function(a){var r;jE(a)&&a.textContent&&(e+=(r=WE(a.textContent))!==null&&r!==void 0?r:"")})),dh(e)}function ZE(t){return V(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null;var e}var Hb=["a","button","form","input","select","textarea","label"];function XE(t,e){if(V(e))return!0;var a,r=function(o){if(e.some((i=>o.matches(i))))return{v:!0}};for(var n of t)if(a=r(n))return a.v;return!1}function KE(t){var e=t.parentNode;return!(!e||!ph(e))&&e}var g3=["next","previous","prev",">","<"],qA=10,VA=[".ph-no-rageclick",".ph-no-capture"];function v3(t,e){if(!T||Ub(t))return!1;var a,r,n;if(vn(e)?(a=!!e&&VA,r=void 0):(a=(n=e?.css_selector_ignorelist)!==null&&n!==void 0?n:VA,r=e?.content_ignorelist),a===!1)return!1;var{targetElementList:o}=YE(t,!1);return!(function(i,s){if(i===!1||V(i))return!1;var l;if(i===!0)l=g3;else{if(!Ce(i))return!1;if(i.length>qA)return $.error("[PostHog] content_ignorelist array cannot exceed "+qA+" items. Use css_selector_ignorelist for more complex matching."),!1;l=i.map((u=>u.toLowerCase()))}return s.some((u=>{var{safeText:c,ariaLabel:d}=u;return l.some((f=>c.includes(f)||d.includes(f)))}))})(r,o.map((i=>{var s;return{safeText:Cc(i).toLowerCase(),ariaLabel:((s=i.getAttribute("aria-label"))==null?void 0:s.toLowerCase().trim())||""}})))&&!XE(o,a)}var Ub=t=>!t||wo(t,"html")||!ph(t),YE=(t,e)=>{if(!T||Ub(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var a=!1,r=[t],n=t;n.parentNode&&!wo(n,"body");)if(GE(n.parentNode))r.push(n.parentNode.host),n=n.parentNode.host;else{var o=KE(n);if(!o)break;if(e||Hb.indexOf(o.tagName.toLowerCase())>-1)a=!0;else{var i=T.getComputedStyle(o);i&&i.getPropertyValue("cursor")==="pointer"&&(a=!0)}r.push(o),n=o}return{parentIsUsefulElement:a,targetElementList:r}};function y3(t,e,a,r,n){var o,i,s,l;if(a===void 0&&(a=void 0),!T||Ub(t)||(o=a)!=null&&o.url_allowlist&&!zA(a.url_allowlist)||(i=a)!=null&&i.url_ignorelist&&zA(a.url_ignorelist))return!1;if((s=a)!=null&&s.dom_event_allowlist){var u=a.dom_event_allowlist;if(u&&!u.some((S=>e.type===S)))return!1}var{parentIsUsefulElement:c,targetElementList:d}=YE(t,r);if(!(function(S,x){var b=x?.element_allowlist;if(V(b))return!0;var g,m=function(v){if(b.some((C=>v.tagName.toLowerCase()===C)))return{v:!0}};for(var y of S)if(g=m(y))return g.v;return!1})(d,a)||!XE(d,(l=a)==null?void 0:l.css_selector_allowlist))return!1;var f=T.getComputedStyle(t);if(f&&f.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;var h=t.tagName.toLowerCase();switch(h){case"html":return!1;case"form":return(n||["submit"]).indexOf(e.type)>=0;case"input":case"select":case"textarea":return(n||["change","click"]).indexOf(e.type)>=0;default:return c?(n||["click"]).indexOf(e.type)>=0:(n||["click"]).indexOf(e.type)>=0&&(Hb.indexOf(h)>-1||t.getAttribute("contenteditable")==="true")}}function Wx(t){for(var e=t;e.parentNode&&!wo(e,"body");e=e.parentNode){var a=Kp(e);if(he(a,"ph-sensitive")||he(a,"ph-no-capture"))return!1}if(he(Kp(t),"ph-include"))return!0;var r=t.type||"";if(vt(r))switch(r.toLowerCase()){case"hidden":case"password":return!1}var n=t.name||t.id||"";return!(vt(n)&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(n.replace(/[^a-zA-Z0-9]/g,"")))}function QE(t){return!!(wo(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||wo(t,"select")||wo(t,"textarea")||t.getAttribute("contenteditable")==="true")}var JE="(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})",x3=new RegExp("^(?:"+JE+")$"),b3=new RegExp(JE),eT="\\d{3}-?\\d{2}-?\\d{4}",S3=new RegExp("^("+eT+")$"),_3=new RegExp("("+eT+")");function Sc(t,e){return e===void 0&&(e=!0),!(ge(t)||vt(t)&&(t=dh(t),(e?x3:b3).test((t||"").replace(/[- ]/g,""))||(e?S3:_3).test(t)))}function tT(t){var e=Cc(t);return Sc(e=(e+" "+aT(t)).trim())?e:""}function aT(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Be(t.childNodes,(function(a){var r;if(a&&((r=a.tagName)==null?void 0:r.toLowerCase())==="span")try{var n=Cc(a);e=(e+" "+n).trim(),a.childNodes&&a.childNodes.length&&(e=(e+" "+aT(a)).trim())}catch(o){$.error("[AutoCapture]",o)}})),e}function C3(t){return(function(e){var a=e.map((r=>{var n,o,i="";if(r.tag_name&&(i+=r.tag_name),r.attr_class)for(var s of(r.attr_class.sort(),r.attr_class))i+="."+s.replace(/"/g,"");var l=j({},r.text?{text:r.text}:{},{"nth-child":(n=r.nth_child)!==null&&n!==void 0?n:0,"nth-of-type":(o=r.nth_of_type)!==null&&o!==void 0?o:0},r.href?{href:r.href}:{},r.attr_id?{attr_id:r.attr_id}:{},r.attributes),u={};return zp(l).sort(((c,d)=>{var[f]=c,[h]=d;return f.localeCompare(h)})).forEach((c=>{var[d,f]=c;return u[$A(d.toString())]=$A(f.toString())})),i+=":",i+=zp(u).map((c=>{var[d,f]=c;return d+'="'+f+'"'})).join("")}));return a.join(";")})((function(e){return e.map((a=>{var r,n,o={text:(r=a.$el_text)==null?void 0:r.slice(0,400),tag_name:a.tag_name,href:(n=a.attr__href)==null?void 0:n.slice(0,2048),attr_class:w3(a),attr_id:a.attr__id,nth_child:a.nth_child,nth_of_type:a.nth_of_type,attributes:{}};return zp(a).filter((i=>{var[s]=i;return s.indexOf("attr__")===0})).forEach((i=>{var[s,l]=i;return o.attributes[s]=l})),o}))})(t))}function $A(t){return t.replace(/"|\\"/g,'\\"')}function w3(t){var e=t.attr__class;return e?Ce(e)?e:Fb(e):void 0}var Yp=class{constructor(e){this.disabled=e===!1;var a=gt(e)?e:{};this.thresholdPx=a.threshold_px||30,this.timeoutMs=a.timeout_ms||1e3,this.clickCount=a.click_count||3,this.clicks=[]}isRageClick(e,a,r){if(this.disabled)return!1;var n=this.clicks[this.clicks.length-1];if(n&&Math.abs(e-n.x)+Math.abs(a-n.y)<this.thresholdPx&&r-n.timestamp<this.timeoutMs){if(this.clicks.push({x:e,y:a,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:a,timestamp:r}];return!1}},Qp=t=>{var e=q?.createElement("a");return V(e)?null:(e.href=t,e)},L3=function(t,e){var a,r;e===void 0&&(e="&");var n=[];return Be(t,(function(o,i){V(o)||V(i)||i==="undefined"||(a=encodeURIComponent((s=>s instanceof File)(o)?o.name:o.toString()),r=encodeURIComponent(i),n[n.length]=r+"="+a)})),n.join(e)},Jp=function(t,e){for(var a,r=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),n=0;n<r.length;n++){var o=r[n].split("=");if(o[0]===e){a=o;break}}if(!Ce(a)||a.length<2)return"";var i=a[1];try{i=decodeURIComponent(i)}catch{$.error("Skipping decoding for malformed query param: "+i)}return i.replace(/\+/g," ")},wc=function(t,e,a){if(!t||!e||!e.length)return t;for(var r=t.split("#"),n=r[0]||"",o=r[1],i=n.split("?"),s=i[1],l=i[0],u=(s||"").split("&"),c=[],d=0;d<u.length;d++){var f=u[d].split("=");Ce(f)&&(e.includes(f[0])?c.push(f[0]+"="+a):c.push(u[d]))}var h=l;return s!=null&&(h+="?"+c.join("&")),o!=null&&(h+="#"+o),h},eh=function(t,e){var a=t.match(new RegExp(e+"=([^&]*)"));return a?a[1]:null},sx="$copy_autocapture",jA=et("[AutoCapture]");function lx(t,e){return e.length>t?e.slice(0,t)+"...":e}function k3(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!ph(e));return e}function I3(t,e,a,r){var n=t.tagName.toLowerCase(),o={tag_name:n};Hb.indexOf(n)>-1&&!a&&(n.toLowerCase()==="a"||n.toLowerCase()==="button"?o.$el_text=lx(1024,tT(t)):o.$el_text=lx(1024,Cc(t)));var i=Kp(t);i.length>0&&(o.classes=i.filter((function(c){return c!==""}))),Be(t.attributes,(function(c){var d;if((!QE(t)||["name","id","class","aria-label"].indexOf(c.name)!==-1)&&(r==null||!r.includes(c.name))&&!e&&Sc(c.value)&&(d=c.name,!vt(d)||d.substring(0,10)!=="_ngcontent"&&d.substring(0,7)!=="_nghost")){var f=c.value;c.name==="class"&&(f=Fb(f).join(" ")),o["attr__"+c.name]=lx(1024,f)}}));for(var s=1,l=1,u=t;u=k3(u);)s++,u.tagName===t.tagName&&l++;return o.nth_child=s,o.nth_of_type=l,o}function A3(t,e){for(var a,r,{e:n,maskAllElementAttributes:o,maskAllText:i,elementAttributeIgnoreList:s,elementsChainAsString:l}=e,u=[t],c=t;c.parentNode&&!wo(c,"body");)GE(c.parentNode)?(u.push(c.parentNode.host),c=c.parentNode.host):(u.push(c.parentNode),c=c.parentNode);var d,f=[],h={},S=!1,x=!1;if(Be(u,(v=>{var C=Wx(v);v.tagName.toLowerCase()==="a"&&(S=v.getAttribute("href"),S=C&&S&&Sc(S)&&S),he(Kp(v),"ph-no-capture")&&(x=!0),f.push(I3(v,o,i,s));var w=(function(_){if(!Wx(_))return{};var L={};return Be(_.attributes,(function(A){if(A.name&&A.name.indexOf("data-ph-capture-attribute")===0){var I=A.name.replace("data-ph-capture-attribute-",""),R=A.value;I&&R&&Sc(R)&&(L[I]=R)}})),L})(v);ot(h,w)})),x)return{props:{},explicitNoCapture:x};if(i||(t.tagName.toLowerCase()==="a"||t.tagName.toLowerCase()==="button"?f[0].$el_text=tT(t):f[0].$el_text=Cc(t)),S){var b,g;f[0].attr__href=S;var m=(b=Qp(S))==null?void 0:b.host,y=T==null||(g=T.location)==null?void 0:g.host;m&&y&&m!==y&&(d=S)}return{props:ot({$event_type:n.type,$ce_version:1},l?{}:{$elements:f},{$elements_chain:C3(f)},(a=f[0])!=null&&a.$el_text?{$el_text:(r=f[0])==null?void 0:r.$el_text}:{},d&&n.type==="click"?{$external_click_url:d}:{},h)}}var Zx=class{constructor(e){this.P=!1,this.T=null,this.I=!1,this.instance=e,this.rageclicks=new Yp(e.config.rageclick),this.C=null}get R(){var e,a,r=gt(this.instance.config.autocapture)?this.instance.config.autocapture:{};return r.url_allowlist=(e=r.url_allowlist)==null?void 0:e.map((n=>new RegExp(n))),r.url_ignorelist=(a=r.url_ignorelist)==null?void 0:a.map((n=>new RegExp(n))),r}F(){if(this.isBrowserSupported()){if(T&&q){var e=r=>{r=r||T?.event;try{this.O(r)}catch(n){jA.error("Failed to capture event",n)}};if(ft(q,"submit",e,{capture:!0}),ft(q,"change",e,{capture:!0}),ft(q,"click",e,{capture:!0}),this.R.capture_copied_text){var a=r=>{r=r||T?.event,this.O(r,sx)};ft(q,"copy",a,{capture:!0}),ft(q,"cut",a,{capture:!0})}}}else jA.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.P&&(this.F(),this.P=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this.I=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[DA]:!!e.autocapture_opt_out}),this.T=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this.C=e}getElementSelectors(e){var a,r=[];return(a=this.C)==null||a.forEach((n=>{var o=q?.querySelectorAll(n);o?.forEach((i=>{e===i&&r.push(n)}))})),r}get isEnabled(){var e,a,r=(e=this.instance.persistence)==null?void 0:e.props[DA],n=this.T;if(cr(n)&&!vn(r)&&!this.instance.M())return!1;var o=(a=this.T)!==null&&a!==void 0?a:!!r;return!!this.instance.config.autocapture&&!o}O(e,a){if(a===void 0&&(a="$autocapture"),this.isEnabled){var r,n=ZE(e);jE(n)&&(n=n.parentNode||null),a==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&this.instance.config.rageclick&&(r=this.rageclicks)!=null&&r.isRageClick(e.clientX,e.clientY,e.timeStamp||new Date().getTime())&&v3(n,this.instance.config.rageclick)&&this.O(e,"$rageclick");var o=a===sx;if(n&&y3(n,e,this.R,o,o?["copy","cut"]:void 0)){var{props:i,explicitNoCapture:s}=A3(n,{e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.R.element_attribute_ignorelist,elementsChainAsString:this.I});if(s)return!1;var l=this.getElementSelectors(n);if(l&&l.length>0&&(i.$element_selectors=l),a===sx){var u,c=WE(T==null||(u=T.getSelection())==null?void 0:u.toString()),d=e.type||"clipboard";if(!c)return!1;i.$selected_content=c,i.$copy_type=d}return this.instance.capture(a,i),!0}}}isBrowserSupported(){return _o(q?.querySelectorAll)}};Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return yn(t)&&isFinite(t)&&Math.floor(t)===t});var GA="0123456789abcdef",Xx=class t{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,a,r,n){if(!Number.isInteger(e)||!Number.isInteger(a)||!Number.isInteger(r)||!Number.isInteger(n)||e<0||a<0||r<0||n<0||e>0xffffffffffff||a>4095||r>1073741823||n>4294967295)throw new RangeError("invalid field value");var o=new Uint8Array(16);return o[0]=e/Math.pow(2,40),o[1]=e/Math.pow(2,32),o[2]=e/Math.pow(2,24),o[3]=e/Math.pow(2,16),o[4]=e/Math.pow(2,8),o[5]=e,o[6]=112|a>>>8,o[7]=a,o[8]=128|r>>>24,o[9]=r>>>16,o[10]=r>>>8,o[11]=r,o[12]=n>>>24,o[13]=n>>>16,o[14]=n>>>8,o[15]=n,new t(o)}toString(){for(var e="",a=0;a<this.bytes.length;a++)e=e+GA.charAt(this.bytes[a]>>>4)+GA.charAt(15&this.bytes[a]),a!==3&&a!==5&&a!==7&&a!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new t(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var a=0;a<16;a++){var r=this.bytes[a]-e.bytes[a];if(r!==0)return Math.sign(r)}return 0}},Kx=class{constructor(){this.A=0,this.j=0,this.D=new Yx}generate(){var e=this.generateOrAbort();if(V(e)){this.A=0;var a=this.generateOrAbort();if(V(a))throw new Error("Could not generate UUID after timestamp reset");return a}return e}generateOrAbort(){var e=Date.now();if(e>this.A)this.A=e,this.L();else{if(!(e+1e4>this.A))return;this.j++,this.j>4398046511103&&(this.A++,this.L())}return Xx.fromFieldsV7(this.A,Math.trunc(this.j/Math.pow(2,30)),this.j&Math.pow(2,30)-1,this.D.nextUint32())}L(){this.j=1024*this.D.nextUint32()+(1023&this.D.nextUint32())}},WA,rT=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;e<t.length;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};T&&!V(T.crypto)&&crypto.getRandomValues&&(rT=t=>crypto.getRandomValues(t));var Yx=class{constructor(){this.N=new Uint32Array(8),this.U=1/0}nextUint32(){return this.U>=this.N.length&&(rT(this.N),this.U=0),this.N[this.U++]}},So=()=>E3().toString(),E3=()=>(WA||(WA=new Kx)).generate(),Qu="",T3=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function R3(t,e){if(e){var a=(function(n,o){if(o===void 0&&(o=q),Qu)return Qu;if(!o||["localhost","127.0.0.1"].includes(n))return"";for(var i=n.split("."),s=Math.min(i.length,8),l="dmn_chk_"+So();!Qu&&s--;){var u=i.slice(s).join("."),c=l+"=1;domain=."+u+";path=/";o.cookie=c+";max-age=3",o.cookie.includes(l)&&(o.cookie=c+";max-age=0",Qu=u)}return Qu})(t);if(!a){var r=(n=>{var o=n.match(T3);return o?o[0]:""})(t);r!==a&&$.info("Warning: cookie subdomain discovery mismatch",r,a),a=r}return a?"; domain=."+a:""}return""}var kr={H:()=>!!q,B:function(t){$.error("cookieStore error: "+t)},q:function(t){if(q){try{for(var e=t+"=",a=q.cookie.split(";").filter((o=>o.length)),r=0;r<a.length;r++){for(var n=a[r];n.charAt(0)==" ";)n=n.substring(1,n.length);if(n.indexOf(e)===0)return decodeURIComponent(n.substring(e.length,n.length))}}catch{}return null}},W:function(t){var e;try{e=JSON.parse(kr.q(t))||{}}catch{}return e},G:function(t,e,a,r,n){if(q)try{var o="",i="",s=R3(q.location.hostname,r);if(a){var l=new Date;l.setTime(l.getTime()+24*a*60*60*1e3),o="; expires="+l.toUTCString()}n&&(i="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+o+"; SameSite=Lax; path=/"+s+i;return u.length>3686.4&&$.warn("cookieStore warning: large cookie, len="+u.length),q.cookie=u,u}catch{return}},V:function(t,e){if(q!=null&&q.cookie)try{kr.G(t,"",-1,e)}catch{return}}},ux=null,Ke={H:function(){if(!cr(ux))return ux;var t=!0;if(V(T))t=!1;else try{var e="__mplssupport__";Ke.G(e,"xyz"),Ke.q(e)!=='"xyz"'&&(t=!1),Ke.V(e)}catch{t=!1}return t||$.error("localStorage unsupported; falling back to cookie store"),ux=t,t},B:function(t){$.error("localStorage error: "+t)},q:function(t){try{return T?.localStorage.getItem(t)}catch(e){Ke.B(e)}return null},W:function(t){try{return JSON.parse(Ke.q(t))||{}}catch{}return null},G:function(t,e){try{T?.localStorage.setItem(t,JSON.stringify(e))}catch(a){Ke.B(a)}},V:function(t){try{T?.localStorage.removeItem(t)}catch(e){Ke.B(e)}}},M3=["$device_id","distinct_id",Gp,VE,Xp,Zp],Np={},O3={H:function(){return!0},B:function(t){$.error("memoryStorage error: "+t)},q:function(t){return Np[t]||null},W:function(t){return Np[t]||null},G:function(t,e){Np[t]=e},V:function(t){delete Np[t]}},_i=null,Dt={H:function(){if(!cr(_i))return _i;if(_i=!0,V(T))_i=!1;else try{var t="__support__";Dt.G(t,"xyz"),Dt.q(t)!=='"xyz"'&&(_i=!1),Dt.V(t)}catch{_i=!1}return _i},B:function(t){$.error("sessionStorage error: ",t)},q:function(t){try{return T?.sessionStorage.getItem(t)}catch(e){Dt.B(e)}return null},W:function(t){try{return JSON.parse(Dt.q(t))||null}catch{}return null},G:function(t,e){try{T?.sessionStorage.setItem(t,JSON.stringify(e))}catch(a){Dt.B(a)}},V:function(t){try{T?.sessionStorage.removeItem(t)}catch(e){Dt.B(e)}}},hn=(function(t){return t[t.PENDING=-1]="PENDING",t[t.DENIED=0]="DENIED",t[t.GRANTED=1]="GRANTED",t})({}),Qx=class{constructor(e){this._instance=e}get R(){return this._instance.config}get consent(){return this.J()?hn.DENIED:this.K}isOptedOut(){return this.R.cookieless_mode==="always"||this.consent===hn.DENIED||this.consent===hn.PENDING&&(this.R.opt_out_capturing_by_default||this.R.cookieless_mode==="on_reject")}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===hn.DENIED}optInOut(e){this.Y.G(this.X,e?1:0,this.R.cookie_expiration,this.R.cross_subdomain_cookie,this.R.secure_cookie)}reset(){this.Y.V(this.X,this.R.cross_subdomain_cookie)}get X(){var{token:e,opt_out_capturing_cookie_prefix:a,consent_persistence_name:r}=this._instance.config;return r||(a?a+e:"__ph_opt_in_out_"+e)}get K(){var e=this.Y.q(this.X);return rx(e)?hn.GRANTED:he(zH,e)?hn.DENIED:hn.PENDING}get Y(){if(!this.Z){var e=this.R.opt_out_capturing_persistence_type;this.Z=e==="localStorage"?Ke:kr;var a=e==="localStorage"?kr:Ke;a.q(this.X)&&(this.Z.q(this.X)||this.optInOut(rx(a.q(this.X))),a.V(this.X,this.R.cross_subdomain_cookie))}return this.Z}J(){return!!this.R.respect_dnt&&!!UE([ka?.doNotTrack,ka?.msDoNotTrack,Q.doNotTrack],(e=>rx(e)))}},Fp=et("[Dead Clicks]"),D3=()=>!0,B3=t=>{var e,a=!((e=t.instance.persistence)==null||!e.get_property(qE)),r=t.instance.config.capture_dead_clicks;return vn(r)?r:!!gt(r)||a},th=class{get lazyLoadedDeadClicksAutocapture(){return this.tt}constructor(e,a,r){this.instance=e,this.isEnabled=a,this.onCapture=r,this.startIfEnabled()}onRemoteConfig(e){this.instance.persistence&&this.instance.persistence.register({[qE]:e?.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.it((()=>{this.et()}))}it(e){var a,r;(a=Q.__PosthogExtensions__)!=null&&a.initDeadClicksAutocapture&&e(),(r=Q.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",(n=>{n?Fp.error("failed to load script",n):e()}))}et(){var e;if(q){if(!this.tt&&(e=Q.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var a=gt(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};a.__onCapture=this.onCapture,this.tt=Q.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,a),this.tt.start(q),Fp.info("starting...")}}else Fp.error("`document` not found. Cannot start.")}stop(){this.tt&&(this.tt.stop(),this.tt=void 0,Fp.info("stopping..."))}},Ju=et("[ExceptionAutocapture]"),Jx=class{constructor(e){var a,r,n;this.rt=()=>{var o;if(T&&this.isEnabled&&(o=Q.__PosthogExtensions__)!=null&&o.errorWrappingFunctions){var i=Q.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,s=Q.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,l=Q.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.st&&this.R.capture_unhandled_errors&&(this.st=i(this.captureException.bind(this))),!this.nt&&this.R.capture_unhandled_rejections&&(this.nt=s(this.captureException.bind(this))),!this.ot&&this.R.capture_console_errors&&(this.ot=l(this.captureException.bind(this)))}catch(u){Ju.error("failed to start",u),this.ut()}}},this._instance=e,this.ht=!((a=this._instance.persistence)==null||!a.props[BA]),this.dt=new Lx({refillRate:(r=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(n=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&n!==void 0?n:10,refillInterval:1e4,h:Ju}),this.R=this.vt(),this.startIfEnabledOrStop()}vt(){var e=this._instance.config.capture_exceptions,a={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return gt(e)?a=j({},a,e):(V(e)?this.ht:e)&&(a=j({},a,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),a}get isEnabled(){return this.R.capture_console_errors||this.R.capture_unhandled_errors||this.R.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ju.info("enabled"),this.ut(),this.it(this.rt)):this.ut()}it(e){var a,r;(a=Q.__PosthogExtensions__)!=null&&a.errorWrappingFunctions&&e(),(r=Q.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"exception-autocapture",(n=>{if(n)return Ju.error("failed to load script",n);e()}))}ut(){var e,a,r;(e=this.st)==null||e.call(this),this.st=void 0,(a=this.nt)==null||a.call(this),this.nt=void 0,(r=this.ot)==null||r.call(this),this.ot=void 0}onRemoteConfig(e){var a=e.autocaptureExceptions;this.ht=!!a||!1,this._instance.persistence&&this._instance.persistence.register({[BA]:this.ht}),this.R=this.vt(),this.startIfEnabledOrStop()}onConfigChange(){this.R=this.vt()}captureException(e){var a,r,n=(a=e==null||(r=e.$exception_list)==null||(r=r[0])==null?void 0:r.type)!==null&&a!==void 0?a:"Exception";this.dt.consumeRateLimit(n)?Ju.info("Skipping exception capture because of client rate limiting.",{exception:n}):this._instance.exceptions.sendExceptionEvent(e)}};function ZA(t,e,a){try{if(!(e in t))return()=>{};var r=t[e],n=a(r);return _o(n)&&(n.prototype=n.prototype||{},Object.defineProperties(n,{__posthog_wrapped__:{enumerable:!1,value:!0}})),t[e]=n,()=>{t[e]=r}}catch{return()=>{}}}var eb=class{constructor(e){var a;this._instance=e,this.ct=(T==null||(a=T.location)==null?void 0:a.pathname)||""}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&($.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.ft&&this.ft(),this.ft=void 0,$.info("History API monitoring stopped")}monitorHistoryChanges(){var e,a;if(T&&T.history){var r=this;(e=T.history.pushState)!=null&&e.__posthog_wrapped__||ZA(T.history,"pushState",(n=>function(o,i,s){n.call(this,o,i,s),r._t("pushState")})),(a=T.history.replaceState)!=null&&a.__posthog_wrapped__||ZA(T.history,"replaceState",(n=>function(o,i,s){n.call(this,o,i,s),r._t("replaceState")})),this.bt()}}_t(e){try{var a,r=T==null||(a=T.location)==null?void 0:a.pathname;if(!r)return;r!==this.ct&&this.isEnabled&&this._instance.capture("$pageview",{navigation_type:e}),this.ct=r}catch(n){$.error("Error capturing "+e+" pageview",n)}}bt(){if(!this.ft){var e=()=>{this._t("popstate")};ft(T,"popstate",e),this.ft=()=>{T&&T.removeEventListener("popstate",e)}}}},cx=et("[SegmentIntegration]");function P3(t,e){var a=t.config.segment;if(!a)return e();(function(r,n){var o=r.config.segment;if(!o)return n();var i=l=>{var u=()=>l.anonymousId()||So();r.config.get_device_id=u,l.id()&&(r.register({distinct_id:l.id(),$device_id:u()}),r.persistence.set_property(pn,"identified")),n()},s=o.user();"then"in s&&_o(s.then)?s.then(i):i(s)})(t,(()=>{a.register((r=>{Promise&&Promise.resolve||cx.warn("This browser does not have Promise support, and can not use the segment integration");var n=(o,i)=>{if(!i)return o;o.event.userId||o.event.anonymousId===r.get_distinct_id()||(cx.info("No userId set, resetting PostHog"),r.reset()),o.event.userId&&o.event.userId!==r.get_distinct_id()&&(cx.info("UserId set, identifying with PostHog"),r.identify(o.event.userId));var s=r.calculateEventProperties(i,o.event.properties);return o.event.properties=Object.assign({},s,o.event.properties),o};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:o=>n(o,o.event.event),page:o=>n(o,"$pageview"),identify:o=>n(o,"$identify"),screen:o=>n(o,"$screen")}})(t)).then((()=>{e()}))}))}var nT="posthog-js";function oT(t,e){var{organization:a,projectId:r,prefix:n,severityAllowList:o=["error"],sendExceptionsToPostHog:i=!0}=e===void 0?{}:e;return s=>{var l,u,c,d,f;if(!(o==="*"||o.includes(s.level))||!t.__loaded)return s;s.tags||(s.tags={});var h=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());s.tags["PostHog Person URL"]=h,t.sessionRecordingStarted()&&(s.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var S=((l=s.exception)==null?void 0:l.values)||[],x=S.map((g=>j({},g,{stacktrace:g.stacktrace?j({},g.stacktrace,{type:"raw",frames:(g.stacktrace.frames||[]).map((m=>j({},m,{platform:"web:javascript"})))}):void 0}))),b={$exception_message:((u=S[0])==null?void 0:u.value)||s.message,$exception_type:(c=S[0])==null?void 0:c.type,$exception_level:s.level,$exception_list:x,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:((d=S[0])==null?void 0:d.value)||s.message,$sentry_exception_type:(f=S[0])==null?void 0:f.type,$sentry_tags:s.tags};return a&&r&&(b.$sentry_url=(n||"https://sentry.io/organizations/")+a+"/issues/?project="+r+"&query="+s.event_id),i&&t.exceptions.sendExceptionEvent(b),s}}var tb=class{constructor(e,a,r,n,o,i){this.name=nT,this.setupOnce=function(s){s(oT(e,{organization:a,projectId:r,prefix:n,severityAllowList:o,sendExceptionsToPostHog:i==null||i}))}}},N3=T!=null&&T.location?eh(T.location.hash,"__posthog")||eh(location.hash,"state"):null,XA="_postHogToolbarParams",KA=et("[Toolbar]"),bo=(function(t){return t[t.UNINITIALIZED=0]="UNINITIALIZED",t[t.LOADING=1]="LOADING",t[t.LOADED=2]="LOADED",t})(bo||{}),ab=class{constructor(e){this.instance=e}yt(e){Q.ph_toolbar_state=e}wt(){var e;return(e=Q.ph_toolbar_state)!==null&&e!==void 0?e:bo.UNINITIALIZED}maybeLoadToolbar(e,a,r){if(e===void 0&&(e=void 0),a===void 0&&(a=void 0),r===void 0&&(r=void 0),!T||!q)return!1;e=e??T.location,r=r??T.history;try{if(!a){try{T.localStorage.setItem("test","test"),T.localStorage.removeItem("test")}catch{return!1}a=T?.localStorage}var n,o=N3||eh(e.hash,"__posthog")||eh(e.hash,"state"),i=o?OA((()=>JSON.parse(atob(decodeURIComponent(o)))))||OA((()=>JSON.parse(decodeURIComponent(o)))):null;return i&&i.action==="ph_authorize"?((n=i).source="url",n&&Object.keys(n).length>0&&(i.desiredHash?e.hash=i.desiredHash:r?r.replaceState(r.state,"",e.pathname+e.search):e.hash="")):((n=JSON.parse(a.getItem(XA)||"{}")).source="localstorage",delete n.userIntent),!(!n.token||this.instance.config.token!==n.token)&&(this.loadToolbar(n),!0)}catch{return!1}}xt(e){var a=Q.ph_load_toolbar||Q.ph_load_editor;!ge(a)&&_o(a)?a(e,this.instance):KA.warn("No toolbar load function found")}loadToolbar(e){var a=!(q==null||!q.getElementById($E));if(!T||a)return!1;var r=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,n=j({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},r?{instrument:!1}:{});if(T.localStorage.setItem(XA,JSON.stringify(j({},n,{source:void 0}))),this.wt()===bo.LOADED)this.xt(n);else if(this.wt()===bo.UNINITIALIZED){var o;this.yt(bo.LOADING),(o=Q.__PosthogExtensions__)==null||o.loadExternalDependency==null||o.loadExternalDependency(this.instance,"toolbar",(i=>{if(i)return KA.error("[Toolbar] Failed to load",i),void this.yt(bo.UNINITIALIZED);this.yt(bo.LOADED),this.xt(n)})),ft(T,"turbolinks:load",(()=>{this.yt(bo.UNINITIALIZED),this.loadToolbar(n)}))}return!0}Et(e){return this.loadToolbar(e)}maybeLoadEditor(e,a,r){return e===void 0&&(e=void 0),a===void 0&&(a=void 0),r===void 0&&(r=void 0),this.maybeLoadToolbar(e,a,r)}},F3=et("[TracingHeaders]"),rb=class{constructor(e){this.$t=void 0,this.St=void 0,this.rt=()=>{var a,r;V(this.$t)&&((a=Q.__PosthogExtensions__)==null||(a=a.tracingHeadersPatchFns)==null||a._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),V(this.St)&&((r=Q.__PosthogExtensions__)==null||(r=r.tracingHeadersPatchFns)==null||r._patchFetch(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=e}it(e){var a,r;(a=Q.__PosthogExtensions__)!=null&&a.tracingHeadersPatchFns&&e(),(r=Q.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"tracing-headers",(n=>{if(n)return F3.error("failed to load script",n);e()}))}startIfEnabledOrStop(){var e,a;this._instance.config.__add_tracing_headers?this.it(this.rt):((e=this.$t)==null||e.call(this),(a=this.St)==null||a.call(this),this.$t=void 0,this.St=void 0)}},Hp="https?://(.*)",rl=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],H3=al(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],rl),Lc="<masked>",U3=["li_fat_id"];function iT(t,e,a){if(!q)return{};var r,n=e?al([],rl,a||[]):[],o=sT(wc(q.URL,n,Lc),t),i=(r={},Be(U3,(function(s){var l=kr.q(s);r[s]=l||null})),r);return ot(i,o)}function sT(t,e){var a=H3.concat(e||[]),r={};return Be(a,(function(n){var o=Jp(t,n);r[n]=o||null})),r}function lT(t){var e=(function(o){return o?o.search(Hp+"google.([^/?]*)")===0?"google":o.search(Hp+"bing.com")===0?"bing":o.search(Hp+"yahoo.com")===0?"yahoo":o.search(Hp+"duckduckgo.com")===0?"duckduckgo":null:null})(t),a=e!="yahoo"?"q":"p",r={};if(!cr(e)){r.$search_engine=e;var n=q?Jp(q.referrer,a):"";n.length&&(r.ph_keyword=n)}return r}function YA(){return navigator.language||navigator.userLanguage}function uT(){return q?.referrer||"$direct"}function cT(t,e){var a=t?al([],rl,e||[]):[],r=Bt?.href.substring(0,1e3);return{r:uT().substring(0,1e3),u:r?wc(r,a,Lc):void 0}}function dT(t){var e,{r:a,u:r}=t,n={$referrer:a,$referring_domain:a==null?void 0:a=="$direct"?"$direct":(e=Qp(a))==null?void 0:e.host};if(r){n.$current_url=r;var o=Qp(r);n.$host=o?.host,n.$pathname=o?.pathname;var i=sT(r);ot(n,i)}if(a){var s=lT(a);ot(n,s)}return n}function fT(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function z3(){try{return new Date().getTimezoneOffset()}catch{return}}function q3(t,e){if(!ua)return{};var a,r,n,o=t?al([],rl,e||[]):[],[i,s]=(function(l){for(var u=0;u<AA.length;u++){var[c,d]=AA[u],f=c.exec(l),h=f&&(_o(d)?d(f,l):d);if(h)return h}return["",""]})(ua);return ot(Nb({$os:i,$os_version:s,$browser:PE(ua,navigator.vendor),$device:EA(ua),$device_type:(r=ua,n=EA(r),n===_E||n===SE||n==="Kobo"||n==="Kindle Fire"||n===BE?vc:n===xc||n===Qs||n===bc||n===Ix?"Console":n===wE?"Wearable":n?$a:"Desktop"),$timezone:fT(),$timezone_offset:z3()}),{$current_url:wc(Bt?.href,o,Lc),$host:Bt?.host,$pathname:Bt?.pathname,$raw_user_agent:ua.length>1e3?ua.substring(0,997)+"...":ua,$browser_version:YH(ua,navigator.vendor),$browser_language:YA(),$browser_language_prefix:(a=YA(),typeof a=="string"?a.split("-")[0]:void 0),$screen_height:T?.screen.height,$screen_width:T?.screen.width,$viewport_height:T?.innerHeight,$viewport_width:T?.innerWidth,$lib:"web",$lib_version:fn.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})}var vo=et("[Web Vitals]"),QA=9e5,nb=class{constructor(e){var a;this.kt=!1,this.P=!1,this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.Pt=()=>{clearTimeout(this.Tt),this.N.metrics.length!==0&&(this._instance.capture("$web_vitals",this.N.metrics.reduce(((r,n)=>j({},r,{["$web_vitals_"+n.name+"_event"]:j({},n),["$web_vitals_"+n.name+"_value"]:n.value})),{})),this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.It=r=>{var n,o=(n=this._instance.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0);if(V(o))vo.error("Could not read session ID. Dropping metrics!");else{this.N=this.N||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var i=this.Ct();V(i)||(ge(r?.name)||ge(r?.value)?vo.error("Invalid metric received",r):this.Rt&&r.value>=this.Rt?vo.error("Ignoring metric with value >= "+this.Rt,r):(this.N.url!==i&&(this.Pt(),this.Tt=setTimeout(this.Pt,this.flushToCaptureTimeoutMs)),V(this.N.url)&&(this.N.url=i),this.N.firstMetricTimestamp=V(this.N.firstMetricTimestamp)?Date.now():this.N.firstMetricTimestamp,r.attribution&&r.attribution.interactionTargetElement&&(r.attribution.interactionTargetElement=void 0),this.N.metrics.push(j({},r,{$current_url:i,$session_id:o.sessionId,$window_id:o.windowId,timestamp:Date.now()})),this.N.metrics.length===this.allowedMetrics.length&&this.Pt()))}},this.rt=()=>{if(!this.P){var r,n,o,i,s=Q.__PosthogExtensions__;V(s)||V(s.postHogWebVitalsCallbacks)||({onLCP:r,onCLS:n,onFCP:o,onINP:i}=s.postHogWebVitalsCallbacks),r&&n&&o&&i?(this.allowedMetrics.indexOf("LCP")>-1&&r(this.It.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&n(this.It.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&o(this.It.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&i(this.It.bind(this)),this.P=!0):vo.error("web vitals callbacks not loaded - not starting")}},this._instance=e,this.kt=!((a=this._instance.persistence)==null||!a.props[NA]),this.startIfEnabled()}get allowedMetrics(){var e,a,r=gt(this._instance.config.capture_performance)?(e=this._instance.config.capture_performance)==null?void 0:e.web_vitals_allowed_metrics:void 0;return ge(r)?((a=this._instance.persistence)==null?void 0:a.props[HA])||["CLS","FCP","INP","LCP"]:r}get flushToCaptureTimeoutMs(){return(gt(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var e=gt(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_attribution:void 0;return e!=null&&e}get Rt(){var e=gt(this._instance.config.capture_performance)&&yn(this._instance.config.capture_performance.__web_vitals_max_value)?this._instance.config.capture_performance.__web_vitals_max_value:QA;return 0<e&&e<=6e4?QA:e}get isEnabled(){var e=Bt?.protocol;if(e!=="http:"&&e!=="https:")return vo.info("Web Vitals are disabled on non-http/https protocols"),!1;var a=gt(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals:vn(this._instance.config.capture_performance)?this._instance.config.capture_performance:void 0;return vn(a)?a:this.kt}startIfEnabled(){this.isEnabled&&!this.P&&(vo.info("enabled, starting..."),this.it(this.rt))}onRemoteConfig(e){var a=gt(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=gt(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[NA]:a}),this._instance.persistence.register({[HA]:r})),this.kt=a,this.startIfEnabled()}it(e){var a,r;if((a=Q.__PosthogExtensions__)!=null&&a.postHogWebVitalsCallbacks)e();else{var n=this.useAttribution?"web-vitals-with-attribution":"web-vitals";(r=Q.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,n,(o=>{o?vo.error("failed to load script",o):e()}))}}Ct(){var e=T?T.location.href:void 0;if(e){var a=this._instance.config.mask_personal_data_properties,r=this._instance.config.custom_personal_data_properties,n=a?al([],rl,r||[]):[];return wc(e,n,Lc)}vo.error("Could not determine current URL")}},V3=et("[Heatmaps]");function JA(t){return gt(t)&&"clientX"in t&&"clientY"in t&&yn(t.clientX)&&yn(t.clientY)}var ob=class{constructor(e){var a;this.kt=!1,this.P=!1,this.Ft=null,this.instance=e,this.kt=!((a=this.instance.persistence)==null||!a.props[Hx]),this.rageclicks=new Yp(e.config.rageclick)}get flushIntervalMilliseconds(){var e=5e3;return gt(this.instance.config.capture_heatmaps)&&this.instance.config.capture_heatmaps.flush_interval_milliseconds&&(e=this.instance.config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return ge(this.instance.config.capture_heatmaps)?ge(this.instance.config.enable_heatmaps)?this.kt:this.instance.config.enable_heatmaps:this.instance.config.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.P)return;V3.info("starting..."),this.Ot(),this.Mt()}else{var e;clearInterval((e=this.Ft)!==null&&e!==void 0?e:void 0),this.At(),this.getAndClearBuffer()}}onRemoteConfig(e){var a=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Hx]:a}),this.kt=a,this.startIfEnabled()}getAndClearBuffer(){var e=this.N;return this.N=void 0,e}jt(e){this.Dt(e.originalEvent,"deadclick")}Mt(){this.Ft&&clearInterval(this.Ft),this.Ft=(function(e){return e?.visibilityState==="visible"})(q)?setInterval(this.Lt.bind(this),this.flushIntervalMilliseconds):null}Ot(){T&&q&&(this.Nt=this.Lt.bind(this),ft(T,"beforeunload",this.Nt),this.Ut=e=>this.Dt(e||T?.event),ft(q,"click",this.Ut,{capture:!0}),this.zt=e=>this.Ht(e||T?.event),ft(q,"mousemove",this.zt,{capture:!0}),this.Bt=new th(this.instance,D3,this.jt.bind(this)),this.Bt.startIfEnabled(),this.qt=this.Mt.bind(this),ft(q,"visibilitychange",this.qt),this.P=!0)}At(){var e;T&&q&&(this.Nt&&T.removeEventListener("beforeunload",this.Nt),this.Ut&&q.removeEventListener("click",this.Ut,{capture:!0}),this.zt&&q.removeEventListener("mousemove",this.zt,{capture:!0}),this.qt&&q.removeEventListener("visibilitychange",this.qt),clearTimeout(this.Wt),(e=this.Bt)==null||e.stop(),this.P=!1)}Gt(e,a){var r=this.instance.scrollManager.scrollY(),n=this.instance.scrollManager.scrollX(),o=this.instance.scrollManager.scrollElement(),i=(function(s,l,u){for(var c=s;c&&ph(c)&&!wo(c,"body");){if(c===u)return!1;if(he(l,T?.getComputedStyle(c).position))return!0;c=KE(c)}return!1})(ZE(e),["fixed","sticky"],o);return{x:e.clientX+(i?0:n),y:e.clientY+(i?0:r),target_fixed:i,type:a}}Dt(e,a){var r;if(a===void 0&&(a="click"),!UA(e.target)&&JA(e)){var n=this.Gt(e,a);(r=this.rageclicks)!=null&&r.isRageClick(e.clientX,e.clientY,new Date().getTime())&&this.Vt(j({},n,{type:"rageclick"})),this.Vt(n)}}Ht(e){!UA(e.target)&&JA(e)&&(clearTimeout(this.Wt),this.Wt=setTimeout((()=>{this.Vt(this.Gt(e,"mousemove"))}),500))}Vt(e){if(T){var a=T.location.href,r=this.instance.config.mask_personal_data_properties,n=this.instance.config.custom_personal_data_properties,o=r?al([],rl,n||[]):[],i=wc(a,o,Lc);this.N=this.N||{},this.N[i]||(this.N[i]=[]),this.N[i].push(e)}}Lt(){this.N&&!Xs(this.N)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},ah=class{constructor(e){this.Jt=(a,r,n)=>{n&&(n.noSessionId||n.activityTimeout||n.sessionPastMaximumLength)&&($.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:a,changeReason:n}),this.Kt=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.Yt()}Yt(){var e;this.Xt=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.Jt)}destroy(){var e;(e=this.Xt)==null||e.call(this),this.Xt=void 0}doPageView(e,a){var r,n=this.Qt(e,a);return this.Kt={pathname:(r=T?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:a,timestamp:e},this._instance.scrollManager.resetContext(),n}doPageLeave(e){var a;return this.Qt(e,(a=this.Kt)==null?void 0:a.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.Kt)==null?void 0:e.pageViewId}}Qt(e,a){var r=this.Kt;if(!r)return{$pageview_id:a};var n={$pageview_id:a,$prev_pageview_id:r.pageViewId},o=this._instance.scrollManager.getContext();if(o&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:i,lastScrollY:s,maxScrollY:l,maxContentHeight:u,lastContentY:c,maxContentY:d}=o;if(!(V(i)||V(s)||V(l)||V(u)||V(c)||V(d))){i=Math.ceil(i),s=Math.ceil(s),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=i<=1?1:Ir(s/i,0,1,$),h=i<=1?1:Ir(l/i,0,1,$),S=u<=1?1:Ir(c/u,0,1,$),x=u<=1?1:Ir(d/u,0,1,$);n=ot(n,{$prev_pageview_last_scroll:s,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:S,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:x})}}return r.pathname&&(n.$prev_pageview_pathname=r.pathname),r.timestamp&&(n.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),n}};var mn=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),ja=Uint8Array,Zt=Uint16Array,tl=Uint32Array,zb=new ja([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),qb=new ja([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),eE=new ja([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),pT=function(t,e){for(var a=new Zt(31),r=0;r<31;++r)a[r]=e+=1<<t[r-1];var n=new tl(a[30]);for(r=1;r<30;++r)for(var o=a[r];o<a[r+1];++o)n[o]=o-a[r]<<5|r;return[a,n]},hT=pT(zb,2),$3=hT[0],ib=hT[1];$3[28]=258,ib[258]=28;for(sb=pT(qb,0)[1],rh=new Zt(32768),Pe=0;Pe<32768;++Pe)yo=(43690&Pe)>>>1|(21845&Pe)<<1,yo=(61680&(yo=(52428&yo)>>>2|(13107&yo)<<2))>>>4|(3855&yo)<<4,rh[Pe]=((65280&yo)>>>8|(255&yo)<<8)>>>1;var yo,sb,rh,Pe,hc=function(t,e,a){for(var r=t.length,n=0,o=new Zt(e);n<r;++n)++o[t[n]-1];var i,s=new Zt(e);for(n=0;n<e;++n)s[n]=s[n-1]+o[n-1]<<1;if(a){i=new Zt(1<<e);var l=15-e;for(n=0;n<r;++n)if(t[n])for(var u=n<<4|t[n],c=e-t[n],d=s[t[n]-1]++<<c,f=d|(1<<c)-1;d<=f;++d)i[rh[d]>>>l]=u}else for(i=new Zt(r),n=0;n<r;++n)i[n]=rh[s[t[n]-1]++]>>>15-t[n];return i},ki=new ja(288);for(Pe=0;Pe<144;++Pe)ki[Pe]=8;for(Pe=144;Pe<256;++Pe)ki[Pe]=9;for(Pe=256;Pe<280;++Pe)ki[Pe]=7;for(Pe=280;Pe<288;++Pe)ki[Pe]=8;var nh=new ja(32);for(Pe=0;Pe<32;++Pe)nh[Pe]=5;var j3=hc(ki,9,0),G3=hc(nh,5,0),mT=function(t){return(t/8>>0)+(7&t&&1)},gT=function(t,e,a){(a==null||a>t.length)&&(a=t.length);var r=new(t instanceof Zt?Zt:t instanceof tl?tl:ja)(a-e);return r.set(t.subarray(e,a)),r},cn=function(t,e,a){a<<=7&e;var r=e/8>>0;t[r]|=a,t[r+1]|=a>>>8},ec=function(t,e,a){a<<=7&e;var r=e/8>>0;t[r]|=a,t[r+1]|=a>>>8,t[r+2]|=a>>>16},dx=function(t,e){for(var a=[],r=0;r<t.length;++r)t[r]&&a.push({s:r,f:t[r]});var n=a.length,o=a.slice();if(!n)return[new ja(0),0];if(n==1){var i=new ja(a[0].s+1);return i[a[0].s]=1,[i,1]}a.sort((function(C,w){return C.f-w.f})),a.push({s:-1,f:25001});var s=a[0],l=a[1],u=0,c=1,d=2;for(a[0]={s:-1,f:s.f+l.f,l:s,r:l};c!=n-1;)s=a[a[u].f<a[d].f?u++:d++],l=a[u!=c&&a[u].f<a[d].f?u++:d++],a[c++]={s:-1,f:s.f+l.f,l:s,r:l};var f=o[0].s;for(r=1;r<n;++r)o[r].s>f&&(f=o[r].s);var h=new Zt(f+1),S=lb(a[c-1],h,0);if(S>e){r=0;var x=0,b=S-e,g=1<<b;for(o.sort((function(C,w){return h[w.s]-h[C.s]||C.f-w.f}));r<n;++r){var m=o[r].s;if(!(h[m]>e))break;x+=g-(1<<S-h[m]),h[m]=e}for(x>>>=b;x>0;){var y=o[r].s;h[y]<e?x-=1<<e-h[y]++-1:++r}for(;r>=0&&x;--r){var v=o[r].s;h[v]==e&&(--h[v],++x)}S=e}return[new ja(h),S]},lb=function(t,e,a){return t.s==-1?Math.max(lb(t.l,e,a+1),lb(t.r,e,a+1)):e[t.s]=a},tE=function(t){for(var e=t.length;e&&!t[--e];);for(var a=new Zt(++e),r=0,n=t[0],o=1,i=function(l){a[r++]=l},s=1;s<=e;++s)if(t[s]==n&&s!=e)++o;else{if(!n&&o>2){for(;o>138;o-=138)i(32754);o>2&&(i(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(i(n),--o;o>6;o-=6)i(8304);o>2&&(i(o-3<<5|8208),o=0)}for(;o--;)i(n);o=1,n=t[s]}return[a.subarray(0,r),e]},tc=function(t,e){for(var a=0,r=0;r<e.length;++r)a+=t[r]*e[r];return a},ub=function(t,e,a){var r=a.length,n=mT(e+2);t[n]=255&r,t[n+1]=r>>>8,t[n+2]=255^t[n],t[n+3]=255^t[n+1];for(var o=0;o<r;++o)t[n+o+4]=a[o];return 8*(n+4+r)},aE=function(t,e,a,r,n,o,i,s,l,u,c){cn(e,c++,a),++n[256];for(var d=dx(n,15),f=d[0],h=d[1],S=dx(o,15),x=S[0],b=S[1],g=tE(f),m=g[0],y=g[1],v=tE(x),C=v[0],w=v[1],_=new Zt(19),L=0;L<m.length;++L)_[31&m[L]]++;for(L=0;L<C.length;++L)_[31&C[L]]++;for(var A=dx(_,7),I=A[0],R=A[1],H=19;H>4&&!I[eE[H-1]];--H);var E,M,D,F,Z=u+5<<3,U=tc(n,ki)+tc(o,nh)+i,W=tc(n,f)+tc(o,x)+i+14+3*H+tc(_,I)+(2*_[16]+3*_[17]+7*_[18]);if(Z<=U&&Z<=W)return ub(e,c,t.subarray(l,l+u));if(cn(e,c,1+(W<U)),c+=2,W<U){E=hc(f,h,0),M=f,D=hc(x,b,0),F=x;var ce=hc(I,R,0);for(cn(e,c,y-257),cn(e,c+5,w-1),cn(e,c+10,H-4),c+=14,L=0;L<H;++L)cn(e,c+3*L,I[eE[L]]);c+=3*H;for(var Xt=[m,C],it=0;it<2;++it){var yt=Xt[it];for(L=0;L<yt.length;++L){var N=31&yt[L];cn(e,c,ce[N]),c+=I[N],N>15&&(cn(e,c,yt[L]>>>5&127),c+=yt[L]>>>12)}}}else E=j3,M=ki,D=G3,F=nh;for(L=0;L<s;++L)if(r[L]>255){N=r[L]>>>18&31,ec(e,c,E[N+257]),c+=M[N+257],N>7&&(cn(e,c,r[L]>>>23&31),c+=zb[N]);var te=31&r[L];ec(e,c,D[te]),c+=F[te],te>3&&(ec(e,c,r[L]>>>5&8191),c+=qb[te])}else ec(e,c,E[r[L]]),c+=M[r[L]];return ec(e,c,E[256]),c+M[256]},W3=new tl([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Z3=(function(){for(var t=new tl(256),e=0;e<256;++e){for(var a=e,r=9;--r;)a=(1&a&&3988292384)^a>>>1;t[e]=a}return t})(),X3=function(t,e,a,r,n){return(function(o,i,s,l,u,c){var d=o.length,f=new ja(l+d+5*(1+Math.floor(d/7e3))+u),h=f.subarray(l,f.length-u),S=0;if(!i||d<8)for(var x=0;x<=d;x+=65535){var b=x+65535;b<d?S=ub(h,S,o.subarray(x,b)):(h[x]=c,S=ub(h,S,o.subarray(x,d)))}else{for(var g=W3[i-1],m=g>>>13,y=8191&g,v=(1<<s)-1,C=new Zt(32768),w=new Zt(v+1),_=Math.ceil(s/3),L=2*_,A=function(Mh){return(o[Mh]^o[Mh+1]<<_^o[Mh+2]<<L)&v},I=new tl(25e3),R=new Zt(288),H=new Zt(32),E=0,M=0,D=(x=0,0),F=0,Z=0;x<d;++x){var U=A(x),W=32767&x,ce=w[U];if(C[W]=ce,w[U]=W,F<=x){var Xt=d-x;if((E>7e3||D>24576)&&Xt>423){S=aE(o,h,0,I,R,H,M,D,Z,x-Z,S),D=E=M=0,Z=x;for(var it=0;it<286;++it)R[it]=0;for(it=0;it<30;++it)H[it]=0}var yt=2,N=0,te=y,pt=W-ce&32767;if(Xt>2&&U==A(x-pt))for(var Sn=Math.min(m,Xt)-1,Eh=Math.min(32767,x),Th=Math.min(258,Xt);pt<=Eh&&--te&&W!=ce;){if(o[x+yt]==o[x+yt-pt]){for(var _n=0;_n<Th&&o[x+_n]==o[x+_n-pt];++_n);if(_n>yt){if(yt=_n,N=pt,_n>Sn)break;var NR=Math.min(pt,_n-2),J0=0;for(it=0;it<NR;++it){var Rh=x-pt+it+32768&32767,eS=Rh-C[Rh]+32768&32767;eS>J0&&(J0=eS,ce=Rh)}}}pt+=(W=ce)-(ce=C[W])+32768&32767}if(N){I[D++]=268435456|ib[yt]<<18|sb[N];var tS=31&ib[yt],aS=31&sb[N];M+=zb[tS]+qb[aS],++R[257+tS],++H[aS],F=x+yt,++E}else I[D++]=o[x],++R[o[x]]}}S=aE(o,h,c,I,R,H,M,D,Z,x-Z,S)}return gT(f,0,l+mT(S)+u)})(t,e.level==null?6:e.level,e.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(t.length)))):12+e.mem,a,r,!0)},fx=function(t,e,a){for(;a;++e)t[e]=a,a>>>=8};function K3(t,e){e===void 0&&(e={});var a=(function(){var s=4294967295;return{p:function(l){for(var u=s,c=0;c<l.length;++c)u=Z3[255&u^l[c]]^u>>>8;s=u},d:function(){return 4294967295^s}}})(),r=t.length;a.p(t);var n,o=X3(t,e,10+((n=e).filename&&n.filename.length+1||0),8),i=o.length;return(function(s,l){var u=l.filename;if(s[0]=31,s[1]=139,s[2]=8,s[8]=l.level<2?4:l.level==9?2:0,s[9]=3,l.mtime!=0&&fx(s,4,Math.floor(new Date(l.mtime||Date.now())/1e3)),u){s[3]=8;for(var c=0;c<=u.length;++c)s[c+10]=u.charCodeAt(c)}})(o,e),fx(o,i-8,a.d()),fx(o,i-4,r),o}var Y3=function(t){var e,a,r,n,o="";for(e=a=0,r=(t=(t+"").replace(/\r\n/g,`
498
+ `,Ua,oo,io,tn,an,so,rn,Ay=class extends HTMLElement{constructor(){super();Cn(this,Ua);Cn(this,oo);Cn(this,io);Cn(this,tn);Cn(this,an);Cn(this,so,null);Cn(this,rn,null);fr(this,Ua,this.attachShadow({mode:"open",delegatesFocus:!0})),fr(this,oo,document.createElement("div")),ye(this,oo).setAttribute("part","mount"),ye(this,Ua).appendChild(ye(this,oo)),fr(this,io,document.createElement("div")),ye(this,io).id="portalRoot",ye(this,Ua).appendChild(ye(this,io)),fr(this,tn,document.createElement("div")),ye(this,tn).id="overlayContainer",Object.assign(ye(this,tn).style,{position:"fixed",inset:"0",zIndex:"2147483645",pointerEvents:"none"}),ye(this,Ua).appendChild(ye(this,tn)),fr(this,an,W1()),this.applyBaseStyles()}connectedCallback(){this.style.setProperty("font-family","inherit")}disconnectedCallback(){ye(this,so)?.unmount(),fr(this,so,null)}getMountNode(){return ye(this,oo)}getController(){return ye(this,an)}getPortalRoot(){return ye(this,io)}getOverlayContainer(){return ye(this,tn)}getShadowRoot(){return ye(this,Ua)}open(){ye(this,an).setOpen(!0)}close(){ye(this,an).setOpen(!1)}toggle(){ye(this,an).toggle()}setOverrideFetcher(a){ye(this,rn)&&(fr(this,rn,{...ye(this,rn),fetcher:a}),this.render())}mountReactApp(a){fr(this,rn,a),this.render()}render(){!this.isConnected||!ye(this,rn)||(ye(this,so)||fr(this,so,(0,SI.createRoot)(ye(this,oo))),ye(this,so).render((0,Ey.jsx)(X1,{shadowRoot:ye(this,Ua),portalRoot:ye(this,io),overlayContainer:ye(this,tn),children:(0,Ey.jsx)(yI,{...ye(this,rn),controller:ye(this,an),canvasHost:this})})))}applyBaseStyles(){if(ye(this,Ua).adoptedStyleSheets!==void 0){let a=new CSSStyleSheet;a.replaceSync(bI),ye(this,Ua).adoptedStyleSheets=[a]}else{let a=document.createElement("style");a.textContent=bI,ye(this,Ua).appendChild(a)}}};Ua=new WeakMap,oo=new WeakMap,io=new WeakMap,tn=new WeakMap,an=new WeakMap,so=new WeakMap,rn=new WeakMap;var _I=()=>{typeof window>"u"||customElements.get(xI)||customElements.define(xI,Ay)};var Ty=async(t={})=>{if(typeof window>"u"||typeof document>"u")throw new Error("SmartCanvas can only be created in a browser-like environment");let e=null;if(t.antiFlicker){let b=typeof t.antiFlicker=="object"?t.antiFlicker:{};e=P1(b)}let a=null,r=null,n=null,{runtime:o}=t;async function i(b){!o?.actions||b.length===0||(n?.isApplied()&&await n.revertAll(),n=await o.actions.applyBatch(b))}async function s(){n?.isApplied()&&(await n.revertAll(),n=null)}if(t.fetcher)try{r=t.fetcher,console.log("[SmartCanvas] Fetching initial config...");let b=await t.fetcher();a=b,console.log("[SmartCanvas] Config fetched:",`tiles=${b.tiles?.length??0},`,`actions=${b.actions?.length??0},`,`theme=${b.theme?.mode??"default"}`),b.actions?.length&&console.log("[SmartCanvas] Actions to apply:",b.actions.map((g,m)=>`[${m}] ${g.kind}${g.anchorId?` anchor="${g.anchorId.selector}"`:""}${g.label?` "${g.label}"`:""}`).join(", ")),b.actions&&b.actions.length>0&&o?.actions&&(await i(b.actions),console.log("[SmartCanvas] Initial actions applied successfully")),b.tiles&&o?.accumulator&&Qf(b.tiles,o.accumulator,b.actions)}catch(b){console.error("[SmartCanvas] Error fetching/applying initial config:",b)}e&&e();let l=Yf();_I();let u=document.createElement("smart-canvas");if(j1(u.getOverlayContainer()),t.tokens)for(let[b,g]of Object.entries(t.tokens))u.style.setProperty(b,g);let c=()=>{let b=t.target??document.body;b&&b.appendChild(u)};document.body?c():document.addEventListener("DOMContentLoaded",c,{once:!0}),l&&(console.log(`[SmartCanvas] Loading editor SDK for ${l} mode`),z1(t.editorUrl).catch(console.error));let d=t.integrations?.experiments,f=t.integrations?.telemetry,h=t.fetcher??Cs({configUri:t.configUri,experiments:d,featureKey:t.configUriFeatureKey,credentials:t.fetchCredentials});r||(r=h);let S={fetcher:h,pollIntervalMs:t.pollIntervalMs,experiments:d,telemetry:f,runtime:o,overlayFetcher:t.overlayFetcher,overlayConfigUri:t.overlayConfigUri,overlayConfigFeatureKey:t.overlayConfigFeatureKey,overlayFetchCredentials:t.overlayFetchCredentials,configUri:t.configUri,configUriFeatureKey:t.configUriFeatureKey,fetchCredentials:t.fetchCredentials,initialBatchHandle:n,workspaceTheme:t.workspaceTheme};u.mountReactApp(S),t.defaultOpen&&u.open();let x={el:u,open:()=>u.open(),close:()=>u.close(),destroy:()=>{s(),u.remove()},setTokens:b=>{for(let[g,m]of Object.entries(b))u.style.setProperty(g,m)},getConfig:async()=>{if(r)try{let b=await r();return a=b,b}catch(b){console.error("[SmartCanvas] Error fetching config:",b)}return a??{tiles:[],actions:[],fetchedAt:""}},setEnabled:async b=>{b?a&&await i(a.actions):await s()},setOverrideFetcher:b=>{r=b,u.setOverrideFetcher(b),o?.accumulator&&b().then(g=>{g?.tiles&&Qf(g.tiles,o.accumulator,g.actions)}).catch(()=>{})},registerTelemetryProperties:b=>{f?.register?.(b)},getSessionId:()=>f?.getSessionId?.(),startSessionRecording:()=>{f?.startSessionRecording?.()},track:(b,g)=>f?.track?(f.track(b,g),!0):!1,runtime:o};if(typeof window<"u"){let b=window.SynOS;b&&(b.handle=x)}return x};typeof window<"u"&&(window.SmartCanvas={async create(t){return Ty(t)}});var uo=Y(Ye(),1);var lo=Y(Ae(),1);function c$({tiles:t,intervalMs:e=7e3,telemetry:a}){let[r,n]=(0,uo.useState)(0),o=(0,uo.useMemo)(()=>[...t].sort((i,s)=>(i.priority??0)-(s.priority??0)),[t]);return(0,uo.useEffect)(()=>{a?.trackCanvasOpened("wheel")},[a]),(0,uo.useEffect)(()=>{if(o.length<=1)return;let i=setInterval(()=>{n(s=>(s+1)%o.length)},e);return()=>clearInterval(i)},[o,e]),(0,uo.useEffect)(()=>{let i=o[r];i&&a?.trackRectangleViewed(i.id,"wheel")},[r,o,a]),o.length?(0,lo.jsxs)("div",{style:{position:"relative",overflow:"hidden",borderRadius:"1.5rem",border:"var(--sc-tile-border)",background:"var(--sc-tile-background)",padding:"1.5rem",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)"},"data-shadow-canvas-id":"wheel",children:[(0,lo.jsx)("div",{style:{display:"flex",transition:"transform 700ms ease-out",transform:`translateX(-${r*100}%)`,width:`${o.length*100}%`},children:o.map(i=>(0,lo.jsx)("div",{style:{width:"100%",flexShrink:0,padding:"0 1rem"},children:(0,lo.jsx)(Uu,{config:i,surface:"wheel",telemetry:a})},i.id))}),(0,lo.jsx)("div",{style:{marginTop:"1rem",display:"flex",justifyContent:"center",gap:"0.5rem"},children:o.map((i,s)=>(0,lo.jsx)("button",{type:"button",style:{height:"0.5rem",width:"1.5rem",borderRadius:"9999px",background:s===r?"var(--sc-color-primary)":"var(--sc-tile-text-color)",border:"none",cursor:"pointer",padding:0},onClick:()=>n(s)},i.id))})]}):null}function zu(t){let e=t.split(".");return{major:parseInt(e[0]||"0",10),minor:parseInt(e[1]||"0",10)}}function p$(t){let e=[],a=[];if(!t||typeof t!="object")return{valid:!1,errors:["Config must be an object"],warnings:e};let r=t;if(r.tiles||a.push("Config missing required field: tiles"),r.actions||a.push("Config missing required field: actions"),r.fetchedAt||a.push("Config missing required field: fetchedAt"),a.length>0)return{valid:!1,errors:a,warnings:e};let n=r.schemaVersion||"1.0",o=zu(n),i=zu(eo);return o.major>i.major&&e.push(`Config schema v${n} is newer than SDK v${eo}. Some features may not work. Update SDK to latest version.`),o.major<i.major||!r.schemaVersion?(e.push(`Config schema v${n} is older than SDK v${eo}. Migrating config to current version.`),{valid:!0,warnings:e,errors:a,migratedConfig:xN(r,n)}):{valid:!0,warnings:e,errors:a}}function xN(t,e){let a={...t};return zu(e).major===1&&(a=bN(a)),a.schemaVersion=eo,a}function bN(t){let e={schemaVersion:"2.0",tiles:[],actions:t.actions||[],fetchedAt:t.fetchedAt||new Date().toISOString()};return t.tiles&&Array.isArray(t.tiles)&&(e.tiles=t.tiles.map(a=>{let r={...a};return a.experiment&&delete r.experiment,r})),t.configVersion&&(e.configVersion=t.configVersion),t.canvasTitle&&(e.canvasTitle=t.canvasTitle),t.theme&&(e.theme=t.theme),t.launcher&&(e.launcher=t.launcher),e}function h$(t){if(!t||typeof t!="object")return!1;let e=t,a=e.schemaVersion||"1.0",r=zu(a),n=zu(eo);return r.major<n.major||!e.schemaVersion}var wI={fetch:globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,SubtleCrypto:globalThis.crypto?globalThis.crypto.subtle:void 0,EventSource:globalThis.EventSource};function LI(){return wI}function Ry(t){let e=2166136261,a=t.length;for(let r=0;r<a;r++)e^=t.charCodeAt(r),e+=(e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24);return e>>>0}function qu(t,e,a){return a===2?Ry(Ry(t+e)+"")%1e4/1e4:a===1?Ry(e+t)%1e3/1e3:null}function SN(t){return t<=0?[]:new Array(t).fill(1/t)}function fp(t,e){return t>=e[0]&&t<e[1]}function kI(t,e){let a=qu("__"+e[0],t,1);return a===null?!1:a>=e[1]&&a<e[2]}function II(t,e){for(let a=0;a<e.length;a++)if(fp(t,e[a]))return a;return-1}function Oy(t){try{let e=t.replace(/([^\\])\//g,"$1\\/");return new RegExp(e)}catch(e){console.error(e);return}}function pp(t,e){if(!e.length)return!1;let a=!1,r=!1;for(let n=0;n<e.length;n++){let o=wN(t,e[n].type,e[n].pattern);if(e[n].include===!1){if(o)return!1}else a=!0,o&&(r=!0)}return r||!a}function _N(t,e,a){try{let r=e.replace(/[*.+?^${}()|[\]\\]/g,"\\$&").replace(/_____/g,".*");return a&&(r="\\/?"+r.replace(/(^\/|\/$)/g,"")+"\\/?"),new RegExp("^"+r+"$","i").test(t)}catch{return!1}}function CN(t,e){try{let a=new URL(e.replace(/^([^:/?]*)\./i,"https://$1.").replace(/\*/g,"_____"),"https://_____"),r=[[t.host,a.host,!1],[t.pathname,a.pathname,!0]];return a.hash&&r.push([t.hash,a.hash,!1]),a.searchParams.forEach((n,o)=>{r.push([t.searchParams.get(o)||"",n,!1])}),!r.some(n=>!_N(n[0],n[1],n[2]))}catch{return!1}}function wN(t,e,a){try{let r=new URL(t,"https://_");if(e==="regex"){let n=Oy(a);return n?n.test(r.href)||n.test(r.href.substring(r.origin.length)):!1}else if(e==="simple")return CN(r,a);return!1}catch{return!1}}function AI(t,e,a){e=e===void 0?1:e,e<0?e=0:e>1&&(e=1);let r=SN(t);a=a||r,a.length!==t&&(a=r);let n=a.reduce((i,s)=>s+i,0);(n<.99||n>1.01)&&(a=r);let o=0;return a.map(i=>{let s=o;return o+=i,[s,s+e*i]})}function EI(t,e,a){if(!e)return null;let r=e.split("?")[1];if(!r)return null;let n=r.replace(/#.*/,"").split("&").map(o=>o.split("=",2)).filter(([o])=>o===t).map(([,o])=>parseInt(o));return n.length>0&&n[0]>=0&&n[0]<a?n[0]:null}function TI(t){try{return t()}catch(e){return console.error(e),!1}}var My=t=>Uint8Array.from(atob(t),e=>e.charCodeAt(0));async function ni(t,e,a){if(e=e||"",a=a||globalThis.crypto&&globalThis.crypto.subtle||wI.SubtleCrypto,!a)throw new Error("No SubtleCrypto implementation found");try{let r=await a.importKey("raw",My(e),{name:"AES-CBC",length:128},!0,["encrypt","decrypt"]),[n,o]=t.split("."),i=await a.decrypt({name:"AES-CBC",iv:My(n)},r,My(o));return new TextDecoder().decode(i)}catch{throw new Error("Failed to decrypt")}}function Vu(t){return typeof t=="string"?t:JSON.stringify(t)}function wa(t){typeof t=="number"&&(t=t+""),(!t||typeof t!="string")&&(t="0");let e=t.replace(/(^v|\+.*$)/g,"").split(/[-.]/);return e.length===3&&e.push("~"),e.map(a=>a.match(/^[0-9]+$/)?a.padStart(5," "):a).join("-")}function RI(){let t;try{t="1.6.4"}catch{t=""}return t}function MI(t,e){let a,r;try{a=new URL(t),r=new URL(e)}catch(n){return console.error(`Unable to merge query strings: ${n}`),e}return a.searchParams.forEach((n,o)=>{r.searchParams.has(o)||r.searchParams.set(o,n)}),r.toString()}function CI(t){return typeof t=="object"&&t!==null}function hp(t){return t.urlPatterns&&t.variations.some(e=>CI(e)&&"urlRedirect"in e)?"redirect":t.variations.some(e=>CI(e)&&(e.domMutations||"js"in e||"css"in e))?"visual":"unknown"}async function mp(t,e){return new Promise(a=>{let r=!1,n,o=i=>{r||(r=!0,n&&clearTimeout(n),a(i||null))};e&&(n=setTimeout(()=>o(),e)),t.then(i=>o(i)).catch(()=>o())})}var Ft={staleTTL:1e3*60,maxAge:1e3*60*60*4,cacheKey:"gbFeaturesCache",backgroundSync:!0,maxEntries:10,disableIdleStreams:!1,idleStreamInterval:2e4,disableCache:!1},_r=LI(),Es={fetchFeaturesCall:({host:t,clientKey:e,headers:a})=>_r.fetch(`${t}/api/features/${e}`,{headers:a}),fetchRemoteEvalCall:({host:t,clientKey:e,payload:a,headers:r})=>{let n={method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify(a)};return _r.fetch(`${t}/api/eval/${e}`,n)},eventSourceCall:({host:t,clientKey:e,headers:a})=>a?new _r.EventSource(`${t}/sub/${e}`,{headers:a}):new _r.EventSource(`${t}/sub/${e}`),startIdleListener:()=>{let t;if(!(typeof window<"u"&&typeof document<"u"))return;let a=()=>{document.visibilityState==="visible"?(window.clearTimeout(t),IN()):document.visibilityState==="hidden"&&(t=window.setTimeout(kN,Ft.idleStreamInterval))};return document.addEventListener("visibilitychange",a),()=>document.removeEventListener("visibilitychange",a)},stopIdleListener:()=>{}};try{globalThis.localStorage&&(_r.localStorage=globalThis.localStorage)}catch{}var Ts=new Map,OI=!1,nn=new Map,gp=new Map,Rs=new Map,Ms=new Set;function BI(t){Object.assign(Ft,t),Ft.backgroundSync||Hy()}async function PI({instance:t,timeout:e,skipCache:a,allowStale:r,backgroundSync:n}){return n||(Ft.backgroundSync=!1),AN({instance:t,allowStale:r,timeout:e,skipCache:a})}function LN(t){let e=$u(t),a=Ts.get(e)||new Set;a.add(t),Ts.set(e,a)}function NI(t){Ts.forEach(e=>e.delete(t))}function kN(){Rs.forEach(t=>{t&&(t.state="idle",Ny(t))})}function IN(){Rs.forEach(t=>{t&&t.state==="idle"&&Fy(t)})}async function DI(){try{if(!_r.localStorage)return;await _r.localStorage.setItem(Ft.cacheKey,JSON.stringify(Array.from(nn.entries())))}catch{}}async function AN({instance:t,allowStale:e,timeout:a,skipCache:r}){let n=$u(t),o=By(t),i=new Date,s=new Date(i.getTime()-Ft.maxAge+Ft.staleTTL);await EN();let l=!Ft.disableCache&&!r?nn.get(o):void 0;return l&&(e||l.staleAt>i)&&l.staleAt>s?(l.sse&&Ms.add(n),l.staleAt<i?Dy(t):Py(t),{data:l.data,success:!0,source:"cache"}):await mp(Dy(t),a)||{data:null,success:!1,source:"timeout",error:new Error("Timeout")}}function $u(t){let[e,a]=t.getApiInfo();return`${e}||${a}`}function By(t){let e=$u(t);if(!("isRemoteEval"in t)||!t.isRemoteEval())return e;let a=t.getAttributes(),r=t.getCacheKeyAttributes()||Object.keys(t.getAttributes()),n={};r.forEach(s=>{n[s]=a[s]});let o=t.getForcedVariations(),i=t.getUrl();return`${e}||${JSON.stringify({ca:n,fv:o,url:i})}`}async function EN(){if(!OI){OI=!0;try{if(_r.localStorage){let t=await _r.localStorage.getItem(Ft.cacheKey);if(!Ft.disableCache&&t){let e=JSON.parse(t);e&&Array.isArray(e)&&e.forEach(([a,r])=>{nn.set(a,{...r,staleAt:new Date(r.staleAt)})}),FI()}}}catch{}if(!Ft.disableIdleStreams){let t=Es.startIdleListener();t&&(Es.stopIdleListener=t)}}}function FI(){let t=Array.from(nn.entries()).map(([a,r])=>({key:a,staleAt:r.staleAt.getTime()})).sort((a,r)=>a.staleAt-r.staleAt),e=Math.min(Math.max(0,nn.size-Ft.maxEntries),nn.size);for(let a=0;a<e;a++)nn.delete(t[a].key)}function HI(t,e,a){let r=a.dateUpdated||"",n=new Date(Date.now()+Ft.staleTTL),o=Ft.disableCache?void 0:nn.get(e);if(o&&r&&o.version===r){o.staleAt=n,DI();return}Ft.disableCache||(nn.set(e,{data:a,version:r,staleAt:n,sse:Ms.has(t)}),FI()),DI();let i=Ts.get(t);i&&i.forEach(s=>TN(s,a))}async function TN(t,e){await t.setPayload(e||t.getPayload())}async function Dy(t){let{apiHost:e,apiRequestHeaders:a}=t.getApiHosts(),r=t.getClientKey(),n="isRemoteEval"in t&&t.isRemoteEval(),o=$u(t),i=By(t),s=gp.get(i);return s||(s=(n?Es.fetchRemoteEvalCall({host:e,clientKey:r,payload:{attributes:t.getAttributes(),forcedVariations:t.getForcedVariations(),forcedFeatures:Array.from(t.getForcedFeatures().entries()),url:t.getUrl()},headers:a}):Es.fetchFeaturesCall({host:e,clientKey:r,headers:a})).then(u=>{if(!u.ok)throw new Error(`HTTP error: ${u.status}`);return u.headers.get("x-sse-support")==="enabled"&&Ms.add(o),u.json()}).then(u=>(HI(o,i,u),Py(t),gp.delete(i),{data:u,success:!0,source:"network"})).catch(u=>(gp.delete(i),{data:null,source:"error",success:!1,error:u})),gp.set(i,s)),s}function Py(t,e=!1){let a=$u(t),r=By(t),{streamingHost:n,streamingHostRequestHeaders:o}=t.getApiHosts(),i=t.getClientKey();if(e&&Ms.add(a),Ft.backgroundSync&&Ms.has(a)&&_r.EventSource){if(Rs.has(a))return;let s={src:null,host:n,clientKey:i,headers:o,cb:l=>{try{if(l.type==="features-updated"){let u=Ts.get(a);u&&u.forEach(c=>{Dy(c)})}else if(l.type==="features"){let u=JSON.parse(l.data);HI(a,r,u)}s.errors=0}catch{UI(s)}},errors:0,state:"active"};Rs.set(a,s),Fy(s)}}function UI(t){if(t.state!=="idle"&&(t.errors++,t.errors>3||t.src&&t.src.readyState===2)){let e=Math.pow(3,t.errors-3)*(1e3+Math.random()*1e3);Ny(t),setTimeout(()=>{["idle","active"].includes(t.state)||Fy(t)},Math.min(e,3e5))}}function Ny(t){t.src&&(t.src.onopen=null,t.src.onerror=null,t.src.close(),t.src=null,t.state==="active"&&(t.state="disabled"))}function Fy(t){t.src=Es.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=()=>UI(t),t.src.onopen=()=>{t.errors=0}}function RN(t,e){Ny(t),Rs.delete(e)}function Hy(){Ms.clear(),Rs.forEach(RN),Ts.clear(),Es.stopIdleListener()}function vp(t,e){if(e.streaming){if(!t.getClientKey())throw new Error("Must specify clientKey to enable streaming");e.payload&&Py(t,!0),LN(t)}}var MN=/^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/,qy={revert:function(){}},Sp=new Map,Vy=new Set;function ON(t){return t==="html"?{childList:!0,subtree:!0,attributes:!0,characterData:!0}:{childList:!1,subtree:!1,attributes:!0,attributeFilter:[t]}}function _p(t){var e=Sp.get(t);return e||(e={element:t,attributes:{}},Sp.set(t,e)),e}function Cp(t,e,a,r,n){var o=a(t),i={isDirty:!1,originalValue:o,virtualValue:o,mutations:[],el:t,_positionTimeout:null,observer:new MutationObserver(function(){if(!(e==="position"&&i._positionTimeout)){e==="position"&&(i._positionTimeout=setTimeout(function(){i._positionTimeout=null},1e3));var s=a(t);e==="position"&&s.parentNode===i.virtualValue.parentNode&&s.insertBeforeNode===i.virtualValue.insertBeforeNode||s!==i.virtualValue&&(i.originalValue=s,n(i))}}),mutationRunner:n,setValue:r,getCurrentValue:a};return e==="position"&&t.parentNode?i.observer.observe(t.parentNode,{childList:!0,subtree:!0,attributes:!1,characterData:!1}):i.observer.observe(t,ON(e)),i}function wp(t,e){var a=e.getCurrentValue(e.el);e.virtualValue=t,t&&typeof t!="string"?(!a||t.parentNode!==a.parentNode||t.insertBeforeNode!==a.insertBeforeNode)&&(e.isDirty=!0,zI()):t!==a&&(e.isDirty=!0,zI())}function DN(t){var e=t.originalValue;t.mutations.forEach(function(a){return e=a.mutate(e)}),wp(ZN(e),t)}function BN(t){var e=new Set(t.originalValue.split(/\s+/).filter(Boolean));t.mutations.forEach(function(a){return a.mutate(e)}),wp(Array.from(e).filter(Boolean).join(" "),t)}function PN(t){var e=t.originalValue;t.mutations.forEach(function(a){return e=a.mutate(e)}),wp(e,t)}function NN(t){var e=t.parentSelector,a=t.insertBeforeSelector,r=document.querySelector(e);if(!r)return null;var n=a?document.querySelector(a):null;return a&&!n?null:{parentNode:r,insertBeforeNode:n}}function FN(t){var e=t.originalValue;t.mutations.forEach(function(a){var r=a.mutate(),n=NN(r);e=n||e}),wp(e,t)}var HN=function(e){return e.innerHTML},UN=function(e,a){return e.innerHTML=a};function VI(t){var e=_p(t);return e.html||(e.html=Cp(t,"html",HN,UN,DN)),e.html}var zN=function(e){return{parentNode:e.parentElement,insertBeforeNode:e.nextElementSibling}},qN=function(e,a){a.insertBeforeNode&&!a.parentNode.contains(a.insertBeforeNode)||a.parentNode.insertBefore(e,a.insertBeforeNode)};function $I(t){var e=_p(t);return e.position||(e.position=Cp(t,"position",zN,qN,FN)),e.position}var VN=function(e,a){return a?e.className=a:e.removeAttribute("class")},$N=function(e){return e.className};function jI(t){var e=_p(t);return e.classes||(e.classes=Cp(t,"class",$N,VN,BN)),e.classes}var jN=function(e){return function(a){var r;return(r=a.getAttribute(e))!=null?r:null}},GN=function(e){return function(a,r){return r!==null?a.setAttribute(e,r):a.removeAttribute(e)}};function GI(t,e){var a=_p(t);return a.attributes[e]||(a.attributes[e]=Cp(t,e,jN(e),GN(e),PN)),a.attributes[e]}function WN(t,e){var a=Sp.get(t);if(a)if(e==="html"){var r,n;(r=a.html)==null||(n=r.observer)==null||n.disconnect(),delete a.html}else if(e==="class"){var o,i;(o=a.classes)==null||(i=o.observer)==null||i.disconnect(),delete a.classes}else if(e==="position"){var s,l;(s=a.position)==null||(l=s.observer)==null||l.disconnect(),delete a.position}else{var u,c,d;(u=a.attributes)==null||(c=u[e])==null||(d=c.observer)==null||d.disconnect(),delete a.attributes[e]}}var yp;function ZN(t){return yp||(yp=document.createElement("div")),yp.innerHTML=t,yp.innerHTML}function xp(t,e,a){if(a.isDirty){a.isDirty=!1;var r=a.virtualValue;a.mutations.length||WN(t,e),a.setValue(t,r)}}function XN(t,e){t.html&&xp(e,"html",t.html),t.classes&&xp(e,"class",t.classes),t.position&&xp(e,"position",t.position),Object.keys(t.attributes).forEach(function(a){xp(e,a,t.attributes[a])})}function zI(){Sp.forEach(XN)}function KN(t,e){var a=null;t.kind==="html"?a=VI(e):t.kind==="class"?a=jI(e):t.kind==="attribute"?a=GI(e,t.attribute):t.kind==="position"&&(a=$I(e)),a&&(a.mutations.push(t),a.mutationRunner(a))}function YN(t,e){var a=null;if(t.kind==="html"?a=VI(e):t.kind==="class"?a=jI(e):t.kind==="attribute"?a=GI(e,t.attribute):t.kind==="position"&&(a=$I(e)),!!a){var r=a.mutations.indexOf(t);r!==-1&&a.mutations.splice(r,1),a.mutationRunner(a)}}function WI(t){if(!(t.kind==="position"&&t.elements.size===1)){var e=new Set(t.elements),a=document.querySelectorAll(t.selector);a.forEach(function(r){e.has(r)||(t.elements.add(r),KN(t,r))})}}function QN(t){t.elements.forEach(function(e){return YN(t,e)}),t.elements.clear(),Vy.delete(t)}function qI(){Vy.forEach(WI)}var Uy;function JN(){typeof document>"u"||(Uy||(Uy=new MutationObserver(function(){qI()})),qI(),Uy.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}JN();function Lp(t){return typeof document>"u"?qy:(Vy.add(t),WI(t),{revert:function(){QN(t)}})}function zy(t,e){return Lp({kind:"html",elements:new Set,mutate:e,selector:t})}function ZI(t,e){return Lp({kind:"position",elements:new Set,mutate:e,selector:t})}function ju(t,e){return Lp({kind:"class",elements:new Set,mutate:e,selector:t})}function bp(t,e,a){return MN.test(e)?e==="class"||e==="className"?ju(t,function(r){var n=a(Array.from(r).join(" "));r.clear(),n&&n.split(/\s+/g).filter(Boolean).forEach(function(o){return r.add(o)})}):Lp({kind:"attribute",attribute:e,elements:new Set,mutate:a,selector:t}):qy}function eF(t){var e=t.selector,a=t.action,r=t.value,n=t.attribute,o=t.parentSelector,i=t.insertBeforeSelector;if(n==="html"){if(a==="append")return zy(e,function(s){return s+(r??"")});if(a==="set")return zy(e,function(){return r??""})}else if(n==="class"){if(a==="append")return ju(e,function(s){r&&s.add(r)});if(a==="remove")return ju(e,function(s){r&&s.delete(r)});if(a==="set")return ju(e,function(s){s.clear(),r&&s.add(r)})}else if(n==="position"){if(a==="set"&&o)return ZI(e,function(){return{insertBeforeSelector:i,parentSelector:o}})}else{if(a==="append")return bp(e,n,function(s){return s!==null?s+(r??""):r??""});if(a==="set")return bp(e,n,function(){return r??""});if(a==="remove")return bp(e,n,function(){return null})}return qy}var tF={html:zy,classes:ju,attribute:bp,position:ZI,declarative:eF},XI=tF;var $y={};function co(t,e,a){a=a||{};for(let[r,n]of Object.entries(e))switch(r){case"$or":if(!QI(t,n,a))return!1;break;case"$nor":if(QI(t,n,a))return!1;break;case"$and":if(!iF(t,n,a))return!1;break;case"$not":if(co(t,n,a))return!1;break;default:if(!Gu(n,aF(t,r),a))return!1}return!0}function aF(t,e){let a=e.split("."),r=t;for(let n=0;n<a.length;n++)if(r&&typeof r=="object"&&a[n]in r)r=r[a[n]];else return null;return r}function KI(t,e=!1){let a=`${t}${e?"/i":""}`;return $y[a]||($y[a]=new RegExp(t.replace(/([^\\])\//g,"$1\\/"),e?"i":void 0)),$y[a]}function Gu(t,e,a,r=!1){if(typeof t=="string")return r?String(e).toLowerCase()===t.toLowerCase():e+""===t;if(typeof t=="number")return e*1===t;if(typeof t=="boolean")return e!==null&&!!e===t;if(t===null)return e===null;if(Array.isArray(t)||!JI(t))return JSON.stringify(e)===JSON.stringify(t);for(let n in t)if(!oF(n,e,t[n],a))return!1;return!0}function JI(t){let e=Object.keys(t);return e.length>0&&e.filter(a=>a[0]==="$").length===e.length}function rF(t){if(t===null)return"null";if(Array.isArray(t))return"array";let e=typeof t;return["string","number","boolean","object","undefined"].includes(e)?e:"unknown"}function nF(t,e,a){if(!Array.isArray(t))return!1;let r=JI(e)?n=>Gu(e,n,a):n=>co(n,e,a);for(let n=0;n<t.length;n++)if(t[n]&&r(t[n]))return!0;return!1}function Os(t,e,a=!1){if(a){let r=n=>typeof n=="string"?n.toLowerCase():n;return Array.isArray(t)?t.some(n=>e.some(o=>r(n)===r(o))):e.some(n=>r(t)===r(n))}return Array.isArray(t)?t.some(r=>e.includes(r)):e.includes(t)}function YI(t,e,a,r=!1){if(!Array.isArray(t))return!1;for(let n=0;n<e.length;n++){let o=!1;for(let i=0;i<t.length;i++)if(Gu(e[n],t[i],a,r)){o=!0;break}if(!o)return!1}return!0}function oF(t,e,a,r){switch(t){case"$veq":return wa(e)===wa(a);case"$vne":return wa(e)!==wa(a);case"$vgt":return wa(e)>wa(a);case"$vgte":return wa(e)>=wa(a);case"$vlt":return wa(e)<wa(a);case"$vlte":return wa(e)<=wa(a);case"$eq":return e===a;case"$ne":return e!==a;case"$lt":return e<a;case"$lte":return e<=a;case"$gt":return e>a;case"$gte":return e>=a;case"$exists":return a?e!=null:e==null;case"$in":return Array.isArray(a)?Os(e,a):!1;case"$ini":return Array.isArray(a)?Os(e,a,!0):!1;case"$inGroup":return Os(e,r[a]||[]);case"$notInGroup":return!Os(e,r[a]||[]);case"$nin":return Array.isArray(a)?!Os(e,a):!1;case"$nini":return Array.isArray(a)?!Os(e,a,!0):!1;case"$not":return!Gu(a,e,r);case"$size":return Array.isArray(e)?Gu(a,e.length,r):!1;case"$elemMatch":return nF(e,a,r);case"$all":return Array.isArray(a)?YI(e,a,r):!1;case"$alli":return Array.isArray(a)?YI(e,a,r,!0):!1;case"$regex":try{return KI(a).test(e)}catch{return!1}case"$regexi":try{return KI(a,!0).test(e)}catch{return!1}case"$type":return rF(e)===a;default:return console.error("Unknown operator: "+t),!1}}function QI(t,e,a){if(!e.length)return!0;for(let r=0;r<e.length;r++)if(co(t,e[r],a))return!0;return!1}function iF(t,e,a){for(let r=0;r<e.length;r++)if(!co(t,e[r],a))return!1;return!0}var sF="Feature Evaluated",lF="Experiment Viewed";function uF(t){let e=new Map;return t.global.forcedFeatureValues&&t.global.forcedFeatureValues.forEach((a,r)=>e.set(r,a)),t.user.forcedFeatureValues&&t.user.forcedFeatureValues.forEach((a,r)=>e.set(r,a)),e}function cF(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:{}}async function Ds(t){try{await t()}catch{}}function eA(t,e,a){if(t.user.trackedExperiments){let n=Ap(e,a);if(t.user.trackedExperiments.has(n))return[];t.user.trackedExperiments.add(n)}t.user.enableDevMode&&t.user.devLogs&&t.user.devLogs.push({experiment:e,result:a,timestamp:Date.now().toString(),logType:"experiment"});let r=[];if(t.global.trackingCallback){let n=t.global.trackingCallback;r.push(Ds(()=>n(e,a,t.user)))}if(t.user.trackingCallback){let n=t.user.trackingCallback;r.push(Ds(()=>n(e,a)))}if(t.global.eventLogger){let n=t.global.eventLogger;r.push(Ds(()=>n(lF,{experimentId:e.key,variationId:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue},t.user)))}return r}function dF(t,e,a){if(t.user.trackedFeatureUsage){let r=JSON.stringify(a.value);if(t.user.trackedFeatureUsage[e]===r)return;t.user.trackedFeatureUsage[e]=r,t.user.enableDevMode&&t.user.devLogs&&t.user.devLogs.push({featureKey:e,result:a,timestamp:Date.now().toString(),logType:"feature"})}if(t.global.onFeatureUsage){let r=t.global.onFeatureUsage;Ds(()=>r(e,a,t.user))}if(t.user.onFeatureUsage){let r=t.user.onFeatureUsage;Ds(()=>r(e,a))}if(t.global.eventLogger){let r=t.global.eventLogger;Ds(()=>r(sF,{feature:e,source:a.source,value:a.value,ruleId:a.source==="defaultValue"?"$default":a.ruleId||"",variationId:a.experimentResult?a.experimentResult.key:""},t.user))}}function kp(t,e){if(e.stack.evaluatedFeatures.has(t))return fo(e,t,null,"cyclicPrerequisite");e.stack.evaluatedFeatures.add(t),e.stack.id=t;let a=uF(e);if(a.has(t))return fo(e,t,a.get(t),"override");if(!e.global.features||!e.global.features[t])return fo(e,t,null,"unknownFeature");let r=e.global.features[t];if(r.rules){let n=new Set(e.stack.evaluatedFeatures);e:for(let o of r.rules){if(o.parentConditions)for(let l of o.parentConditions){e.stack.evaluatedFeatures=new Set(n);let u=kp(l.id,e);if(u.source==="cyclicPrerequisite")return fo(e,t,null,"cyclicPrerequisite");let c={value:u.value};if(!co(c,l.condition||{})){if(l.gate)return fo(e,t,null,"prerequisite");continue e}}if(o.filters&&rA(o.filters,e))continue;if("force"in o){if(o.condition&&!aA(o.condition,e)||!fF(e,o.seed||t,o.hashAttribute,e.user.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion))continue;return o.tracks&&o.tracks.forEach(l=>{!eA(e,l.experiment,l.result).length&&e.global.saveDeferredTrack&&e.global.saveDeferredTrack({experiment:l.experiment,result:l.result})}),fo(e,t,o.force,"force",o.id)}if(!o.variations)continue;let i={variations:o.variations,key:o.key||t};"coverage"in o&&(i.coverage=o.coverage),o.weights&&(i.weights=o.weights),o.hashAttribute&&(i.hashAttribute=o.hashAttribute),o.fallbackAttribute&&(i.fallbackAttribute=o.fallbackAttribute),o.disableStickyBucketing&&(i.disableStickyBucketing=o.disableStickyBucketing),o.bucketVersion!==void 0&&(i.bucketVersion=o.bucketVersion),o.minBucketVersion!==void 0&&(i.minBucketVersion=o.minBucketVersion),o.namespace&&(i.namespace=o.namespace),o.meta&&(i.meta=o.meta),o.ranges&&(i.ranges=o.ranges),o.name&&(i.name=o.name),o.phase&&(i.phase=o.phase),o.seed&&(i.seed=o.seed),o.hashVersion&&(i.hashVersion=o.hashVersion),o.filters&&(i.filters=o.filters),o.condition&&(i.condition=o.condition);let{result:s}=Ip(i,t,e);if(e.global.onExperimentEval&&e.global.onExperimentEval(i,s),s.inExperiment&&!s.passthrough)return fo(e,t,s.value,"experiment",o.id,i,s)}}return fo(e,t,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function Ip(t,e,a){let r=t.key,n=t.variations.length;if(n<2)return{result:Ze(a,t,-1,!1,e)};if(a.global.enabled===!1||a.user.enabled===!1)return{result:Ze(a,t,-1,!1,e)};if(t=pF(t,a),t.urlPatterns&&!pp(a.user.url||"",t.urlPatterns))return{result:Ze(a,t,-1,!1,e)};let o=EI(r,a.user.url||"",n);if(o!==null)return{result:Ze(a,t,o,!1,e)};let i=cF(a);if(r in i){let b=i[r];return{result:Ze(a,t,b,!1,e)}}if(t.status==="draft"||t.active===!1)return{result:Ze(a,t,-1,!1,e)};let{hashAttribute:s,hashValue:l}=oi(a,t.hashAttribute,a.user.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0);if(!l)return{result:Ze(a,t,-1,!1,e)};let u=-1,c=!1,d=!1;if(a.user.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing){let{variation:b,versionIsBlocked:g}=gF({ctx:a,expKey:t.key,expBucketVersion:t.bucketVersion,expHashAttribute:t.hashAttribute,expFallbackAttribute:t.fallbackAttribute,expMinBucketVersion:t.minBucketVersion,expMeta:t.meta});c=b>=0,u=b,d=!!g}if(!c){if(t.filters){if(rA(t.filters,a))return{result:Ze(a,t,-1,!1,e)}}else if(t.namespace&&!kI(l,t.namespace))return{result:Ze(a,t,-1,!1,e)};if(t.include&&!TI(t.include))return{result:Ze(a,t,-1,!1,e)};if(t.condition&&!aA(t.condition,a))return{result:Ze(a,t,-1,!1,e)};if(t.parentConditions){let b=new Set(a.stack.evaluatedFeatures);for(let g of t.parentConditions){a.stack.evaluatedFeatures=new Set(b);let m=kp(g.id,a);if(m.source==="cyclicPrerequisite")return{result:Ze(a,t,-1,!1,e)};let y={value:m.value};if(!co(y,g.condition||{}))return{result:Ze(a,t,-1,!1,e)}}}if(t.groups&&!mF(t.groups,a))return{result:Ze(a,t,-1,!1,e)}}if(t.url&&!hF(t.url,a))return{result:Ze(a,t,-1,!1,e)};let f=qu(t.seed||r,l,t.hashVersion||1);if(f===null)return{result:Ze(a,t,-1,!1,e)};if(!c){let b=t.ranges||AI(n,t.coverage===void 0?1:t.coverage,t.weights);u=II(f,b)}if(d)return{result:Ze(a,t,-1,!1,e,void 0,!0)};if(u<0)return{result:Ze(a,t,-1,!1,e)};if("force"in t)return{result:Ze(a,t,t.force===void 0?-1:t.force,!1,e)};if(a.global.qaMode||a.user.qaMode)return{result:Ze(a,t,-1,!1,e)};if(t.status==="stopped")return{result:Ze(a,t,-1,!1,e)};let h=Ze(a,t,u,!0,e,f,c);if(a.user.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing){let{changed:b,key:g,doc:m}=yF(a,s,Vu(l),{[jy(t.key,t.bucketVersion)]:h.key});b&&(a.user.stickyBucketAssignmentDocs=a.user.stickyBucketAssignmentDocs||{},a.user.stickyBucketAssignmentDocs[g]=m,a.user.saveStickyBucketAssignmentDoc(m))}let S=eA(a,t,h);S.length===0&&a.global.saveDeferredTrack&&a.global.saveDeferredTrack({experiment:t,result:h});let x=S.length?S.length===1?S[0]:Promise.all(S).then(()=>{}):void 0;return"changeId"in t&&t.changeId&&a.global.recordChangeId&&a.global.recordChangeId(t.changeId),{result:h,trackingCall:x}}function fo(t,e,a,r,n,o,i){let s={value:a,on:!!a,off:!a,source:r,ruleId:n||""};return o&&(s.experiment=o),i&&(s.experimentResult=i),r!=="override"&&dF(t,e,s),s}function tA(t){return{...t.user.attributes,...t.user.attributeOverrides}}function aA(t,e){return co(tA(e),t,e.global.savedGroups||{})}function rA(t,e){return t.some(a=>{let{hashValue:r}=oi(e,a.attribute);if(!r)return!0;let n=qu(a.seed,r,a.hashVersion||2);return n===null?!0:!a.ranges.some(o=>fp(n,o))})}function fF(t,e,a,r,n,o,i){if(!n&&o===void 0)return!0;if(!n&&o===0)return!1;let{hashValue:s}=oi(t,a,r);if(!s)return!1;let l=qu(e,s,i||1);return l===null?!1:n?fp(l,n):o!==void 0?l<=o:!0}function Ze(t,e,a,r,n,o,i){let s=!0;(a<0||a>=e.variations.length)&&(a=0,s=!1);let{hashAttribute:l,hashValue:u}=oi(t,e.hashAttribute,t.user.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0),c=e.meta?e.meta[a]:{},d={key:c.key||""+a,featureId:n,inExperiment:s,hashUsed:r,variationId:a,value:e.variations[a],hashAttribute:l,hashValue:u,stickyBucketUsed:!!i};return c.name&&(d.name=c.name),o!==void 0&&(d.bucket=o),c.passthrough&&(d.passthrough=c.passthrough),d}function pF(t,e){let a=t.key,r=e.global.overrides;return r&&r[a]&&(t=Object.assign({},t,r[a]),typeof t.url=="string"&&(t.url=Oy(t.url))),t}function oi(t,e,a){let r=e||"id",n="",o=tA(t);return o[r]&&(n=o[r]),!n&&a&&(o[a]&&(n=o[a]),n&&(r=a)),{hashAttribute:r,hashValue:n}}function hF(t,e){let a=e.user.url;if(!a)return!1;let r=a.replace(/^https?:\/\//,"").replace(/^[^/]*\//,"/");return!!(t.test(a)||t.test(r))}function mF(t,e){let a=e.global.groups||{};for(let r=0;r<t.length;r++)if(a[t[r]])return!0;return!1}function gF({ctx:t,expKey:e,expBucketVersion:a,expHashAttribute:r,expFallbackAttribute:n,expMinBucketVersion:o,expMeta:i}){a=a||0,o=o||0,r=r||"id",i=i||[];let s=jy(e,a),l=vF(t,r,n);if(o>0)for(let d=0;d<o;d++){let f=jy(e,d);if(l[f]!==void 0)return{variation:-1,versionIsBlocked:!0}}let u=l[s];if(u===void 0)return{variation:-1};let c=i.findIndex(d=>d.key===u);return c<0?{variation:-1}:{variation:c}}function jy(t,e){return e=e||0,`${t}__${e}`}function Gy(t,e){return`${t}||${e}`}function vF(t,e,a){if(!t.user.stickyBucketAssignmentDocs)return{};let{hashAttribute:r,hashValue:n}=oi(t,e),o=Gy(r,Vu(n)),{hashAttribute:i,hashValue:s}=oi(t,a),l=s?Gy(i,Vu(s)):null,u={};return l&&t.user.stickyBucketAssignmentDocs[l]&&Object.assign(u,t.user.stickyBucketAssignmentDocs[l].assignments||{}),t.user.stickyBucketAssignmentDocs[o]&&Object.assign(u,t.user.stickyBucketAssignmentDocs[o].assignments||{}),u}function yF(t,e,a,r){let n=Gy(e,a),o=t.user.stickyBucketAssignmentDocs&&t.user.stickyBucketAssignmentDocs[n]?t.user.stickyBucketAssignmentDocs[n].assignments||{}:{},i={...o,...r},s=JSON.stringify(o)!==JSON.stringify(i);return{key:n,doc:{attributeName:e,attributeValue:a,assignments:i},changed:s}}function xF(t,e){let a=new Set,r=e&&e.features?e.features:t.global.features||{},n=e&&e.experiments?e.experiments:t.global.experiments||[];return Object.keys(r).forEach(o=>{let i=r[o];if(i.rules)for(let s of i.rules)s.variations&&(a.add(s.hashAttribute||"id"),s.fallbackAttribute&&a.add(s.fallbackAttribute))}),n.map(o=>{a.add(o.hashAttribute||"id"),o.fallbackAttribute&&a.add(o.fallbackAttribute)}),Array.from(a)}async function nA(t,e,a){let r=Wy(t,a);return e.getAllAssignments(r)}function Wy(t,e){let a={};return xF(t,e).forEach(n=>{let{hashValue:o}=oi(t,n);a[n]=Vu(o)}),a}async function oA(t,e,a){if(t={...t},t.encryptedFeatures){try{t.features=JSON.parse(await ni(t.encryptedFeatures,e,a))}catch(r){console.error(r)}delete t.encryptedFeatures}if(t.encryptedExperiments){try{t.experiments=JSON.parse(await ni(t.encryptedExperiments,e,a))}catch(r){console.error(r)}delete t.encryptedExperiments}if(t.encryptedSavedGroups){try{t.savedGroups=JSON.parse(await ni(t.encryptedSavedGroups,e,a))}catch(r){console.error(r)}delete t.encryptedSavedGroups}return t}function iA(t){let e=t.apiHost||"https://cdn.growthbook.io";return{apiHost:e.replace(/\/*$/,""),streamingHost:(t.streamingHost||e).replace(/\/*$/,""),apiRequestHeaders:t.apiHostRequestHeaders,streamingHostRequestHeaders:t.streamingHostRequestHeaders}}function Ap(t,e){return e.hashAttribute+e.hashValue+t.key+e.variationId}var Bs=typeof window<"u"&&typeof document<"u",bF=RI(),Wu=class{constructor(e){if(e=e||{},this.version=bF,this._options=this.context=e,this._renderer=e.renderer||null,this._trackedExperiments=new Set,this._completedChangeIds=new Set,this._trackedFeatures={},this.debug=!!e.debug,this._subscriptions=new Set,this.ready=!1,this._assigned=new Map,this._activeAutoExperiments=new Map,this._triggeredExpKeys=new Set,this._initialized=!1,this._redirectedUrl="",this._deferredTrackingCalls=new Map,this._autoExperimentsAllowed=!e.disableExperimentsOnLoad,this._destroyCallbacks=[],this.logs=[],this.log=this.log.bind(this),this._saveDeferredTrack=this._saveDeferredTrack.bind(this),this._onExperimentEval=this._onExperimentEval.bind(this),this._fireSubscriptions=this._fireSubscriptions.bind(this),this._recordChangedId=this._recordChangedId.bind(this),e.remoteEval){if(e.decryptionKey)throw new Error("Encryption is not available for remoteEval");if(!e.clientKey)throw new Error("Missing clientKey");let a=!1;try{a=!!new URL(e.apiHost||"").hostname.match(/growthbook\.io$/i)}catch{}if(a)throw new Error("Cannot use remoteEval on GrowthBook Cloud")}else if(e.cacheKeyAttributes)throw new Error("cacheKeyAttributes are only used for remoteEval");if(e.stickyBucketService){let a=e.stickyBucketService;this._saveStickyBucketAssignmentDoc=r=>a.saveAssignments(r)}if(e.plugins)for(let a of e.plugins)a(this);if(e.features&&(this.ready=!0),Bs&&e.enableDevMode&&(window._growthbook=this,document.dispatchEvent(new Event("gbloaded"))),e.experiments&&(this.ready=!0,this._updateAllAutoExperiments()),this._options.stickyBucketService&&this._options.stickyBucketAssignmentDocs)for(let a in this._options.stickyBucketAssignmentDocs){let r=this._options.stickyBucketAssignmentDocs[a];r&&this._options.stickyBucketService.saveAssignments(r).catch(()=>{})}this.ready&&this.refreshStickyBuckets(this.getPayload())}async setPayload(e){this._payload=e;let a=await oA(e,this._options.decryptionKey);this._decryptedPayload=a,await this.refreshStickyBuckets(a),a.features&&(this._options.features=a.features),a.savedGroups&&(this._options.savedGroups=a.savedGroups),a.experiments&&(this._options.experiments=a.experiments,this._updateAllAutoExperiments()),this.ready=!0,this._render()}initSync(e){this._initialized=!0;let a=e.payload;if(a.encryptedExperiments||a.encryptedFeatures)throw new Error("initSync does not support encrypted payloads");return this._options.stickyBucketService&&!this._options.stickyBucketAssignmentDocs&&(this._options.stickyBucketAssignmentDocs=this.generateStickyBucketAssignmentDocsSync(this._options.stickyBucketService,a)),this._payload=a,this._decryptedPayload=a,a.features&&(this._options.features=a.features),a.experiments&&(this._options.experiments=a.experiments,this._updateAllAutoExperiments()),this.ready=!0,vp(this,e),this}async init(e){if(this._initialized=!0,e=e||{},e.cacheSettings&&BI(e.cacheSettings),e.payload)return await this.setPayload(e.payload),vp(this,e),{success:!0,source:"init"};{let{data:a,...r}=await this._refresh({...e,allowStale:!0});return vp(this,e),await this.setPayload(a||{}),r}}async loadFeatures(e){e=e||{},await this.init({skipCache:e.skipCache,timeout:e.timeout,streaming:(this._options.backgroundSync??!0)&&(e.autoRefresh||this._options.subscribeToChanges)})}async refreshFeatures(e){let a=await this._refresh({...e||{},allowStale:!1});a.data&&await this.setPayload(a.data)}getApiInfo(){return[this.getApiHosts().apiHost,this.getClientKey()]}getApiHosts(){return iA(this._options)}getClientKey(){return this._options.clientKey||""}getPayload(){return this._payload||{features:this.getFeatures(),experiments:this.getExperiments()}}getDecryptedPayload(){return this._decryptedPayload||this.getPayload()}isRemoteEval(){return this._options.remoteEval||!1}getCacheKeyAttributes(){return this._options.cacheKeyAttributes}async _refresh({timeout:e,skipCache:a,allowStale:r,streaming:n}){if(!this._options.clientKey)throw new Error("Missing clientKey");return PI({instance:this,timeout:e,skipCache:a||this._options.disableCache,allowStale:r,backgroundSync:n??this._options.backgroundSync??!0})}_render(){if(this._renderer)try{this._renderer()}catch(e){console.error("Failed to render",e)}}setFeatures(e){this._options.features=e,this.ready=!0,this._render()}async setEncryptedFeatures(e,a,r){let n=await ni(e,a||this._options.decryptionKey,r);this.setFeatures(JSON.parse(n))}setExperiments(e){this._options.experiments=e,this.ready=!0,this._updateAllAutoExperiments()}async setEncryptedExperiments(e,a,r){let n=await ni(e,a||this._options.decryptionKey,r);this.setExperiments(JSON.parse(n))}async setAttributes(e){if(this._options.attributes=e,this._options.stickyBucketService&&await this.refreshStickyBuckets(),this._options.remoteEval){await this._refreshForRemoteEval();return}this._render(),this._updateAllAutoExperiments()}async updateAttributes(e){return this.setAttributes({...this._options.attributes,...e})}async setAttributeOverrides(e){if(this._options.attributeOverrides=e,this._options.stickyBucketService&&await this.refreshStickyBuckets(),this._options.remoteEval){await this._refreshForRemoteEval();return}this._render(),this._updateAllAutoExperiments()}async setForcedVariations(e){if(this._options.forcedVariations=e||{},this._options.remoteEval){await this._refreshForRemoteEval();return}this._render(),this._updateAllAutoExperiments()}setForcedFeatures(e){this._options.forcedFeatureValues=e,this._render()}async setURL(e){if(e!==this._options.url){if(this._options.url=e,this._redirectedUrl="",this._options.remoteEval){await this._refreshForRemoteEval(),this._updateAllAutoExperiments(!0);return}this._updateAllAutoExperiments(!0)}}getAttributes(){return{...this._options.attributes,...this._options.attributeOverrides}}getForcedVariations(){return this._options.forcedVariations||{}}getForcedFeatures(){return this._options.forcedFeatureValues||new Map}getStickyBucketAssignmentDocs(){return this._options.stickyBucketAssignmentDocs||{}}getUrl(){return this._options.url||""}getFeatures(){return this._options.features||{}}getExperiments(){return this._options.experiments||[]}getCompletedChangeIds(){return Array.from(this._completedChangeIds)}subscribe(e){return this._subscriptions.add(e),()=>{this._subscriptions.delete(e)}}async _refreshForRemoteEval(){if(!this._options.remoteEval||!this._initialized)return;let e=await this._refresh({allowStale:!1});e.data&&await this.setPayload(e.data)}getAllResults(){return new Map(this._assigned)}onDestroy(e){this._destroyCallbacks.push(e)}isDestroyed(){return!!this._destroyed}destroy(e){e=e||{},this._destroyed=!0,this._destroyCallbacks.forEach(a=>{try{a()}catch(r){console.error(r)}}),this._subscriptions.clear(),this._assigned.clear(),this._trackedExperiments.clear(),this._completedChangeIds.clear(),this._deferredTrackingCalls.clear(),this._trackedFeatures={},this._destroyCallbacks=[],this._payload=void 0,this._saveStickyBucketAssignmentDoc=void 0,NI(this),e.destroyAllStreams&&Hy(),this.logs=[],Bs&&window._growthbook===this&&delete window._growthbook,this._activeAutoExperiments.forEach(a=>{a.undo()}),this._activeAutoExperiments.clear(),this._triggeredExpKeys.clear()}setRenderer(e){this._renderer=e}forceVariation(e,a){if(this._options.forcedVariations=this._options.forcedVariations||{},this._options.forcedVariations[e]=a,this._options.remoteEval){this._refreshForRemoteEval();return}this._updateAllAutoExperiments(),this._render()}run(e){let{result:a}=Ip(e,null,this._getEvalContext());return this._onExperimentEval(e,a),a}triggerExperiment(e){return this._triggeredExpKeys.add(e),this._options.experiments?this._options.experiments.filter(r=>r.key===e).map(r=>this._runAutoExperiment(r)).filter(r=>r!==null):null}triggerAutoExperiments(){this._autoExperimentsAllowed=!0,this._updateAllAutoExperiments(!0)}_getEvalContext(){return{user:this._getUserContext(),global:this._getGlobalContext(),stack:{evaluatedFeatures:new Set}}}_getUserContext(){return{attributes:this._options.user?{...this._options.user,...this._options.attributes}:this._options.attributes,enableDevMode:this._options.enableDevMode,blockedChangeIds:this._options.blockedChangeIds,stickyBucketAssignmentDocs:this._options.stickyBucketAssignmentDocs,url:this._getContextUrl(),forcedVariations:this._options.forcedVariations,forcedFeatureValues:this._options.forcedFeatureValues,attributeOverrides:this._options.attributeOverrides,saveStickyBucketAssignmentDoc:this._saveStickyBucketAssignmentDoc,trackingCallback:this._options.trackingCallback,onFeatureUsage:this._options.onFeatureUsage,devLogs:this.logs,trackedExperiments:this._trackedExperiments,trackedFeatureUsage:this._trackedFeatures}}_getGlobalContext(){return{features:this._options.features,experiments:this._options.experiments,log:this.log,enabled:this._options.enabled,qaMode:this._options.qaMode,savedGroups:this._options.savedGroups,groups:this._options.groups,overrides:this._options.overrides,onExperimentEval:this._onExperimentEval,recordChangeId:this._recordChangedId,saveDeferredTrack:this._saveDeferredTrack,eventLogger:this._options.eventLogger}}_runAutoExperiment(e,a){let r=this._activeAutoExperiments.get(e);if(e.manual&&!this._triggeredExpKeys.has(e.key)&&!r)return null;let n=this._isAutoExperimentBlockedByContext(e),o,i;n?o=Ze(this._getEvalContext(),e,-1,!1,""):({result:o,trackingCall:i}=Ip(e,null,this._getEvalContext()),this._onExperimentEval(e,o));let s=JSON.stringify(o.value);if(!a&&o.inExperiment&&r&&r.valueHash===s)return o;if(r&&this._undoActiveAutoExperiment(e),o.inExperiment){let l=hp(e);if(l==="redirect"&&o.value.urlRedirect&&e.urlPatterns){let u=e.persistQueryString?MI(this._getContextUrl(),o.value.urlRedirect):o.value.urlRedirect;if(pp(u,e.urlPatterns))return this.log("Skipping redirect because original URL matches redirect URL",{id:e.key}),o;this._redirectedUrl=u;let{navigate:c,delay:d}=this._getNavigateFunction();if(c)if(Bs)Promise.all([...i?[mp(i,this._options.maxNavigateDelay??1e3)]:[],new Promise(f=>window.setTimeout(f,this._options.navigateDelay??d))]).then(()=>{try{c(u)}catch(f){console.error(f)}});else try{c(u)}catch(f){console.error(f)}}else if(l==="visual"){let u=this._options.applyDomChangesCallback?this._options.applyDomChangesCallback(o.value):this._applyDOMChanges(o.value);u&&this._activeAutoExperiments.set(e,{undo:u,valueHash:s})}}return o}_undoActiveAutoExperiment(e){let a=this._activeAutoExperiments.get(e);a&&(a.undo(),this._activeAutoExperiments.delete(e))}_updateAllAutoExperiments(e){if(!this._autoExperimentsAllowed)return;let a=this._options.experiments||[],r=new Set(a);this._activeAutoExperiments.forEach((n,o)=>{r.has(o)||(n.undo(),this._activeAutoExperiments.delete(o))});for(let n of a){let o=this._runAutoExperiment(n,e);if(o&&o.inExperiment&&hp(n)==="redirect")break}}_onExperimentEval(e,a){let r=this._assigned.get(e.key);this._assigned.set(e.key,{experiment:e,result:a}),this._subscriptions.size>0&&this._fireSubscriptions(e,a,r)}_fireSubscriptions(e,a,r){(!r||r.result.inExperiment!==a.inExperiment||r.result.variationId!==a.variationId)&&this._subscriptions.forEach(n=>{try{n(e,a)}catch(o){console.error(o)}})}_recordChangedId(e){this._completedChangeIds.add(e)}isOn(e){return this.evalFeature(e).on}isOff(e){return this.evalFeature(e).off}getFeatureValue(e,a){let r=this.evalFeature(e).value;return r===null?a:r}feature(e){return this.evalFeature(e)}evalFeature(e){return kp(e,this._getEvalContext())}log(e,a){this.debug&&(this._options.log?this._options.log(e,a):console.log(e,a))}getDeferredTrackingCalls(){return Array.from(this._deferredTrackingCalls.values())}setDeferredTrackingCalls(e){this._deferredTrackingCalls=new Map(e.filter(a=>a&&a.experiment&&a.result).map(a=>[Ap(a.experiment,a.result),a]))}async fireDeferredTrackingCalls(){if(!this._options.trackingCallback)return;let e=[];this._deferredTrackingCalls.forEach(a=>{!a||!a.experiment||!a.result?console.error("Invalid deferred tracking call",{call:a}):e.push(this._options.trackingCallback(a.experiment,a.result))}),this._deferredTrackingCalls.clear(),await Promise.all(e)}setTrackingCallback(e){this._options.trackingCallback=e,this.fireDeferredTrackingCalls()}setEventLogger(e){this._options.eventLogger=e}async logEvent(e,a){if(this._destroyed){console.error("Cannot log event to destroyed GrowthBook instance");return}if(this._options.enableDevMode&&this.logs.push({eventName:e,properties:a,timestamp:Date.now().toString(),logType:"event"}),this._options.eventLogger)try{await this._options.eventLogger(e,a||{},this._getUserContext())}catch(r){console.error(r)}else console.error("No event logger configured")}_saveDeferredTrack(e){this._deferredTrackingCalls.set(Ap(e.experiment,e.result),e)}_getContextUrl(){return this._options.url||(Bs?window.location.href:"")}_isAutoExperimentBlockedByContext(e){let a=hp(e);if(a==="visual"){if(this._options.disableVisualExperiments||this._options.disableJsInjection&&e.variations.some(r=>r.js))return!0}else if(a==="redirect"){if(this._options.disableUrlRedirectExperiments)return!0;try{let r=new URL(this._getContextUrl());for(let n of e.variations){if(!n||!n.urlRedirect)continue;let o=new URL(n.urlRedirect);if(this._options.disableCrossOriginUrlRedirectExperiments&&(o.protocol!==r.protocol||o.host!==r.host))return!0}}catch(r){return this.log("Error parsing current or redirect URL",{id:e.key,error:r}),!0}}else return!0;return!!(e.changeId&&(this._options.blockedChangeIds||[]).includes(e.changeId))}getRedirectUrl(){return this._redirectedUrl}_getNavigateFunction(){return this._options.navigate?{navigate:this._options.navigate,delay:0}:Bs?{navigate:e=>{window.location.replace(e)},delay:100}:{navigate:null,delay:0}}_applyDOMChanges(e){if(!Bs)return;let a=[];if(e.css){let r=document.createElement("style");r.innerHTML=e.css,document.head.appendChild(r),a.push(()=>r.remove())}if(e.js){let r=document.createElement("script");r.innerHTML=e.js,this._options.jsInjectionNonce&&(r.nonce=this._options.jsInjectionNonce),document.head.appendChild(r),a.push(()=>r.remove())}return e.domMutations&&e.domMutations.forEach(r=>{a.push(XI.declarative(r).revert)}),()=>{a.forEach(r=>r())}}async refreshStickyBuckets(e){if(this._options.stickyBucketService){let a=this._getEvalContext(),r=await nA(a,this._options.stickyBucketService,e);this._options.stickyBucketAssignmentDocs=r}}generateStickyBucketAssignmentDocsSync(e,a){if(!("getAllAssignmentsSync"in e)){console.error("generating StickyBucketAssignmentDocs docs requires StickyBucketServiceSync");return}let r=this._getEvalContext(),n=Wy(r,a);return e.getAllAssignmentsSync(n)}inDevMode(){return!!this._options.enableDevMode}};var SF="https://experiment.syntrologie.com",Zy=class{constructor(e={}){B(this,"gb");B(this,"featureListeners",new Set);if(e.client)this.gb=e.client;else{let a=e.onExperimentViewed?(r,n)=>{e.onExperimentViewed(r.key,n.variationId,typeof n.value=="string"?n.value:`variation_${n.variationId}`)}:void 0;this.gb=new Wu({...e,apiHost:e.apiHost??SF,enableDevMode:e.enableDevMode??!0,trackingCallback:a}),e.autoInit&&this.gb.init({streaming:!0})}}get _internal(){return this.gb}async refreshFeatures(){await this.gb.loadFeatures()}setAttributes(e){this.gb.setAttributes({...this.gb.getAttributes(),...e})}setForcedVariations(e){this.gb.setForcedVariations(e)}getFeatureValue(e,a){return this.gb.getFeatureValue(e,a)}getAllFeatures(){let e=this.gb.getFeatures(),a={};for(let r of Object.keys(e))a[r]=this.gb.getFeatureValue(r,null);return a}shouldRenderRectangle(e){return!0}onFeaturesChanged(e){return this.featureListeners.add(e),this.featureListeners.size===1&&this.gb.setRenderer(()=>{for(let a of this.featureListeners)a()}),()=>{this.featureListeners.delete(e),this.featureListeners.size===0&&this.gb.setRenderer(null)}}};function Xy(t={}){return new Zy(t)}var sA="syntro_session_metrics",Ep=class{constructor(e={}){B(this,"metrics",new Map);B(this,"experiments");B(this,"attributePrefix");B(this,"onMetricChange");this.experiments=e.experiments,this.attributePrefix=e.attributePrefix??"session_",this.onMetricChange=e.onMetricChange,this.loadFromStorage()}increment(e,a=1){let n=(this.metrics.get(e)??0)+a;return this.metrics.set(e,n),this.saveToStorage(),this.updateExperimentAttributes(e,n),this.onMetricChange?.(e,n),n}set(e,a){this.metrics.set(e,a),this.saveToStorage(),this.updateExperimentAttributes(e,a),this.onMetricChange?.(e,a)}get(e){return this.metrics.get(e)??0}meetsThreshold(e,a){return this.get(e)>=a}getAll(){return Object.fromEntries(this.metrics)}reset(e){this.metrics.delete(e),this.saveToStorage(),this.updateExperimentAttributes(e,0),this.onMetricChange?.(e,0)}resetAll(){let e=Array.from(this.metrics.keys());this.metrics.clear(),this.saveToStorage();let a={};for(let r of e)a[`${this.attributePrefix}${r}`]=0,this.onMetricChange?.(r,0);this.experiments?.setAttributes?.(a)}setExperiments(e){this.experiments=e,this.syncAllToExperiments()}updateExperimentAttributes(e,a){if(!this.experiments?.setAttributes)return;let r=`${this.attributePrefix}${e}`;this.experiments.setAttributes({[r]:a})}syncAllToExperiments(){if(!this.experiments?.setAttributes)return;let e={};for(let[a,r]of this.metrics)e[`${this.attributePrefix}${a}`]=r;this.experiments.setAttributes(e)}loadFromStorage(){if(!(typeof window>"u"||typeof sessionStorage>"u"))try{let e=sessionStorage.getItem(sA);if(e){let a=JSON.parse(e);for(let[r,n]of Object.entries(a))this.metrics.set(r,n.count)}}catch(e){console.warn("[SessionMetricTracker] Failed to load from sessionStorage:",e)}}saveToStorage(){if(!(typeof window>"u"||typeof sessionStorage>"u"))try{let e={};for(let[a,r]of this.metrics)e[a]={count:r,lastUpdated:Date.now()};sessionStorage.setItem(sA,JSON.stringify(e))}catch(e){console.warn("[SessionMetricTracker] Failed to save to sessionStorage:",e)}}};function Ky(t={}){return new Ep(t)}var p={};$R(p,{BRAND:()=>WF,DIRTY:()=>ii,EMPTY_PATH:()=>LF,INVALID:()=>J,NEVER:()=>R3,OK:()=>Ht,ParseStatus:()=>Ot,Schema:()=>le,ZodAny:()=>mo,ZodArray:()=>un,ZodBigInt:()=>li,ZodBoolean:()=>ui,ZodBranded:()=>Xu,ZodCatch:()=>bi,ZodDate:()=>ci,ZodDefault:()=>xi,ZodDiscriminatedUnion:()=>Mp,ZodEffects:()=>Va,ZodEnum:()=>vi,ZodError:()=>sa,ZodFirstPartyTypeKind:()=>ee,ZodFunction:()=>Dp,ZodIntersection:()=>hi,ZodIssueCode:()=>P,ZodLazy:()=>mi,ZodLiteral:()=>gi,ZodMap:()=>zs,ZodNaN:()=>Vs,ZodNativeEnum:()=>yi,ZodNever:()=>ur,ZodNull:()=>fi,ZodNullable:()=>Lr,ZodNumber:()=>si,ZodObject:()=>la,ZodOptional:()=>za,ZodParsedType:()=>G,ZodPipeline:()=>Ku,ZodPromise:()=>go,ZodReadonly:()=>Si,ZodRecord:()=>Op,ZodSchema:()=>le,ZodSet:()=>qs,ZodString:()=>ho,ZodSymbol:()=>Hs,ZodTransformer:()=>Va,ZodTuple:()=>wr,ZodType:()=>le,ZodUndefined:()=>di,ZodUnion:()=>pi,ZodUnknown:()=>ln,ZodVoid:()=>Us,addIssueToContext:()=>z,any:()=>a3,array:()=>i3,bigint:()=>YF,boolean:()=>yA,coerce:()=>T3,custom:()=>mA,date:()=>QF,datetimeRegex:()=>pA,defaultErrorMap:()=>on,discriminatedUnion:()=>c3,effect:()=>_3,enum:()=>x3,function:()=>g3,getErrorMap:()=>Ps,getParsedType:()=>Cr,instanceof:()=>XF,intersection:()=>d3,isAborted:()=>Tp,isAsync:()=>Ns,isDirty:()=>Rp,isValid:()=>po,late:()=>ZF,lazy:()=>v3,literal:()=>y3,makeIssue:()=>Zu,map:()=>h3,nan:()=>KF,nativeEnum:()=>b3,never:()=>n3,null:()=>t3,nullable:()=>w3,number:()=>vA,object:()=>s3,objectUtil:()=>Yy,oboolean:()=>E3,onumber:()=>A3,optional:()=>C3,ostring:()=>I3,pipeline:()=>k3,preprocess:()=>L3,promise:()=>S3,quotelessJson:()=>_F,record:()=>p3,set:()=>m3,setErrorMap:()=>wF,strictObject:()=>l3,string:()=>gA,symbol:()=>JF,transformer:()=>_3,tuple:()=>f3,undefined:()=>e3,union:()=>u3,unknown:()=>r3,util:()=>pe,void:()=>o3});var pe;(function(t){t.assertEqual=n=>{};function e(n){}t.assertIs=e;function a(n){throw new Error}t.assertNever=a,t.arrayToEnum=n=>{let o={};for(let i of n)o[i]=i;return o},t.getValidEnumValues=n=>{let o=t.objectKeys(n).filter(s=>typeof n[n[s]]!="number"),i={};for(let s of o)i[s]=n[s];return t.objectValues(i)},t.objectValues=n=>t.objectKeys(n).map(function(o){return n[o]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let o=[];for(let i in n)Object.prototype.hasOwnProperty.call(n,i)&&o.push(i);return o},t.find=(n,o)=>{for(let i of n)if(o(i))return i},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function r(n,o=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=r,t.jsonStringifyReplacer=(n,o)=>typeof o=="bigint"?o.toString():o})(pe||(pe={}));var Yy;(function(t){t.mergeShapes=(e,a)=>({...e,...a})})(Yy||(Yy={}));var G=pe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Cr=t=>{switch(typeof t){case"undefined":return G.undefined;case"string":return G.string;case"number":return Number.isNaN(t)?G.nan:G.number;case"boolean":return G.boolean;case"function":return G.function;case"bigint":return G.bigint;case"symbol":return G.symbol;case"object":return Array.isArray(t)?G.array:t===null?G.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?G.promise:typeof Map<"u"&&t instanceof Map?G.map:typeof Set<"u"&&t instanceof Set?G.set:typeof Date<"u"&&t instanceof Date?G.date:G.object;default:return G.unknown}};var P=pe.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),_F=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),sa=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let a=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,a):this.__proto__=a,this.name="ZodError",this.issues=e}format(e){let a=e||function(o){return o.message},r={_errors:[]},n=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)r._errors.push(a(i));else{let s=r,l=0;for(;l<i.path.length;){let u=i.path[l];l===i.path.length-1?(s[u]=s[u]||{_errors:[]},s[u]._errors.push(a(i))):s[u]=s[u]||{_errors:[]},s=s[u],l++}}};return n(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,pe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=a=>a.message){let a={},r=[];for(let n of this.issues)if(n.path.length>0){let o=n.path[0];a[o]=a[o]||[],a[o].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:a}}get formErrors(){return this.flatten()}};sa.create=t=>new sa(t);var CF=(t,e)=>{let a;switch(t.code){case P.invalid_type:t.received===G.undefined?a="Required":a=`Expected ${t.expected}, received ${t.received}`;break;case P.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(t.expected,pe.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:a=`Unrecognized key(s) in object: ${pe.joinValues(t.keys,", ")}`;break;case P.invalid_union:a="Invalid input";break;case P.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${pe.joinValues(t.options)}`;break;case P.invalid_enum_value:a=`Invalid enum value. Expected ${pe.joinValues(t.options)}, received '${t.received}'`;break;case P.invalid_arguments:a="Invalid function arguments";break;case P.invalid_return_type:a="Invalid function return type";break;case P.invalid_date:a="Invalid date";break;case P.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(a=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(a=`${a} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?a=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?a=`Invalid input: must end with "${t.validation.endsWith}"`:pe.assertNever(t.validation):t.validation!=="regex"?a=`Invalid ${t.validation}`:a="Invalid";break;case P.too_small:t.type==="array"?a=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?a=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?a=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?a=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?a=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:a="Invalid input";break;case P.too_big:t.type==="array"?a=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?a=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?a=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?a=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?a=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:a="Invalid input";break;case P.custom:a="Invalid input";break;case P.invalid_intersection_types:a="Intersection results could not be merged";break;case P.not_multiple_of:a=`Number must be a multiple of ${t.multipleOf}`;break;case P.not_finite:a="Number must be finite";break;default:a=e.defaultError,pe.assertNever(t)}return{message:a}},on=CF;var lA=on;function wF(t){lA=t}function Ps(){return lA}var Zu=t=>{let{data:e,path:a,errorMaps:r,issueData:n}=t,o=[...a,...n.path||[]],i={...n,path:o};if(n.message!==void 0)return{...n,path:o,message:n.message};let s="",l=r.filter(u=>!!u).slice().reverse();for(let u of l)s=u(i,{data:e,defaultError:s}).message;return{...n,path:o,message:s}},LF=[];function z(t,e){let a=Ps(),r=Zu({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,a,a===on?void 0:on].filter(n=>!!n)});t.common.issues.push(r)}var Ot=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,a){let r=[];for(let n of a){if(n.status==="aborted")return J;n.status==="dirty"&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,a){let r=[];for(let n of a){let o=await n.key,i=await n.value;r.push({key:o,value:i})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,a){let r={};for(let n of a){let{key:o,value:i}=n;if(o.status==="aborted"||i.status==="aborted")return J;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(r[o.value]=i.value)}return{status:e.value,value:r}}},J=Object.freeze({status:"aborted"}),ii=t=>({status:"dirty",value:t}),Ht=t=>({status:"valid",value:t}),Tp=t=>t.status==="aborted",Rp=t=>t.status==="dirty",po=t=>t.status==="valid",Ns=t=>typeof Promise<"u"&&t instanceof Promise;var X;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(X||(X={}));var qa=class{constructor(e,a,r,n){this._cachedPath=[],this.parent=e,this.data=a,this._path=r,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},uA=(t,e)=>{if(po(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let a=new sa(t.common.issues);return this._error=a,this._error}}};function se(t){if(!t)return{};let{errorMap:e,invalid_type_error:a,required_error:r,description:n}=t;if(e&&(a||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(i,s)=>{let{message:l}=t;return i.code==="invalid_enum_value"?{message:l??s.defaultError}:typeof s.data>"u"?{message:l??r??s.defaultError}:i.code!=="invalid_type"?{message:s.defaultError}:{message:l??a??s.defaultError}},description:n}}var le=class{get description(){return this._def.description}_getType(e){return Cr(e.data)}_getOrReturnCtx(e,a){return a||{common:e.parent.common,data:e.data,parsedType:Cr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ot,ctx:{common:e.parent.common,data:e.data,parsedType:Cr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let a=this._parse(e);if(Ns(a))throw new Error("Synchronous parse encountered promise.");return a}_parseAsync(e){let a=this._parse(e);return Promise.resolve(a)}parse(e,a){let r=this.safeParse(e,a);if(r.success)return r.data;throw r.error}safeParse(e,a){let r={common:{issues:[],async:a?.async??!1,contextualErrorMap:a?.errorMap},path:a?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Cr(e)},n=this._parseSync({data:e,path:r.path,parent:r});return uA(r,n)}"~validate"(e){let a={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Cr(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:a});return po(r)?{value:r.value}:{issues:a.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),a.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:a}).then(r=>po(r)?{value:r.value}:{issues:a.common.issues})}async parseAsync(e,a){let r=await this.safeParseAsync(e,a);if(r.success)return r.data;throw r.error}async safeParseAsync(e,a){let r={common:{issues:[],contextualErrorMap:a?.errorMap,async:!0},path:a?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Cr(e)},n=this._parse({data:e,path:r.path,parent:r}),o=await(Ns(n)?n:Promise.resolve(n));return uA(r,o)}refine(e,a){let r=n=>typeof a=="string"||typeof a>"u"?{message:a}:typeof a=="function"?a(n):a;return this._refinement((n,o)=>{let i=e(n),s=()=>o.addIssue({code:P.custom,...r(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(s(),!1)):i?!0:(s(),!1)})}refinement(e,a){return this._refinement((r,n)=>e(r)?!0:(n.addIssue(typeof a=="function"?a(r,n):a),!1))}_refinement(e){return new Va({schema:this,typeName:ee.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:a=>this["~validate"](a)}}optional(){return za.create(this,this._def)}nullable(){return Lr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return un.create(this)}promise(){return go.create(this,this._def)}or(e){return pi.create([this,e],this._def)}and(e){return hi.create(this,e,this._def)}transform(e){return new Va({...se(this._def),schema:this,typeName:ee.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let a=typeof e=="function"?e:()=>e;return new xi({...se(this._def),innerType:this,defaultValue:a,typeName:ee.ZodDefault})}brand(){return new Xu({typeName:ee.ZodBranded,type:this,...se(this._def)})}catch(e){let a=typeof e=="function"?e:()=>e;return new bi({...se(this._def),innerType:this,catchValue:a,typeName:ee.ZodCatch})}describe(e){let a=this.constructor;return new a({...this._def,description:e})}pipe(e){return Ku.create(this,e)}readonly(){return Si.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},kF=/^c[^\s-]{8,}$/i,IF=/^[0-9a-z]+$/,AF=/^[0-9A-HJKMNP-TV-Z]{26}$/i,EF=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,TF=/^[a-z0-9_-]{21}$/i,RF=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,MF=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,OF=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,DF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Qy,BF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,PF=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,NF=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,FF=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,HF=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,UF=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dA="((\\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])))",zF=new RegExp(`^${dA}$`);function fA(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let a=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${a}`}function qF(t){return new RegExp(`^${fA(t)}$`)}function pA(t){let e=`${dA}T${fA(t)}`,a=[];return a.push(t.local?"Z?":"Z"),t.offset&&a.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${a.join("|")})`,new RegExp(`^${e}$`)}function VF(t,e){return!!((e==="v4"||!e)&&BF.test(t)||(e==="v6"||!e)&&NF.test(t))}function $F(t,e){if(!RF.test(t))return!1;try{let[a]=t.split(".");if(!a)return!1;let r=a.replace(/-/g,"+").replace(/_/g,"/").padEnd(a.length+(4-a.length%4)%4,"="),n=JSON.parse(atob(r));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function jF(t,e){return!!((e==="v4"||!e)&&PF.test(t)||(e==="v6"||!e)&&FF.test(t))}var ho=class t extends le{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==G.string){let o=this._getOrReturnCtx(e);return z(o,{code:P.invalid_type,expected:G.string,received:o.parsedType}),J}let r=new Ot,n;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(n=this._getOrReturnCtx(e,n),z(n,{code:P.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")e.data.length>o.value&&(n=this._getOrReturnCtx(e,n),z(n,{code:P.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let i=e.data.length>o.value,s=e.data.length<o.value;(i||s)&&(n=this._getOrReturnCtx(e,n),i?z(n,{code:P.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):s&&z(n,{code:P.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")OF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"email",code:P.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Qy||(Qy=new RegExp(DF,"u")),Qy.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"emoji",code:P.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")EF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"uuid",code:P.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")TF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"nanoid",code:P.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")kF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"cuid",code:P.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")IF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"cuid2",code:P.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")AF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"ulid",code:P.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),z(n,{validation:"url",code:P.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"regex",code:P.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(n=this._getOrReturnCtx(e,n),z(n,{code:P.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(n=this._getOrReturnCtx(e,n),z(n,{code:P.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(n=this._getOrReturnCtx(e,n),z(n,{code:P.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?pA(o).test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:P.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?zF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:P.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?qF(o).test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:P.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?MF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"duration",code:P.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?VF(e.data,o.version)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"ip",code:P.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?$F(e.data,o.alg)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"jwt",code:P.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?jF(e.data,o.version)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"cidr",code:P.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?HF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"base64",code:P.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?UF.test(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{validation:"base64url",code:P.invalid_string,message:o.message}),r.dirty()):pe.assertNever(o);return{status:r.value,value:e.data}}_regex(e,a,r){return this.refinement(n=>e.test(n),{validation:a,code:P.invalid_string,...X.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...X.errToObj(e)})}url(e){return this._addCheck({kind:"url",...X.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...X.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...X.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...X.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...X.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...X.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...X.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...X.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...X.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...X.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...X.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...X.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...X.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...X.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...X.errToObj(e)})}regex(e,a){return this._addCheck({kind:"regex",regex:e,...X.errToObj(a)})}includes(e,a){return this._addCheck({kind:"includes",value:e,position:a?.position,...X.errToObj(a?.message)})}startsWith(e,a){return this._addCheck({kind:"startsWith",value:e,...X.errToObj(a)})}endsWith(e,a){return this._addCheck({kind:"endsWith",value:e,...X.errToObj(a)})}min(e,a){return this._addCheck({kind:"min",value:e,...X.errToObj(a)})}max(e,a){return this._addCheck({kind:"max",value:e,...X.errToObj(a)})}length(e,a){return this._addCheck({kind:"length",value:e,...X.errToObj(a)})}nonempty(e){return this.min(1,X.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e}get maxLength(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.value<e)&&(e=a.value);return e}};ho.create=t=>new ho({checks:[],typeName:ee.ZodString,coerce:t?.coerce??!1,...se(t)});function GF(t,e){let a=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,n=a>r?a:r,o=Number.parseInt(t.toFixed(n).replace(".","")),i=Number.parseInt(e.toFixed(n).replace(".",""));return o%i/10**n}var si=class t extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==G.number){let o=this._getOrReturnCtx(e);return z(o,{code:P.invalid_type,expected:G.number,received:o.parsedType}),J}let r,n=new Ot;for(let o of this._def.checks)o.kind==="int"?pe.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),z(r,{code:P.invalid_type,expected:"integer",received:"float",message:o.message}),n.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),z(r,{code:P.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),z(r,{code:P.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()):o.kind==="multipleOf"?GF(e.data,o.value)!==0&&(r=this._getOrReturnCtx(e,r),z(r,{code:P.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),z(r,{code:P.not_finite,message:o.message}),n.dirty()):pe.assertNever(o);return{status:n.value,value:e.data}}gte(e,a){return this.setLimit("min",e,!0,X.toString(a))}gt(e,a){return this.setLimit("min",e,!1,X.toString(a))}lte(e,a){return this.setLimit("max",e,!0,X.toString(a))}lt(e,a){return this.setLimit("max",e,!1,X.toString(a))}setLimit(e,a,r,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:a,inclusive:r,message:X.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:X.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:X.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:X.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:X.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:X.toString(e)})}multipleOf(e,a){return this._addCheck({kind:"multipleOf",value:e,message:X.toString(a)})}finite(e){return this._addCheck({kind:"finite",message:X.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:X.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:X.toString(e)})}get minValue(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e}get maxValue(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.value<e)&&(e=a.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&pe.isInteger(e.value))}get isFinite(){let e=null,a=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(a===null||r.value>a)&&(a=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(a)&&Number.isFinite(e)}};si.create=t=>new si({checks:[],typeName:ee.ZodNumber,coerce:t?.coerce||!1,...se(t)});var li=class t extends le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==G.bigint)return this._getInvalidInput(e);let r,n=new Ot;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),z(r,{code:P.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),n.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),z(r,{code:P.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),n.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),z(r,{code:P.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()):pe.assertNever(o);return{status:n.value,value:e.data}}_getInvalidInput(e){let a=this._getOrReturnCtx(e);return z(a,{code:P.invalid_type,expected:G.bigint,received:a.parsedType}),J}gte(e,a){return this.setLimit("min",e,!0,X.toString(a))}gt(e,a){return this.setLimit("min",e,!1,X.toString(a))}lte(e,a){return this.setLimit("max",e,!0,X.toString(a))}lt(e,a){return this.setLimit("max",e,!1,X.toString(a))}setLimit(e,a,r,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:a,inclusive:r,message:X.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:X.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:X.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:X.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:X.toString(e)})}multipleOf(e,a){return this._addCheck({kind:"multipleOf",value:e,message:X.toString(a)})}get minValue(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e}get maxValue(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.value<e)&&(e=a.value);return e}};li.create=t=>new li({checks:[],typeName:ee.ZodBigInt,coerce:t?.coerce??!1,...se(t)});var ui=class extends le{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==G.boolean){let r=this._getOrReturnCtx(e);return z(r,{code:P.invalid_type,expected:G.boolean,received:r.parsedType}),J}return Ht(e.data)}};ui.create=t=>new ui({typeName:ee.ZodBoolean,coerce:t?.coerce||!1,...se(t)});var ci=class t extends le{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==G.date){let o=this._getOrReturnCtx(e);return z(o,{code:P.invalid_type,expected:G.date,received:o.parsedType}),J}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return z(o,{code:P.invalid_date}),J}let r=new Ot,n;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(n=this._getOrReturnCtx(e,n),z(n,{code:P.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(n=this._getOrReturnCtx(e,n),z(n,{code:P.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):pe.assertNever(o);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,a){return this._addCheck({kind:"min",value:e.getTime(),message:X.toString(a)})}max(e,a){return this._addCheck({kind:"max",value:e.getTime(),message:X.toString(a)})}get minDate(){let e=null;for(let a of this._def.checks)a.kind==="min"&&(e===null||a.value>e)&&(e=a.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let a of this._def.checks)a.kind==="max"&&(e===null||a.value<e)&&(e=a.value);return e!=null?new Date(e):null}};ci.create=t=>new ci({checks:[],coerce:t?.coerce||!1,typeName:ee.ZodDate,...se(t)});var Hs=class extends le{_parse(e){if(this._getType(e)!==G.symbol){let r=this._getOrReturnCtx(e);return z(r,{code:P.invalid_type,expected:G.symbol,received:r.parsedType}),J}return Ht(e.data)}};Hs.create=t=>new Hs({typeName:ee.ZodSymbol,...se(t)});var di=class extends le{_parse(e){if(this._getType(e)!==G.undefined){let r=this._getOrReturnCtx(e);return z(r,{code:P.invalid_type,expected:G.undefined,received:r.parsedType}),J}return Ht(e.data)}};di.create=t=>new di({typeName:ee.ZodUndefined,...se(t)});var fi=class extends le{_parse(e){if(this._getType(e)!==G.null){let r=this._getOrReturnCtx(e);return z(r,{code:P.invalid_type,expected:G.null,received:r.parsedType}),J}return Ht(e.data)}};fi.create=t=>new fi({typeName:ee.ZodNull,...se(t)});var mo=class extends le{constructor(){super(...arguments),this._any=!0}_parse(e){return Ht(e.data)}};mo.create=t=>new mo({typeName:ee.ZodAny,...se(t)});var ln=class extends le{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ht(e.data)}};ln.create=t=>new ln({typeName:ee.ZodUnknown,...se(t)});var ur=class extends le{_parse(e){let a=this._getOrReturnCtx(e);return z(a,{code:P.invalid_type,expected:G.never,received:a.parsedType}),J}};ur.create=t=>new ur({typeName:ee.ZodNever,...se(t)});var Us=class extends le{_parse(e){if(this._getType(e)!==G.undefined){let r=this._getOrReturnCtx(e);return z(r,{code:P.invalid_type,expected:G.void,received:r.parsedType}),J}return Ht(e.data)}};Us.create=t=>new Us({typeName:ee.ZodVoid,...se(t)});var un=class t extends le{_parse(e){let{ctx:a,status:r}=this._processInputParams(e),n=this._def;if(a.parsedType!==G.array)return z(a,{code:P.invalid_type,expected:G.array,received:a.parsedType}),J;if(n.exactLength!==null){let i=a.data.length>n.exactLength.value,s=a.data.length<n.exactLength.value;(i||s)&&(z(a,{code:i?P.too_big:P.too_small,minimum:s?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(n.minLength!==null&&a.data.length<n.minLength.value&&(z(a,{code:P.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),n.maxLength!==null&&a.data.length>n.maxLength.value&&(z(a,{code:P.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),a.common.async)return Promise.all([...a.data].map((i,s)=>n.type._parseAsync(new qa(a,i,a.path,s)))).then(i=>Ot.mergeArray(r,i));let o=[...a.data].map((i,s)=>n.type._parseSync(new qa(a,i,a.path,s)));return Ot.mergeArray(r,o)}get element(){return this._def.type}min(e,a){return new t({...this._def,minLength:{value:e,message:X.toString(a)}})}max(e,a){return new t({...this._def,maxLength:{value:e,message:X.toString(a)}})}length(e,a){return new t({...this._def,exactLength:{value:e,message:X.toString(a)}})}nonempty(e){return this.min(1,e)}};un.create=(t,e)=>new un({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ee.ZodArray,...se(e)});function Fs(t){if(t instanceof la){let e={};for(let a in t.shape){let r=t.shape[a];e[a]=za.create(Fs(r))}return new la({...t._def,shape:()=>e})}else return t instanceof un?new un({...t._def,type:Fs(t.element)}):t instanceof za?za.create(Fs(t.unwrap())):t instanceof Lr?Lr.create(Fs(t.unwrap())):t instanceof wr?wr.create(t.items.map(e=>Fs(e))):t}var la=class t extends le{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),a=pe.objectKeys(e);return this._cached={shape:e,keys:a},this._cached}_parse(e){if(this._getType(e)!==G.object){let u=this._getOrReturnCtx(e);return z(u,{code:P.invalid_type,expected:G.object,received:u.parsedType}),J}let{status:r,ctx:n}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof ur&&this._def.unknownKeys==="strip"))for(let u in n.data)i.includes(u)||s.push(u);let l=[];for(let u of i){let c=o[u],d=n.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new qa(n,d,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof ur){let u=this._def.unknownKeys;if(u==="passthrough")for(let c of s)l.push({key:{status:"valid",value:c},value:{status:"valid",value:n.data[c]}});else if(u==="strict")s.length>0&&(z(n,{code:P.unrecognized_keys,keys:s}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let c of s){let d=n.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new qa(n,d,n.path,c)),alwaysSet:c in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let u=[];for(let c of l){let d=await c.key,f=await c.value;u.push({key:d,value:f,alwaysSet:c.alwaysSet})}return u}).then(u=>Ot.mergeObjectSync(r,u)):Ot.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return X.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(a,r)=>{let n=this._def.errorMap?.(a,r).message??r.defaultError;return a.code==="unrecognized_keys"?{message:X.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ee.ZodObject})}setKey(e,a){return this.augment({[e]:a})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let a={};for(let r of pe.objectKeys(e))e[r]&&this.shape[r]&&(a[r]=this.shape[r]);return new t({...this._def,shape:()=>a})}omit(e){let a={};for(let r of pe.objectKeys(this.shape))e[r]||(a[r]=this.shape[r]);return new t({...this._def,shape:()=>a})}deepPartial(){return Fs(this)}partial(e){let a={};for(let r of pe.objectKeys(this.shape)){let n=this.shape[r];e&&!e[r]?a[r]=n:a[r]=n.optional()}return new t({...this._def,shape:()=>a})}required(e){let a={};for(let r of pe.objectKeys(this.shape))if(e&&!e[r])a[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof za;)o=o._def.innerType;a[r]=o}return new t({...this._def,shape:()=>a})}keyof(){return hA(pe.objectKeys(this.shape))}};la.create=(t,e)=>new la({shape:()=>t,unknownKeys:"strip",catchall:ur.create(),typeName:ee.ZodObject,...se(e)});la.strictCreate=(t,e)=>new la({shape:()=>t,unknownKeys:"strict",catchall:ur.create(),typeName:ee.ZodObject,...se(e)});la.lazycreate=(t,e)=>new la({shape:t,unknownKeys:"strip",catchall:ur.create(),typeName:ee.ZodObject,...se(e)});var pi=class extends le{_parse(e){let{ctx:a}=this._processInputParams(e),r=this._def.options;function n(o){for(let s of o)if(s.result.status==="valid")return s.result;for(let s of o)if(s.result.status==="dirty")return a.common.issues.push(...s.ctx.common.issues),s.result;let i=o.map(s=>new sa(s.ctx.common.issues));return z(a,{code:P.invalid_union,unionErrors:i}),J}if(a.common.async)return Promise.all(r.map(async o=>{let i={...a,common:{...a.common,issues:[]},parent:null};return{result:await o._parseAsync({data:a.data,path:a.path,parent:i}),ctx:i}})).then(n);{let o,i=[];for(let l of r){let u={...a,common:{...a.common,issues:[]},parent:null},c=l._parseSync({data:a.data,path:a.path,parent:u});if(c.status==="valid")return c;c.status==="dirty"&&!o&&(o={result:c,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(o)return a.common.issues.push(...o.ctx.common.issues),o.result;let s=i.map(l=>new sa(l));return z(a,{code:P.invalid_union,unionErrors:s}),J}}get options(){return this._def.options}};pi.create=(t,e)=>new pi({options:t,typeName:ee.ZodUnion,...se(e)});var sn=t=>t instanceof mi?sn(t.schema):t instanceof Va?sn(t.innerType()):t instanceof gi?[t.value]:t instanceof vi?t.options:t instanceof yi?pe.objectValues(t.enum):t instanceof xi?sn(t._def.innerType):t instanceof di?[void 0]:t instanceof fi?[null]:t instanceof za?[void 0,...sn(t.unwrap())]:t instanceof Lr?[null,...sn(t.unwrap())]:t instanceof Xu||t instanceof Si?sn(t.unwrap()):t instanceof bi?sn(t._def.innerType):[],Mp=class t extends le{_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==G.object)return z(a,{code:P.invalid_type,expected:G.object,received:a.parsedType}),J;let r=this.discriminator,n=a.data[r],o=this.optionsMap.get(n);return o?a.common.async?o._parseAsync({data:a.data,path:a.path,parent:a}):o._parseSync({data:a.data,path:a.path,parent:a}):(z(a,{code:P.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),J)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,a,r){let n=new Map;for(let o of a){let i=sn(o.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of i){if(n.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,o)}}return new t({typeName:ee.ZodDiscriminatedUnion,discriminator:e,options:a,optionsMap:n,...se(r)})}};function Jy(t,e){let a=Cr(t),r=Cr(e);if(t===e)return{valid:!0,data:t};if(a===G.object&&r===G.object){let n=pe.objectKeys(e),o=pe.objectKeys(t).filter(s=>n.indexOf(s)!==-1),i={...t,...e};for(let s of o){let l=Jy(t[s],e[s]);if(!l.valid)return{valid:!1};i[s]=l.data}return{valid:!0,data:i}}else if(a===G.array&&r===G.array){if(t.length!==e.length)return{valid:!1};let n=[];for(let o=0;o<t.length;o++){let i=t[o],s=e[o],l=Jy(i,s);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return a===G.date&&r===G.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var hi=class extends le{_parse(e){let{status:a,ctx:r}=this._processInputParams(e),n=(o,i)=>{if(Tp(o)||Tp(i))return J;let s=Jy(o.value,i.value);return s.valid?((Rp(o)||Rp(i))&&a.dirty(),{status:a.value,value:s.data}):(z(r,{code:P.invalid_intersection_types}),J)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>n(o,i)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};hi.create=(t,e,a)=>new hi({left:t,right:e,typeName:ee.ZodIntersection,...se(a)});var wr=class t extends le{_parse(e){let{status:a,ctx:r}=this._processInputParams(e);if(r.parsedType!==G.array)return z(r,{code:P.invalid_type,expected:G.array,received:r.parsedType}),J;if(r.data.length<this._def.items.length)return z(r,{code:P.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&r.data.length>this._def.items.length&&(z(r,{code:P.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),a.dirty());let o=[...r.data].map((i,s)=>{let l=this._def.items[s]||this._def.rest;return l?l._parse(new qa(r,i,r.path,s)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>Ot.mergeArray(a,i)):Ot.mergeArray(a,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};wr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new wr({items:t,typeName:ee.ZodTuple,rest:null,...se(e)})};var Op=class t extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:a,ctx:r}=this._processInputParams(e);if(r.parsedType!==G.object)return z(r,{code:P.invalid_type,expected:G.object,received:r.parsedType}),J;let n=[],o=this._def.keyType,i=this._def.valueType;for(let s in r.data)n.push({key:o._parse(new qa(r,s,r.path,s)),value:i._parse(new qa(r,r.data[s],r.path,s)),alwaysSet:s in r.data});return r.common.async?Ot.mergeObjectAsync(a,n):Ot.mergeObjectSync(a,n)}get element(){return this._def.valueType}static create(e,a,r){return a instanceof le?new t({keyType:e,valueType:a,typeName:ee.ZodRecord,...se(r)}):new t({keyType:ho.create(),valueType:e,typeName:ee.ZodRecord,...se(a)})}},zs=class extends le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:a,ctx:r}=this._processInputParams(e);if(r.parsedType!==G.map)return z(r,{code:P.invalid_type,expected:G.map,received:r.parsedType}),J;let n=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([s,l],u)=>({key:n._parse(new qa(r,s,r.path,[u,"key"])),value:o._parse(new qa(r,l,r.path,[u,"value"]))}));if(r.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let l of i){let u=await l.key,c=await l.value;if(u.status==="aborted"||c.status==="aborted")return J;(u.status==="dirty"||c.status==="dirty")&&a.dirty(),s.set(u.value,c.value)}return{status:a.value,value:s}})}else{let s=new Map;for(let l of i){let u=l.key,c=l.value;if(u.status==="aborted"||c.status==="aborted")return J;(u.status==="dirty"||c.status==="dirty")&&a.dirty(),s.set(u.value,c.value)}return{status:a.value,value:s}}}};zs.create=(t,e,a)=>new zs({valueType:e,keyType:t,typeName:ee.ZodMap,...se(a)});var qs=class t extends le{_parse(e){let{status:a,ctx:r}=this._processInputParams(e);if(r.parsedType!==G.set)return z(r,{code:P.invalid_type,expected:G.set,received:r.parsedType}),J;let n=this._def;n.minSize!==null&&r.data.size<n.minSize.value&&(z(r,{code:P.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),a.dirty()),n.maxSize!==null&&r.data.size>n.maxSize.value&&(z(r,{code:P.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),a.dirty());let o=this._def.valueType;function i(l){let u=new Set;for(let c of l){if(c.status==="aborted")return J;c.status==="dirty"&&a.dirty(),u.add(c.value)}return{status:a.value,value:u}}let s=[...r.data.values()].map((l,u)=>o._parse(new qa(r,l,r.path,u)));return r.common.async?Promise.all(s).then(l=>i(l)):i(s)}min(e,a){return new t({...this._def,minSize:{value:e,message:X.toString(a)}})}max(e,a){return new t({...this._def,maxSize:{value:e,message:X.toString(a)}})}size(e,a){return this.min(e,a).max(e,a)}nonempty(e){return this.min(1,e)}};qs.create=(t,e)=>new qs({valueType:t,minSize:null,maxSize:null,typeName:ee.ZodSet,...se(e)});var Dp=class t extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==G.function)return z(a,{code:P.invalid_type,expected:G.function,received:a.parsedType}),J;function r(s,l){return Zu({data:s,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,Ps(),on].filter(u=>!!u),issueData:{code:P.invalid_arguments,argumentsError:l}})}function n(s,l){return Zu({data:s,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,Ps(),on].filter(u=>!!u),issueData:{code:P.invalid_return_type,returnTypeError:l}})}let o={errorMap:a.common.contextualErrorMap},i=a.data;if(this._def.returns instanceof go){let s=this;return Ht(async function(...l){let u=new sa([]),c=await s._def.args.parseAsync(l,o).catch(h=>{throw u.addIssue(r(l,h)),u}),d=await Reflect.apply(i,this,c);return await s._def.returns._def.type.parseAsync(d,o).catch(h=>{throw u.addIssue(n(d,h)),u})})}else{let s=this;return Ht(function(...l){let u=s._def.args.safeParse(l,o);if(!u.success)throw new sa([r(l,u.error)]);let c=Reflect.apply(i,this,u.data),d=s._def.returns.safeParse(c,o);if(!d.success)throw new sa([n(c,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:wr.create(e).rest(ln.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,a,r){return new t({args:e||wr.create([]).rest(ln.create()),returns:a||ln.create(),typeName:ee.ZodFunction,...se(r)})}},mi=class extends le{get schema(){return this._def.getter()}_parse(e){let{ctx:a}=this._processInputParams(e);return this._def.getter()._parse({data:a.data,path:a.path,parent:a})}};mi.create=(t,e)=>new mi({getter:t,typeName:ee.ZodLazy,...se(e)});var gi=class extends le{_parse(e){if(e.data!==this._def.value){let a=this._getOrReturnCtx(e);return z(a,{received:a.data,code:P.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}};gi.create=(t,e)=>new gi({value:t,typeName:ee.ZodLiteral,...se(e)});function hA(t,e){return new vi({values:t,typeName:ee.ZodEnum,...se(e)})}var vi=class t extends le{_parse(e){if(typeof e.data!="string"){let a=this._getOrReturnCtx(e),r=this._def.values;return z(a,{expected:pe.joinValues(r),received:a.parsedType,code:P.invalid_type}),J}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let a=this._getOrReturnCtx(e),r=this._def.values;return z(a,{received:a.data,code:P.invalid_enum_value,options:r}),J}return Ht(e.data)}get options(){return this._def.values}get enum(){let e={};for(let a of this._def.values)e[a]=a;return e}get Values(){let e={};for(let a of this._def.values)e[a]=a;return e}get Enum(){let e={};for(let a of this._def.values)e[a]=a;return e}extract(e,a=this._def){return t.create(e,{...this._def,...a})}exclude(e,a=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...a})}};vi.create=hA;var yi=class extends le{_parse(e){let a=pe.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==G.string&&r.parsedType!==G.number){let n=pe.objectValues(a);return z(r,{expected:pe.joinValues(n),received:r.parsedType,code:P.invalid_type}),J}if(this._cache||(this._cache=new Set(pe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=pe.objectValues(a);return z(r,{received:r.data,code:P.invalid_enum_value,options:n}),J}return Ht(e.data)}get enum(){return this._def.values}};yi.create=(t,e)=>new yi({values:t,typeName:ee.ZodNativeEnum,...se(e)});var go=class extends le{unwrap(){return this._def.type}_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==G.promise&&a.common.async===!1)return z(a,{code:P.invalid_type,expected:G.promise,received:a.parsedType}),J;let r=a.parsedType===G.promise?a.data:Promise.resolve(a.data);return Ht(r.then(n=>this._def.type.parseAsync(n,{path:a.path,errorMap:a.common.contextualErrorMap})))}};go.create=(t,e)=>new go({type:t,typeName:ee.ZodPromise,...se(e)});var Va=class extends le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ee.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:a,ctx:r}=this._processInputParams(e),n=this._def.effect||null,o={addIssue:i=>{z(r,i),i.fatal?a.abort():a.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),n.type==="preprocess"){let i=n.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async s=>{if(a.value==="aborted")return J;let l=await this._def.schema._parseAsync({data:s,path:r.path,parent:r});return l.status==="aborted"?J:l.status==="dirty"?ii(l.value):a.value==="dirty"?ii(l.value):l});{if(a.value==="aborted")return J;let s=this._def.schema._parseSync({data:i,path:r.path,parent:r});return s.status==="aborted"?J:s.status==="dirty"?ii(s.value):a.value==="dirty"?ii(s.value):s}}if(n.type==="refinement"){let i=s=>{let l=n.refinement(s,o);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?J:(s.status==="dirty"&&a.dirty(),i(s.value),{status:a.value,value:s.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>s.status==="aborted"?J:(s.status==="dirty"&&a.dirty(),i(s.value).then(()=>({status:a.value,value:s.value}))))}if(n.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!po(i))return J;let s=n.transform(i.value,o);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:a.value,value:s}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>po(i)?Promise.resolve(n.transform(i.value,o)).then(s=>({status:a.value,value:s})):J);pe.assertNever(n)}};Va.create=(t,e,a)=>new Va({schema:t,typeName:ee.ZodEffects,effect:e,...se(a)});Va.createWithPreprocess=(t,e,a)=>new Va({schema:e,effect:{type:"preprocess",transform:t},typeName:ee.ZodEffects,...se(a)});var za=class extends le{_parse(e){return this._getType(e)===G.undefined?Ht(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};za.create=(t,e)=>new za({innerType:t,typeName:ee.ZodOptional,...se(e)});var Lr=class extends le{_parse(e){return this._getType(e)===G.null?Ht(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Lr.create=(t,e)=>new Lr({innerType:t,typeName:ee.ZodNullable,...se(e)});var xi=class extends le{_parse(e){let{ctx:a}=this._processInputParams(e),r=a.data;return a.parsedType===G.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:a.path,parent:a})}removeDefault(){return this._def.innerType}};xi.create=(t,e)=>new xi({innerType:t,typeName:ee.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...se(e)});var bi=class extends le{_parse(e){let{ctx:a}=this._processInputParams(e),r={...a,common:{...a.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Ns(n)?n.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new sa(r.common.issues)},input:r.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new sa(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};bi.create=(t,e)=>new bi({innerType:t,typeName:ee.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...se(e)});var Vs=class extends le{_parse(e){if(this._getType(e)!==G.nan){let r=this._getOrReturnCtx(e);return z(r,{code:P.invalid_type,expected:G.nan,received:r.parsedType}),J}return{status:"valid",value:e.data}}};Vs.create=t=>new Vs({typeName:ee.ZodNaN,...se(t)});var WF=Symbol("zod_brand"),Xu=class extends le{_parse(e){let{ctx:a}=this._processInputParams(e),r=a.data;return this._def.type._parse({data:r,path:a.path,parent:a})}unwrap(){return this._def.type}},Ku=class t extends le{_parse(e){let{status:a,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?J:o.status==="dirty"?(a.dirty(),ii(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return n.status==="aborted"?J:n.status==="dirty"?(a.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,a){return new t({in:e,out:a,typeName:ee.ZodPipeline})}},Si=class extends le{_parse(e){let a=this._def.innerType._parse(e),r=n=>(po(n)&&(n.value=Object.freeze(n.value)),n);return Ns(a)?a.then(n=>r(n)):r(a)}unwrap(){return this._def.innerType}};Si.create=(t,e)=>new Si({innerType:t,typeName:ee.ZodReadonly,...se(e)});function cA(t,e){let a=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof a=="string"?{message:a}:a}function mA(t,e={},a){return t?mo.create().superRefine((r,n)=>{let o=t(r);if(o instanceof Promise)return o.then(i=>{if(!i){let s=cA(e,r),l=s.fatal??a??!0;n.addIssue({code:"custom",...s,fatal:l})}});if(!o){let i=cA(e,r),s=i.fatal??a??!0;n.addIssue({code:"custom",...i,fatal:s})}}):mo.create()}var ZF={object:la.lazycreate},ee;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(ee||(ee={}));var XF=(t,e={message:`Input not instance of ${t.name}`})=>mA(a=>a instanceof t,e),gA=ho.create,vA=si.create,KF=Vs.create,YF=li.create,yA=ui.create,QF=ci.create,JF=Hs.create,e3=di.create,t3=fi.create,a3=mo.create,r3=ln.create,n3=ur.create,o3=Us.create,i3=un.create,s3=la.create,l3=la.strictCreate,u3=pi.create,c3=Mp.create,d3=hi.create,f3=wr.create,p3=Op.create,h3=zs.create,m3=qs.create,g3=Dp.create,v3=mi.create,y3=gi.create,x3=vi.create,b3=yi.create,S3=go.create,_3=Va.create,C3=za.create,w3=Lr.create,L3=Va.createWithPreprocess,k3=Ku.create,I3=()=>gA().optional(),A3=()=>vA().optional(),E3=()=>yA().optional(),T3={string:(t=>ho.create({...t,coerce:!0})),number:(t=>si.create({...t,coerce:!0})),boolean:(t=>ui.create({...t,coerce:!0})),bigint:(t=>li.create({...t,coerce:!0})),date:(t=>ci.create({...t,coerce:!0}))};var R3=J;var xA=p.union([p.object({type:p.literal("data"),key:p.string(),value:p.string().optional()}),p.object({type:p.literal("css"),value:p.string()}),p.object({type:p.literal("aria"),role:p.string().optional(),label:p.string().optional()}),p.object({type:p.literal("shadow-css"),value:p.string()}),p.object({type:p.literal("ref"),el:p.any()})]),M3=p.object({kind:p.literal("tooltip"),id:p.string(),anchor:xA,content:p.object({title:p.string().optional(),body:p.string()}),placement:p.enum(["top","bottom","left","right","auto"]).optional(),offsetPx:p.number().optional(),blocking:p.boolean().optional(),trigger:p.enum(["immediate","hover","click"]).optional(),dismiss:p.object({onEsc:p.boolean().optional(),closeButton:p.boolean().optional(),timeoutMs:p.number().optional()}).optional()}),O3=p.object({kind:p.literal("highlight"),id:p.string(),anchor:xA,copy:p.string().optional(),ring:p.object({paddingPx:p.number().optional(),radiusPx:p.number().optional()}).optional(),scrim:p.object({opacity:p.number().optional()}).optional(),ringColor:p.string().optional(),blocking:p.boolean().optional(),dismiss:p.object({onClickOutside:p.boolean().optional(),onEsc:p.boolean().optional(),timeoutMs:p.number().optional()}).optional()}),ex=p.object({id:p.string(),version:p.number(),routes:p.array(p.string()).optional(),steps:p.array(p.union([M3,O3]))});function m8(t){return ex.parse(t)}var x8=({configUri:t,experiments:e,featureKey:a="smart-canvas-overlay-uri",credentials:r="include"}={})=>async()=>{let n=ny({configUri:t,experiments:e,featureKey:a});if(!n)throw new Error("SmartCanvas overlays: recipe URI missing (env + feature unset).");let o=await fetch(n,{credentials:r});if(!o.ok)throw new Error(`SmartCanvas overlays: failed to fetch recipe (${o.status})`);let i=await o.json();return ex.parse(i)};var Bp=Y(Ye(),1),bA=Y(ol(),1);function S8({element:t,children:e}){let[a,r]=(0,Bp.useState)(null);return(0,Bp.useLayoutEffect)(()=>{if(!t){r(null);return}return r(t.getMountNode()),()=>r(null)},[t]),a?(0,bA.createPortal)(e,a):null}function D3(){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e="";for(let a=0;a<16;a++)e+=t[Math.floor(Math.random()*t.length)];return e}var tx=class{constructor(){B(this,"sessionId");this.sessionId=D3(),console.log(`[Syntro Telemetry] Using noop adapter (no telemetry configured). sessionId=${this.sessionId}`)}trackCanvasOpened(e){}trackCanvasClosed(e){}trackRectangleViewed(e,a){}trackAction(e,a,r){}register(e){}getSessionId(){return this.sessionId}startSessionRecording(){}trackExperiment(e,a,r){}setPersonProperties(e){}setPersonPropertiesOnce(e){}getDistinctId(){return"demo-user"}getAllFeatureFlags(){return{}}getSegmentFlags(){return{}}track(e,a){}};function ax(){return new tx}var T=typeof window<"u"?window:void 0,Pt=typeof globalThis<"u"?globalThis:T;typeof self>"u"&&(Pt.self=Pt),typeof File>"u"&&(Pt.File=function(){});var gE=Array.prototype,SA=gE.forEach,_A=gE.indexOf,ka=Pt?.navigator,q=Pt?.document,Bt=Pt?.location,bx=Pt?.fetch,Sx=Pt!=null&&Pt.XMLHttpRequest&&"withCredentials"in new Pt.XMLHttpRequest?Pt.XMLHttpRequest:void 0,CA=Pt?.AbortController,ua=ka?.userAgent,Q=T??{},fn={DEBUG:!1,LIB_VERSION:"1.341.0"};function wA(t,e,a,r,n,o,i){try{var s=t[o](i),l=s.value}catch(u){return void a(u)}s.done?e(l):Promise.resolve(l).then(r,n)}function Zs(t){return function(){var e=this,a=arguments;return new Promise((function(r,n){var o=t.apply(e,a);function i(l){wA(o,r,n,i,s,"next",l)}function s(l){wA(o,r,n,i,s,"throw",l)}i(void 0)}))}}function j(){return j=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var a=arguments[e];for(var r in a)({}).hasOwnProperty.call(a,r)&&(t[r]=a[r])}return t},j.apply(null,arguments)}function vE(t,e){if(t==null)return{};var a={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;a[r]=t[r]}return a}var B3=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],LA=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var a=t.toLowerCase();return B3.concat(e).some((r=>{var n=r.toLowerCase();return a.indexOf(n)!==-1}))},P3=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"];function he(t,e){return t.indexOf(e)!==-1}var dh=function(t){return t.trim()},_x=function(t){return t.replace(/^\$/,"")},N3=Array.isArray,yE=Object.prototype,xE=yE.hasOwnProperty,fh=yE.toString,Ce=N3||function(t){return fh.call(t)==="[object Array]"},_o=t=>typeof t=="function",gt=t=>t===Object(t)&&!Ce(t),Xs=t=>{if(gt(t)){for(var e in t)if(xE.call(t,e))return!1;return!0}return!1},V=t=>t===void 0,vt=t=>fh.call(t)=="[object String]",Cx=t=>vt(t)&&t.trim().length===0,cr=t=>t===null,ge=t=>V(t)||cr(t),yn=t=>fh.call(t)=="[object Number]"&&t==t,Gs=t=>yn(t)&&t>0,vn=t=>fh.call(t)==="[object Boolean]",F3=t=>t instanceof FormData,H3=t=>he(P3,t);function wx(t){return t===null||typeof t!="object"}function Vp(t,e){return Object.prototype.toString.call(t)==="[object "+e+"]"}function bE(t){return!V(Event)&&(function(e,a){try{return e instanceof a}catch{return!1}})(t,Event)}var U3=[!0,"true",1,"1","yes"],rx=t=>he(U3,t),z3=[!1,"false",0,"0","no"];function Ir(t,e,a,r,n){return e>a&&(r.warn("min cannot be greater than max."),e=a),yn(t)?t>a?(r.warn(" cannot be greater than max: "+a+". Using max value instead."),a):t<e?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+a+", fallback: "+n),Ir(n||a,e,a,r))}var Lx=class{constructor(e){this.t={},this.i=e.i,this.o=Ir(e.bucketSize,0,100,e.h),this.m=Ir(e.refillRate,0,this.o,e.h),this.$=Ir(e.refillInterval,0,864e5,e.h)}S(e,a){var r=a-e.lastAccess,n=Math.floor(r/this.$);if(n>0){var o=n*this.m;e.tokens=Math.min(e.tokens+o,this.o),e.lastAccess=e.lastAccess+n*this.$}}consumeRateLimit(e){var a,r=Date.now(),n=String(e),o=this.t[n];return o?this.S(o,r):(o={tokens:this.o,lastAccess:r},this.t[n]=o),o.tokens===0||(o.tokens--,o.tokens===0&&((a=this.i)==null||a.call(this,e)),o.tokens===0)}stop(){this.t={}}},$a="Mobile",$p="iOS",gn="Android",vc="Tablet",SE=gn+" "+vc,_E="iPad",CE="Apple",wE=CE+" Watch",yc="Safari",Js="BlackBerry",LE="Samsung",kE=LE+"Browser",IE=LE+" Internet",Li="Chrome",q3=Li+" OS",AE=Li+" "+$p,Ob="Internet Explorer",EE=Ob+" "+$a,Db="Opera",V3=Db+" Mini",Bb="Edge",TE="Microsoft "+Bb,Ys="Firefox",RE=Ys+" "+$p,xc="Nintendo",bc="PlayStation",Qs="Xbox",ME=gn+" "+$a,OE=$a+" "+yc,ic="Windows",kx=ic+" Phone",kA="Nokia",Ix="Ouya",DE="Generic",$3=DE+" "+$a.toLowerCase(),BE=DE+" "+vc.toLowerCase(),Ax="Konqueror",Wt="(\\d+(\\.\\d+)?)",nx=new RegExp("Version/"+Wt),j3=new RegExp(Qs,"i"),G3=new RegExp(bc+" \\w+","i"),W3=new RegExp(xc+" \\w+","i"),Pb=new RegExp(Js+"|PlayBook|BB10","i"),Z3={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},Pp,IA,ox,X3=(t,e)=>e&&he(e,CE)||(function(a){return he(a,yc)&&!he(a,Li)&&!he(a,gn)})(t),PE=function(t,e){return e=e||"",he(t," OPR/")&&he(t,"Mini")?V3:he(t," OPR/")?Db:Pb.test(t)?Js:he(t,"IE"+$a)||he(t,"WPDesktop")?EE:he(t,kE)?IE:he(t,Bb)||he(t,"Edg/")?TE:he(t,"FBIOS")?"Facebook "+$a:he(t,"UCWEB")||he(t,"UCBrowser")?"UC Browser":he(t,"CriOS")?AE:he(t,"CrMo")||he(t,Li)?Li:he(t,gn)&&he(t,yc)?ME:he(t,"FxiOS")?RE:he(t.toLowerCase(),Ax.toLowerCase())?Ax:X3(t,e)?he(t,$a)?OE:yc:he(t,Ys)?Ys:he(t,"MSIE")||he(t,"Trident/")?Ob:he(t,"Gecko")?Ys:""},K3={[EE]:[new RegExp("rv:"+Wt)],[TE]:[new RegExp(Bb+"?\\/"+Wt)],[Li]:[new RegExp("("+Li+"|CrMo)\\/"+Wt)],[AE]:[new RegExp("CriOS\\/"+Wt)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Wt)],[yc]:[nx],[OE]:[nx],[Db]:[new RegExp("(Opera|OPR)\\/"+Wt)],[Ys]:[new RegExp(Ys+"\\/"+Wt)],[RE]:[new RegExp("FxiOS\\/"+Wt)],[Ax]:[new RegExp("Konqueror[:/]?"+Wt,"i")],[Js]:[new RegExp(Js+" "+Wt),nx],[ME]:[new RegExp("android\\s"+Wt,"i")],[IE]:[new RegExp(kE+"\\/"+Wt)],[Ob]:[new RegExp("(rv:|MSIE )"+Wt)],Mozilla:[new RegExp("rv:"+Wt)]},Y3=function(t,e){var a=PE(t,e),r=K3[a];if(V(r))return null;for(var n=0;n<r.length;n++){var o=r[n],i=t.match(o);if(i)return parseFloat(i[i.length-2])}return null},AA=[[new RegExp(Qs+"; "+Qs+" (.*?)[);]","i"),t=>[Qs,t&&t[1]||""]],[new RegExp(xc,"i"),[xc,""]],[new RegExp(bc,"i"),[bc,""]],[Pb,[Js,""]],[new RegExp(ic,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[kx,""];if(new RegExp($a).test(e)&&!/IEMobile\b/.test(e))return[ic+" "+$a,""];var a=/Windows NT ([0-9.]+)/i.exec(e);if(a&&a[1]){var r=a[1],n=Z3[r]||"";return/arm/i.test(e)&&(n="RT"),[ic,n]}return[ic,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){var e=[t[3],t[4],t[5]||"0"];return[$p,e.join(".")]}return[$p,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=V(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+gn+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+gn+")","i"),t=>{if(t&&t[2]){var e=[t[2],t[3],t[4]||"0"];return[gn,e.join(".")]}return[gn,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];if(t&&t[1]){var a=[t[1],t[2],t[3]||"0"];e[1]=a.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[q3,""]],[/Linux|debian/i,["Linux",""]]],EA=function(t){return W3.test(t)?xc:G3.test(t)?bc:j3.test(t)?Qs:new RegExp(Ix,"i").test(t)?Ix:new RegExp("("+kx+"|WPDesktop)","i").test(t)?kx:/iPad/.test(t)?_E:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?wE:Pb.test(t)?Js:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(kA,"i").test(t)?kA:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp($a).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?gn:SE:new RegExp("(pda|"+$a+")","i").test(t)?$3:new RegExp(vc,"i").test(t)&&!new RegExp(vc+" pc","i").test(t)?BE:""},Q3=t=>t instanceof Error;function J3(t){var e=globalThis._posthogChunkIds;if(e){var a=Object.keys(e);return ox&&a.length===IA||(IA=a.length,ox=a.reduce(((r,n)=>{Pp||(Pp={});var o=Pp[n];if(o)r[o[0]]=o[1];else for(var i=t(n),s=i.length-1;s>=0;s--){var l=i[s],u=l?.filename,c=e[n];if(u&&c){r[u]=c,Pp[n]=[u,c];break}}return r}),{})),ox}}var Ex=class{constructor(e,a,r){r===void 0&&(r=[]),this.coercers=e,this.stackParser=a,this.modifiers=r}buildFromUnknown(e,a){a===void 0&&(a={});var r=a&&a.mechanism||{handled:!0,type:"generic"},n=this.buildCoercingContext(r,a,0).apply(e),o=this.buildParsingContext(),i=this.parseStacktrace(n,o);return{$exception_list:this.convertToExceptionList(i,r),$exception_level:"error"}}modifyFrames(e){var a=this;return Zs((function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&Ce(r.stacktrace.frames)&&(r.stacktrace.frames=yield a.applyModifiers(r.stacktrace.frames));return e}))()}coerceFallback(e){var a;return{type:"Error",value:"Unknown error",stack:(a=e.syntheticException)==null?void 0:a.stack,synthetic:!0}}parseStacktrace(e,a){var r,n;return e.cause!=null&&(r=this.parseStacktrace(e.cause,a)),e.stack!=""&&e.stack!=null&&(n=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?1:0),a.chunkIdMap)),j({},e,{cause:r,stack:n})}applyChunkIds(e,a){return e.map((r=>(r.filename&&a&&(r.chunk_id=a[r.filename]),r)))}applyCoercers(e,a){for(var r of this.coercers)if(r.match(e))return r.coerce(e,a);return this.coerceFallback(a)}applyModifiers(e){var a=this;return Zs((function*(){var r=e;for(var n of a.modifiers)r=yield n(r);return r}))()}convertToExceptionList(e,a){var r,n,o,i={type:e.type,value:e.value,mechanism:{type:(r=a.type)!==null&&r!==void 0?r:"generic",handled:(n=a.handled)===null||n===void 0||n,synthetic:(o=e.synthetic)!==null&&o!==void 0&&o}};e.stack&&(i.stacktrace={type:"raw",frames:e.stack});var s=[i];return e.cause!=null&&s.push(...this.convertToExceptionList(e.cause,j({},a,{handled:!0}))),s}buildParsingContext(){return{chunkIdMap:J3(this.stackParser)}}buildCoercingContext(e,a,r){r===void 0&&(r=0);var n=(o,i)=>{if(i<=4){var s=this.buildCoercingContext(e,a,i);return this.applyCoercers(o,s)}};return j({},a,{syntheticException:r==0?a.syntheticException:void 0,mechanism:e,apply:o=>n(o,r),next:o=>n(o,r+1)})}},el="?";function Tx(t,e,a,r,n){var o={platform:t,filename:e,function:a==="<anonymous>"?el:a,in_app:!0};return V(r)||(o.lineno=r),V(n)||(o.colno=n),o}var NE=(t,e)=>{var a=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return a||r?[t.indexOf("@")!==-1?t.split("@")[0]:el,a?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},eH=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,tH=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,aH=/\((\S*)(?::(\d+))(?::(\d+))\)/,rH=(t,e)=>{var a=eH.exec(t);if(a){var[,r,n,o]=a;return Tx(e,r,el,+n,+o)}var i=tH.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var s=aH.exec(i[2]);s&&(i[2]=s[1],i[3]=s[2],i[4]=s[3])}var[l,u]=NE(i[1]||el,i[2]);return Tx(e,u,l,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},nH=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,oH=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,iH=(t,e)=>{var a=nH.exec(t);if(a){if(a[3]&&a[3].indexOf(" > eval")>-1){var r=oH.exec(a[3]);r&&(a[1]=a[1]||"eval",a[3]=r[1],a[4]=r[2],a[5]="")}var n=a[3],o=a[1]||el;return[o,n]=NE(o,n),Tx(e,n,o,a[4]?+a[4]:void 0,a[5]?+a[5]:void 0)}},TA=/\(error: (.*)\)/,RA=50;function sH(){return(function(t){for(var e=arguments.length,a=new Array(e>1?e-1:0),r=1;r<e;r++)a[r-1]=arguments[r];return function(n,o){o===void 0&&(o=0);for(var i=[],s=n.split(`
499
+ `),l=o;l<s.length;l++){var u=s[l];if(!(u.length>1024)){var c=TA.test(u)?u.replace(TA,"$1"):u;if(!c.match(/\S*Error: /)){for(var d of a){var f=d(c,t);if(f){i.push(f);break}}if(i.length>=RA)break}}}return(function(h){if(!h.length)return[];var S=Array.from(h);return S.reverse(),S.slice(0,RA).map((x=>{return j({},x,{filename:x.filename||(b=S,b[b.length-1]||{}).filename,function:x.function||el});var b}))})(i)}})("web:javascript",rH,iH)}var Rx=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,a){var r=vt(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?a.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var a=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?a+": "+e.message:a}isDOMException(e){return Vp(e,"DOMException")}isDOMError(e){return Vp(e,"DOMError")}},Mx=class{match(e){return(a=>a instanceof Error)(e)}coerce(e,a){return{type:this.getType(e),value:this.getMessage(e,a),stack:this.getStack(e),cause:e.cause?a.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,a){var r=e.message;return r.error&&typeof r.error.message=="string"?String(r.error.message):String(r)}getStack(e){return e.stacktrace||e.stack||void 0}},Ox=class{constructor(){}match(e){return Vp(e,"ErrorEvent")&&e.error!=null}coerce(e,a){var r,n=a.apply(e.error);return n||{type:"ErrorEvent",value:e.message,stack:(r=a.syntheticException)==null?void 0:r.stack,synthetic:!0}}},lH=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,Dx=class{match(e){return typeof e=="string"}coerce(e,a){var r,[n,o]=this.getInfos(e);return{type:n??"Error",value:o??e,stack:(r=a.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(e){var a="Error",r=e,n=e.match(lH);return n&&(a=n[1],r=n[2]),[a,r]}},uH=["fatal","error","warning","log","info","debug"];function FE(t,e){e===void 0&&(e=40);var a=Object.keys(t);if(a.sort(),!a.length)return"[object has no keys]";for(var r=a.length;r>0;r--){var n=a.slice(0,r).join(", ");if(!(n.length>e))return r===a.length||n.length<=e?n:n.slice(0,e)+"..."}return""}var Bx=class{match(e){return typeof e=="object"&&e!==null}coerce(e,a){var r,n=this.getErrorPropertyFromObject(e);return n?a.apply(n):{type:this.getType(e),value:this.getValue(e),stack:(r=a.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return bE(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var a="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(a+=" with message: '"+e.message+"'"),a}if("message"in e&&typeof e.message=="string")return e.message;var r=this.getObjectClassName(e);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+FE(e)}isSeverityLevel(e){return vt(e)&&!Cx(e)&&uH.indexOf(e)>=0}getErrorPropertyFromObject(e){for(var a in e)if(Object.prototype.hasOwnProperty.call(e,a)){var r=e[a];if(Q3(r))return r}}getObjectClassName(e){try{var a=Object.getPrototypeOf(e);return a?a.constructor.name:void 0}catch{return}}},Px=class{match(e){return bE(e)}coerce(e,a){var r,n=e.constructor.name;return{type:n,value:n+" captured as exception with keys: "+FE(e),stack:(r=a.syntheticException)==null?void 0:r.stack,synthetic:!0}}},Nx=class{match(e){return wx(e)}coerce(e,a){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(r=a.syntheticException)==null?void 0:r.stack,synthetic:!0}}},Fx=class{match(e){return Vp(e,"PromiseRejectionEvent")}coerce(e,a){var r,n=this.getUnhandledRejectionReason(e);return wx(n)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(n),stack:(r=a.syntheticException)==null?void 0:r.stack,synthetic:!0}:a.apply(n)}getUnhandledRejectionReason(e){if(wx(e))return e;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch{}return e}},HE=function(t,e){var{debugEnabled:a}=e===void 0?{}:e,r={k:function(n){if(T&&(fn.DEBUG||Q.POSTHOG_DEBUG||a)&&!V(T.console)&&T.console){for(var o=("__rrweb_original__"in T.console[n])?T.console[n].__rrweb_original__:T.console[n],i=arguments.length,s=new Array(i>1?i-1:0),l=1;l<i;l++)s[l-1]=arguments[l];o(t,...s)}},info:function(){for(var n=arguments.length,o=new Array(n),i=0;i<n;i++)o[i]=arguments[i];r.k("log",...o)},warn:function(){for(var n=arguments.length,o=new Array(n),i=0;i<n;i++)o[i]=arguments[i];r.k("warn",...o)},error:function(){for(var n=arguments.length,o=new Array(n),i=0;i<n;i++)o[i]=arguments[i];r.k("error",...o)},critical:function(){for(var n=arguments.length,o=new Array(n),i=0;i<n;i++)o[i]=arguments[i];console.error(t,...o)},uninitializedWarning:n=>{r.error("You must initialize PostHog before calling "+n)},createLogger:(n,o)=>HE(t+" "+n,o)};return r},$=HE("[PostHog.js]"),et=$.createLogger,cH=et("[ExternalScriptsLoader]"),MA=(t,e,a)=>{if(t.config.disable_external_dependency_loading)return cH.warn(e+" was requested but loading of external scripts is disabled."),a("Loading of external scripts is disabled");var r=q?.querySelectorAll("script");if(r){for(var n,o=function(){if(r[i].src===e){var l=r[i];return l.__posthog_loading_callback_fired?{v:a()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,a(void 0,u)})),l.onerror=u=>a(u),{v:void 0})}},i=0;i<r.length;i++)if(n=o())return n.v}var s=()=>{if(!q)return a("document not found");var l=q.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,a(void 0,d)},l.onerror=d=>a(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return a("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")q.head.appendChild(l);else{var u,c=q.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):q.body.appendChild(l)}};q!=null&&q.body?s():q?.addEventListener("DOMContentLoaded",s)};Q.__PosthogExtensions__=Q.__PosthogExtensions__||{},Q.__PosthogExtensions__.loadExternalDependency=(t,e,a)=>{var r="/static/"+e+".js?v="+t.version;if(e==="remote-config"&&(r="/array/"+t.config.token+"/config.js"),e==="toolbar"){var n=3e5;r=r+"&t="+Math.floor(Date.now()/n)*n}var o=t.requestRouter.endpointFor("assets",r);MA(t,o,a)},Q.__PosthogExtensions__.loadSiteApp=(t,e,a)=>{var r=t.requestRouter.endpointFor("api",e);MA(t,r,a)};var jp={};function Co(t,e,a){if(Ce(t)){if(SA&&t.forEach===SA)t.forEach(e,a);else if("length"in t&&t.length===+t.length){for(var r=0,n=t.length;r<n;r++)if(r in t&&e.call(a,t[r],r)===jp)return}}}function Be(t,e,a){if(!ge(t)){if(Ce(t))return Co(t,e,a);if(F3(t)){for(var r of t.entries())if(e.call(a,r[1],r[0])===jp)return}else for(var n in t)if(xE.call(t,n)&&e.call(a,t[n],n)===jp)return}}var ot=function(t){for(var e=arguments.length,a=new Array(e>1?e-1:0),r=1;r<e;r++)a[r-1]=arguments[r];return Co(a,(function(n){for(var o in n)n[o]!==void 0&&(t[o]=n[o])})),t},al=function(t){for(var e=arguments.length,a=new Array(e>1?e-1:0),r=1;r<e;r++)a[r-1]=arguments[r];return Co(a,(function(n){Co(n,(function(o){t.push(o)}))})),t};function zp(t){for(var e=Object.keys(t),a=e.length,r=new Array(a);a--;)r[a]=[e[a],t[e[a]]];return r}var OA=function(t){try{return t()}catch{return}},dH=function(t){return function(){try{for(var e=arguments.length,a=new Array(e),r=0;r<e;r++)a[r]=arguments[r];return t.apply(this,a)}catch(n){$.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),$.critical(n)}}},Nb=function(t){var e={};return Be(t,(function(a,r){(vt(a)&&a.length>0||yn(a))&&(e[r]=a)})),e};function fH(t,e){return a=t,r=o=>vt(o)&&!cr(e)?o.slice(0,e):o,n=new Set,(function o(i,s){return i!==Object(i)?r?r(i,s):i:n.has(i)?void 0:(n.add(i),Ce(i)?(l=[],Co(i,(u=>{l.push(o(u))}))):(l={},Be(i,((u,c)=>{n.has(u)||(l[c]=o(u,c))}))),l);var l})(a);var a,r,n}var pH=["herokuapp.com","vercel.app","netlify.app"];function hH(t){var e=t?.hostname;if(!vt(e))return!1;var a=e.split(".").slice(-2).join(".");for(var r of pH)if(a===r)return!1;return!0}function UE(t,e){for(var a=0;a<t.length;a++)if(e(t[a]))return t[a]}function ft(t,e,a,r){var{capture:n=!1,passive:o=!0}=r??{};t?.addEventListener(e,a,{capture:n,passive:o})}var zE="$people_distinct_id",sc="__alias",lc="__timers",DA="$autocapture_disabled_server_side",Hx="$heatmaps_enabled_server_side",BA="$exception_capture_enabled_server_side",Ux="$error_tracking_suppression_rules",PA="$error_tracking_capture_extension_exceptions",NA="$web_vitals_enabled_server_side",qE="$dead_clicks_enabled_server_side",FA="$product_tours_enabled_server_side",HA="$web_vitals_allowed_metrics",ix="$session_recording_remote_config",Gp="$sesid",VE="$session_is_sampled",Ks="$enabled_feature_flags",uc="$early_access_features",zx="$feature_flag_details",cc="$stored_person_properties",wi="$stored_group_properties",qx="$surveys",Wp="$flag_call_reported",pn="$user_state",Vx="$client_session_props",$x="$capture_rate_limit",jx="$initial_campaign_params",Gx="$initial_referrer_info",Zp="$initial_person_info",Xp="$epp",$E="__POSTHOG_TOOLBAR__",Yu="$posthog_cookieless",mH=[zE,sc,"__cmpns",lc,"$session_recording_enabled_server_side",Hx,Gp,Ks,Ux,pn,uc,zx,wi,cc,qx,Wp,Vx,$x,jx,Gx,Xp,Zp,"$conversations_widget_session_id","$conversations_ticket_id","$conversations_widget_state","$conversations_user_traits"];function UA(t){return t instanceof Element&&(t.id===$E||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function ph(t){return!!t&&t.nodeType===1}function wo(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function jE(t){return!!t&&t.nodeType===3}function GE(t){return!!t&&t.nodeType===11}function Fb(t){return t?dh(t).split(/\s+/):[]}function zA(t){var e=T?.location.href;return!!(e&&t&&t.some((a=>e.match(a))))}function Kp(t){var e="";switch(typeof t.className){case"string":e=t.className;break;case"object":e=(t.className&&"baseVal"in t.className?t.className.baseVal:null)||t.getAttribute("class")||"";break;default:e=""}return Fb(e)}function WE(t){return ge(t)?null:dh(t).split(/(\s+)/).filter((e=>Sc(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Cc(t){var e="";return Wx(t)&&!QE(t)&&t.childNodes&&t.childNodes.length&&Be(t.childNodes,(function(a){var r;jE(a)&&a.textContent&&(e+=(r=WE(a.textContent))!==null&&r!==void 0?r:"")})),dh(e)}function ZE(t){return V(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null;var e}var Hb=["a","button","form","input","select","textarea","label"];function XE(t,e){if(V(e))return!0;var a,r=function(o){if(e.some((i=>o.matches(i))))return{v:!0}};for(var n of t)if(a=r(n))return a.v;return!1}function KE(t){var e=t.parentNode;return!(!e||!ph(e))&&e}var gH=["next","previous","prev",">","<"],qA=10,VA=[".ph-no-rageclick",".ph-no-capture"];function vH(t,e){if(!T||Ub(t))return!1;var a,r,n;if(vn(e)?(a=!!e&&VA,r=void 0):(a=(n=e?.css_selector_ignorelist)!==null&&n!==void 0?n:VA,r=e?.content_ignorelist),a===!1)return!1;var{targetElementList:o}=YE(t,!1);return!(function(i,s){if(i===!1||V(i))return!1;var l;if(i===!0)l=gH;else{if(!Ce(i))return!1;if(i.length>qA)return $.error("[PostHog] content_ignorelist array cannot exceed "+qA+" items. Use css_selector_ignorelist for more complex matching."),!1;l=i.map((u=>u.toLowerCase()))}return s.some((u=>{var{safeText:c,ariaLabel:d}=u;return l.some((f=>c.includes(f)||d.includes(f)))}))})(r,o.map((i=>{var s;return{safeText:Cc(i).toLowerCase(),ariaLabel:((s=i.getAttribute("aria-label"))==null?void 0:s.toLowerCase().trim())||""}})))&&!XE(o,a)}var Ub=t=>!t||wo(t,"html")||!ph(t),YE=(t,e)=>{if(!T||Ub(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var a=!1,r=[t],n=t;n.parentNode&&!wo(n,"body");)if(GE(n.parentNode))r.push(n.parentNode.host),n=n.parentNode.host;else{var o=KE(n);if(!o)break;if(e||Hb.indexOf(o.tagName.toLowerCase())>-1)a=!0;else{var i=T.getComputedStyle(o);i&&i.getPropertyValue("cursor")==="pointer"&&(a=!0)}r.push(o),n=o}return{parentIsUsefulElement:a,targetElementList:r}};function yH(t,e,a,r,n){var o,i,s,l;if(a===void 0&&(a=void 0),!T||Ub(t)||(o=a)!=null&&o.url_allowlist&&!zA(a.url_allowlist)||(i=a)!=null&&i.url_ignorelist&&zA(a.url_ignorelist))return!1;if((s=a)!=null&&s.dom_event_allowlist){var u=a.dom_event_allowlist;if(u&&!u.some((S=>e.type===S)))return!1}var{parentIsUsefulElement:c,targetElementList:d}=YE(t,r);if(!(function(S,x){var b=x?.element_allowlist;if(V(b))return!0;var g,m=function(v){if(b.some((C=>v.tagName.toLowerCase()===C)))return{v:!0}};for(var y of S)if(g=m(y))return g.v;return!1})(d,a)||!XE(d,(l=a)==null?void 0:l.css_selector_allowlist))return!1;var f=T.getComputedStyle(t);if(f&&f.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;var h=t.tagName.toLowerCase();switch(h){case"html":return!1;case"form":return(n||["submit"]).indexOf(e.type)>=0;case"input":case"select":case"textarea":return(n||["change","click"]).indexOf(e.type)>=0;default:return c?(n||["click"]).indexOf(e.type)>=0:(n||["click"]).indexOf(e.type)>=0&&(Hb.indexOf(h)>-1||t.getAttribute("contenteditable")==="true")}}function Wx(t){for(var e=t;e.parentNode&&!wo(e,"body");e=e.parentNode){var a=Kp(e);if(he(a,"ph-sensitive")||he(a,"ph-no-capture"))return!1}if(he(Kp(t),"ph-include"))return!0;var r=t.type||"";if(vt(r))switch(r.toLowerCase()){case"hidden":case"password":return!1}var n=t.name||t.id||"";return!(vt(n)&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(n.replace(/[^a-zA-Z0-9]/g,"")))}function QE(t){return!!(wo(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||wo(t,"select")||wo(t,"textarea")||t.getAttribute("contenteditable")==="true")}var JE="(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})",xH=new RegExp("^(?:"+JE+")$"),bH=new RegExp(JE),eT="\\d{3}-?\\d{2}-?\\d{4}",SH=new RegExp("^("+eT+")$"),_H=new RegExp("("+eT+")");function Sc(t,e){return e===void 0&&(e=!0),!(ge(t)||vt(t)&&(t=dh(t),(e?xH:bH).test((t||"").replace(/[- ]/g,""))||(e?SH:_H).test(t)))}function tT(t){var e=Cc(t);return Sc(e=(e+" "+aT(t)).trim())?e:""}function aT(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Be(t.childNodes,(function(a){var r;if(a&&((r=a.tagName)==null?void 0:r.toLowerCase())==="span")try{var n=Cc(a);e=(e+" "+n).trim(),a.childNodes&&a.childNodes.length&&(e=(e+" "+aT(a)).trim())}catch(o){$.error("[AutoCapture]",o)}})),e}function CH(t){return(function(e){var a=e.map((r=>{var n,o,i="";if(r.tag_name&&(i+=r.tag_name),r.attr_class)for(var s of(r.attr_class.sort(),r.attr_class))i+="."+s.replace(/"/g,"");var l=j({},r.text?{text:r.text}:{},{"nth-child":(n=r.nth_child)!==null&&n!==void 0?n:0,"nth-of-type":(o=r.nth_of_type)!==null&&o!==void 0?o:0},r.href?{href:r.href}:{},r.attr_id?{attr_id:r.attr_id}:{},r.attributes),u={};return zp(l).sort(((c,d)=>{var[f]=c,[h]=d;return f.localeCompare(h)})).forEach((c=>{var[d,f]=c;return u[$A(d.toString())]=$A(f.toString())})),i+=":",i+=zp(u).map((c=>{var[d,f]=c;return d+'="'+f+'"'})).join("")}));return a.join(";")})((function(e){return e.map((a=>{var r,n,o={text:(r=a.$el_text)==null?void 0:r.slice(0,400),tag_name:a.tag_name,href:(n=a.attr__href)==null?void 0:n.slice(0,2048),attr_class:wH(a),attr_id:a.attr__id,nth_child:a.nth_child,nth_of_type:a.nth_of_type,attributes:{}};return zp(a).filter((i=>{var[s]=i;return s.indexOf("attr__")===0})).forEach((i=>{var[s,l]=i;return o.attributes[s]=l})),o}))})(t))}function $A(t){return t.replace(/"|\\"/g,'\\"')}function wH(t){var e=t.attr__class;return e?Ce(e)?e:Fb(e):void 0}var Yp=class{constructor(e){this.disabled=e===!1;var a=gt(e)?e:{};this.thresholdPx=a.threshold_px||30,this.timeoutMs=a.timeout_ms||1e3,this.clickCount=a.click_count||3,this.clicks=[]}isRageClick(e,a,r){if(this.disabled)return!1;var n=this.clicks[this.clicks.length-1];if(n&&Math.abs(e-n.x)+Math.abs(a-n.y)<this.thresholdPx&&r-n.timestamp<this.timeoutMs){if(this.clicks.push({x:e,y:a,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:a,timestamp:r}];return!1}},Qp=t=>{var e=q?.createElement("a");return V(e)?null:(e.href=t,e)},LH=function(t,e){var a,r;e===void 0&&(e="&");var n=[];return Be(t,(function(o,i){V(o)||V(i)||i==="undefined"||(a=encodeURIComponent((s=>s instanceof File)(o)?o.name:o.toString()),r=encodeURIComponent(i),n[n.length]=r+"="+a)})),n.join(e)},Jp=function(t,e){for(var a,r=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),n=0;n<r.length;n++){var o=r[n].split("=");if(o[0]===e){a=o;break}}if(!Ce(a)||a.length<2)return"";var i=a[1];try{i=decodeURIComponent(i)}catch{$.error("Skipping decoding for malformed query param: "+i)}return i.replace(/\+/g," ")},wc=function(t,e,a){if(!t||!e||!e.length)return t;for(var r=t.split("#"),n=r[0]||"",o=r[1],i=n.split("?"),s=i[1],l=i[0],u=(s||"").split("&"),c=[],d=0;d<u.length;d++){var f=u[d].split("=");Ce(f)&&(e.includes(f[0])?c.push(f[0]+"="+a):c.push(u[d]))}var h=l;return s!=null&&(h+="?"+c.join("&")),o!=null&&(h+="#"+o),h},eh=function(t,e){var a=t.match(new RegExp(e+"=([^&]*)"));return a?a[1]:null},sx="$copy_autocapture",jA=et("[AutoCapture]");function lx(t,e){return e.length>t?e.slice(0,t)+"...":e}function kH(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!ph(e));return e}function IH(t,e,a,r){var n=t.tagName.toLowerCase(),o={tag_name:n};Hb.indexOf(n)>-1&&!a&&(n.toLowerCase()==="a"||n.toLowerCase()==="button"?o.$el_text=lx(1024,tT(t)):o.$el_text=lx(1024,Cc(t)));var i=Kp(t);i.length>0&&(o.classes=i.filter((function(c){return c!==""}))),Be(t.attributes,(function(c){var d;if((!QE(t)||["name","id","class","aria-label"].indexOf(c.name)!==-1)&&(r==null||!r.includes(c.name))&&!e&&Sc(c.value)&&(d=c.name,!vt(d)||d.substring(0,10)!=="_ngcontent"&&d.substring(0,7)!=="_nghost")){var f=c.value;c.name==="class"&&(f=Fb(f).join(" ")),o["attr__"+c.name]=lx(1024,f)}}));for(var s=1,l=1,u=t;u=kH(u);)s++,u.tagName===t.tagName&&l++;return o.nth_child=s,o.nth_of_type=l,o}function AH(t,e){for(var a,r,{e:n,maskAllElementAttributes:o,maskAllText:i,elementAttributeIgnoreList:s,elementsChainAsString:l}=e,u=[t],c=t;c.parentNode&&!wo(c,"body");)GE(c.parentNode)?(u.push(c.parentNode.host),c=c.parentNode.host):(u.push(c.parentNode),c=c.parentNode);var d,f=[],h={},S=!1,x=!1;if(Be(u,(v=>{var C=Wx(v);v.tagName.toLowerCase()==="a"&&(S=v.getAttribute("href"),S=C&&S&&Sc(S)&&S),he(Kp(v),"ph-no-capture")&&(x=!0),f.push(IH(v,o,i,s));var w=(function(_){if(!Wx(_))return{};var L={};return Be(_.attributes,(function(A){if(A.name&&A.name.indexOf("data-ph-capture-attribute")===0){var I=A.name.replace("data-ph-capture-attribute-",""),R=A.value;I&&R&&Sc(R)&&(L[I]=R)}})),L})(v);ot(h,w)})),x)return{props:{},explicitNoCapture:x};if(i||(t.tagName.toLowerCase()==="a"||t.tagName.toLowerCase()==="button"?f[0].$el_text=tT(t):f[0].$el_text=Cc(t)),S){var b,g;f[0].attr__href=S;var m=(b=Qp(S))==null?void 0:b.host,y=T==null||(g=T.location)==null?void 0:g.host;m&&y&&m!==y&&(d=S)}return{props:ot({$event_type:n.type,$ce_version:1},l?{}:{$elements:f},{$elements_chain:CH(f)},(a=f[0])!=null&&a.$el_text?{$el_text:(r=f[0])==null?void 0:r.$el_text}:{},d&&n.type==="click"?{$external_click_url:d}:{},h)}}var Zx=class{constructor(e){this.P=!1,this.T=null,this.I=!1,this.instance=e,this.rageclicks=new Yp(e.config.rageclick),this.C=null}get R(){var e,a,r=gt(this.instance.config.autocapture)?this.instance.config.autocapture:{};return r.url_allowlist=(e=r.url_allowlist)==null?void 0:e.map((n=>new RegExp(n))),r.url_ignorelist=(a=r.url_ignorelist)==null?void 0:a.map((n=>new RegExp(n))),r}F(){if(this.isBrowserSupported()){if(T&&q){var e=r=>{r=r||T?.event;try{this.O(r)}catch(n){jA.error("Failed to capture event",n)}};if(ft(q,"submit",e,{capture:!0}),ft(q,"change",e,{capture:!0}),ft(q,"click",e,{capture:!0}),this.R.capture_copied_text){var a=r=>{r=r||T?.event,this.O(r,sx)};ft(q,"copy",a,{capture:!0}),ft(q,"cut",a,{capture:!0})}}}else jA.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.P&&(this.F(),this.P=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this.I=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[DA]:!!e.autocapture_opt_out}),this.T=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this.C=e}getElementSelectors(e){var a,r=[];return(a=this.C)==null||a.forEach((n=>{var o=q?.querySelectorAll(n);o?.forEach((i=>{e===i&&r.push(n)}))})),r}get isEnabled(){var e,a,r=(e=this.instance.persistence)==null?void 0:e.props[DA],n=this.T;if(cr(n)&&!vn(r)&&!this.instance.M())return!1;var o=(a=this.T)!==null&&a!==void 0?a:!!r;return!!this.instance.config.autocapture&&!o}O(e,a){if(a===void 0&&(a="$autocapture"),this.isEnabled){var r,n=ZE(e);jE(n)&&(n=n.parentNode||null),a==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&this.instance.config.rageclick&&(r=this.rageclicks)!=null&&r.isRageClick(e.clientX,e.clientY,e.timeStamp||new Date().getTime())&&vH(n,this.instance.config.rageclick)&&this.O(e,"$rageclick");var o=a===sx;if(n&&yH(n,e,this.R,o,o?["copy","cut"]:void 0)){var{props:i,explicitNoCapture:s}=AH(n,{e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.R.element_attribute_ignorelist,elementsChainAsString:this.I});if(s)return!1;var l=this.getElementSelectors(n);if(l&&l.length>0&&(i.$element_selectors=l),a===sx){var u,c=WE(T==null||(u=T.getSelection())==null?void 0:u.toString()),d=e.type||"clipboard";if(!c)return!1;i.$selected_content=c,i.$copy_type=d}return this.instance.capture(a,i),!0}}}isBrowserSupported(){return _o(q?.querySelectorAll)}};Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return yn(t)&&isFinite(t)&&Math.floor(t)===t});var GA="0123456789abcdef",Xx=class t{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,a,r,n){if(!Number.isInteger(e)||!Number.isInteger(a)||!Number.isInteger(r)||!Number.isInteger(n)||e<0||a<0||r<0||n<0||e>0xffffffffffff||a>4095||r>1073741823||n>4294967295)throw new RangeError("invalid field value");var o=new Uint8Array(16);return o[0]=e/Math.pow(2,40),o[1]=e/Math.pow(2,32),o[2]=e/Math.pow(2,24),o[3]=e/Math.pow(2,16),o[4]=e/Math.pow(2,8),o[5]=e,o[6]=112|a>>>8,o[7]=a,o[8]=128|r>>>24,o[9]=r>>>16,o[10]=r>>>8,o[11]=r,o[12]=n>>>24,o[13]=n>>>16,o[14]=n>>>8,o[15]=n,new t(o)}toString(){for(var e="",a=0;a<this.bytes.length;a++)e=e+GA.charAt(this.bytes[a]>>>4)+GA.charAt(15&this.bytes[a]),a!==3&&a!==5&&a!==7&&a!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new t(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var a=0;a<16;a++){var r=this.bytes[a]-e.bytes[a];if(r!==0)return Math.sign(r)}return 0}},Kx=class{constructor(){this.A=0,this.j=0,this.D=new Yx}generate(){var e=this.generateOrAbort();if(V(e)){this.A=0;var a=this.generateOrAbort();if(V(a))throw new Error("Could not generate UUID after timestamp reset");return a}return e}generateOrAbort(){var e=Date.now();if(e>this.A)this.A=e,this.L();else{if(!(e+1e4>this.A))return;this.j++,this.j>4398046511103&&(this.A++,this.L())}return Xx.fromFieldsV7(this.A,Math.trunc(this.j/Math.pow(2,30)),this.j&Math.pow(2,30)-1,this.D.nextUint32())}L(){this.j=1024*this.D.nextUint32()+(1023&this.D.nextUint32())}},WA,rT=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;e<t.length;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};T&&!V(T.crypto)&&crypto.getRandomValues&&(rT=t=>crypto.getRandomValues(t));var Yx=class{constructor(){this.N=new Uint32Array(8),this.U=1/0}nextUint32(){return this.U>=this.N.length&&(rT(this.N),this.U=0),this.N[this.U++]}},So=()=>EH().toString(),EH=()=>(WA||(WA=new Kx)).generate(),Qu="",TH=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function RH(t,e){if(e){var a=(function(n,o){if(o===void 0&&(o=q),Qu)return Qu;if(!o||["localhost","127.0.0.1"].includes(n))return"";for(var i=n.split("."),s=Math.min(i.length,8),l="dmn_chk_"+So();!Qu&&s--;){var u=i.slice(s).join("."),c=l+"=1;domain=."+u+";path=/";o.cookie=c+";max-age=3",o.cookie.includes(l)&&(o.cookie=c+";max-age=0",Qu=u)}return Qu})(t);if(!a){var r=(n=>{var o=n.match(TH);return o?o[0]:""})(t);r!==a&&$.info("Warning: cookie subdomain discovery mismatch",r,a),a=r}return a?"; domain=."+a:""}return""}var kr={H:()=>!!q,B:function(t){$.error("cookieStore error: "+t)},q:function(t){if(q){try{for(var e=t+"=",a=q.cookie.split(";").filter((o=>o.length)),r=0;r<a.length;r++){for(var n=a[r];n.charAt(0)==" ";)n=n.substring(1,n.length);if(n.indexOf(e)===0)return decodeURIComponent(n.substring(e.length,n.length))}}catch{}return null}},W:function(t){var e;try{e=JSON.parse(kr.q(t))||{}}catch{}return e},G:function(t,e,a,r,n){if(q)try{var o="",i="",s=RH(q.location.hostname,r);if(a){var l=new Date;l.setTime(l.getTime()+24*a*60*60*1e3),o="; expires="+l.toUTCString()}n&&(i="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+o+"; SameSite=Lax; path=/"+s+i;return u.length>3686.4&&$.warn("cookieStore warning: large cookie, len="+u.length),q.cookie=u,u}catch{return}},V:function(t,e){if(q!=null&&q.cookie)try{kr.G(t,"",-1,e)}catch{return}}},ux=null,Ke={H:function(){if(!cr(ux))return ux;var t=!0;if(V(T))t=!1;else try{var e="__mplssupport__";Ke.G(e,"xyz"),Ke.q(e)!=='"xyz"'&&(t=!1),Ke.V(e)}catch{t=!1}return t||$.error("localStorage unsupported; falling back to cookie store"),ux=t,t},B:function(t){$.error("localStorage error: "+t)},q:function(t){try{return T?.localStorage.getItem(t)}catch(e){Ke.B(e)}return null},W:function(t){try{return JSON.parse(Ke.q(t))||{}}catch{}return null},G:function(t,e){try{T?.localStorage.setItem(t,JSON.stringify(e))}catch(a){Ke.B(a)}},V:function(t){try{T?.localStorage.removeItem(t)}catch(e){Ke.B(e)}}},MH=["$device_id","distinct_id",Gp,VE,Xp,Zp],Np={},OH={H:function(){return!0},B:function(t){$.error("memoryStorage error: "+t)},q:function(t){return Np[t]||null},W:function(t){return Np[t]||null},G:function(t,e){Np[t]=e},V:function(t){delete Np[t]}},_i=null,Dt={H:function(){if(!cr(_i))return _i;if(_i=!0,V(T))_i=!1;else try{var t="__support__";Dt.G(t,"xyz"),Dt.q(t)!=='"xyz"'&&(_i=!1),Dt.V(t)}catch{_i=!1}return _i},B:function(t){$.error("sessionStorage error: ",t)},q:function(t){try{return T?.sessionStorage.getItem(t)}catch(e){Dt.B(e)}return null},W:function(t){try{return JSON.parse(Dt.q(t))||null}catch{}return null},G:function(t,e){try{T?.sessionStorage.setItem(t,JSON.stringify(e))}catch(a){Dt.B(a)}},V:function(t){try{T?.sessionStorage.removeItem(t)}catch(e){Dt.B(e)}}},hn=(function(t){return t[t.PENDING=-1]="PENDING",t[t.DENIED=0]="DENIED",t[t.GRANTED=1]="GRANTED",t})({}),Qx=class{constructor(e){this._instance=e}get R(){return this._instance.config}get consent(){return this.J()?hn.DENIED:this.K}isOptedOut(){return this.R.cookieless_mode==="always"||this.consent===hn.DENIED||this.consent===hn.PENDING&&(this.R.opt_out_capturing_by_default||this.R.cookieless_mode==="on_reject")}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===hn.DENIED}optInOut(e){this.Y.G(this.X,e?1:0,this.R.cookie_expiration,this.R.cross_subdomain_cookie,this.R.secure_cookie)}reset(){this.Y.V(this.X,this.R.cross_subdomain_cookie)}get X(){var{token:e,opt_out_capturing_cookie_prefix:a,consent_persistence_name:r}=this._instance.config;return r||(a?a+e:"__ph_opt_in_out_"+e)}get K(){var e=this.Y.q(this.X);return rx(e)?hn.GRANTED:he(z3,e)?hn.DENIED:hn.PENDING}get Y(){if(!this.Z){var e=this.R.opt_out_capturing_persistence_type;this.Z=e==="localStorage"?Ke:kr;var a=e==="localStorage"?kr:Ke;a.q(this.X)&&(this.Z.q(this.X)||this.optInOut(rx(a.q(this.X))),a.V(this.X,this.R.cross_subdomain_cookie))}return this.Z}J(){return!!this.R.respect_dnt&&!!UE([ka?.doNotTrack,ka?.msDoNotTrack,Q.doNotTrack],(e=>rx(e)))}},Fp=et("[Dead Clicks]"),DH=()=>!0,BH=t=>{var e,a=!((e=t.instance.persistence)==null||!e.get_property(qE)),r=t.instance.config.capture_dead_clicks;return vn(r)?r:!!gt(r)||a},th=class{get lazyLoadedDeadClicksAutocapture(){return this.tt}constructor(e,a,r){this.instance=e,this.isEnabled=a,this.onCapture=r,this.startIfEnabled()}onRemoteConfig(e){this.instance.persistence&&this.instance.persistence.register({[qE]:e?.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.it((()=>{this.et()}))}it(e){var a,r;(a=Q.__PosthogExtensions__)!=null&&a.initDeadClicksAutocapture&&e(),(r=Q.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",(n=>{n?Fp.error("failed to load script",n):e()}))}et(){var e;if(q){if(!this.tt&&(e=Q.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var a=gt(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};a.__onCapture=this.onCapture,this.tt=Q.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,a),this.tt.start(q),Fp.info("starting...")}}else Fp.error("`document` not found. Cannot start.")}stop(){this.tt&&(this.tt.stop(),this.tt=void 0,Fp.info("stopping..."))}},Ju=et("[ExceptionAutocapture]"),Jx=class{constructor(e){var a,r,n;this.rt=()=>{var o;if(T&&this.isEnabled&&(o=Q.__PosthogExtensions__)!=null&&o.errorWrappingFunctions){var i=Q.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,s=Q.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,l=Q.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.st&&this.R.capture_unhandled_errors&&(this.st=i(this.captureException.bind(this))),!this.nt&&this.R.capture_unhandled_rejections&&(this.nt=s(this.captureException.bind(this))),!this.ot&&this.R.capture_console_errors&&(this.ot=l(this.captureException.bind(this)))}catch(u){Ju.error("failed to start",u),this.ut()}}},this._instance=e,this.ht=!((a=this._instance.persistence)==null||!a.props[BA]),this.dt=new Lx({refillRate:(r=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(n=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&n!==void 0?n:10,refillInterval:1e4,h:Ju}),this.R=this.vt(),this.startIfEnabledOrStop()}vt(){var e=this._instance.config.capture_exceptions,a={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return gt(e)?a=j({},a,e):(V(e)?this.ht:e)&&(a=j({},a,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),a}get isEnabled(){return this.R.capture_console_errors||this.R.capture_unhandled_errors||this.R.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ju.info("enabled"),this.ut(),this.it(this.rt)):this.ut()}it(e){var a,r;(a=Q.__PosthogExtensions__)!=null&&a.errorWrappingFunctions&&e(),(r=Q.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"exception-autocapture",(n=>{if(n)return Ju.error("failed to load script",n);e()}))}ut(){var e,a,r;(e=this.st)==null||e.call(this),this.st=void 0,(a=this.nt)==null||a.call(this),this.nt=void 0,(r=this.ot)==null||r.call(this),this.ot=void 0}onRemoteConfig(e){var a=e.autocaptureExceptions;this.ht=!!a||!1,this._instance.persistence&&this._instance.persistence.register({[BA]:this.ht}),this.R=this.vt(),this.startIfEnabledOrStop()}onConfigChange(){this.R=this.vt()}captureException(e){var a,r,n=(a=e==null||(r=e.$exception_list)==null||(r=r[0])==null?void 0:r.type)!==null&&a!==void 0?a:"Exception";this.dt.consumeRateLimit(n)?Ju.info("Skipping exception capture because of client rate limiting.",{exception:n}):this._instance.exceptions.sendExceptionEvent(e)}};function ZA(t,e,a){try{if(!(e in t))return()=>{};var r=t[e],n=a(r);return _o(n)&&(n.prototype=n.prototype||{},Object.defineProperties(n,{__posthog_wrapped__:{enumerable:!1,value:!0}})),t[e]=n,()=>{t[e]=r}}catch{return()=>{}}}var eb=class{constructor(e){var a;this._instance=e,this.ct=(T==null||(a=T.location)==null?void 0:a.pathname)||""}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&($.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.ft&&this.ft(),this.ft=void 0,$.info("History API monitoring stopped")}monitorHistoryChanges(){var e,a;if(T&&T.history){var r=this;(e=T.history.pushState)!=null&&e.__posthog_wrapped__||ZA(T.history,"pushState",(n=>function(o,i,s){n.call(this,o,i,s),r._t("pushState")})),(a=T.history.replaceState)!=null&&a.__posthog_wrapped__||ZA(T.history,"replaceState",(n=>function(o,i,s){n.call(this,o,i,s),r._t("replaceState")})),this.bt()}}_t(e){try{var a,r=T==null||(a=T.location)==null?void 0:a.pathname;if(!r)return;r!==this.ct&&this.isEnabled&&this._instance.capture("$pageview",{navigation_type:e}),this.ct=r}catch(n){$.error("Error capturing "+e+" pageview",n)}}bt(){if(!this.ft){var e=()=>{this._t("popstate")};ft(T,"popstate",e),this.ft=()=>{T&&T.removeEventListener("popstate",e)}}}},cx=et("[SegmentIntegration]");function PH(t,e){var a=t.config.segment;if(!a)return e();(function(r,n){var o=r.config.segment;if(!o)return n();var i=l=>{var u=()=>l.anonymousId()||So();r.config.get_device_id=u,l.id()&&(r.register({distinct_id:l.id(),$device_id:u()}),r.persistence.set_property(pn,"identified")),n()},s=o.user();"then"in s&&_o(s.then)?s.then(i):i(s)})(t,(()=>{a.register((r=>{Promise&&Promise.resolve||cx.warn("This browser does not have Promise support, and can not use the segment integration");var n=(o,i)=>{if(!i)return o;o.event.userId||o.event.anonymousId===r.get_distinct_id()||(cx.info("No userId set, resetting PostHog"),r.reset()),o.event.userId&&o.event.userId!==r.get_distinct_id()&&(cx.info("UserId set, identifying with PostHog"),r.identify(o.event.userId));var s=r.calculateEventProperties(i,o.event.properties);return o.event.properties=Object.assign({},s,o.event.properties),o};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:o=>n(o,o.event.event),page:o=>n(o,"$pageview"),identify:o=>n(o,"$identify"),screen:o=>n(o,"$screen")}})(t)).then((()=>{e()}))}))}var nT="posthog-js";function oT(t,e){var{organization:a,projectId:r,prefix:n,severityAllowList:o=["error"],sendExceptionsToPostHog:i=!0}=e===void 0?{}:e;return s=>{var l,u,c,d,f;if(!(o==="*"||o.includes(s.level))||!t.__loaded)return s;s.tags||(s.tags={});var h=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());s.tags["PostHog Person URL"]=h,t.sessionRecordingStarted()&&(s.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var S=((l=s.exception)==null?void 0:l.values)||[],x=S.map((g=>j({},g,{stacktrace:g.stacktrace?j({},g.stacktrace,{type:"raw",frames:(g.stacktrace.frames||[]).map((m=>j({},m,{platform:"web:javascript"})))}):void 0}))),b={$exception_message:((u=S[0])==null?void 0:u.value)||s.message,$exception_type:(c=S[0])==null?void 0:c.type,$exception_level:s.level,$exception_list:x,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:((d=S[0])==null?void 0:d.value)||s.message,$sentry_exception_type:(f=S[0])==null?void 0:f.type,$sentry_tags:s.tags};return a&&r&&(b.$sentry_url=(n||"https://sentry.io/organizations/")+a+"/issues/?project="+r+"&query="+s.event_id),i&&t.exceptions.sendExceptionEvent(b),s}}var tb=class{constructor(e,a,r,n,o,i){this.name=nT,this.setupOnce=function(s){s(oT(e,{organization:a,projectId:r,prefix:n,severityAllowList:o,sendExceptionsToPostHog:i==null||i}))}}},NH=T!=null&&T.location?eh(T.location.hash,"__posthog")||eh(location.hash,"state"):null,XA="_postHogToolbarParams",KA=et("[Toolbar]"),bo=(function(t){return t[t.UNINITIALIZED=0]="UNINITIALIZED",t[t.LOADING=1]="LOADING",t[t.LOADED=2]="LOADED",t})(bo||{}),ab=class{constructor(e){this.instance=e}yt(e){Q.ph_toolbar_state=e}wt(){var e;return(e=Q.ph_toolbar_state)!==null&&e!==void 0?e:bo.UNINITIALIZED}maybeLoadToolbar(e,a,r){if(e===void 0&&(e=void 0),a===void 0&&(a=void 0),r===void 0&&(r=void 0),!T||!q)return!1;e=e??T.location,r=r??T.history;try{if(!a){try{T.localStorage.setItem("test","test"),T.localStorage.removeItem("test")}catch{return!1}a=T?.localStorage}var n,o=NH||eh(e.hash,"__posthog")||eh(e.hash,"state"),i=o?OA((()=>JSON.parse(atob(decodeURIComponent(o)))))||OA((()=>JSON.parse(decodeURIComponent(o)))):null;return i&&i.action==="ph_authorize"?((n=i).source="url",n&&Object.keys(n).length>0&&(i.desiredHash?e.hash=i.desiredHash:r?r.replaceState(r.state,"",e.pathname+e.search):e.hash="")):((n=JSON.parse(a.getItem(XA)||"{}")).source="localstorage",delete n.userIntent),!(!n.token||this.instance.config.token!==n.token)&&(this.loadToolbar(n),!0)}catch{return!1}}xt(e){var a=Q.ph_load_toolbar||Q.ph_load_editor;!ge(a)&&_o(a)?a(e,this.instance):KA.warn("No toolbar load function found")}loadToolbar(e){var a=!(q==null||!q.getElementById($E));if(!T||a)return!1;var r=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,n=j({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},r?{instrument:!1}:{});if(T.localStorage.setItem(XA,JSON.stringify(j({},n,{source:void 0}))),this.wt()===bo.LOADED)this.xt(n);else if(this.wt()===bo.UNINITIALIZED){var o;this.yt(bo.LOADING),(o=Q.__PosthogExtensions__)==null||o.loadExternalDependency==null||o.loadExternalDependency(this.instance,"toolbar",(i=>{if(i)return KA.error("[Toolbar] Failed to load",i),void this.yt(bo.UNINITIALIZED);this.yt(bo.LOADED),this.xt(n)})),ft(T,"turbolinks:load",(()=>{this.yt(bo.UNINITIALIZED),this.loadToolbar(n)}))}return!0}Et(e){return this.loadToolbar(e)}maybeLoadEditor(e,a,r){return e===void 0&&(e=void 0),a===void 0&&(a=void 0),r===void 0&&(r=void 0),this.maybeLoadToolbar(e,a,r)}},FH=et("[TracingHeaders]"),rb=class{constructor(e){this.$t=void 0,this.St=void 0,this.rt=()=>{var a,r;V(this.$t)&&((a=Q.__PosthogExtensions__)==null||(a=a.tracingHeadersPatchFns)==null||a._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),V(this.St)&&((r=Q.__PosthogExtensions__)==null||(r=r.tracingHeadersPatchFns)==null||r._patchFetch(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=e}it(e){var a,r;(a=Q.__PosthogExtensions__)!=null&&a.tracingHeadersPatchFns&&e(),(r=Q.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"tracing-headers",(n=>{if(n)return FH.error("failed to load script",n);e()}))}startIfEnabledOrStop(){var e,a;this._instance.config.__add_tracing_headers?this.it(this.rt):((e=this.$t)==null||e.call(this),(a=this.St)==null||a.call(this),this.$t=void 0,this.St=void 0)}},Hp="https?://(.*)",rl=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],HH=al(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],rl),Lc="<masked>",UH=["li_fat_id"];function iT(t,e,a){if(!q)return{};var r,n=e?al([],rl,a||[]):[],o=sT(wc(q.URL,n,Lc),t),i=(r={},Be(UH,(function(s){var l=kr.q(s);r[s]=l||null})),r);return ot(i,o)}function sT(t,e){var a=HH.concat(e||[]),r={};return Be(a,(function(n){var o=Jp(t,n);r[n]=o||null})),r}function lT(t){var e=(function(o){return o?o.search(Hp+"google.([^/?]*)")===0?"google":o.search(Hp+"bing.com")===0?"bing":o.search(Hp+"yahoo.com")===0?"yahoo":o.search(Hp+"duckduckgo.com")===0?"duckduckgo":null:null})(t),a=e!="yahoo"?"q":"p",r={};if(!cr(e)){r.$search_engine=e;var n=q?Jp(q.referrer,a):"";n.length&&(r.ph_keyword=n)}return r}function YA(){return navigator.language||navigator.userLanguage}function uT(){return q?.referrer||"$direct"}function cT(t,e){var a=t?al([],rl,e||[]):[],r=Bt?.href.substring(0,1e3);return{r:uT().substring(0,1e3),u:r?wc(r,a,Lc):void 0}}function dT(t){var e,{r:a,u:r}=t,n={$referrer:a,$referring_domain:a==null?void 0:a=="$direct"?"$direct":(e=Qp(a))==null?void 0:e.host};if(r){n.$current_url=r;var o=Qp(r);n.$host=o?.host,n.$pathname=o?.pathname;var i=sT(r);ot(n,i)}if(a){var s=lT(a);ot(n,s)}return n}function fT(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function zH(){try{return new Date().getTimezoneOffset()}catch{return}}function qH(t,e){if(!ua)return{};var a,r,n,o=t?al([],rl,e||[]):[],[i,s]=(function(l){for(var u=0;u<AA.length;u++){var[c,d]=AA[u],f=c.exec(l),h=f&&(_o(d)?d(f,l):d);if(h)return h}return["",""]})(ua);return ot(Nb({$os:i,$os_version:s,$browser:PE(ua,navigator.vendor),$device:EA(ua),$device_type:(r=ua,n=EA(r),n===_E||n===SE||n==="Kobo"||n==="Kindle Fire"||n===BE?vc:n===xc||n===Qs||n===bc||n===Ix?"Console":n===wE?"Wearable":n?$a:"Desktop"),$timezone:fT(),$timezone_offset:zH()}),{$current_url:wc(Bt?.href,o,Lc),$host:Bt?.host,$pathname:Bt?.pathname,$raw_user_agent:ua.length>1e3?ua.substring(0,997)+"...":ua,$browser_version:Y3(ua,navigator.vendor),$browser_language:YA(),$browser_language_prefix:(a=YA(),typeof a=="string"?a.split("-")[0]:void 0),$screen_height:T?.screen.height,$screen_width:T?.screen.width,$viewport_height:T?.innerHeight,$viewport_width:T?.innerWidth,$lib:"web",$lib_version:fn.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})}var vo=et("[Web Vitals]"),QA=9e5,nb=class{constructor(e){var a;this.kt=!1,this.P=!1,this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.Pt=()=>{clearTimeout(this.Tt),this.N.metrics.length!==0&&(this._instance.capture("$web_vitals",this.N.metrics.reduce(((r,n)=>j({},r,{["$web_vitals_"+n.name+"_event"]:j({},n),["$web_vitals_"+n.name+"_value"]:n.value})),{})),this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.It=r=>{var n,o=(n=this._instance.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0);if(V(o))vo.error("Could not read session ID. Dropping metrics!");else{this.N=this.N||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var i=this.Ct();V(i)||(ge(r?.name)||ge(r?.value)?vo.error("Invalid metric received",r):this.Rt&&r.value>=this.Rt?vo.error("Ignoring metric with value >= "+this.Rt,r):(this.N.url!==i&&(this.Pt(),this.Tt=setTimeout(this.Pt,this.flushToCaptureTimeoutMs)),V(this.N.url)&&(this.N.url=i),this.N.firstMetricTimestamp=V(this.N.firstMetricTimestamp)?Date.now():this.N.firstMetricTimestamp,r.attribution&&r.attribution.interactionTargetElement&&(r.attribution.interactionTargetElement=void 0),this.N.metrics.push(j({},r,{$current_url:i,$session_id:o.sessionId,$window_id:o.windowId,timestamp:Date.now()})),this.N.metrics.length===this.allowedMetrics.length&&this.Pt()))}},this.rt=()=>{if(!this.P){var r,n,o,i,s=Q.__PosthogExtensions__;V(s)||V(s.postHogWebVitalsCallbacks)||({onLCP:r,onCLS:n,onFCP:o,onINP:i}=s.postHogWebVitalsCallbacks),r&&n&&o&&i?(this.allowedMetrics.indexOf("LCP")>-1&&r(this.It.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&n(this.It.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&o(this.It.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&i(this.It.bind(this)),this.P=!0):vo.error("web vitals callbacks not loaded - not starting")}},this._instance=e,this.kt=!((a=this._instance.persistence)==null||!a.props[NA]),this.startIfEnabled()}get allowedMetrics(){var e,a,r=gt(this._instance.config.capture_performance)?(e=this._instance.config.capture_performance)==null?void 0:e.web_vitals_allowed_metrics:void 0;return ge(r)?((a=this._instance.persistence)==null?void 0:a.props[HA])||["CLS","FCP","INP","LCP"]:r}get flushToCaptureTimeoutMs(){return(gt(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var e=gt(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_attribution:void 0;return e!=null&&e}get Rt(){var e=gt(this._instance.config.capture_performance)&&yn(this._instance.config.capture_performance.__web_vitals_max_value)?this._instance.config.capture_performance.__web_vitals_max_value:QA;return 0<e&&e<=6e4?QA:e}get isEnabled(){var e=Bt?.protocol;if(e!=="http:"&&e!=="https:")return vo.info("Web Vitals are disabled on non-http/https protocols"),!1;var a=gt(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals:vn(this._instance.config.capture_performance)?this._instance.config.capture_performance:void 0;return vn(a)?a:this.kt}startIfEnabled(){this.isEnabled&&!this.P&&(vo.info("enabled, starting..."),this.it(this.rt))}onRemoteConfig(e){var a=gt(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=gt(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[NA]:a}),this._instance.persistence.register({[HA]:r})),this.kt=a,this.startIfEnabled()}it(e){var a,r;if((a=Q.__PosthogExtensions__)!=null&&a.postHogWebVitalsCallbacks)e();else{var n=this.useAttribution?"web-vitals-with-attribution":"web-vitals";(r=Q.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,n,(o=>{o?vo.error("failed to load script",o):e()}))}}Ct(){var e=T?T.location.href:void 0;if(e){var a=this._instance.config.mask_personal_data_properties,r=this._instance.config.custom_personal_data_properties,n=a?al([],rl,r||[]):[];return wc(e,n,Lc)}vo.error("Could not determine current URL")}},VH=et("[Heatmaps]");function JA(t){return gt(t)&&"clientX"in t&&"clientY"in t&&yn(t.clientX)&&yn(t.clientY)}var ob=class{constructor(e){var a;this.kt=!1,this.P=!1,this.Ft=null,this.instance=e,this.kt=!((a=this.instance.persistence)==null||!a.props[Hx]),this.rageclicks=new Yp(e.config.rageclick)}get flushIntervalMilliseconds(){var e=5e3;return gt(this.instance.config.capture_heatmaps)&&this.instance.config.capture_heatmaps.flush_interval_milliseconds&&(e=this.instance.config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return ge(this.instance.config.capture_heatmaps)?ge(this.instance.config.enable_heatmaps)?this.kt:this.instance.config.enable_heatmaps:this.instance.config.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.P)return;VH.info("starting..."),this.Ot(),this.Mt()}else{var e;clearInterval((e=this.Ft)!==null&&e!==void 0?e:void 0),this.At(),this.getAndClearBuffer()}}onRemoteConfig(e){var a=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Hx]:a}),this.kt=a,this.startIfEnabled()}getAndClearBuffer(){var e=this.N;return this.N=void 0,e}jt(e){this.Dt(e.originalEvent,"deadclick")}Mt(){this.Ft&&clearInterval(this.Ft),this.Ft=(function(e){return e?.visibilityState==="visible"})(q)?setInterval(this.Lt.bind(this),this.flushIntervalMilliseconds):null}Ot(){T&&q&&(this.Nt=this.Lt.bind(this),ft(T,"beforeunload",this.Nt),this.Ut=e=>this.Dt(e||T?.event),ft(q,"click",this.Ut,{capture:!0}),this.zt=e=>this.Ht(e||T?.event),ft(q,"mousemove",this.zt,{capture:!0}),this.Bt=new th(this.instance,DH,this.jt.bind(this)),this.Bt.startIfEnabled(),this.qt=this.Mt.bind(this),ft(q,"visibilitychange",this.qt),this.P=!0)}At(){var e;T&&q&&(this.Nt&&T.removeEventListener("beforeunload",this.Nt),this.Ut&&q.removeEventListener("click",this.Ut,{capture:!0}),this.zt&&q.removeEventListener("mousemove",this.zt,{capture:!0}),this.qt&&q.removeEventListener("visibilitychange",this.qt),clearTimeout(this.Wt),(e=this.Bt)==null||e.stop(),this.P=!1)}Gt(e,a){var r=this.instance.scrollManager.scrollY(),n=this.instance.scrollManager.scrollX(),o=this.instance.scrollManager.scrollElement(),i=(function(s,l,u){for(var c=s;c&&ph(c)&&!wo(c,"body");){if(c===u)return!1;if(he(l,T?.getComputedStyle(c).position))return!0;c=KE(c)}return!1})(ZE(e),["fixed","sticky"],o);return{x:e.clientX+(i?0:n),y:e.clientY+(i?0:r),target_fixed:i,type:a}}Dt(e,a){var r;if(a===void 0&&(a="click"),!UA(e.target)&&JA(e)){var n=this.Gt(e,a);(r=this.rageclicks)!=null&&r.isRageClick(e.clientX,e.clientY,new Date().getTime())&&this.Vt(j({},n,{type:"rageclick"})),this.Vt(n)}}Ht(e){!UA(e.target)&&JA(e)&&(clearTimeout(this.Wt),this.Wt=setTimeout((()=>{this.Vt(this.Gt(e,"mousemove"))}),500))}Vt(e){if(T){var a=T.location.href,r=this.instance.config.mask_personal_data_properties,n=this.instance.config.custom_personal_data_properties,o=r?al([],rl,n||[]):[],i=wc(a,o,Lc);this.N=this.N||{},this.N[i]||(this.N[i]=[]),this.N[i].push(e)}}Lt(){this.N&&!Xs(this.N)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},ah=class{constructor(e){this.Jt=(a,r,n)=>{n&&(n.noSessionId||n.activityTimeout||n.sessionPastMaximumLength)&&($.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:a,changeReason:n}),this.Kt=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.Yt()}Yt(){var e;this.Xt=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.Jt)}destroy(){var e;(e=this.Xt)==null||e.call(this),this.Xt=void 0}doPageView(e,a){var r,n=this.Qt(e,a);return this.Kt={pathname:(r=T?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:a,timestamp:e},this._instance.scrollManager.resetContext(),n}doPageLeave(e){var a;return this.Qt(e,(a=this.Kt)==null?void 0:a.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.Kt)==null?void 0:e.pageViewId}}Qt(e,a){var r=this.Kt;if(!r)return{$pageview_id:a};var n={$pageview_id:a,$prev_pageview_id:r.pageViewId},o=this._instance.scrollManager.getContext();if(o&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:i,lastScrollY:s,maxScrollY:l,maxContentHeight:u,lastContentY:c,maxContentY:d}=o;if(!(V(i)||V(s)||V(l)||V(u)||V(c)||V(d))){i=Math.ceil(i),s=Math.ceil(s),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var f=i<=1?1:Ir(s/i,0,1,$),h=i<=1?1:Ir(l/i,0,1,$),S=u<=1?1:Ir(c/u,0,1,$),x=u<=1?1:Ir(d/u,0,1,$);n=ot(n,{$prev_pageview_last_scroll:s,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:S,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:x})}}return r.pathname&&(n.$prev_pageview_pathname=r.pathname),r.timestamp&&(n.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),n}};var mn=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),ja=Uint8Array,Zt=Uint16Array,tl=Uint32Array,zb=new ja([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),qb=new ja([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),eE=new ja([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),pT=function(t,e){for(var a=new Zt(31),r=0;r<31;++r)a[r]=e+=1<<t[r-1];var n=new tl(a[30]);for(r=1;r<30;++r)for(var o=a[r];o<a[r+1];++o)n[o]=o-a[r]<<5|r;return[a,n]},hT=pT(zb,2),$H=hT[0],ib=hT[1];$H[28]=258,ib[258]=28;for(sb=pT(qb,0)[1],rh=new Zt(32768),Pe=0;Pe<32768;++Pe)yo=(43690&Pe)>>>1|(21845&Pe)<<1,yo=(61680&(yo=(52428&yo)>>>2|(13107&yo)<<2))>>>4|(3855&yo)<<4,rh[Pe]=((65280&yo)>>>8|(255&yo)<<8)>>>1;var yo,sb,rh,Pe,hc=function(t,e,a){for(var r=t.length,n=0,o=new Zt(e);n<r;++n)++o[t[n]-1];var i,s=new Zt(e);for(n=0;n<e;++n)s[n]=s[n-1]+o[n-1]<<1;if(a){i=new Zt(1<<e);var l=15-e;for(n=0;n<r;++n)if(t[n])for(var u=n<<4|t[n],c=e-t[n],d=s[t[n]-1]++<<c,f=d|(1<<c)-1;d<=f;++d)i[rh[d]>>>l]=u}else for(i=new Zt(r),n=0;n<r;++n)i[n]=rh[s[t[n]-1]++]>>>15-t[n];return i},ki=new ja(288);for(Pe=0;Pe<144;++Pe)ki[Pe]=8;for(Pe=144;Pe<256;++Pe)ki[Pe]=9;for(Pe=256;Pe<280;++Pe)ki[Pe]=7;for(Pe=280;Pe<288;++Pe)ki[Pe]=8;var nh=new ja(32);for(Pe=0;Pe<32;++Pe)nh[Pe]=5;var jH=hc(ki,9,0),GH=hc(nh,5,0),mT=function(t){return(t/8>>0)+(7&t&&1)},gT=function(t,e,a){(a==null||a>t.length)&&(a=t.length);var r=new(t instanceof Zt?Zt:t instanceof tl?tl:ja)(a-e);return r.set(t.subarray(e,a)),r},cn=function(t,e,a){a<<=7&e;var r=e/8>>0;t[r]|=a,t[r+1]|=a>>>8},ec=function(t,e,a){a<<=7&e;var r=e/8>>0;t[r]|=a,t[r+1]|=a>>>8,t[r+2]|=a>>>16},dx=function(t,e){for(var a=[],r=0;r<t.length;++r)t[r]&&a.push({s:r,f:t[r]});var n=a.length,o=a.slice();if(!n)return[new ja(0),0];if(n==1){var i=new ja(a[0].s+1);return i[a[0].s]=1,[i,1]}a.sort((function(C,w){return C.f-w.f})),a.push({s:-1,f:25001});var s=a[0],l=a[1],u=0,c=1,d=2;for(a[0]={s:-1,f:s.f+l.f,l:s,r:l};c!=n-1;)s=a[a[u].f<a[d].f?u++:d++],l=a[u!=c&&a[u].f<a[d].f?u++:d++],a[c++]={s:-1,f:s.f+l.f,l:s,r:l};var f=o[0].s;for(r=1;r<n;++r)o[r].s>f&&(f=o[r].s);var h=new Zt(f+1),S=lb(a[c-1],h,0);if(S>e){r=0;var x=0,b=S-e,g=1<<b;for(o.sort((function(C,w){return h[w.s]-h[C.s]||C.f-w.f}));r<n;++r){var m=o[r].s;if(!(h[m]>e))break;x+=g-(1<<S-h[m]),h[m]=e}for(x>>>=b;x>0;){var y=o[r].s;h[y]<e?x-=1<<e-h[y]++-1:++r}for(;r>=0&&x;--r){var v=o[r].s;h[v]==e&&(--h[v],++x)}S=e}return[new ja(h),S]},lb=function(t,e,a){return t.s==-1?Math.max(lb(t.l,e,a+1),lb(t.r,e,a+1)):e[t.s]=a},tE=function(t){for(var e=t.length;e&&!t[--e];);for(var a=new Zt(++e),r=0,n=t[0],o=1,i=function(l){a[r++]=l},s=1;s<=e;++s)if(t[s]==n&&s!=e)++o;else{if(!n&&o>2){for(;o>138;o-=138)i(32754);o>2&&(i(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(i(n),--o;o>6;o-=6)i(8304);o>2&&(i(o-3<<5|8208),o=0)}for(;o--;)i(n);o=1,n=t[s]}return[a.subarray(0,r),e]},tc=function(t,e){for(var a=0,r=0;r<e.length;++r)a+=t[r]*e[r];return a},ub=function(t,e,a){var r=a.length,n=mT(e+2);t[n]=255&r,t[n+1]=r>>>8,t[n+2]=255^t[n],t[n+3]=255^t[n+1];for(var o=0;o<r;++o)t[n+o+4]=a[o];return 8*(n+4+r)},aE=function(t,e,a,r,n,o,i,s,l,u,c){cn(e,c++,a),++n[256];for(var d=dx(n,15),f=d[0],h=d[1],S=dx(o,15),x=S[0],b=S[1],g=tE(f),m=g[0],y=g[1],v=tE(x),C=v[0],w=v[1],_=new Zt(19),L=0;L<m.length;++L)_[31&m[L]]++;for(L=0;L<C.length;++L)_[31&C[L]]++;for(var A=dx(_,7),I=A[0],R=A[1],H=19;H>4&&!I[eE[H-1]];--H);var E,M,D,F,Z=u+5<<3,U=tc(n,ki)+tc(o,nh)+i,W=tc(n,f)+tc(o,x)+i+14+3*H+tc(_,I)+(2*_[16]+3*_[17]+7*_[18]);if(Z<=U&&Z<=W)return ub(e,c,t.subarray(l,l+u));if(cn(e,c,1+(W<U)),c+=2,W<U){E=hc(f,h,0),M=f,D=hc(x,b,0),F=x;var ce=hc(I,R,0);for(cn(e,c,y-257),cn(e,c+5,w-1),cn(e,c+10,H-4),c+=14,L=0;L<H;++L)cn(e,c+3*L,I[eE[L]]);c+=3*H;for(var Xt=[m,C],it=0;it<2;++it){var yt=Xt[it];for(L=0;L<yt.length;++L){var N=31&yt[L];cn(e,c,ce[N]),c+=I[N],N>15&&(cn(e,c,yt[L]>>>5&127),c+=yt[L]>>>12)}}}else E=jH,M=ki,D=GH,F=nh;for(L=0;L<s;++L)if(r[L]>255){N=r[L]>>>18&31,ec(e,c,E[N+257]),c+=M[N+257],N>7&&(cn(e,c,r[L]>>>23&31),c+=zb[N]);var te=31&r[L];ec(e,c,D[te]),c+=F[te],te>3&&(ec(e,c,r[L]>>>5&8191),c+=qb[te])}else ec(e,c,E[r[L]]),c+=M[r[L]];return ec(e,c,E[256]),c+M[256]},WH=new tl([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ZH=(function(){for(var t=new tl(256),e=0;e<256;++e){for(var a=e,r=9;--r;)a=(1&a&&3988292384)^a>>>1;t[e]=a}return t})(),XH=function(t,e,a,r,n){return(function(o,i,s,l,u,c){var d=o.length,f=new ja(l+d+5*(1+Math.floor(d/7e3))+u),h=f.subarray(l,f.length-u),S=0;if(!i||d<8)for(var x=0;x<=d;x+=65535){var b=x+65535;b<d?S=ub(h,S,o.subarray(x,b)):(h[x]=c,S=ub(h,S,o.subarray(x,d)))}else{for(var g=WH[i-1],m=g>>>13,y=8191&g,v=(1<<s)-1,C=new Zt(32768),w=new Zt(v+1),_=Math.ceil(s/3),L=2*_,A=function(Mh){return(o[Mh]^o[Mh+1]<<_^o[Mh+2]<<L)&v},I=new tl(25e3),R=new Zt(288),H=new Zt(32),E=0,M=0,D=(x=0,0),F=0,Z=0;x<d;++x){var U=A(x),W=32767&x,ce=w[U];if(C[W]=ce,w[U]=W,F<=x){var Xt=d-x;if((E>7e3||D>24576)&&Xt>423){S=aE(o,h,0,I,R,H,M,D,Z,x-Z,S),D=E=M=0,Z=x;for(var it=0;it<286;++it)R[it]=0;for(it=0;it<30;++it)H[it]=0}var yt=2,N=0,te=y,pt=W-ce&32767;if(Xt>2&&U==A(x-pt))for(var Sn=Math.min(m,Xt)-1,Eh=Math.min(32767,x),Th=Math.min(258,Xt);pt<=Eh&&--te&&W!=ce;){if(o[x+yt]==o[x+yt-pt]){for(var _n=0;_n<Th&&o[x+_n]==o[x+_n-pt];++_n);if(_n>yt){if(yt=_n,N=pt,_n>Sn)break;var NR=Math.min(pt,_n-2),J0=0;for(it=0;it<NR;++it){var Rh=x-pt+it+32768&32767,eS=Rh-C[Rh]+32768&32767;eS>J0&&(J0=eS,ce=Rh)}}}pt+=(W=ce)-(ce=C[W])+32768&32767}if(N){I[D++]=268435456|ib[yt]<<18|sb[N];var tS=31&ib[yt],aS=31&sb[N];M+=zb[tS]+qb[aS],++R[257+tS],++H[aS],F=x+yt,++E}else I[D++]=o[x],++R[o[x]]}}S=aE(o,h,c,I,R,H,M,D,Z,x-Z,S)}return gT(f,0,l+mT(S)+u)})(t,e.level==null?6:e.level,e.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(t.length)))):12+e.mem,a,r,!0)},fx=function(t,e,a){for(;a;++e)t[e]=a,a>>>=8};function KH(t,e){e===void 0&&(e={});var a=(function(){var s=4294967295;return{p:function(l){for(var u=s,c=0;c<l.length;++c)u=ZH[255&u^l[c]]^u>>>8;s=u},d:function(){return 4294967295^s}}})(),r=t.length;a.p(t);var n,o=XH(t,e,10+((n=e).filename&&n.filename.length+1||0),8),i=o.length;return(function(s,l){var u=l.filename;if(s[0]=31,s[1]=139,s[2]=8,s[8]=l.level<2?4:l.level==9?2:0,s[9]=3,l.mtime!=0&&fx(s,4,Math.floor(new Date(l.mtime||Date.now())/1e3)),u){s[3]=8;for(var c=0;c<=u.length;++c)s[c+10]=u.charCodeAt(c)}})(o,e),fx(o,i-8,a.d()),fx(o,i-4,r),o}var YH=function(t){var e,a,r,n,o="";for(e=a=0,r=(t=(t+"").replace(/\r\n/g,`
500
500
  `).replace(/\r/g,`
501
- `)).length,n=0;n<r;n++){var i=t.charCodeAt(n),s=null;i<128?a++:s=i>127&&i<2048?String.fromCharCode(i>>6|192,63&i|128):String.fromCharCode(i>>12|224,i>>6&63|128,63&i|128),cr(s)||(a>e&&(o+=t.substring(e,a)),o+=s,e=a=n+1)}return a>e&&(o+=t.substring(e,t.length)),o},Q3=!!Sx||!!bx,rE="text/plain",oh=function(t,e,a){var r;a===void 0&&(a=!0);var[n,o]=t.split("?"),i=j({},e),s=(r=o?.split("&").map((u=>{var c,[d,f]=u.split("="),h=a&&(c=i[d])!==null&&c!==void 0?c:f;return delete i[d],d+"="+h})))!==null&&r!==void 0?r:[],l=L3(i);return l&&s.push(l),n+"?"+s.join("&")},dc=(t,e)=>JSON.stringify(t,((a,r)=>typeof r=="bigint"?r.toString():r),e),px=t=>{var{data:e,compression:a}=t;if(e){if(a===mn.GZipJS){var r=K3((function(l,u){var c=l.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(l);for(var d=new ja(l.length+(l.length>>>1)),f=0,h=function(g){d[f++]=g},S=0;S<c;++S){if(f+5>d.length){var x=new ja(f+8+(c-S<<1));x.set(d),d=x}var b=l.charCodeAt(S);b<128||u?h(b):b<2048?(h(192|b>>>6),h(128|63&b)):b>55295&&b<57344?(h(240|(b=65536+(1047552&b)|1023&l.charCodeAt(++S))>>>18),h(128|b>>>12&63),h(128|b>>>6&63),h(128|63&b)):(h(224|b>>>12),h(128|b>>>6&63),h(128|63&b))}return gT(d,0,f)})(dc(e)),{mtime:0}),n=new Blob([r],{type:rE});return{contentType:rE,body:n,estimatedSize:n.size}}if(a===mn.Base64){var o=(function(l){var u,c,d,f,h,S="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",x=0,b=0,g="",m=[];if(!l)return l;l=Y3(l);do u=(h=l.charCodeAt(x++)<<16|l.charCodeAt(x++)<<8|l.charCodeAt(x++))>>18&63,c=h>>12&63,d=h>>6&63,f=63&h,m[b++]=S.charAt(u)+S.charAt(c)+S.charAt(d)+S.charAt(f);while(x<l.length);switch(g=m.join(""),l.length%3){case 1:g=g.slice(0,-2)+"==";break;case 2:g=g.slice(0,-1)+"="}return g})(dc(e)),i=(l=>"data="+encodeURIComponent(typeof l=="string"?l:dc(l)))(o);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}var s=dc(e);return{contentType:"application/json",body:s,estimatedSize:new Blob([s]).size}}},qp=[];bx&&qp.push({transport:"fetch",method:t=>{var e,a,{contentType:r,body:n,estimatedSize:o}=(e=px(t))!==null&&e!==void 0?e:{},i=new Headers;Be(t.headers,(function(c,d){i.append(d,c)})),r&&i.append("Content-Type",r);var s=t.url,l=null;if(CA){var u=new CA;l={signal:u.signal,timeout:setTimeout((()=>u.abort()),t.timeout)}}bx(s,j({method:t?.method||"GET",headers:i,keepalive:t.method==="POST"&&(o||0)<52428.8,body:n,signal:(a=l)==null?void 0:a.signal},t.fetchOptions)).then((c=>c.text().then((d=>{var f={statusCode:c.status,text:d};if(c.status===200)try{f.json=JSON.parse(d)}catch(h){$.error(h)}t.callback==null||t.callback(f)})))).catch((c=>{$.error(c),t.callback==null||t.callback({statusCode:0,text:c})})).finally((()=>l?clearTimeout(l.timeout):null))}}),Sx&&qp.push({transport:"XHR",method:t=>{var e,a=new Sx;a.open(t.method||"GET",t.url,!0);var{contentType:r,body:n}=(e=px(t))!==null&&e!==void 0?e:{};Be(t.headers,(function(o,i){a.setRequestHeader(i,o)})),r&&a.setRequestHeader("Content-Type",r),t.timeout&&(a.timeout=t.timeout),t.disableXHRCredentials||(a.withCredentials=!0),a.onreadystatechange=()=>{if(a.readyState===4){var o={statusCode:a.status,text:a.responseText};if(a.status===200)try{o.json=JSON.parse(a.responseText)}catch{}t.callback==null||t.callback(o)}},a.send(n)}}),ka!=null&&ka.sendBeacon&&qp.push({transport:"sendBeacon",method:t=>{var e=oh(t.url,{beacon:"1"});try{var a,{contentType:r,body:n}=(a=px(t))!==null&&a!==void 0?a:{},o=typeof n=="string"?new Blob([n],{type:r}):n;ka.sendBeacon(e,o)}catch{}}});var ih=function(t,e){if(!(function(a){try{new RegExp(a)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function nE(t,e,a){return dc({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:a})}var vT={exact:(t,e)=>e.some((a=>t.some((r=>a===r)))),is_not:(t,e)=>e.every((a=>t.every((r=>a!==r)))),regex:(t,e)=>e.some((a=>t.some((r=>ih(a,r))))),not_regex:(t,e)=>e.every((a=>t.every((r=>!ih(a,r))))),icontains:(t,e)=>e.map(Up).some((a=>t.map(Up).some((r=>a.includes(r))))),not_icontains:(t,e)=>e.map(Up).every((a=>t.map(Up).every((r=>!a.includes(r))))),gt:(t,e)=>e.some((a=>{var r=parseFloat(a);return!isNaN(r)&&t.some((n=>r>parseFloat(n)))})),lt:(t,e)=>e.some((a=>{var r=parseFloat(a);return!isNaN(r)&&t.some((n=>r<parseFloat(n)))}))},Up=t=>t.toLowerCase();function yT(t,e){return!t||Object.entries(t).every((a=>{var[r,n]=a,o=e?.[r];if(V(o)||cr(o))return!1;var i=[String(o)],s=vT[n.operator];return!!s&&s(n.values,i)}))}var hx=et("[Error tracking]"),cb=class{constructor(e){var a,r;this.Zt=[],this.ti=new Ex([new Rx,new Fx,new Ox,new Mx,new Px,new Bx,new Dx,new Nx],s3()),this._instance=e,this.Zt=(a=(r=this._instance.persistence)==null?void 0:r.get_property(Ux))!==null&&a!==void 0?a:[]}onRemoteConfig(e){var a,r,n,o=(a=(r=e.errorTracking)==null?void 0:r.suppressionRules)!==null&&a!==void 0?a:[],i=(n=e.errorTracking)==null?void 0:n.captureExtensionExceptions;this.Zt=o,this._instance.persistence&&this._instance.persistence.register({[Ux]:this.Zt,[PA]:i})}get ii(){var e,a=!!this._instance.get_property(PA),r=this._instance.config.error_tracking.captureExtensionExceptions;return(e=r??a)!==null&&e!==void 0&&e}buildProperties(e,a){return this.ti.buildFromUnknown(e,{syntheticException:a?.syntheticException,mechanism:{handled:a?.handled}})}sendExceptionEvent(e){var a=e.$exception_list;if(this.ei(a)){if(this.ri(a))return void hx.info("Skipping exception capture because a suppression rule matched");if(!this.ii&&this.si(a))return void hx.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ni(a))return void hx.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent"})}ri(e){if(e.length===0)return!1;var a=e.reduce(((r,n)=>{var{type:o,value:i}=n;return vt(o)&&o.length>0&&r.$exception_types.push(o),vt(i)&&i.length>0&&r.$exception_values.push(i),r}),{$exception_types:[],$exception_values:[]});return this.Zt.some((r=>{var n=r.values.map((o=>{var i,s=vT[o.operator],l=Ce(o.value)?o.value:[o.value],u=(i=a[o.key])!==null&&i!==void 0?i:[];return l.length>0&&s(l,u)}));return r.type==="OR"?n.some(Boolean):n.every(Boolean)}))}si(e){return e.flatMap((a=>{var r,n;return(r=(n=a.stacktrace)==null?void 0:n.frames)!==null&&r!==void 0?r:[]})).some((a=>a.filename&&a.filename.startsWith("chrome-extension://")))}ni(e){if(e.length>0){var a,r,n,o,i=(a=(r=e[0].stacktrace)==null?void 0:r.frames)!==null&&a!==void 0?a:[],s=i[i.length-1];return(n=s==null||(o=s.filename)==null?void 0:o.includes("posthog.com/static"))!==null&&n!==void 0&&n}return!1}ei(e){return!ge(e)&&Ce(e)}},La=et("[FeatureFlags]"),ac=et("[FeatureFlags]",{debugEnabled:!0}),mx="$active_feature_flags",$s="$override_feature_flags",oE="$feature_flag_payloads",rc="$override_feature_flag_payloads",iE="$feature_flag_request_id",sE="$feature_flag_evaluated_at",lE=t=>{var e={};for(var[a,r]of zp(t||{}))r&&(e[a]=r);return e},J3=t=>{var e=t.flags;return e?(t.featureFlags=Object.fromEntries(Object.keys(e).map((a=>{var r;return[a,(r=e[a].variant)!==null&&r!==void 0?r:e[a].enabled]}))),t.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter((a=>e[a].enabled)).filter((a=>{var r;return(r=e[a].metadata)==null?void 0:r.payload})).map((a=>{var r;return[a,(r=e[a].metadata)==null?void 0:r.payload]})))):La.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),t},e4=(function(t){return t.FeatureFlags="feature_flags",t.Recordings="recordings",t})({}),db=class{constructor(e){this.oi=!1,this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.ci=!1,this._instance=e,this.featureFlagEventHandlers=[]}fi(){var e,a=(e=this._instance.config.evaluation_contexts)!==null&&e!==void 0?e:this._instance.config.evaluation_environments;return!this._instance.config.evaluation_environments||this._instance.config.evaluation_contexts||this.ci||(La.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.ci=!0),a!=null&&a.length?a.filter((r=>{var n=r&&typeof r=="string"&&r.trim().length>0;return n||La.error("Invalid evaluation context found:",r,"Expected non-empty string"),n})):[]}pi(){return this.fi().length>0}flags(){if(this._instance.config.__preview_remote_config)this.di=!0;else{var e=!this.gi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.mi({disableFlags:e})}}get hasLoadedFlags(){return this.ai}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(zx),a=this._instance.get_property($s),r=this._instance.get_property(rc);if(!r&&!a)return e||{};var n=ot({},e||{}),o=[...new Set([...Object.keys(r||{}),...Object.keys(a||{})])];for(var i of o){var s,l,u=n[i],c=a?.[i],d=V(c)?(s=u?.enabled)!==null&&s!==void 0&&s:!!c,f=V(c)?u.variant:typeof c=="string"?c:void 0,h=r?.[i],S=j({},u,{enabled:d,variant:d?f??u?.variant:void 0});d!==u?.enabled&&(S.original_enabled=u?.enabled),f!==u?.variant&&(S.original_variant=u?.variant),h&&(S.metadata=j({},u?.metadata,{payload:h,original_payload:u==null||(l=u.metadata)==null?void 0:l.payload})),n[i]=S}return this.oi||(La.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:r,finalDetails:n}),this.oi=!0),n}getFlagVariants(){var e=this._instance.get_property(Ks),a=this._instance.get_property($s);if(!a)return e||{};for(var r=ot({},e),n=Object.keys(a),o=0;o<n.length;o++)r[n[o]]=a[n[o]];return this.oi||(La.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:a,finalFlags:r}),this.oi=!0),r}getFlagPayloads(){var e=this._instance.get_property(oE),a=this._instance.get_property(rc);if(!a)return e||{};for(var r=ot({},e||{}),n=Object.keys(a),o=0;o<n.length;o++)r[n[o]]=a[n[o]];return this.oi||(La.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:a,finalPayloads:r}),this.oi=!0),r}reloadFeatureFlags(){this.ui||this._instance.config.advanced_disable_feature_flags||this.gi||(this.gi=setTimeout((()=>{this.mi()}),5))}bi(){clearTimeout(this.gi),this.gi=void 0}ensureFlagsLoaded(){this.ai||this.li||this.gi||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.ui=e}mi(e){var a;if(this.bi(),!this._instance.M())if(this.li)this.hi=!0;else{var r=this._instance.config.token,n=this._instance.get_property("$device_id"),o={token:r,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:j({},((a=this._instance.persistence)==null?void 0:a.get_initial_props())||{},this._instance.get_property(cc)||{}),group_properties:this._instance.get_property(wi)};cr(n)||V(n)||(o.$device_id=n),(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(o.disable_flags=!0),this.pi()&&(o.evaluation_contexts=this.fi());var i=this._instance.config.__preview_remote_config,s=i?"/flags/?v=2":"/flags/?v=2&config=true",l=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",u=this._instance.requestRouter.endpointFor("flags",s+l);i&&(o.timezone=fT()),this.li=!0,this._instance._send_request({method:"POST",url:u,data:o,compression:this._instance.config.disable_compression?void 0:mn.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:c=>{var d,f,h=!0;if(c.statusCode===200&&(this.hi||(this.$anon_distinct_id=void 0),h=!1),this.li=!1,this.di||(this.di=!0,this._instance.yi((f=c.json)!==null&&f!==void 0?f:{})),!o.disable_flags||this.hi)if(this.vi=!h,c.json&&(d=c.json.quotaLimited)!=null&&d.includes(e4.FeatureFlags))La.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more.");else{var S;o.disable_flags||this.receivedFeatureFlags((S=c.json)!==null&&S!==void 0?S:{},h),this.hi&&(this.hi=!1,this.mi())}}})}}getFeatureFlag(e,a){var r;if(a===void 0&&(a={}),this.ai||this.getFlags()&&this.getFlags().length>0){var n=this.getFeatureFlagResult(e,a);return(r=n?.variant)!==null&&r!==void 0?r:n?.enabled}La.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){var a=this.getFeatureFlagResult(e,{send_event:!1});return a?.payload}getFeatureFlagResult(e,a){if(a===void 0&&(a={}),this.ai||this.getFlags()&&this.getFlags().length>0){var r=this.getFlagVariants(),n=e in r,o=r[e],i=this.getFlagPayloads()[e],s=String(o),l=this._instance.get_property(iE)||void 0,u=this._instance.get_property(sE)||void 0,c=this._instance.get_property(Wp)||{};if((a.send_event||!("send_event"in a))&&(!(e in c)||!c[e].includes(s))){var d,f,h,S,x,b,g,m,y;Ce(c[e])?c[e].push(s):c[e]=[s],(d=this._instance.persistence)==null||d.register({[Wp]:c});var v=this.getFeatureFlagDetails(e),C={$feature_flag:e,$feature_flag_response:o,$feature_flag_payload:i||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((f=this._instance.config.bootstrap)==null||(f=f.featureFlags)==null?void 0:f[e])||null,$feature_flag_bootstrapped_payload:((h=this._instance.config.bootstrap)==null||(h=h.featureFlagPayloads)==null?void 0:h[e])||null,$used_bootstrap_value:!this.vi};V(v==null||(S=v.metadata)==null?void 0:S.version)||(C.$feature_flag_version=v.metadata.version);var w,_=(x=v==null||(b=v.reason)==null?void 0:b.description)!==null&&x!==void 0?x:v==null||(g=v.reason)==null?void 0:g.code;_&&(C.$feature_flag_reason=_),v!=null&&(m=v.metadata)!=null&&m.id&&(C.$feature_flag_id=v.metadata.id),V(v?.original_variant)&&V(v?.original_enabled)||(C.$feature_flag_original_response=V(v.original_variant)?v.original_enabled:v.original_variant),v!=null&&(y=v.metadata)!=null&&y.original_payload&&(C.$feature_flag_original_payload=v==null||(w=v.metadata)==null?void 0:w.original_payload),this._instance.capture("$feature_flag_called",C)}if(n){var L=i;if(!V(i))try{L=JSON.parse(i)}catch{}return{key:e,enabled:!!o,variant:typeof o=="string"?o:void 0,payload:L}}}else La.warn('getFeatureFlagResult for key "'+e+`" failed. Feature flags didn't load in time.`)}getRemoteConfigPayload(e,a){var r=this._instance.config.token,n={distinct_id:this._instance.get_distinct_id(),token:r};this.pi()&&(n.evaluation_contexts=this.fi()),this._instance._send_request({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2&config=true"),data:n,compression:this._instance.config.disable_compression?void 0:mn.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:o=>{var i,s=(i=o.json)==null?void 0:i.featureFlagPayloads;a(s?.[e]||void 0)}})}isFeatureEnabled(e,a){if(a===void 0&&(a={}),this.ai||this.getFlags()&&this.getFlags().length>0){var r=this.getFeatureFlag(e,a);return V(r)?void 0:!!r}La.warn('isFeatureEnabled for key "'+e+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((a=>a!==e))}receivedFeatureFlags(e,a){if(this._instance.persistence){this.ai=!0;var r=this.getFlagVariants(),n=this.getFlagPayloads(),o=this.getFlagsWithDetails();(function(i,s,l,u,c){l===void 0&&(l={}),u===void 0&&(u={}),c===void 0&&(c={});var d=J3(i),f=d.flags,h=d.featureFlags,S=d.featureFlagPayloads;if(h){var x=i.requestId,b=i.evaluatedAt;if(Ce(h)){La.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var g={};if(h)for(var m=0;m<h.length;m++)g[h[m]]=!0;s&&s.register({[mx]:h,[Ks]:g})}else{var y=h,v=S,C=f;if(i.errorsWhileComputingFlags)if(f){var w=new Set(Object.keys(f).filter((_=>{var L;return!((L=f[_])!=null&&L.failed)})));y=j({},l,Object.fromEntries(Object.entries(y).filter((_=>{var[L]=_;return w.has(L)})))),v=j({},u,Object.fromEntries(Object.entries(v||{}).filter((_=>{var[L]=_;return w.has(L)})))),C=j({},c,Object.fromEntries(Object.entries(C||{}).filter((_=>{var[L]=_;return w.has(L)}))))}else y=j({},l,y),v=j({},u,v),C=j({},c,C);s&&s.register(j({[mx]:Object.keys(lE(y)),[Ks]:y||{},[oE]:v||{},[zx]:C||{}},x?{[iE]:x}:{},b?{[sE]:b}:{}))}}})(e,this._instance.persistence,r,n,o),this.wi(a)}}override(e,a){a===void 0&&(a=!1),La.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:a})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return La.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister($s),this._instance.persistence.unregister(rc),this.wi(),ac.info("All overrides cleared");if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var a,r=e;if(this.oi=!!((a=r.suppressWarning)!==null&&a!==void 0&&a),"flags"in r){if(r.flags===!1)this._instance.persistence.unregister($s),ac.info("Flag overrides cleared");else if(r.flags){if(Ce(r.flags)){for(var n={},o=0;o<r.flags.length;o++)n[r.flags[o]]=!0;this._instance.persistence.register({[$s]:n})}else this._instance.persistence.register({[$s]:r.flags});ac.info("Flag overrides set",{flags:r.flags})}}return"payloads"in r&&(r.payloads===!1?(this._instance.persistence.unregister(rc),ac.info("Payload overrides cleared")):r.payloads&&(this._instance.persistence.register({[rc]:r.payloads}),ac.info("Payload overrides set",{payloads:r.payloads}))),void this.wi()}this.wi()}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.ai){var{flags:a,flagVariants:r}=this.xi();e(a,r)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,a,r){var n,o=(this._instance.get_property(uc)||[]).find((u=>u.flagKey===e)),i={["$feature_enrollment/"+e]:a},s={$feature_flag:e,$feature_enrollment:a,$set:i};o&&(s.$early_access_feature_name=o.name),r&&(s.$feature_enrollment_stage=r),this._instance.capture("$feature_enrollment_update",s),this.setPersonPropertiesForFlags(i,!1);var l=j({},this.getFlagVariants(),{[e]:a});(n=this._instance.persistence)==null||n.register({[mx]:Object.keys(lE(l)),[Ks]:l}),this.wi()}getEarlyAccessFeatures(e,a,r){a===void 0&&(a=!1);var n=this._instance.get_property(uc),o=r?"&"+r.map((i=>"stage="+i)).join("&"):"";if(n&&!a)return e(n);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+o),method:"GET",callback:i=>{var s,l;if(i.json){var u=i.json.earlyAccessFeatures;return(s=this._instance.persistence)==null||s.unregister(uc),(l=this._instance.persistence)==null||l.register({[uc]:u}),e(u)}}})}xi(){var e=this.getFlags(),a=this.getFlagVariants();return{flags:e.filter((r=>a[r])),flagVariants:Object.keys(a).filter((r=>a[r])).reduce(((r,n)=>(r[n]=a[n],r)),{})}}wi(e){var{flags:a,flagVariants:r}=this.xi();this.featureFlagEventHandlers.forEach((n=>n(a,r,{errorsLoading:e})))}setPersonPropertiesForFlags(e,a){a===void 0&&(a=!0);var r=this._instance.get_property(cc)||{};this._instance.register({[cc]:j({},r,e)}),a&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(cc)}setGroupPropertiesForFlags(e,a){a===void 0&&(a=!0);var r=this._instance.get_property(wi)||{};Object.keys(r).length!==0&&Object.keys(r).forEach((n=>{r[n]=j({},r[n],e[n]),delete e[n]})),this._instance.register({[wi]:j({},r,e)}),a&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var a=this._instance.get_property(wi)||{};this._instance.register({[wi]:j({},a,{[e]:{}})})}else this._instance.unregister(wi)}reset(){this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.$anon_distinct_id=void 0,this.bi(),this.oi=!1}},t4=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],mc=class{constructor(e,a){this.R=e,this.props={},this.Ei=!1,this.$i=(r=>{var n="";return r.token&&(n=r.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),r.persistence_name?"ph_"+r.persistence_name:"ph_"+n+"_posthog"})(e),this.Y=this.Si(e),this.load(),e.debug&&$.info("Persistence loaded",e.persistence,j({},this.props)),this.update_config(e,e,a),this.save()}isDisabled(){return!!this.ki}Si(e){t4.indexOf(e.persistence.toLowerCase())===-1&&($.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var a=(function(n){n===void 0&&(n=[]);var o=[...M3,...n];return j({},Ke,{W:function(i){try{var s={};try{s=kr.W(i)||{}}catch{}var l=ot(s,JSON.parse(Ke.q(i)||"{}"));return Ke.G(i,l),l}catch{}return null},G:function(i,s,l,u,c,d){try{Ke.G(i,s,void 0,void 0,d);var f={};o.forEach((h=>{s[h]&&(f[h]=s[h])})),Object.keys(f).length&&kr.G(i,f,l,u,c,d)}catch(h){Ke.B(h)}},V:function(i,s){try{T?.localStorage.removeItem(i),kr.V(i,s)}catch(l){Ke.B(l)}}})})(e.cookie_persisted_properties||[]),r=e.persistence.toLowerCase();return r==="localstorage"&&Ke.H()?Ke:r==="localstorage+cookie"&&a.H()?a:r==="sessionstorage"&&Dt.H()?Dt:r==="memory"?O3:r==="cookie"?kr:a.H()?a:kr}properties(){var e={};return Be(this.props,(function(a,r){if(r===Ks&&gt(a))for(var n=Object.keys(a),o=0;o<n.length;o++)e["$feature/"+n[o]]=a[n[o]];else s=r,l=!1,(cr(i=m3)?l:_A&&i.indexOf===_A?i.indexOf(s)!=-1:(Be(i,(function(u){if(l||(l=u===s))return jp})),l))||(e[r]=a);var i,s,l})),e}load(){if(!this.ki){var e=this.Y.W(this.$i);e&&(this.props=ot({},e))}}save(){this.ki||this.Y.G(this.$i,this.props,this.Pi,this.Ti,this.Ii,this.R.debug)}remove(){this.Y.V(this.$i,!1),this.Y.V(this.$i,!0)}clear(){this.remove(),this.props={}}register_once(e,a,r){if(gt(e)){V(a)&&(a="None"),this.Pi=V(r)?this.Ci:r;var n=!1;if(Be(e,((o,i)=>{this.props.hasOwnProperty(i)&&this.props[i]!==a||(this.props[i]=o,n=!0)})),n)return this.save(),!0}return!1}register(e,a){if(gt(e)){this.Pi=V(a)?this.Ci:a;var r=!1;if(Be(e,((n,o)=>{e.hasOwnProperty(o)&&this.props[o]!==n&&(this.props[o]=n,r=!0)})),r)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.Ei){var e=iT(this.R.custom_campaign_params,this.R.mask_personal_data_properties,this.R.custom_personal_data_properties);Xs(Nb(e))||this.register(e),this.Ei=!0}}update_search_keyword(){var e;this.register((e=q?.referrer)?lT(e):{})}update_referrer_info(){var e;this.register_once({$referrer:uT(),$referring_domain:q!=null&&q.referrer&&((e=Qp(q.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[jx]||this.props[Gx]||this.register_once({[Zp]:cT(this.R.mask_personal_data_properties,this.R.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};Be([Gx,jx],(i=>{var s=this.props[i];s&&Be(s,(function(l,u){e["$initial_"+_x(u)]=l}))}));var a,r,n=this.props[Zp];if(n){var o=(a=dT(n),r={},Be(a,(function(i,s){r["$initial_"+_x(s)]=i})),r);ot(e,o)}return e}safe_merge(e){return Be(this.props,(function(a,r){r in e||(e[r]=a)})),e}update_config(e,a,r){if(this.Ci=this.Pi=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==a.persistence||!((i,s)=>{if(i.length!==s.length)return!1;var l=[...i].sort(),u=[...s].sort();return l.every(((c,d)=>c===u[d]))})(e.cookie_persisted_properties||[],a.cookie_persisted_properties||[])){var n=this.Si(e),o=this.props;this.clear(),this.Y=n,this.props=o,this.save()}}set_disabled(e){this.ki=e,this.ki?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ti&&(this.Ti=e,this.remove(),this.save())}set_secure(e){e!==this.Ii&&(this.Ii=e,this.remove(),this.save())}set_event_timer(e,a){var r=this.props[lc]||{};r[e]=a,this.props[lc]=r,this.save()}remove_event_timer(e){var a=(this.props[lc]||{})[e];return V(a)||(delete this.props[lc][e],this.save()),a}get_property(e){return this.props[e]}set_property(e,a){this.props[e]=a,this.save()}},uE=et("[Product Tours]"),gx="ph_product_tours",fb=class{constructor(e){this.Ri=null,this.Fi=null,this._instance=e}onRemoteConfig(e){this._instance.persistence&&this._instance.persistence.register({[FA]:!(e==null||!e.productTours)}),this.loadIfEnabled()}loadIfEnabled(){var e,a;this.Ri||(e=this._instance).config.disable_product_tours||(a=e.persistence)==null||!a.get_property(FA)||this.it((()=>this.Oi()))}it(e){var a,r;(a=Q.__PosthogExtensions__)!=null&&a.generateProductTours?e():(r=Q.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"product-tours",(n=>{n?uE.error("Could not load product tours script",n):e()}))}Oi(){var e;!this.Ri&&(e=Q.__PosthogExtensions__)!=null&&e.generateProductTours&&(this.Ri=Q.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,a){if(a===void 0&&(a=!1),!Ce(this.Fi)||a){var r=this._instance.persistence;if(r){var n=r.props[gx];if(Ce(n)&&!a)return this.Fi=n,void e(n,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:o=>{var i=o.statusCode;if(i!==200||!o.json){var s="Product Tours API could not be loaded, status: "+i;return uE.error(s),void e([],{isLoaded:!1,error:s})}var l=Ce(o.json.product_tours)?o.json.product_tours:[];this.Fi=l,r&&r.register({[gx]:l}),e(l,{isLoaded:!0})}})}else e(this.Fi,{isLoaded:!0})}getActiveProductTours(e){ge(this.Ri)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.Ri.getActiveProductTours(e)}showProductTour(e){var a;(a=this.Ri)==null||a.showTourById(e)}previewTour(e){this.Ri?this.Ri.previewTour(e):this.it((()=>{var a;this.Oi(),(a=this.Ri)==null||a.previewTour(e)}))}dismissProductTour(){var e;(e=this.Ri)==null||e.dismissTour("user_clicked_skip")}nextStep(){var e;(e=this.Ri)==null||e.nextStep()}previousStep(){var e;(e=this.Ri)==null||e.previousStep()}clearCache(){var e;this.Fi=null,(e=this._instance.persistence)==null||e.unregister(gx)}resetTour(e){var a;(a=this.Ri)==null||a.resetTour(e)}resetAllTours(){var e;(e=this.Ri)==null||e.resetAllTours()}cancelPendingTour(e){var a;(a=this.Ri)==null||a.cancelPendingTour(e)}},nc=(function(t){return t.Activation="events",t.Cancellation="cancelEvents",t})({}),L8=(function(t){return t.Button="button",t.Tab="tab",t.Selector="selector",t})({}),k8=(function(t){return t.TopLeft="top_left",t.TopRight="top_right",t.TopCenter="top_center",t.MiddleLeft="middle_left",t.MiddleRight="middle_right",t.MiddleCenter="middle_center",t.Left="left",t.Center="center",t.Right="right",t.NextToTrigger="next_to_trigger",t})({}),I8=(function(t){return t.Top="top",t.Left="left",t.Right="right",t.Bottom="bottom",t})({}),vx=(function(t){return t.Popover="popover",t.API="api",t.Widget="widget",t.ExternalSurvey="external_survey",t})({}),A8=(function(t){return t.Open="open",t.MultipleChoice="multiple_choice",t.SingleChoice="single_choice",t.Rating="rating",t.Link="link",t})({}),E8=(function(t){return t.NextQuestion="next_question",t.End="end",t.ResponseBased="response_based",t.SpecificQuestion="specific_question",t})({}),T8=(function(t){return t.Once="once",t.Recurring="recurring",t.Always="always",t})({}),fc=(function(t){return t.SHOWN="survey shown",t.DISMISSED="survey dismissed",t.SENT="survey sent",t.ABANDONED="survey abandoned",t})({}),yx=(function(t){return t.SURVEY_ID="$survey_id",t.SURVEY_NAME="$survey_name",t.SURVEY_RESPONSE="$survey_response",t.SURVEY_ITERATION="$survey_iteration",t.SURVEY_ITERATION_START_DATE="$survey_iteration_start_date",t.SURVEY_PARTIALLY_COMPLETED="$survey_partially_completed",t.SURVEY_SUBMISSION_ID="$survey_submission_id",t.SURVEY_QUESTIONS="$survey_questions",t.SURVEY_COMPLETED="$survey_completed",t.PRODUCT_TOUR_ID="$product_tour_id",t.SURVEY_LAST_SEEN_DATE="$survey_last_seen_date",t})({}),pb=(function(t){return t.Popover="popover",t.Inline="inline",t})({}),Oe=et("[Surveys]"),xT="seenSurvey_",a4=(t,e)=>{var a="$survey_"+e+"/"+t.id;return t.current_iteration&&t.current_iteration>0&&(a="$survey_"+e+"/"+t.id+"/"+t.current_iteration),a},cE=t=>((e,a)=>{var r=""+e+a.id;return a.current_iteration&&a.current_iteration>0&&(r=""+e+a.id+"_"+a.current_iteration),r})(xT,t),r4=[vx.Popover,vx.Widget,vx.API],n4={ignoreConditions:!1,ignoreDelay:!1,displayType:pb.Popover},_c=class{constructor(){this.Mi={},this.Mi={}}on(e,a){return this.Mi[e]||(this.Mi[e]=[]),this.Mi[e].push(a),()=>{this.Mi[e]=this.Mi[e].filter((r=>r!==a))}}emit(e,a){for(var r of this.Mi[e]||[])r(a);for(var n of this.Mi["*"]||[])n(e,a)}};function js(t,e,a){if(ge(t))return!1;switch(a){case"exact":return t===e;case"contains":var r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}var hb=class{constructor(e){this.Ai=new _c,this.ji=(a,r)=>this.Di(a,r)&&this.Li(a,r)&&this.Ni(a,r)&&this.Ui(a,r),this.Di=(a,r)=>r==null||!r.event||a?.event===r?.event,this._instance=e,this.zi=new Set,this.Hi=new Set}init(){var e;if(!V((e=this._instance)==null?void 0:e._addCaptureHook)){var a;(a=this._instance)==null||a._addCaptureHook(((r,n)=>{this.on(r,n)}))}}register(e){var a,r;if(!V((a=this._instance)==null?void 0:a._addCaptureHook)&&(e.forEach((i=>{var s,l;(s=this.Hi)==null||s.add(i),(l=i.steps)==null||l.forEach((u=>{var c;(c=this.zi)==null||c.add(u?.event||"")}))})),(r=this._instance)!=null&&r.autocapture)){var n,o=new Set;e.forEach((i=>{var s;(s=i.steps)==null||s.forEach((l=>{l!=null&&l.selector&&o.add(l?.selector)}))})),(n=this._instance)==null||n.autocapture.setElementSelectors(o)}}on(e,a){var r;a!=null&&e.length!=0&&(this.zi.has(e)||this.zi.has(a?.event))&&this.Hi&&((r=this.Hi)==null?void 0:r.size)>0&&this.Hi.forEach((n=>{this.Bi(a,n)&&this.Ai.emit("actionCaptured",n.name)}))}qi(e){this.onAction("actionCaptured",(a=>e(a)))}Bi(e,a){if(a?.steps==null)return!1;for(var r of a.steps)if(this.ji(e,r))return!0;return!1}onAction(e,a){return this.Ai.on(e,a)}Li(e,a){if(a!=null&&a.url){var r,n=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!n||typeof n!="string"||!js(n,a.url,a.url_matching||"contains"))return!1}return!0}Ni(e,a){return!!this.Wi(e,a)&&!!this.Gi(e,a)&&!!this.Vi(e,a)}Wi(e,a){var r;if(a==null||!a.href)return!0;var n=this.Ji(e);if(n.length>0)return n.some((s=>js(s.href,a.href,a.href_matching||"exact")));var o,i=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!i&&js((o=i.match(/(?::|")href="(.*?)"/))?o[1]:"",a.href,a.href_matching||"exact")}Gi(e,a){var r;if(a==null||!a.text)return!0;var n=this.Ji(e);if(n.length>0)return n.some((u=>js(u.text,a.text,a.text_matching||"exact")||js(u.$el_text,a.text,a.text_matching||"exact")));var o,i,s,l=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(o=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!ge(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),i=a.text,s=a.text_matching||"exact",o.some((u=>js(u,i,s))))}Vi(e,a){var r,n;if(a==null||!a.selector)return!0;var o=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(o!=null&&o.includes(a.selector))return!0;var i=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";if(a.selector_regex&&i)try{return new RegExp(a.selector_regex).test(i)}catch{return!1}return!1}Ji(e){var a;return(e==null||(a=e.properties)==null?void 0:a.$elements)==null?[]:e?.properties.$elements}Ui(e,a){return a==null||!a.properties||a.properties.length===0||yT(a.properties.reduce(((r,n)=>{var o=Ce(n.value)?n.value.map(String):n.value!=null?[String(n.value)]:[];return r[n.key]={values:o,operator:n.operator||"exact"},r}),{}),e?.properties)}},mb=class{constructor(e){this._instance=e,this.Ki=new Map,this.Yi=new Map,this.Xi=new Map}Qi(e,a){return!!e&&yT(e.propertyFilters,a?.properties)}Zi(e,a){var r=new Map;return e.forEach((n=>{var o;(o=n.conditions)==null||(o=o[a])==null||(o=o.values)==null||o.forEach((i=>{if(i!=null&&i.name){var s=r.get(i.name)||[];s.push(n.id),r.set(i.name,s)}}))})),r}te(e,a,r){var n=(r===nc.Activation?this.Ki:this.Yi).get(e),o=[];return this.ie((i=>{o=i.filter((s=>n?.includes(s.id)))})),o.filter((i=>{var s,l=(s=i.conditions)==null||(s=s[r])==null||(s=s.values)==null?void 0:s.find((u=>u.name===e));return this.Qi(l,a)}))}register(e){var a;V((a=this._instance)==null?void 0:a._addCaptureHook)||(this.ee(e),this.re(e))}re(e){var a=e.filter((r=>{var n,o;return((n=r.conditions)==null?void 0:n.actions)&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0}));a.length!==0&&(this.se==null&&(this.se=new hb(this._instance),this.se.init(),this.se.qi((r=>{this.onAction(r)}))),a.forEach((r=>{var n,o,i,s,l;r.conditions&&(n=r.conditions)!=null&&n.actions&&(o=r.conditions)!=null&&(o=o.actions)!=null&&o.values&&((i=r.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0&&((s=this.se)==null||s.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.Xi.get(u.name);c&&c.push(r.id),this.Xi.set(u.name,c||[r.id])}})))})))}ee(e){var a,r=e.filter((o=>{var i,s;return((i=o.conditions)==null?void 0:i.events)&&((s=o.conditions)==null||(s=s.events)==null||(s=s.values)==null?void 0:s.length)>0})),n=e.filter((o=>{var i,s;return((i=o.conditions)==null?void 0:i.cancelEvents)&&((s=o.conditions)==null||(s=s.cancelEvents)==null||(s=s.values)==null?void 0:s.length)>0}));(r.length!==0||n.length!==0)&&((a=this._instance)==null||a._addCaptureHook(((o,i)=>{this.onEvent(o,i)})),this.Ki=this.Zi(e,nc.Activation),this.Yi=this.Zi(e,nc.Cancellation))}onEvent(e,a){var r,n=this.ne(),o=this.oe(),i=this.ae(),s=((r=this._instance)==null||(r=r.persistence)==null?void 0:r.props[o])||[];if(i===e&&a&&s.length>0){var l,u;n.info("event matched, removing item from activated items",{event:e,eventPayload:a,existingActivatedItems:s});var c=(a==null||(l=a.properties)==null?void 0:l.$survey_id)||(a==null||(u=a.properties)==null?void 0:u.$product_tour_id);if(c){var d=s.indexOf(c);d>=0&&(s.splice(d,1),this.le(s))}}else{if(this.Yi.has(e)){var f=this.te(e,a,nc.Cancellation);f.length>0&&(n.info("cancel event matched, cancelling items",{event:e,itemsToCancel:f.map((S=>S.id))}),f.forEach((S=>{var x=s.indexOf(S.id);x>=0&&s.splice(x,1),this.ue(S.id)})),this.le(s))}if(this.Ki.has(e)){n.info("event name matched",{event:e,eventPayload:a,items:this.Ki.get(e)});var h=this.te(e,a,nc.Activation);this.le(s.concat(h.map((S=>S.id))||[]))}}}onAction(e){var a,r=this.oe(),n=((a=this._instance)==null||(a=a.persistence)==null?void 0:a.props[r])||[];this.Xi.has(e)&&this.le(n.concat(this.Xi.get(e)||[]))}le(e){var a,r=this.ne(),n=this.oe(),o=[...new Set(e)].filter((i=>!this.he(i)));r.info("updating activated items",{activatedItems:o}),(a=this._instance)==null||(a=a.persistence)==null||a.register({[n]:o})}getActivatedIds(){var e,a=this.oe(),r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[a];return r||[]}getEventToItemsMap(){return this.Ki}de(){return this.se}},gb=class extends mb{constructor(e){super(e)}oe(){return"$surveys_activated"}ae(){return fc.SHOWN}ie(e){var a;(a=this._instance)==null||a.getSurveys(e)}ue(e){var a;(a=this._instance)==null||a.cancelPendingSurvey(e)}ne(){return Oe}he(){return!1}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}},vb=class{constructor(e){this.ve=void 0,this._surveyManager=null,this.ce=!1,this.fe=[],this.pe=null,this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var a=e.surveys;if(ge(a))return Oe.warn("Flags not loaded yet. Not loading surveys.");var r=Ce(a);this.ve=r?a.length>0:a,Oe.info("flags response received, isSurveysEnabled: "+this.ve),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],a=0;a<localStorage.length;a++){var r=localStorage.key(a);(r!=null&&r.startsWith(xT)||r!=null&&r.startsWith("inProgressSurvey_"))&&e.push(r)}e.forEach((n=>localStorage.removeItem(n)))}loadIfEnabled(){if(!this._surveyManager)if(this.ce)Oe.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)Oe.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())Oe.info("Not loading surveys in cookieless mode without consent.");else{var e=Q?.__PosthogExtensions__;if(e){if(!V(this.ve)||this._instance.config.advanced_enable_surveys){var a=this.ve||this._instance.config.advanced_enable_surveys;this.ce=!0;try{var r=e.generateSurveys;if(r)return void this.ge(r,a);var n=e.loadExternalDependency;if(!n)return void this._e("PostHog loadExternalDependency extension not found.");n(this._instance,"surveys",(o=>{o||!e.generateSurveys?this._e("Could not load surveys script",o):this.ge(e.generateSurveys,a)}))}catch(o){throw this._e("Error initializing surveys",o),o}finally{this.ce=!1}}}else Oe.error("PostHog Extensions not found.")}}ge(e,a){this._surveyManager=e(this._instance,a),this._surveyEventReceiver=new gb(this._instance),Oe.info("Surveys loaded successfully"),this.me({isLoaded:!0})}_e(e,a){Oe.error(e,a),this.me({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.fe.push(e),this._surveyManager&&this.me({isLoaded:!0}),()=>{this.fe=this.fe.filter((a=>a!==e))}}getSurveys(e,a){if(a===void 0&&(a=!1),this._instance.config.disable_surveys)return Oe.info("Disabled. Not loading surveys."),e([]);var r,n=this._instance.get_property(qx);if(n&&!a)return e(n,{isLoaded:!0});typeof Promise<"u"&&this.pe?this.pe.then((o=>{var{surveys:i,context:s}=o;return e(i,s)})):(typeof Promise<"u"&&(this.pe=new Promise((o=>{r=o}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:o=>{var i;this.pe=null;var s=o.statusCode;if(s!==200||!o.json){var l="Surveys API could not be loaded, status: "+s;Oe.error(l);var u={isLoaded:!1,error:l};return e([],u),void(r==null||r({surveys:[],context:u}))}var c,d=o.json.surveys||[],f=d.filter((S=>(function(x){return!(!x.start_date||x.end_date)})(S)&&((function(x){var b;return!((b=x.conditions)==null||(b=b.events)==null||(b=b.values)==null||!b.length)})(S)||(function(x){var b;return!((b=x.conditions)==null||(b=b.actions)==null||(b=b.values)==null||!b.length)})(S))));f.length>0&&((c=this._surveyEventReceiver)==null||c.register(f)),(i=this._instance.persistence)==null||i.register({[qx]:d});var h={isLoaded:!0};e(d,h),r?.({surveys:d,context:h})}}))}me(e){for(var a of this.fe)try{if(!e.isLoaded)return a([],e);this.getSurveys(a)}catch(r){Oe.error("Error in survey callback",r)}}getActiveMatchingSurveys(e,a){if(a===void 0&&(a=!1),!ge(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,a);Oe.warn("init was not called")}be(e){var a=null;return this.getSurveys((r=>{var n;a=(n=r.find((o=>o.id===e)))!==null&&n!==void 0?n:null})),a}ye(e){if(ge(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var a=typeof e=="string"?this.be(e):e;return a?this._surveyManager.checkSurveyEligibility(a):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(ge(this._surveyManager))return Oe.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var a=this.ye(e);return{visible:a.eligible,disabledReason:a.reason}}canRenderSurveyAsync(e,a){return ge(this._surveyManager)?(Oe.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise((r=>{this.getSurveys((n=>{var o,i=(o=n.find((l=>l.id===e)))!==null&&o!==void 0?o:null;if(i){var s=this.ye(i);r({visible:s.eligible,disabledReason:s.reason})}else r({visible:!1,disabledReason:"Survey not found"})}),a)}))}renderSurvey(e,a,r){var n;if(ge(this._surveyManager))Oe.warn("init was not called");else{var o=typeof e=="string"?this.be(e):e;if(o!=null&&o.id)if(r4.includes(o.type)){var i=q?.querySelector(a);if(i)return(n=o.appearance)!=null&&n.surveyPopupDelaySeconds?(Oe.info("Rendering survey "+o.id+" with delay of "+o.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var s,l;Oe.info("Rendering survey "+o.id+" with delay of "+((s=o.appearance)==null?void 0:s.surveyPopupDelaySeconds)+" seconds"),(l=this._surveyManager)==null||l.renderSurvey(o,i,r),Oe.info("Survey "+o.id+" rendered")}),1e3*o.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(o,i,r);Oe.warn("Survey element not found")}else Oe.warn("Surveys of type "+o.type+" cannot be rendered in the app");else Oe.warn("Survey not found")}}displaySurvey(e,a){var r;if(ge(this._surveyManager))Oe.warn("init was not called");else{var n=this.be(e);if(n){var o=n;if((r=n.appearance)!=null&&r.surveyPopupDelaySeconds&&a.ignoreDelay&&(o=j({},n,{appearance:j({},n.appearance,{surveyPopupDelaySeconds:0})})),a.displayType!==pb.Popover&&a.initialResponses&&Oe.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),a.ignoreConditions===!1){var i=this.canRenderSurvey(n);if(!i.visible)return void Oe.warn("Survey is not eligible to be displayed: ",i.disabledReason)}a.displayType!==pb.Inline?this._surveyManager.handlePopoverSurvey(o,a):this.renderSurvey(o,a.selector,a.properties)}else Oe.warn("Survey not found")}}cancelPendingSurvey(e){ge(this._surveyManager)?Oe.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;(e=this._surveyManager)==null||e.handlePageUnload()}},dn=et("[Conversations]"),yb=class{constructor(e){this.we=void 0,this._conversationsManager=null,this.xe=!1,this.Ee=null,this._instance=e}onRemoteConfig(e){if(!this._instance.config.disable_conversations){var a=e.conversations;ge(a)||(vn(a)?this.we=a:(this.we=a.enabled,this.Ee=a),this.loadIfEnabled())}}reset(){var e;(e=this._conversationsManager)==null||e.reset(),this._conversationsManager=null,this.we=void 0,this.Ee=null}loadIfEnabled(){if(!this._conversationsManager&&!this.xe&&!(this._instance.config.disable_conversations||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=Q?.__PosthogExtensions__;if(e&&!V(this.we)&&this.we)if(this.Ee&&this.Ee.token){this.xe=!0;try{var a=e.initConversations;if(a)return this.$e(a),void(this.xe=!1);var r=e.loadExternalDependency;if(!r)return void this.Se("PostHog loadExternalDependency extension not found.");r(this._instance,"conversations",(n=>{n||!e.initConversations?this.Se("Could not load conversations script",n):this.$e(e.initConversations),this.xe=!1}))}catch(n){this.Se("Error initializing conversations",n),this.xe=!1}}else dn.error("Conversations enabled but missing token in remote config.")}}$e(e){if(this.Ee)try{this._conversationsManager=e(this.Ee,this._instance),dn.info("Conversations loaded successfully")}catch(a){this.Se("Error completing conversations initialization",a)}else dn.error("Cannot complete initialization: remote config is null")}Se(e,a){dn.error(e,a),this._conversationsManager=null,this.xe=!1}show(){this._conversationsManager?this._conversationsManager.show():dn.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.we===!0&&!cr(this._conversationsManager)}isVisible(){var e,a;return(e=(a=this._conversationsManager)==null?void 0:a.isVisible())!==null&&e!==void 0&&e}sendMessage(e,a,r){var n=this;return Zs((function*(){return n._conversationsManager?n._conversationsManager.sendMessage(e,a,r):(dn.warn("Conversations not available yet."),null)}))()}getMessages(e,a){var r=this;return Zs((function*(){return r._conversationsManager?r._conversationsManager.getMessages(e,a):(dn.warn("Conversations not available yet."),null)}))()}markAsRead(e){var a=this;return Zs((function*(){return a._conversationsManager?a._conversationsManager.markAsRead(e):(dn.warn("Conversations not available yet."),null)}))()}getTickets(e){var a=this;return Zs((function*(){return a._conversationsManager?a._conversationsManager.getTickets(e):(dn.warn("Conversations not available yet."),null)}))()}getCurrentTicketId(){var e,a;return(e=(a=this._conversationsManager)==null?void 0:a.getCurrentTicketId())!==null&&e!==void 0?e:null}getWidgetSessionId(){var e,a;return(e=(a=this._conversationsManager)==null?void 0:a.getWidgetSessionId())!==null&&e!==void 0?e:null}},xb=class{constructor(e){var a;this.ke=!1,this.Pe=!1,this._instance=e,this._instance&&(a=this._instance.config.logs)!=null&&a.captureConsoleLogs&&(this.ke=!0)}onRemoteConfig(e){var a,r=(a=e.logs)==null?void 0:a.captureConsoleLogs;!ge(r)&&r&&(this.ke=!0,this.loadIfEnabled())}reset(){}loadIfEnabled(){if(this.ke&&!this.Pe){var e=et("[logs]"),a=Q?.__PosthogExtensions__;if(a){var r=a.loadExternalDependency;r?r(this._instance,"logs",(n=>{var o;n||(o=a.logs)==null||!o.initializeLogs?e.error("Could not load logs script",n):(a.logs.initializeLogs(this._instance),this.Pe=!0)})):e.error("PostHog loadExternalDependency extension not found.")}else e.error("PostHog Extensions not found.")}}},dE=et("[RateLimiter]"),bb=class{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=a=>{var r=a.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach((n=>{dE.info((n||"events")+" is quota limited."),this.serverLimits[n]=new Date().getTime()+6e4}))}catch(n){return void dE.warn('could not rate limit - continuing. Error: "'+n?.message+'"',{text:r})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var a,r,n;e===void 0&&(e=!1);var{captureEventsBurstLimit:o,captureEventsPerSecond:i}=this,s=new Date().getTime(),l=(a=(r=this.instance.persistence)==null?void 0:r.get_property($x))!==null&&a!==void 0?a:{tokens:o,last:s};l.tokens+=(s-l.last)/1e3*i,l.last=s,l.tokens>o&&(l.tokens=o);var u=l.tokens<1;return u||e||(l.tokens=Math.max(0,l.tokens-1)),!u||this.lastEventRateLimited||e||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+i+" events per second and "+o+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=u,(n=this.instance.persistence)==null||n.set_property($x,l),{isRateLimited:u,remainingTokens:l.tokens}}isServerRateLimited(e){var a=this.serverLimits[e||"events"]||!1;return a!==!1&&new Date().getTime()<a}},Ci=et("[RemoteConfig]"),Sb=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=Q._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.config}Te(e){var a,r;(a=Q.__PosthogExtensions__)!=null&&a.loadExternalDependency?(r=Q.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"remote-config",(()=>e(this.remoteConfig))):(Ci.error("PostHog Extensions not found. Cannot load remote config."),e())}Ie(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:a=>{e(a.json)}})}load(){try{if(this.remoteConfig)return Ci.info("Using preloaded remote config",this.remoteConfig),void this.yi(this.remoteConfig);if(this._instance.M())return void Ci.warn("Remote config is disabled. Falling back to local config.");this.Te((e=>{if(!e)return Ci.info("No config found after loading remote JS config. Falling back to JSON."),void this.Ie((a=>{this.yi(a)}));this.yi(e)}))}catch(e){Ci.error("Error loading remote config",e)}}yi(e){e?this._instance.config.__preview_remote_config?(this._instance.yi(e),e.hasFeatureFlags!==!1&&this._instance.featureFlags.ensureFlagsLoaded()):Ci.info("__preview_remote_config is disabled. Logging config instead",e):Ci.error("Failed to fetch remote config from PostHog.")}},_b=3e3,Cb=class{constructor(e,a){this.Ce=!0,this.Re=[],this.Fe=Ir(a?.flush_interval_ms||_b,250,5e3,$.createLogger("flush interval"),_b),this.Oe=e}enqueue(e){this.Re.push(e),this.Me||this.Ae()}unload(){this.je();var e=this.Re.length>0?this.De():{},a=Object.values(e);[...a.filter((r=>r.url.indexOf("/e")===0)),...a.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.Oe(j({},r,{transport:"sendBeacon"}))}))}enable(){this.Ce=!1,this.Ae()}Ae(){var e=this;this.Ce||(this.Me=setTimeout((()=>{if(this.je(),this.Re.length>0){var a=this.De(),r=function(){var o=a[n],i=new Date().getTime();o.data&&Ce(o.data)&&Be(o.data,(s=>{s.offset=Math.abs(s.timestamp-i),delete s.timestamp})),e.Oe(o)};for(var n in a)r()}}),this.Fe))}je(){clearTimeout(this.Me),this.Me=void 0}De(){var e={};return Be(this.Re,(a=>{var r,n=a,o=(n?n.batchKey:null)||n.url;V(e[o])&&(e[o]=j({},n,{data:[]})),(r=e[o].data)==null||r.push(n.data)})),this.Re=[],e}},o4=["retriesPerformedSoFar"],wb=class{constructor(e){this.Le=!1,this.Ne=3e3,this.Re=[],this._instance=e,this.Re=[],this.Ue=!0,!V(T)&&"onLine"in T.navigator&&(this.Ue=T.navigator.onLine,this.ze=()=>{this.Ue=!0,this.Lt()},this.He=()=>{this.Ue=!1},ft(T,"online",this.ze),ft(T,"offline",this.He))}get length(){return this.Re.length}retriableRequest(e){var{retriesPerformedSoFar:a}=e,r=vE(e,o4);Gs(a)&&(r.url=oh(r.url,{retry_count:a})),this._instance._send_request(j({},r,{callback:n=>{n.statusCode!==200&&(n.statusCode<400||n.statusCode>=500)&&(a??0)<10?this.Be(j({retriesPerformedSoFar:a},r)):r.callback==null||r.callback(n)}}))}Be(e){var a=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=a+1;var r=(function(i){var s=3e3*Math.pow(2,i),l=s/2,u=Math.min(18e5,s),c=(Math.random()-.5)*(u-l);return Math.ceil(u+c)})(a),n=Date.now()+r;this.Re.push({retryAt:n,requestOptions:e});var o="Enqueued failed request for retry in "+r;navigator.onLine||(o+=" (Browser is offline)"),$.warn(o),this.Le||(this.Le=!0,this.qe())}qe(){if(this.We&&clearTimeout(this.We),this.Re.length===0)return this.Le=!1,void(this.We=void 0);this.We=setTimeout((()=>{this.Ue&&this.Re.length>0&&this.Lt(),this.qe()}),this.Ne)}Lt(){var e=Date.now(),a=[],r=this.Re.filter((o=>o.retryAt<e||(a.push(o),!1)));if(this.Re=a,r.length>0)for(var{requestOptions:n}of r)this.retriableRequest(n)}unload(){for(var{requestOptions:e}of(this.We&&(clearTimeout(this.We),this.We=void 0),this.Le=!1,V(T)||(this.ze&&(T.removeEventListener("online",this.ze),this.ze=void 0),this.He&&(T.removeEventListener("offline",this.He),this.He=void 0)),this.Re))try{this._instance._send_request(j({},e,{transport:"sendBeacon"}))}catch(a){$.error(a)}this.Re=[]}},Lb=class{constructor(e){this.Ge=()=>{var a,r,n,o;this.Ve||(this.Ve={});var i=this.scrollElement(),s=this.scrollY(),l=i?Math.max(0,i.scrollHeight-i.clientHeight):0,u=s+(i?.clientHeight||0),c=i?.scrollHeight||0;this.Ve.lastScrollY=Math.ceil(s),this.Ve.maxScrollY=Math.max(s,(a=this.Ve.maxScrollY)!==null&&a!==void 0?a:0),this.Ve.maxScrollHeight=Math.max(l,(r=this.Ve.maxScrollHeight)!==null&&r!==void 0?r:0),this.Ve.lastContentY=u,this.Ve.maxContentY=Math.max(u,(n=this.Ve.maxContentY)!==null&&n!==void 0?n:0),this.Ve.maxContentHeight=Math.max(c,(o=this.Ve.maxContentHeight)!==null&&o!==void 0?o:0)},this._instance=e}getContext(){return this.Ve}resetContext(){var e=this.Ve;return setTimeout(this.Ge,0),e}startMeasuringScrollPosition(){ft(T,"scroll",this.Ge,{capture:!0}),ft(T,"scrollend",this.Ge,{capture:!0}),ft(T,"resize",this.Ge)}scrollElement(){if(!this._instance.config.scroll_root_selector)return T?.document.documentElement;var e=Ce(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var a of e){var r=T?.document.querySelector(a);if(r)return r}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return T&&(T.scrollY||T.pageYOffset||T.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return T&&(T.scrollX||T.pageXOffset||T.document.documentElement.scrollLeft)||0}},i4=t=>cT(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties),sh=class{constructor(e,a,r,n){this.Je=o=>{var i=this.Ke();if(!i||i.sessionId!==o){var s={sessionId:o,props:this.Ye(this._instance)};this.Xe.register({[Vx]:s})}},this._instance=e,this.Qe=a,this.Xe=r,this.Ye=n||i4,this.Qe.onSessionId(this.Je)}Ke(){return this.Xe.props[Vx]}getSetOnceProps(){var e,a=(e=this.Ke())==null?void 0:e.props;return a?"r"in a?dT(a):{$referring_domain:a.referringDomain,$pathname:a.initialPathName,utm_source:a.utm_source,utm_campaign:a.utm_campaign,utm_medium:a.utm_medium,utm_content:a.utm_content,utm_term:a.utm_term}:{}}getSessionProps(){var e={};return Be(Nb(this.getSetOnceProps()),((a,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+_x(r)]=a})),e}},xx=et("[SessionId]"),lh=class{on(e,a){return this.Ze.on(e,a)}constructor(e,a,r){var n;if(this.tr=[],this.ir=void 0,this.Ze=new _c,this.er=(c,d)=>!(!Gs(c)||!Gs(d))&&Math.abs(c-d)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.R=e.config,this.Xe=e.persistence,this.rr=void 0,this.sr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.nr=a||So,this.ar=r||So;var o=this.R.persistence_name||this.R.token,i=this.R.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*Ir(i,60,36e3,xx.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.lr(),this.ur="ph_"+o+"_window_id",this.hr="ph_"+o+"_primary_window_exists",this.dr()){var s=Dt.W(this.ur),l=Dt.W(this.hr);s&&!l?this.rr=s:Dt.V(this.ur),Dt.G(this.hr,!0)}if((n=this.R.bootstrap)!=null&&n.sessionID)try{var u=(c=>{var d=c.replace(/-/g,"");if(d.length!==32)throw new Error("Not a valid UUID");if(d[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(d.substring(0,12),16)})(this.R.bootstrap.sessionID);this.vr(this.R.bootstrap.sessionID,new Date().getTime(),u)}catch(c){xx.error("Invalid sessionID in bootstrap",c)}this.cr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return V(this.tr)&&(this.tr=[]),this.tr.push(e),this.sr&&e(this.sr,this.rr),()=>{this.tr=this.tr.filter((a=>a!==e))}}dr(){return this.R.persistence!=="memory"&&!this.Xe.ki&&Dt.H()}pr(e){e!==this.rr&&(this.rr=e,this.dr()&&Dt.G(this.ur,e))}gr(){return this.rr?this.rr:this.dr()?Dt.W(this.ur):null}vr(e,a,r){e===this.sr&&a===this._sessionActivityTimestamp&&r===this._sessionStartTimestamp||(this._sessionStartTimestamp=r,this._sessionActivityTimestamp=a,this.sr=e,this.Xe.register({[Gp]:[a,e,r]}))}_r(){var e=this.Xe.props[Gp];return Ce(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.vr(null,null,null)}destroy(){clearTimeout(this.mr),this.mr=void 0,this.ir&&T&&(T.removeEventListener("beforeunload",this.ir,{capture:!1}),this.ir=void 0),this.tr=[]}cr(){this.ir=()=>{this.dr()&&Dt.V(this.hr)},ft(T,"beforeunload",this.ir,{capture:!1})}checkAndGetSessionAndWindowId(e,a){if(e===void 0&&(e=!1),a===void 0&&(a=null),this.R.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=a||new Date().getTime(),[n,o,i]=this._r(),s=this.gr(),l=Gs(i)&&Math.abs(r-i)>864e5,u=!1,c=!o,d=!c&&!e&&this.er(r,n);c||d||l?(o=this.nr(),s=this.ar(),xx.info("new session ID generated",{sessionId:o,windowId:s,changeReason:{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}}),i=r,u=!0):s||(s=this.ar(),u=!0);var f=Gs(n)&&e&&!l?n:r,h=Gs(i)?i:new Date().getTime();return this.pr(s),this.vr(o,f,h),e||this.lr(),u&&this.tr.forEach((S=>S(o,s,u?{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}:void 0))),{sessionId:o,windowId:s,sessionStartTimestamp:h,changeReason:u?{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:n}}lr(){clearTimeout(this.mr),this.mr=setTimeout((()=>{var[e]=this._r();if(this.er(new Date().getTime(),e)){var a=this.sr;this.resetSessionId(),this.Ze.emit("forcedIdleReset",{idleSessionId:a})}}),1.1*this.sessionTimeoutMs)}},s4=["$set_once","$set"],xo=et("[SiteApps]"),kb=class{constructor(e){this._instance=e,this.br=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}yr(e,a){if(a){var r=this.globalsForEvent(a);this.br.push(r),this.br.length>1e3&&(this.br=this.br.slice(10))}}get siteAppLoaders(){var e;return(e=Q._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance._addCaptureHook(this.yr.bind(this));this.wr=()=>{e(),this.br=[],this.wr=void 0}}}globalsForEvent(e){var a,r,n,o,i,s,l;if(!e)throw new Error("Event payload is required");var u={},c=this._instance.get_property("$groups")||[],d=this._instance.get_property("$stored_group_properties")||{};for(var[f,h]of Object.entries(d))u[f]={id:c[f],type:f,properties:h};var{$set_once:S,$set:x}=e;return{event:j({},vE(e,s4),{properties:j({},e.properties,x?{$set:j({},(a=(r=e.properties)==null?void 0:r.$set)!==null&&a!==void 0?a:{},x)}:{},S?{$set_once:j({},(n=(o=e.properties)==null?void 0:o.$set_once)!==null&&n!==void 0?n:{},S)}:{}),elements_chain:(i=(s=e.properties)==null?void 0:s.$elements_chain)!==null&&i!==void 0?i:"",distinct_id:(l=e.properties)==null?void 0:l.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:u}}setupSiteApp(e){var a=this.apps[e.id],r=()=>{var s;!a.errored&&this.br.length&&(xo.info("Processing "+this.br.length+" events for site app with id "+e.id),this.br.forEach((l=>a.processEvent==null?void 0:a.processEvent(l))),a.processedBuffer=!0),Object.values(this.apps).every((l=>l.processedBuffer||l.errored))&&((s=this.wr)==null||s.call(this))},n=!1,o=s=>{a.errored=!s,a.loaded=!0,xo.info("Site app with id "+e.id+" "+(s?"loaded":"errored")),n&&r()};try{var{processEvent:i}=e.init({posthog:this._instance,callback:s=>{o(s)}});i&&(a.processEvent=i),n=!0}catch(s){xo.error("Error while initializing PostHog app with config id "+e.id,s),o(!1)}if(n&&a.loaded)try{r()}catch(s){xo.error("Error while processing buffered events PostHog app with config id "+e.id,s),a.errored=!0}}Er(){var e=this.siteAppLoaders||[];for(var a of e)this.apps[a.id]={id:a.id,loaded:!1,errored:!1,processedBuffer:!1};for(var r of e)this.setupSiteApp(r)}$r(e){if(Object.keys(this.apps).length!==0){var a=this.globalsForEvent(e);for(var r of Object.values(this.apps))try{r.processEvent==null||r.processEvent(a)}catch(n){xo.error("Error while processing event "+e.event+" for site app "+r.id,n)}}}onRemoteConfig(e){var a,r,n,o=this;if((a=this.siteAppLoaders)!=null&&a.length)return this.isEnabled?(this.Er(),void this._instance.on("eventCaptured",(u=>this.$r(u)))):void xo.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((r=this.wr)==null||r.call(this),(n=e.siteApps)!=null&&n.length)if(this.isEnabled){var i=function(u){var c;Q["__$$ph_site_app_"+u]=o._instance,(c=Q.__PosthogExtensions__)==null||c.loadSiteApp==null||c.loadSiteApp(o._instance,l,(d=>{if(d)return xo.error("Error while initializing PostHog app with config id "+u,d)}))};for(var{id:s,url:l}of e.siteApps)i(s)}else xo.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}},bT=function(t,e){if(!t)return!1;var a=t.userAgent;if(a&&LA(a,e))return!0;try{var r=t?.userAgentData;if(r!=null&&r.brands&&r.brands.some((n=>LA(n?.brand,e))))return!0}catch{}return!!t.webdriver},pc=(function(t){return t.US="us",t.EU="eu",t.CUSTOM="custom",t})({}),fE="i.posthog.com",Ib=class{constructor(e){this.Sr={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,a=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return a||(a=this.apiHost.replace("."+fE,".posthog.com")),a==="https://app.posthog.com"?"https://us.posthog.com":a}get region(){return this.Sr[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Sr[this.apiHost]=pc.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Sr[this.apiHost]=pc.EU:this.Sr[this.apiHost]=pc.CUSTOM),this.Sr[this.apiHost]}endpointFor(e,a){if(a===void 0&&(a=""),a&&(a=a[0]==="/"?a:"/"+a),e==="ui")return this.uiHost+a;if(e==="flags")return this.flagsApiHost+a;if(this.region===pc.CUSTOM)return this.apiHost+a;var r=fE+a;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}},l4={icontains:(t,e)=>!!T&&e.href.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>!!T&&e.href.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>!!T&&ih(e.href,t),not_regex:(t,e)=>!!T&&!ih(e.href,t),exact:(t,e)=>e.href===t,is_not:(t,e)=>e.href!==t},Ab=class t{constructor(e){var a=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),a.getWebExperiments((n=>{t.kr("retrieved web experiments from the server"),a.Pr=new Map,n.forEach((o=>{if(o.feature_flag_key){var i;a.Pr&&(t.kr("setting flag key ",o.feature_flag_key," to web experiment ",o),(i=a.Pr)==null||i.set(o.feature_flag_key,o));var s=a._instance.getFeatureFlag(o.feature_flag_key);vt(s)&&o.variants[s]&&a.Tr(o.name,s,o.variants[s].transforms)}else if(o.variants)for(var l in o.variants){var u=o.variants[l];t.Ir(u)&&a.Tr(o.name,l,u.transforms)}}))}),r)},this._instance=e,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}onFeatureFlags(e){if(this._is_bot())t.kr("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(ge(this.Pr))return this.Pr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();t.kr("applying feature flags",e),e.forEach((a=>{var r;if(this.Pr&&(r=this.Pr)!=null&&r.has(a)){var n,o=this._instance.getFeatureFlag(a),i=(n=this.Pr)==null?void 0:n.get(a);o&&i!=null&&i.variants[o]&&this.Tr(i.name,o,i.variants[o].transforms)}}))}}previewWebExperiment(){var e=t.getWindowLocation();if(e!=null&&e.search){var a=Jp(e?.search,"__experiment_id"),r=Jp(e?.search,"__experiment_variant");a&&r&&(t.kr("previewing web experiments "+a+" && "+r),this.getWebExperiments((n=>{this.Cr(parseInt(a),r,n)}),!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,a,r){if(this._instance.config.disable_web_experiments&&!r)return e([]);var n=this._instance.get_property("$web_experiments");if(n&&!a)return e(n);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:o=>{if(o.statusCode!==200||!o.json)return e([]);var i=o.json.experiments||[];return e(i)}})}Cr(e,a,r){var n=r.filter((o=>o.id===e));n&&n.length>0&&(t.kr("Previewing web experiment ["+n[0].name+"] with variant ["+a+"]"),this.Tr(n[0].name,a,n[0].variants[a].transforms))}static Ir(e){return!ge(e.conditions)&&t.Rr(e)&&t.Fr(e)}static Rr(e){var a;if(ge(e.conditions)||ge((a=e.conditions)==null?void 0:a.url))return!0;var r,n,o,i=t.getWindowLocation();return!!i&&((r=e.conditions)==null||!r.url||l4[(n=(o=e.conditions)==null?void 0:o.urlMatchType)!==null&&n!==void 0?n:"icontains"](e.conditions.url,i))}static getWindowLocation(){return T?.location}static Fr(e){var a;if(ge(e.conditions)||ge((a=e.conditions)==null?void 0:a.utm))return!0;var r=iT();if(r.utm_source){var n,o,i,s,l,u,c,d,f=(n=e.conditions)==null||(n=n.utm)==null||!n.utm_campaign||((o=e.conditions)==null||(o=o.utm)==null?void 0:o.utm_campaign)==r.utm_campaign,h=(i=e.conditions)==null||(i=i.utm)==null||!i.utm_source||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_source)==r.utm_source,S=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,x=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==r.utm_term;return f&&S&&x&&h}return!1}static kr(e){for(var a=arguments.length,r=new Array(a>1?a-1:0),n=1;n<a;n++)r[n-1]=arguments[n];$.info("[WebExperiments] "+e,r)}Tr(e,a,r){this._is_bot()?t.kr("Refusing to render web experiment since the viewer is a likely bot"):a!=="control"?r.forEach((n=>{if(n.selector){var o;t.kr("applying transform of variant "+a+" for experiment "+e+" ",n);var i=(o=document)==null?void 0:o.querySelectorAll(n.selector);i?.forEach((s=>{var l=s;n.html&&(l.innerHTML=n.html),n.css&&l.setAttribute("style",n.css)}))}})):t.kr("Control variants leave the page unmodified.")}_is_bot(){return ka&&this._instance?bT(ka,this._instance.config.custom_blocked_useragents):void 0}},u4=et("[PostHog ExternalIntegrations]"),c4={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},Eb=class{constructor(e){this._instance=e}it(e,a){var r;(r=Q.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,(n=>{if(n)return u4.error("failed to load script",n);a()}))}startIfEnabledOrStop(){var e=this,a=function(i){var s,l,u;!n||(s=Q.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[i]||e.it(c4[i],(()=>{var c;(c=Q.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[i])==null||c.start(e._instance)})),!n&&(l=Q.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[i]&&((u=Q.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[i])==null||u.stop())};for(var[r,n]of Object.entries((o=this._instance.config.integrations)!==null&&o!==void 0?o:{})){var o;a(r)}}},Tb="[SessionRecording]",oc=et(Tb),uh=class{get started(){var e;return!((e=this.Or)==null||!e.isStarted)}get status(){return this.Or?this.Or.status:this.Mr&&!this.Ar?"disabled":"lazy_loading"}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.Mr=!1,this.jr=void 0,this._instance=e,!this._instance.sessionManager)throw oc.error("started without valid sessionManager"),new Error(Tb+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(Tb+' cannot be used with cookieless_mode="always"')}get Ar(){var e,a=!((e=this._instance.get_property(ix))==null||!e.enabled),r=!this._instance.config.disable_session_recording,n=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return T&&a&&r&&!n}startIfEnabledOrStop(e){var a;if(!this.Ar||(a=this.Or)==null||!a.isStarted){var r=!V(Object.assign)&&!V(Array.from);this.Ar&&r?(this.Dr(e),oc.info("starting")):this.stopRecording()}}Dr(e){var a,r,n;this.Ar&&(Q!=null&&(a=Q.__PosthogExtensions__)!=null&&(a=a.rrweb)!=null&&a.record&&(r=Q.__PosthogExtensions__)!=null&&r.initSessionRecording?this.Lr(e):(n=Q.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,this.Nr,(o=>{if(o)return oc.error("could not load recorder",o);this.Lr(e)})))}stopRecording(){var e,a;(e=this.jr)==null||e.call(this),this.jr=void 0,(a=this.Or)==null||a.stop()}Ur(){var e;(e=this._instance.persistence)==null||e.unregister(VE)}zr(e){if(this._instance.persistence){var a,r,n=this._instance.persistence,o=()=>{var i=e.sessionRecording===!1?void 0:e.sessionRecording,s=i?.sampleRate,l=ge(s)?null:parseFloat(s);ge(l)&&this.Ur();var u=i?.minimumDurationMilliseconds;n.register({[ix]:j({enabled:!!i},i,{networkPayloadCapture:j({capturePerformance:e.capturePerformance},i?.networkPayloadCapture),canvasRecording:{enabled:i?.recordCanvas,fps:i?.canvasFps,quality:i?.canvasQuality},sampleRate:l,minimumDurationMilliseconds:V(u)?null:u,endpoint:i?.endpoint,triggerMatchType:i?.triggerMatchType,masking:i?.masking,urlTriggers:i?.urlTriggers})})};o(),(a=this.jr)==null||a.call(this),this.jr=(r=this._instance.sessionManager)==null?void 0:r.onSessionId(o)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.zr(e),this.Mr=!0,this.startIfEnabledOrStop()):this.Mr=!0:oc.info("skipping remote config with no sessionRecording",e)}log(e,a){var r;a===void 0&&(a="log"),(r=this.Or)!=null&&r.log?this.Or.log(e,a):oc.warn("log called before recorder was ready")}get Nr(){var e,a,r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(ix);return(r==null||(a=r.scriptConfig)==null?void 0:a.script)||"lazy-recorder"}Lr(e){var a,r;if((a=Q.__PosthogExtensions__)==null||!a.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.Or||(this.Or=(r=Q.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance),this.Or._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.Or.start(e)}onRRwebEmit(e){var a;(a=this.Or)==null||a.onRRwebEmit==null||a.onRRwebEmit(e)}overrideLinkedFlag(){var e,a;this.Or||(a=this._instance.persistence)==null||a.register({$replay_override_linked_flag:!0}),(e=this.Or)==null||e.overrideLinkedFlag()}overrideSampling(){var e,a;this.Or||(a=this._instance.persistence)==null||a.register({$replay_override_sampling:!0}),(e=this.Or)==null||e.overrideSampling()}overrideTrigger(e){var a,r;this.Or||(r=this._instance.persistence)==null||r.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(a=this.Or)==null||a.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.Or)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,a){var r;return!((r=this.Or)==null||!r.tryAddCustomEvent(e,a))}},gc={},Rb=()=>{},Ws="posthog",ST=!Q3&&ua?.indexOf("MSIE")===-1&&ua?.indexOf("Mozilla")===-1,pE=t=>{var e;return j({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:h3(q?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Rb,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,debug:Bt&&vt(Bt?.search)&&Bt.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!0,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(T==null||(e=T.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:a=>{var r="Bad HTTP status: "+a.statusCode+" "+a.text;$.error(r)},get_device_id:a=>a,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:_b},error_tracking:{},_onCapture:Rb,__preview_eager_load_replay:!1},(a=>({rageclick:!(a&&a>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(a&&a>="2025-05-24")||"history_change",session_recording:a&&a>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:a&&a>="2026-01-30"?"head":"body",internal_or_test_user_hostname:a&&a>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0}))(t))},hE=t=>{var e={};V(t.process_person)||(e.person_profiles=t.process_person),V(t.xhr_headers)||(e.request_headers=t.xhr_headers),V(t.cookie_name)||(e.persistence_name=t.cookie_name),V(t.disable_cookie)||(e.disable_persistence=t.disable_cookie),V(t.store_google)||(e.save_campaign_params=t.store_google),V(t.verbose)||(e.debug=t.verbose);var a=ot({},e,t);return Ce(t.property_blacklist)&&(V(t.property_denylist)?a.property_denylist=t.property_blacklist:Ce(t.property_denylist)?a.property_denylist=[...t.property_blacklist,...t.property_denylist]:$.error("Invalid value for property_denylist config: "+t.property_denylist)),a},Mb=class{constructor(){this.__forceAllowLocalhost=!1}get Hr(){return this.__forceAllowLocalhost}set Hr(e){$.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},ch=class t{get decideEndpointWasHit(){var e,a;return(e=(a=this.featureFlags)==null?void 0:a.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,a;return(e=(a=this.featureFlags)==null?void 0:a.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new Mb,this.Br=!1,this.version=fn.LIB_VERSION,this.qr=new _c,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=pE(),this.SentryIntegration=tb,this.sentryIntegration=e=>(function(a,r){var n=oT(a,r);return{name:nT,processEvent:o=>n(o)}})(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Wr=!1,this.Gr=null,this.Vr=null,this.Jr=null,this.featureFlags=new db(this),this.toolbar=new ab(this),this.scrollManager=new Lb(this),this.pageViewManager=new ah(this),this.surveys=new vb(this),this.conversations=new yb(this),this.logs=new xb(this),this.experiments=new Ab(this),this.exceptions=new cb(this),this.rateLimiter=new bb(this),this.requestRouter=new Ib(this),this.consent=new Qx(this),this.externalIntegrations=new Eb(this),this.people={set:(e,a,r)=>{var n=vt(e)?{[e]:a}:e;this.setPersonProperties(n),r?.({})},set_once:(e,a,r)=>{var n=vt(e)?{[e]:a}:e;this.setPersonProperties(void 0,n),r?.({})}},this.on("eventCaptured",(e=>$.info('send "'+e?.event+'"',e)))}init(e,a,r){if(r&&r!==Ws){var n,o=(n=gc[r])!==null&&n!==void 0?n:new t;return o._init(e,a,r),gc[r]=o,gc[Ws][r]=o,o}return this._init(e,a,r)}_init(e,a,r){var n;if(a===void 0&&(a={}),V(e)||Cx(e))return $.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},a.debug=this.Kr(a.debug),this.Yr=a,this.Xr=[],a.person_profiles&&(this.Vr=a.person_profiles),this.set_config(ot({},pE(a.defaults),hE(a),{name:r,token:e})),this.config.on_xhr_error&&$.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=a.disable_compression?void 0:mn.GZipJS;var o=this.Qr();this.persistence=new mc(this.config,o),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new mc(j({},this.config,{persistence:"sessionStorage"}),o);var i=j({},this.persistence.props),s=j({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Zr=new Cb((m=>this.ts(m)),this.config.request_queue_config),this.es=new wb(this),this.__request_queue=[];var l=this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut();if(l||(this.sessionManager=new lh(this),this.sessionPropsManager=new sh(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?($.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.rs(l)}),0)):($.info("Initializing extensions synchronously"),this.rs(l)),fn.DEBUG=fn.DEBUG||this.config.debug,fn.DEBUG&&$.info("Starting in debug mode",{this:this,config:a,thisC:j({},this.config),p:i,s}),((n=a.bootstrap)==null?void 0:n.distinctID)!==void 0){var u,c,d=this.config.get_device_id(So()),f=(u=a.bootstrap)!=null&&u.isIdentifiedID?d:a.bootstrap.distinctID;this.persistence.set_property(pn,(c=a.bootstrap)!=null&&c.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:a.bootstrap.distinctID,$device_id:f})}if(this.ss()){var h,S,x=Object.keys(((h=a.bootstrap)==null?void 0:h.featureFlags)||{}).filter((m=>{var y;return!((y=a.bootstrap)==null||(y=y.featureFlags)==null||!y[m])})).reduce(((m,y)=>{var v;return m[y]=((v=a.bootstrap)==null||(v=v.featureFlags)==null?void 0:v[y])||!1,m}),{}),b=Object.keys(((S=a.bootstrap)==null?void 0:S.featureFlagPayloads)||{}).filter((m=>x[m])).reduce(((m,y)=>{var v,C;return(v=a.bootstrap)!=null&&(v=v.featureFlagPayloads)!=null&&v[y]&&(m[y]=(C=a.bootstrap)==null||(C=C.featureFlagPayloads)==null?void 0:C[y]),m}),{});this.featureFlags.receivedFeatureFlags({featureFlags:x,featureFlagPayloads:b})}if(l)this.register_once({distinct_id:Yu,$device_id:null},"");else if(!this.get_distinct_id()){var g=this.config.get_device_id(So());this.register_once({distinct_id:g,$device_id:g},""),this.persistence.set_property(pn,"anonymous")}return ft(T,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),a.segment?P3(this,(()=>this.ns())):this.ns(),_o(this.config._onCapture)&&this.config._onCapture!==Rb&&($.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(m=>this.config._onCapture(m.event,m)))),this.config.ip&&$.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this}rs(e){var a=performance.now();this.historyAutocapture=new eb(this),this.historyAutocapture.startIfEnabled();var r=[];r.push((()=>{new rb(this).startIfEnabledOrStop()})),r.push((()=>{var n;this.siteApps=new kb(this),(n=this.siteApps)==null||n.init()})),e||r.push((()=>{this.sessionRecording=new uh(this),this.sessionRecording.startIfEnabledOrStop()})),this.config.disable_scroll_properties||r.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),r.push((()=>{this.autocapture=new Zx(this),this.autocapture.startIfEnabled()})),r.push((()=>{this.surveys.loadIfEnabled()})),r.push((()=>{this.logs.loadIfEnabled()})),r.push((()=>{this.conversations.loadIfEnabled()})),r.push((()=>{this.productTours=new fb(this),this.productTours.loadIfEnabled()})),r.push((()=>{this.heatmaps=new ob(this),this.heatmaps.startIfEnabled()})),r.push((()=>{this.webVitalsAutocapture=new nb(this)})),r.push((()=>{this.exceptionObserver=new Jx(this),this.exceptionObserver.startIfEnabledOrStop()})),r.push((()=>{this.deadClicksAutocapture=new th(this,B3),this.deadClicksAutocapture.startIfEnabled()})),r.push((()=>{if(this.os){var n=this.os;this.os=void 0,this.yi(n)}})),this.ls(r,a)}ls(e,a){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-a>=30&&e.length>0)return void setTimeout((()=>{this.ls(e,a)}),0);var r=e.shift();if(r)try{r()}catch(o){$.error("Error initializing extension:",o)}}var n=Math.round(performance.now()-a);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:n}),this.config.__preview_deferred_init_extensions&&$.info("PostHog extensions initialized ("+n+"ms)")}yi(e){var a,r,n,o,i,s,l,u,c;if(!q||!q.body)return $.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.yi(e)}),500);this.config.__preview_deferred_init_extensions&&(this.os=e),this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=he(e.supportedCompression,mn.GZipJS)?mn.GZipJS:he(e.supportedCompression,mn.Base64)?mn.Base64:void 0),(a=e.analytics)!=null&&a.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Vr?this.Vr:"identified_only"}),(r=this.siteApps)==null||r.onRemoteConfig(e),(n=this.sessionRecording)==null||n.onRemoteConfig(e),(o=this.autocapture)==null||o.onRemoteConfig(e),(i=this.heatmaps)==null||i.onRemoteConfig(e),this.surveys.onRemoteConfig(e),this.logs.onRemoteConfig(e),this.conversations.onRemoteConfig(e),(s=this.productTours)==null||s.onRemoteConfig(e),(l=this.webVitalsAutocapture)==null||l.onRemoteConfig(e),(u=this.exceptionObserver)==null||u.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(c=this.deadClicksAutocapture)==null||c.onRemoteConfig(e)}ns(){try{this.config.loaded(this)}catch(r){$.critical("`loaded` function failed",r)}if(this.us(),this.config.internal_or_test_user_hostname&&Bt!=null&&Bt.hostname){var e=Bt.hostname,a=this.config.internal_or_test_user_hostname;(typeof a=="string"?e===a:a.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.hs()}),1),new Sb(this).load(),this.featureFlags.flags()}us(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.Zr)==null||e.enable())}_dom_loaded(){this.is_capturing()&&Co(this.__request_queue,(e=>this.ts(e))),this.__request_queue=[],this.us()}_handle_unload(){var e,a;this.surveys.handlePageUnload(),this.config.request_batching?(this.ds()&&this.capture("$pageleave"),(e=this.Zr)==null||e.unload(),(a=this.es)==null||a.unload()):this.ds()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}_send_request(e){this.__loaded&&(ST?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=oh(e.url,{ip:this.config.ip?1:0}),e.headers=j({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,e.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(a=>{var r,n,o,i=j({},a);i.timeout=i.timeout||6e4,i.url=oh(i.url,{_:new Date().getTime().toString(),ver:fn.LIB_VERSION,compression:i.compression});var s=(r=i.transport)!==null&&r!==void 0?r:"fetch",l=qp.filter((c=>!i.disableTransport||!c.transport||!i.disableTransport.includes(c.transport))),u=(n=(o=UE(l,(c=>c.transport===s)))==null?void 0:o.method)!==null&&n!==void 0?n:l[0].method;if(!u)throw new Error("No available transport method");u(i)})(j({},e,{callback:a=>{var r,n;this.rateLimiter.checkForLimiting(a),a.statusCode>=400&&((r=(n=this.config).on_request_error)==null||r.call(n,a)),e.callback==null||e.callback(a)}}))))}ts(e){this.es?this.es.retriableRequest(e):this._send_request(e)}_execute_array(e){var a,r=[],n=[],o=[];Co(e,(s=>{s&&(a=s[0],Ce(a)?o.push(s):_o(s)?s.call(this):Ce(s)&&a==="alias"?r.push(s):Ce(s)&&a.indexOf("capture")!==-1&&_o(this[a])?o.push(s):n.push(s))}));var i=function(s,l){Co(s,(function(u){if(Ce(u[0])){var c=l;Be(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else this[u[0]].apply(this,u.slice(1))}),l)};i(r,this),i(n,this),i(o,this)}ss(){var e,a;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((a=this.config.bootstrap)==null?void 0:a.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,a,r){var n;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Zr){if(this.is_capturing())if(!V(e)&&vt(e)){var o=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(o&&!this.config.__preview_capture_bot_pageviews)){var i=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(i==null||!i.isRateLimited){a!=null&&a.$current_url&&!vt(a?.$current_url)&&($.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),a==null||delete a.$current_url),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var s=new Date,l=r?.timestamp||s,u=So(),c={uuid:u,event:e,properties:this.calculateEventProperties(e,a||{},l,u)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&o&&(c.event="$bot_pageview",c.properties.$browser_type="bot"),i&&(c.properties.$lib_rate_limit_remaining_tokens=i.remainingTokens),r?.$set&&(c.$set=r?.$set);var d,f=e!=="$groupidentify",h=this.vs(r?.$set_once,f);if(h&&(c.$set_once=h),(c=f3(c,r!=null&&r._noTruncate?null:this.config.properties_string_max_length)).timestamp=l,V(r?.timestamp)||(c.properties.$event_time_override_provided=!0,c.properties.$event_time_override_system_time=s),e===fc.DISMISSED||e===fc.SENT){var S=a?.[yx.SURVEY_ID],x=a?.[yx.SURVEY_ITERATION];d={id:S,current_iteration:x},localStorage.getItem(cE(d))||localStorage.setItem(cE(d),"true"),c.$set=j({},c.$set,{[a4({id:S,current_iteration:x},e===fc.SENT?"responded":"dismissed")]:!0})}else e===fc.SHOWN&&(c.$set=j({},c.$set,{[yx.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));var b=j({},c.properties.$set,c.$set);if(Xs(b)||this.setPersonPropertiesForFlags(b),!ge(this.config.before_send)){var g=this.cs(c);if(!g)return;c=g}this.qr.emit("eventCaptured",c);var m={method:"POST",url:(n=r?._url)!==null&&n!==void 0?n:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:c,compression:"best-available",batchKey:r?._batchKey};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.ts(m):this.Zr.enqueue(m),c}$.critical("This capture call is ignored due to client rate limiting.")}}else $.error("No event name provided to posthog.capture")}else $.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(a=>e(a.event,a)))}calculateEventProperties(e,a,r,n,o){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return a;var i=o?void 0:this.persistence.remove_event_timer(e),s=j({},a);if(s.token=this.config.token,s.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(s.$cookieless_mode=!0),e==="$snapshot"){var l=j({},this.persistence.properties(),this.sessionPersistence.properties());return s.distinct_id=l.distinct_id,(!vt(s.distinct_id)&&!yn(s.distinct_id)||Cx(s.distinct_id))&&$.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),s}var u,c=q3(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:d,windowId:f}=this.sessionManager.checkAndGetSessionAndWindowId(o,r.getTime());s.$session_id=d,s.$window_id=f}this.sessionPropsManager&&ot(s,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&ot(s,this.sessionRecording.sdkDebugProperties),s.$sdk_debug_retry_queue_size=(h=this.es)==null?void 0:h.length}catch(g){s.$sdk_debug_error_capturing_properties=String(g)}if(this.requestRouter.region===pc.CUSTOM&&(s.$lib_custom_api_host=this.config.api_host),u=e!=="$pageview"||o?e!=="$pageleave"||o?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,n),s=ot(s,u),e==="$pageview"&&q&&(s.title=q.title),!V(i)){var S=r.getTime()-i;s.$duration=parseFloat((S/1e3).toFixed(3))}ua&&this.config.opt_out_useragent_filter&&(s.$browser_type=this._is_bot()?"bot":"browser"),(s=ot({},c,this.persistence.properties(),this.sessionPersistence.properties(),s)).$is_identified=this._isIdentified(),Ce(this.config.property_denylist)?Be(this.config.property_denylist,(function(g){delete s[g]})):$.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var x=this.config.sanitize_properties;x&&($.error("sanitize_properties is deprecated. Use before_send instead"),s=x(s,e));var b=this.fs();return s.$process_person_profile=b,b&&!o&&this.ps("_calculate_event_properties"),s}vs(e,a){var r;if(a===void 0&&(a=!0),!this.persistence||!this.fs()||this.Br)return e;var n=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),i=ot({},n,o||{},e||{}),s=this.config.sanitize_properties;return s&&($.error("sanitize_properties is deprecated. Use before_send instead"),i=s(i,"$set_once")),a&&(this.Br=!0),Xs(i)?void 0:i}register(e,a){var r;(r=this.persistence)==null||r.register(e,a)}register_once(e,a,r){var n;(n=this.persistence)==null||n.register_once(e,a,r)}register_for_session(e){var a;(a=this.sessionPersistence)==null||a.register(e)}unregister(e){var a;(a=this.persistence)==null||a.unregister(e)}unregister_for_session(e){var a;(a=this.sessionPersistence)==null||a.unregister(e)}gs(e,a){this.register({[e]:a})}getFeatureFlag(e,a){return this.featureFlags.getFeatureFlag(e,a)}getFeatureFlagPayload(e){return this.featureFlags.getFeatureFlagPayload(e)}getFeatureFlagResult(e,a){return this.featureFlags.getFeatureFlagResult(e,a)}isFeatureEnabled(e,a){return this.featureFlags.isFeatureEnabled(e,a)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateFlags(e,a,r){var n=r!=null&&r.merge?this.featureFlags.getFlagVariants():{},o=r!=null&&r.merge?this.featureFlags.getFlagPayloads():{},i=j({},n,e),s=j({},o,a),l={};for(var[u,c]of Object.entries(i)){var d=typeof c=="string";l[u]={key:u,enabled:!!d||!!c,variant:d?c:void 0,reason:void 0,metadata:V(s?.[u])?void 0:{id:0,version:void 0,description:void 0,payload:s[u]}}}this.featureFlags.receivedFeatureFlags({flags:l})}updateEarlyAccessFeatureEnrollment(e,a,r){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,a,r)}getEarlyAccessFeatures(e,a,r){return a===void 0&&(a=!1),this.featureFlags.getEarlyAccessFeatures(e,a,r)}on(e,a){return this.qr.on(e,a)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var a,r;return(a=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&a!==void 0?a:()=>{}}getSurveys(e,a){a===void 0&&(a=!1),this.surveys.getSurveys(e,a)}getActiveMatchingSurveys(e,a){a===void 0&&(a=!1),this.surveys.getActiveMatchingSurveys(e,a)}renderSurvey(e,a){this.surveys.renderSurvey(e,a)}displaySurvey(e,a){a===void 0&&(a=n4),this.surveys.displaySurvey(e,a)}cancelPendingSurvey(e){this.surveys.cancelPendingSurvey(e)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,a){return a===void 0&&(a=!1),this.surveys.canRenderSurveyAsync(e,a)}identify(e,a,r){if(!this.__loaded||!this.persistence)return $.uninitializedWarning("posthog.identify");if(yn(e)&&(e=e.toString(),$.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))$.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(e!==Yu){if(this.ps("posthog.identify")){var n=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var o=n;this.register_once({$had_persisted_distinct_id:!0,$device_id:o},"")}e!==n&&e!==this.get_property(sc)&&(this.unregister(sc),this.register({distinct_id:e}));var i=(this.persistence.get_property(pn)||"anonymous")==="anonymous";e!==n&&i?(this.persistence.set_property(pn,"identified"),this.setPersonPropertiesForFlags(j({},r||{},a||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:n},{$set:a||{},$set_once:r||{}}),this.Jr=nE(e,a,r),this.featureFlags.setAnonymousDistinctId(n)):(a||r)&&this.setPersonProperties(a,r),e!==n&&(this.reloadFeatureFlags(),this.unregister(Wp))}}else $.critical('The string "'+Yu+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else $.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,a){if((e||a)&&this.ps("posthog.setPersonProperties")){var r=nE(this.get_distinct_id(),e,a);this.Jr!==r?(this.setPersonPropertiesForFlags(j({},a||{},e||{})),this.capture("$set",{$set:e||{},$set_once:a||{}}),this.Jr=r):$.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,a,r){if(e&&a){var n=this.getGroups();n[e]!==a&&this.resetGroupPropertiesForFlags(e),this.register({$groups:j({},n,{[e]:a})}),r&&(this.capture("$groupidentify",{$group_type:e,$group_key:a,$group_set:r}),this.setGroupPropertiesForFlags({[e]:r})),n[e]===a||r||this.reloadFeatureFlags()}else $.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,a){a===void 0&&(a=!0),this.featureFlags.setPersonPropertiesForFlags(e,a)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,a){a===void 0&&(a=!0),this.ps("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,a)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var a,r,n,o;if($.info("reset"),!this.__loaded)return $.uninitializedWarning("posthog.reset");var i=this.get_property("$device_id");if(this.consent.reset(),(a=this.persistence)==null||a.clear(),(r=this.sessionPersistence)==null||r.clear(),this.surveys.reset(),this.featureFlags.reset(),(n=this.persistence)==null||n.set_property(pn,"anonymous"),(o=this.sessionManager)==null||o.resetSessionId(),this.Jr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:Yu,$device_id:null},"");else{var s=this.config.get_device_id(So());this.register_once({distinct_id:s,$device_id:e?s:i},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,a;return(e=(a=this.sessionManager)==null?void 0:a.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:a,sessionStartTimestamp:r}=this.sessionManager.checkAndGetSessionAndWindowId(!0),n=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+a);if(e!=null&&e.withTimestamp&&r){var o,i=(o=e.timestampLookBack)!==null&&o!==void 0?o:10;if(!r)return n;n+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-i,0)}return n}alias(e,a){return e===this.get_property(zE)?($.critical("Attempting to create alias for existing People user - aborting."),-2):this.ps("posthog.alias")?(V(a)&&(a=this.get_distinct_id()),e!==a?(this.gs(sc,e),this.capture("$create_alias",{alias:e,distinct_id:a})):($.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var a=j({},this.config);if(gt(e)){var r,n,o,i,s,l,u;ot(this.config,hE(e));var c=this.Qr();(r=this.persistence)==null||r.update_config(this.config,a,c),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new mc(j({},this.config,{persistence:"sessionStorage"}),c);var d=this.Kr(this.config.debug);vn(d)&&(this.config.debug=d),vn(this.config.debug)&&(this.config.debug?(fn.DEBUG=!0,Ke.H()&&Ke.G("ph_debug","true"),$.info("set_config",{config:e,oldConfig:a,newConfig:j({},this.config)})):(fn.DEBUG=!1,Ke.H()&&Ke.V("ph_debug"))),(n=this.exceptionObserver)==null||n.onConfigChange(),(o=this.sessionRecording)==null||o.startIfEnabledOrStop(),(i=this.autocapture)==null||i.startIfEnabled(),(s=this.heatmaps)==null||s.startIfEnabled(),(l=this.exceptionObserver)==null||l.startIfEnabledOrStop(),this.surveys.loadIfEnabled(),this._s(),(u=this.externalIntegrations)==null||u.startIfEnabledOrStop()}}startSessionRecording(e){var a=e===!0,r={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};if(Object.values(r).some(Boolean)){var n,o,i,s,l;(n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),r.sampling&&((o=this.sessionRecording)==null||o.overrideSampling()),r.linked_flag&&((i=this.sessionRecording)==null||i.overrideLinkedFlag()),r.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),r.event_trigger&&((l=this.sessionRecording)==null||l.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,a){var r=new Error("PostHog syntheticException"),n=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(j({},n,a))}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var a;return(a=this.persistence)==null?void 0:a.props[e]}getSessionProperty(e){var a;return(a=this.sessionPersistence)==null?void 0:a.props[e]}toString(){var e,a=(e=this.config.name)!==null&&e!==void 0?e:Ws;return a!==Ws&&(a=Ws+"."+a),a}_isIdentified(){var e,a;return((e=this.persistence)==null?void 0:e.get_property(pn))==="identified"||((a=this.sessionPersistence)==null?void 0:a.get_property(pn))==="identified"}fs(){var e,a;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&Xs(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[sc])&&((a=this.persistence)==null||(a=a.props)==null||!a[Xp]))}ds(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.fs()||this.ps("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.ps("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}ps(e){return this.config.person_profiles==="never"?($.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.gs(Xp,!0),!0)}Qr(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),a=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!a}_s(){var e,a,r,n,o=this.Qr();return((e=this.persistence)==null?void 0:e.ki)!==o&&((r=this.persistence)==null||r.set_disabled(o)),((a=this.sessionPersistence)==null?void 0:a.ki)!==o&&((n=this.sessionPersistence)==null||n.set_disabled(o)),o}opt_in_capturing(e){var a;if(this.config.cookieless_mode!=="always"){var r,n,o;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(r=this.sessionManager)==null||r.destroy(),(n=this.pageViewManager)==null||n.destroy(),this.sessionManager=new lh(this),this.pageViewManager=new ah(this),this.persistence&&(this.sessionPropsManager=new sh(this,this.sessionManager,this.persistence)),this.sessionRecording=new uh(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this._s(),this.us(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(V(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((o=e?.captureEventName)!==null&&o!==void 0?o:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.hs()}else $.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,a,r;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this._s(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:Yu,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),(a=this.pageViewManager)==null||a.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(r=this.sessionRecording)==null||r.stopRecording(),this.sessionRecording=void 0,this.hs())):$.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===hn.GRANTED?"granted":e===hn.DENIED?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isExplicitlyOptedOut()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this._s()}_is_bot(){return ka?bT(ka,this.config.custom_blocked_useragents):void 0}hs(){q&&(q.visibilityState==="visible"?this.Wr||(this.Wr=!0,this.capture("$pageview",{title:q.title},{send_instantly:!0}),this.Gr&&(q.removeEventListener("visibilitychange",this.Gr),this.Gr=null)):this.Gr||(this.Gr=this.hs.bind(this),ft(q,"visibilitychange",this.Gr)))}debug(e){e===!1?(T?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(T?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}M(){var e,a,r,n,o,i,s,l=this.Yr||{};return"advanced_disable_flags"in l?!!l.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?($.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(r="advanced_disable_decide",n=!1,o=$,i=(a="advanced_disable_flags")in(e=l)&&!ge(e[a]),s=r in e&&!ge(e[r]),i?e[a]:s?(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+a+"' instead. The old field will be removed in a future major version."),e[r]):n)}cs(e){if(ge(this.config.before_send))return e;var a=Ce(this.config.before_send)?this.config.before_send:[this.config.before_send],r=e;for(var n of a){if(r=n(r),ge(r)){var o="Event '"+e.event+"' was rejected in beforeSend function";return HH(e.event)?$.warn(o+". This can cause unexpected behavior."):$.info(o),null}r.properties&&!Xs(r.properties)||$.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return r}getPageViewId(){var e;return(e=this.pageViewManager.Kt)==null?void 0:e.pageViewId}captureTraceFeedback(e,a){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:a})}captureTraceMetric(e,a,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:a,$ai_metric_value:String(r)})}Kr(e){var a=vn(e)&&!e,r=Ke.H()&&Ke.q("ph_debug")==="true";return!a&&(!!r||e)}};(function(t,e){for(var a=0;a<e.length;a++)t.prototype[e[a]]=d3(t.prototype[e[a]])})(ch,["identify"]);var mE;var _T=(mE=gc[Ws]=new ch,(function(){function t(){t.done||(t.done=!0,ST=!1,Be(gc,(function(e){e._dom_loaded()})))}q!=null&&q.addEventListener?q.readyState==="complete"?t():ft(q,"DOMContentLoaded",t,{capture:!1}):T&&$.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),mE);var Vb=class{constructor(e={}){this.options=e;B(this,"client");B(this,"featureFlagsCallback");B(this,"captureCallback");B(this,"rrwebCallback");if(this.client=e.client,this.featureFlagsCallback=e.onFeatureFlagsLoaded,this.captureCallback=e.onCapture,this.rrwebCallback=e.onRRWebEvent,!this.client&&e.consent&&e.requireExplicitConsent&&typeof window<"u"&&e.apiKey){let a=e.consent;a.getStatus()==="granted"&&this.initPostHog(),a.subscribe(n=>{n==="granted"?this.client?this.client.opt_in_capturing():this.initPostHog():n==="denied"&&this.client&&this.client.opt_out_capturing()});return}!this.client&&typeof window<"u"&&e.apiKey&&this.initPostHog()}initPostHog(){let e=this.options;if(!e.apiKey)return;let a=e.enableFeatureFlags??!0,r=`syntro_${e.apiKey.slice(-6)||"sdk"}`,n={api_host:e.apiHost??"https://telemetry.syntrologie.com",advanced_disable_feature_flags:!a,advanced_disable_feature_flags_on_first_load:!a,autocapture:e.autocapture??!0,capture_pageview:e.capturePageview??"history_change",capture_pageleave:e.capturePageleave??!0,disable_session_recording:!(e.sessionRecording??!0),opt_out_useragent_filter:!0,session_recording:{recordCrossDomainIFrames:!0},capture_performance:!0,enable_recording_console_log:!0,loaded:i=>{if(a&&this.featureFlagsCallback){i.onFeatureFlags(()=>{let l=this.getAllFeatureFlags();l&&this.featureFlagsCallback&&this.featureFlagsCallback(l)});let s=this.getAllFeatureFlags();s&&Object.keys(s).length>0&&this.featureFlagsCallback(s)}this.captureCallback&&i.on("eventCaptured",(...s)=>{let l=s[0],u=typeof l=="string"?l:l?.event,c=typeof l=="string"?void 0:l?.properties;typeof u=="string"&&this.captureCallback?.(u,c)})}},o=_T.init(e.apiKey,n,r);o&&(this.client=o),this.rrwebCallback&&this.client&&this.setupRRWebIntercept()}setupRRWebIntercept(e=30){let a=this.client?.sessionRecording;if(!a){e>0&&setTimeout(()=>this.setupRRWebIntercept(e-1),500);return}let r=null,n=a;for(let i of Object.getOwnPropertyNames(n)){let s=n[i];if(s&&typeof s=="object"&&typeof s.onRRwebEmit=="function"&&typeof s.start=="function"&&s!==a){r=s;break}}if(!r){e>0&&setTimeout(()=>this.setupRRWebIntercept(e-1),500);return}let o=r.onRRwebEmit.bind(r);r.onRRwebEmit=i=>{this.rrwebCallback?.({kind:"rrweb",...i}),o(i)},typeof window<"u"&&(window.__RRWEB_INTERCEPT_READY__=!0)}getAllFeatureFlags(){return this.client?.featureFlags?.getFlagVariants()}getSegmentFlags(){let e=this.getAllFeatureFlags();if(!e)return{};let a={};for(let[r,n]of Object.entries(e))r.startsWith("in_segment_")&&(a[r]=n===!0);return a}identify(e,a){this.client?.identify(e,a)}alias(e,a){this.client?.alias(e,a)}track(e,a){this.client?.capture(e,a)}trackCanvasOpened(e){this.track("shadow_canvas_opened",{surface:e})}trackCanvasClosed(e){this.track("shadow_canvas_closed",{surface:e})}trackRectangleViewed(e,a){this.track("shadow_canvas_rectangle_viewed",{rectangleId:e,surface:a})}trackAction(e,a,r){this.track("shadow_canvas_action",{action:e,rectangleId:a,surface:r})}register(e){this.client?.register?.(e)}getSessionId(){return this.client?.get_session_id?.()}startSessionRecording(){this.client?.startSessionRecording?.()}trackExperiment(e,a,r){let n=`$experiment_${e}`;this.register({[n]:r??`variation_${a}`,[`${n}_id`]:a}),this.track("$experiment_started",{$experiment_key:e,$experiment_variation_id:a,$experiment_variation_name:r??`variation_${a}`})}setPersonProperties(e){this.client?.capture("$set",{$set:e})}setPersonPropertiesOnce(e){this.client?.capture("$set",{$set_once:e})}getDistinctId(){return this.client?.get_distinct_id?.()}};function $b(t={}){return new Vb(t)}var kc=class{constructor(e,a){B(this,"telemetry");B(this,"variantId");B(this,"seenSet",new Set);B(this,"triggeredSet",new Set);this.telemetry=e,this.variantId=a}trackServed(e,a){this.telemetry.track?.("syntro_config_served",{variant_id:this.variantId,tiles:e,actions:a})}trackSeen(e,a){this.seenSet.has(e)||(this.seenSet.add(e),this.telemetry.track?.("syntro_intervention_seen",{variant_id:this.variantId,intervention_id:e,intervention_kind:a}))}trackTriggered(e,a){this.triggeredSet.has(e)||(this.triggeredSet.add(e),this.telemetry.track?.("syntro_intervention_triggered",{variant_id:this.variantId,intervention_id:e,intervention_kind:a}))}trackInteracted(e,a,r){this.telemetry.track?.("syntro_intervention_interacted",{variant_id:this.variantId,intervention_id:e,intervention_kind:a,interaction_type:r})}resetPage(){this.seenSet.clear(),this.triggeredSet.clear()}};var jb=async(t,e)=>{let a=[];if(e.applyAction)for(let r of t.actions){let n=await e.applyAction(r);a.push(n)}return{cleanup:async()=>{for(let r=a.length-1;r>=0;r--)try{await a[r].revert()}catch{}}}},Gb=async(t,e)=>{let a=[];if(e.applyAction){let r=t.actions.map(n=>e.applyAction(n));if(t.waitFor==="any"){let n=await Promise.race(r);a.push(n);let o=await Promise.allSettled(r);for(let i of o)i.status==="fulfilled"&&i.value!==n&&a.push(i.value)}else{let n=await Promise.all(r);a.push(...n)}}return{cleanup:async()=>{for(let r of a)try{await r.revert()}catch{}}}},Wb=async(t,e)=>{let a,r,n=!1,o={cleanup:()=>{n=!0,r&&clearTimeout(r),a&&a()}};return t.event&&e.subscribeEvent?await new Promise(i=>{a=e.subscribeEvent(t.event,()=>{n||i()}),t.durationMs!==void 0&&(r=setTimeout(()=>{n||i()},t.durationMs))}):t.durationMs!==void 0&&await new Promise(i=>{r=setTimeout(()=>{n||i()},t.durationMs)}),o};var hh=class{constructor(){B(this,"executors",new Map);for(let{kind:e,executor:a}of xv)this.registerCore(e,a);for(let{kind:e,executor:a}of Rv)this.registerCore(e,a);this.registerCore("core:mountWidget",async()=>{throw new Error("core:mountWidget must be handled by ActionEngine")}),this.registerCore("core:sequence",jb),this.registerCore("core:parallel",Gb),this.registerCore("core:wait",Wb)}registerCore(e,a,r){this.executors.set(e,{kind:e,executor:a,schema:r,source:"core",isBuiltIn:!0})}register(e,a,r,n="custom",o=!1){if(this.executors.has(e)){if(this.executors.get(e).isBuiltIn)return;console.warn(`[ExecutorRegistry] Overriding executor for kind: ${e} (source: ${n})`)}console.log(`[ExecutorRegistry] Registered executor: ${e} (source: ${n})`),this.executors.set(e,{kind:e,executor:a,schema:r,source:n,isBuiltIn:o})}unregister(e){let a=this.executors.get(e);return a?a.isBuiltIn?(console.warn(`[ExecutorRegistry] Cannot unregister built-in executor: ${e}`),!1):(this.executors.delete(e),!0):!1}unregisterBySource(e){for(let[a,r]of this.executors.entries())r.source===e&&this.executors.delete(a)}get(e){return this.executors.get(e)?.executor}getRegistration(e){return this.executors.get(e)}has(e){return this.executors.has(e)}validate(e){let a=[];if(!e||typeof e!="object")return a.push({code:"INVALID_ACTION",message:"Action must be an object"}),{valid:!1,errors:a,warnings:[]};let{kind:r}=e;if(!r||typeof r!="string")return a.push({code:"MISSING_KIND",message:"Action must have a 'kind' property"}),{valid:!1,errors:a,warnings:[]};let n=this.executors.get(r);if(!n)return a.push({code:"UNKNOWN_KIND",message:`Unknown action kind: ${r}`,field:"kind"}),{valid:!1,errors:a,warnings:[]};if(n.schema){let o=n.schema.safeParse(e);if(!o.success){for(let i of o.error.issues)a.push({code:"SCHEMA_VALIDATION_ERROR",message:i.message,field:i.path.join(".")});return{valid:!1,errors:a,warnings:[]}}}return{valid:!0,errors:[],warnings:[]}}list(){return Array.from(this.executors.keys())}listRegistrations(){return Array.from(this.executors.values())}getBuiltInKinds(){return Array.from(this.executors.entries()).filter(([,e])=>e.isBuiltIn).map(([e])=>e)}getCustomKinds(){return Array.from(this.executors.entries()).filter(([,e])=>!e.isBuiltIn).map(([e])=>e)}},xn=new hh;function d4(t){return xn.get(t)}function Zb(t){return xn.has(t)}function Xb(t,e,a){!t.content||typeof t.content!="string"?e.push({code:"MISSING_CONTENT",message:"Badge action requires 'content' property",field:"content"}):t.content.length>100&&a.push({code:"LONG_BADGE_CONTENT",message:"Badge content is quite long",suggestion:"Keep badge content short (under 100 characters)"})}function Kb(t,e,a){if(!t.content||typeof t.content!="object"){e.push({code:"MISSING_CONTENT",message:"Tooltip action requires 'content' object",field:"content"});return}(!t.content.body||typeof t.content.body!="string")&&e.push({code:"MISSING_BODY",message:"Tooltip content requires 'body' property",field:"content.body"})}function Yb(t,e,a){!t.html||typeof t.html!="string"?e.push({code:"MISSING_HTML",message:"insertHtml action requires 'html' property",field:"html"}):t.html.length>mh&&e.push({code:"HTML_TOO_LONG",message:`HTML content exceeds maximum length of ${mh}`,field:"html"});let r=["before","after","prepend","append","replace"];(!t.position||!r.includes(t.position))&&e.push({code:"INVALID_POSITION",message:`Position must be one of: ${r.join(", ")}`,field:"position"})}function Qb(t,e,a){(t.text===void 0||t.text===null)&&e.push({code:"MISSING_TEXT",message:"setText action requires 'text' property",field:"text"})}function Jb(t,e,a){!t.attr||typeof t.attr!="string"?e.push({code:"MISSING_ATTR",message:"setAttr action requires 'attr' property",field:"attr"}):(u0.has(t.attr.toLowerCase())||t.attr.toLowerCase().startsWith("on"))&&e.push({code:"DANGEROUS_ATTR",message:`Event handler attributes are not allowed: ${t.attr}`,field:"attr"}),(t.value===void 0||t.value===null)&&e.push({code:"MISSING_VALUE",message:"setAttr action requires 'value' property",field:"value"})}function e0(t,e,a){!t.className||typeof t.className!="string"?e.push({code:"MISSING_CLASS_NAME",message:"Class action requires 'className' property",field:"className"}):/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t.className)||a.push({code:"INVALID_CLASS_NAME",message:"Class name contains unusual characters",suggestion:"Use alphanumeric characters, hyphens, and underscores"})}function t0(t,e,a){if(!t.styles||typeof t.styles!="object")e.push({code:"MISSING_STYLES",message:"setStyle action requires 'styles' object",field:"styles"});else{let r=Object.keys(t.styles).length;r>gh&&e.push({code:"TOO_MANY_STYLES",message:`Too many styles (${r}). Maximum is ${gh}`,field:"styles"});for(let[n,o]of Object.entries(t.styles))typeof o=="string"&&o.includes("expression(")&&e.push({code:"DANGEROUS_STYLE",message:`Style expressions are not allowed: ${n}`,field:`styles.${n}`})}}function a0(t,e,a){(!t.slot||typeof t.slot!="string")&&e.push({code:"MISSING_SLOT",message:"mountWidget action requires 'slot' property",field:"slot"}),!t.widget||typeof t.widget!="object"?e.push({code:"MISSING_WIDGET",message:"mountWidget action requires 'widget' object",field:"widget"}):(!t.widget.widgetId||typeof t.widget.widgetId!="string")&&e.push({code:"MISSING_WIDGET_ID",message:"Widget must have a 'widgetId' property",field:"widget.widgetId"})}function r0(t,e,a){t.durationMs===void 0&&!t.event&&e.push({code:"MISSING_WAIT_CONFIG",message:"wait action requires either 'durationMs' or 'event' property"}),t.durationMs!==void 0&&t.durationMs<0&&e.push({code:"INVALID_DURATION",message:"durationMs must be a positive number",field:"durationMs"}),t.event!==void 0&&typeof t.event!="string"&&e.push({code:"INVALID_EVENT",message:"event must be a string",field:"event"})}function n0(t,e,a){if(!t.actions||!Array.isArray(t.actions)){e.push({code:"MISSING_ACTIONS",message:"sequence action requires 'actions' array",field:"actions"});return}t.actions.length===0&&a.push({code:"EMPTY_SEQUENCE",message:"sequence has no actions",suggestion:"Add at least one action to the sequence"});for(let r=0;r<t.actions.length;r++){let n=Ar(t.actions[r]);for(let o of n.errors)e.push({...o,field:`actions[${r}]${o.field?`.${o.field}`:""}`});for(let o of n.warnings)a.push(o)}}function o0(t,e,a){if(!t.actions||!Array.isArray(t.actions)){e.push({code:"MISSING_ACTIONS",message:"parallel action requires 'actions' array",field:"actions"});return}t.actions.length===0&&a.push({code:"EMPTY_PARALLEL",message:"parallel has no actions",suggestion:"Add at least one action to the parallel group"}),t.waitFor&&!["all","any"].includes(t.waitFor)&&e.push({code:"INVALID_WAIT_FOR",message:"waitFor must be 'all' or 'any'",field:"waitFor"});for(let r=0;r<t.actions.length;r++){let n=Ar(t.actions[r]);for(let o of n.errors)e.push({...o,field:`actions[${r}]${o.field?`.${o.field}`:""}`});for(let o of n.warnings)a.push(o)}}function i0(t,e,a){if(!t.url||typeof t.url!="string")e.push({code:"MISSING_URL",message:"navigate action requires 'url' property",field:"url"});else{let r=t.url.trim().toLowerCase();r.startsWith("javascript:")&&e.push({code:"DANGEROUS_URL",message:"javascript: URLs are not allowed",field:"url"}),r.startsWith("data:")&&a.push({code:"DATA_URL",message:"data: URLs may have limited support",suggestion:"Consider using a regular URL instead"})}}function s0(t,e,a){if(!t.content||typeof t.content!="object"){e.push({code:"MISSING_CONTENT",message:"Modal action requires 'content' object",field:"content"});return}if((!t.content.body||typeof t.content.body!="string")&&e.push({code:"MISSING_BODY",message:"Modal content requires 'body' property",field:"content.body"}),t.size&&!["sm","md","lg"].includes(t.size)&&e.push({code:"INVALID_SIZE",message:"Modal size must be 'sm', 'md', or 'lg'",field:"size"}),t.ctaButtons)if(!Array.isArray(t.ctaButtons))e.push({code:"INVALID_CTA_BUTTONS",message:"ctaButtons must be an array",field:"ctaButtons"});else for(let r=0;r<t.ctaButtons.length;r++){let n=t.ctaButtons[r];(!n.label||typeof n.label!="string")&&e.push({code:"MISSING_BUTTON_LABEL",message:`CTA button at index ${r} requires 'label' property`,field:`ctaButtons[${r}].label`}),(!n.actionId||typeof n.actionId!="string")&&e.push({code:"MISSING_BUTTON_ACTION_ID",message:`CTA button at index ${r} requires 'actionId' property`,field:`ctaButtons[${r}].actionId`})}}function l0(t,e,a){if((!t.tourId||typeof t.tourId!="string")&&e.push({code:"MISSING_TOUR_ID",message:"Tour action requires 'tourId' property",field:"tourId"}),!t.steps||!Array.isArray(t.steps)){e.push({code:"MISSING_STEPS",message:"Tour action requires 'steps' array",field:"steps"});return}t.steps.length===0&&e.push({code:"EMPTY_STEPS",message:"Tour must have at least one step",field:"steps"});let r=new Set;for(let n=0;n<t.steps.length;n++){let o=t.steps[n];if(!o.id||typeof o.id!="string"?e.push({code:"MISSING_STEP_ID",message:`Step at index ${n} requires 'id' property`,field:`steps[${n}].id`}):(r.has(o.id)&&e.push({code:"DUPLICATE_STEP_ID",message:`Duplicate step ID: ${o.id}`,field:`steps[${n}].id`}),r.add(o.id)),!o.action)e.push({code:"MISSING_STEP_ACTION",message:`Step at index ${n} requires 'action' property`,field:`steps[${n}].action`});else{let i=Ar(o.action);for(let s of i.errors)e.push({...s,field:`steps[${n}].action${s.field?`.${s.field}`:""}`});for(let s of i.warnings)a.push(s)}if(o.onAction)for(let[i,s]of Object.entries(o.onAction))s!=="end"&&!t.steps.some(l=>l.id===s)&&a.push({code:"UNKNOWN_TARGET_STEP",message:`Step "${o.id}" references unknown target step: ${s}`,suggestion:`Make sure step "${s}" exists in the tour`})}}var u0=new Set(["onclick","onerror","onload","onmouseover","onfocus","onblur","onchange","onsubmit","onkeydown","onkeyup","onkeypress"]),mh=5e4,gh=50;function Ar(t){let e=[],a=[];if(!t||typeof t!="object")return e.push({code:"INVALID_ACTION",message:"Action must be an object"}),{valid:!1,errors:e,warnings:a};let{kind:r}=t;if(!r||typeof r!="string")return e.push({code:"MISSING_KIND",message:"Action must have a 'kind' property"}),{valid:!1,errors:e,warnings:a};if(!Zb(r)&&r!=="core:mountWidget"){let n=xn.list();return console.error(`[ActionValidation] Unknown action kind: "${r}". Registered kinds (${n.length}): [${n.join(", ")}]. This usually means the app that provides "${r}" hasn't been activated yet, or the executor was never registered in ExecutorRegistry.`),e.push({code:"UNKNOWN_KIND",message:`Unknown action kind: ${r}`,field:"kind"}),{valid:!1,errors:e,warnings:a}}switch(r){case"overlays:highlight":case"overlays:pulse":case"navigation:scrollTo":bn(t,e,a);break;case"overlays:badge":bn(t,e,a),Xb(t,e,a);break;case"overlays:tooltip":bn(t,e,a),Kb(t,e,a);break;case"overlays:modal":s0(t,e,a);break;case"content:insertHtml":bn(t,e,a),Yb(t,e,a);break;case"content:setText":bn(t,e,a),Qb(t,e,a);break;case"content:setAttr":bn(t,e,a),Jb(t,e,a);break;case"content:addClass":case"content:removeClass":bn(t,e,a),e0(t,e,a);break;case"content:setStyle":bn(t,e,a),t0(t,e,a);break;case"core:mountWidget":a0(t,e,a);break;case"core:wait":r0(t,e,a);break;case"core:sequence":n0(t,e,a);break;case"core:parallel":o0(t,e,a);break;case"overlays:tour":l0(t,e,a);break;case"navigation:navigate":i0(t,e,a);break}return{valid:e.length===0,errors:e,warnings:a}}function bn(t,e,a){let r=t.anchorId;if(!r||typeof r!="object"){e.push({code:"MISSING_ANCHOR_ID",message:"Action requires an 'anchorId' object with a 'selector' string",field:"anchorId"});return}if(!r.selector||typeof r.selector!="string"?e.push({code:"MISSING_ANCHOR_SELECTOR",message:"anchorId requires a 'selector' string",field:"anchorId.selector"}):r.selector.length>200&&a.push({code:"LONG_ANCHOR_ID",message:"Anchor selector is unusually long",suggestion:"Consider using a shorter, more descriptive selector"}),r.route===void 0||r.route===null)e.push({code:"MISSING_ANCHOR_ROUTE",message:`anchorId requires a 'route' (string or array of strings). Use "**" for all routes.`,field:"anchorId.route"});else{let n=Array.isArray(r.route)?r.route:[r.route];for(let o of n)if(typeof o!="string"){e.push({code:"INVALID_ANCHOR_ROUTE",message:"anchorId.route must be a string or array of strings",field:"anchorId.route"});break}}}function vh(t){let e=[],a=[];if(!Array.isArray(t))return console.error("[ActionValidation] validateActions called with non-array:",typeof t),e.push({code:"INVALID_ACTIONS",message:"Actions must be an array"}),{valid:!1,errors:e,warnings:a};for(let r=0;r<t.length;r++){let n=Ar(t[r]);if(!n.valid){let o=t[r];console.error(`[ActionValidation] Action [${r}] failed validation:`,`kind="${o?.kind??"undefined"}"`,n.errors.map(i=>`${i.code}: ${i.message}`).join("; "),o)}for(let o of n.errors)e.push({...o,field:o.field?`[${r}].${o.field}`:`[${r}]`});for(let o of n.warnings)a.push({...o,suggestion:o.suggestion?`Action ${r}: ${o.suggestion}`:void 0})}return e.length>0&&console.error(`[ActionValidation] Batch validation failed: ${e.length} error(s) in ${t.length} action(s).`,e.map(r=>`${r.field??"?"}: ${r.message}`).join(" | ")),{valid:e.length===0,errors:e,warnings:a}}var f4=0;function c0(t){let{overlayRoot:e,eventBus:a,surfaces:r,anchorResolver:n,waitForAnchor:o,adaptiveId:i,executorRegistry:s=xn,subscribeNavigation:l,runtime:u}=t,c=new Map,d=new Map;function f(){return`action-${++f4}`}function h(_,L){a&&a.publish(_,L)}function S(){return{overlayRoot:e,resolveAnchor:n,waitForAnchor:o,generateId:f,publishEvent:h,adaptiveId:i,applyAction:m,subscribeEvent:a?(_,L)=>a.subscribe({names:[_]},A=>L(A.props)):void 0,subscribeNavigation:l}}async function x(_,L){if(!r)throw new Error("Surfaces provider required for core:mountWidget actions");let A=r.mount(_.slot,{type:"widget",widgetId:_.widget.widgetId,config:_.widget.props},{priority:_.widget.priority});return L.publishEvent("action.applied",{id:L.generateId(),kind:"core:mountWidget",slot:_.slot,widgetId:_.widget.widgetId}),{cleanup:()=>{A.unmount()},updateFn:I=>{if("widget"in I&&I.widget){let R=I.widget;R.props&&A.update({type:"widget",widgetId:_.widget.widgetId,config:R.props})}}}}async function b(_,L){if(_.kind==="core:mountWidget")return x(_,L);let A=s.get(_.kind);if(!A){let I="list"in s?s.list():"(list unavailable)";throw console.error(`[ActionEngine] No executor for kind="${_.kind}".`,`Registered: [${I}]`),new Error(`No executor for action kind: ${_.kind}`)}return A(_,L)}function g(_,L,A,I){if(!u)return;let R=[],H=async()=>{let E=c.get(_);if(!E)return;let D=u.evaluateSync(A).value;if(E.state==="applied"&&!D){try{await E.cleanup()}catch(F){console.error(`[ActionEngine] Error reverting conditional action ${_}:`,F)}E.state="deferred",E.cleanup=()=>{},E.updateFn=void 0,h("action.deferred",{id:_,kind:L.kind})}else if(E.state==="deferred"&&D)try{let F=S(),Z=await b(L,F);E.state="applied",E.cleanup=Z.cleanup,E.updateFn=Z.updateFn,E.appliedTs=Date.now(),h("action.applied",{id:_,kind:L.kind,anchorId:"anchorId"in L?L.anchorId:void 0})}catch(F){console.error(`[ActionEngine] Error applying deferred action ${_}:`,F),E.state="failed"}};u.context&&R.push(u.context.subscribe(H)),u.accumulator&&R.push(u.accumulator.subscribe(H)),d.set(_,R)}async function m(_){let L=Ar(_);if(!L.valid){let D=L.errors.map(F=>F.message).join("; ");throw console.error(`[ActionEngine] Validation failed for action kind="${_?.kind}":`,D,_),new Error(`Action validation failed: ${D}`)}let A=f(),I=_.triggerWhen;if(I&&u&&!u.evaluateSync(I).value){let F={id:A,action:_,adaptiveId:i,appliedTs:Date.now(),state:"deferred",cleanup:()=>{}};c.set(A,F);let Z={id:A,action:_,async revert(){let U=c.get(A);if(!U)return;let W=d.get(A);if(W){for(let ce of W)ce();d.delete(A)}U.state="reverted",c.delete(A)},isApplied(){return c.get(A)?.state==="applied"},async update(U){let W=c.get(A);if(!W||W.state!=="applied")throw new Error("Cannot update action that is not applied");if(W.updateFn)await W.updateFn(U);else throw new Error(`Action kind ${_.kind} does not support updates`)},getState(){return c.get(A)?.state??"reverted"}};return g(A,_,I,Z),Z}let R=S(),H=await b(_,R),E={id:A,action:_,adaptiveId:i,appliedTs:Date.now(),state:"applied",cleanup:H.cleanup,updateFn:H.updateFn};c.set(A,E),h("action.applied",{id:A,kind:_.kind,anchorId:"anchorId"in _?_.anchorId:void 0});let M={id:A,action:_,async revert(){let D=c.get(A);if(!D||D.state!=="applied")return;let F=d.get(A);if(F){for(let Z of F)Z();d.delete(A)}try{await D.cleanup(),D.state="reverted",h("action.reverted",{id:A,kind:_.kind})}catch(Z){console.warn(`[ActionEngine] Cleanup error for ${_.kind} (${A}), ignoring:`,Z),D.state="reverted",h("action.reverted",{id:A,kind:_.kind})}finally{c.delete(A)}},isApplied(){return c.get(A)?.state==="applied"},async update(D){let F=c.get(A);if(!F||F.state!=="applied")throw new Error("Cannot update action that is not applied");if(F.updateFn)await F.updateFn(D);else throw new Error(`Action kind ${_.kind} does not support updates`)},getState(){return c.get(A)?.state??"reverted"}};return I&&u&&g(A,_,I,M),M}async function y(_){console.log(`[ActionEngine] applyBatch: ${_.length} action(s)`,_.map(E=>E.kind).join(", "));let L=vh(_);if(!L.valid){let E=L.errors.map(M=>M.message).join("; ");throw console.error(`[ActionEngine] Batch validation FAILED for ${_.length} action(s):`,E,`
501
+ `)).length,n=0;n<r;n++){var i=t.charCodeAt(n),s=null;i<128?a++:s=i>127&&i<2048?String.fromCharCode(i>>6|192,63&i|128):String.fromCharCode(i>>12|224,i>>6&63|128,63&i|128),cr(s)||(a>e&&(o+=t.substring(e,a)),o+=s,e=a=n+1)}return a>e&&(o+=t.substring(e,t.length)),o},QH=!!Sx||!!bx,rE="text/plain",oh=function(t,e,a){var r;a===void 0&&(a=!0);var[n,o]=t.split("?"),i=j({},e),s=(r=o?.split("&").map((u=>{var c,[d,f]=u.split("="),h=a&&(c=i[d])!==null&&c!==void 0?c:f;return delete i[d],d+"="+h})))!==null&&r!==void 0?r:[],l=LH(i);return l&&s.push(l),n+"?"+s.join("&")},dc=(t,e)=>JSON.stringify(t,((a,r)=>typeof r=="bigint"?r.toString():r),e),px=t=>{var{data:e,compression:a}=t;if(e){if(a===mn.GZipJS){var r=KH((function(l,u){var c=l.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(l);for(var d=new ja(l.length+(l.length>>>1)),f=0,h=function(g){d[f++]=g},S=0;S<c;++S){if(f+5>d.length){var x=new ja(f+8+(c-S<<1));x.set(d),d=x}var b=l.charCodeAt(S);b<128||u?h(b):b<2048?(h(192|b>>>6),h(128|63&b)):b>55295&&b<57344?(h(240|(b=65536+(1047552&b)|1023&l.charCodeAt(++S))>>>18),h(128|b>>>12&63),h(128|b>>>6&63),h(128|63&b)):(h(224|b>>>12),h(128|b>>>6&63),h(128|63&b))}return gT(d,0,f)})(dc(e)),{mtime:0}),n=new Blob([r],{type:rE});return{contentType:rE,body:n,estimatedSize:n.size}}if(a===mn.Base64){var o=(function(l){var u,c,d,f,h,S="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",x=0,b=0,g="",m=[];if(!l)return l;l=YH(l);do u=(h=l.charCodeAt(x++)<<16|l.charCodeAt(x++)<<8|l.charCodeAt(x++))>>18&63,c=h>>12&63,d=h>>6&63,f=63&h,m[b++]=S.charAt(u)+S.charAt(c)+S.charAt(d)+S.charAt(f);while(x<l.length);switch(g=m.join(""),l.length%3){case 1:g=g.slice(0,-2)+"==";break;case 2:g=g.slice(0,-1)+"="}return g})(dc(e)),i=(l=>"data="+encodeURIComponent(typeof l=="string"?l:dc(l)))(o);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}var s=dc(e);return{contentType:"application/json",body:s,estimatedSize:new Blob([s]).size}}},qp=[];bx&&qp.push({transport:"fetch",method:t=>{var e,a,{contentType:r,body:n,estimatedSize:o}=(e=px(t))!==null&&e!==void 0?e:{},i=new Headers;Be(t.headers,(function(c,d){i.append(d,c)})),r&&i.append("Content-Type",r);var s=t.url,l=null;if(CA){var u=new CA;l={signal:u.signal,timeout:setTimeout((()=>u.abort()),t.timeout)}}bx(s,j({method:t?.method||"GET",headers:i,keepalive:t.method==="POST"&&(o||0)<52428.8,body:n,signal:(a=l)==null?void 0:a.signal},t.fetchOptions)).then((c=>c.text().then((d=>{var f={statusCode:c.status,text:d};if(c.status===200)try{f.json=JSON.parse(d)}catch(h){$.error(h)}t.callback==null||t.callback(f)})))).catch((c=>{$.error(c),t.callback==null||t.callback({statusCode:0,text:c})})).finally((()=>l?clearTimeout(l.timeout):null))}}),Sx&&qp.push({transport:"XHR",method:t=>{var e,a=new Sx;a.open(t.method||"GET",t.url,!0);var{contentType:r,body:n}=(e=px(t))!==null&&e!==void 0?e:{};Be(t.headers,(function(o,i){a.setRequestHeader(i,o)})),r&&a.setRequestHeader("Content-Type",r),t.timeout&&(a.timeout=t.timeout),t.disableXHRCredentials||(a.withCredentials=!0),a.onreadystatechange=()=>{if(a.readyState===4){var o={statusCode:a.status,text:a.responseText};if(a.status===200)try{o.json=JSON.parse(a.responseText)}catch{}t.callback==null||t.callback(o)}},a.send(n)}}),ka!=null&&ka.sendBeacon&&qp.push({transport:"sendBeacon",method:t=>{var e=oh(t.url,{beacon:"1"});try{var a,{contentType:r,body:n}=(a=px(t))!==null&&a!==void 0?a:{},o=typeof n=="string"?new Blob([n],{type:r}):n;ka.sendBeacon(e,o)}catch{}}});var ih=function(t,e){if(!(function(a){try{new RegExp(a)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function nE(t,e,a){return dc({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:a})}var vT={exact:(t,e)=>e.some((a=>t.some((r=>a===r)))),is_not:(t,e)=>e.every((a=>t.every((r=>a!==r)))),regex:(t,e)=>e.some((a=>t.some((r=>ih(a,r))))),not_regex:(t,e)=>e.every((a=>t.every((r=>!ih(a,r))))),icontains:(t,e)=>e.map(Up).some((a=>t.map(Up).some((r=>a.includes(r))))),not_icontains:(t,e)=>e.map(Up).every((a=>t.map(Up).every((r=>!a.includes(r))))),gt:(t,e)=>e.some((a=>{var r=parseFloat(a);return!isNaN(r)&&t.some((n=>r>parseFloat(n)))})),lt:(t,e)=>e.some((a=>{var r=parseFloat(a);return!isNaN(r)&&t.some((n=>r<parseFloat(n)))}))},Up=t=>t.toLowerCase();function yT(t,e){return!t||Object.entries(t).every((a=>{var[r,n]=a,o=e?.[r];if(V(o)||cr(o))return!1;var i=[String(o)],s=vT[n.operator];return!!s&&s(n.values,i)}))}var hx=et("[Error tracking]"),cb=class{constructor(e){var a,r;this.Zt=[],this.ti=new Ex([new Rx,new Fx,new Ox,new Mx,new Px,new Bx,new Dx,new Nx],sH()),this._instance=e,this.Zt=(a=(r=this._instance.persistence)==null?void 0:r.get_property(Ux))!==null&&a!==void 0?a:[]}onRemoteConfig(e){var a,r,n,o=(a=(r=e.errorTracking)==null?void 0:r.suppressionRules)!==null&&a!==void 0?a:[],i=(n=e.errorTracking)==null?void 0:n.captureExtensionExceptions;this.Zt=o,this._instance.persistence&&this._instance.persistence.register({[Ux]:this.Zt,[PA]:i})}get ii(){var e,a=!!this._instance.get_property(PA),r=this._instance.config.error_tracking.captureExtensionExceptions;return(e=r??a)!==null&&e!==void 0&&e}buildProperties(e,a){return this.ti.buildFromUnknown(e,{syntheticException:a?.syntheticException,mechanism:{handled:a?.handled}})}sendExceptionEvent(e){var a=e.$exception_list;if(this.ei(a)){if(this.ri(a))return void hx.info("Skipping exception capture because a suppression rule matched");if(!this.ii&&this.si(a))return void hx.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ni(a))return void hx.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent"})}ri(e){if(e.length===0)return!1;var a=e.reduce(((r,n)=>{var{type:o,value:i}=n;return vt(o)&&o.length>0&&r.$exception_types.push(o),vt(i)&&i.length>0&&r.$exception_values.push(i),r}),{$exception_types:[],$exception_values:[]});return this.Zt.some((r=>{var n=r.values.map((o=>{var i,s=vT[o.operator],l=Ce(o.value)?o.value:[o.value],u=(i=a[o.key])!==null&&i!==void 0?i:[];return l.length>0&&s(l,u)}));return r.type==="OR"?n.some(Boolean):n.every(Boolean)}))}si(e){return e.flatMap((a=>{var r,n;return(r=(n=a.stacktrace)==null?void 0:n.frames)!==null&&r!==void 0?r:[]})).some((a=>a.filename&&a.filename.startsWith("chrome-extension://")))}ni(e){if(e.length>0){var a,r,n,o,i=(a=(r=e[0].stacktrace)==null?void 0:r.frames)!==null&&a!==void 0?a:[],s=i[i.length-1];return(n=s==null||(o=s.filename)==null?void 0:o.includes("posthog.com/static"))!==null&&n!==void 0&&n}return!1}ei(e){return!ge(e)&&Ce(e)}},La=et("[FeatureFlags]"),ac=et("[FeatureFlags]",{debugEnabled:!0}),mx="$active_feature_flags",$s="$override_feature_flags",oE="$feature_flag_payloads",rc="$override_feature_flag_payloads",iE="$feature_flag_request_id",sE="$feature_flag_evaluated_at",lE=t=>{var e={};for(var[a,r]of zp(t||{}))r&&(e[a]=r);return e},JH=t=>{var e=t.flags;return e?(t.featureFlags=Object.fromEntries(Object.keys(e).map((a=>{var r;return[a,(r=e[a].variant)!==null&&r!==void 0?r:e[a].enabled]}))),t.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter((a=>e[a].enabled)).filter((a=>{var r;return(r=e[a].metadata)==null?void 0:r.payload})).map((a=>{var r;return[a,(r=e[a].metadata)==null?void 0:r.payload]})))):La.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),t},e4=(function(t){return t.FeatureFlags="feature_flags",t.Recordings="recordings",t})({}),db=class{constructor(e){this.oi=!1,this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.ci=!1,this._instance=e,this.featureFlagEventHandlers=[]}fi(){var e,a=(e=this._instance.config.evaluation_contexts)!==null&&e!==void 0?e:this._instance.config.evaluation_environments;return!this._instance.config.evaluation_environments||this._instance.config.evaluation_contexts||this.ci||(La.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.ci=!0),a!=null&&a.length?a.filter((r=>{var n=r&&typeof r=="string"&&r.trim().length>0;return n||La.error("Invalid evaluation context found:",r,"Expected non-empty string"),n})):[]}pi(){return this.fi().length>0}flags(){if(this._instance.config.__preview_remote_config)this.di=!0;else{var e=!this.gi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.mi({disableFlags:e})}}get hasLoadedFlags(){return this.ai}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(zx),a=this._instance.get_property($s),r=this._instance.get_property(rc);if(!r&&!a)return e||{};var n=ot({},e||{}),o=[...new Set([...Object.keys(r||{}),...Object.keys(a||{})])];for(var i of o){var s,l,u=n[i],c=a?.[i],d=V(c)?(s=u?.enabled)!==null&&s!==void 0&&s:!!c,f=V(c)?u.variant:typeof c=="string"?c:void 0,h=r?.[i],S=j({},u,{enabled:d,variant:d?f??u?.variant:void 0});d!==u?.enabled&&(S.original_enabled=u?.enabled),f!==u?.variant&&(S.original_variant=u?.variant),h&&(S.metadata=j({},u?.metadata,{payload:h,original_payload:u==null||(l=u.metadata)==null?void 0:l.payload})),n[i]=S}return this.oi||(La.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:r,finalDetails:n}),this.oi=!0),n}getFlagVariants(){var e=this._instance.get_property(Ks),a=this._instance.get_property($s);if(!a)return e||{};for(var r=ot({},e),n=Object.keys(a),o=0;o<n.length;o++)r[n[o]]=a[n[o]];return this.oi||(La.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:a,finalFlags:r}),this.oi=!0),r}getFlagPayloads(){var e=this._instance.get_property(oE),a=this._instance.get_property(rc);if(!a)return e||{};for(var r=ot({},e||{}),n=Object.keys(a),o=0;o<n.length;o++)r[n[o]]=a[n[o]];return this.oi||(La.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:a,finalPayloads:r}),this.oi=!0),r}reloadFeatureFlags(){this.ui||this._instance.config.advanced_disable_feature_flags||this.gi||(this.gi=setTimeout((()=>{this.mi()}),5))}bi(){clearTimeout(this.gi),this.gi=void 0}ensureFlagsLoaded(){this.ai||this.li||this.gi||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.ui=e}mi(e){var a;if(this.bi(),!this._instance.M())if(this.li)this.hi=!0;else{var r=this._instance.config.token,n=this._instance.get_property("$device_id"),o={token:r,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:j({},((a=this._instance.persistence)==null?void 0:a.get_initial_props())||{},this._instance.get_property(cc)||{}),group_properties:this._instance.get_property(wi)};cr(n)||V(n)||(o.$device_id=n),(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(o.disable_flags=!0),this.pi()&&(o.evaluation_contexts=this.fi());var i=this._instance.config.__preview_remote_config,s=i?"/flags/?v=2":"/flags/?v=2&config=true",l=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",u=this._instance.requestRouter.endpointFor("flags",s+l);i&&(o.timezone=fT()),this.li=!0,this._instance._send_request({method:"POST",url:u,data:o,compression:this._instance.config.disable_compression?void 0:mn.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:c=>{var d,f,h=!0;if(c.statusCode===200&&(this.hi||(this.$anon_distinct_id=void 0),h=!1),this.li=!1,this.di||(this.di=!0,this._instance.yi((f=c.json)!==null&&f!==void 0?f:{})),!o.disable_flags||this.hi)if(this.vi=!h,c.json&&(d=c.json.quotaLimited)!=null&&d.includes(e4.FeatureFlags))La.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more.");else{var S;o.disable_flags||this.receivedFeatureFlags((S=c.json)!==null&&S!==void 0?S:{},h),this.hi&&(this.hi=!1,this.mi())}}})}}getFeatureFlag(e,a){var r;if(a===void 0&&(a={}),this.ai||this.getFlags()&&this.getFlags().length>0){var n=this.getFeatureFlagResult(e,a);return(r=n?.variant)!==null&&r!==void 0?r:n?.enabled}La.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){var a=this.getFeatureFlagResult(e,{send_event:!1});return a?.payload}getFeatureFlagResult(e,a){if(a===void 0&&(a={}),this.ai||this.getFlags()&&this.getFlags().length>0){var r=this.getFlagVariants(),n=e in r,o=r[e],i=this.getFlagPayloads()[e],s=String(o),l=this._instance.get_property(iE)||void 0,u=this._instance.get_property(sE)||void 0,c=this._instance.get_property(Wp)||{};if((a.send_event||!("send_event"in a))&&(!(e in c)||!c[e].includes(s))){var d,f,h,S,x,b,g,m,y;Ce(c[e])?c[e].push(s):c[e]=[s],(d=this._instance.persistence)==null||d.register({[Wp]:c});var v=this.getFeatureFlagDetails(e),C={$feature_flag:e,$feature_flag_response:o,$feature_flag_payload:i||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((f=this._instance.config.bootstrap)==null||(f=f.featureFlags)==null?void 0:f[e])||null,$feature_flag_bootstrapped_payload:((h=this._instance.config.bootstrap)==null||(h=h.featureFlagPayloads)==null?void 0:h[e])||null,$used_bootstrap_value:!this.vi};V(v==null||(S=v.metadata)==null?void 0:S.version)||(C.$feature_flag_version=v.metadata.version);var w,_=(x=v==null||(b=v.reason)==null?void 0:b.description)!==null&&x!==void 0?x:v==null||(g=v.reason)==null?void 0:g.code;_&&(C.$feature_flag_reason=_),v!=null&&(m=v.metadata)!=null&&m.id&&(C.$feature_flag_id=v.metadata.id),V(v?.original_variant)&&V(v?.original_enabled)||(C.$feature_flag_original_response=V(v.original_variant)?v.original_enabled:v.original_variant),v!=null&&(y=v.metadata)!=null&&y.original_payload&&(C.$feature_flag_original_payload=v==null||(w=v.metadata)==null?void 0:w.original_payload),this._instance.capture("$feature_flag_called",C)}if(n){var L=i;if(!V(i))try{L=JSON.parse(i)}catch{}return{key:e,enabled:!!o,variant:typeof o=="string"?o:void 0,payload:L}}}else La.warn('getFeatureFlagResult for key "'+e+`" failed. Feature flags didn't load in time.`)}getRemoteConfigPayload(e,a){var r=this._instance.config.token,n={distinct_id:this._instance.get_distinct_id(),token:r};this.pi()&&(n.evaluation_contexts=this.fi()),this._instance._send_request({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2&config=true"),data:n,compression:this._instance.config.disable_compression?void 0:mn.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:o=>{var i,s=(i=o.json)==null?void 0:i.featureFlagPayloads;a(s?.[e]||void 0)}})}isFeatureEnabled(e,a){if(a===void 0&&(a={}),this.ai||this.getFlags()&&this.getFlags().length>0){var r=this.getFeatureFlag(e,a);return V(r)?void 0:!!r}La.warn('isFeatureEnabled for key "'+e+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((a=>a!==e))}receivedFeatureFlags(e,a){if(this._instance.persistence){this.ai=!0;var r=this.getFlagVariants(),n=this.getFlagPayloads(),o=this.getFlagsWithDetails();(function(i,s,l,u,c){l===void 0&&(l={}),u===void 0&&(u={}),c===void 0&&(c={});var d=JH(i),f=d.flags,h=d.featureFlags,S=d.featureFlagPayloads;if(h){var x=i.requestId,b=i.evaluatedAt;if(Ce(h)){La.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var g={};if(h)for(var m=0;m<h.length;m++)g[h[m]]=!0;s&&s.register({[mx]:h,[Ks]:g})}else{var y=h,v=S,C=f;if(i.errorsWhileComputingFlags)if(f){var w=new Set(Object.keys(f).filter((_=>{var L;return!((L=f[_])!=null&&L.failed)})));y=j({},l,Object.fromEntries(Object.entries(y).filter((_=>{var[L]=_;return w.has(L)})))),v=j({},u,Object.fromEntries(Object.entries(v||{}).filter((_=>{var[L]=_;return w.has(L)})))),C=j({},c,Object.fromEntries(Object.entries(C||{}).filter((_=>{var[L]=_;return w.has(L)}))))}else y=j({},l,y),v=j({},u,v),C=j({},c,C);s&&s.register(j({[mx]:Object.keys(lE(y)),[Ks]:y||{},[oE]:v||{},[zx]:C||{}},x?{[iE]:x}:{},b?{[sE]:b}:{}))}}})(e,this._instance.persistence,r,n,o),this.wi(a)}}override(e,a){a===void 0&&(a=!1),La.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:a})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return La.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister($s),this._instance.persistence.unregister(rc),this.wi(),ac.info("All overrides cleared");if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var a,r=e;if(this.oi=!!((a=r.suppressWarning)!==null&&a!==void 0&&a),"flags"in r){if(r.flags===!1)this._instance.persistence.unregister($s),ac.info("Flag overrides cleared");else if(r.flags){if(Ce(r.flags)){for(var n={},o=0;o<r.flags.length;o++)n[r.flags[o]]=!0;this._instance.persistence.register({[$s]:n})}else this._instance.persistence.register({[$s]:r.flags});ac.info("Flag overrides set",{flags:r.flags})}}return"payloads"in r&&(r.payloads===!1?(this._instance.persistence.unregister(rc),ac.info("Payload overrides cleared")):r.payloads&&(this._instance.persistence.register({[rc]:r.payloads}),ac.info("Payload overrides set",{payloads:r.payloads}))),void this.wi()}this.wi()}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.ai){var{flags:a,flagVariants:r}=this.xi();e(a,r)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,a,r){var n,o=(this._instance.get_property(uc)||[]).find((u=>u.flagKey===e)),i={["$feature_enrollment/"+e]:a},s={$feature_flag:e,$feature_enrollment:a,$set:i};o&&(s.$early_access_feature_name=o.name),r&&(s.$feature_enrollment_stage=r),this._instance.capture("$feature_enrollment_update",s),this.setPersonPropertiesForFlags(i,!1);var l=j({},this.getFlagVariants(),{[e]:a});(n=this._instance.persistence)==null||n.register({[mx]:Object.keys(lE(l)),[Ks]:l}),this.wi()}getEarlyAccessFeatures(e,a,r){a===void 0&&(a=!1);var n=this._instance.get_property(uc),o=r?"&"+r.map((i=>"stage="+i)).join("&"):"";if(n&&!a)return e(n);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+o),method:"GET",callback:i=>{var s,l;if(i.json){var u=i.json.earlyAccessFeatures;return(s=this._instance.persistence)==null||s.unregister(uc),(l=this._instance.persistence)==null||l.register({[uc]:u}),e(u)}}})}xi(){var e=this.getFlags(),a=this.getFlagVariants();return{flags:e.filter((r=>a[r])),flagVariants:Object.keys(a).filter((r=>a[r])).reduce(((r,n)=>(r[n]=a[n],r)),{})}}wi(e){var{flags:a,flagVariants:r}=this.xi();this.featureFlagEventHandlers.forEach((n=>n(a,r,{errorsLoading:e})))}setPersonPropertiesForFlags(e,a){a===void 0&&(a=!0);var r=this._instance.get_property(cc)||{};this._instance.register({[cc]:j({},r,e)}),a&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(cc)}setGroupPropertiesForFlags(e,a){a===void 0&&(a=!0);var r=this._instance.get_property(wi)||{};Object.keys(r).length!==0&&Object.keys(r).forEach((n=>{r[n]=j({},r[n],e[n]),delete e[n]})),this._instance.register({[wi]:j({},r,e)}),a&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var a=this._instance.get_property(wi)||{};this._instance.register({[wi]:j({},a,{[e]:{}})})}else this._instance.unregister(wi)}reset(){this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.$anon_distinct_id=void 0,this.bi(),this.oi=!1}},t4=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],mc=class{constructor(e,a){this.R=e,this.props={},this.Ei=!1,this.$i=(r=>{var n="";return r.token&&(n=r.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),r.persistence_name?"ph_"+r.persistence_name:"ph_"+n+"_posthog"})(e),this.Y=this.Si(e),this.load(),e.debug&&$.info("Persistence loaded",e.persistence,j({},this.props)),this.update_config(e,e,a),this.save()}isDisabled(){return!!this.ki}Si(e){t4.indexOf(e.persistence.toLowerCase())===-1&&($.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var a=(function(n){n===void 0&&(n=[]);var o=[...MH,...n];return j({},Ke,{W:function(i){try{var s={};try{s=kr.W(i)||{}}catch{}var l=ot(s,JSON.parse(Ke.q(i)||"{}"));return Ke.G(i,l),l}catch{}return null},G:function(i,s,l,u,c,d){try{Ke.G(i,s,void 0,void 0,d);var f={};o.forEach((h=>{s[h]&&(f[h]=s[h])})),Object.keys(f).length&&kr.G(i,f,l,u,c,d)}catch(h){Ke.B(h)}},V:function(i,s){try{T?.localStorage.removeItem(i),kr.V(i,s)}catch(l){Ke.B(l)}}})})(e.cookie_persisted_properties||[]),r=e.persistence.toLowerCase();return r==="localstorage"&&Ke.H()?Ke:r==="localstorage+cookie"&&a.H()?a:r==="sessionstorage"&&Dt.H()?Dt:r==="memory"?OH:r==="cookie"?kr:a.H()?a:kr}properties(){var e={};return Be(this.props,(function(a,r){if(r===Ks&&gt(a))for(var n=Object.keys(a),o=0;o<n.length;o++)e["$feature/"+n[o]]=a[n[o]];else s=r,l=!1,(cr(i=mH)?l:_A&&i.indexOf===_A?i.indexOf(s)!=-1:(Be(i,(function(u){if(l||(l=u===s))return jp})),l))||(e[r]=a);var i,s,l})),e}load(){if(!this.ki){var e=this.Y.W(this.$i);e&&(this.props=ot({},e))}}save(){this.ki||this.Y.G(this.$i,this.props,this.Pi,this.Ti,this.Ii,this.R.debug)}remove(){this.Y.V(this.$i,!1),this.Y.V(this.$i,!0)}clear(){this.remove(),this.props={}}register_once(e,a,r){if(gt(e)){V(a)&&(a="None"),this.Pi=V(r)?this.Ci:r;var n=!1;if(Be(e,((o,i)=>{this.props.hasOwnProperty(i)&&this.props[i]!==a||(this.props[i]=o,n=!0)})),n)return this.save(),!0}return!1}register(e,a){if(gt(e)){this.Pi=V(a)?this.Ci:a;var r=!1;if(Be(e,((n,o)=>{e.hasOwnProperty(o)&&this.props[o]!==n&&(this.props[o]=n,r=!0)})),r)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.Ei){var e=iT(this.R.custom_campaign_params,this.R.mask_personal_data_properties,this.R.custom_personal_data_properties);Xs(Nb(e))||this.register(e),this.Ei=!0}}update_search_keyword(){var e;this.register((e=q?.referrer)?lT(e):{})}update_referrer_info(){var e;this.register_once({$referrer:uT(),$referring_domain:q!=null&&q.referrer&&((e=Qp(q.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[jx]||this.props[Gx]||this.register_once({[Zp]:cT(this.R.mask_personal_data_properties,this.R.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};Be([Gx,jx],(i=>{var s=this.props[i];s&&Be(s,(function(l,u){e["$initial_"+_x(u)]=l}))}));var a,r,n=this.props[Zp];if(n){var o=(a=dT(n),r={},Be(a,(function(i,s){r["$initial_"+_x(s)]=i})),r);ot(e,o)}return e}safe_merge(e){return Be(this.props,(function(a,r){r in e||(e[r]=a)})),e}update_config(e,a,r){if(this.Ci=this.Pi=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==a.persistence||!((i,s)=>{if(i.length!==s.length)return!1;var l=[...i].sort(),u=[...s].sort();return l.every(((c,d)=>c===u[d]))})(e.cookie_persisted_properties||[],a.cookie_persisted_properties||[])){var n=this.Si(e),o=this.props;this.clear(),this.Y=n,this.props=o,this.save()}}set_disabled(e){this.ki=e,this.ki?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ti&&(this.Ti=e,this.remove(),this.save())}set_secure(e){e!==this.Ii&&(this.Ii=e,this.remove(),this.save())}set_event_timer(e,a){var r=this.props[lc]||{};r[e]=a,this.props[lc]=r,this.save()}remove_event_timer(e){var a=(this.props[lc]||{})[e];return V(a)||(delete this.props[lc][e],this.save()),a}get_property(e){return this.props[e]}set_property(e,a){this.props[e]=a,this.save()}},uE=et("[Product Tours]"),gx="ph_product_tours",fb=class{constructor(e){this.Ri=null,this.Fi=null,this._instance=e}onRemoteConfig(e){this._instance.persistence&&this._instance.persistence.register({[FA]:!(e==null||!e.productTours)}),this.loadIfEnabled()}loadIfEnabled(){var e,a;this.Ri||(e=this._instance).config.disable_product_tours||(a=e.persistence)==null||!a.get_property(FA)||this.it((()=>this.Oi()))}it(e){var a,r;(a=Q.__PosthogExtensions__)!=null&&a.generateProductTours?e():(r=Q.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"product-tours",(n=>{n?uE.error("Could not load product tours script",n):e()}))}Oi(){var e;!this.Ri&&(e=Q.__PosthogExtensions__)!=null&&e.generateProductTours&&(this.Ri=Q.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,a){if(a===void 0&&(a=!1),!Ce(this.Fi)||a){var r=this._instance.persistence;if(r){var n=r.props[gx];if(Ce(n)&&!a)return this.Fi=n,void e(n,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:o=>{var i=o.statusCode;if(i!==200||!o.json){var s="Product Tours API could not be loaded, status: "+i;return uE.error(s),void e([],{isLoaded:!1,error:s})}var l=Ce(o.json.product_tours)?o.json.product_tours:[];this.Fi=l,r&&r.register({[gx]:l}),e(l,{isLoaded:!0})}})}else e(this.Fi,{isLoaded:!0})}getActiveProductTours(e){ge(this.Ri)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.Ri.getActiveProductTours(e)}showProductTour(e){var a;(a=this.Ri)==null||a.showTourById(e)}previewTour(e){this.Ri?this.Ri.previewTour(e):this.it((()=>{var a;this.Oi(),(a=this.Ri)==null||a.previewTour(e)}))}dismissProductTour(){var e;(e=this.Ri)==null||e.dismissTour("user_clicked_skip")}nextStep(){var e;(e=this.Ri)==null||e.nextStep()}previousStep(){var e;(e=this.Ri)==null||e.previousStep()}clearCache(){var e;this.Fi=null,(e=this._instance.persistence)==null||e.unregister(gx)}resetTour(e){var a;(a=this.Ri)==null||a.resetTour(e)}resetAllTours(){var e;(e=this.Ri)==null||e.resetAllTours()}cancelPendingTour(e){var a;(a=this.Ri)==null||a.cancelPendingTour(e)}},nc=(function(t){return t.Activation="events",t.Cancellation="cancelEvents",t})({}),L8=(function(t){return t.Button="button",t.Tab="tab",t.Selector="selector",t})({}),k8=(function(t){return t.TopLeft="top_left",t.TopRight="top_right",t.TopCenter="top_center",t.MiddleLeft="middle_left",t.MiddleRight="middle_right",t.MiddleCenter="middle_center",t.Left="left",t.Center="center",t.Right="right",t.NextToTrigger="next_to_trigger",t})({}),I8=(function(t){return t.Top="top",t.Left="left",t.Right="right",t.Bottom="bottom",t})({}),vx=(function(t){return t.Popover="popover",t.API="api",t.Widget="widget",t.ExternalSurvey="external_survey",t})({}),A8=(function(t){return t.Open="open",t.MultipleChoice="multiple_choice",t.SingleChoice="single_choice",t.Rating="rating",t.Link="link",t})({}),E8=(function(t){return t.NextQuestion="next_question",t.End="end",t.ResponseBased="response_based",t.SpecificQuestion="specific_question",t})({}),T8=(function(t){return t.Once="once",t.Recurring="recurring",t.Always="always",t})({}),fc=(function(t){return t.SHOWN="survey shown",t.DISMISSED="survey dismissed",t.SENT="survey sent",t.ABANDONED="survey abandoned",t})({}),yx=(function(t){return t.SURVEY_ID="$survey_id",t.SURVEY_NAME="$survey_name",t.SURVEY_RESPONSE="$survey_response",t.SURVEY_ITERATION="$survey_iteration",t.SURVEY_ITERATION_START_DATE="$survey_iteration_start_date",t.SURVEY_PARTIALLY_COMPLETED="$survey_partially_completed",t.SURVEY_SUBMISSION_ID="$survey_submission_id",t.SURVEY_QUESTIONS="$survey_questions",t.SURVEY_COMPLETED="$survey_completed",t.PRODUCT_TOUR_ID="$product_tour_id",t.SURVEY_LAST_SEEN_DATE="$survey_last_seen_date",t})({}),pb=(function(t){return t.Popover="popover",t.Inline="inline",t})({}),Oe=et("[Surveys]"),xT="seenSurvey_",a4=(t,e)=>{var a="$survey_"+e+"/"+t.id;return t.current_iteration&&t.current_iteration>0&&(a="$survey_"+e+"/"+t.id+"/"+t.current_iteration),a},cE=t=>((e,a)=>{var r=""+e+a.id;return a.current_iteration&&a.current_iteration>0&&(r=""+e+a.id+"_"+a.current_iteration),r})(xT,t),r4=[vx.Popover,vx.Widget,vx.API],n4={ignoreConditions:!1,ignoreDelay:!1,displayType:pb.Popover},_c=class{constructor(){this.Mi={},this.Mi={}}on(e,a){return this.Mi[e]||(this.Mi[e]=[]),this.Mi[e].push(a),()=>{this.Mi[e]=this.Mi[e].filter((r=>r!==a))}}emit(e,a){for(var r of this.Mi[e]||[])r(a);for(var n of this.Mi["*"]||[])n(e,a)}};function js(t,e,a){if(ge(t))return!1;switch(a){case"exact":return t===e;case"contains":var r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}var hb=class{constructor(e){this.Ai=new _c,this.ji=(a,r)=>this.Di(a,r)&&this.Li(a,r)&&this.Ni(a,r)&&this.Ui(a,r),this.Di=(a,r)=>r==null||!r.event||a?.event===r?.event,this._instance=e,this.zi=new Set,this.Hi=new Set}init(){var e;if(!V((e=this._instance)==null?void 0:e._addCaptureHook)){var a;(a=this._instance)==null||a._addCaptureHook(((r,n)=>{this.on(r,n)}))}}register(e){var a,r;if(!V((a=this._instance)==null?void 0:a._addCaptureHook)&&(e.forEach((i=>{var s,l;(s=this.Hi)==null||s.add(i),(l=i.steps)==null||l.forEach((u=>{var c;(c=this.zi)==null||c.add(u?.event||"")}))})),(r=this._instance)!=null&&r.autocapture)){var n,o=new Set;e.forEach((i=>{var s;(s=i.steps)==null||s.forEach((l=>{l!=null&&l.selector&&o.add(l?.selector)}))})),(n=this._instance)==null||n.autocapture.setElementSelectors(o)}}on(e,a){var r;a!=null&&e.length!=0&&(this.zi.has(e)||this.zi.has(a?.event))&&this.Hi&&((r=this.Hi)==null?void 0:r.size)>0&&this.Hi.forEach((n=>{this.Bi(a,n)&&this.Ai.emit("actionCaptured",n.name)}))}qi(e){this.onAction("actionCaptured",(a=>e(a)))}Bi(e,a){if(a?.steps==null)return!1;for(var r of a.steps)if(this.ji(e,r))return!0;return!1}onAction(e,a){return this.Ai.on(e,a)}Li(e,a){if(a!=null&&a.url){var r,n=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!n||typeof n!="string"||!js(n,a.url,a.url_matching||"contains"))return!1}return!0}Ni(e,a){return!!this.Wi(e,a)&&!!this.Gi(e,a)&&!!this.Vi(e,a)}Wi(e,a){var r;if(a==null||!a.href)return!0;var n=this.Ji(e);if(n.length>0)return n.some((s=>js(s.href,a.href,a.href_matching||"exact")));var o,i=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!i&&js((o=i.match(/(?::|")href="(.*?)"/))?o[1]:"",a.href,a.href_matching||"exact")}Gi(e,a){var r;if(a==null||!a.text)return!0;var n=this.Ji(e);if(n.length>0)return n.some((u=>js(u.text,a.text,a.text_matching||"exact")||js(u.$el_text,a.text,a.text_matching||"exact")));var o,i,s,l=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(o=(function(u){for(var c,d=[],f=/(?::|")text="(.*?)"/g;!ge(c=f.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),i=a.text,s=a.text_matching||"exact",o.some((u=>js(u,i,s))))}Vi(e,a){var r,n;if(a==null||!a.selector)return!0;var o=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(o!=null&&o.includes(a.selector))return!0;var i=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";if(a.selector_regex&&i)try{return new RegExp(a.selector_regex).test(i)}catch{return!1}return!1}Ji(e){var a;return(e==null||(a=e.properties)==null?void 0:a.$elements)==null?[]:e?.properties.$elements}Ui(e,a){return a==null||!a.properties||a.properties.length===0||yT(a.properties.reduce(((r,n)=>{var o=Ce(n.value)?n.value.map(String):n.value!=null?[String(n.value)]:[];return r[n.key]={values:o,operator:n.operator||"exact"},r}),{}),e?.properties)}},mb=class{constructor(e){this._instance=e,this.Ki=new Map,this.Yi=new Map,this.Xi=new Map}Qi(e,a){return!!e&&yT(e.propertyFilters,a?.properties)}Zi(e,a){var r=new Map;return e.forEach((n=>{var o;(o=n.conditions)==null||(o=o[a])==null||(o=o.values)==null||o.forEach((i=>{if(i!=null&&i.name){var s=r.get(i.name)||[];s.push(n.id),r.set(i.name,s)}}))})),r}te(e,a,r){var n=(r===nc.Activation?this.Ki:this.Yi).get(e),o=[];return this.ie((i=>{o=i.filter((s=>n?.includes(s.id)))})),o.filter((i=>{var s,l=(s=i.conditions)==null||(s=s[r])==null||(s=s.values)==null?void 0:s.find((u=>u.name===e));return this.Qi(l,a)}))}register(e){var a;V((a=this._instance)==null?void 0:a._addCaptureHook)||(this.ee(e),this.re(e))}re(e){var a=e.filter((r=>{var n,o;return((n=r.conditions)==null?void 0:n.actions)&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0}));a.length!==0&&(this.se==null&&(this.se=new hb(this._instance),this.se.init(),this.se.qi((r=>{this.onAction(r)}))),a.forEach((r=>{var n,o,i,s,l;r.conditions&&(n=r.conditions)!=null&&n.actions&&(o=r.conditions)!=null&&(o=o.actions)!=null&&o.values&&((i=r.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0&&((s=this.se)==null||s.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.Xi.get(u.name);c&&c.push(r.id),this.Xi.set(u.name,c||[r.id])}})))})))}ee(e){var a,r=e.filter((o=>{var i,s;return((i=o.conditions)==null?void 0:i.events)&&((s=o.conditions)==null||(s=s.events)==null||(s=s.values)==null?void 0:s.length)>0})),n=e.filter((o=>{var i,s;return((i=o.conditions)==null?void 0:i.cancelEvents)&&((s=o.conditions)==null||(s=s.cancelEvents)==null||(s=s.values)==null?void 0:s.length)>0}));(r.length!==0||n.length!==0)&&((a=this._instance)==null||a._addCaptureHook(((o,i)=>{this.onEvent(o,i)})),this.Ki=this.Zi(e,nc.Activation),this.Yi=this.Zi(e,nc.Cancellation))}onEvent(e,a){var r,n=this.ne(),o=this.oe(),i=this.ae(),s=((r=this._instance)==null||(r=r.persistence)==null?void 0:r.props[o])||[];if(i===e&&a&&s.length>0){var l,u;n.info("event matched, removing item from activated items",{event:e,eventPayload:a,existingActivatedItems:s});var c=(a==null||(l=a.properties)==null?void 0:l.$survey_id)||(a==null||(u=a.properties)==null?void 0:u.$product_tour_id);if(c){var d=s.indexOf(c);d>=0&&(s.splice(d,1),this.le(s))}}else{if(this.Yi.has(e)){var f=this.te(e,a,nc.Cancellation);f.length>0&&(n.info("cancel event matched, cancelling items",{event:e,itemsToCancel:f.map((S=>S.id))}),f.forEach((S=>{var x=s.indexOf(S.id);x>=0&&s.splice(x,1),this.ue(S.id)})),this.le(s))}if(this.Ki.has(e)){n.info("event name matched",{event:e,eventPayload:a,items:this.Ki.get(e)});var h=this.te(e,a,nc.Activation);this.le(s.concat(h.map((S=>S.id))||[]))}}}onAction(e){var a,r=this.oe(),n=((a=this._instance)==null||(a=a.persistence)==null?void 0:a.props[r])||[];this.Xi.has(e)&&this.le(n.concat(this.Xi.get(e)||[]))}le(e){var a,r=this.ne(),n=this.oe(),o=[...new Set(e)].filter((i=>!this.he(i)));r.info("updating activated items",{activatedItems:o}),(a=this._instance)==null||(a=a.persistence)==null||a.register({[n]:o})}getActivatedIds(){var e,a=this.oe(),r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[a];return r||[]}getEventToItemsMap(){return this.Ki}de(){return this.se}},gb=class extends mb{constructor(e){super(e)}oe(){return"$surveys_activated"}ae(){return fc.SHOWN}ie(e){var a;(a=this._instance)==null||a.getSurveys(e)}ue(e){var a;(a=this._instance)==null||a.cancelPendingSurvey(e)}ne(){return Oe}he(){return!1}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}},vb=class{constructor(e){this.ve=void 0,this._surveyManager=null,this.ce=!1,this.fe=[],this.pe=null,this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var a=e.surveys;if(ge(a))return Oe.warn("Flags not loaded yet. Not loading surveys.");var r=Ce(a);this.ve=r?a.length>0:a,Oe.info("flags response received, isSurveysEnabled: "+this.ve),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],a=0;a<localStorage.length;a++){var r=localStorage.key(a);(r!=null&&r.startsWith(xT)||r!=null&&r.startsWith("inProgressSurvey_"))&&e.push(r)}e.forEach((n=>localStorage.removeItem(n)))}loadIfEnabled(){if(!this._surveyManager)if(this.ce)Oe.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)Oe.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())Oe.info("Not loading surveys in cookieless mode without consent.");else{var e=Q?.__PosthogExtensions__;if(e){if(!V(this.ve)||this._instance.config.advanced_enable_surveys){var a=this.ve||this._instance.config.advanced_enable_surveys;this.ce=!0;try{var r=e.generateSurveys;if(r)return void this.ge(r,a);var n=e.loadExternalDependency;if(!n)return void this._e("PostHog loadExternalDependency extension not found.");n(this._instance,"surveys",(o=>{o||!e.generateSurveys?this._e("Could not load surveys script",o):this.ge(e.generateSurveys,a)}))}catch(o){throw this._e("Error initializing surveys",o),o}finally{this.ce=!1}}}else Oe.error("PostHog Extensions not found.")}}ge(e,a){this._surveyManager=e(this._instance,a),this._surveyEventReceiver=new gb(this._instance),Oe.info("Surveys loaded successfully"),this.me({isLoaded:!0})}_e(e,a){Oe.error(e,a),this.me({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.fe.push(e),this._surveyManager&&this.me({isLoaded:!0}),()=>{this.fe=this.fe.filter((a=>a!==e))}}getSurveys(e,a){if(a===void 0&&(a=!1),this._instance.config.disable_surveys)return Oe.info("Disabled. Not loading surveys."),e([]);var r,n=this._instance.get_property(qx);if(n&&!a)return e(n,{isLoaded:!0});typeof Promise<"u"&&this.pe?this.pe.then((o=>{var{surveys:i,context:s}=o;return e(i,s)})):(typeof Promise<"u"&&(this.pe=new Promise((o=>{r=o}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:o=>{var i;this.pe=null;var s=o.statusCode;if(s!==200||!o.json){var l="Surveys API could not be loaded, status: "+s;Oe.error(l);var u={isLoaded:!1,error:l};return e([],u),void(r==null||r({surveys:[],context:u}))}var c,d=o.json.surveys||[],f=d.filter((S=>(function(x){return!(!x.start_date||x.end_date)})(S)&&((function(x){var b;return!((b=x.conditions)==null||(b=b.events)==null||(b=b.values)==null||!b.length)})(S)||(function(x){var b;return!((b=x.conditions)==null||(b=b.actions)==null||(b=b.values)==null||!b.length)})(S))));f.length>0&&((c=this._surveyEventReceiver)==null||c.register(f)),(i=this._instance.persistence)==null||i.register({[qx]:d});var h={isLoaded:!0};e(d,h),r?.({surveys:d,context:h})}}))}me(e){for(var a of this.fe)try{if(!e.isLoaded)return a([],e);this.getSurveys(a)}catch(r){Oe.error("Error in survey callback",r)}}getActiveMatchingSurveys(e,a){if(a===void 0&&(a=!1),!ge(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,a);Oe.warn("init was not called")}be(e){var a=null;return this.getSurveys((r=>{var n;a=(n=r.find((o=>o.id===e)))!==null&&n!==void 0?n:null})),a}ye(e){if(ge(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var a=typeof e=="string"?this.be(e):e;return a?this._surveyManager.checkSurveyEligibility(a):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(ge(this._surveyManager))return Oe.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var a=this.ye(e);return{visible:a.eligible,disabledReason:a.reason}}canRenderSurveyAsync(e,a){return ge(this._surveyManager)?(Oe.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise((r=>{this.getSurveys((n=>{var o,i=(o=n.find((l=>l.id===e)))!==null&&o!==void 0?o:null;if(i){var s=this.ye(i);r({visible:s.eligible,disabledReason:s.reason})}else r({visible:!1,disabledReason:"Survey not found"})}),a)}))}renderSurvey(e,a,r){var n;if(ge(this._surveyManager))Oe.warn("init was not called");else{var o=typeof e=="string"?this.be(e):e;if(o!=null&&o.id)if(r4.includes(o.type)){var i=q?.querySelector(a);if(i)return(n=o.appearance)!=null&&n.surveyPopupDelaySeconds?(Oe.info("Rendering survey "+o.id+" with delay of "+o.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var s,l;Oe.info("Rendering survey "+o.id+" with delay of "+((s=o.appearance)==null?void 0:s.surveyPopupDelaySeconds)+" seconds"),(l=this._surveyManager)==null||l.renderSurvey(o,i,r),Oe.info("Survey "+o.id+" rendered")}),1e3*o.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(o,i,r);Oe.warn("Survey element not found")}else Oe.warn("Surveys of type "+o.type+" cannot be rendered in the app");else Oe.warn("Survey not found")}}displaySurvey(e,a){var r;if(ge(this._surveyManager))Oe.warn("init was not called");else{var n=this.be(e);if(n){var o=n;if((r=n.appearance)!=null&&r.surveyPopupDelaySeconds&&a.ignoreDelay&&(o=j({},n,{appearance:j({},n.appearance,{surveyPopupDelaySeconds:0})})),a.displayType!==pb.Popover&&a.initialResponses&&Oe.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),a.ignoreConditions===!1){var i=this.canRenderSurvey(n);if(!i.visible)return void Oe.warn("Survey is not eligible to be displayed: ",i.disabledReason)}a.displayType!==pb.Inline?this._surveyManager.handlePopoverSurvey(o,a):this.renderSurvey(o,a.selector,a.properties)}else Oe.warn("Survey not found")}}cancelPendingSurvey(e){ge(this._surveyManager)?Oe.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;(e=this._surveyManager)==null||e.handlePageUnload()}},dn=et("[Conversations]"),yb=class{constructor(e){this.we=void 0,this._conversationsManager=null,this.xe=!1,this.Ee=null,this._instance=e}onRemoteConfig(e){if(!this._instance.config.disable_conversations){var a=e.conversations;ge(a)||(vn(a)?this.we=a:(this.we=a.enabled,this.Ee=a),this.loadIfEnabled())}}reset(){var e;(e=this._conversationsManager)==null||e.reset(),this._conversationsManager=null,this.we=void 0,this.Ee=null}loadIfEnabled(){if(!this._conversationsManager&&!this.xe&&!(this._instance.config.disable_conversations||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=Q?.__PosthogExtensions__;if(e&&!V(this.we)&&this.we)if(this.Ee&&this.Ee.token){this.xe=!0;try{var a=e.initConversations;if(a)return this.$e(a),void(this.xe=!1);var r=e.loadExternalDependency;if(!r)return void this.Se("PostHog loadExternalDependency extension not found.");r(this._instance,"conversations",(n=>{n||!e.initConversations?this.Se("Could not load conversations script",n):this.$e(e.initConversations),this.xe=!1}))}catch(n){this.Se("Error initializing conversations",n),this.xe=!1}}else dn.error("Conversations enabled but missing token in remote config.")}}$e(e){if(this.Ee)try{this._conversationsManager=e(this.Ee,this._instance),dn.info("Conversations loaded successfully")}catch(a){this.Se("Error completing conversations initialization",a)}else dn.error("Cannot complete initialization: remote config is null")}Se(e,a){dn.error(e,a),this._conversationsManager=null,this.xe=!1}show(){this._conversationsManager?this._conversationsManager.show():dn.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.we===!0&&!cr(this._conversationsManager)}isVisible(){var e,a;return(e=(a=this._conversationsManager)==null?void 0:a.isVisible())!==null&&e!==void 0&&e}sendMessage(e,a,r){var n=this;return Zs((function*(){return n._conversationsManager?n._conversationsManager.sendMessage(e,a,r):(dn.warn("Conversations not available yet."),null)}))()}getMessages(e,a){var r=this;return Zs((function*(){return r._conversationsManager?r._conversationsManager.getMessages(e,a):(dn.warn("Conversations not available yet."),null)}))()}markAsRead(e){var a=this;return Zs((function*(){return a._conversationsManager?a._conversationsManager.markAsRead(e):(dn.warn("Conversations not available yet."),null)}))()}getTickets(e){var a=this;return Zs((function*(){return a._conversationsManager?a._conversationsManager.getTickets(e):(dn.warn("Conversations not available yet."),null)}))()}getCurrentTicketId(){var e,a;return(e=(a=this._conversationsManager)==null?void 0:a.getCurrentTicketId())!==null&&e!==void 0?e:null}getWidgetSessionId(){var e,a;return(e=(a=this._conversationsManager)==null?void 0:a.getWidgetSessionId())!==null&&e!==void 0?e:null}},xb=class{constructor(e){var a;this.ke=!1,this.Pe=!1,this._instance=e,this._instance&&(a=this._instance.config.logs)!=null&&a.captureConsoleLogs&&(this.ke=!0)}onRemoteConfig(e){var a,r=(a=e.logs)==null?void 0:a.captureConsoleLogs;!ge(r)&&r&&(this.ke=!0,this.loadIfEnabled())}reset(){}loadIfEnabled(){if(this.ke&&!this.Pe){var e=et("[logs]"),a=Q?.__PosthogExtensions__;if(a){var r=a.loadExternalDependency;r?r(this._instance,"logs",(n=>{var o;n||(o=a.logs)==null||!o.initializeLogs?e.error("Could not load logs script",n):(a.logs.initializeLogs(this._instance),this.Pe=!0)})):e.error("PostHog loadExternalDependency extension not found.")}else e.error("PostHog Extensions not found.")}}},dE=et("[RateLimiter]"),bb=class{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=a=>{var r=a.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach((n=>{dE.info((n||"events")+" is quota limited."),this.serverLimits[n]=new Date().getTime()+6e4}))}catch(n){return void dE.warn('could not rate limit - continuing. Error: "'+n?.message+'"',{text:r})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var a,r,n;e===void 0&&(e=!1);var{captureEventsBurstLimit:o,captureEventsPerSecond:i}=this,s=new Date().getTime(),l=(a=(r=this.instance.persistence)==null?void 0:r.get_property($x))!==null&&a!==void 0?a:{tokens:o,last:s};l.tokens+=(s-l.last)/1e3*i,l.last=s,l.tokens>o&&(l.tokens=o);var u=l.tokens<1;return u||e||(l.tokens=Math.max(0,l.tokens-1)),!u||this.lastEventRateLimited||e||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+i+" events per second and "+o+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=u,(n=this.instance.persistence)==null||n.set_property($x,l),{isRateLimited:u,remainingTokens:l.tokens}}isServerRateLimited(e){var a=this.serverLimits[e||"events"]||!1;return a!==!1&&new Date().getTime()<a}},Ci=et("[RemoteConfig]"),Sb=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=Q._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.config}Te(e){var a,r;(a=Q.__PosthogExtensions__)!=null&&a.loadExternalDependency?(r=Q.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"remote-config",(()=>e(this.remoteConfig))):(Ci.error("PostHog Extensions not found. Cannot load remote config."),e())}Ie(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:a=>{e(a.json)}})}load(){try{if(this.remoteConfig)return Ci.info("Using preloaded remote config",this.remoteConfig),void this.yi(this.remoteConfig);if(this._instance.M())return void Ci.warn("Remote config is disabled. Falling back to local config.");this.Te((e=>{if(!e)return Ci.info("No config found after loading remote JS config. Falling back to JSON."),void this.Ie((a=>{this.yi(a)}));this.yi(e)}))}catch(e){Ci.error("Error loading remote config",e)}}yi(e){e?this._instance.config.__preview_remote_config?(this._instance.yi(e),e.hasFeatureFlags!==!1&&this._instance.featureFlags.ensureFlagsLoaded()):Ci.info("__preview_remote_config is disabled. Logging config instead",e):Ci.error("Failed to fetch remote config from PostHog.")}},_b=3e3,Cb=class{constructor(e,a){this.Ce=!0,this.Re=[],this.Fe=Ir(a?.flush_interval_ms||_b,250,5e3,$.createLogger("flush interval"),_b),this.Oe=e}enqueue(e){this.Re.push(e),this.Me||this.Ae()}unload(){this.je();var e=this.Re.length>0?this.De():{},a=Object.values(e);[...a.filter((r=>r.url.indexOf("/e")===0)),...a.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.Oe(j({},r,{transport:"sendBeacon"}))}))}enable(){this.Ce=!1,this.Ae()}Ae(){var e=this;this.Ce||(this.Me=setTimeout((()=>{if(this.je(),this.Re.length>0){var a=this.De(),r=function(){var o=a[n],i=new Date().getTime();o.data&&Ce(o.data)&&Be(o.data,(s=>{s.offset=Math.abs(s.timestamp-i),delete s.timestamp})),e.Oe(o)};for(var n in a)r()}}),this.Fe))}je(){clearTimeout(this.Me),this.Me=void 0}De(){var e={};return Be(this.Re,(a=>{var r,n=a,o=(n?n.batchKey:null)||n.url;V(e[o])&&(e[o]=j({},n,{data:[]})),(r=e[o].data)==null||r.push(n.data)})),this.Re=[],e}},o4=["retriesPerformedSoFar"],wb=class{constructor(e){this.Le=!1,this.Ne=3e3,this.Re=[],this._instance=e,this.Re=[],this.Ue=!0,!V(T)&&"onLine"in T.navigator&&(this.Ue=T.navigator.onLine,this.ze=()=>{this.Ue=!0,this.Lt()},this.He=()=>{this.Ue=!1},ft(T,"online",this.ze),ft(T,"offline",this.He))}get length(){return this.Re.length}retriableRequest(e){var{retriesPerformedSoFar:a}=e,r=vE(e,o4);Gs(a)&&(r.url=oh(r.url,{retry_count:a})),this._instance._send_request(j({},r,{callback:n=>{n.statusCode!==200&&(n.statusCode<400||n.statusCode>=500)&&(a??0)<10?this.Be(j({retriesPerformedSoFar:a},r)):r.callback==null||r.callback(n)}}))}Be(e){var a=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=a+1;var r=(function(i){var s=3e3*Math.pow(2,i),l=s/2,u=Math.min(18e5,s),c=(Math.random()-.5)*(u-l);return Math.ceil(u+c)})(a),n=Date.now()+r;this.Re.push({retryAt:n,requestOptions:e});var o="Enqueued failed request for retry in "+r;navigator.onLine||(o+=" (Browser is offline)"),$.warn(o),this.Le||(this.Le=!0,this.qe())}qe(){if(this.We&&clearTimeout(this.We),this.Re.length===0)return this.Le=!1,void(this.We=void 0);this.We=setTimeout((()=>{this.Ue&&this.Re.length>0&&this.Lt(),this.qe()}),this.Ne)}Lt(){var e=Date.now(),a=[],r=this.Re.filter((o=>o.retryAt<e||(a.push(o),!1)));if(this.Re=a,r.length>0)for(var{requestOptions:n}of r)this.retriableRequest(n)}unload(){for(var{requestOptions:e}of(this.We&&(clearTimeout(this.We),this.We=void 0),this.Le=!1,V(T)||(this.ze&&(T.removeEventListener("online",this.ze),this.ze=void 0),this.He&&(T.removeEventListener("offline",this.He),this.He=void 0)),this.Re))try{this._instance._send_request(j({},e,{transport:"sendBeacon"}))}catch(a){$.error(a)}this.Re=[]}},Lb=class{constructor(e){this.Ge=()=>{var a,r,n,o;this.Ve||(this.Ve={});var i=this.scrollElement(),s=this.scrollY(),l=i?Math.max(0,i.scrollHeight-i.clientHeight):0,u=s+(i?.clientHeight||0),c=i?.scrollHeight||0;this.Ve.lastScrollY=Math.ceil(s),this.Ve.maxScrollY=Math.max(s,(a=this.Ve.maxScrollY)!==null&&a!==void 0?a:0),this.Ve.maxScrollHeight=Math.max(l,(r=this.Ve.maxScrollHeight)!==null&&r!==void 0?r:0),this.Ve.lastContentY=u,this.Ve.maxContentY=Math.max(u,(n=this.Ve.maxContentY)!==null&&n!==void 0?n:0),this.Ve.maxContentHeight=Math.max(c,(o=this.Ve.maxContentHeight)!==null&&o!==void 0?o:0)},this._instance=e}getContext(){return this.Ve}resetContext(){var e=this.Ve;return setTimeout(this.Ge,0),e}startMeasuringScrollPosition(){ft(T,"scroll",this.Ge,{capture:!0}),ft(T,"scrollend",this.Ge,{capture:!0}),ft(T,"resize",this.Ge)}scrollElement(){if(!this._instance.config.scroll_root_selector)return T?.document.documentElement;var e=Ce(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var a of e){var r=T?.document.querySelector(a);if(r)return r}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return T&&(T.scrollY||T.pageYOffset||T.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return T&&(T.scrollX||T.pageXOffset||T.document.documentElement.scrollLeft)||0}},i4=t=>cT(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties),sh=class{constructor(e,a,r,n){this.Je=o=>{var i=this.Ke();if(!i||i.sessionId!==o){var s={sessionId:o,props:this.Ye(this._instance)};this.Xe.register({[Vx]:s})}},this._instance=e,this.Qe=a,this.Xe=r,this.Ye=n||i4,this.Qe.onSessionId(this.Je)}Ke(){return this.Xe.props[Vx]}getSetOnceProps(){var e,a=(e=this.Ke())==null?void 0:e.props;return a?"r"in a?dT(a):{$referring_domain:a.referringDomain,$pathname:a.initialPathName,utm_source:a.utm_source,utm_campaign:a.utm_campaign,utm_medium:a.utm_medium,utm_content:a.utm_content,utm_term:a.utm_term}:{}}getSessionProps(){var e={};return Be(Nb(this.getSetOnceProps()),((a,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+_x(r)]=a})),e}},xx=et("[SessionId]"),lh=class{on(e,a){return this.Ze.on(e,a)}constructor(e,a,r){var n;if(this.tr=[],this.ir=void 0,this.Ze=new _c,this.er=(c,d)=>!(!Gs(c)||!Gs(d))&&Math.abs(c-d)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.R=e.config,this.Xe=e.persistence,this.rr=void 0,this.sr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.nr=a||So,this.ar=r||So;var o=this.R.persistence_name||this.R.token,i=this.R.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*Ir(i,60,36e3,xx.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.lr(),this.ur="ph_"+o+"_window_id",this.hr="ph_"+o+"_primary_window_exists",this.dr()){var s=Dt.W(this.ur),l=Dt.W(this.hr);s&&!l?this.rr=s:Dt.V(this.ur),Dt.G(this.hr,!0)}if((n=this.R.bootstrap)!=null&&n.sessionID)try{var u=(c=>{var d=c.replace(/-/g,"");if(d.length!==32)throw new Error("Not a valid UUID");if(d[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(d.substring(0,12),16)})(this.R.bootstrap.sessionID);this.vr(this.R.bootstrap.sessionID,new Date().getTime(),u)}catch(c){xx.error("Invalid sessionID in bootstrap",c)}this.cr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return V(this.tr)&&(this.tr=[]),this.tr.push(e),this.sr&&e(this.sr,this.rr),()=>{this.tr=this.tr.filter((a=>a!==e))}}dr(){return this.R.persistence!=="memory"&&!this.Xe.ki&&Dt.H()}pr(e){e!==this.rr&&(this.rr=e,this.dr()&&Dt.G(this.ur,e))}gr(){return this.rr?this.rr:this.dr()?Dt.W(this.ur):null}vr(e,a,r){e===this.sr&&a===this._sessionActivityTimestamp&&r===this._sessionStartTimestamp||(this._sessionStartTimestamp=r,this._sessionActivityTimestamp=a,this.sr=e,this.Xe.register({[Gp]:[a,e,r]}))}_r(){var e=this.Xe.props[Gp];return Ce(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.vr(null,null,null)}destroy(){clearTimeout(this.mr),this.mr=void 0,this.ir&&T&&(T.removeEventListener("beforeunload",this.ir,{capture:!1}),this.ir=void 0),this.tr=[]}cr(){this.ir=()=>{this.dr()&&Dt.V(this.hr)},ft(T,"beforeunload",this.ir,{capture:!1})}checkAndGetSessionAndWindowId(e,a){if(e===void 0&&(e=!1),a===void 0&&(a=null),this.R.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=a||new Date().getTime(),[n,o,i]=this._r(),s=this.gr(),l=Gs(i)&&Math.abs(r-i)>864e5,u=!1,c=!o,d=!c&&!e&&this.er(r,n);c||d||l?(o=this.nr(),s=this.ar(),xx.info("new session ID generated",{sessionId:o,windowId:s,changeReason:{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}}),i=r,u=!0):s||(s=this.ar(),u=!0);var f=Gs(n)&&e&&!l?n:r,h=Gs(i)?i:new Date().getTime();return this.pr(s),this.vr(o,f,h),e||this.lr(),u&&this.tr.forEach((S=>S(o,s,u?{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}:void 0))),{sessionId:o,windowId:s,sessionStartTimestamp:h,changeReason:u?{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:n}}lr(){clearTimeout(this.mr),this.mr=setTimeout((()=>{var[e]=this._r();if(this.er(new Date().getTime(),e)){var a=this.sr;this.resetSessionId(),this.Ze.emit("forcedIdleReset",{idleSessionId:a})}}),1.1*this.sessionTimeoutMs)}},s4=["$set_once","$set"],xo=et("[SiteApps]"),kb=class{constructor(e){this._instance=e,this.br=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}yr(e,a){if(a){var r=this.globalsForEvent(a);this.br.push(r),this.br.length>1e3&&(this.br=this.br.slice(10))}}get siteAppLoaders(){var e;return(e=Q._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance._addCaptureHook(this.yr.bind(this));this.wr=()=>{e(),this.br=[],this.wr=void 0}}}globalsForEvent(e){var a,r,n,o,i,s,l;if(!e)throw new Error("Event payload is required");var u={},c=this._instance.get_property("$groups")||[],d=this._instance.get_property("$stored_group_properties")||{};for(var[f,h]of Object.entries(d))u[f]={id:c[f],type:f,properties:h};var{$set_once:S,$set:x}=e;return{event:j({},vE(e,s4),{properties:j({},e.properties,x?{$set:j({},(a=(r=e.properties)==null?void 0:r.$set)!==null&&a!==void 0?a:{},x)}:{},S?{$set_once:j({},(n=(o=e.properties)==null?void 0:o.$set_once)!==null&&n!==void 0?n:{},S)}:{}),elements_chain:(i=(s=e.properties)==null?void 0:s.$elements_chain)!==null&&i!==void 0?i:"",distinct_id:(l=e.properties)==null?void 0:l.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:u}}setupSiteApp(e){var a=this.apps[e.id],r=()=>{var s;!a.errored&&this.br.length&&(xo.info("Processing "+this.br.length+" events for site app with id "+e.id),this.br.forEach((l=>a.processEvent==null?void 0:a.processEvent(l))),a.processedBuffer=!0),Object.values(this.apps).every((l=>l.processedBuffer||l.errored))&&((s=this.wr)==null||s.call(this))},n=!1,o=s=>{a.errored=!s,a.loaded=!0,xo.info("Site app with id "+e.id+" "+(s?"loaded":"errored")),n&&r()};try{var{processEvent:i}=e.init({posthog:this._instance,callback:s=>{o(s)}});i&&(a.processEvent=i),n=!0}catch(s){xo.error("Error while initializing PostHog app with config id "+e.id,s),o(!1)}if(n&&a.loaded)try{r()}catch(s){xo.error("Error while processing buffered events PostHog app with config id "+e.id,s),a.errored=!0}}Er(){var e=this.siteAppLoaders||[];for(var a of e)this.apps[a.id]={id:a.id,loaded:!1,errored:!1,processedBuffer:!1};for(var r of e)this.setupSiteApp(r)}$r(e){if(Object.keys(this.apps).length!==0){var a=this.globalsForEvent(e);for(var r of Object.values(this.apps))try{r.processEvent==null||r.processEvent(a)}catch(n){xo.error("Error while processing event "+e.event+" for site app "+r.id,n)}}}onRemoteConfig(e){var a,r,n,o=this;if((a=this.siteAppLoaders)!=null&&a.length)return this.isEnabled?(this.Er(),void this._instance.on("eventCaptured",(u=>this.$r(u)))):void xo.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((r=this.wr)==null||r.call(this),(n=e.siteApps)!=null&&n.length)if(this.isEnabled){var i=function(u){var c;Q["__$$ph_site_app_"+u]=o._instance,(c=Q.__PosthogExtensions__)==null||c.loadSiteApp==null||c.loadSiteApp(o._instance,l,(d=>{if(d)return xo.error("Error while initializing PostHog app with config id "+u,d)}))};for(var{id:s,url:l}of e.siteApps)i(s)}else xo.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}},bT=function(t,e){if(!t)return!1;var a=t.userAgent;if(a&&LA(a,e))return!0;try{var r=t?.userAgentData;if(r!=null&&r.brands&&r.brands.some((n=>LA(n?.brand,e))))return!0}catch{}return!!t.webdriver},pc=(function(t){return t.US="us",t.EU="eu",t.CUSTOM="custom",t})({}),fE="i.posthog.com",Ib=class{constructor(e){this.Sr={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,a=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return a||(a=this.apiHost.replace("."+fE,".posthog.com")),a==="https://app.posthog.com"?"https://us.posthog.com":a}get region(){return this.Sr[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Sr[this.apiHost]=pc.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Sr[this.apiHost]=pc.EU:this.Sr[this.apiHost]=pc.CUSTOM),this.Sr[this.apiHost]}endpointFor(e,a){if(a===void 0&&(a=""),a&&(a=a[0]==="/"?a:"/"+a),e==="ui")return this.uiHost+a;if(e==="flags")return this.flagsApiHost+a;if(this.region===pc.CUSTOM)return this.apiHost+a;var r=fE+a;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}},l4={icontains:(t,e)=>!!T&&e.href.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>!!T&&e.href.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>!!T&&ih(e.href,t),not_regex:(t,e)=>!!T&&!ih(e.href,t),exact:(t,e)=>e.href===t,is_not:(t,e)=>e.href!==t},Ab=class t{constructor(e){var a=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),a.getWebExperiments((n=>{t.kr("retrieved web experiments from the server"),a.Pr=new Map,n.forEach((o=>{if(o.feature_flag_key){var i;a.Pr&&(t.kr("setting flag key ",o.feature_flag_key," to web experiment ",o),(i=a.Pr)==null||i.set(o.feature_flag_key,o));var s=a._instance.getFeatureFlag(o.feature_flag_key);vt(s)&&o.variants[s]&&a.Tr(o.name,s,o.variants[s].transforms)}else if(o.variants)for(var l in o.variants){var u=o.variants[l];t.Ir(u)&&a.Tr(o.name,l,u.transforms)}}))}),r)},this._instance=e,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}onFeatureFlags(e){if(this._is_bot())t.kr("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(ge(this.Pr))return this.Pr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();t.kr("applying feature flags",e),e.forEach((a=>{var r;if(this.Pr&&(r=this.Pr)!=null&&r.has(a)){var n,o=this._instance.getFeatureFlag(a),i=(n=this.Pr)==null?void 0:n.get(a);o&&i!=null&&i.variants[o]&&this.Tr(i.name,o,i.variants[o].transforms)}}))}}previewWebExperiment(){var e=t.getWindowLocation();if(e!=null&&e.search){var a=Jp(e?.search,"__experiment_id"),r=Jp(e?.search,"__experiment_variant");a&&r&&(t.kr("previewing web experiments "+a+" && "+r),this.getWebExperiments((n=>{this.Cr(parseInt(a),r,n)}),!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,a,r){if(this._instance.config.disable_web_experiments&&!r)return e([]);var n=this._instance.get_property("$web_experiments");if(n&&!a)return e(n);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:o=>{if(o.statusCode!==200||!o.json)return e([]);var i=o.json.experiments||[];return e(i)}})}Cr(e,a,r){var n=r.filter((o=>o.id===e));n&&n.length>0&&(t.kr("Previewing web experiment ["+n[0].name+"] with variant ["+a+"]"),this.Tr(n[0].name,a,n[0].variants[a].transforms))}static Ir(e){return!ge(e.conditions)&&t.Rr(e)&&t.Fr(e)}static Rr(e){var a;if(ge(e.conditions)||ge((a=e.conditions)==null?void 0:a.url))return!0;var r,n,o,i=t.getWindowLocation();return!!i&&((r=e.conditions)==null||!r.url||l4[(n=(o=e.conditions)==null?void 0:o.urlMatchType)!==null&&n!==void 0?n:"icontains"](e.conditions.url,i))}static getWindowLocation(){return T?.location}static Fr(e){var a;if(ge(e.conditions)||ge((a=e.conditions)==null?void 0:a.utm))return!0;var r=iT();if(r.utm_source){var n,o,i,s,l,u,c,d,f=(n=e.conditions)==null||(n=n.utm)==null||!n.utm_campaign||((o=e.conditions)==null||(o=o.utm)==null?void 0:o.utm_campaign)==r.utm_campaign,h=(i=e.conditions)==null||(i=i.utm)==null||!i.utm_source||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_source)==r.utm_source,S=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,x=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==r.utm_term;return f&&S&&x&&h}return!1}static kr(e){for(var a=arguments.length,r=new Array(a>1?a-1:0),n=1;n<a;n++)r[n-1]=arguments[n];$.info("[WebExperiments] "+e,r)}Tr(e,a,r){this._is_bot()?t.kr("Refusing to render web experiment since the viewer is a likely bot"):a!=="control"?r.forEach((n=>{if(n.selector){var o;t.kr("applying transform of variant "+a+" for experiment "+e+" ",n);var i=(o=document)==null?void 0:o.querySelectorAll(n.selector);i?.forEach((s=>{var l=s;n.html&&(l.innerHTML=n.html),n.css&&l.setAttribute("style",n.css)}))}})):t.kr("Control variants leave the page unmodified.")}_is_bot(){return ka&&this._instance?bT(ka,this._instance.config.custom_blocked_useragents):void 0}},u4=et("[PostHog ExternalIntegrations]"),c4={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},Eb=class{constructor(e){this._instance=e}it(e,a){var r;(r=Q.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,(n=>{if(n)return u4.error("failed to load script",n);a()}))}startIfEnabledOrStop(){var e=this,a=function(i){var s,l,u;!n||(s=Q.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[i]||e.it(c4[i],(()=>{var c;(c=Q.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[i])==null||c.start(e._instance)})),!n&&(l=Q.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[i]&&((u=Q.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[i])==null||u.stop())};for(var[r,n]of Object.entries((o=this._instance.config.integrations)!==null&&o!==void 0?o:{})){var o;a(r)}}},Tb="[SessionRecording]",oc=et(Tb),uh=class{get started(){var e;return!((e=this.Or)==null||!e.isStarted)}get status(){return this.Or?this.Or.status:this.Mr&&!this.Ar?"disabled":"lazy_loading"}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.Mr=!1,this.jr=void 0,this._instance=e,!this._instance.sessionManager)throw oc.error("started without valid sessionManager"),new Error(Tb+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(Tb+' cannot be used with cookieless_mode="always"')}get Ar(){var e,a=!((e=this._instance.get_property(ix))==null||!e.enabled),r=!this._instance.config.disable_session_recording,n=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return T&&a&&r&&!n}startIfEnabledOrStop(e){var a;if(!this.Ar||(a=this.Or)==null||!a.isStarted){var r=!V(Object.assign)&&!V(Array.from);this.Ar&&r?(this.Dr(e),oc.info("starting")):this.stopRecording()}}Dr(e){var a,r,n;this.Ar&&(Q!=null&&(a=Q.__PosthogExtensions__)!=null&&(a=a.rrweb)!=null&&a.record&&(r=Q.__PosthogExtensions__)!=null&&r.initSessionRecording?this.Lr(e):(n=Q.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,this.Nr,(o=>{if(o)return oc.error("could not load recorder",o);this.Lr(e)})))}stopRecording(){var e,a;(e=this.jr)==null||e.call(this),this.jr=void 0,(a=this.Or)==null||a.stop()}Ur(){var e;(e=this._instance.persistence)==null||e.unregister(VE)}zr(e){if(this._instance.persistence){var a,r,n=this._instance.persistence,o=()=>{var i=e.sessionRecording===!1?void 0:e.sessionRecording,s=i?.sampleRate,l=ge(s)?null:parseFloat(s);ge(l)&&this.Ur();var u=i?.minimumDurationMilliseconds;n.register({[ix]:j({enabled:!!i},i,{networkPayloadCapture:j({capturePerformance:e.capturePerformance},i?.networkPayloadCapture),canvasRecording:{enabled:i?.recordCanvas,fps:i?.canvasFps,quality:i?.canvasQuality},sampleRate:l,minimumDurationMilliseconds:V(u)?null:u,endpoint:i?.endpoint,triggerMatchType:i?.triggerMatchType,masking:i?.masking,urlTriggers:i?.urlTriggers})})};o(),(a=this.jr)==null||a.call(this),this.jr=(r=this._instance.sessionManager)==null?void 0:r.onSessionId(o)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.zr(e),this.Mr=!0,this.startIfEnabledOrStop()):this.Mr=!0:oc.info("skipping remote config with no sessionRecording",e)}log(e,a){var r;a===void 0&&(a="log"),(r=this.Or)!=null&&r.log?this.Or.log(e,a):oc.warn("log called before recorder was ready")}get Nr(){var e,a,r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(ix);return(r==null||(a=r.scriptConfig)==null?void 0:a.script)||"lazy-recorder"}Lr(e){var a,r;if((a=Q.__PosthogExtensions__)==null||!a.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.Or||(this.Or=(r=Q.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance),this.Or._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.Or.start(e)}onRRwebEmit(e){var a;(a=this.Or)==null||a.onRRwebEmit==null||a.onRRwebEmit(e)}overrideLinkedFlag(){var e,a;this.Or||(a=this._instance.persistence)==null||a.register({$replay_override_linked_flag:!0}),(e=this.Or)==null||e.overrideLinkedFlag()}overrideSampling(){var e,a;this.Or||(a=this._instance.persistence)==null||a.register({$replay_override_sampling:!0}),(e=this.Or)==null||e.overrideSampling()}overrideTrigger(e){var a,r;this.Or||(r=this._instance.persistence)==null||r.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(a=this.Or)==null||a.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.Or)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,a){var r;return!((r=this.Or)==null||!r.tryAddCustomEvent(e,a))}},gc={},Rb=()=>{},Ws="posthog",ST=!QH&&ua?.indexOf("MSIE")===-1&&ua?.indexOf("Mozilla")===-1,pE=t=>{var e;return j({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:hH(q?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Rb,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,debug:Bt&&vt(Bt?.search)&&Bt.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!0,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(T==null||(e=T.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:a=>{var r="Bad HTTP status: "+a.statusCode+" "+a.text;$.error(r)},get_device_id:a=>a,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:_b},error_tracking:{},_onCapture:Rb,__preview_eager_load_replay:!1},(a=>({rageclick:!(a&&a>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(a&&a>="2025-05-24")||"history_change",session_recording:a&&a>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:a&&a>="2026-01-30"?"head":"body",internal_or_test_user_hostname:a&&a>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0}))(t))},hE=t=>{var e={};V(t.process_person)||(e.person_profiles=t.process_person),V(t.xhr_headers)||(e.request_headers=t.xhr_headers),V(t.cookie_name)||(e.persistence_name=t.cookie_name),V(t.disable_cookie)||(e.disable_persistence=t.disable_cookie),V(t.store_google)||(e.save_campaign_params=t.store_google),V(t.verbose)||(e.debug=t.verbose);var a=ot({},e,t);return Ce(t.property_blacklist)&&(V(t.property_denylist)?a.property_denylist=t.property_blacklist:Ce(t.property_denylist)?a.property_denylist=[...t.property_blacklist,...t.property_denylist]:$.error("Invalid value for property_denylist config: "+t.property_denylist)),a},Mb=class{constructor(){this.__forceAllowLocalhost=!1}get Hr(){return this.__forceAllowLocalhost}set Hr(e){$.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},ch=class t{get decideEndpointWasHit(){var e,a;return(e=(a=this.featureFlags)==null?void 0:a.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,a;return(e=(a=this.featureFlags)==null?void 0:a.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new Mb,this.Br=!1,this.version=fn.LIB_VERSION,this.qr=new _c,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=pE(),this.SentryIntegration=tb,this.sentryIntegration=e=>(function(a,r){var n=oT(a,r);return{name:nT,processEvent:o=>n(o)}})(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Wr=!1,this.Gr=null,this.Vr=null,this.Jr=null,this.featureFlags=new db(this),this.toolbar=new ab(this),this.scrollManager=new Lb(this),this.pageViewManager=new ah(this),this.surveys=new vb(this),this.conversations=new yb(this),this.logs=new xb(this),this.experiments=new Ab(this),this.exceptions=new cb(this),this.rateLimiter=new bb(this),this.requestRouter=new Ib(this),this.consent=new Qx(this),this.externalIntegrations=new Eb(this),this.people={set:(e,a,r)=>{var n=vt(e)?{[e]:a}:e;this.setPersonProperties(n),r?.({})},set_once:(e,a,r)=>{var n=vt(e)?{[e]:a}:e;this.setPersonProperties(void 0,n),r?.({})}},this.on("eventCaptured",(e=>$.info('send "'+e?.event+'"',e)))}init(e,a,r){if(r&&r!==Ws){var n,o=(n=gc[r])!==null&&n!==void 0?n:new t;return o._init(e,a,r),gc[r]=o,gc[Ws][r]=o,o}return this._init(e,a,r)}_init(e,a,r){var n;if(a===void 0&&(a={}),V(e)||Cx(e))return $.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},a.debug=this.Kr(a.debug),this.Yr=a,this.Xr=[],a.person_profiles&&(this.Vr=a.person_profiles),this.set_config(ot({},pE(a.defaults),hE(a),{name:r,token:e})),this.config.on_xhr_error&&$.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=a.disable_compression?void 0:mn.GZipJS;var o=this.Qr();this.persistence=new mc(this.config,o),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new mc(j({},this.config,{persistence:"sessionStorage"}),o);var i=j({},this.persistence.props),s=j({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Zr=new Cb((m=>this.ts(m)),this.config.request_queue_config),this.es=new wb(this),this.__request_queue=[];var l=this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut();if(l||(this.sessionManager=new lh(this),this.sessionPropsManager=new sh(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?($.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.rs(l)}),0)):($.info("Initializing extensions synchronously"),this.rs(l)),fn.DEBUG=fn.DEBUG||this.config.debug,fn.DEBUG&&$.info("Starting in debug mode",{this:this,config:a,thisC:j({},this.config),p:i,s}),((n=a.bootstrap)==null?void 0:n.distinctID)!==void 0){var u,c,d=this.config.get_device_id(So()),f=(u=a.bootstrap)!=null&&u.isIdentifiedID?d:a.bootstrap.distinctID;this.persistence.set_property(pn,(c=a.bootstrap)!=null&&c.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:a.bootstrap.distinctID,$device_id:f})}if(this.ss()){var h,S,x=Object.keys(((h=a.bootstrap)==null?void 0:h.featureFlags)||{}).filter((m=>{var y;return!((y=a.bootstrap)==null||(y=y.featureFlags)==null||!y[m])})).reduce(((m,y)=>{var v;return m[y]=((v=a.bootstrap)==null||(v=v.featureFlags)==null?void 0:v[y])||!1,m}),{}),b=Object.keys(((S=a.bootstrap)==null?void 0:S.featureFlagPayloads)||{}).filter((m=>x[m])).reduce(((m,y)=>{var v,C;return(v=a.bootstrap)!=null&&(v=v.featureFlagPayloads)!=null&&v[y]&&(m[y]=(C=a.bootstrap)==null||(C=C.featureFlagPayloads)==null?void 0:C[y]),m}),{});this.featureFlags.receivedFeatureFlags({featureFlags:x,featureFlagPayloads:b})}if(l)this.register_once({distinct_id:Yu,$device_id:null},"");else if(!this.get_distinct_id()){var g=this.config.get_device_id(So());this.register_once({distinct_id:g,$device_id:g},""),this.persistence.set_property(pn,"anonymous")}return ft(T,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),a.segment?PH(this,(()=>this.ns())):this.ns(),_o(this.config._onCapture)&&this.config._onCapture!==Rb&&($.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(m=>this.config._onCapture(m.event,m)))),this.config.ip&&$.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this}rs(e){var a=performance.now();this.historyAutocapture=new eb(this),this.historyAutocapture.startIfEnabled();var r=[];r.push((()=>{new rb(this).startIfEnabledOrStop()})),r.push((()=>{var n;this.siteApps=new kb(this),(n=this.siteApps)==null||n.init()})),e||r.push((()=>{this.sessionRecording=new uh(this),this.sessionRecording.startIfEnabledOrStop()})),this.config.disable_scroll_properties||r.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),r.push((()=>{this.autocapture=new Zx(this),this.autocapture.startIfEnabled()})),r.push((()=>{this.surveys.loadIfEnabled()})),r.push((()=>{this.logs.loadIfEnabled()})),r.push((()=>{this.conversations.loadIfEnabled()})),r.push((()=>{this.productTours=new fb(this),this.productTours.loadIfEnabled()})),r.push((()=>{this.heatmaps=new ob(this),this.heatmaps.startIfEnabled()})),r.push((()=>{this.webVitalsAutocapture=new nb(this)})),r.push((()=>{this.exceptionObserver=new Jx(this),this.exceptionObserver.startIfEnabledOrStop()})),r.push((()=>{this.deadClicksAutocapture=new th(this,BH),this.deadClicksAutocapture.startIfEnabled()})),r.push((()=>{if(this.os){var n=this.os;this.os=void 0,this.yi(n)}})),this.ls(r,a)}ls(e,a){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-a>=30&&e.length>0)return void setTimeout((()=>{this.ls(e,a)}),0);var r=e.shift();if(r)try{r()}catch(o){$.error("Error initializing extension:",o)}}var n=Math.round(performance.now()-a);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:n}),this.config.__preview_deferred_init_extensions&&$.info("PostHog extensions initialized ("+n+"ms)")}yi(e){var a,r,n,o,i,s,l,u,c;if(!q||!q.body)return $.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.yi(e)}),500);this.config.__preview_deferred_init_extensions&&(this.os=e),this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=he(e.supportedCompression,mn.GZipJS)?mn.GZipJS:he(e.supportedCompression,mn.Base64)?mn.Base64:void 0),(a=e.analytics)!=null&&a.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Vr?this.Vr:"identified_only"}),(r=this.siteApps)==null||r.onRemoteConfig(e),(n=this.sessionRecording)==null||n.onRemoteConfig(e),(o=this.autocapture)==null||o.onRemoteConfig(e),(i=this.heatmaps)==null||i.onRemoteConfig(e),this.surveys.onRemoteConfig(e),this.logs.onRemoteConfig(e),this.conversations.onRemoteConfig(e),(s=this.productTours)==null||s.onRemoteConfig(e),(l=this.webVitalsAutocapture)==null||l.onRemoteConfig(e),(u=this.exceptionObserver)==null||u.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(c=this.deadClicksAutocapture)==null||c.onRemoteConfig(e)}ns(){try{this.config.loaded(this)}catch(r){$.critical("`loaded` function failed",r)}if(this.us(),this.config.internal_or_test_user_hostname&&Bt!=null&&Bt.hostname){var e=Bt.hostname,a=this.config.internal_or_test_user_hostname;(typeof a=="string"?e===a:a.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.hs()}),1),new Sb(this).load(),this.featureFlags.flags()}us(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.Zr)==null||e.enable())}_dom_loaded(){this.is_capturing()&&Co(this.__request_queue,(e=>this.ts(e))),this.__request_queue=[],this.us()}_handle_unload(){var e,a;this.surveys.handlePageUnload(),this.config.request_batching?(this.ds()&&this.capture("$pageleave"),(e=this.Zr)==null||e.unload(),(a=this.es)==null||a.unload()):this.ds()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}_send_request(e){this.__loaded&&(ST?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=oh(e.url,{ip:this.config.ip?1:0}),e.headers=j({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,e.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(a=>{var r,n,o,i=j({},a);i.timeout=i.timeout||6e4,i.url=oh(i.url,{_:new Date().getTime().toString(),ver:fn.LIB_VERSION,compression:i.compression});var s=(r=i.transport)!==null&&r!==void 0?r:"fetch",l=qp.filter((c=>!i.disableTransport||!c.transport||!i.disableTransport.includes(c.transport))),u=(n=(o=UE(l,(c=>c.transport===s)))==null?void 0:o.method)!==null&&n!==void 0?n:l[0].method;if(!u)throw new Error("No available transport method");u(i)})(j({},e,{callback:a=>{var r,n;this.rateLimiter.checkForLimiting(a),a.statusCode>=400&&((r=(n=this.config).on_request_error)==null||r.call(n,a)),e.callback==null||e.callback(a)}}))))}ts(e){this.es?this.es.retriableRequest(e):this._send_request(e)}_execute_array(e){var a,r=[],n=[],o=[];Co(e,(s=>{s&&(a=s[0],Ce(a)?o.push(s):_o(s)?s.call(this):Ce(s)&&a==="alias"?r.push(s):Ce(s)&&a.indexOf("capture")!==-1&&_o(this[a])?o.push(s):n.push(s))}));var i=function(s,l){Co(s,(function(u){if(Ce(u[0])){var c=l;Be(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else this[u[0]].apply(this,u.slice(1))}),l)};i(r,this),i(n,this),i(o,this)}ss(){var e,a;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((a=this.config.bootstrap)==null?void 0:a.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,a,r){var n;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Zr){if(this.is_capturing())if(!V(e)&&vt(e)){var o=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(o&&!this.config.__preview_capture_bot_pageviews)){var i=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(i==null||!i.isRateLimited){a!=null&&a.$current_url&&!vt(a?.$current_url)&&($.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),a==null||delete a.$current_url),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var s=new Date,l=r?.timestamp||s,u=So(),c={uuid:u,event:e,properties:this.calculateEventProperties(e,a||{},l,u)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&o&&(c.event="$bot_pageview",c.properties.$browser_type="bot"),i&&(c.properties.$lib_rate_limit_remaining_tokens=i.remainingTokens),r?.$set&&(c.$set=r?.$set);var d,f=e!=="$groupidentify",h=this.vs(r?.$set_once,f);if(h&&(c.$set_once=h),(c=fH(c,r!=null&&r._noTruncate?null:this.config.properties_string_max_length)).timestamp=l,V(r?.timestamp)||(c.properties.$event_time_override_provided=!0,c.properties.$event_time_override_system_time=s),e===fc.DISMISSED||e===fc.SENT){var S=a?.[yx.SURVEY_ID],x=a?.[yx.SURVEY_ITERATION];d={id:S,current_iteration:x},localStorage.getItem(cE(d))||localStorage.setItem(cE(d),"true"),c.$set=j({},c.$set,{[a4({id:S,current_iteration:x},e===fc.SENT?"responded":"dismissed")]:!0})}else e===fc.SHOWN&&(c.$set=j({},c.$set,{[yx.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));var b=j({},c.properties.$set,c.$set);if(Xs(b)||this.setPersonPropertiesForFlags(b),!ge(this.config.before_send)){var g=this.cs(c);if(!g)return;c=g}this.qr.emit("eventCaptured",c);var m={method:"POST",url:(n=r?._url)!==null&&n!==void 0?n:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:c,compression:"best-available",batchKey:r?._batchKey};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.ts(m):this.Zr.enqueue(m),c}$.critical("This capture call is ignored due to client rate limiting.")}}else $.error("No event name provided to posthog.capture")}else $.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(a=>e(a.event,a)))}calculateEventProperties(e,a,r,n,o){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return a;var i=o?void 0:this.persistence.remove_event_timer(e),s=j({},a);if(s.token=this.config.token,s.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(s.$cookieless_mode=!0),e==="$snapshot"){var l=j({},this.persistence.properties(),this.sessionPersistence.properties());return s.distinct_id=l.distinct_id,(!vt(s.distinct_id)&&!yn(s.distinct_id)||Cx(s.distinct_id))&&$.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),s}var u,c=qH(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:d,windowId:f}=this.sessionManager.checkAndGetSessionAndWindowId(o,r.getTime());s.$session_id=d,s.$window_id=f}this.sessionPropsManager&&ot(s,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&ot(s,this.sessionRecording.sdkDebugProperties),s.$sdk_debug_retry_queue_size=(h=this.es)==null?void 0:h.length}catch(g){s.$sdk_debug_error_capturing_properties=String(g)}if(this.requestRouter.region===pc.CUSTOM&&(s.$lib_custom_api_host=this.config.api_host),u=e!=="$pageview"||o?e!=="$pageleave"||o?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,n),s=ot(s,u),e==="$pageview"&&q&&(s.title=q.title),!V(i)){var S=r.getTime()-i;s.$duration=parseFloat((S/1e3).toFixed(3))}ua&&this.config.opt_out_useragent_filter&&(s.$browser_type=this._is_bot()?"bot":"browser"),(s=ot({},c,this.persistence.properties(),this.sessionPersistence.properties(),s)).$is_identified=this._isIdentified(),Ce(this.config.property_denylist)?Be(this.config.property_denylist,(function(g){delete s[g]})):$.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var x=this.config.sanitize_properties;x&&($.error("sanitize_properties is deprecated. Use before_send instead"),s=x(s,e));var b=this.fs();return s.$process_person_profile=b,b&&!o&&this.ps("_calculate_event_properties"),s}vs(e,a){var r;if(a===void 0&&(a=!0),!this.persistence||!this.fs()||this.Br)return e;var n=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),i=ot({},n,o||{},e||{}),s=this.config.sanitize_properties;return s&&($.error("sanitize_properties is deprecated. Use before_send instead"),i=s(i,"$set_once")),a&&(this.Br=!0),Xs(i)?void 0:i}register(e,a){var r;(r=this.persistence)==null||r.register(e,a)}register_once(e,a,r){var n;(n=this.persistence)==null||n.register_once(e,a,r)}register_for_session(e){var a;(a=this.sessionPersistence)==null||a.register(e)}unregister(e){var a;(a=this.persistence)==null||a.unregister(e)}unregister_for_session(e){var a;(a=this.sessionPersistence)==null||a.unregister(e)}gs(e,a){this.register({[e]:a})}getFeatureFlag(e,a){return this.featureFlags.getFeatureFlag(e,a)}getFeatureFlagPayload(e){return this.featureFlags.getFeatureFlagPayload(e)}getFeatureFlagResult(e,a){return this.featureFlags.getFeatureFlagResult(e,a)}isFeatureEnabled(e,a){return this.featureFlags.isFeatureEnabled(e,a)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateFlags(e,a,r){var n=r!=null&&r.merge?this.featureFlags.getFlagVariants():{},o=r!=null&&r.merge?this.featureFlags.getFlagPayloads():{},i=j({},n,e),s=j({},o,a),l={};for(var[u,c]of Object.entries(i)){var d=typeof c=="string";l[u]={key:u,enabled:!!d||!!c,variant:d?c:void 0,reason:void 0,metadata:V(s?.[u])?void 0:{id:0,version:void 0,description:void 0,payload:s[u]}}}this.featureFlags.receivedFeatureFlags({flags:l})}updateEarlyAccessFeatureEnrollment(e,a,r){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,a,r)}getEarlyAccessFeatures(e,a,r){return a===void 0&&(a=!1),this.featureFlags.getEarlyAccessFeatures(e,a,r)}on(e,a){return this.qr.on(e,a)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var a,r;return(a=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&a!==void 0?a:()=>{}}getSurveys(e,a){a===void 0&&(a=!1),this.surveys.getSurveys(e,a)}getActiveMatchingSurveys(e,a){a===void 0&&(a=!1),this.surveys.getActiveMatchingSurveys(e,a)}renderSurvey(e,a){this.surveys.renderSurvey(e,a)}displaySurvey(e,a){a===void 0&&(a=n4),this.surveys.displaySurvey(e,a)}cancelPendingSurvey(e){this.surveys.cancelPendingSurvey(e)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,a){return a===void 0&&(a=!1),this.surveys.canRenderSurveyAsync(e,a)}identify(e,a,r){if(!this.__loaded||!this.persistence)return $.uninitializedWarning("posthog.identify");if(yn(e)&&(e=e.toString(),$.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))$.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(e!==Yu){if(this.ps("posthog.identify")){var n=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var o=n;this.register_once({$had_persisted_distinct_id:!0,$device_id:o},"")}e!==n&&e!==this.get_property(sc)&&(this.unregister(sc),this.register({distinct_id:e}));var i=(this.persistence.get_property(pn)||"anonymous")==="anonymous";e!==n&&i?(this.persistence.set_property(pn,"identified"),this.setPersonPropertiesForFlags(j({},r||{},a||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:n},{$set:a||{},$set_once:r||{}}),this.Jr=nE(e,a,r),this.featureFlags.setAnonymousDistinctId(n)):(a||r)&&this.setPersonProperties(a,r),e!==n&&(this.reloadFeatureFlags(),this.unregister(Wp))}}else $.critical('The string "'+Yu+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else $.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,a){if((e||a)&&this.ps("posthog.setPersonProperties")){var r=nE(this.get_distinct_id(),e,a);this.Jr!==r?(this.setPersonPropertiesForFlags(j({},a||{},e||{})),this.capture("$set",{$set:e||{},$set_once:a||{}}),this.Jr=r):$.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,a,r){if(e&&a){var n=this.getGroups();n[e]!==a&&this.resetGroupPropertiesForFlags(e),this.register({$groups:j({},n,{[e]:a})}),r&&(this.capture("$groupidentify",{$group_type:e,$group_key:a,$group_set:r}),this.setGroupPropertiesForFlags({[e]:r})),n[e]===a||r||this.reloadFeatureFlags()}else $.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,a){a===void 0&&(a=!0),this.featureFlags.setPersonPropertiesForFlags(e,a)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,a){a===void 0&&(a=!0),this.ps("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,a)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var a,r,n,o;if($.info("reset"),!this.__loaded)return $.uninitializedWarning("posthog.reset");var i=this.get_property("$device_id");if(this.consent.reset(),(a=this.persistence)==null||a.clear(),(r=this.sessionPersistence)==null||r.clear(),this.surveys.reset(),this.featureFlags.reset(),(n=this.persistence)==null||n.set_property(pn,"anonymous"),(o=this.sessionManager)==null||o.resetSessionId(),this.Jr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:Yu,$device_id:null},"");else{var s=this.config.get_device_id(So());this.register_once({distinct_id:s,$device_id:e?s:i},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,a;return(e=(a=this.sessionManager)==null?void 0:a.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:a,sessionStartTimestamp:r}=this.sessionManager.checkAndGetSessionAndWindowId(!0),n=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+a);if(e!=null&&e.withTimestamp&&r){var o,i=(o=e.timestampLookBack)!==null&&o!==void 0?o:10;if(!r)return n;n+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-i,0)}return n}alias(e,a){return e===this.get_property(zE)?($.critical("Attempting to create alias for existing People user - aborting."),-2):this.ps("posthog.alias")?(V(a)&&(a=this.get_distinct_id()),e!==a?(this.gs(sc,e),this.capture("$create_alias",{alias:e,distinct_id:a})):($.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var a=j({},this.config);if(gt(e)){var r,n,o,i,s,l,u;ot(this.config,hE(e));var c=this.Qr();(r=this.persistence)==null||r.update_config(this.config,a,c),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new mc(j({},this.config,{persistence:"sessionStorage"}),c);var d=this.Kr(this.config.debug);vn(d)&&(this.config.debug=d),vn(this.config.debug)&&(this.config.debug?(fn.DEBUG=!0,Ke.H()&&Ke.G("ph_debug","true"),$.info("set_config",{config:e,oldConfig:a,newConfig:j({},this.config)})):(fn.DEBUG=!1,Ke.H()&&Ke.V("ph_debug"))),(n=this.exceptionObserver)==null||n.onConfigChange(),(o=this.sessionRecording)==null||o.startIfEnabledOrStop(),(i=this.autocapture)==null||i.startIfEnabled(),(s=this.heatmaps)==null||s.startIfEnabled(),(l=this.exceptionObserver)==null||l.startIfEnabledOrStop(),this.surveys.loadIfEnabled(),this._s(),(u=this.externalIntegrations)==null||u.startIfEnabledOrStop()}}startSessionRecording(e){var a=e===!0,r={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};if(Object.values(r).some(Boolean)){var n,o,i,s,l;(n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),r.sampling&&((o=this.sessionRecording)==null||o.overrideSampling()),r.linked_flag&&((i=this.sessionRecording)==null||i.overrideLinkedFlag()),r.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),r.event_trigger&&((l=this.sessionRecording)==null||l.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,a){var r=new Error("PostHog syntheticException"),n=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(j({},n,a))}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var a;return(a=this.persistence)==null?void 0:a.props[e]}getSessionProperty(e){var a;return(a=this.sessionPersistence)==null?void 0:a.props[e]}toString(){var e,a=(e=this.config.name)!==null&&e!==void 0?e:Ws;return a!==Ws&&(a=Ws+"."+a),a}_isIdentified(){var e,a;return((e=this.persistence)==null?void 0:e.get_property(pn))==="identified"||((a=this.sessionPersistence)==null?void 0:a.get_property(pn))==="identified"}fs(){var e,a;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&Xs(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[sc])&&((a=this.persistence)==null||(a=a.props)==null||!a[Xp]))}ds(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.fs()||this.ps("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.ps("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}ps(e){return this.config.person_profiles==="never"?($.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.gs(Xp,!0),!0)}Qr(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),a=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!a}_s(){var e,a,r,n,o=this.Qr();return((e=this.persistence)==null?void 0:e.ki)!==o&&((r=this.persistence)==null||r.set_disabled(o)),((a=this.sessionPersistence)==null?void 0:a.ki)!==o&&((n=this.sessionPersistence)==null||n.set_disabled(o)),o}opt_in_capturing(e){var a;if(this.config.cookieless_mode!=="always"){var r,n,o;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(r=this.sessionManager)==null||r.destroy(),(n=this.pageViewManager)==null||n.destroy(),this.sessionManager=new lh(this),this.pageViewManager=new ah(this),this.persistence&&(this.sessionPropsManager=new sh(this,this.sessionManager,this.persistence)),this.sessionRecording=new uh(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this._s(),this.us(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(V(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((o=e?.captureEventName)!==null&&o!==void 0?o:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.hs()}else $.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,a,r;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this._s(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:Yu,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),(a=this.pageViewManager)==null||a.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(r=this.sessionRecording)==null||r.stopRecording(),this.sessionRecording=void 0,this.hs())):$.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===hn.GRANTED?"granted":e===hn.DENIED?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isExplicitlyOptedOut()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this._s()}_is_bot(){return ka?bT(ka,this.config.custom_blocked_useragents):void 0}hs(){q&&(q.visibilityState==="visible"?this.Wr||(this.Wr=!0,this.capture("$pageview",{title:q.title},{send_instantly:!0}),this.Gr&&(q.removeEventListener("visibilitychange",this.Gr),this.Gr=null)):this.Gr||(this.Gr=this.hs.bind(this),ft(q,"visibilitychange",this.Gr)))}debug(e){e===!1?(T?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(T?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}M(){var e,a,r,n,o,i,s,l=this.Yr||{};return"advanced_disable_flags"in l?!!l.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?($.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(r="advanced_disable_decide",n=!1,o=$,i=(a="advanced_disable_flags")in(e=l)&&!ge(e[a]),s=r in e&&!ge(e[r]),i?e[a]:s?(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+a+"' instead. The old field will be removed in a future major version."),e[r]):n)}cs(e){if(ge(this.config.before_send))return e;var a=Ce(this.config.before_send)?this.config.before_send:[this.config.before_send],r=e;for(var n of a){if(r=n(r),ge(r)){var o="Event '"+e.event+"' was rejected in beforeSend function";return H3(e.event)?$.warn(o+". This can cause unexpected behavior."):$.info(o),null}r.properties&&!Xs(r.properties)||$.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return r}getPageViewId(){var e;return(e=this.pageViewManager.Kt)==null?void 0:e.pageViewId}captureTraceFeedback(e,a){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:a})}captureTraceMetric(e,a,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:a,$ai_metric_value:String(r)})}Kr(e){var a=vn(e)&&!e,r=Ke.H()&&Ke.q("ph_debug")==="true";return!a&&(!!r||e)}};(function(t,e){for(var a=0;a<e.length;a++)t.prototype[e[a]]=dH(t.prototype[e[a]])})(ch,["identify"]);var mE;var _T=(mE=gc[Ws]=new ch,(function(){function t(){t.done||(t.done=!0,ST=!1,Be(gc,(function(e){e._dom_loaded()})))}q!=null&&q.addEventListener?q.readyState==="complete"?t():ft(q,"DOMContentLoaded",t,{capture:!1}):T&&$.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),mE);var Vb=class{constructor(e={}){this.options=e;B(this,"client");B(this,"featureFlagsCallback");B(this,"captureCallback");B(this,"rrwebCallback");if(this.client=e.client,this.featureFlagsCallback=e.onFeatureFlagsLoaded,this.captureCallback=e.onCapture,this.rrwebCallback=e.onRRWebEvent,!this.client&&e.consent&&e.requireExplicitConsent&&typeof window<"u"&&e.apiKey){let a=e.consent;a.getStatus()==="granted"&&this.initPostHog(),a.subscribe(n=>{n==="granted"?this.client?this.client.opt_in_capturing():this.initPostHog():n==="denied"&&this.client&&this.client.opt_out_capturing()});return}!this.client&&typeof window<"u"&&e.apiKey&&this.initPostHog()}initPostHog(){let e=this.options;if(!e.apiKey)return;let a=e.enableFeatureFlags??!0,r=`syntro_${e.apiKey.slice(-6)||"sdk"}`,n={api_host:e.apiHost??"https://telemetry.syntrologie.com",advanced_disable_feature_flags:!a,advanced_disable_feature_flags_on_first_load:!a,autocapture:e.autocapture??!0,capture_pageview:e.capturePageview??"history_change",capture_pageleave:e.capturePageleave??!0,disable_session_recording:!(e.sessionRecording??!0),opt_out_useragent_filter:!0,session_recording:{recordCrossDomainIFrames:!0},capture_performance:!0,enable_recording_console_log:!0},o=_T.init(e.apiKey,n,r);if(o&&(this.client=o),this.captureCallback&&this.client&&this.client.on("eventCaptured",(...i)=>{let s=i[0],l=typeof s=="string"?s:s?.event,u=typeof s=="string"?void 0:s?.properties;typeof l=="string"&&this.captureCallback?.(l,u)}),a&&this.featureFlagsCallback&&this.client){this.client.onFeatureFlags(()=>{let s=this.getAllFeatureFlags();s&&this.featureFlagsCallback&&this.featureFlagsCallback(s)});let i=this.getAllFeatureFlags();i&&Object.keys(i).length>0&&this.featureFlagsCallback(i)}this.rrwebCallback&&this.client&&this.setupRRWebIntercept()}setupRRWebIntercept(e=30){let a=this.client?.sessionRecording;if(!a){e>0&&setTimeout(()=>this.setupRRWebIntercept(e-1),500);return}let r=null,n=a;for(let i of Object.getOwnPropertyNames(n)){let s=n[i];if(s&&typeof s=="object"&&typeof s.onRRwebEmit=="function"&&typeof s.start=="function"&&s!==a){r=s;break}}if(!r){e>0&&setTimeout(()=>this.setupRRWebIntercept(e-1),500);return}let o=r.onRRwebEmit.bind(r);r.onRRwebEmit=i=>{this.rrwebCallback?.({kind:"rrweb",...i}),o(i)},typeof window<"u"&&(window.__RRWEB_INTERCEPT_READY__=!0)}getAllFeatureFlags(){return this.client?.featureFlags?.getFlagVariants()}getSegmentFlags(){let e=this.getAllFeatureFlags();if(!e)return{};let a={};for(let[r,n]of Object.entries(e))r.startsWith("in_segment_")&&(a[r]=n===!0);return a}identify(e,a){this.client?.identify(e,a)}alias(e,a){this.client?.alias(e,a)}track(e,a){this.client?.capture(e,a)}trackCanvasOpened(e){this.track("shadow_canvas_opened",{surface:e})}trackCanvasClosed(e){this.track("shadow_canvas_closed",{surface:e})}trackRectangleViewed(e,a){this.track("shadow_canvas_rectangle_viewed",{rectangleId:e,surface:a})}trackAction(e,a,r){this.track("shadow_canvas_action",{action:e,rectangleId:a,surface:r})}register(e){this.client?.register?.(e)}getSessionId(){return this.client?.get_session_id?.()}startSessionRecording(){this.client?.startSessionRecording?.()}trackExperiment(e,a,r){let n=`$experiment_${e}`;this.register({[n]:r??`variation_${a}`,[`${n}_id`]:a}),this.track("$experiment_started",{$experiment_key:e,$experiment_variation_id:a,$experiment_variation_name:r??`variation_${a}`})}setPersonProperties(e){this.client?.capture("$set",{$set:e})}setPersonPropertiesOnce(e){this.client?.capture("$set",{$set_once:e})}getDistinctId(){return this.client?.get_distinct_id?.()}};function $b(t={}){return new Vb(t)}var kc=class{constructor(e,a){B(this,"telemetry");B(this,"variantId");B(this,"seenSet",new Set);B(this,"triggeredSet",new Set);this.telemetry=e,this.variantId=a}trackServed(e,a){this.telemetry.track?.("syntro_config_served",{variant_id:this.variantId,tiles:e,actions:a})}trackSeen(e,a){this.seenSet.has(e)||(this.seenSet.add(e),this.telemetry.track?.("syntro_intervention_seen",{variant_id:this.variantId,intervention_id:e,intervention_kind:a}))}trackTriggered(e,a){this.triggeredSet.has(e)||(this.triggeredSet.add(e),this.telemetry.track?.("syntro_intervention_triggered",{variant_id:this.variantId,intervention_id:e,intervention_kind:a}))}trackInteracted(e,a,r){this.telemetry.track?.("syntro_intervention_interacted",{variant_id:this.variantId,intervention_id:e,intervention_kind:a,interaction_type:r})}resetPage(){this.seenSet.clear(),this.triggeredSet.clear()}};var jb=async(t,e)=>{let a=[];if(e.applyAction)for(let r of t.actions){let n=await e.applyAction(r);a.push(n)}return{cleanup:async()=>{for(let r=a.length-1;r>=0;r--)try{await a[r].revert()}catch{}}}},Gb=async(t,e)=>{let a=[];if(e.applyAction){let r=t.actions.map(n=>e.applyAction(n));if(t.waitFor==="any"){let n=await Promise.race(r);a.push(n);let o=await Promise.allSettled(r);for(let i of o)i.status==="fulfilled"&&i.value!==n&&a.push(i.value)}else{let n=await Promise.all(r);a.push(...n)}}return{cleanup:async()=>{for(let r of a)try{await r.revert()}catch{}}}},Wb=async(t,e)=>{let a,r,n=!1,o={cleanup:()=>{n=!0,r&&clearTimeout(r),a&&a()}};return t.event&&e.subscribeEvent?await new Promise(i=>{a=e.subscribeEvent(t.event,()=>{n||i()}),t.durationMs!==void 0&&(r=setTimeout(()=>{n||i()},t.durationMs))}):t.durationMs!==void 0&&await new Promise(i=>{r=setTimeout(()=>{n||i()},t.durationMs)}),o};var hh=class{constructor(){B(this,"executors",new Map);for(let{kind:e,executor:a}of xv)this.registerCore(e,a);for(let{kind:e,executor:a}of Rv)this.registerCore(e,a);this.registerCore("core:mountWidget",async()=>{throw new Error("core:mountWidget must be handled by ActionEngine")}),this.registerCore("core:sequence",jb),this.registerCore("core:parallel",Gb),this.registerCore("core:wait",Wb)}registerCore(e,a,r){this.executors.set(e,{kind:e,executor:a,schema:r,source:"core",isBuiltIn:!0})}register(e,a,r,n="custom",o=!1){if(this.executors.has(e)){if(this.executors.get(e).isBuiltIn)return;console.warn(`[ExecutorRegistry] Overriding executor for kind: ${e} (source: ${n})`)}console.log(`[ExecutorRegistry] Registered executor: ${e} (source: ${n})`),this.executors.set(e,{kind:e,executor:a,schema:r,source:n,isBuiltIn:o})}unregister(e){let a=this.executors.get(e);return a?a.isBuiltIn?(console.warn(`[ExecutorRegistry] Cannot unregister built-in executor: ${e}`),!1):(this.executors.delete(e),!0):!1}unregisterBySource(e){for(let[a,r]of this.executors.entries())r.source===e&&this.executors.delete(a)}get(e){return this.executors.get(e)?.executor}getRegistration(e){return this.executors.get(e)}has(e){return this.executors.has(e)}validate(e){let a=[];if(!e||typeof e!="object")return a.push({code:"INVALID_ACTION",message:"Action must be an object"}),{valid:!1,errors:a,warnings:[]};let{kind:r}=e;if(!r||typeof r!="string")return a.push({code:"MISSING_KIND",message:"Action must have a 'kind' property"}),{valid:!1,errors:a,warnings:[]};let n=this.executors.get(r);if(!n)return a.push({code:"UNKNOWN_KIND",message:`Unknown action kind: ${r}`,field:"kind"}),{valid:!1,errors:a,warnings:[]};if(n.schema){let o=n.schema.safeParse(e);if(!o.success){for(let i of o.error.issues)a.push({code:"SCHEMA_VALIDATION_ERROR",message:i.message,field:i.path.join(".")});return{valid:!1,errors:a,warnings:[]}}}return{valid:!0,errors:[],warnings:[]}}list(){return Array.from(this.executors.keys())}listRegistrations(){return Array.from(this.executors.values())}getBuiltInKinds(){return Array.from(this.executors.entries()).filter(([,e])=>e.isBuiltIn).map(([e])=>e)}getCustomKinds(){return Array.from(this.executors.entries()).filter(([,e])=>!e.isBuiltIn).map(([e])=>e)}},xn=new hh;function d4(t){return xn.get(t)}function Zb(t){return xn.has(t)}function Xb(t,e,a){!t.content||typeof t.content!="string"?e.push({code:"MISSING_CONTENT",message:"Badge action requires 'content' property",field:"content"}):t.content.length>100&&a.push({code:"LONG_BADGE_CONTENT",message:"Badge content is quite long",suggestion:"Keep badge content short (under 100 characters)"})}function Kb(t,e,a){if(!t.content||typeof t.content!="object"){e.push({code:"MISSING_CONTENT",message:"Tooltip action requires 'content' object",field:"content"});return}(!t.content.body||typeof t.content.body!="string")&&e.push({code:"MISSING_BODY",message:"Tooltip content requires 'body' property",field:"content.body"})}function Yb(t,e,a){!t.html||typeof t.html!="string"?e.push({code:"MISSING_HTML",message:"insertHtml action requires 'html' property",field:"html"}):t.html.length>mh&&e.push({code:"HTML_TOO_LONG",message:`HTML content exceeds maximum length of ${mh}`,field:"html"});let r=["before","after","prepend","append","replace"];(!t.position||!r.includes(t.position))&&e.push({code:"INVALID_POSITION",message:`Position must be one of: ${r.join(", ")}`,field:"position"})}function Qb(t,e,a){(t.text===void 0||t.text===null)&&e.push({code:"MISSING_TEXT",message:"setText action requires 'text' property",field:"text"})}function Jb(t,e,a){!t.attr||typeof t.attr!="string"?e.push({code:"MISSING_ATTR",message:"setAttr action requires 'attr' property",field:"attr"}):(u0.has(t.attr.toLowerCase())||t.attr.toLowerCase().startsWith("on"))&&e.push({code:"DANGEROUS_ATTR",message:`Event handler attributes are not allowed: ${t.attr}`,field:"attr"}),(t.value===void 0||t.value===null)&&e.push({code:"MISSING_VALUE",message:"setAttr action requires 'value' property",field:"value"})}function e0(t,e,a){!t.className||typeof t.className!="string"?e.push({code:"MISSING_CLASS_NAME",message:"Class action requires 'className' property",field:"className"}):/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t.className)||a.push({code:"INVALID_CLASS_NAME",message:"Class name contains unusual characters",suggestion:"Use alphanumeric characters, hyphens, and underscores"})}function t0(t,e,a){if(!t.styles||typeof t.styles!="object")e.push({code:"MISSING_STYLES",message:"setStyle action requires 'styles' object",field:"styles"});else{let r=Object.keys(t.styles).length;r>gh&&e.push({code:"TOO_MANY_STYLES",message:`Too many styles (${r}). Maximum is ${gh}`,field:"styles"});for(let[n,o]of Object.entries(t.styles))typeof o=="string"&&o.includes("expression(")&&e.push({code:"DANGEROUS_STYLE",message:`Style expressions are not allowed: ${n}`,field:`styles.${n}`})}}function a0(t,e,a){(!t.slot||typeof t.slot!="string")&&e.push({code:"MISSING_SLOT",message:"mountWidget action requires 'slot' property",field:"slot"}),!t.widget||typeof t.widget!="object"?e.push({code:"MISSING_WIDGET",message:"mountWidget action requires 'widget' object",field:"widget"}):(!t.widget.widgetId||typeof t.widget.widgetId!="string")&&e.push({code:"MISSING_WIDGET_ID",message:"Widget must have a 'widgetId' property",field:"widget.widgetId"})}function r0(t,e,a){t.durationMs===void 0&&!t.event&&e.push({code:"MISSING_WAIT_CONFIG",message:"wait action requires either 'durationMs' or 'event' property"}),t.durationMs!==void 0&&t.durationMs<0&&e.push({code:"INVALID_DURATION",message:"durationMs must be a positive number",field:"durationMs"}),t.event!==void 0&&typeof t.event!="string"&&e.push({code:"INVALID_EVENT",message:"event must be a string",field:"event"})}function n0(t,e,a){if(!t.actions||!Array.isArray(t.actions)){e.push({code:"MISSING_ACTIONS",message:"sequence action requires 'actions' array",field:"actions"});return}t.actions.length===0&&a.push({code:"EMPTY_SEQUENCE",message:"sequence has no actions",suggestion:"Add at least one action to the sequence"});for(let r=0;r<t.actions.length;r++){let n=Ar(t.actions[r]);for(let o of n.errors)e.push({...o,field:`actions[${r}]${o.field?`.${o.field}`:""}`});for(let o of n.warnings)a.push(o)}}function o0(t,e,a){if(!t.actions||!Array.isArray(t.actions)){e.push({code:"MISSING_ACTIONS",message:"parallel action requires 'actions' array",field:"actions"});return}t.actions.length===0&&a.push({code:"EMPTY_PARALLEL",message:"parallel has no actions",suggestion:"Add at least one action to the parallel group"}),t.waitFor&&!["all","any"].includes(t.waitFor)&&e.push({code:"INVALID_WAIT_FOR",message:"waitFor must be 'all' or 'any'",field:"waitFor"});for(let r=0;r<t.actions.length;r++){let n=Ar(t.actions[r]);for(let o of n.errors)e.push({...o,field:`actions[${r}]${o.field?`.${o.field}`:""}`});for(let o of n.warnings)a.push(o)}}function i0(t,e,a){if(!t.url||typeof t.url!="string")e.push({code:"MISSING_URL",message:"navigate action requires 'url' property",field:"url"});else{let r=t.url.trim().toLowerCase();r.startsWith("javascript:")&&e.push({code:"DANGEROUS_URL",message:"javascript: URLs are not allowed",field:"url"}),r.startsWith("data:")&&a.push({code:"DATA_URL",message:"data: URLs may have limited support",suggestion:"Consider using a regular URL instead"})}}function s0(t,e,a){if(!t.content||typeof t.content!="object"){e.push({code:"MISSING_CONTENT",message:"Modal action requires 'content' object",field:"content"});return}if((!t.content.body||typeof t.content.body!="string")&&e.push({code:"MISSING_BODY",message:"Modal content requires 'body' property",field:"content.body"}),t.size&&!["sm","md","lg"].includes(t.size)&&e.push({code:"INVALID_SIZE",message:"Modal size must be 'sm', 'md', or 'lg'",field:"size"}),t.ctaButtons)if(!Array.isArray(t.ctaButtons))e.push({code:"INVALID_CTA_BUTTONS",message:"ctaButtons must be an array",field:"ctaButtons"});else for(let r=0;r<t.ctaButtons.length;r++){let n=t.ctaButtons[r];(!n.label||typeof n.label!="string")&&e.push({code:"MISSING_BUTTON_LABEL",message:`CTA button at index ${r} requires 'label' property`,field:`ctaButtons[${r}].label`}),(!n.actionId||typeof n.actionId!="string")&&e.push({code:"MISSING_BUTTON_ACTION_ID",message:`CTA button at index ${r} requires 'actionId' property`,field:`ctaButtons[${r}].actionId`})}}function l0(t,e,a){if((!t.tourId||typeof t.tourId!="string")&&e.push({code:"MISSING_TOUR_ID",message:"Tour action requires 'tourId' property",field:"tourId"}),!t.steps||!Array.isArray(t.steps)){e.push({code:"MISSING_STEPS",message:"Tour action requires 'steps' array",field:"steps"});return}t.steps.length===0&&e.push({code:"EMPTY_STEPS",message:"Tour must have at least one step",field:"steps"});let r=new Set;for(let n=0;n<t.steps.length;n++){let o=t.steps[n];if(!o.id||typeof o.id!="string"?e.push({code:"MISSING_STEP_ID",message:`Step at index ${n} requires 'id' property`,field:`steps[${n}].id`}):(r.has(o.id)&&e.push({code:"DUPLICATE_STEP_ID",message:`Duplicate step ID: ${o.id}`,field:`steps[${n}].id`}),r.add(o.id)),!o.action)e.push({code:"MISSING_STEP_ACTION",message:`Step at index ${n} requires 'action' property`,field:`steps[${n}].action`});else{let i=Ar(o.action);for(let s of i.errors)e.push({...s,field:`steps[${n}].action${s.field?`.${s.field}`:""}`});for(let s of i.warnings)a.push(s)}if(o.onAction)for(let[i,s]of Object.entries(o.onAction))s!=="end"&&!t.steps.some(l=>l.id===s)&&a.push({code:"UNKNOWN_TARGET_STEP",message:`Step "${o.id}" references unknown target step: ${s}`,suggestion:`Make sure step "${s}" exists in the tour`})}}var u0=new Set(["onclick","onerror","onload","onmouseover","onfocus","onblur","onchange","onsubmit","onkeydown","onkeyup","onkeypress"]),mh=5e4,gh=50;function Ar(t){let e=[],a=[];if(!t||typeof t!="object")return e.push({code:"INVALID_ACTION",message:"Action must be an object"}),{valid:!1,errors:e,warnings:a};let{kind:r}=t;if(!r||typeof r!="string")return e.push({code:"MISSING_KIND",message:"Action must have a 'kind' property"}),{valid:!1,errors:e,warnings:a};if(!Zb(r)&&r!=="core:mountWidget"){let n=xn.list();return console.error(`[ActionValidation] Unknown action kind: "${r}". Registered kinds (${n.length}): [${n.join(", ")}]. This usually means the app that provides "${r}" hasn't been activated yet, or the executor was never registered in ExecutorRegistry.`),e.push({code:"UNKNOWN_KIND",message:`Unknown action kind: ${r}`,field:"kind"}),{valid:!1,errors:e,warnings:a}}switch(r){case"overlays:highlight":case"overlays:pulse":case"navigation:scrollTo":bn(t,e,a);break;case"overlays:badge":bn(t,e,a),Xb(t,e,a);break;case"overlays:tooltip":bn(t,e,a),Kb(t,e,a);break;case"overlays:modal":s0(t,e,a);break;case"content:insertHtml":bn(t,e,a),Yb(t,e,a);break;case"content:setText":bn(t,e,a),Qb(t,e,a);break;case"content:setAttr":bn(t,e,a),Jb(t,e,a);break;case"content:addClass":case"content:removeClass":bn(t,e,a),e0(t,e,a);break;case"content:setStyle":bn(t,e,a),t0(t,e,a);break;case"core:mountWidget":a0(t,e,a);break;case"core:wait":r0(t,e,a);break;case"core:sequence":n0(t,e,a);break;case"core:parallel":o0(t,e,a);break;case"overlays:tour":l0(t,e,a);break;case"navigation:navigate":i0(t,e,a);break}return{valid:e.length===0,errors:e,warnings:a}}function bn(t,e,a){let r=t.anchorId;if(!r||typeof r!="object"){e.push({code:"MISSING_ANCHOR_ID",message:"Action requires an 'anchorId' object with a 'selector' string",field:"anchorId"});return}if(!r.selector||typeof r.selector!="string"?e.push({code:"MISSING_ANCHOR_SELECTOR",message:"anchorId requires a 'selector' string",field:"anchorId.selector"}):r.selector.length>200&&a.push({code:"LONG_ANCHOR_ID",message:"Anchor selector is unusually long",suggestion:"Consider using a shorter, more descriptive selector"}),r.route===void 0||r.route===null)e.push({code:"MISSING_ANCHOR_ROUTE",message:`anchorId requires a 'route' (string or array of strings). Use "**" for all routes.`,field:"anchorId.route"});else{let n=Array.isArray(r.route)?r.route:[r.route];for(let o of n)if(typeof o!="string"){e.push({code:"INVALID_ANCHOR_ROUTE",message:"anchorId.route must be a string or array of strings",field:"anchorId.route"});break}}}function vh(t){let e=[],a=[];if(!Array.isArray(t))return console.error("[ActionValidation] validateActions called with non-array:",typeof t),e.push({code:"INVALID_ACTIONS",message:"Actions must be an array"}),{valid:!1,errors:e,warnings:a};for(let r=0;r<t.length;r++){let n=Ar(t[r]);if(!n.valid){let o=t[r];console.error(`[ActionValidation] Action [${r}] failed validation:`,`kind="${o?.kind??"undefined"}"`,n.errors.map(i=>`${i.code}: ${i.message}`).join("; "),o)}for(let o of n.errors)e.push({...o,field:o.field?`[${r}].${o.field}`:`[${r}]`});for(let o of n.warnings)a.push({...o,suggestion:o.suggestion?`Action ${r}: ${o.suggestion}`:void 0})}return e.length>0&&console.error(`[ActionValidation] Batch validation failed: ${e.length} error(s) in ${t.length} action(s).`,e.map(r=>`${r.field??"?"}: ${r.message}`).join(" | ")),{valid:e.length===0,errors:e,warnings:a}}var f4=0;function c0(t){let{overlayRoot:e,eventBus:a,surfaces:r,anchorResolver:n,waitForAnchor:o,adaptiveId:i,executorRegistry:s=xn,subscribeNavigation:l,runtime:u}=t,c=new Map,d=new Map;function f(){return`action-${++f4}`}function h(_,L){a&&a.publish(_,L)}function S(){return{overlayRoot:e,resolveAnchor:n,waitForAnchor:o,generateId:f,publishEvent:h,adaptiveId:i,applyAction:m,subscribeEvent:a?(_,L)=>a.subscribe({names:[_]},A=>L(A.props)):void 0,subscribeNavigation:l}}async function x(_,L){if(!r)throw new Error("Surfaces provider required for core:mountWidget actions");let A=r.mount(_.slot,{type:"widget",widgetId:_.widget.widgetId,config:_.widget.props},{priority:_.widget.priority});return L.publishEvent("action.applied",{id:L.generateId(),kind:"core:mountWidget",slot:_.slot,widgetId:_.widget.widgetId}),{cleanup:()=>{A.unmount()},updateFn:I=>{if("widget"in I&&I.widget){let R=I.widget;R.props&&A.update({type:"widget",widgetId:_.widget.widgetId,config:R.props})}}}}async function b(_,L){if(_.kind==="core:mountWidget")return x(_,L);let A=s.get(_.kind);if(!A){let I="list"in s?s.list():"(list unavailable)";throw console.error(`[ActionEngine] No executor for kind="${_.kind}".`,`Registered: [${I}]`),new Error(`No executor for action kind: ${_.kind}`)}return A(_,L)}function g(_,L,A,I){if(!u)return;let R=[],H=async()=>{let E=c.get(_);if(!E)return;let D=u.evaluateSync(A).value;if(E.state==="applied"&&!D){try{await E.cleanup()}catch(F){console.error(`[ActionEngine] Error reverting conditional action ${_}:`,F)}E.state="deferred",E.cleanup=()=>{},E.updateFn=void 0,h("action.deferred",{id:_,kind:L.kind})}else if(E.state==="deferred"&&D)try{let F=S(),Z=await b(L,F);E.state="applied",E.cleanup=Z.cleanup,E.updateFn=Z.updateFn,E.appliedTs=Date.now(),h("action.applied",{id:_,kind:L.kind,anchorId:"anchorId"in L?L.anchorId:void 0})}catch(F){console.error(`[ActionEngine] Error applying deferred action ${_}:`,F),E.state="failed"}};u.context&&R.push(u.context.subscribe(H)),u.accumulator&&R.push(u.accumulator.subscribe(H)),d.set(_,R)}async function m(_){let L=Ar(_);if(!L.valid){let D=L.errors.map(F=>F.message).join("; ");throw console.error(`[ActionEngine] Validation failed for action kind="${_?.kind}":`,D,_),new Error(`Action validation failed: ${D}`)}let A=f(),I=_.triggerWhen;if(I&&u&&!u.evaluateSync(I).value){let F={id:A,action:_,adaptiveId:i,appliedTs:Date.now(),state:"deferred",cleanup:()=>{}};c.set(A,F);let Z={id:A,action:_,async revert(){let U=c.get(A);if(!U)return;let W=d.get(A);if(W){for(let ce of W)ce();d.delete(A)}U.state="reverted",c.delete(A)},isApplied(){return c.get(A)?.state==="applied"},async update(U){let W=c.get(A);if(!W||W.state!=="applied")throw new Error("Cannot update action that is not applied");if(W.updateFn)await W.updateFn(U);else throw new Error(`Action kind ${_.kind} does not support updates`)},getState(){return c.get(A)?.state??"reverted"}};return g(A,_,I,Z),Z}let R=S(),H=await b(_,R),E={id:A,action:_,adaptiveId:i,appliedTs:Date.now(),state:"applied",cleanup:H.cleanup,updateFn:H.updateFn};c.set(A,E),h("action.applied",{id:A,kind:_.kind,anchorId:"anchorId"in _?_.anchorId:void 0});let M={id:A,action:_,async revert(){let D=c.get(A);if(!D||D.state!=="applied")return;let F=d.get(A);if(F){for(let Z of F)Z();d.delete(A)}try{await D.cleanup(),D.state="reverted",h("action.reverted",{id:A,kind:_.kind})}catch(Z){console.warn(`[ActionEngine] Cleanup error for ${_.kind} (${A}), ignoring:`,Z),D.state="reverted",h("action.reverted",{id:A,kind:_.kind})}finally{c.delete(A)}},isApplied(){return c.get(A)?.state==="applied"},async update(D){let F=c.get(A);if(!F||F.state!=="applied")throw new Error("Cannot update action that is not applied");if(F.updateFn)await F.updateFn(D);else throw new Error(`Action kind ${_.kind} does not support updates`)},getState(){return c.get(A)?.state??"reverted"}};return I&&u&&g(A,_,I,M),M}async function y(_){console.log(`[ActionEngine] applyBatch: ${_.length} action(s)`,_.map(E=>E.kind).join(", "));let L=vh(_);if(!L.valid){let E=L.errors.map(M=>M.message).join("; ");throw console.error(`[ActionEngine] Batch validation FAILED for ${_.length} action(s):`,E,`
502
502
  Actions:`,_.map((M,D)=>` [${D}] ${M.kind} ${M.anchorId?`anchor="${M.anchorId.selector}"`:""} ${M.label?`label="${M.label}"`:""}`).join(`
503
- `)),new Error(`Batch validation failed: ${E}`)}let A=f(),I=[],R=[];try{for(let E of _){let M=await m(E);I.push(M),R.push(M)}}catch(E){console.error(`[ActionEngine] Batch apply FAILED at action ${R.length+1}/${_.length}.`,`Successfully applied: ${R.length}. Rolling back...`,E);for(let M of R)try{await M.revert()}catch{}throw E}return{id:A,handles:I,async revertAll(){for(let E=I.length-1;E>=0;E--)try{await I[E].revert()}catch(M){console.error(`[ActionEngine] Error reverting action ${I[E].id}:`,M)}},isApplied(){return I.every(E=>E.isApplied())}}}function v(_){return Ar(_)}function C(){return Array.from(c.values()).map(_=>({id:_.id,action:_.action,adaptiveId:_.adaptiveId,appliedTs:_.appliedTs,state:_.state}))}function w(){for(let _ of d.values())for(let L of _)try{L()}catch{}d.clear();for(let _ of c.values())if(_.state==="applied")try{_.cleanup()}catch(L){console.error("[ActionEngine] Error during cleanup:",L)}c.clear()}return{apply:m,applyBatch:y,validate:v,getActive:C,destroy:w}}var p4=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),CT=["ui.click","ui.scroll","ui.input","ui.change","ui.submit","ui.hover","ui.idle","ui.scroll_thrash","ui.focus_bounce","nav.page_view","nav.page_leave","behavior.rage_click","behavior.hesitation","behavior.confusion"],wT=p.enum(CT).describe("Event name to count. ui.* = user interactions and behavioral detectors, nav.* = page navigation, behavior.* = derived behavioral signals."),LT=["time_on_page","page_views","scroll_depth"],kT=p.enum(LT).describe("Session metric key. time_on_page = seconds on current page, page_views = pages visited this session, scroll_depth = 0-100 percentage.");var d0=p.object({type:p.literal("page_url"),url:p.string().describe('URL path to match (e.g. "/pricing", "/dashboard")')}).describe('Fires when the current page URL matches. Use for page-specific actions. Example: {"type": "page_url", "url": "/pricing"}'),f0=p.object({type:p.literal("route"),routeId:p.string().describe("Named route ID from the route filter")}).describe("Fires when the current route matches a named route ID."),p0=p.object({type:p.literal("anchor_visible"),anchorId:p.string().describe("CSS selector of the anchor element"),state:p.enum(["visible","present","absent"]).describe('"visible" = in viewport, "present" = in DOM, "absent" = not in DOM')}).describe(`Fires based on a DOM element's visibility state. Example: {"type": "anchor_visible", "anchorId": "#cta-button", "state": "visible"}`),h0=p.object({type:p.literal("event_occurred"),eventName:p.string().describe('Event name (e.g. "ui.click", "$pageview")'),withinMs:p.number().optional().describe("Time window in ms. Omit = any time this session.")}).describe('Fires when a specific event has occurred during this session. Example: {"type": "event_occurred", "eventName": "ui.click", "withinMs": 5000}'),m0=p.object({type:p.literal("state_equals"),key:p.string().describe("Key in the SDK persistent state store (localStorage). Only valid for keys the host app explicitly sets via syntro.state.set()."),value:p.unknown().describe("Expected value to match against")}).describe("Checks the SDK persistent state store (localStorage). ONLY for host-app state set via syntro.state.set() \u2014 NOT for user attributes like region, device, or UTM params (those are handled by segment targeting). Do NOT use this for targeting. If you do not know the valid state keys, do not use this condition type."),g0=p.object({type:p.literal("viewport"),minWidth:p.number().optional().describe("Minimum viewport width in pixels"),maxWidth:p.number().optional().describe("Maximum viewport width in pixels"),minHeight:p.number().optional().describe("Minimum viewport height in pixels"),maxHeight:p.number().optional().describe("Maximum viewport height in pixels")}).describe('Fires based on viewport (screen) size. Use for responsive behavior. Example: {"type": "viewport", "minWidth": 768} \u2014 fires on tablet and larger.'),v0=p.object({type:p.literal("session_metric"),key:kT,operator:p.enum(["gte","lte","eq","gt","lt"]),threshold:p.number().describe("Numeric threshold to compare against")}).describe('Fires when a session metric crosses a threshold. Valid keys: "time_on_page" (seconds), "page_views" (count), "scroll_depth" (0-100). Example: {"type": "session_metric", "key": "time_on_page", "operator": "gte", "threshold": 30}'),y0=p.object({type:p.literal("dismissed"),key:p.string().describe("Dismissal key (usually a tile or action ID)"),inverted:p.boolean().optional().describe("When true, fires if NOT dismissed (default behavior)")}).describe("Checks if an item has been dismissed by the user. Use with inverted: true to show only if not dismissed."),x0=p.object({type:p.literal("cooldown_active"),key:p.string().describe("Cooldown key"),inverted:p.boolean().optional().describe("When true, fires if cooldown is NOT active")}).describe("Checks if a cooldown timer is currently active. Use to prevent showing the same intervention too frequently."),b0=p.object({type:p.literal("frequency_limit"),key:p.string().describe("Frequency counter key"),limit:p.number().describe("Maximum allowed count"),inverted:p.boolean().optional().describe("When true, fires if limit NOT reached")}).describe("Checks if a frequency limit has been reached. Use to cap how many times an action fires per session."),Ic=p.object({equals:p.union([p.string(),p.number(),p.boolean()]).optional(),contains:p.string().optional()}).describe("Match operator for counter filters. Exactly one of equals or contains must be specified."),Ac=p.object({events:p.array(wT).min(1).describe("Event names to count. Use values from the countable events enum."),match:p.record(p.string(),Ic).optional().describe("Property filters. Keys are event prop names or element-chain fields (tag_name, $el_text, attr__*). All entries AND together.")}).describe("Defines what events to count. Registered as an accumulator predicate at config-load time."),S0=p.object({type:p.literal("event_count"),key:p.string().describe("Unique key for this counter (used for accumulator registration)"),operator:p.enum(["gte","lte","eq","gt","lt"]),count:p.number().int().min(0).describe("Target count threshold"),withinMs:p.number().positive().optional().describe("Time window in ms. Omit = count across entire session."),counter:Ac.optional().describe("Inline counter definition. Defines what events to count.")}).describe('Fires when accumulated event count crosses a threshold. Most powerful trigger type. Example: {"type": "event_count", "key": "pricing-clicks", "operator": "gte", "count": 3, "counter": {"events": ["ui.click"], "match": {"attr__data-cta": {"contains": "pricing"}}}}'),Lo=p.discriminatedUnion("type",[d0,f0,p0,h0,m0,g0,v0,y0,x0,b0,S0]),Ec=p.object({conditions:p.array(Lo).describe("Array of conditions \u2014 ALL must match (AND logic) for this rule to fire."),value:p.unknown().describe("Value returned when all conditions match. For triggerWhen: true = fire the action.")}).describe("A single rule. ALL conditions must match (AND logic). Rules in a strategy are evaluated top-to-bottom \u2014 first rule where all conditions match wins and returns its value."),Tc=p.object({type:p.literal("rules"),rules:p.array(Ec).describe("Ordered list of rules. Evaluated top-to-bottom \u2014 first match wins."),default:p.unknown().describe("Fallback value when no rule matches. For triggerWhen: false = do not fire by default.")}).describe("Rule-based strategy. Evaluates rules top-to-bottom. First rule where ALL conditions match returns its value. If no rule matches, returns default. For triggerWhen: set value=true on matching rules, default=false."),Rc=p.object({type:p.literal("score"),field:p.string(),threshold:p.number(),above:p.unknown(),below:p.unknown()}).describe("Score-based strategy. Compares a field value against a threshold."),Mc=p.object({type:p.literal("model"),modelId:p.string(),inputs:p.array(p.string()),outputMapping:p.record(p.string(),p.unknown()),default:p.unknown()}).describe("ML model strategy. Sends inputs to a model and maps outputs."),Oc=p.object({type:p.literal("external"),endpoint:p.string(),method:p.enum(["GET","POST"]).optional(),default:p.unknown(),timeoutMs:p.number().optional()}).describe("External API strategy. Calls an endpoint to determine the value."),Dc=p.discriminatedUnion("type",[Tc,Rc,Mc,Oc]),yh=Dc.nullable().optional();var h4=p.object({events:p.array(p.string()),urlContains:p.string().optional(),props:p.record(p.union([p.string(),p.number(),p.boolean()])).optional()}),m4=p.object({title:p.string().optional(),body:p.string().optional(),icon:p.string().optional()}).nullable().optional();var IT=p.object({include:p.array(p.string()).optional().describe("URL patterns where this tile appears. Supports *, **, :param wildcards. Use sparingly \u2014 mostly to isolate to specific webapp functionality. Omit to appear on all routes."),exclude:p.array(p.string()).optional().describe("URL patterns where this tile should NOT appear. Evaluated before include.")}),xh=p.object({routes:IT,onlyIfPopulated:p.boolean().optional().describe("When true, tile is hidden if none of its props.actions[] have an active triggerWhen. Useful for tiles with all-deferred FAQ questions or nav tips. Default: false.")});function g9(t){return Lo.safeParse(t)}function v9(t){return Dc.safeParse(t)}function y9(t){return xh.safeParse(t)}var x9=[{defName:"matchOp",schema:Ic},{defName:"counterDef",schema:Ac},{defName:"activationConfig",schema:xh},{defName:"routeFilter",schema:IT},{defName:"ruleStrategy",schema:Tc},{defName:"scoreStrategy",schema:Rc},{defName:"modelStrategy",schema:Mc},{defName:"externalStrategy",schema:Oc},{defName:"rule",schema:Ec},{defName:"condition",schema:Lo}];var _0=p.object({tileId:p.string(),itemId:p.string().optional()}).strict(),g4=p.object({on:p.string(),title:p.string(),body:p.string().optional(),icon:p.string().optional(),ttl:p.number().optional(),cooldown:p.number().optional(),deepLink:_0.optional()}).strict(),v4=p.object({id:p.string(),title:p.string().optional(),subtitle:p.string().optional(),icon:p.string().optional(),priority:p.number().optional(),widget:p.string(),props:p.record(p.unknown()).optional(),activation:xh.optional(),notifications:p.array(g4).optional()}).strict(),y4=p.object({position:p.enum(["left","right"]).optional(),layout:p.enum(["overlay","push"]).optional(),background:p.string().optional(),blur:p.string().optional(),border:p.string().optional(),width:p.string().optional(),transitionDuration:p.string().optional(),transitionEasing:p.string().optional(),transitionFade:p.string().optional()}),x4=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),color:p.string().optional(),size:p.string().optional(),shadow:p.string().optional(),borderRadius:p.string().optional(),icon:p.string().optional()}),b4=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),shadow:p.string().optional(),titleColor:p.string().optional(),textColor:p.string().optional(),iconBackground:p.string().optional(),iconShadow:p.string().optional(),headerPadding:p.string().optional(),bodyPadding:p.string().optional(),gap:p.string().optional()}),S4=p.object({background:p.string().optional(),textColor:p.string().optional(),titleColor:p.string().optional(),arrowColor:p.string().optional(),arrowSize:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),scrimOpacity:p.string().optional(),highlightRing:p.string().optional()}),_4=p.object({background:p.string().optional(),textColor:p.string().optional(),textSecondaryColor:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),successColor:p.string().optional(),warningColor:p.string().optional(),errorColor:p.string().optional(),iconBackground:p.string().optional(),progressGradient:p.string().optional()}),C4=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),textColor:p.string().optional(),textSecondaryColor:p.string().optional(),itemDivider:p.string().optional(),itemGap:p.string().optional(),itemPadding:p.string().optional(),itemFontSize:p.string().optional(),bodyPadding:p.string().optional(),bodyFontSize:p.string().optional(),categoryPadding:p.string().optional(),categoryGap:p.string().optional(),categoryFontSize:p.string().optional(),searchBackground:p.string().optional(),searchColor:p.string().optional(),chevronColor:p.string().optional()}),w4=p.object({mode:p.enum(["dark","light"]).optional(),fontFamily:p.string().optional(),colorPrimary:p.string().optional(),colorPrimaryHover:p.string().optional(),borderRadius:p.string().optional(),canvas:y4.optional(),launcher:x4.optional(),tile:b4.optional(),overlay:S4.optional(),notification:_4.optional(),content:C4.optional()}).strict(),L4=p.object({enabled:p.boolean().optional(),label:p.string().optional(),position:p.string().optional(),animate:p.boolean().optional(),animationStyle:p.enum(["pulse","bounce","glow"]).optional(),notificationCount:p.number().optional()}).strict(),w9=p.object({schemaVersion:p.string().optional(),fetchedAt:p.string().datetime(),configVersion:p.string().optional(),canvasTitle:p.string().optional(),tiles:p.array(v4),actions:p.array(p.any()),theme:w4.optional(),launcher:L4.optional(),meta:p.object({verificationSteps:p.array(p.union([p.string(),p.object({text:p.string(),check:Lo.optional()})])).optional()}).passthrough().optional()}).strict();var Ct={triggerWhen:yh},Ga=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),AT=p.object({color:p.string().optional(),scrimOpacity:p.number().min(0).max(1).optional(),paddingPx:p.number().optional(),radiusPx:p.number().optional()}).strict(),ET=p.enum(["top-left","top-right","bottom-left","bottom-right"]),TT=p.enum(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),w0=p.object({label:p.string(),actionId:p.string(),primary:p.boolean().optional()}).strict(),RT=p.object({title:p.string().optional(),body:p.string(),ctaButtons:p.array(w0).optional()}).strict(),MT=p.object({title:p.string().optional(),body:p.string()}).strict(),OT=p.enum(["before","after","prepend","append","replace"]),DT=p.enum(["immediate","hover","click"]),BT=p.object({widgetId:p.string(),props:p.record(p.unknown()).optional(),priority:p.number().optional()}).strict(),PT=p.object({id:p.string(),action:p.any(),route:p.string().optional(),onAction:p.record(p.string()).optional()}).passthrough(),NT=p.enum(["auto","smooth","instant"]),C0=p.enum(["start","center","end","nearest"]),FT=p.object({kind:p.literal("content:setText"),anchorId:Ga,text:p.string(),label:p.string().optional()}).extend(Ct).strict(),HT=p.object({kind:p.literal("content:setAttr"),anchorId:Ga,attr:p.string(),value:p.string(),label:p.string().optional()}).extend(Ct).strict(),UT=p.object({kind:p.literal("content:addClass"),anchorId:Ga,className:p.string(),label:p.string().optional()}).extend(Ct).strict(),zT=p.object({kind:p.literal("content:removeClass"),anchorId:Ga,className:p.string(),label:p.string().optional()}).extend(Ct).strict(),qT=p.object({kind:p.literal("content:setStyle"),anchorId:Ga,styles:p.record(p.string()),label:p.string().optional()}).extend(Ct).strict(),VT=p.object({kind:p.literal("content:insertHtml"),anchorId:Ga,html:p.string(),position:OT,deepLink:_0.optional(),label:p.string().optional()}).extend(Ct).strict(),$T=p.object({kind:p.literal("overlays:highlight"),anchorId:Ga,style:AT.optional(),duration:p.number().optional(),label:p.string().optional()}).extend(Ct).strict(),jT=p.object({kind:p.literal("overlays:pulse"),anchorId:Ga,duration:p.number().optional(),label:p.string().optional()}).extend(Ct).strict(),GT=p.object({kind:p.literal("overlays:badge"),anchorId:Ga,content:p.string(),position:ET.optional(),label:p.string().optional()}).extend(Ct).strict(),WT=p.object({kind:p.literal("overlays:tooltip"),anchorId:Ga,content:RT,trigger:DT.optional(),placement:TT.optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(Ct).strict(),ZT=p.object({kind:p.literal("overlays:modal"),content:MT,size:p.enum(["sm","md","lg"]).optional(),blocking:p.boolean().optional(),scrim:p.object({opacity:p.number().min(0).max(1).optional()}).strict().optional(),dismiss:p.object({onEsc:p.boolean().optional(),closeButton:p.boolean().optional(),timeoutMs:p.number().min(0).optional()}).strict().optional(),ctaButtons:p.array(w0).optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(Ct).strict(),XT=p.object({kind:p.literal("navigation:scrollTo"),anchorId:Ga,behavior:NT.optional(),block:C0.optional(),inline:C0.optional(),label:p.string().optional()}).extend(Ct).strict(),KT=p.object({kind:p.literal("navigation:navigate"),url:p.string(),target:p.enum(["_self","_blank"]).optional(),label:p.string().optional()}).extend(Ct).strict(),YT=p.object({kind:p.literal("core:mountWidget"),slot:p.string(),widget:BT,label:p.string().optional()}).extend(Ct).strict(),QT=p.object({kind:p.literal("core:wait"),durationMs:p.number().min(0).optional(),event:p.string().optional(),label:p.string().optional()}).extend(Ct).strict(),JT=p.object({kind:p.literal("core:sequence"),actions:p.array(p.any()),label:p.string().optional()}).extend(Ct).strict(),eR=p.object({kind:p.literal("core:parallel"),actions:p.array(p.any()),waitFor:p.enum(["all","any"]).optional(),label:p.string().optional()}).extend(Ct).strict(),tR=p.object({kind:p.literal("overlays:tour"),tourId:p.string(),steps:p.array(PT).min(1),startStep:p.string().optional(),autoStart:p.boolean().optional(),label:p.string().optional()}).extend(Ct).passthrough(),k4=[{defName:"setText",schema:FT},{defName:"setAttr",schema:HT},{defName:"addClass",schema:UT},{defName:"removeClass",schema:zT},{defName:"setStyle",schema:qT},{defName:"insertHtml",schema:VT},{defName:"highlight",schema:$T},{defName:"pulse",schema:jT},{defName:"badge",schema:GT},{defName:"tooltip",schema:WT},{defName:"modal",schema:ZT},{defName:"scrollTo",schema:XT},{defName:"navigate",schema:KT},{defName:"mountWidget",schema:YT},{defName:"wait",schema:QT},{defName:"sequence",schema:JT},{defName:"parallel",schema:eR},{defName:"tour",schema:tR}];function L0(t){let e=t?.root??(typeof document<"u"?document.body:null),a=t?.defaultTimeoutMs??5e3,r=new Map,n=new Map,o=null,i=!1;function s(b){if(!e)return null;try{return e.matches(b)?e:e.querySelector(b)}catch{return null}}function l(){for(let[b,g]of r){let m=s(b);if(m){for(let y of g)clearTimeout(y.timer),y.resolve(m);r.delete(b)}}for(let[b,g]of n){let m=s(b);if(m){for(let y of g)y.cancelled||y.cb(m);n.delete(b)}}r.size===0&&n.size===0&&c()}function u(){o||i||typeof MutationObserver>"u"||!e||(o=new MutationObserver(()=>{l()}),o.observe(e,{childList:!0,subtree:!0}))}function c(){o&&(o.disconnect(),o=null)}function d(b,g){let m=r.get(b);m&&(m.delete(g),m.size===0&&r.delete(b)),r.size===0&&n.size===0&&c()}function f(b,g){if(i)return Promise.reject(new Error("AnchorResolver destroyed"));let m=s(b);if(m)return Promise.resolve(m);let y=g??a;return new Promise((v,C)=>{let w={resolve:v,reject:C,timer:setTimeout(()=>{d(b,w),C(new Error(`waitFor("${b}") timed out after ${y}ms`))},y)},_=r.get(b);_||(_=new Set,r.set(b,_)),_.add(w),u()})}function h(b,g){if(i)return()=>{};let m=s(b);if(m)return g(m),()=>{};let y={cb:g,cancelled:!1},v=n.get(b);return v||(v=new Set,n.set(b,v)),v.add(y),u(),()=>{y.cancelled=!0;let C=n.get(b);C&&(C.delete(y),C.size===0&&n.delete(b)),r.size===0&&n.size===0&&c()}}function S(){let b=0;for(let g of r.values())b+=g.size;return b}function x(){i=!0,c();let b=new Error("AnchorResolver destroyed");for(let g of r.values())for(let m of g)clearTimeout(m.timer),m.reject(b);r.clear(),n.clear()}return{resolve:s,waitFor:f,onAppear:h,pendingCount:S,destroy:x}}function I4(){let t=Date.now();return{page:{url:typeof window<"u"?window.location.href:"",title:typeof document<"u"?document.title:void 0},session:{sessionId:"",startTs:t,pageHistory:[]},viewport:{width:typeof window<"u"?window.innerWidth:0,height:typeof window<"u"?window.innerHeight:0}}}function k0(t,e){if(!e)return;let a;try{a=new URL(t).pathname}catch{a=t}if(e.exclude){for(let r of e.exclude)if(aR(a,r))return}if(e.include){for(let r of e.include)if(aR(a,r))return r;return}return a}function aR(t,e){let a=t.replace(/\/$/,"")||"/",r=e.replace(/\/$/,"")||"/";if(a===r)return!0;let n=r.replace(/:[^/]+/g,"[^/]+").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(a)}var bh=class{constructor(e){B(this,"context");B(this,"previousContext");B(this,"listeners",new Set);B(this,"telemetry");B(this,"routes");B(this,"navigation");B(this,"cleanupFns",[]);if(this.telemetry=e.telemetry,this.routes=e.routes,this.navigation=e.navigation,this.context=I4(),this.previousContext={...this.context},e.telemetry?.getSessionId){let a=e.telemetry.getSessionId();a&&(this.context.session.sessionId=a)}e.initialPageHistory&&(this.context.session.pageHistory=e.initialPageHistory),this.context.page.routeId=k0(this.context.page.url,this.routes),this.addPageToHistory(this.context.page.url),typeof window<"u"&&this.setupBrowserListeners()}get(){return{...this.context}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setRoutes(e){this.routes=e;let a=k0(this.context.page.url,this.routes);a!==this.context.page.routeId&&this.updateContext({page:{...this.context.page,routeId:a}})}setAnchors(e){this.updateContext({anchors:e})}setSessionId(e){e!==this.context.session.sessionId&&this.updateContext({session:{...this.context.session,sessionId:e}})}destroy(){for(let e of this.cleanupFns)e();this.cleanupFns=[],this.listeners.clear()}setupBrowserListeners(){let e,a=()=>{clearTimeout(e),e=setTimeout(()=>{this.updateViewport()},100)};window.addEventListener("resize",a),this.cleanupFns.push(()=>window.removeEventListener("resize",a));let r=this.navigation.subscribe(()=>this.updatePage());this.cleanupFns.push(r)}updateViewport(){let e={width:window.innerWidth,height:window.innerHeight};(e.width!==this.context.viewport.width||e.height!==this.context.viewport.height)&&this.updateContext({viewport:e})}updatePage(){let e=window.location.href,{title:a}=document,r=k0(e,this.routes),n={url:e,title:a,routeId:r};(n.url!==this.context.page.url||n.title!==this.context.page.title||n.routeId!==this.context.page.routeId)&&(n.url!==this.context.page.url&&this.addPageToHistory(n.url),this.updateContext({page:n}))}addPageToHistory(e){let a={url:e,ts:Date.now()},r=[...this.context.session.pageHistory||[],a];r.length>50&&r.shift(),this.context.session.pageHistory=r}updateContext(e){this.previousContext={...this.context},this.context={...this.context,...e},this.notifyListeners()}notifyListeners(){for(let e of this.listeners)try{e(this.context,this.previousContext)}catch(a){console.error("[ContextManager] Listener error:",a)}}};function I0(t){return new bh(t)}var A4=p.object({url:p.string(),routeId:p.string().optional(),title:p.string().optional(),locale:p.string().optional()}),E4=p.object({url:p.string(),ts:p.number()}),T4=p.object({sessionId:p.string(),startTs:p.number(),pageHistory:p.array(E4).optional()}),R4=p.object({width:p.number(),height:p.number()}),M4=p.object({x:p.number(),y:p.number(),w:p.number(),h:p.number()}),O4=p.object({anchorId:p.string(),present:p.boolean(),visible:p.boolean().optional(),boundingBox:M4.optional()}),D4=p.record(p.string(),p.union([p.number(),p.string(),p.boolean(),p.undefined()])),B4=p.object({page:A4,session:T4,viewport:R4,anchors:p.array(O4).optional(),augmented:D4.optional()});function z9(t){return B4.safeParse(t)}function rR(t,e){let{context:a,state:r,events:n}=e;switch(t.type){case"page_url":{let{url:o}=t,i=a.page.url.split("?")[0].split("#")[0],s=o.replace(/\*\*/g,"\0GLOBSTAR\0").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\0GLOBSTAR\0/g,".*");return new RegExp(`^${s}$`).test(i)}case"route":return a.page.routeId===t.routeId;case"anchor_visible":{let o=a.anchors?.find(i=>i.anchorId===t.anchorId);switch(t.state){case"visible":return o?.visible===!0;case"present":return o?.present===!0;case"absent":return!o?.present;default:return!1}}case"event_occurred":{if(!n)return!1;let o=t.withinMs??6e4;return n.hasRecentEvent(t.eventName,o)}case"state_equals":return r?.getValue?r.getValue(t.key)===t.value:!1;case"viewport":{let{width:o,height:i}=a.viewport;return!(t.minWidth!==void 0&&o<t.minWidth||t.maxWidth!==void 0&&o>t.maxWidth||t.minHeight!==void 0&&i<t.minHeight||t.maxHeight!==void 0&&i>t.maxHeight)}case"session_metric":{if(!r)return!1;let o=r.getSessionMetric(t.key),{operator:i,threshold:s}=t;switch(i){case"gte":return o>=s;case"lte":return o<=s;case"eq":return o===s;case"gt":return o>s;case"lt":return o<s;default:return!1}}case"dismissed":{if(!r)return t.inverted??!1;let o=r.isDismissed(t.key);return t.inverted?!o:o}case"cooldown_active":{if(!r)return t.inverted??!1;let o=r.isCooldownActive(t.key);return t.inverted?!o:o}case"frequency_limit":{if(!r)return t.inverted??!1;let i=r.getFrequencyCount(t.key)>=t.limit;return t.inverted?!i:i}case"event_count":{if(!e.accumulator)return!1;let o=t,i=e.accumulator.getCount(o.key,o.withinMs);switch(o.operator){case"gte":return i>=o.count;case"lte":return i<=o.count;case"eq":return i===o.count;case"gt":return i>o.count;case"lt":return i<o.count;default:return!1}}default:return console.warn("[RuleStrategy] Unknown condition type:",t.type),!1}}function nR(t,e){let a=[];for(let r of t.conditions){let n=rR(r,e);if(a.push({condition:r,result:n}),!n)return{matched:!1,conditionResults:a}}return{matched:!0,conditionResults:a}}function Sh(t,e){for(let a=0;a<t.rules.length;a++){let r=t.rules[a],{matched:n,conditionResults:o}=nR(r,e);if(n)return{value:r.value,isFallback:!1,matchInfo:{strategyType:"rules",matchedRuleIndex:a,evaluatedConditions:o}}}return{value:t.default,isFallback:!0,matchInfo:{strategyType:"rules"}}}function _h(t,e){let{context:a}=e,r=a.augmented?.[t.field];return r===void 0||typeof r!="number"?{value:t.below,isFallback:!0,matchInfo:{strategyType:"score"}}:{value:r>=t.threshold?t.above:t.below,isFallback:!1,matchInfo:{strategyType:"score"}}}function oR(t,e){let{state:a,events:r,sessionMetrics:n,accumulator:o}=e;return{context:t,state:a?{isDismissed:i=>a.dismissals.isDismissed(i),isCooldownActive:i=>a.cooldowns.isActive(i),getFrequencyCount:i=>a.frequency.count(i),getSessionMetric:i=>n?.get(i)??0,getValue:i=>a.session.get(i)??a.user.get(i)}:void 0,events:r?{hasRecentEvent:(i,s)=>r.hasRecentEvent(i,s)}:void 0,accumulator:o?{getCount:(i,s)=>o.getCount(i,s)}:void 0}}async function iR(t,e,a={}){let r=oR(e,a);switch(t.type){case"rules":return Sh(t,r);case"score":return _h(t,r);case"model":return{value:t.default,isFallback:!0,matchInfo:{strategyType:"model"}};case"external":return{value:t.default,isFallback:!0,matchInfo:{strategyType:"external"}};default:return console.warn("[DecisionEngine] Unknown strategy type:",t.type),{value:void 0,isFallback:!0,matchInfo:{strategyType:t.type}}}}function sR(t,e,a={}){let r=oR(e,a);switch(t.type){case"rules":return Sh(t,r);case"score":return _h(t,r);case"model":case"external":return{value:t.default,isFallback:!0,matchInfo:{strategyType:t.type}};default:return{value:void 0,isFallback:!0,matchInfo:{strategyType:t.type}}}}function A0(t){return{evaluate:(e,a)=>iR(e,a,t),evaluateSync:(e,a)=>sR(e,a,t)}}function E0(t){let{eventBus:e,stateStore:a}=t,r=new Map,n=new Set,o=null,i=a.ns("accumulator");function s(u){let c=!1;for(let d of r.values()){if(!d.predicate(u))continue;let f=i.get(d.stateKey)||{count:0};f.count++,d.needsTimestamps&&(f.timestamps||(f.timestamps=[]),f.timestamps.push(u.ts),f.timestamps.length>200&&(f.timestamps=f.timestamps.slice(-200))),i.set(d.stateKey,f),c=!0}if(c)for(let d of n)try{d()}catch(f){console.error("[EventAccumulator] Subscriber error:",f)}}function l(){o||r.size===0||(o=e.subscribe(s))}return{register(u,c,d=!1){let f=`ev:${u}`,h=r.get(f);if(h){d&&!h.needsTimestamps&&(h.needsTimestamps=!0);return}r.set(f,{stateKey:f,needsTimestamps:d,predicate:c}),l()},getCount(u,c){let d=`ev:${u}`,f=i.get(d);if(!f)return 0;if(c===void 0||!f.timestamps)return f.count;let h=Date.now()-c;return f.timestamps.filter(S=>S>=h).length},subscribe(u){return n.add(u),()=>{n.delete(u)}},destroy(){o&&(o(),o=null),r.clear(),n.clear()}}}var lR="app:",P4="syntro:",N4=/^[a-z][a-z0-9_]*$/;function T0(t){if(!t)return{valid:!1,reason:"Event name cannot be empty"};if(t.startsWith(P4))return{valid:!1,reason:'"syntro:" prefix is reserved for internal SDK events'};if(!t.startsWith(lR))return{valid:!1,reason:`Custom events must start with "app:" prefix. Got: "${t}"`};let e=t.slice(lR.length).split(":");if(e.length<2)return{valid:!1,reason:`Event name must have at least 2 segments after "app:" (app:{category}:{action}). Got: "${t}"`};for(let a of e)if(!N4.test(a))return{valid:!1,reason:`Segment "${a}" must be lowercase alphanumeric + underscores. Got: "${t}"`};return{valid:!0}}function F4(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t===null}function uR(t,e,a=0){if(a>=e)return!1;for(let r of Object.values(t))if(r!==null&&typeof r=="object"&&!Array.isArray(r)&&!uR(r,e,a+1))return!1;return!0}function R0(t){if(t===void 0)return{valid:!0};if(t===null||typeof t!="object"||Array.isArray(t))return{valid:!1,reason:"Props must be a plain object"};if(!uR(t,2))return{valid:!1,reason:"Props nesting depth exceeds 2 levels"};let e=[];for(let[a,r]of Object.entries(t))r!==null&&typeof r=="object"||F4(r)||e.push(a);return e.length>0?{valid:!0,stripped:e}:{valid:!0}}function Ch(t,e){return e?!(e.names&&e.names.length>0&&!e.names.includes(t.name)||e.patterns&&e.patterns.length>0&&!e.patterns.some(r=>{try{return new RegExp(r).test(t.name)}catch{return!1}})||e.sources&&e.sources.length>0&&!e.sources.includes(t.source)):!0}var wh=class{constructor(e={}){B(this,"subscriptions",new Set);B(this,"history",[]);B(this,"maxHistorySize");B(this,"debug");B(this,"emitHistory");B(this,"posthogCapture");B(this,"testMode");this.maxHistorySize=e.maxHistorySize??100,this.debug=e.debug??!1,this.emitHistory=e.history??null,this.posthogCapture=e.posthogCapture??null,this.testMode=e.testMode??!1}subscribe(e,a){let r,n;typeof e=="function"?(r=void 0,n=e):(r=e,n=a);let o={filter:r,callback:n};return this.subscriptions.add(o),()=>{this.subscriptions.delete(o)}}publish(e,a,r="canvas"){let n={ts:Date.now(),name:e,source:r,props:a,schemaVersion:rt};this.publishEvent(n)}publishEvent(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift();for(let a of this.subscriptions)if(Ch(e,a.filter))try{a.callback(e)}catch(r){console.error("[EventBus] Subscriber error:",r)}}emit(e,a){let r=T0(e);if(!r.valid)return console.warn(`[EventBus] emit() rejected: ${r.reason}`),this.debug?{delivered:!1,matchedRules:[],posthogCaptured:!1,listenersNotified:0}:void 0;let n=R0(a);if(!n.valid)return console.warn(`[EventBus] emit() rejected props: ${n.reason}`),this.debug?{delivered:!1,matchedRules:[],posthogCaptured:!1,listenersNotified:0}:void 0;let o={ts:Date.now(),name:e,source:"custom",props:a,schemaVersion:rt};this.history.push(o),this.history.length>this.maxHistorySize&&this.history.shift();let i=0;for(let l of this.subscriptions)if(Ch(o,l.filter))try{l.callback(o),i++}catch(u){console.error("[EventBus] Subscriber error:",u),i++}let s=!1;if(this.posthogCapture&&!this.testMode)try{this.posthogCapture(e,a),s=!0}catch(l){console.error("[EventBus] PostHog capture error:",l)}if(this.emitHistory&&this.emitHistory.record({name:e,props:a,source:"custom",timestamp:o.ts,matchedRules:[]}),this.debug)return console.debug("[EventBus] emit()",{name:e,props:a,listenersNotified:i,posthogCaptured:s}),{delivered:!0,matchedRules:[],posthogCaptured:s,listenersNotified:i}}setPosthogCapture(e){this.posthogCapture=e}getRecent(e,a){let r=this.history;return e&&(r=r.filter(n=>Ch(n,e))),a&&a>0&&(r=r.slice(-a)),r}hasRecentEvent(e,a,r){let n=Date.now()-a;return this.history.some(o=>o.name===e&&o.ts>=n&&(r===void 0||o.source===r))}countRecentEvents(e,a){let r=this.history.filter(n=>Ch(n,e));if(a!==void 0){let n=Date.now()-a;r=r.filter(o=>o.ts>=n)}return r.length}clearHistory(){this.history=[]}getSubscriberCount(){return this.subscriptions.size}};function Bc(t={}){return new wh(t)}var Pc=class{constructor(e=100){B(this,"entries",[]);B(this,"maxSize");this.maxSize=e}record(e){this.entries.push(e),this.maxSize>0&&this.entries.length>this.maxSize&&this.entries.shift()}getAll(){return[...this.entries]}clear(){this.entries=[]}};var cR=p.enum(["posthog","canvas","derived"]),H4=p.object({ts:p.number(),name:p.string(),source:cR,props:p.record(p.string(),p.unknown()).optional(),schemaVersion:p.string()}),U4=p.object({names:p.array(p.string()).optional(),patterns:p.array(p.string()).optional(),sources:p.array(cR).optional()});function mj(t){return H4.safeParse(t)}function gj(t){return U4.safeParse(t)}var Nc=class{constructor(){B(this,"listeners",new Set);B(this,"capturedPushState");B(this,"capturedReplaceState");B(this,"wasNative");B(this,"destroyed",!1);B(this,"onPopState",()=>{this.notify(window.location.href,"popstate")});this.wasNative=this.isNativeFunction(history.pushState),this.capturedPushState=history.pushState,this.capturedReplaceState=history.replaceState,history.pushState=(...e)=>{this.capturedPushState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"pushState"))},history.replaceState=(...e)=>{this.capturedReplaceState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"replaceState"))},window.addEventListener("popstate",this.onPopState)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}diagnose(){return{isNative:this.wasNative,subscriberCount:this.listeners.size}}destroy(){this.destroyed||(this.destroyed=!0,history.pushState=this.capturedPushState,history.replaceState=this.capturedReplaceState,window.removeEventListener("popstate",this.onPopState),this.listeners.clear())}notify(e,a){if(!this.destroyed)for(let r of this.listeners)try{r(e,a)}catch{}}isNativeFunction(e){try{return Function.prototype.toString.call(e).includes("[native code]")}catch{return!1}}};var M0="cooldown:";function dR(t){return{set(e,a){let r=M0+e,n=Date.now()+a;t.set(r,n)},isActive(e){return this.remaining(e)>0},remaining(e){let a=M0+e,r=t.get(a);if(r===void 0)return 0;let n=r-Date.now();return n<=0?(t.remove(a),0):n},clear(e){let a=M0+e;t.remove(a)}}}var Fc="dismissed:";function fR(t,e){return{mark(a,r=!1){let n=Fc+a;(r?e:t).set(n,!0)},isDismissed(a){let r=Fc+a;return t.has(r)||e.has(r)},clear(a){let r=Fc+a;t.remove(r),e.remove(r)},clearAll(){for(let a of t.keys())a.startsWith(Fc)&&t.remove(a);for(let a of e.keys())a.startsWith(Fc)&&e.remove(a)}}}var O0="freq:";function pR(t){function e(a){let r=O0+a,n=t.get(r);if(n){if(n.resetAt&&Date.now()>=n.resetAt){t.remove(r);return}return n}}return{increment(a,r){let n=O0+a,o=e(a),i=(o?.count??0)+1,s={count:i,resetAt:o?.resetAt??(r?Date.now()+r:void 0)};return t.set(n,s),i},count(a){return e(a)?.count??0},reset(a){let r=O0+a;t.remove(r)},hasReachedLimit(a,r){return this.count(a)>=r}}}var z4="syntro";function D0(t,e){let a=`${e}:`;return{get(r){if(t)try{let n=t.getItem(a+r);if(!n)return;let o=JSON.parse(n);if(o.expiresAt&&Date.now()>=o.expiresAt){t.removeItem(a+r);return}return o.value}catch{return}},set(r,n,o){if(t)try{let i={value:n,expiresAt:o?Date.now()+o:void 0};t.setItem(a+r,JSON.stringify(i))}catch(i){console.warn("[StateStore] Failed to save:",i)}},remove(r){t&&t.removeItem(a+r)},has(r){return t?this.get(r)!==void 0:!1},keys(){if(!t)return[];let r=[];for(let n=0;n<t.length;n++){let o=t.key(n);o?.startsWith(a)&&r.push(o.slice(a.length))}return r},clear(){if(!t)return;let r=this.keys();for(let n of r)t.removeItem(a+n)}}}function Hc(t){let e=new Map,a=`${t}:`;return{get(r){let n=e.get(a+r);if(n){if(n.expiresAt&&Date.now()>=n.expiresAt){e.delete(a+r);return}return n.value}},set(r,n,o){e.set(a+r,{value:n,expiresAt:o?Date.now()+o:void 0})},remove(r){e.delete(a+r)},has(r){return this.get(r)!==void 0},keys(){let r=[];for(let n of e.keys())n.startsWith(a)&&r.push(n.slice(a.length));return r},clear(){for(let r of e.keys())r.startsWith(a)&&e.delete(r)}}}var Lh=class{constructor(e={}){B(this,"session");B(this,"user");B(this,"dismissals");B(this,"cooldowns");B(this,"frequency");B(this,"namespace");B(this,"namespacedStorages",new Map);this.namespace=e.namespace??z4;let a=r=>typeof r=="object"&&r!==null&&typeof r.setItem=="function";typeof window<"u"?(this.session=a(window.sessionStorage)?D0(window.sessionStorage,this.namespace):Hc(this.namespace),this.user=a(window.localStorage)?D0(window.localStorage,this.namespace):Hc(this.namespace)):(this.session=Hc(this.namespace),this.user=Hc(this.namespace)),this.dismissals=fR(this.session,this.user),this.cooldowns=dR(this.user),this.frequency=pR(this.session)}ns(e){let a=`${this.namespace}:${e}`;if(!this.namespacedStorages.has(a)){let r=typeof window<"u"&&typeof sessionStorage<"u"?D0(sessionStorage,a):Hc(a);this.namespacedStorages.set(a,r)}return this.namespacedStorages.get(a)}};function B0(t={}){return new Lh(t)}function Uc(t){return t.startsWith("inline:")?"inline":t.startsWith("adjacent:")?"adjacent":"static"}function kh(t){return t.startsWith("inline:")?t.slice(7):t.startsWith("adjacent:")?t.slice(9):null}var hR={drawer_right:{position:"fixed",top:"0",right:"0",bottom:"0",width:"360px",maxWidth:"90vw"},drawer_left:{position:"fixed",top:"0",left:"0",bottom:"0",width:"360px",maxWidth:"90vw"},drawer_bottom:{position:"fixed",left:"0",right:"0",bottom:"0",maxHeight:"50vh"},overlay_center:{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)",maxWidth:"90vw",maxHeight:"90vh"},overlay_corner_br:{position:"fixed",bottom:"16px",right:"16px",maxWidth:"400px",maxHeight:"80vh"},overlay_corner_bl:{position:"fixed",bottom:"16px",left:"16px",maxWidth:"400px",maxHeight:"80vh"},toast_top:{position:"fixed",top:"16px",left:"50%",transform:"translateX(-50%)",maxWidth:"90vw"},toast_bottom:{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",maxWidth:"90vw"}},zc={fade:[{opacity:0},{opacity:1}],slide:[{opacity:0,transform:"translateY(10px)"},{opacity:1,transform:"translateY(0)"}],scale:[{opacity:0,transform:"scale(0.95)"},{opacity:1,transform:"scale(1)"}],none:[]},mR={duration:200,easing:"cubic-bezier(0.16, 1, 0.3, 1)",fill:"forwards"};function P0(t,e,a){let r=hR[e];Object.assign(t.style,r),a&&(a.maxWidth&&(t.style.maxWidth=a.maxWidth),a.maxHeight&&(t.style.maxHeight=a.maxHeight),a.minWidth&&(t.style.minWidth=a.minWidth),a.minHeight&&(t.style.minHeight=a.minHeight))}function N0(t,e,a){let r=a.placement==="auto"?"bottom":a.placement,n=[Df(a.offset?{mainAxis:a.offset.y,crossAxis:a.offset.x}:8)];return a.flip!==!1&&n.push(Pf()),a.shift!==!1&&n.push(Bf({padding:8})),t.style.position="absolute",t.style.zIndex="2147483646",Of(e,t,async()=>{let{x:i,y:s,strategy:l}=await Nf(e,t,{placement:r,middleware:n});Object.assign(t.style,{position:l,left:`${i}px`,top:`${s}px`})})}function F0(t,e,a="append"){return t.style.position="relative",t.style.display="inline-block",a==="prepend"?e.insertBefore(t,e.firstChild):e.appendChild(t),()=>{t.remove()}}function H0(t,e){return e==="none"||zc[e].length===0?null:t.animate(zc[e],mR)}function U0(t,e){if(e==="none"||zc[e].length===0)return Promise.resolve();let a=[...zc[e]].reverse(),r=t.animate(a,mR);return new Promise(n=>{r.onfinish=()=>n(),r.oncancel=()=>n()})}function z0(t,e){let a=document.createElement("div");return a.setAttribute("data-syntro-surface",t),a.setAttribute("data-syntro-mount-id",e),a.className="syntro-surface",Object.assign(a.style,{pointerEvents:"auto",boxSizing:"border-box",overflow:"auto"}),a}function q0(t){switch(Uc(t)){case"static":return t.startsWith("drawer")?2147483640:t.startsWith("overlay")?2147483642:t.startsWith("toast")?2147483644:2147483640;case"inline":return 1;case"adjacent":return 2147483638;default:return 2147483640}}function gR(t){if(typeof window.Sanitizer=="function")try{let l=new window.Sanitizer({}).sanitizeToFragment(t),u=document.createElement("div");return u.append(l),u.innerHTML}catch{}let a=document.createElement("template");a.innerHTML=t;let r=a.content,n=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),o=new Set(["b","strong","i","em","u","span","div","p","br","ul","ol","li","code","pre","small","sup","sub","a","button"]),i=[];for(;n.nextNode();){let s=n.currentNode,l=s.tagName.toLowerCase();if(!o.has(l)){i.push(s);continue}for(let u of Array.from(s.attributes)){let c=u.name.toLowerCase(),d=u.value.trim().toLowerCase(),f=c.startsWith("on"),h=(c==="href"||c==="src")&&d.startsWith("javascript:");(f||h)&&s.removeAttribute(u.name)}}for(let s of i){for(;s.firstChild;)s.parentNode?.insertBefore(s.firstChild,s);s.remove()}return a.innerHTML=(r.firstChild,a.innerHTML)}var q4=0;function V0(t){let{overlayRoot:e,eventBus:a,anchorResolver:r,defaultAnimation:n="fade",widgetRegistry:o}=t,i=new Map,s=new Map,l=new Map;function u(){return`mount-${++q4}`}function c(v,C){a&&a.publish(v,C)}function d(v){let C=l.get(v);if(C){let w=b(v);for(let _ of C)try{_(w)}catch(L){console.error("[Surfaces] State callback error:",L)}}}let f=new Map;function h(v,C,w){switch(C.type){case"html":v.innerHTML=gR(C.content);return;case"widget":{if(o?.has(C.widgetId)){let _=o.mount(C.widgetId,v,C.config);return w&&f.set(w,_),()=>{_.unmount(),w&&f.delete(w)}}console.warn(`[Surfaces] Widget not found: ${C.widgetId}`),v.innerHTML=`<div data-widget-id="${C.widgetId}" data-widget-missing="true">Widget: ${C.widgetId}</div>`;return}case"custom":return C.mount(v);case"react":v.innerHTML="<div data-react-component>React Component</div>";return;default:console.warn("[Surfaces] Unknown content type");return}}function S(v,C,w){let _=u(),L=Uc(v),A=w?.priority??0,I=w?.animation??n,R=w?.exclusive??!0,H=i.get(v);if(H&&R){if(H.options.priority>A)throw new Error(`Slot ${v} is occupied by higher priority content (${H.options.priority} > ${A})`);x(H)}let E=z0(v,_);E.style.zIndex=String(q0(v));let M;if(L==="static")P0(E,v,w?.constraints),e.appendChild(E);else if(L==="inline"){let U=kh(v);if(!U)throw new Error(`Invalid inline slot: ${v}`);if(!r)throw new Error("Anchor resolver required for inline slots");let W=r({selector:U,route:"**"});if(!W)throw new Error(`Anchor not found for inline slot: ${U}`);M=F0(E,W)}else if(L==="adjacent"){let U=kh(v);if(!U)throw new Error(`Invalid adjacent slot: ${v}`);if(!r)throw new Error("Anchor resolver required for adjacent slots");let W=r({selector:U,route:"**"});if(!W)throw new Error(`Anchor not found for adjacent slot: ${U}`);e.appendChild(E),M=N0(E,W,w?.position??{placement:"bottom"})}let D=h(E,C,_);H0(E,I);let F={id:_,slot:v,content:C,options:{priority:A,exclusive:R,animation:I,position:w?.position??{placement:"auto"},constraints:w?.constraints??{},adaptiveId:w?.adaptiveId,autoUnmountOnRouteChange:w?.autoUnmountOnRouteChange??!0},container:E,cleanup:()=>{M?.(),D?.()},mountedAt:Date.now()};return i.set(v,F),s.set(v,(s.get(v)??0)+1),c("surface.mounted",{slot:v,id:_,adaptiveId:w?.adaptiveId}),d(v),{id:_,update(U){let W=i.get(v);if(!W||W.id!==_)throw new Error("Mount no longer active");let ce=f.get(_);if(ce){if(U.type==="widget"){ce.update(U.config),W.content=U;return}ce.unmount(),f.delete(_)}W.container.innerHTML="";let Xt=h(W.container,U,_);if(W.content=U,Xt){let it=W.cleanup;W.cleanup=()=>{it?.(),Xt()}}},setOptions(U){let W=i.get(v);if(!W||W.id!==_)throw new Error("Mount no longer active");U.priority!==void 0&&(W.options.priority=U.priority),U.animation!==void 0&&(W.options.animation=U.animation),U.constraints&&L==="static"&&(U.constraints.maxWidth&&(W.container.style.maxWidth=U.constraints.maxWidth),U.constraints.maxHeight&&(W.container.style.maxHeight=U.constraints.maxHeight),U.constraints.minWidth&&(W.container.style.minWidth=U.constraints.minWidth),U.constraints.minHeight&&(W.container.style.minHeight=U.constraints.minHeight)),d(v)},async unmount(){let U=i.get(v);!U||U.id!==_||await x(U)},isMounted(){return i.get(v)?.id===_},getContainer(){let U=i.get(v);return U?.id===_?U.container:null}}}async function x(v){v.container.isConnected&&await U0(v.container,v.options.animation);try{v.cleanup?.()}catch(C){console.warn("[Surfaces] Cleanup error during unmount, ignoring:",C)}try{v.container.remove()}catch{}i.delete(v.slot),c("surface.unmounted",{slot:v.slot,id:v.id}),d(v.slot)}function b(v){let C=i.get(v);return{slot:v,occupied:!!C,currentPriority:C?.options.priority,currentAdaptiveId:C?.options.adaptiveId,mountCount:s.get(v)??0,currentMountId:C?.id}}function g(v,C){let w=l.get(v);return w||(w=new Set,l.set(v,w)),w.add(C),()=>{w?.delete(C),w?.size===0&&l.delete(v)}}function m(v,C){let w=i.get(v);return w?C!==void 0?C>=w.options.priority:!1:!0}function y(){for(let v of i.values())try{v.cleanup?.(),v.container.remove()}catch(C){console.error("[Surfaces] Error during cleanup:",C)}i.clear(),l.clear()}return{mount:S,getState:b,onStateChange:g,canMount:m,destroy:y}}var Ih=class{constructor(){B(this,"widgets",new Map);B(this,"mountedWidgets",new Map);B(this,"mountIdCounter",0);B(this,"runtimeRef");B(this,"listeners",new Set)}bindRuntime(e){this.runtimeRef=e}register(e,a,r="custom",n){if(this.widgets.has(e)){if(this.widgets.get(e).source==="built-in")throw new Error(`Cannot override built-in widget: ${e}`);console.warn(`[WidgetRegistry] Overriding widget: ${e}`)}this.widgets.set(e,{id:e,widget:a,source:r,metadata:n}),this.notify({type:"registered",widgetId:e})}unregister(e){let a=this.widgets.get(e);return a?a.source==="built-in"?(console.warn(`[WidgetRegistry] Cannot unregister built-in widget: ${e}`),!1):(this.widgets.delete(e),this.notify({type:"unregistered",widgetId:e}),!0):!1}unregisterBySource(e){for(let[a,r]of this.widgets.entries())r.source===e&&this.widgets.delete(a)}get(e){return this.widgets.get(e)?.widget}getRegistration(e){return this.widgets.get(e)}has(e){return this.widgets.has(e)}mount(e,a,r){let n=this.widgets.get(e);if(!n)throw new Error(`Widget not found: ${e}`);let o=`widget-mount-${++this.mountIdCounter}`;a.setAttribute("data-widget-mount-id",o),a.setAttribute("data-widget-id",e);let i={...r,runtime:this.runtimeRef},s=n.widget.mount(a,i);return this.mountedWidgets.set(o,{cleanup:s??void 0,container:a}),{widgetId:e,container:a,unmount:()=>{let u=this.mountedWidgets.get(o);u&&(a.isConnected&&u.cleanup?.(),this.mountedWidgets.delete(o),a.removeAttribute("data-widget-mount-id"),a.removeAttribute("data-widget-id"),a.innerHTML="")},update:u=>{if(n.widget.update)n.widget.update(a,u);else{let c=this.mountedWidgets.get(o);if(c){c.cleanup?.(),a.innerHTML="";let d={...u,runtime:this.runtimeRef},f=n.widget.mount(a,d);c.cleanup=f??void 0}}}}}list(){return Array.from(this.widgets.keys())}listRegistrations(){return Array.from(this.widgets.values())}getBySource(e){return Array.from(this.widgets.values()).filter(a=>a.source===e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(let a of this.listeners)try{a(e)}catch(r){console.error("[WidgetRegistry] Listener error:",r)}}destroy(){for(let[e,a]of this.mountedWidgets.entries())a.cleanup?.(),a.container.innerHTML="";this.mountedWidgets.clear()}},$0=new Ih;var yR="2.0.0";function V4(t,e){if(!e)return!0;let a;try{a=new URL(t).pathname}catch{a=t}let r=a.replace(/\/$/,"")||"/";if(e.exclude){for(let n of e.exclude)if(j0(r,n))return!1}if(e.include&&e.include.length>0){for(let n of e.include)if(j0(r,n))return!0;return!1}return!0}function j0(t,e){let a=e.replace(/\/$/,"")||"/";if(t===a)return!0;let r=a.replace(/\*\*/g,"\0GLOBSTAR\0").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\0GLOBSTAR\0/g,".*").replace(/:[^/]+/g,"[^/]+");return new RegExp(`^${r}$`).test(t)}function vR(t){let a=(typeof window<"u"?window.location.pathname:"/").replace(/\/$/,"")||"/";return(Array.isArray(t.route)?t.route:[t.route]).some(n=>{let o=n;if(/^https?:\/\//.test(o))try{o=new URL(o).pathname}catch{}return j0(a,o)})}function G0(t={}){let{telemetry:e,sessionMetrics:a,routes:r,mode:n="production",namespace:o}=t,i=t.widgets??$0,s=t.executors??xn,l=t.apps??hu,u=new Nc,c=I0({telemetry:e,routes:r,navigation:u}),d=t.events??Bc(),f=B0({namespace:o}),h=E0({eventBus:d,stateStore:f}),S=A0({state:f,events:d,sessionMetrics:a,accumulator:h}),x=G1(),b=L0(),g=_=>vR(_)?b.resolve(_.selector):null,m=async(_,L)=>{if(!vR(_))return null;try{return await b.waitFor(_.selector,L)}catch{return null}},y=V0({overlayRoot:x,eventBus:d,anchorResolver:g,widgetRegistry:i}),v=c0({overlayRoot:x,eventBus:d,surfaces:y,anchorResolver:g,waitForAnchor:m,executorRegistry:s,subscribeNavigation:_=>u.subscribe(_),runtime:{evaluateSync:_=>S.evaluateSync(_,c.get()),context:c,accumulator:h}}),C;if(a){a.increment("page_views");let _=typeof window<"u"?window.location.pathname:"/";C=u.subscribe((L,A)=>{if(A!=="replaceState")try{let I=new URL(L).pathname;I!==_&&(_=I,a.increment("page_views"))}catch{}})}let w={telemetry:e,context:c,events:d,state:f,sessionMetrics:a,actions:v,surfaces:y,widgets:i,executors:s,apps:l,accumulator:h,anchorResolver:b,navigation:u,version:yR,mode:n,async evaluate(_){return S.evaluate(_,c.get())},evaluateSync(_){return S.evaluateSync(_,c.get())},async filterTiles(_){let L=c.get().page.url,A=[];for(let I of _){let R=I.activation;if(!R){A.push(I);continue}if(V4(L,R.routes)){if(R.onlyIfPopulated){let H=I.props?.actions??[];if(H.length>0&&!H.some(M=>M.triggerWhen?S.evaluateSync(M.triggerWhen,c.get()).value:!0))continue}A.push(I)}}return A},setRoutes(_){c.setRoutes(_)},destroy(){l.unbind().catch(_=>{console.error("[Runtime] Error unbinding apps registry:",_)}),C?.(),b.destroy(),h.destroy(),u.destroy(),c.destroy(),v.destroy(),y.destroy()}};return l.bind(w),i.bindRuntime(w),w}var $4=p.object({value:p.unknown(),expiresAt:p.number().optional()}),j4=p.object({count:p.number(),resetAt:p.number().optional()});function SG(t){return $4.safeParse(t)}function _G(t){return j4.safeParse(t)}var W0="syn_";function qc(t){if(!t.startsWith(W0))throw new Error("Invalid Syntro token: must start with 'syn_'");let a=t.slice(W0.length).replace(/-/g,"+").replace(/_/g,"/"),r=atob(a),n=JSON.parse(r);if(n.v!==1)throw new Error(`Unsupported token version: ${n.v}`);return n}function Z0(t){let e=JSON.stringify(t),a=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return W0+a}function Wa(t){if(typeof process<"u"&&process.env)return process.env[t];try{let e=(0,eval)("import.meta");if(e?.env)return e.env[t]}catch{}}var bR="syntro_segment_attributes";function SR(){if(typeof window>"u")return{};try{let t=localStorage.getItem(bR);if(t){let e=JSON.parse(t);return K("Syntro Bootstrap","Loaded cached segment attributes:",e),e}}catch(t){na("Syntro Bootstrap","Failed to load cached segment attributes:",t)}return{}}function _R(t){if(!(typeof window>"u"))try{localStorage.setItem(bR,JSON.stringify(t)),K("Syntro Bootstrap","Cached segment attributes:",t)}catch(e){na("Syntro Bootstrap","Failed to cache segment attributes:",e)}}function CR(t){if(!t)return{};let e={};for(let[a,r]of Object.entries(t))a.startsWith("in_segment_")&&(e[a]=r===!0);return e}function X0(){if(typeof window>"u")return{};let t={};try{let e=new URLSearchParams(window.location.search);for(let a of["utm_source","utm_medium","utm_campaign","utm_content","utm_term"]){let r=e.get(a);r&&(t[a]=r)}}catch{}try{navigator.language&&(t.browser_language=navigator.language),navigator.languages?.length&&(t.browser_languages=[...navigator.languages])}catch{}try{let e=window.innerWidth;t.device_type=e<768?"mobile":e<1024?"tablet":"desktop"}catch{}try{if(document.referrer){t.referrer=document.referrer;try{t.referrer_hostname=new URL(document.referrer).hostname}catch{}}}catch{}try{let e=navigator.userAgent;e.includes("Edg/")?t.browser="Edge":e.includes("OPR/")||e.includes("Opera")?t.browser="Opera":e.includes("Chrome/")&&!e.includes("Chromium")?t.browser="Chrome":e.includes("Safari/")&&!e.includes("Chrome")?t.browser="Safari":e.includes("Firefox/")&&(t.browser="Firefox"),e.includes("Windows")?t.os="Windows":e.includes("iPhone")||e.includes("iPad")?t.os="iOS":e.includes("Mac OS X")||e.includes("Macintosh")?t.os="macOS":e.includes("Android")?t.os="Android":e.includes("Linux")&&(t.os="Linux")}catch{}try{t.page_url=window.location.href,t.page_path=window.location.pathname,t.page_host=window.location.hostname,window.location.search&&(t.page_query=window.location.search)}catch{}return t}var xR="syntro_geo",wR="https://geo.syntrologie.com";async function K0(t){if(typeof window>"u")return{};try{let e=localStorage.getItem(xR);if(e){let a=JSON.parse(e);return K("Syntro Bootstrap","Geo: using cached data:",a),a}}catch{}try{let e=await fetch(t,{signal:AbortSignal.timeout(2e3)});if(e.ok){let a=await e.json(),r={};for(let[n,o]of Object.entries(a))typeof o=="string"&&o&&(r[n]=o);try{localStorage.setItem(xR,JSON.stringify(r))}catch{}return K("Syntro Bootstrap","Geo: fetched from worker:",r),r}}catch{}return{}}var LR={growthbook:t=>Xy({...t,autoInit:!0})};function kR(t,e){let a=LR[t];if(!a)throw new Error(`Unknown experiment provider: ${t}. Supported: ${Object.keys(LR).join(", ")}`);return a(e)}var G4=["cdn.syntrologie.com","localhost","127.0.0.1"];function W4(t){try{let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(console.warn("[SmartCanvas] CDN URL must use HTTPS:",t),!1):G4.some(n=>e.hostname===n)?!0:(console.warn("[SmartCanvas] CDN host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid CDN URL:",t),!1}}var Y0=class{constructor(e){B(this,"name","cdn");B(this,"url");B(this,"integrity");if(this.url=`${e.baseUrl}/${e.configId}.json`,this.integrity=e.integrity,!W4(this.url))throw new Error(`[SmartCanvas] CDN URL not allowed: ${this.url}`)}async fetch(){let e=performance.now(),a=await fetch(this.url,{credentials:"omit",cache:"default"});if(!a.ok)throw new Error(`[SmartCanvas] Failed to fetch config from CDN (${a.status})`);let r=await a.text();if(this.integrity){let l=await Z4(r),u=this.integrity.replace("sha384-","");if(l!==u)throw new Error(`[SmartCanvas] Config integrity check failed. Expected ${u}, got ${l}`)}let n=JSON.parse(r),o=performance.now()-e,i=a.headers.get("cache-control"),s=a.headers.get("age");return{config:n,meta:{source:"cdn",fetchTimeMs:o,cached:i?.includes("public")??!1,cacheAge:s?parseInt(s,10):void 0}}}};async function Z4(t){let a=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-384",a),n=new Uint8Array(r);return btoa(String.fromCharCode(...n))}function IR(t){return new Y0(t)}var X4="syntro_exp",K4="syntro_var",Q0=class{constructor(e){B(this,"name","experiments");B(this,"client");B(this,"featureKey");B(this,"manifestKey");B(this,"variantFlagPrefix");this.client=e.client,this.featureKey=e.featureKey??"smart-canvas-config",this.manifestKey=e.manifestKey,this.variantFlagPrefix=e.variantFlagPrefix}async fetch(){let e=performance.now();if(typeof window<"u"){let n=new URLSearchParams(window.location.search),o=n.get(X4),i=n.get(K4);if(o&&i!==null&&this.client.setForcedVariations){let s=parseInt(i,10);Number.isNaN(s)||(console.log(`[SmartCanvas] Preview mode: forcing "${o}" to variation ${s}`),this.client.setForcedVariations({[o]:s}))}}if(this.manifestKey||this.variantFlagPrefix||this.client.getAllFeatures){let n=this.fetchMultiFlag();if(n){let o=performance.now()-e;return{config:n,meta:{source:"experiments",fetchTimeMs:o,cached:!0}}}}if(!this.featureKey)throw new Error("[SmartCanvas] No featureKey configured and no variant flags found. Ensure at least one config feature flag exists in your experiment platform.");let a=this.client.getFeatureValue?.(this.featureKey,null);if(!a||typeof a!="object")throw new Error(`[SmartCanvas] Feature "${this.featureKey}" not found or invalid. Ensure the feature is configured in your experiment platform.`);let r=performance.now()-e;return{config:a,meta:{source:"experiments",fetchTimeMs:r,cached:!0}}}fetchMultiFlag(){let e=this.getVariantFlagKeys();return!e||e.length===0?null:Zf(this.client,e)}getVariantFlagKeys(){if(this.manifestKey){let e=this.client.getFeatureValue?.(this.manifestKey,null);if(e&&typeof e=="object"){let a=e.variant_flags;if(a&&a.length>0)return a}}if(this.client.getAllFeatures){let e=this.client.getAllFeatures();return this.variantFlagPrefix?Object.keys(e).filter(a=>a.startsWith(this.variantFlagPrefix)):Object.keys(e)}return[]}};function AR(t){return new Q0(t)}var Y4="https://cdn.syntrologie.com/configs",ER={cdn:t=>{if(!t.configId)throw new Error("CDN fetcher requires 'configId' option");return IR({baseUrl:t.baseUrl??Y4,configId:t.configId,integrity:t.integrity})},experiments:t=>{if(!t.featureKey)throw new Error("Experiments fetcher requires 'featureKey' option");return AR({featureKey:t.featureKey})}};function TR(t,e={}){let a=ER[t];if(!a)throw new Error(`Unknown config fetcher type: ${t}. Supported: ${Object.keys(ER).join(", ")}`);return a(e)}var RR={posthog:t=>$b(t),noop:()=>ax()};function MR(t,e){let a=RR[t];if(!a)throw new Error(`Unknown telemetry provider: ${t}. Supported: ${Object.keys(RR).join(", ")}`);return a(e)}async function OR(t){ay(),K("Syntro Bootstrap","====== INIT ======"),K("Syntro Bootstrap","Options:",{hasToken:!!t.token,tokenPrefix:`${t.token?.slice(0,15)}...`,hasCanvasOptions:!!t.canvas});let e=Yf();if(console.log(`[DIAG] Mode detection: sdkMode=${e}`),console.log("[DIAG] editorSource:",Su()),console.log("[DIAG] editorConf:",Kf()),K("Syntro Bootstrap","SDK mode:",e??"normal"),!e&&typeof window<"u"){let E=!!window.__SYNTRO_EDITOR_PARAMS__,M=!!window.__SYNTRO_AUDIT_LEGEND__,D=!!window.__SYNTRO_REVIEW_DATA__;if(E||M||D){let F=[E&&"__SYNTRO_EDITOR_PARAMS__",M&&"__SYNTRO_AUDIT_LEGEND__",D&&"__SYNTRO_REVIEW_DATA__"].filter(Boolean);console.warn(`[Syntro Bootstrap] \u26A0 Mode detection returned null but mode-specific globals found: ${F.join(", ")}. This suggests URL params were lost (redirect?) but the service worker injected mode data. Check if replaceState failed or if page JS changed the URL before init().`)}}console.log(`[DIAG] Token resolution: options.token=${t.token?t.token.slice(0,15)+"...":"null"}`);let a=t.token;if(!a&&e){let M=Kf()?.syntro_token;M?.startsWith("syn_")&&(a=M,K("Syntro Bootstrap",`\u2713 Using syntro_token from editor_conf (${e} mode)`))}let r;if(a)if(a.startsWith("syn_"))K("Syntro Bootstrap","Token starts with syn_, decoding..."),r=qc(a),ay(r.d);else if(e)K("Syntro Bootstrap",`\u2713 Non-syn_ token allowed (${e} mode)`);else throw Xf("Syntro Bootstrap","\u274C Token does not start with syn_ and NOT in editor/audit/review mode!"),Xf("Syntro Bootstrap","Token received:",a),new Error("Invalid Syntro token: must start with 'syn_'");else if(e)K("Syntro Bootstrap",`\u2713 No token, but ${e} mode - proceeding`);else throw Xf("Syntro Bootstrap","\u274C No token provided and NOT in editor/audit/review mode!"),new Error("Syntro token is required (unless in editor, audit, or review mode)");let n=Wa("NEXT_PUBLIC_SYNTRO_EXPERIMENT_HOST")||Wa("VITE_SYNTRO_EXPERIMENT_HOST")||r?.eh,o=Wa("NEXT_PUBLIC_SYNTRO_TELEMETRY_HOST")||Wa("VITE_SYNTRO_TELEMETRY_HOST")||r?.th,i=Wa("NEXT_PUBLIC_SYNTRO_EDITOR_URL")||Wa("VITE_SYNTRO_EDITOR_URL")||t.canvas?.editorUrl,s=r?.g||Wa("NEXT_PUBLIC_SYNTRO_GEO_HOST")||Wa("VITE_SYNTRO_GEO_HOST")||wR,l=SR(),u=X0(),c={...u,...l};K("Syntro Bootstrap","Phase 1: Browser metadata:",u),K("Syntro Bootstrap","Phase 1: Cached segment attributes:",l);let d=K0(s),f,h=t.debug||t.testMode,S=Bc({debug:t.debug,history:h?new Pc(t.testMode?0:100):void 0,testMode:t.testMode});console.log("[Syntro Bootstrap] EventBus created");let x=sy({elementResolver:typeof window<"u"?(E,M)=>{let D=document.elementFromPoint(E,M);if(!D)return null;let F={tag_name:D.tagName.toLowerCase()};D.id&&(F.attr__id=D.id),D.className&&typeof D.className=="string"&&(F.classes=D.className.split(" ").filter(Boolean));for(let Z of D.attributes)Z.name.startsWith("data-")&&(F[`attr__${Z.name}`]=Z.value);return F}:void 0});x.onEvent(E=>S.publishEvent(E)),typeof window<"u"&&(setInterval(()=>x.tick(Date.now()),1e3),document.addEventListener("click",E=>{let M=[],D=E.target;for(;D&&D!==document.body;){let F={tag_name:D.tagName.toLowerCase()};for(let Z of D.attributes)(Z.name.startsWith("data-")||Z.name==="id"||Z.name==="class"||Z.name==="aria-label")&&(F[`attr__${Z.name}`]=Z.value);M.push(F),D=D.parentElement}x.enrichClickAttributes(Date.now(),M)},!0));let b=E=>{K("Syntro Bootstrap","Phase 2: PostHog feature flags loaded");let M=CR(E);if(K("Syntro Bootstrap","Segment flags from PostHog:",M),_R(M),f){let D=m?.getAll?.()??{},F={...u,...D,...M};K("Syntro Bootstrap","Updating GrowthBook with attributes:",F),f.setAttributes?.(F)}},g;if(r?.t){let E=r.t==="noop"?"noop":"posthog";g=MR(E,{apiKey:r.t,apiHost:o,enableFeatureFlags:!0,sessionRecording:!r.d,onFeatureFlagsLoaded:b,onCapture:(D,F)=>{x.ingest({kind:"posthog",event:D,properties:F,timestamp:Date.now()})},onRRWebEvent:D=>{x.ingest(D)}}),console.log(`[Syntro Bootstrap] Telemetry client created (${E}) with EventBus wiring`);let M=g;S.setPosthogCapture((D,F)=>{M.track?.(D,F)})}let m;r?.e&&(f=kR("growthbook",{clientKey:r.e,apiHost:n,attributes:c,onExperimentViewed:g?.trackExperiment?(E,M,D)=>{g.trackExperiment(E,M,D)}:void 0})),m=Ky({experiments:f,onMetricChange:(E,M)=>{K("Syntro Bootstrap",`Session metric changed: ${E} = ${M}`)}}),K("Syntro Bootstrap","SessionMetricTracker created");let y="production";e==="editor"?y="editor":e==="audit"?y="audit":Wa("NODE_ENV")==="development"&&(y="development");let v=G0({telemetry:g,sessionMetrics:m,mode:y,events:S});K("Syntro Bootstrap","Runtime created:",{version:v.version,mode:v.mode,hasContext:!!v.context,hasEvents:!!v.events,hasState:!!v.state}),K("Syntro Bootstrap","Core app executors already registered");let C=t.cdnBase||Wa("NEXT_PUBLIC_SYNTRO_CDN_BASE")||Wa("VITE_SYNTRO_CDN_BASE")||"https://cdn.syntrologie.com",w=Pv({cdnBase:C,registry:v.apps,onLoadStart:E=>{K("Syntro Bootstrap",`Loading app from CDN: ${E}`)},onLoadEnd:(E,M,D)=>{M?K("Syntro Bootstrap",`App loaded successfully: ${E}`):na("Syntro Bootstrap",`Failed to load app: ${E}`,D)}});typeof window<"u"&&(window.SynOS={...window.SynOS,appRegistry:v.apps,runtime:v,version:v.version},K("Syntro Bootstrap","Global SynOS object exposed"));let _=v.apps.list?.()??[];console.log(`[DIAG] Activation loop: ${_.length} apps in registry:`,_.map(E=>`${E.manifest.id}(${E.state})`).join(", "));for(let E of _)if(E.state==="registered")try{await v.apps.activate(E.manifest.id),console.log(`[DIAG] Activated: ${E.manifest.id} \u2192 widgets: [${v.widgets.list().join(", ")}]`)}catch(M){console.error(`[DIAG] FAILED to activate: ${E.manifest.id}`,M),na("Syntro Bootstrap",`Failed to auto-activate built-in app: ${E.manifest.id}`,M)}if(console.log(`[DIAG] Activation complete. Total widgets: [${v.widgets.list().join(", ")}]`),f?.refreshFeatures)try{await f.refreshFeatures(),K("Syntro Bootstrap","GrowthBook features loaded")}catch(E){na("Syntro Bootstrap","Failed to load GrowthBook features:",E)}let L=await d;if(f&&Object.keys(L).length>0){let E={...u,...L};K("Syntro Bootstrap","Merging geo data into GrowthBook attributes:",L),f.setAttributes?.(E)}let A;if(t.fetcher)A=t.fetcher;else if(r?.f){let E=TR(r.f,r.o??{});A=async()=>{let M=await E.fetch();return{...M.config,tiles:M.config.tiles??[]}}}else f&&(A=Cs({experiments:f}));let I=new Set,R=A?async()=>{let E=await A(),M=E.tiles?.length??0,D=E.actions?.length??0,F=E.meta?.variant_id;if((M>0||D>0)&&(F||console.warn("[Syntro] Config has content but no meta.variant_id \u2014 intervention tracking disabled")),g&&F){let W=new kc(g,F);W.trackServed(M,D),typeof window<"u"&&(window.SynOS.interventionTracker=W),v.navigation.subscribe(()=>{W.resetPage()})}console.log("[Syntro Bootstrap] Config fetched:",`tiles=${E.tiles?.length??0},`,`actions=${E.actions?.length??0},`,`theme=${E.theme?.name??"none"}`),E.actions?.length>0&&console.log("[Syntro Bootstrap] Actions in config:",E.actions.map((W,ce)=>`[${ce}] ${W.kind}${W.anchorId?` anchor="${W.anchorId.selector}"`:""}${W.label?` "${W.label}"`:""}`).join(", "));let Z=E,U=w.getRequiredApps(Z);return U.length>0?console.log("[Syntro Bootstrap] Required external apps:",U.join(", ")):K("Syntro Bootstrap","No external apps required (all executors are built-in)"),U.length>0&&await w.loadAppsForConfig(Z).then(async ce=>{let Xt=ce.filter(N=>N.success),it=ce.filter(N=>!N.success);Xt.length>0&&console.log(`[Syntro Bootstrap] Apps loaded from CDN: ${Xt.map(N=>N.appId).join(", ")}`);let yt=it.filter(N=>!I.has(N.appId));yt.length>0&&(console.error("[Syntro Bootstrap] Apps FAILED to load from CDN:",yt.map(N=>`${N.appId} (${N.error})`).join(", ")),yt.forEach(N=>I.add(N.appId)));for(let N of U)if(v.apps.has(N))try{await v.apps.activate(N),console.log(`[Syntro Bootstrap] App activated: ${N}`)}catch(te){console.error(`[Syntro Bootstrap] Failed to activate app: ${N}`,te)}else console.error(`[Syntro Bootstrap] App "${N}" required by config but NOT registered.`,`Available apps: [${Array.from(v.apps.list?.()??[]).join(", ")}]`)}),E}:void 0;return{canvas:await Ty({...t.canvas,fetcher:R,integrations:{experiments:f,telemetry:g},editorUrl:i,runtime:v}),runtime:v,experiments:f,telemetry:g,sessionMetrics:m,appLoader:w}}async function Q4(t){try{return await OR(t)}catch(e){let a=e instanceof Error?e.message:String(e);console.warn("[Syntrologie] SDK initialization failed:",a),typeof document<"u"&&document.getElementById("syntrologie-anti-flicker")?.remove();return}}function J4(t,e={}){if(typeof window>"u")return;let a=window.SynOS?.runtime;a?.events?.publish&&a.events.publish({name:t,source:"custom",props:e})}var DR={init:Q4,encodeToken:Z0,decodeToken:qc,events:{emit:J4}};typeof window<"u"&&(window.Syntro=DR);var BR="2026-04-13T06:17:12.836Z (04de87d27a6)";if(typeof window<"u"){console.log(`[Syntro Runtime] Build: ${BR}`);let t=window.SynOS,e=t?.appRegistry||hu;window.SynOS={...t,appRegistry:e,_runtimeBuild:BR,React:PR.default,ReactDOM:{...eU,createPortal:Ah.createPortal,flushSync:Ah.flushSync}},D1(e)}export{zc as ANIMATION_KEYFRAMES,xh as ActivationConfigZ,UT as AddClassZ,Ga as AnchorIdZ,O4 as AnchorStateZ,p0 as AnchorVisibleConditionZ,Hf as AppRegistry,D4 as AugmentationZ,ET as BadgePositionZ,GT as BadgeZ,M4 as BoundingBoxZ,Lu as CanvasEvents,ex as CanvasRecipeZ,Lo as ConditionZ,bh as ContextManager,x0 as CooldownActiveConditionZ,Ac as CounterDefZ,w0 as CtaButtonZ,py as DEFAULT_COOLDOWN,fy as DEFAULT_TTL,Dc as DecisionStrategyZ,y0 as DismissedConditionZ,rt as EVENT_SCHEMA_VERSION,wh as EventBus,S0 as EventCountConditionZ,U4 as EventFilterZ,Pc as EventHistory,h0 as EventOccurredConditionZ,cR as EventSourceZ,hh as ExecutorRegistry,Oc as ExternalStrategyZ,j4 as FrequencyEntryZ,b0 as FrequencyLimitConditionZ,OH as HighlightStepZ,AT as HighlightStyleZ,$T as HighlightZ,VT as InsertHtmlZ,OT as InsertPositionZ,kc as InterventionTracker,dy as MAX_VISIBLE_TOASTS,Ic as MatchOpZ,MT as ModalContentZ,ZT as ModalZ,Mc as ModelStrategyZ,YT as MountWidgetZ,KT as NavigateZ,Nc as NavigationMonitor,H4 as NormalizedEventZ,cy as NotificationToastStack,A4 as PageContextZ,E4 as PageHistoryEntryZ,d0 as PageUrlConditionZ,eR as ParallelZ,TT as PlacementZ,jT as PulseZ,BR as RUNTIME_SDK_BUILD,yR as RUNTIME_VERSION,zT as RemoveClassZ,f0 as RouteConditionZ,IT as RouteFilterZ,Tc as RuleStrategyZ,Ec as RuleZ,B4 as RuntimeContextZ,yy as RuntimeProvider,eo as SDK_SCHEMA_VERSION,ry as SDK_VERSION,hR as STATIC_SLOT_STYLES,Rc as ScoreStrategyZ,NT as ScrollBehaviorZ,C0 as ScrollLogicalPositionZ,XT as ScrollToZ,xA as SelectorZ,JT as SequenceZ,T4 as SessionContextZ,v0 as SessionMetricConditionZ,Ep as SessionMetricTracker,HT as SetAttrZ,qT as SetStyleZ,FT as SetTextZ,pI as ShadowCanvasOverlay,X1 as ShadowRootProvider,yI as SmartCanvasApp,oy as SmartCanvasController,Ay as SmartCanvasElement,S8 as SmartCanvasPortal,Mt as StandardEvents,m0 as StateEqualsConditionZ,Lh as StateStore,$4 as StoredValueZ,DR as Syntro,Uu as TileCard,c$ as TileWheel,RT as TooltipContentZ,MH as TooltipStepZ,DT as TooltipTriggerZ,WT as TooltipZ,PT as TourStepForSchemaZ,tR as TourZ,yh as TriggerWhenZ,g0 as ViewportConditionZ,R4 as ViewportContextZ,QT as WaitZ,BT as WidgetConfigZ,Ih as WidgetRegistry,hu as appRegistry,P0 as applyStaticSlotStyles,Dv as cleanupAppContext,bv as contentRuntime,k4 as coreActionStepSchemas,c0 as createActionEngine,L0 as createAnchorResolver,Ov as createAppContext,Pv as createAppLoader,Cs as createCanvasConfigFetcher,I0 as createContextManager,A0 as createDecisionEngine,E0 as createEventAccumulator,Bc as createEventBus,Xy as createGrowthBookClient,ax as createNoopClient,x8 as createOverlayRecipeFetcher,$b as createPostHogClient,eI as createPostHogNormalizer,Ky as createSessionMetricTracker,Ty as createSmartCanvas,W1 as createSmartCanvasController,G0 as createSmartCanvasRuntime,B0 as createStateStore,z0 as createSurfaceContainer,V0 as createSurfaces,x9 as decisionSchemas,qc as decodeToken,Z0 as encodeToken,iR as evaluate,rR as evaluateCondition,nR as evaluateRule,Sh as evaluateRuleStrategy,_h as evaluateScoreStrategy,sR as evaluateSync,xn as executorRegistry,oP as getAntiFlickerSnippet,e1 as getAppIdFromActionKind,Bv as getAppIdFromWidgetId,d4 as getExecutor,kh as getSlotAnchorId,Uc as getSlotType,q0 as getSlotZIndex,Zb as hasExecutor,up as interpolateTemplate,Jk as isCoreActionKind,hy as matchEvent,h$ as needsMigration,Cu as normalizePostHogEvent,Mv as overlaysRuntime,zu as parseVersion,H0 as playEnterAnimation,U0 as playExitAnimation,Qf as registerConfigPredicates,_I as registerSmartCanvasElement,ny as resolveConfigUri,N0 as setupAdjacentPositioning,F0 as setupInlinePositioning,wu as shouldNormalizeEvent,dN as useDecision,my as useNotifications,gy as useNotifyWatcher,xy as usePageContext,Jr as useRuntime,dp as useRuntimeContext,uN as useRuntimeEvents,cN as useRuntimeState,sN as useSessionContext,gI as useShadowCanvasConfig,ks as useShadowRoot,lN as useViewportContext,Ar as validateAction,vh as validateActions,y9 as validateActivationConfig,g9 as validateCondition,p$ as validateConfig,gj as validateEventFilter,T0 as validateEventName,_G as validateFrequencyEntry,mj as validateNormalizedEvent,R0 as validateProps,m8 as validateRecipe,z9 as validateRuntimeContext,SG as validateStoredValue,v9 as validateStrategy,$0 as widgetRegistry};
503
+ `)),new Error(`Batch validation failed: ${E}`)}let A=f(),I=[],R=[];try{for(let E of _){let M=await m(E);I.push(M),R.push(M)}}catch(E){console.error(`[ActionEngine] Batch apply FAILED at action ${R.length+1}/${_.length}.`,`Successfully applied: ${R.length}. Rolling back...`,E);for(let M of R)try{await M.revert()}catch{}throw E}return{id:A,handles:I,async revertAll(){for(let E=I.length-1;E>=0;E--)try{await I[E].revert()}catch(M){console.error(`[ActionEngine] Error reverting action ${I[E].id}:`,M)}},isApplied(){return I.every(E=>E.isApplied())}}}function v(_){return Ar(_)}function C(){return Array.from(c.values()).map(_=>({id:_.id,action:_.action,adaptiveId:_.adaptiveId,appliedTs:_.appliedTs,state:_.state}))}function w(){for(let _ of d.values())for(let L of _)try{L()}catch{}d.clear();for(let _ of c.values())if(_.state==="applied")try{_.cleanup()}catch(L){console.error("[ActionEngine] Error during cleanup:",L)}c.clear()}return{apply:m,applyBatch:y,validate:v,getActive:C,destroy:w}}var p4=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),CT=["ui.click","ui.scroll","ui.input","ui.change","ui.submit","ui.hover","ui.idle","ui.scroll_thrash","ui.focus_bounce","nav.page_view","nav.page_leave","behavior.rage_click","behavior.hesitation","behavior.confusion"],wT=p.enum(CT).describe("Event name to count. ui.* = user interactions and behavioral detectors, nav.* = page navigation, behavior.* = derived behavioral signals."),LT=["time_on_page","page_views","scroll_depth"],kT=p.enum(LT).describe("Session metric key. time_on_page = seconds on current page, page_views = pages visited this session, scroll_depth = 0-100 percentage.");var d0=p.object({type:p.literal("page_url"),url:p.string().describe('URL path to match (e.g. "/pricing", "/dashboard")')}).describe('Fires when the current page URL matches. Use for page-specific actions. Example: {"type": "page_url", "url": "/pricing"}'),f0=p.object({type:p.literal("route"),routeId:p.string().describe("Named route ID from the route filter")}).describe("Fires when the current route matches a named route ID."),p0=p.object({type:p.literal("anchor_visible"),anchorId:p.string().describe("CSS selector of the anchor element"),state:p.enum(["visible","present","absent"]).describe('"visible" = in viewport, "present" = in DOM, "absent" = not in DOM')}).describe(`Fires based on a DOM element's visibility state. Example: {"type": "anchor_visible", "anchorId": "#cta-button", "state": "visible"}`),h0=p.object({type:p.literal("event_occurred"),eventName:p.string().describe('Event name (e.g. "ui.click", "$pageview")'),withinMs:p.number().optional().describe("Time window in ms. Omit = any time this session.")}).describe('Fires when a specific event has occurred during this session. Example: {"type": "event_occurred", "eventName": "ui.click", "withinMs": 5000}'),m0=p.object({type:p.literal("state_equals"),key:p.string().describe("Key in the SDK persistent state store (localStorage). Only valid for keys the host app explicitly sets via syntro.state.set()."),value:p.unknown().describe("Expected value to match against")}).describe("Checks the SDK persistent state store (localStorage). ONLY for host-app state set via syntro.state.set() \u2014 NOT for user attributes like region, device, or UTM params (those are handled by segment targeting). Do NOT use this for targeting. If you do not know the valid state keys, do not use this condition type."),g0=p.object({type:p.literal("viewport"),minWidth:p.number().optional().describe("Minimum viewport width in pixels"),maxWidth:p.number().optional().describe("Maximum viewport width in pixels"),minHeight:p.number().optional().describe("Minimum viewport height in pixels"),maxHeight:p.number().optional().describe("Maximum viewport height in pixels")}).describe('Fires based on viewport (screen) size. Use for responsive behavior. Example: {"type": "viewport", "minWidth": 768} \u2014 fires on tablet and larger.'),v0=p.object({type:p.literal("session_metric"),key:kT,operator:p.enum(["gte","lte","eq","gt","lt"]),threshold:p.number().describe("Numeric threshold to compare against")}).describe('Fires when a session metric crosses a threshold. Valid keys: "time_on_page" (seconds), "page_views" (count), "scroll_depth" (0-100). Example: {"type": "session_metric", "key": "time_on_page", "operator": "gte", "threshold": 30}'),y0=p.object({type:p.literal("dismissed"),key:p.string().describe("Dismissal key (usually a tile or action ID)"),inverted:p.boolean().optional().describe("When true, fires if NOT dismissed (default behavior)")}).describe("Checks if an item has been dismissed by the user. Use with inverted: true to show only if not dismissed."),x0=p.object({type:p.literal("cooldown_active"),key:p.string().describe("Cooldown key"),inverted:p.boolean().optional().describe("When true, fires if cooldown is NOT active")}).describe("Checks if a cooldown timer is currently active. Use to prevent showing the same intervention too frequently."),b0=p.object({type:p.literal("frequency_limit"),key:p.string().describe("Frequency counter key"),limit:p.number().describe("Maximum allowed count"),inverted:p.boolean().optional().describe("When true, fires if limit NOT reached")}).describe("Checks if a frequency limit has been reached. Use to cap how many times an action fires per session."),Ic=p.object({equals:p.union([p.string(),p.number(),p.boolean()]).optional(),contains:p.string().optional()}).describe("Match operator for counter filters. Exactly one of equals or contains must be specified."),Ac=p.object({events:p.array(wT).min(1).describe("Event names to count. Use values from the countable events enum."),match:p.record(p.string(),Ic).optional().describe("Property filters. Keys are event prop names or element-chain fields (tag_name, $el_text, attr__*). All entries AND together.")}).describe("Defines what events to count. Registered as an accumulator predicate at config-load time."),S0=p.object({type:p.literal("event_count"),key:p.string().describe("Unique key for this counter (used for accumulator registration)"),operator:p.enum(["gte","lte","eq","gt","lt"]),count:p.number().int().min(0).describe("Target count threshold"),withinMs:p.number().positive().optional().describe("Time window in ms. Omit = count across entire session."),counter:Ac.optional().describe("Inline counter definition. Defines what events to count.")}).describe('Fires when accumulated event count crosses a threshold. Most powerful trigger type. Example: {"type": "event_count", "key": "pricing-clicks", "operator": "gte", "count": 3, "counter": {"events": ["ui.click"], "match": {"attr__data-cta": {"contains": "pricing"}}}}'),Lo=p.discriminatedUnion("type",[d0,f0,p0,h0,m0,g0,v0,y0,x0,b0,S0]),Ec=p.object({conditions:p.array(Lo).describe("Array of conditions \u2014 ALL must match (AND logic) for this rule to fire."),value:p.unknown().describe("Value returned when all conditions match. For triggerWhen: true = fire the action.")}).describe("A single rule. ALL conditions must match (AND logic). Rules in a strategy are evaluated top-to-bottom \u2014 first rule where all conditions match wins and returns its value."),Tc=p.object({type:p.literal("rules"),rules:p.array(Ec).describe("Ordered list of rules. Evaluated top-to-bottom \u2014 first match wins."),default:p.unknown().describe("Fallback value when no rule matches. For triggerWhen: false = do not fire by default.")}).describe("Rule-based strategy. Evaluates rules top-to-bottom. First rule where ALL conditions match returns its value. If no rule matches, returns default. For triggerWhen: set value=true on matching rules, default=false."),Rc=p.object({type:p.literal("score"),field:p.string(),threshold:p.number(),above:p.unknown(),below:p.unknown()}).describe("Score-based strategy. Compares a field value against a threshold."),Mc=p.object({type:p.literal("model"),modelId:p.string(),inputs:p.array(p.string()),outputMapping:p.record(p.string(),p.unknown()),default:p.unknown()}).describe("ML model strategy. Sends inputs to a model and maps outputs."),Oc=p.object({type:p.literal("external"),endpoint:p.string(),method:p.enum(["GET","POST"]).optional(),default:p.unknown(),timeoutMs:p.number().optional()}).describe("External API strategy. Calls an endpoint to determine the value."),Dc=p.discriminatedUnion("type",[Tc,Rc,Mc,Oc]),yh=Dc.nullable().optional();var h4=p.object({events:p.array(p.string()),urlContains:p.string().optional(),props:p.record(p.union([p.string(),p.number(),p.boolean()])).optional()}),m4=p.object({title:p.string().optional(),body:p.string().optional(),icon:p.string().optional()}).nullable().optional();var IT=p.object({include:p.array(p.string()).optional().describe("URL patterns where this tile appears. Supports *, **, :param wildcards. Use sparingly \u2014 mostly to isolate to specific webapp functionality. Omit to appear on all routes."),exclude:p.array(p.string()).optional().describe("URL patterns where this tile should NOT appear. Evaluated before include.")}),xh=p.object({routes:IT,onlyIfPopulated:p.boolean().optional().describe("When true, tile is hidden if none of its props.actions[] have an active triggerWhen. Useful for tiles with all-deferred FAQ questions or nav tips. Default: false.")});function g9(t){return Lo.safeParse(t)}function v9(t){return Dc.safeParse(t)}function y9(t){return xh.safeParse(t)}var x9=[{defName:"matchOp",schema:Ic},{defName:"counterDef",schema:Ac},{defName:"activationConfig",schema:xh},{defName:"routeFilter",schema:IT},{defName:"ruleStrategy",schema:Tc},{defName:"scoreStrategy",schema:Rc},{defName:"modelStrategy",schema:Mc},{defName:"externalStrategy",schema:Oc},{defName:"rule",schema:Ec},{defName:"condition",schema:Lo}];var _0=p.object({tileId:p.string(),itemId:p.string().optional()}).strict(),g4=p.object({on:p.string(),title:p.string(),body:p.string().optional(),icon:p.string().optional(),ttl:p.number().optional(),cooldown:p.number().optional(),deepLink:_0.optional()}).strict(),v4=p.object({id:p.string(),title:p.string().optional(),subtitle:p.string().optional(),icon:p.string().optional(),priority:p.number().optional(),widget:p.string(),props:p.record(p.unknown()).optional(),activation:xh.optional(),notifications:p.array(g4).optional()}).strict(),y4=p.object({position:p.enum(["left","right"]).optional(),layout:p.enum(["overlay","push"]).optional(),background:p.string().optional(),blur:p.string().optional(),border:p.string().optional(),width:p.string().optional(),transitionDuration:p.string().optional(),transitionEasing:p.string().optional(),transitionFade:p.string().optional()}),x4=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),color:p.string().optional(),size:p.string().optional(),shadow:p.string().optional(),borderRadius:p.string().optional(),icon:p.string().optional()}),b4=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),shadow:p.string().optional(),titleColor:p.string().optional(),textColor:p.string().optional(),iconBackground:p.string().optional(),iconShadow:p.string().optional(),headerPadding:p.string().optional(),bodyPadding:p.string().optional(),gap:p.string().optional()}),S4=p.object({background:p.string().optional(),textColor:p.string().optional(),titleColor:p.string().optional(),arrowColor:p.string().optional(),arrowSize:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),scrimOpacity:p.string().optional(),highlightRing:p.string().optional()}),_4=p.object({background:p.string().optional(),textColor:p.string().optional(),textSecondaryColor:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),successColor:p.string().optional(),warningColor:p.string().optional(),errorColor:p.string().optional(),iconBackground:p.string().optional(),progressGradient:p.string().optional()}),C4=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),textColor:p.string().optional(),textSecondaryColor:p.string().optional(),itemDivider:p.string().optional(),itemGap:p.string().optional(),itemPadding:p.string().optional(),itemFontSize:p.string().optional(),bodyPadding:p.string().optional(),bodyFontSize:p.string().optional(),categoryPadding:p.string().optional(),categoryGap:p.string().optional(),categoryFontSize:p.string().optional(),searchBackground:p.string().optional(),searchColor:p.string().optional(),chevronColor:p.string().optional()}),w4=p.object({mode:p.enum(["dark","light"]).optional(),fontFamily:p.string().optional(),colorPrimary:p.string().optional(),colorPrimaryHover:p.string().optional(),borderRadius:p.string().optional(),canvas:y4.optional(),launcher:x4.optional(),tile:b4.optional(),overlay:S4.optional(),notification:_4.optional(),content:C4.optional()}).strict(),L4=p.object({enabled:p.boolean().optional(),label:p.string().optional(),position:p.string().optional(),animate:p.boolean().optional(),animationStyle:p.enum(["pulse","bounce","glow"]).optional(),notificationCount:p.number().optional()}).strict(),w9=p.object({schemaVersion:p.string().optional(),fetchedAt:p.string().datetime(),configVersion:p.string().optional(),canvasTitle:p.string().optional(),tiles:p.array(v4),actions:p.array(p.any()),theme:w4.optional(),launcher:L4.optional(),meta:p.object({verificationSteps:p.array(p.union([p.string(),p.object({text:p.string(),check:Lo.optional()})])).optional()}).passthrough().optional()}).strict();var Ct={triggerWhen:yh},Ga=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),AT=p.object({color:p.string().optional(),scrimOpacity:p.number().min(0).max(1).optional(),paddingPx:p.number().optional(),radiusPx:p.number().optional()}).strict(),ET=p.enum(["top-left","top-right","bottom-left","bottom-right"]),TT=p.enum(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),w0=p.object({label:p.string(),actionId:p.string(),primary:p.boolean().optional()}).strict(),RT=p.object({title:p.string().optional(),body:p.string(),ctaButtons:p.array(w0).optional()}).strict(),MT=p.object({title:p.string().optional(),body:p.string()}).strict(),OT=p.enum(["before","after","prepend","append","replace"]),DT=p.enum(["immediate","hover","click"]),BT=p.object({widgetId:p.string(),props:p.record(p.unknown()).optional(),priority:p.number().optional()}).strict(),PT=p.object({id:p.string(),action:p.any(),route:p.string().optional(),onAction:p.record(p.string()).optional()}).passthrough(),NT=p.enum(["auto","smooth","instant"]),C0=p.enum(["start","center","end","nearest"]),FT=p.object({kind:p.literal("content:setText"),anchorId:Ga,text:p.string(),label:p.string().optional()}).extend(Ct).strict(),HT=p.object({kind:p.literal("content:setAttr"),anchorId:Ga,attr:p.string(),value:p.string(),label:p.string().optional()}).extend(Ct).strict(),UT=p.object({kind:p.literal("content:addClass"),anchorId:Ga,className:p.string(),label:p.string().optional()}).extend(Ct).strict(),zT=p.object({kind:p.literal("content:removeClass"),anchorId:Ga,className:p.string(),label:p.string().optional()}).extend(Ct).strict(),qT=p.object({kind:p.literal("content:setStyle"),anchorId:Ga,styles:p.record(p.string()),label:p.string().optional()}).extend(Ct).strict(),VT=p.object({kind:p.literal("content:insertHtml"),anchorId:Ga,html:p.string(),position:OT,deepLink:_0.optional(),label:p.string().optional()}).extend(Ct).strict(),$T=p.object({kind:p.literal("overlays:highlight"),anchorId:Ga,style:AT.optional(),duration:p.number().optional(),label:p.string().optional()}).extend(Ct).strict(),jT=p.object({kind:p.literal("overlays:pulse"),anchorId:Ga,duration:p.number().optional(),label:p.string().optional()}).extend(Ct).strict(),GT=p.object({kind:p.literal("overlays:badge"),anchorId:Ga,content:p.string(),position:ET.optional(),label:p.string().optional()}).extend(Ct).strict(),WT=p.object({kind:p.literal("overlays:tooltip"),anchorId:Ga,content:RT,trigger:DT.optional(),placement:TT.optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(Ct).strict(),ZT=p.object({kind:p.literal("overlays:modal"),content:MT,size:p.enum(["sm","md","lg"]).optional(),blocking:p.boolean().optional(),scrim:p.object({opacity:p.number().min(0).max(1).optional()}).strict().optional(),dismiss:p.object({onEsc:p.boolean().optional(),closeButton:p.boolean().optional(),timeoutMs:p.number().min(0).optional()}).strict().optional(),ctaButtons:p.array(w0).optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(Ct).strict(),XT=p.object({kind:p.literal("navigation:scrollTo"),anchorId:Ga,behavior:NT.optional(),block:C0.optional(),inline:C0.optional(),label:p.string().optional()}).extend(Ct).strict(),KT=p.object({kind:p.literal("navigation:navigate"),url:p.string(),target:p.enum(["_self","_blank"]).optional(),label:p.string().optional()}).extend(Ct).strict(),YT=p.object({kind:p.literal("core:mountWidget"),slot:p.string(),widget:BT,label:p.string().optional()}).extend(Ct).strict(),QT=p.object({kind:p.literal("core:wait"),durationMs:p.number().min(0).optional(),event:p.string().optional(),label:p.string().optional()}).extend(Ct).strict(),JT=p.object({kind:p.literal("core:sequence"),actions:p.array(p.any()),label:p.string().optional()}).extend(Ct).strict(),eR=p.object({kind:p.literal("core:parallel"),actions:p.array(p.any()),waitFor:p.enum(["all","any"]).optional(),label:p.string().optional()}).extend(Ct).strict(),tR=p.object({kind:p.literal("overlays:tour"),tourId:p.string(),steps:p.array(PT).min(1),startStep:p.string().optional(),autoStart:p.boolean().optional(),label:p.string().optional()}).extend(Ct).passthrough(),k4=[{defName:"setText",schema:FT},{defName:"setAttr",schema:HT},{defName:"addClass",schema:UT},{defName:"removeClass",schema:zT},{defName:"setStyle",schema:qT},{defName:"insertHtml",schema:VT},{defName:"highlight",schema:$T},{defName:"pulse",schema:jT},{defName:"badge",schema:GT},{defName:"tooltip",schema:WT},{defName:"modal",schema:ZT},{defName:"scrollTo",schema:XT},{defName:"navigate",schema:KT},{defName:"mountWidget",schema:YT},{defName:"wait",schema:QT},{defName:"sequence",schema:JT},{defName:"parallel",schema:eR},{defName:"tour",schema:tR}];function L0(t){let e=t?.root??(typeof document<"u"?document.body:null),a=t?.defaultTimeoutMs??5e3,r=new Map,n=new Map,o=null,i=!1;function s(b){if(!e)return null;try{return e.matches(b)?e:e.querySelector(b)}catch{return null}}function l(){for(let[b,g]of r){let m=s(b);if(m){for(let y of g)clearTimeout(y.timer),y.resolve(m);r.delete(b)}}for(let[b,g]of n){let m=s(b);if(m){for(let y of g)y.cancelled||y.cb(m);n.delete(b)}}r.size===0&&n.size===0&&c()}function u(){o||i||typeof MutationObserver>"u"||!e||(o=new MutationObserver(()=>{l()}),o.observe(e,{childList:!0,subtree:!0}))}function c(){o&&(o.disconnect(),o=null)}function d(b,g){let m=r.get(b);m&&(m.delete(g),m.size===0&&r.delete(b)),r.size===0&&n.size===0&&c()}function f(b,g){if(i)return Promise.reject(new Error("AnchorResolver destroyed"));let m=s(b);if(m)return Promise.resolve(m);let y=g??a;return new Promise((v,C)=>{let w={resolve:v,reject:C,timer:setTimeout(()=>{d(b,w),C(new Error(`waitFor("${b}") timed out after ${y}ms`))},y)},_=r.get(b);_||(_=new Set,r.set(b,_)),_.add(w),u()})}function h(b,g){if(i)return()=>{};let m=s(b);if(m)return g(m),()=>{};let y={cb:g,cancelled:!1},v=n.get(b);return v||(v=new Set,n.set(b,v)),v.add(y),u(),()=>{y.cancelled=!0;let C=n.get(b);C&&(C.delete(y),C.size===0&&n.delete(b)),r.size===0&&n.size===0&&c()}}function S(){let b=0;for(let g of r.values())b+=g.size;return b}function x(){i=!0,c();let b=new Error("AnchorResolver destroyed");for(let g of r.values())for(let m of g)clearTimeout(m.timer),m.reject(b);r.clear(),n.clear()}return{resolve:s,waitFor:f,onAppear:h,pendingCount:S,destroy:x}}function I4(){let t=Date.now();return{page:{url:typeof window<"u"?window.location.href:"",title:typeof document<"u"?document.title:void 0},session:{sessionId:"",startTs:t,pageHistory:[]},viewport:{width:typeof window<"u"?window.innerWidth:0,height:typeof window<"u"?window.innerHeight:0}}}function k0(t,e){if(!e)return;let a;try{a=new URL(t).pathname}catch{a=t}if(e.exclude){for(let r of e.exclude)if(aR(a,r))return}if(e.include){for(let r of e.include)if(aR(a,r))return r;return}return a}function aR(t,e){let a=t.replace(/\/$/,"")||"/",r=e.replace(/\/$/,"")||"/";if(a===r)return!0;let n=r.replace(/:[^/]+/g,"[^/]+").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(a)}var bh=class{constructor(e){B(this,"context");B(this,"previousContext");B(this,"listeners",new Set);B(this,"telemetry");B(this,"routes");B(this,"navigation");B(this,"cleanupFns",[]);if(this.telemetry=e.telemetry,this.routes=e.routes,this.navigation=e.navigation,this.context=I4(),this.previousContext={...this.context},e.telemetry?.getSessionId){let a=e.telemetry.getSessionId();a&&(this.context.session.sessionId=a)}e.initialPageHistory&&(this.context.session.pageHistory=e.initialPageHistory),this.context.page.routeId=k0(this.context.page.url,this.routes),this.addPageToHistory(this.context.page.url),typeof window<"u"&&this.setupBrowserListeners()}get(){return{...this.context}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setRoutes(e){this.routes=e;let a=k0(this.context.page.url,this.routes);a!==this.context.page.routeId&&this.updateContext({page:{...this.context.page,routeId:a}})}setAnchors(e){this.updateContext({anchors:e})}setSessionId(e){e!==this.context.session.sessionId&&this.updateContext({session:{...this.context.session,sessionId:e}})}destroy(){for(let e of this.cleanupFns)e();this.cleanupFns=[],this.listeners.clear()}setupBrowserListeners(){let e,a=()=>{clearTimeout(e),e=setTimeout(()=>{this.updateViewport()},100)};window.addEventListener("resize",a),this.cleanupFns.push(()=>window.removeEventListener("resize",a));let r=this.navigation.subscribe(()=>this.updatePage());this.cleanupFns.push(r)}updateViewport(){let e={width:window.innerWidth,height:window.innerHeight};(e.width!==this.context.viewport.width||e.height!==this.context.viewport.height)&&this.updateContext({viewport:e})}updatePage(){let e=window.location.href,{title:a}=document,r=k0(e,this.routes),n={url:e,title:a,routeId:r};(n.url!==this.context.page.url||n.title!==this.context.page.title||n.routeId!==this.context.page.routeId)&&(n.url!==this.context.page.url&&this.addPageToHistory(n.url),this.updateContext({page:n}))}addPageToHistory(e){let a={url:e,ts:Date.now()},r=[...this.context.session.pageHistory||[],a];r.length>50&&r.shift(),this.context.session.pageHistory=r}updateContext(e){this.previousContext={...this.context},this.context={...this.context,...e},this.notifyListeners()}notifyListeners(){for(let e of this.listeners)try{e(this.context,this.previousContext)}catch(a){console.error("[ContextManager] Listener error:",a)}}};function I0(t){return new bh(t)}var A4=p.object({url:p.string(),routeId:p.string().optional(),title:p.string().optional(),locale:p.string().optional()}),E4=p.object({url:p.string(),ts:p.number()}),T4=p.object({sessionId:p.string(),startTs:p.number(),pageHistory:p.array(E4).optional()}),R4=p.object({width:p.number(),height:p.number()}),M4=p.object({x:p.number(),y:p.number(),w:p.number(),h:p.number()}),O4=p.object({anchorId:p.string(),present:p.boolean(),visible:p.boolean().optional(),boundingBox:M4.optional()}),D4=p.record(p.string(),p.union([p.number(),p.string(),p.boolean(),p.undefined()])),B4=p.object({page:A4,session:T4,viewport:R4,anchors:p.array(O4).optional(),augmented:D4.optional()});function z9(t){return B4.safeParse(t)}function rR(t,e){let{context:a,state:r,events:n}=e;switch(t.type){case"page_url":{let{url:o}=t,i=a.page.url.split("?")[0].split("#")[0],s=o.replace(/\*\*/g,"\0GLOBSTAR\0").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\0GLOBSTAR\0/g,".*");return new RegExp(`^${s}$`).test(i)}case"route":return a.page.routeId===t.routeId;case"anchor_visible":{let o=a.anchors?.find(i=>i.anchorId===t.anchorId);switch(t.state){case"visible":return o?.visible===!0;case"present":return o?.present===!0;case"absent":return!o?.present;default:return!1}}case"event_occurred":{if(!n)return!1;let o=t.withinMs??6e4;return n.hasRecentEvent(t.eventName,o)}case"state_equals":return r?.getValue?r.getValue(t.key)===t.value:!1;case"viewport":{let{width:o,height:i}=a.viewport;return!(t.minWidth!==void 0&&o<t.minWidth||t.maxWidth!==void 0&&o>t.maxWidth||t.minHeight!==void 0&&i<t.minHeight||t.maxHeight!==void 0&&i>t.maxHeight)}case"session_metric":{if(!r)return!1;let o=r.getSessionMetric(t.key),{operator:i,threshold:s}=t;switch(i){case"gte":return o>=s;case"lte":return o<=s;case"eq":return o===s;case"gt":return o>s;case"lt":return o<s;default:return!1}}case"dismissed":{if(!r)return t.inverted??!1;let o=r.isDismissed(t.key);return t.inverted?!o:o}case"cooldown_active":{if(!r)return t.inverted??!1;let o=r.isCooldownActive(t.key);return t.inverted?!o:o}case"frequency_limit":{if(!r)return t.inverted??!1;let i=r.getFrequencyCount(t.key)>=t.limit;return t.inverted?!i:i}case"event_count":{if(!e.accumulator)return!1;let o=t,i=e.accumulator.getCount(o.key,o.withinMs);switch(o.operator){case"gte":return i>=o.count;case"lte":return i<=o.count;case"eq":return i===o.count;case"gt":return i>o.count;case"lt":return i<o.count;default:return!1}}default:return console.warn("[RuleStrategy] Unknown condition type:",t.type),!1}}function nR(t,e){let a=[];for(let r of t.conditions){let n=rR(r,e);if(a.push({condition:r,result:n}),!n)return{matched:!1,conditionResults:a}}return{matched:!0,conditionResults:a}}function Sh(t,e){for(let a=0;a<t.rules.length;a++){let r=t.rules[a],{matched:n,conditionResults:o}=nR(r,e);if(n)return{value:r.value,isFallback:!1,matchInfo:{strategyType:"rules",matchedRuleIndex:a,evaluatedConditions:o}}}return{value:t.default,isFallback:!0,matchInfo:{strategyType:"rules"}}}function _h(t,e){let{context:a}=e,r=a.augmented?.[t.field];return r===void 0||typeof r!="number"?{value:t.below,isFallback:!0,matchInfo:{strategyType:"score"}}:{value:r>=t.threshold?t.above:t.below,isFallback:!1,matchInfo:{strategyType:"score"}}}function oR(t,e){let{state:a,events:r,sessionMetrics:n,accumulator:o}=e;return{context:t,state:a?{isDismissed:i=>a.dismissals.isDismissed(i),isCooldownActive:i=>a.cooldowns.isActive(i),getFrequencyCount:i=>a.frequency.count(i),getSessionMetric:i=>n?.get(i)??0,getValue:i=>a.session.get(i)??a.user.get(i)}:void 0,events:r?{hasRecentEvent:(i,s)=>r.hasRecentEvent(i,s)}:void 0,accumulator:o?{getCount:(i,s)=>o.getCount(i,s)}:void 0}}async function iR(t,e,a={}){let r=oR(e,a);switch(t.type){case"rules":return Sh(t,r);case"score":return _h(t,r);case"model":return{value:t.default,isFallback:!0,matchInfo:{strategyType:"model"}};case"external":return{value:t.default,isFallback:!0,matchInfo:{strategyType:"external"}};default:return console.warn("[DecisionEngine] Unknown strategy type:",t.type),{value:void 0,isFallback:!0,matchInfo:{strategyType:t.type}}}}function sR(t,e,a={}){let r=oR(e,a);switch(t.type){case"rules":return Sh(t,r);case"score":return _h(t,r);case"model":case"external":return{value:t.default,isFallback:!0,matchInfo:{strategyType:t.type}};default:return{value:void 0,isFallback:!0,matchInfo:{strategyType:t.type}}}}function A0(t){return{evaluate:(e,a)=>iR(e,a,t),evaluateSync:(e,a)=>sR(e,a,t)}}function E0(t){let{eventBus:e,stateStore:a}=t,r=new Map,n=new Set,o=null,i=a.ns("accumulator");function s(u){let c=!1;for(let d of r.values()){if(!d.predicate(u))continue;let f=i.get(d.stateKey)||{count:0};f.count++,d.needsTimestamps&&(f.timestamps||(f.timestamps=[]),f.timestamps.push(u.ts),f.timestamps.length>200&&(f.timestamps=f.timestamps.slice(-200))),i.set(d.stateKey,f),c=!0}if(c)for(let d of n)try{d()}catch(f){console.error("[EventAccumulator] Subscriber error:",f)}}function l(){o||r.size===0||(o=e.subscribe(s))}return{register(u,c,d=!1){let f=`ev:${u}`,h=r.get(f);if(h){d&&!h.needsTimestamps&&(h.needsTimestamps=!0);return}r.set(f,{stateKey:f,needsTimestamps:d,predicate:c}),l()},getCount(u,c){let d=`ev:${u}`,f=i.get(d);if(!f)return 0;if(c===void 0||!f.timestamps)return f.count;let h=Date.now()-c;return f.timestamps.filter(S=>S>=h).length},subscribe(u){return n.add(u),()=>{n.delete(u)}},destroy(){o&&(o(),o=null),r.clear(),n.clear()}}}var lR="app:",P4="syntro:",N4=/^[a-z][a-z0-9_]*$/;function T0(t){if(!t)return{valid:!1,reason:"Event name cannot be empty"};if(t.startsWith(P4))return{valid:!1,reason:'"syntro:" prefix is reserved for internal SDK events'};if(!t.startsWith(lR))return{valid:!1,reason:`Custom events must start with "app:" prefix. Got: "${t}"`};let e=t.slice(lR.length).split(":");if(e.length<2)return{valid:!1,reason:`Event name must have at least 2 segments after "app:" (app:{category}:{action}). Got: "${t}"`};for(let a of e)if(!N4.test(a))return{valid:!1,reason:`Segment "${a}" must be lowercase alphanumeric + underscores. Got: "${t}"`};return{valid:!0}}function F4(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t===null}function uR(t,e,a=0){if(a>=e)return!1;for(let r of Object.values(t))if(r!==null&&typeof r=="object"&&!Array.isArray(r)&&!uR(r,e,a+1))return!1;return!0}function R0(t){if(t===void 0)return{valid:!0};if(t===null||typeof t!="object"||Array.isArray(t))return{valid:!1,reason:"Props must be a plain object"};if(!uR(t,2))return{valid:!1,reason:"Props nesting depth exceeds 2 levels"};let e=[];for(let[a,r]of Object.entries(t))r!==null&&typeof r=="object"||F4(r)||e.push(a);return e.length>0?{valid:!0,stripped:e}:{valid:!0}}function Ch(t,e){return e?!(e.names&&e.names.length>0&&!e.names.includes(t.name)||e.patterns&&e.patterns.length>0&&!e.patterns.some(r=>{try{return new RegExp(r).test(t.name)}catch{return!1}})||e.sources&&e.sources.length>0&&!e.sources.includes(t.source)):!0}var wh=class{constructor(e={}){B(this,"subscriptions",new Set);B(this,"history",[]);B(this,"maxHistorySize");B(this,"debug");B(this,"emitHistory");B(this,"posthogCapture");B(this,"testMode");this.maxHistorySize=e.maxHistorySize??100,this.debug=e.debug??!1,this.emitHistory=e.history??null,this.posthogCapture=e.posthogCapture??null,this.testMode=e.testMode??!1}subscribe(e,a){let r,n;typeof e=="function"?(r=void 0,n=e):(r=e,n=a);let o={filter:r,callback:n};return this.subscriptions.add(o),()=>{this.subscriptions.delete(o)}}publish(e,a,r="canvas"){let n={ts:Date.now(),name:e,source:r,props:a,schemaVersion:rt};this.publishEvent(n)}publishEvent(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift();for(let a of this.subscriptions)if(Ch(e,a.filter))try{a.callback(e)}catch(r){console.error("[EventBus] Subscriber error:",r)}}emit(e,a){let r=T0(e);if(!r.valid)return console.warn(`[EventBus] emit() rejected: ${r.reason}`),this.debug?{delivered:!1,matchedRules:[],posthogCaptured:!1,listenersNotified:0}:void 0;let n=R0(a);if(!n.valid)return console.warn(`[EventBus] emit() rejected props: ${n.reason}`),this.debug?{delivered:!1,matchedRules:[],posthogCaptured:!1,listenersNotified:0}:void 0;let o={ts:Date.now(),name:e,source:"custom",props:a,schemaVersion:rt};this.history.push(o),this.history.length>this.maxHistorySize&&this.history.shift();let i=0;for(let l of this.subscriptions)if(Ch(o,l.filter))try{l.callback(o),i++}catch(u){console.error("[EventBus] Subscriber error:",u),i++}let s=!1;if(this.posthogCapture&&!this.testMode)try{this.posthogCapture(e,a),s=!0}catch(l){console.error("[EventBus] PostHog capture error:",l)}if(this.emitHistory&&this.emitHistory.record({name:e,props:a,source:"custom",timestamp:o.ts,matchedRules:[]}),this.debug)return console.debug("[EventBus] emit()",{name:e,props:a,listenersNotified:i,posthogCaptured:s}),{delivered:!0,matchedRules:[],posthogCaptured:s,listenersNotified:i}}setPosthogCapture(e){this.posthogCapture=e}getRecent(e,a){let r=this.history;return e&&(r=r.filter(n=>Ch(n,e))),a&&a>0&&(r=r.slice(-a)),r}hasRecentEvent(e,a,r){let n=Date.now()-a;return this.history.some(o=>o.name===e&&o.ts>=n&&(r===void 0||o.source===r))}countRecentEvents(e,a){let r=this.history.filter(n=>Ch(n,e));if(a!==void 0){let n=Date.now()-a;r=r.filter(o=>o.ts>=n)}return r.length}clearHistory(){this.history=[]}getSubscriberCount(){return this.subscriptions.size}};function Bc(t={}){return new wh(t)}var Pc=class{constructor(e=100){B(this,"entries",[]);B(this,"maxSize");this.maxSize=e}record(e){this.entries.push(e),this.maxSize>0&&this.entries.length>this.maxSize&&this.entries.shift()}getAll(){return[...this.entries]}clear(){this.entries=[]}};var cR=p.enum(["posthog","canvas","derived"]),H4=p.object({ts:p.number(),name:p.string(),source:cR,props:p.record(p.string(),p.unknown()).optional(),schemaVersion:p.string()}),U4=p.object({names:p.array(p.string()).optional(),patterns:p.array(p.string()).optional(),sources:p.array(cR).optional()});function mj(t){return H4.safeParse(t)}function gj(t){return U4.safeParse(t)}var Nc=class{constructor(){B(this,"listeners",new Set);B(this,"capturedPushState");B(this,"capturedReplaceState");B(this,"wasNative");B(this,"destroyed",!1);B(this,"onPopState",()=>{this.notify(window.location.href,"popstate")});this.wasNative=this.isNativeFunction(history.pushState),this.capturedPushState=history.pushState,this.capturedReplaceState=history.replaceState,history.pushState=(...e)=>{this.capturedPushState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"pushState"))},history.replaceState=(...e)=>{this.capturedReplaceState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"replaceState"))},window.addEventListener("popstate",this.onPopState)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}diagnose(){return{isNative:this.wasNative,subscriberCount:this.listeners.size}}destroy(){this.destroyed||(this.destroyed=!0,history.pushState=this.capturedPushState,history.replaceState=this.capturedReplaceState,window.removeEventListener("popstate",this.onPopState),this.listeners.clear())}notify(e,a){if(!this.destroyed)for(let r of this.listeners)try{r(e,a)}catch{}}isNativeFunction(e){try{return Function.prototype.toString.call(e).includes("[native code]")}catch{return!1}}};var M0="cooldown:";function dR(t){return{set(e,a){let r=M0+e,n=Date.now()+a;t.set(r,n)},isActive(e){return this.remaining(e)>0},remaining(e){let a=M0+e,r=t.get(a);if(r===void 0)return 0;let n=r-Date.now();return n<=0?(t.remove(a),0):n},clear(e){let a=M0+e;t.remove(a)}}}var Fc="dismissed:";function fR(t,e){return{mark(a,r=!1){let n=Fc+a;(r?e:t).set(n,!0)},isDismissed(a){let r=Fc+a;return t.has(r)||e.has(r)},clear(a){let r=Fc+a;t.remove(r),e.remove(r)},clearAll(){for(let a of t.keys())a.startsWith(Fc)&&t.remove(a);for(let a of e.keys())a.startsWith(Fc)&&e.remove(a)}}}var O0="freq:";function pR(t){function e(a){let r=O0+a,n=t.get(r);if(n){if(n.resetAt&&Date.now()>=n.resetAt){t.remove(r);return}return n}}return{increment(a,r){let n=O0+a,o=e(a),i=(o?.count??0)+1,s={count:i,resetAt:o?.resetAt??(r?Date.now()+r:void 0)};return t.set(n,s),i},count(a){return e(a)?.count??0},reset(a){let r=O0+a;t.remove(r)},hasReachedLimit(a,r){return this.count(a)>=r}}}var z4="syntro";function D0(t,e){let a=`${e}:`;return{get(r){if(t)try{let n=t.getItem(a+r);if(!n)return;let o=JSON.parse(n);if(o.expiresAt&&Date.now()>=o.expiresAt){t.removeItem(a+r);return}return o.value}catch{return}},set(r,n,o){if(t)try{let i={value:n,expiresAt:o?Date.now()+o:void 0};t.setItem(a+r,JSON.stringify(i))}catch(i){console.warn("[StateStore] Failed to save:",i)}},remove(r){t&&t.removeItem(a+r)},has(r){return t?this.get(r)!==void 0:!1},keys(){if(!t)return[];let r=[];for(let n=0;n<t.length;n++){let o=t.key(n);o?.startsWith(a)&&r.push(o.slice(a.length))}return r},clear(){if(!t)return;let r=this.keys();for(let n of r)t.removeItem(a+n)}}}function Hc(t){let e=new Map,a=`${t}:`;return{get(r){let n=e.get(a+r);if(n){if(n.expiresAt&&Date.now()>=n.expiresAt){e.delete(a+r);return}return n.value}},set(r,n,o){e.set(a+r,{value:n,expiresAt:o?Date.now()+o:void 0})},remove(r){e.delete(a+r)},has(r){return this.get(r)!==void 0},keys(){let r=[];for(let n of e.keys())n.startsWith(a)&&r.push(n.slice(a.length));return r},clear(){for(let r of e.keys())r.startsWith(a)&&e.delete(r)}}}var Lh=class{constructor(e={}){B(this,"session");B(this,"user");B(this,"dismissals");B(this,"cooldowns");B(this,"frequency");B(this,"namespace");B(this,"namespacedStorages",new Map);this.namespace=e.namespace??z4;let a=r=>typeof r=="object"&&r!==null&&typeof r.setItem=="function";typeof window<"u"?(this.session=a(window.sessionStorage)?D0(window.sessionStorage,this.namespace):Hc(this.namespace),this.user=a(window.localStorage)?D0(window.localStorage,this.namespace):Hc(this.namespace)):(this.session=Hc(this.namespace),this.user=Hc(this.namespace)),this.dismissals=fR(this.session,this.user),this.cooldowns=dR(this.user),this.frequency=pR(this.session)}ns(e){let a=`${this.namespace}:${e}`;if(!this.namespacedStorages.has(a)){let r=typeof window<"u"&&typeof sessionStorage<"u"?D0(sessionStorage,a):Hc(a);this.namespacedStorages.set(a,r)}return this.namespacedStorages.get(a)}};function B0(t={}){return new Lh(t)}function Uc(t){return t.startsWith("inline:")?"inline":t.startsWith("adjacent:")?"adjacent":"static"}function kh(t){return t.startsWith("inline:")?t.slice(7):t.startsWith("adjacent:")?t.slice(9):null}var hR={drawer_right:{position:"fixed",top:"0",right:"0",bottom:"0",width:"360px",maxWidth:"90vw"},drawer_left:{position:"fixed",top:"0",left:"0",bottom:"0",width:"360px",maxWidth:"90vw"},drawer_bottom:{position:"fixed",left:"0",right:"0",bottom:"0",maxHeight:"50vh"},overlay_center:{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)",maxWidth:"90vw",maxHeight:"90vh"},overlay_corner_br:{position:"fixed",bottom:"16px",right:"16px",maxWidth:"400px",maxHeight:"80vh"},overlay_corner_bl:{position:"fixed",bottom:"16px",left:"16px",maxWidth:"400px",maxHeight:"80vh"},toast_top:{position:"fixed",top:"16px",left:"50%",transform:"translateX(-50%)",maxWidth:"90vw"},toast_bottom:{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",maxWidth:"90vw"}},zc={fade:[{opacity:0},{opacity:1}],slide:[{opacity:0,transform:"translateY(10px)"},{opacity:1,transform:"translateY(0)"}],scale:[{opacity:0,transform:"scale(0.95)"},{opacity:1,transform:"scale(1)"}],none:[]},mR={duration:200,easing:"cubic-bezier(0.16, 1, 0.3, 1)",fill:"forwards"};function P0(t,e,a){let r=hR[e];Object.assign(t.style,r),a&&(a.maxWidth&&(t.style.maxWidth=a.maxWidth),a.maxHeight&&(t.style.maxHeight=a.maxHeight),a.minWidth&&(t.style.minWidth=a.minWidth),a.minHeight&&(t.style.minHeight=a.minHeight))}function N0(t,e,a){let r=a.placement==="auto"?"bottom":a.placement,n=[Df(a.offset?{mainAxis:a.offset.y,crossAxis:a.offset.x}:8)];return a.flip!==!1&&n.push(Pf()),a.shift!==!1&&n.push(Bf({padding:8})),t.style.position="absolute",t.style.zIndex="2147483646",Of(e,t,async()=>{let{x:i,y:s,strategy:l}=await Nf(e,t,{placement:r,middleware:n});Object.assign(t.style,{position:l,left:`${i}px`,top:`${s}px`})})}function F0(t,e,a="append"){return t.style.position="relative",t.style.display="inline-block",a==="prepend"?e.insertBefore(t,e.firstChild):e.appendChild(t),()=>{t.remove()}}function H0(t,e){return e==="none"||zc[e].length===0?null:t.animate(zc[e],mR)}function U0(t,e){if(e==="none"||zc[e].length===0)return Promise.resolve();let a=[...zc[e]].reverse(),r=t.animate(a,mR);return new Promise(n=>{r.onfinish=()=>n(),r.oncancel=()=>n()})}function z0(t,e){let a=document.createElement("div");return a.setAttribute("data-syntro-surface",t),a.setAttribute("data-syntro-mount-id",e),a.className="syntro-surface",Object.assign(a.style,{pointerEvents:"auto",boxSizing:"border-box",overflow:"auto"}),a}function q0(t){switch(Uc(t)){case"static":return t.startsWith("drawer")?2147483640:t.startsWith("overlay")?2147483642:t.startsWith("toast")?2147483644:2147483640;case"inline":return 1;case"adjacent":return 2147483638;default:return 2147483640}}function gR(t){if(typeof window.Sanitizer=="function")try{let l=new window.Sanitizer({}).sanitizeToFragment(t),u=document.createElement("div");return u.append(l),u.innerHTML}catch{}let a=document.createElement("template");a.innerHTML=t;let r=a.content,n=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),o=new Set(["b","strong","i","em","u","span","div","p","br","ul","ol","li","code","pre","small","sup","sub","a","button"]),i=[];for(;n.nextNode();){let s=n.currentNode,l=s.tagName.toLowerCase();if(!o.has(l)){i.push(s);continue}for(let u of Array.from(s.attributes)){let c=u.name.toLowerCase(),d=u.value.trim().toLowerCase(),f=c.startsWith("on"),h=(c==="href"||c==="src")&&d.startsWith("javascript:");(f||h)&&s.removeAttribute(u.name)}}for(let s of i){for(;s.firstChild;)s.parentNode?.insertBefore(s.firstChild,s);s.remove()}return a.innerHTML=(r.firstChild,a.innerHTML)}var q4=0;function V0(t){let{overlayRoot:e,eventBus:a,anchorResolver:r,defaultAnimation:n="fade",widgetRegistry:o}=t,i=new Map,s=new Map,l=new Map;function u(){return`mount-${++q4}`}function c(v,C){a&&a.publish(v,C)}function d(v){let C=l.get(v);if(C){let w=b(v);for(let _ of C)try{_(w)}catch(L){console.error("[Surfaces] State callback error:",L)}}}let f=new Map;function h(v,C,w){switch(C.type){case"html":v.innerHTML=gR(C.content);return;case"widget":{if(o?.has(C.widgetId)){let _=o.mount(C.widgetId,v,C.config);return w&&f.set(w,_),()=>{_.unmount(),w&&f.delete(w)}}console.warn(`[Surfaces] Widget not found: ${C.widgetId}`),v.innerHTML=`<div data-widget-id="${C.widgetId}" data-widget-missing="true">Widget: ${C.widgetId}</div>`;return}case"custom":return C.mount(v);case"react":v.innerHTML="<div data-react-component>React Component</div>";return;default:console.warn("[Surfaces] Unknown content type");return}}function S(v,C,w){let _=u(),L=Uc(v),A=w?.priority??0,I=w?.animation??n,R=w?.exclusive??!0,H=i.get(v);if(H&&R){if(H.options.priority>A)throw new Error(`Slot ${v} is occupied by higher priority content (${H.options.priority} > ${A})`);x(H)}let E=z0(v,_);E.style.zIndex=String(q0(v));let M;if(L==="static")P0(E,v,w?.constraints),e.appendChild(E);else if(L==="inline"){let U=kh(v);if(!U)throw new Error(`Invalid inline slot: ${v}`);if(!r)throw new Error("Anchor resolver required for inline slots");let W=r({selector:U,route:"**"});if(!W)throw new Error(`Anchor not found for inline slot: ${U}`);M=F0(E,W)}else if(L==="adjacent"){let U=kh(v);if(!U)throw new Error(`Invalid adjacent slot: ${v}`);if(!r)throw new Error("Anchor resolver required for adjacent slots");let W=r({selector:U,route:"**"});if(!W)throw new Error(`Anchor not found for adjacent slot: ${U}`);e.appendChild(E),M=N0(E,W,w?.position??{placement:"bottom"})}let D=h(E,C,_);H0(E,I);let F={id:_,slot:v,content:C,options:{priority:A,exclusive:R,animation:I,position:w?.position??{placement:"auto"},constraints:w?.constraints??{},adaptiveId:w?.adaptiveId,autoUnmountOnRouteChange:w?.autoUnmountOnRouteChange??!0},container:E,cleanup:()=>{M?.(),D?.()},mountedAt:Date.now()};return i.set(v,F),s.set(v,(s.get(v)??0)+1),c("surface.mounted",{slot:v,id:_,adaptiveId:w?.adaptiveId}),d(v),{id:_,update(U){let W=i.get(v);if(!W||W.id!==_)throw new Error("Mount no longer active");let ce=f.get(_);if(ce){if(U.type==="widget"){ce.update(U.config),W.content=U;return}ce.unmount(),f.delete(_)}W.container.innerHTML="";let Xt=h(W.container,U,_);if(W.content=U,Xt){let it=W.cleanup;W.cleanup=()=>{it?.(),Xt()}}},setOptions(U){let W=i.get(v);if(!W||W.id!==_)throw new Error("Mount no longer active");U.priority!==void 0&&(W.options.priority=U.priority),U.animation!==void 0&&(W.options.animation=U.animation),U.constraints&&L==="static"&&(U.constraints.maxWidth&&(W.container.style.maxWidth=U.constraints.maxWidth),U.constraints.maxHeight&&(W.container.style.maxHeight=U.constraints.maxHeight),U.constraints.minWidth&&(W.container.style.minWidth=U.constraints.minWidth),U.constraints.minHeight&&(W.container.style.minHeight=U.constraints.minHeight)),d(v)},async unmount(){let U=i.get(v);!U||U.id!==_||await x(U)},isMounted(){return i.get(v)?.id===_},getContainer(){let U=i.get(v);return U?.id===_?U.container:null}}}async function x(v){v.container.isConnected&&await U0(v.container,v.options.animation);try{v.cleanup?.()}catch(C){console.warn("[Surfaces] Cleanup error during unmount, ignoring:",C)}try{v.container.remove()}catch{}i.delete(v.slot),c("surface.unmounted",{slot:v.slot,id:v.id}),d(v.slot)}function b(v){let C=i.get(v);return{slot:v,occupied:!!C,currentPriority:C?.options.priority,currentAdaptiveId:C?.options.adaptiveId,mountCount:s.get(v)??0,currentMountId:C?.id}}function g(v,C){let w=l.get(v);return w||(w=new Set,l.set(v,w)),w.add(C),()=>{w?.delete(C),w?.size===0&&l.delete(v)}}function m(v,C){let w=i.get(v);return w?C!==void 0?C>=w.options.priority:!1:!0}function y(){for(let v of i.values())try{v.cleanup?.(),v.container.remove()}catch(C){console.error("[Surfaces] Error during cleanup:",C)}i.clear(),l.clear()}return{mount:S,getState:b,onStateChange:g,canMount:m,destroy:y}}var Ih=class{constructor(){B(this,"widgets",new Map);B(this,"mountedWidgets",new Map);B(this,"mountIdCounter",0);B(this,"runtimeRef");B(this,"listeners",new Set)}bindRuntime(e){this.runtimeRef=e}register(e,a,r="custom",n){if(this.widgets.has(e)){if(this.widgets.get(e).source==="built-in")throw new Error(`Cannot override built-in widget: ${e}`);console.warn(`[WidgetRegistry] Overriding widget: ${e}`)}this.widgets.set(e,{id:e,widget:a,source:r,metadata:n}),this.notify({type:"registered",widgetId:e})}unregister(e){let a=this.widgets.get(e);return a?a.source==="built-in"?(console.warn(`[WidgetRegistry] Cannot unregister built-in widget: ${e}`),!1):(this.widgets.delete(e),this.notify({type:"unregistered",widgetId:e}),!0):!1}unregisterBySource(e){for(let[a,r]of this.widgets.entries())r.source===e&&this.widgets.delete(a)}get(e){return this.widgets.get(e)?.widget}getRegistration(e){return this.widgets.get(e)}has(e){return this.widgets.has(e)}mount(e,a,r){let n=this.widgets.get(e);if(!n)throw new Error(`Widget not found: ${e}`);let o=`widget-mount-${++this.mountIdCounter}`;a.setAttribute("data-widget-mount-id",o),a.setAttribute("data-widget-id",e);let i={...r,runtime:this.runtimeRef},s=n.widget.mount(a,i);return this.mountedWidgets.set(o,{cleanup:s??void 0,container:a}),{widgetId:e,container:a,unmount:()=>{let u=this.mountedWidgets.get(o);u&&(a.isConnected&&u.cleanup?.(),this.mountedWidgets.delete(o),a.removeAttribute("data-widget-mount-id"),a.removeAttribute("data-widget-id"),a.innerHTML="")},update:u=>{if(n.widget.update)n.widget.update(a,u);else{let c=this.mountedWidgets.get(o);if(c){c.cleanup?.(),a.innerHTML="";let d={...u,runtime:this.runtimeRef},f=n.widget.mount(a,d);c.cleanup=f??void 0}}}}}list(){return Array.from(this.widgets.keys())}listRegistrations(){return Array.from(this.widgets.values())}getBySource(e){return Array.from(this.widgets.values()).filter(a=>a.source===e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(let a of this.listeners)try{a(e)}catch(r){console.error("[WidgetRegistry] Listener error:",r)}}destroy(){for(let[e,a]of this.mountedWidgets.entries())a.cleanup?.(),a.container.innerHTML="";this.mountedWidgets.clear()}},$0=new Ih;var yR="2.0.0";function V4(t,e){if(!e)return!0;let a;try{a=new URL(t).pathname}catch{a=t}let r=a.replace(/\/$/,"")||"/";if(e.exclude){for(let n of e.exclude)if(j0(r,n))return!1}if(e.include&&e.include.length>0){for(let n of e.include)if(j0(r,n))return!0;return!1}return!0}function j0(t,e){let a=e.replace(/\/$/,"")||"/";if(t===a)return!0;let r=a.replace(/\*\*/g,"\0GLOBSTAR\0").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\0GLOBSTAR\0/g,".*").replace(/:[^/]+/g,"[^/]+");return new RegExp(`^${r}$`).test(t)}function vR(t){let a=(typeof window<"u"?window.location.pathname:"/").replace(/\/$/,"")||"/";return(Array.isArray(t.route)?t.route:[t.route]).some(n=>{let o=n;if(/^https?:\/\//.test(o))try{o=new URL(o).pathname}catch{}return j0(a,o)})}function G0(t={}){let{telemetry:e,sessionMetrics:a,routes:r,mode:n="production",namespace:o}=t,i=t.widgets??$0,s=t.executors??xn,l=t.apps??hu,u=new Nc,c=I0({telemetry:e,routes:r,navigation:u}),d=t.events??Bc(),f=B0({namespace:o}),h=E0({eventBus:d,stateStore:f}),S=A0({state:f,events:d,sessionMetrics:a,accumulator:h}),x=G1(),b=L0(),g=_=>vR(_)?b.resolve(_.selector):null,m=async(_,L)=>{if(!vR(_))return null;try{return await b.waitFor(_.selector,L)}catch{return null}},y=V0({overlayRoot:x,eventBus:d,anchorResolver:g,widgetRegistry:i}),v=c0({overlayRoot:x,eventBus:d,surfaces:y,anchorResolver:g,waitForAnchor:m,executorRegistry:s,subscribeNavigation:_=>u.subscribe(_),runtime:{evaluateSync:_=>S.evaluateSync(_,c.get()),context:c,accumulator:h}}),C;if(a){a.increment("page_views");let _=typeof window<"u"?window.location.pathname:"/";C=u.subscribe((L,A)=>{if(A!=="replaceState")try{let I=new URL(L).pathname;I!==_&&(_=I,a.increment("page_views"))}catch{}})}let w={telemetry:e,context:c,events:d,state:f,sessionMetrics:a,actions:v,surfaces:y,widgets:i,executors:s,apps:l,accumulator:h,anchorResolver:b,navigation:u,version:yR,mode:n,async evaluate(_){return S.evaluate(_,c.get())},evaluateSync(_){return S.evaluateSync(_,c.get())},async filterTiles(_){let L=c.get().page.url,A=[];for(let I of _){let R=I.activation;if(!R){A.push(I);continue}if(V4(L,R.routes)){if(R.onlyIfPopulated){let H=I.props?.actions??[];if(H.length>0&&!H.some(M=>M.triggerWhen?S.evaluateSync(M.triggerWhen,c.get()).value:!0))continue}A.push(I)}}return A},setRoutes(_){c.setRoutes(_)},destroy(){l.unbind().catch(_=>{console.error("[Runtime] Error unbinding apps registry:",_)}),C?.(),b.destroy(),h.destroy(),u.destroy(),c.destroy(),v.destroy(),y.destroy()}};return l.bind(w),i.bindRuntime(w),w}var $4=p.object({value:p.unknown(),expiresAt:p.number().optional()}),j4=p.object({count:p.number(),resetAt:p.number().optional()});function SG(t){return $4.safeParse(t)}function _G(t){return j4.safeParse(t)}var W0="syn_";function qc(t){if(!t.startsWith(W0))throw new Error("Invalid Syntro token: must start with 'syn_'");let a=t.slice(W0.length).replace(/-/g,"+").replace(/_/g,"/"),r=atob(a),n=JSON.parse(r);if(n.v!==1)throw new Error(`Unsupported token version: ${n.v}`);return n}function Z0(t){let e=JSON.stringify(t),a=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return W0+a}function Wa(t){if(typeof process<"u"&&process.env)return process.env[t];try{let e=(0,eval)("import.meta");if(e?.env)return e.env[t]}catch{}}var bR="syntro_segment_attributes";function SR(){if(typeof window>"u")return{};try{let t=localStorage.getItem(bR);if(t){let e=JSON.parse(t);return K("Syntro Bootstrap","Loaded cached segment attributes:",e),e}}catch(t){na("Syntro Bootstrap","Failed to load cached segment attributes:",t)}return{}}function _R(t){if(!(typeof window>"u"))try{localStorage.setItem(bR,JSON.stringify(t)),K("Syntro Bootstrap","Cached segment attributes:",t)}catch(e){na("Syntro Bootstrap","Failed to cache segment attributes:",e)}}function CR(t){if(!t)return{};let e={};for(let[a,r]of Object.entries(t))a.startsWith("in_segment_")&&(e[a]=r===!0);return e}function X0(){if(typeof window>"u")return{};let t={};try{let e=new URLSearchParams(window.location.search);for(let a of["utm_source","utm_medium","utm_campaign","utm_content","utm_term"]){let r=e.get(a);r&&(t[a]=r)}}catch{}try{navigator.language&&(t.browser_language=navigator.language),navigator.languages?.length&&(t.browser_languages=[...navigator.languages])}catch{}try{let e=window.innerWidth;t.device_type=e<768?"mobile":e<1024?"tablet":"desktop"}catch{}try{if(document.referrer){t.referrer=document.referrer;try{t.referrer_hostname=new URL(document.referrer).hostname}catch{}}}catch{}try{let e=navigator.userAgent;e.includes("Edg/")?t.browser="Edge":e.includes("OPR/")||e.includes("Opera")?t.browser="Opera":e.includes("Chrome/")&&!e.includes("Chromium")?t.browser="Chrome":e.includes("Safari/")&&!e.includes("Chrome")?t.browser="Safari":e.includes("Firefox/")&&(t.browser="Firefox"),e.includes("Windows")?t.os="Windows":e.includes("iPhone")||e.includes("iPad")?t.os="iOS":e.includes("Mac OS X")||e.includes("Macintosh")?t.os="macOS":e.includes("Android")?t.os="Android":e.includes("Linux")&&(t.os="Linux")}catch{}try{t.page_url=window.location.href,t.page_path=window.location.pathname,t.page_host=window.location.hostname,window.location.search&&(t.page_query=window.location.search)}catch{}return t}var xR="syntro_geo",wR="https://geo.syntrologie.com";async function K0(t){if(typeof window>"u")return{};try{let e=localStorage.getItem(xR);if(e){let a=JSON.parse(e);return K("Syntro Bootstrap","Geo: using cached data:",a),a}}catch{}try{let e=await fetch(t,{signal:AbortSignal.timeout(2e3)});if(e.ok){let a=await e.json(),r={};for(let[n,o]of Object.entries(a))typeof o=="string"&&o&&(r[n]=o);try{localStorage.setItem(xR,JSON.stringify(r))}catch{}return K("Syntro Bootstrap","Geo: fetched from worker:",r),r}}catch{}return{}}var LR={growthbook:t=>Xy({...t,autoInit:!0})};function kR(t,e){let a=LR[t];if(!a)throw new Error(`Unknown experiment provider: ${t}. Supported: ${Object.keys(LR).join(", ")}`);return a(e)}var G4=["cdn.syntrologie.com","localhost","127.0.0.1"];function W4(t){try{let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(console.warn("[SmartCanvas] CDN URL must use HTTPS:",t),!1):G4.some(n=>e.hostname===n)?!0:(console.warn("[SmartCanvas] CDN host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid CDN URL:",t),!1}}var Y0=class{constructor(e){B(this,"name","cdn");B(this,"url");B(this,"integrity");if(this.url=`${e.baseUrl}/${e.configId}.json`,this.integrity=e.integrity,!W4(this.url))throw new Error(`[SmartCanvas] CDN URL not allowed: ${this.url}`)}async fetch(){let e=performance.now(),a=await fetch(this.url,{credentials:"omit",cache:"default"});if(!a.ok)throw new Error(`[SmartCanvas] Failed to fetch config from CDN (${a.status})`);let r=await a.text();if(this.integrity){let l=await Z4(r),u=this.integrity.replace("sha384-","");if(l!==u)throw new Error(`[SmartCanvas] Config integrity check failed. Expected ${u}, got ${l}`)}let n=JSON.parse(r),o=performance.now()-e,i=a.headers.get("cache-control"),s=a.headers.get("age");return{config:n,meta:{source:"cdn",fetchTimeMs:o,cached:i?.includes("public")??!1,cacheAge:s?parseInt(s,10):void 0}}}};async function Z4(t){let a=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-384",a),n=new Uint8Array(r);return btoa(String.fromCharCode(...n))}function IR(t){return new Y0(t)}var X4="syntro_exp",K4="syntro_var",Q0=class{constructor(e){B(this,"name","experiments");B(this,"client");B(this,"featureKey");B(this,"manifestKey");B(this,"variantFlagPrefix");this.client=e.client,this.featureKey=e.featureKey??"smart-canvas-config",this.manifestKey=e.manifestKey,this.variantFlagPrefix=e.variantFlagPrefix}async fetch(){let e=performance.now();if(typeof window<"u"){let n=new URLSearchParams(window.location.search),o=n.get(X4),i=n.get(K4);if(o&&i!==null&&this.client.setForcedVariations){let s=parseInt(i,10);Number.isNaN(s)||(console.log(`[SmartCanvas] Preview mode: forcing "${o}" to variation ${s}`),this.client.setForcedVariations({[o]:s}))}}if(this.manifestKey||this.variantFlagPrefix||this.client.getAllFeatures){let n=this.fetchMultiFlag();if(n){let o=performance.now()-e;return{config:n,meta:{source:"experiments",fetchTimeMs:o,cached:!0}}}}if(!this.featureKey)throw new Error("[SmartCanvas] No featureKey configured and no variant flags found. Ensure at least one config feature flag exists in your experiment platform.");let a=this.client.getFeatureValue?.(this.featureKey,null);if(!a||typeof a!="object")throw new Error(`[SmartCanvas] Feature "${this.featureKey}" not found or invalid. Ensure the feature is configured in your experiment platform.`);let r=performance.now()-e;return{config:a,meta:{source:"experiments",fetchTimeMs:r,cached:!0}}}fetchMultiFlag(){let e=this.getVariantFlagKeys();return!e||e.length===0?null:Zf(this.client,e)}getVariantFlagKeys(){if(this.manifestKey){let e=this.client.getFeatureValue?.(this.manifestKey,null);if(e&&typeof e=="object"){let a=e.variant_flags;if(a&&a.length>0)return a}}if(this.client.getAllFeatures){let e=this.client.getAllFeatures();return this.variantFlagPrefix?Object.keys(e).filter(a=>a.startsWith(this.variantFlagPrefix)):Object.keys(e)}return[]}};function AR(t){return new Q0(t)}var Y4="https://cdn.syntrologie.com/configs",ER={cdn:t=>{if(!t.configId)throw new Error("CDN fetcher requires 'configId' option");return IR({baseUrl:t.baseUrl??Y4,configId:t.configId,integrity:t.integrity})},experiments:t=>{if(!t.featureKey)throw new Error("Experiments fetcher requires 'featureKey' option");return AR({featureKey:t.featureKey})}};function TR(t,e={}){let a=ER[t];if(!a)throw new Error(`Unknown config fetcher type: ${t}. Supported: ${Object.keys(ER).join(", ")}`);return a(e)}var RR={posthog:t=>$b(t),noop:()=>ax()};function MR(t,e){let a=RR[t];if(!a)throw new Error(`Unknown telemetry provider: ${t}. Supported: ${Object.keys(RR).join(", ")}`);return a(e)}async function OR(t){ay(),K("Syntro Bootstrap","====== INIT ======"),K("Syntro Bootstrap","Options:",{hasToken:!!t.token,tokenPrefix:`${t.token?.slice(0,15)}...`,hasCanvasOptions:!!t.canvas});let e=Yf();if(console.log(`[DIAG] Mode detection: sdkMode=${e}`),console.log("[DIAG] editorSource:",Su()),console.log("[DIAG] editorConf:",Kf()),K("Syntro Bootstrap","SDK mode:",e??"normal"),!e&&typeof window<"u"){let E=!!window.__SYNTRO_EDITOR_PARAMS__,M=!!window.__SYNTRO_AUDIT_LEGEND__,D=!!window.__SYNTRO_REVIEW_DATA__;if(E||M||D){let F=[E&&"__SYNTRO_EDITOR_PARAMS__",M&&"__SYNTRO_AUDIT_LEGEND__",D&&"__SYNTRO_REVIEW_DATA__"].filter(Boolean);console.warn(`[Syntro Bootstrap] \u26A0 Mode detection returned null but mode-specific globals found: ${F.join(", ")}. This suggests URL params were lost (redirect?) but the service worker injected mode data. Check if replaceState failed or if page JS changed the URL before init().`)}}console.log(`[DIAG] Token resolution: options.token=${t.token?t.token.slice(0,15)+"...":"null"}`);let a=t.token;if(!a&&e){let M=Kf()?.syntro_token;M?.startsWith("syn_")&&(a=M,K("Syntro Bootstrap",`\u2713 Using syntro_token from editor_conf (${e} mode)`))}let r;if(a)if(a.startsWith("syn_"))K("Syntro Bootstrap","Token starts with syn_, decoding..."),r=qc(a),ay(r.d);else if(e)K("Syntro Bootstrap",`\u2713 Non-syn_ token allowed (${e} mode)`);else throw Xf("Syntro Bootstrap","\u274C Token does not start with syn_ and NOT in editor/audit/review mode!"),Xf("Syntro Bootstrap","Token received:",a),new Error("Invalid Syntro token: must start with 'syn_'");else if(e)K("Syntro Bootstrap",`\u2713 No token, but ${e} mode - proceeding`);else throw Xf("Syntro Bootstrap","\u274C No token provided and NOT in editor/audit/review mode!"),new Error("Syntro token is required (unless in editor, audit, or review mode)");let n=Wa("NEXT_PUBLIC_SYNTRO_EXPERIMENT_HOST")||Wa("VITE_SYNTRO_EXPERIMENT_HOST")||r?.eh,o=Wa("NEXT_PUBLIC_SYNTRO_TELEMETRY_HOST")||Wa("VITE_SYNTRO_TELEMETRY_HOST")||r?.th,i=Wa("NEXT_PUBLIC_SYNTRO_EDITOR_URL")||Wa("VITE_SYNTRO_EDITOR_URL")||t.canvas?.editorUrl,s=r?.g||Wa("NEXT_PUBLIC_SYNTRO_GEO_HOST")||Wa("VITE_SYNTRO_GEO_HOST")||wR,l=SR(),u=X0(),c={...u,...l};K("Syntro Bootstrap","Phase 1: Browser metadata:",u),K("Syntro Bootstrap","Phase 1: Cached segment attributes:",l);let d=K0(s),f,h=t.debug||t.testMode,S=Bc({debug:t.debug,history:h?new Pc(t.testMode?0:100):void 0,testMode:t.testMode});console.log("[Syntro Bootstrap] EventBus created");let x=sy({elementResolver:typeof window<"u"?(E,M)=>{let D=document.elementFromPoint(E,M);if(!D)return null;let F={tag_name:D.tagName.toLowerCase()};D.id&&(F.attr__id=D.id),D.className&&typeof D.className=="string"&&(F.classes=D.className.split(" ").filter(Boolean));for(let Z of D.attributes)Z.name.startsWith("data-")&&(F[`attr__${Z.name}`]=Z.value);return F}:void 0});x.onEvent(E=>S.publishEvent(E)),typeof window<"u"&&(setInterval(()=>x.tick(Date.now()),1e3),document.addEventListener("click",E=>{let M=[],D=E.target;for(;D&&D!==document.body;){let F={tag_name:D.tagName.toLowerCase()};for(let Z of D.attributes)(Z.name.startsWith("data-")||Z.name==="id"||Z.name==="class"||Z.name==="aria-label")&&(F[`attr__${Z.name}`]=Z.value);M.push(F),D=D.parentElement}x.enrichClickAttributes(Date.now(),M)},!0));let b=E=>{K("Syntro Bootstrap","Phase 2: PostHog feature flags loaded");let M=CR(E);if(K("Syntro Bootstrap","Segment flags from PostHog:",M),_R(M),f){let D=m?.getAll?.()??{},F={...u,...D,...M};K("Syntro Bootstrap","Updating GrowthBook with attributes:",F),f.setAttributes?.(F)}},g;if(r?.t){let E=r.t==="noop"?"noop":"posthog";g=MR(E,{apiKey:r.t,apiHost:o,enableFeatureFlags:!0,sessionRecording:!r.d,onFeatureFlagsLoaded:b,onCapture:(D,F)=>{x.ingest({kind:"posthog",event:D,properties:F,timestamp:Date.now()})},onRRWebEvent:D=>{x.ingest(D)}}),console.log(`[Syntro Bootstrap] Telemetry client created (${E}) with EventBus wiring`);let M=g;S.setPosthogCapture((D,F)=>{M.track?.(D,F)})}let m;r?.e&&(f=kR("growthbook",{clientKey:r.e,apiHost:n,attributes:c,onExperimentViewed:g?.trackExperiment?(E,M,D)=>{g.trackExperiment(E,M,D)}:void 0})),m=Ky({experiments:f,onMetricChange:(E,M)=>{K("Syntro Bootstrap",`Session metric changed: ${E} = ${M}`)}}),K("Syntro Bootstrap","SessionMetricTracker created");let y="production";e==="editor"?y="editor":e==="audit"?y="audit":Wa("NODE_ENV")==="development"&&(y="development");let v=G0({telemetry:g,sessionMetrics:m,mode:y,events:S});K("Syntro Bootstrap","Runtime created:",{version:v.version,mode:v.mode,hasContext:!!v.context,hasEvents:!!v.events,hasState:!!v.state}),K("Syntro Bootstrap","Core app executors already registered");let C=t.cdnBase||Wa("NEXT_PUBLIC_SYNTRO_CDN_BASE")||Wa("VITE_SYNTRO_CDN_BASE")||"https://cdn.syntrologie.com",w=Pv({cdnBase:C,registry:v.apps,onLoadStart:E=>{K("Syntro Bootstrap",`Loading app from CDN: ${E}`)},onLoadEnd:(E,M,D)=>{M?K("Syntro Bootstrap",`App loaded successfully: ${E}`):na("Syntro Bootstrap",`Failed to load app: ${E}`,D)}});typeof window<"u"&&(window.SynOS={...window.SynOS,appRegistry:v.apps,runtime:v,version:v.version},K("Syntro Bootstrap","Global SynOS object exposed"));let _=v.apps.list?.()??[];console.log(`[DIAG] Activation loop: ${_.length} apps in registry:`,_.map(E=>`${E.manifest.id}(${E.state})`).join(", "));for(let E of _)if(E.state==="registered")try{await v.apps.activate(E.manifest.id),console.log(`[DIAG] Activated: ${E.manifest.id} \u2192 widgets: [${v.widgets.list().join(", ")}]`)}catch(M){console.error(`[DIAG] FAILED to activate: ${E.manifest.id}`,M),na("Syntro Bootstrap",`Failed to auto-activate built-in app: ${E.manifest.id}`,M)}if(console.log(`[DIAG] Activation complete. Total widgets: [${v.widgets.list().join(", ")}]`),f?.refreshFeatures)try{await f.refreshFeatures(),K("Syntro Bootstrap","GrowthBook features loaded")}catch(E){na("Syntro Bootstrap","Failed to load GrowthBook features:",E)}let L=await d;if(f&&Object.keys(L).length>0){let E={...u,...L};K("Syntro Bootstrap","Merging geo data into GrowthBook attributes:",L),f.setAttributes?.(E)}let A;if(t.fetcher)A=t.fetcher;else if(r?.f){let E=TR(r.f,r.o??{});A=async()=>{let M=await E.fetch();return{...M.config,tiles:M.config.tiles??[]}}}else f&&(A=Cs({experiments:f}));let I=new Set,R=A?async()=>{let E=await A(),M=E.tiles?.length??0,D=E.actions?.length??0,F=E.meta?.variant_id;if((M>0||D>0)&&(F||console.warn("[Syntro] Config has content but no meta.variant_id \u2014 intervention tracking disabled")),g&&F){let W=new kc(g,F);W.trackServed(M,D),typeof window<"u"&&(window.SynOS.interventionTracker=W),v.navigation.subscribe(()=>{W.resetPage()})}console.log("[Syntro Bootstrap] Config fetched:",`tiles=${E.tiles?.length??0},`,`actions=${E.actions?.length??0},`,`theme=${E.theme?.name??"none"}`),E.actions?.length>0&&console.log("[Syntro Bootstrap] Actions in config:",E.actions.map((W,ce)=>`[${ce}] ${W.kind}${W.anchorId?` anchor="${W.anchorId.selector}"`:""}${W.label?` "${W.label}"`:""}`).join(", "));let Z=E,U=w.getRequiredApps(Z);return U.length>0?console.log("[Syntro Bootstrap] Required external apps:",U.join(", ")):K("Syntro Bootstrap","No external apps required (all executors are built-in)"),U.length>0&&await w.loadAppsForConfig(Z).then(async ce=>{let Xt=ce.filter(N=>N.success),it=ce.filter(N=>!N.success);Xt.length>0&&console.log(`[Syntro Bootstrap] Apps loaded from CDN: ${Xt.map(N=>N.appId).join(", ")}`);let yt=it.filter(N=>!I.has(N.appId));yt.length>0&&(console.error("[Syntro Bootstrap] Apps FAILED to load from CDN:",yt.map(N=>`${N.appId} (${N.error})`).join(", ")),yt.forEach(N=>I.add(N.appId)));for(let N of U)if(v.apps.has(N))try{await v.apps.activate(N),console.log(`[Syntro Bootstrap] App activated: ${N}`)}catch(te){console.error(`[Syntro Bootstrap] Failed to activate app: ${N}`,te)}else console.error(`[Syntro Bootstrap] App "${N}" required by config but NOT registered.`,`Available apps: [${Array.from(v.apps.list?.()??[]).join(", ")}]`)}),E}:void 0;return{canvas:await Ty({...t.canvas,fetcher:R,integrations:{experiments:f,telemetry:g},editorUrl:i,runtime:v}),runtime:v,experiments:f,telemetry:g,sessionMetrics:m,appLoader:w}}async function Q4(t){try{return await OR(t)}catch(e){let a=e instanceof Error?e.message:String(e);console.warn("[Syntrologie] SDK initialization failed:",a),typeof document<"u"&&document.getElementById("syntrologie-anti-flicker")?.remove();return}}function J4(t,e={}){if(typeof window>"u")return;let a=window.SynOS?.runtime;a?.events?.publish&&a.events.publish({name:t,source:"custom",props:e})}var DR={init:Q4,encodeToken:Z0,decodeToken:qc,events:{emit:J4}};typeof window<"u"&&(window.Syntro=DR);var BR="2026-04-13T17:37:13.929Z (e3f2c1dda1d)";if(typeof window<"u"){console.log(`[Syntro Runtime] Build: ${BR}`);let t=window.SynOS,e=t?.appRegistry||hu;window.SynOS={...t,appRegistry:e,_runtimeBuild:BR,React:PR.default,ReactDOM:{...eU,createPortal:Ah.createPortal,flushSync:Ah.flushSync}},D1(e)}export{zc as ANIMATION_KEYFRAMES,xh as ActivationConfigZ,UT as AddClassZ,Ga as AnchorIdZ,O4 as AnchorStateZ,p0 as AnchorVisibleConditionZ,Hf as AppRegistry,D4 as AugmentationZ,ET as BadgePositionZ,GT as BadgeZ,M4 as BoundingBoxZ,Lu as CanvasEvents,ex as CanvasRecipeZ,Lo as ConditionZ,bh as ContextManager,x0 as CooldownActiveConditionZ,Ac as CounterDefZ,w0 as CtaButtonZ,py as DEFAULT_COOLDOWN,fy as DEFAULT_TTL,Dc as DecisionStrategyZ,y0 as DismissedConditionZ,rt as EVENT_SCHEMA_VERSION,wh as EventBus,S0 as EventCountConditionZ,U4 as EventFilterZ,Pc as EventHistory,h0 as EventOccurredConditionZ,cR as EventSourceZ,hh as ExecutorRegistry,Oc as ExternalStrategyZ,j4 as FrequencyEntryZ,b0 as FrequencyLimitConditionZ,O3 as HighlightStepZ,AT as HighlightStyleZ,$T as HighlightZ,VT as InsertHtmlZ,OT as InsertPositionZ,kc as InterventionTracker,dy as MAX_VISIBLE_TOASTS,Ic as MatchOpZ,MT as ModalContentZ,ZT as ModalZ,Mc as ModelStrategyZ,YT as MountWidgetZ,KT as NavigateZ,Nc as NavigationMonitor,H4 as NormalizedEventZ,cy as NotificationToastStack,A4 as PageContextZ,E4 as PageHistoryEntryZ,d0 as PageUrlConditionZ,eR as ParallelZ,TT as PlacementZ,jT as PulseZ,BR as RUNTIME_SDK_BUILD,yR as RUNTIME_VERSION,zT as RemoveClassZ,f0 as RouteConditionZ,IT as RouteFilterZ,Tc as RuleStrategyZ,Ec as RuleZ,B4 as RuntimeContextZ,yy as RuntimeProvider,eo as SDK_SCHEMA_VERSION,ry as SDK_VERSION,hR as STATIC_SLOT_STYLES,Rc as ScoreStrategyZ,NT as ScrollBehaviorZ,C0 as ScrollLogicalPositionZ,XT as ScrollToZ,xA as SelectorZ,JT as SequenceZ,T4 as SessionContextZ,v0 as SessionMetricConditionZ,Ep as SessionMetricTracker,HT as SetAttrZ,qT as SetStyleZ,FT as SetTextZ,pI as ShadowCanvasOverlay,X1 as ShadowRootProvider,yI as SmartCanvasApp,oy as SmartCanvasController,Ay as SmartCanvasElement,S8 as SmartCanvasPortal,Mt as StandardEvents,m0 as StateEqualsConditionZ,Lh as StateStore,$4 as StoredValueZ,DR as Syntro,Uu as TileCard,c$ as TileWheel,RT as TooltipContentZ,M3 as TooltipStepZ,DT as TooltipTriggerZ,WT as TooltipZ,PT as TourStepForSchemaZ,tR as TourZ,yh as TriggerWhenZ,g0 as ViewportConditionZ,R4 as ViewportContextZ,QT as WaitZ,BT as WidgetConfigZ,Ih as WidgetRegistry,hu as appRegistry,P0 as applyStaticSlotStyles,Dv as cleanupAppContext,bv as contentRuntime,k4 as coreActionStepSchemas,c0 as createActionEngine,L0 as createAnchorResolver,Ov as createAppContext,Pv as createAppLoader,Cs as createCanvasConfigFetcher,I0 as createContextManager,A0 as createDecisionEngine,E0 as createEventAccumulator,Bc as createEventBus,Xy as createGrowthBookClient,ax as createNoopClient,x8 as createOverlayRecipeFetcher,$b as createPostHogClient,eI as createPostHogNormalizer,Ky as createSessionMetricTracker,Ty as createSmartCanvas,W1 as createSmartCanvasController,G0 as createSmartCanvasRuntime,B0 as createStateStore,z0 as createSurfaceContainer,V0 as createSurfaces,x9 as decisionSchemas,qc as decodeToken,Z0 as encodeToken,iR as evaluate,rR as evaluateCondition,nR as evaluateRule,Sh as evaluateRuleStrategy,_h as evaluateScoreStrategy,sR as evaluateSync,xn as executorRegistry,oP as getAntiFlickerSnippet,e1 as getAppIdFromActionKind,Bv as getAppIdFromWidgetId,d4 as getExecutor,kh as getSlotAnchorId,Uc as getSlotType,q0 as getSlotZIndex,Zb as hasExecutor,up as interpolateTemplate,Jk as isCoreActionKind,hy as matchEvent,h$ as needsMigration,Cu as normalizePostHogEvent,Mv as overlaysRuntime,zu as parseVersion,H0 as playEnterAnimation,U0 as playExitAnimation,Qf as registerConfigPredicates,_I as registerSmartCanvasElement,ny as resolveConfigUri,N0 as setupAdjacentPositioning,F0 as setupInlinePositioning,wu as shouldNormalizeEvent,dN as useDecision,my as useNotifications,gy as useNotifyWatcher,xy as usePageContext,Jr as useRuntime,dp as useRuntimeContext,uN as useRuntimeEvents,cN as useRuntimeState,sN as useSessionContext,gI as useShadowCanvasConfig,ks as useShadowRoot,lN as useViewportContext,Ar as validateAction,vh as validateActions,y9 as validateActivationConfig,g9 as validateCondition,p$ as validateConfig,gj as validateEventFilter,T0 as validateEventName,_G as validateFrequencyEntry,mj as validateNormalizedEvent,R0 as validateProps,m8 as validateRecipe,z9 as validateRuntimeContext,SG as validateStoredValue,v9 as validateStrategy,$0 as widgetRegistry};
504
504
  /*! Bundled license information:
505
505
 
506
506
  react/cjs/react.production.js: