@syntrologie/runtime-sdk 2.6.0-canary.7 → 2.7.0-canary.1

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.
@@ -126,7 +126,7 @@ Error generating stack: `+r.message+`
126
126
  s.textContent = '.${e} { ${a} }';
127
127
  document.head.appendChild(s);
128
128
  document.documentElement.className += ' ${e}';
129
- })();`}function kf(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}}}return null}var $v=!1;function OI(){if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("syntro_debug")==="true"}catch{return!1}}function jv(t){if(OI()){$v=!0;return}$v=t??!1}function _D(){return OI()?!0:$v}function X(t,e,a){_D()&&(a!==void 0?console.log(`[${t}]`,e,a):console.log(`[${t}]`,e))}function ga(t,e,a){a!==void 0?console.warn(`[${t}]`,e,a):console.warn(`[${t}]`,e)}function Ef(t,e,a){a!==void 0?console.error(`[${t}]`,e,a):console.error(`[${t}]`,e)}var Tf="2.6.0-canary.7";var jr="2.0";var wD=["api.syntrologie.com","cdn.syntrologie.com","localhost","127.0.0.1"];function LD(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):wD.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 ID(t){if(typeof window>"u")return!1;try{return new URL(t).origin===window.location.origin}catch{return!1}}var BI="syntro_config_cache",AD=1440*60*1e3;function FI(){try{return typeof localStorage<"u"&&localStorage!==null}catch{return!1}}function kD(t,e){if(FI())try{let a={config:t,timestamp:Date.now(),sdkVersion:e};localStorage.setItem(BI,JSON.stringify(a))}catch{}}function ED(t){if(!FI())return null;try{let e=localStorage.getItem(BI);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>AD?null:a.config}catch{return null}}var Rf=({configUri:t,experiments:e,featureKey:a="smart-canvas-config-uri"})=>{if(t)return t;let r=e?.getFeatureValue?.(a,null);if(r)return r};function TD(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(a&&t.getAllFeatures){let r=t.getAllFeatures();return Object.keys(r).filter(n=>n.startsWith(a))}return[]}var Vo=({configUri:t,experiments:e,featureKey:a,credentials:r,configFeatureKey:n="smart-canvas-config",manifestKey:o,variantFlagPrefix:i,sdkVersion:s})=>async()=>{if(e&&n){let c=e.getFeatureValue?.(n,null);if(c&&typeof c=="object")return X("SmartCanvas Config","Resolved config directly from feature flag",c),c}if(e&&(o||i)){let c=TD(e,o,i);if(c.length>0){let d=kf(e,c);if(d)return X("SmartCanvas Config","Resolved config from variant flags",d),d}}let l=Rf({configUri:t,experiments:e,featureKey:a});if(!l)return X("SmartCanvas Config","No config available \u2014 returning empty config"),{tiles:[],actions:[],fetchedAt:new Date().toISOString()};if(!LD(l))throw new Error(`SmartCanvas: config URI not allowed: ${l}`);let u=r??(ID(l)?"include":"omit");try{let c=await fetch(l,{credentials:u,headers:{"X-SDK-Version":Tf,"X-SDK-Schema-Version":jr}});if(!c.ok)throw new Error(`SmartCanvas: failed to fetch config (${c.status})`);let d=await c.json();return X("SmartCanvas Config","Fetched config from URI",d),s&&kD(d,s),d}catch(c){if(s){let d=ED(s);if(d)return X("SmartCanvas Config","Serving config from offline cache"),d}throw c}};var RD=["cdn.syntrologie.com","api.syntrologie.com","dev-api.syntrologie.com","localhost","127.0.0.1",".syntrologie.com"];function NI(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 ga("Syntro Runtime",`Failed to decode ${t}:`,r),null}}var hs,ms;function $n(){if(hs==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.token)hs={token:t.token,api_base:t.apiBase||""},console.log(`[DIAG] getEditorSource: from __SYNTRO_EDITOR_PARAMS__ (token=${hs.token.slice(0,15)}...)`);else{let e=NI("editor_source");e&&(hs=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 hs??null}function $o(){if(ms==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.mode)ms={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=${ms.mode})`);else{let e=NI("editor_conf");e&&(ms=e),console.log(`[DIAG] getEditorConf: from URL param \u2192 ${e?`mode=${e.mode}`:"NULL"}`)}}return ms??null}function MD(t){X("Syntro Runtime","Validating editor URL:",t);try{if(t.startsWith("/"))return X("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?(ga("Syntro Runtime","\u274C Editor URL must use HTTPS:",t),!1):RD.some(n=>n.startsWith(".")?e.hostname.endsWith(n)||e.hostname===n.slice(1):e.hostname===n)?(X("Syntro Runtime","\u2713 Editor URL validated"),!0):(ga("Syntro Runtime","\u274C Editor URL host not in allowlist:",e.hostname),!1)}catch(e){return ga("Syntro Runtime",`\u274C Invalid editor URL: ${t}`,e),!1}}var PI=()=>{let t=$o();return!$n()?.token||!t?null:t.mode==="editor"||t.mode==="audit"||t.mode==="review"?t.mode:null};function DD(){return $n()?.token??null}function OD(){return $n()?.api_base??null}var yu=null,HI=async t=>{if(X("Syntro Runtime","====== LOAD EDITOR SDK ======"),typeof window>"u"){X("Syntro Runtime","Not in browser - skipping editor SDK load");return}if(window.SyntroEditor){X("Syntro Runtime","Editor SDK already loaded (window.SyntroEditor exists)");return}if(yu)return X("Syntro Runtime","Editor SDK load already in progress, waiting..."),yu;let e=typeof t=="string"?{editorUrl:t}:t??{};if(e.editorUrl==="skip"){X("Syntro Runtime",'editorUrl="skip" \u2014 deferring to caller'),X("Syntro Runtime","================================");return}let a=OD(),n=(a?`${a}/api/editor/sdk/editor-sdk.js`:null)||e.editorUrl;if(!n){ga("Syntro Runtime","\u274C No editor SDK URL available (no api_base, no editorUrl option)"),X("Syntro Runtime","================================");return}let o=DD();if(!o){ga("Syntro Runtime","\u274C No token found in editor_source."),X("Syntro Runtime","================================");return}let i=`${n}?token=${encodeURIComponent(o)}`;if(X("Syntro Runtime","Editor URL:",i),X("Syntro Runtime","Options:",{hasIntegrity:!!e.integrity,hasEditorUrl:!!n,hasApiBase:!!a,tokenPrefix:`${o.slice(0,10)}...`}),!MD(n)){console.error("[Syntro Runtime] \u274C BLOCKED: Editor from untrusted URL:",n),X("Syntro Runtime","================================");return}return X("Syntro Runtime","\u2713 URL validated, injecting script tag..."),yu=new Promise((s,l)=>{let u=document.createElement("script");u.src=i,u.async=!0,e.integrity&&(u.integrity=e.integrity,u.crossOrigin="anonymous",X("Syntro Runtime","SRI integrity check enabled")),u.onload=()=>{X("Syntro Runtime","\u2713 Editor SDK script loaded successfully"),X("Syntro Runtime","================================"),s()},u.onerror=c=>{console.error("[Syntro Runtime] \u274C Failed to load Editor SDK:",c),console.error("[Syntro Runtime] URL attempted:",i),X("Syntro Runtime","================================"),yu=null,l(c)},document.head.appendChild(u),X("Syntro Runtime","Script tag appended to <head>")}),yu};var BD=new Set(["tag_name","$el_text"]);function FD(t){return BD.has(t)||t.startsWith("attr__")}function UI(t,e){return t.equals!==void 0?e===t.equals:t.contains!==void 0?typeof e=="string"&&e.includes(t.contains):!1}function ND(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(FD(n)){let i=r.props?.elements;if(!i||!i.some(l=>UI(o,l[n])))return!1}else if(!UI(o,r.props?.[n]))return!1}return!0}}function qI(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?ND(n):()=>!0;e.register(r.key,o)}}function xu(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"&&qI(i.triggerWhen,e)}if(a)for(let r of a){let n=r;n.triggerWhen?.type==="rules"&&qI(n.triggerWhen,e)}}var cr=null;function VI(t){cr&&cr!==t?t.appendChild(cr):cr=t;let e=t.getRootNode();e instanceof ShadowRoot&&PD(e)}function $I(){return cr||(cr=document.createElement("div"),cr.id="syntro-overlays",Object.assign(cr.style,{position:"fixed",inset:"0",zIndex:"2147483645",pointerEvents:"none"}),document.body.appendChild(cr)),cr}var zI=!1;function PD(t){if(zI)return;let e=`
129
+ })();`}function kf(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}}}return null}var $v=!1;function OI(){if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("syntro_debug")==="true"}catch{return!1}}function jv(t){if(OI()){$v=!0;return}$v=t??!1}function _D(){return OI()?!0:$v}function X(t,e,a){_D()&&(a!==void 0?console.log(`[${t}]`,e,a):console.log(`[${t}]`,e))}function ga(t,e,a){a!==void 0?console.warn(`[${t}]`,e,a):console.warn(`[${t}]`,e)}function Ef(t,e,a){a!==void 0?console.error(`[${t}]`,e,a):console.error(`[${t}]`,e)}var Tf="2.7.0-canary.1";var jr="2.0";var wD=["api.syntrologie.com","cdn.syntrologie.com","localhost","127.0.0.1"];function LD(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):wD.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 ID(t){if(typeof window>"u")return!1;try{return new URL(t).origin===window.location.origin}catch{return!1}}var BI="syntro_config_cache",AD=1440*60*1e3;function FI(){try{return typeof localStorage<"u"&&localStorage!==null}catch{return!1}}function kD(t,e){if(FI())try{let a={config:t,timestamp:Date.now(),sdkVersion:e};localStorage.setItem(BI,JSON.stringify(a))}catch{}}function ED(t){if(!FI())return null;try{let e=localStorage.getItem(BI);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>AD?null:a.config}catch{return null}}var Rf=({configUri:t,experiments:e,featureKey:a="smart-canvas-config-uri"})=>{if(t)return t;let r=e?.getFeatureValue?.(a,null);if(r)return r};function TD(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 Vo=({configUri:t,experiments:e,featureKey:a,credentials:r,configFeatureKey:n="smart-canvas-config",manifestKey:o,variantFlagPrefix:i,sdkVersion:s})=>async()=>{if(e&&n){let c=e.getFeatureValue?.(n,null);if(c&&typeof c=="object")return X("SmartCanvas Config","Resolved config directly from feature flag",c),c}if(e&&(o||i||e.getAllFeatures)){let c=TD(e,o,i);if(c.length>0){let d=kf(e,c);if(d)return X("SmartCanvas Config","Resolved config from variant flags",d),d}}let l=Rf({configUri:t,experiments:e,featureKey:a});if(!l)return X("SmartCanvas Config","No config available \u2014 returning empty config"),{tiles:[],actions:[],fetchedAt:new Date().toISOString()};if(!LD(l))throw new Error(`SmartCanvas: config URI not allowed: ${l}`);let u=r??(ID(l)?"include":"omit");try{let c=await fetch(l,{credentials:u,headers:{"X-SDK-Version":Tf,"X-SDK-Schema-Version":jr}});if(!c.ok)throw new Error(`SmartCanvas: failed to fetch config (${c.status})`);let d=await c.json();return X("SmartCanvas Config","Fetched config from URI",d),s&&kD(d,s),d}catch(c){if(s){let d=ED(s);if(d)return X("SmartCanvas Config","Serving config from offline cache"),d}throw c}};var RD=["cdn.syntrologie.com","api.syntrologie.com","dev-api.syntrologie.com","localhost","127.0.0.1",".syntrologie.com"];function NI(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 ga("Syntro Runtime",`Failed to decode ${t}:`,r),null}}var hs,ms;function $n(){if(hs==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.token)hs={token:t.token,api_base:t.apiBase||""},console.log(`[DIAG] getEditorSource: from __SYNTRO_EDITOR_PARAMS__ (token=${hs.token.slice(0,15)}...)`);else{let e=NI("editor_source");e&&(hs=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 hs??null}function $o(){if(ms==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.mode)ms={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=${ms.mode})`);else{let e=NI("editor_conf");e&&(ms=e),console.log(`[DIAG] getEditorConf: from URL param \u2192 ${e?`mode=${e.mode}`:"NULL"}`)}}return ms??null}function MD(t){X("Syntro Runtime","Validating editor URL:",t);try{if(t.startsWith("/"))return X("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?(ga("Syntro Runtime","\u274C Editor URL must use HTTPS:",t),!1):RD.some(n=>n.startsWith(".")?e.hostname.endsWith(n)||e.hostname===n.slice(1):e.hostname===n)?(X("Syntro Runtime","\u2713 Editor URL validated"),!0):(ga("Syntro Runtime","\u274C Editor URL host not in allowlist:",e.hostname),!1)}catch(e){return ga("Syntro Runtime",`\u274C Invalid editor URL: ${t}`,e),!1}}var PI=()=>{let t=$o();return!$n()?.token||!t?null:t.mode==="editor"||t.mode==="audit"||t.mode==="review"?t.mode:null};function DD(){return $n()?.token??null}function OD(){return $n()?.api_base??null}var yu=null,HI=async t=>{if(X("Syntro Runtime","====== LOAD EDITOR SDK ======"),typeof window>"u"){X("Syntro Runtime","Not in browser - skipping editor SDK load");return}if(window.SyntroEditor){X("Syntro Runtime","Editor SDK already loaded (window.SyntroEditor exists)");return}if(yu)return X("Syntro Runtime","Editor SDK load already in progress, waiting..."),yu;let e=typeof t=="string"?{editorUrl:t}:t??{};if(e.editorUrl==="skip"){X("Syntro Runtime",'editorUrl="skip" \u2014 deferring to caller'),X("Syntro Runtime","================================");return}let a=OD(),n=(a?`${a}/api/editor/sdk/editor-sdk.js`:null)||e.editorUrl;if(!n){ga("Syntro Runtime","\u274C No editor SDK URL available (no api_base, no editorUrl option)"),X("Syntro Runtime","================================");return}let o=DD();if(!o){ga("Syntro Runtime","\u274C No token found in editor_source."),X("Syntro Runtime","================================");return}let i=`${n}?token=${encodeURIComponent(o)}`;if(X("Syntro Runtime","Editor URL:",i),X("Syntro Runtime","Options:",{hasIntegrity:!!e.integrity,hasEditorUrl:!!n,hasApiBase:!!a,tokenPrefix:`${o.slice(0,10)}...`}),!MD(n)){console.error("[Syntro Runtime] \u274C BLOCKED: Editor from untrusted URL:",n),X("Syntro Runtime","================================");return}return X("Syntro Runtime","\u2713 URL validated, injecting script tag..."),yu=new Promise((s,l)=>{let u=document.createElement("script");u.src=i,u.async=!0,e.integrity&&(u.integrity=e.integrity,u.crossOrigin="anonymous",X("Syntro Runtime","SRI integrity check enabled")),u.onload=()=>{X("Syntro Runtime","\u2713 Editor SDK script loaded successfully"),X("Syntro Runtime","================================"),s()},u.onerror=c=>{console.error("[Syntro Runtime] \u274C Failed to load Editor SDK:",c),console.error("[Syntro Runtime] URL attempted:",i),X("Syntro Runtime","================================"),yu=null,l(c)},document.head.appendChild(u),X("Syntro Runtime","Script tag appended to <head>")}),yu};var BD=new Set(["tag_name","$el_text"]);function FD(t){return BD.has(t)||t.startsWith("attr__")}function UI(t,e){return t.equals!==void 0?e===t.equals:t.contains!==void 0?typeof e=="string"&&e.includes(t.contains):!1}function ND(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(FD(n)){let i=r.props?.elements;if(!i||!i.some(l=>UI(o,l[n])))return!1}else if(!UI(o,r.props?.[n]))return!1}return!0}}function qI(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?ND(n):()=>!0;e.register(r.key,o)}}function xu(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"&&qI(i.triggerWhen,e)}if(a)for(let r of a){let n=r;n.triggerWhen?.type==="rules"&&qI(n.triggerWhen,e)}}var cr=null;function VI(t){cr&&cr!==t?t.appendChild(cr):cr=t;let e=t.getRootNode();e instanceof ShadowRoot&&PD(e)}function $I(){return cr||(cr=document.createElement("div"),cr.id="syntro-overlays",Object.assign(cr.style,{position:"fixed",inset:"0",zIndex:"2147483645",pointerEvents:"none"}),document.body.appendChild(cr)),cr}var zI=!1;function PD(t){if(zI)return;let e=`
130
130
  :host {
131
131
  --syntro-surface: var(--sc-overlay-background, #0f1318);
132
132
  --syntro-fg: var(--sc-overlay-text-color, #cbd0d7);
@@ -456,12 +456,12 @@ ${l}
456
456
  *, *::before, *::after {
457
457
  box-sizing: border-box;
458
458
  }
459
- `,Oa,Wn,Zn,Wr,Zr,Xn,Xr,Gf=class extends HTMLElement{constructor(){super();pn(this,Oa);pn(this,Wn);pn(this,Zn);pn(this,Wr);pn(this,Zr);pn(this,Xn,null);pn(this,Xr,null);ar(this,Oa,this.attachShadow({mode:"open",delegatesFocus:!0})),ar(this,Wn,document.createElement("div")),ge(this,Wn).setAttribute("part","mount"),ge(this,Oa).appendChild(ge(this,Wn)),ar(this,Zn,document.createElement("div")),ge(this,Zn).id="portalRoot",ge(this,Oa).appendChild(ge(this,Zn)),ar(this,Wr,document.createElement("div")),ge(this,Wr).id="overlayContainer",Object.assign(ge(this,Wr).style,{position:"fixed",inset:"0",zIndex:"2147483645",pointerEvents:"none"}),ge(this,Oa).appendChild(ge(this,Wr)),ar(this,Zr,Gv()),this.applyBaseStyles()}connectedCallback(){this.style.setProperty("font-family","inherit")}disconnectedCallback(){ge(this,Xn)?.unmount(),ar(this,Xn,null)}getMountNode(){return ge(this,Wn)}getController(){return ge(this,Zr)}getPortalRoot(){return ge(this,Zn)}getOverlayContainer(){return ge(this,Wr)}getShadowRoot(){return ge(this,Oa)}open(){ge(this,Zr).setOpen(!0)}close(){ge(this,Zr).setOpen(!1)}toggle(){ge(this,Zr).toggle()}setOverrideFetcher(a){ge(this,Xr)&&(ar(this,Xr,{...ge(this,Xr),fetcher:a}),this.render())}mountReactApp(a){ar(this,Xr,a),this.render()}render(){!this.isConnected||!ge(this,Xr)||(ge(this,Xn)||ar(this,Xn,(0,p1.createRoot)(ge(this,Wn))),ge(this,Xn).render((0,ly.jsx)(Wv,{shadowRoot:ge(this,Oa),portalRoot:ge(this,Zn),overlayContainer:ge(this,Wr),children:(0,ly.jsx)(sy,{...ge(this,Xr),controller:ge(this,Zr),canvasHost:this})})))}applyBaseStyles(){if(ge(this,Oa).adoptedStyleSheets!==void 0){let a=new CSSStyleSheet;a.replaceSync(f1),ge(this,Oa).adoptedStyleSheets=[a]}else{let a=document.createElement("style");a.textContent=f1,ge(this,Oa).appendChild(a)}}};Oa=new WeakMap,Wn=new WeakMap,Zn=new WeakMap,Wr=new WeakMap,Zr=new WeakMap,Xn=new WeakMap,Xr=new WeakMap;var uy=()=>{typeof window>"u"||customElements.get(d1)||customElements.define(d1,Gf)};var Wf=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 x=typeof t.antiFlicker=="object"?t.antiFlicker:{};e=MI(x)}let a=null,r=null,n=null,{runtime:o}=t;async function i(x){!o?.actions||x.length===0||(n?.isApplied()&&await n.revertAll(),n=await o.actions.applyBatch(x))}async function s(){n?.isApplied()&&(await n.revertAll(),n=null)}if(t.fetcher)try{r=t.fetcher,console.log("[SmartCanvas] Fetching initial config...");let x=await t.fetcher();a=x,console.log("[SmartCanvas] Config fetched:",`tiles=${x.tiles?.length??0},`,`actions=${x.actions?.length??0},`,`theme=${x.theme?.mode??"default"}`),x.actions?.length&&console.log("[SmartCanvas] Actions to apply:",x.actions.map((f,g)=>`[${g}] ${f.kind}${f.anchorId?` anchor="${typeof f.anchorId=="string"?f.anchorId:f.anchorId.selector}"`:""}${f.label?` "${f.label}"`:""}`).join(", ")),x.actions&&x.actions.length>0&&o?.actions&&(await i(x.actions),console.log("[SmartCanvas] Initial actions applied successfully")),x.tiles&&o?.accumulator&&xu(x.tiles,o.accumulator,x.actions)}catch(x){console.error("[SmartCanvas] Error fetching/applying initial config:",x)}e&&e();let l=PI();uy();let u=document.createElement("smart-canvas");if(VI(u.getOverlayContainer()),t.tokens)for(let[x,f]of Object.entries(t.tokens))u.style.setProperty(x,f);let c=()=>{let x=t.target??document.body;x&&x.appendChild(u)};document.body?c():document.addEventListener("DOMContentLoaded",c,{once:!0}),l&&(console.log(`[SmartCanvas] Loading editor SDK for ${l} mode`),HI(t.editorUrl).catch(console.error));let d=t.integrations?.experiments,h=t.integrations?.telemetry,m=t.fetcher??Vo({configUri:t.configUri,experiments:d,featureKey:t.configUriFeatureKey,credentials:t.fetchCredentials});r||(r=m);let S={fetcher:m,pollIntervalMs:t.pollIntervalMs,experiments:d,telemetry:h,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 b={el:u,open:()=>u.open(),close:()=>u.close(),destroy:()=>{s(),u.remove()},setTokens:x=>{for(let[f,g]of Object.entries(x))u.style.setProperty(f,g)},getConfig:async()=>{if(r)try{let x=await r();return a=x,x}catch(x){console.error("[SmartCanvas] Error fetching config:",x)}return a??{tiles:[],actions:[],fetchedAt:""}},setEnabled:async x=>{x?a&&await i(a.actions):await s()},setOverrideFetcher:x=>{r=x,u.setOverrideFetcher(x),o?.accumulator&&x().then(f=>{f?.tiles&&xu(f.tiles,o.accumulator,f.actions)}).catch(()=>{})},registerTelemetryProperties:x=>{h?.register?.(x)},getSessionId:()=>h?.getSessionId?.(),startSessionRecording:()=>{h?.startSessionRecording?.()},track:(x,f)=>h?.track?(h.track(x,f),!0):!1,runtime:o};if(typeof window<"u"){let x=window.SynOS;x&&(x.handle=b)}return b};typeof window<"u"&&(window.SmartCanvas={async create(t){return Wf(t)}});var Kn=K(We(),1);var Yn=K(Me(),1);function gO({tiles:t,intervalMs:e=7e3,telemetry:a}){let[r,n]=(0,Kn.useState)(0),o=(0,Kn.useMemo)(()=>[...t].sort((i,s)=>(i.priority??0)-(s.priority??0)),[t]);return(0,Kn.useEffect)(()=>{a?.trackCanvasOpened("wheel")},[a]),(0,Kn.useEffect)(()=>{if(o.length<=1)return;let i=setInterval(()=>{n(s=>(s+1)%o.length)},e);return()=>clearInterval(i)},[o,e]),(0,Kn.useEffect)(()=>{let i=o[r];i&&a?.trackRectangleViewed(i.id,"wheel")},[r,o,a]),o.length?(0,Yn.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,Yn.jsx)("div",{style:{display:"flex",transition:"transform 700ms ease-out",transform:`translateX(-${r*100}%)`,width:`${o.length*100}%`},children:o.map(i=>(0,Yn.jsx)("div",{style:{width:"100%",flexShrink:0,padding:"0 1rem"},children:(0,Yn.jsx)(vs,{config:i,surface:"wheel",telemetry:a})},i.id))}),(0,Yn.jsx)("div",{style:{marginTop:"1rem",display:"flex",justifyContent:"center",gap:"0.5rem"},children:o.map((i,s)=>(0,Yn.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 xs(t){let e=t.split(".");return{major:parseInt(e[0]||"0",10),minor:parseInt(e[1]||"0",10)}}function vO(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=xs(n),i=xs(jr);return o.major>i.major&&e.push(`Config schema v${n} is newer than SDK v${jr}. 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${jr}. Migrating config to current version.`),{valid:!0,warnings:e,errors:a,migratedConfig:yO(r,n)}):{valid:!0,warnings:e,errors:a}}function yO(t,e){let a={...t};return xs(e).major===1&&(a=xO(a)),a.schemaVersion=jr,a}function xO(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 bO(t){if(!t||typeof t!="object")return!1;let e=t,a=e.schemaVersion||"1.0",r=xs(a),n=xs(jr);return r.major<n.major||!e.schemaVersion}var m1={fetch:globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,SubtleCrypto:globalThis.crypto?globalThis.crypto.subtle:void 0,EventSource:globalThis.EventSource};function g1(){return m1}function cy(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 ku(t,e,a){return a===2?cy(cy(t+e)+"")%1e4/1e4:a===1?cy(e+t)%1e3/1e3:null}function SO(t){return t<=0?[]:new Array(t).fill(1/t)}function Zf(t,e){return t>=e[0]&&t<e[1]}function v1(t,e){let a=ku("__"+e[0],t,1);return a===null?!1:a>=e[1]&&a<e[2]}function y1(t,e){for(let a=0;a<e.length;a++)if(Zf(t,e[a]))return a;return-1}function fy(t){try{let e=t.replace(/([^\\])\//g,"$1\\/");return new RegExp(e)}catch(e){console.error(e);return}}function Xf(t,e){if(!e.length)return!1;let a=!1,r=!1;for(let n=0;n<e.length;n++){let o=wO(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 CO(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 _O(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=>!CO(n[0],n[1],n[2]))}catch{return!1}}function wO(t,e,a){try{let r=new URL(t,"https://_");if(e==="regex"){let n=fy(a);return n?n.test(r.href)||n.test(r.href.substring(r.origin.length)):!1}else if(e==="simple")return _O(r,a);return!1}catch{return!1}}function x1(t,e,a){e=e===void 0?1:e,e<0?e=0:e>1&&(e=1);let r=SO(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 b1(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 S1(t){try{return t()}catch(e){return console.error(e),!1}}var dy=t=>Uint8Array.from(atob(t),e=>e.charCodeAt(0));async function Wo(t,e,a){if(e=e||"",a=a||globalThis.crypto&&globalThis.crypto.subtle||m1.SubtleCrypto,!a)throw new Error("No SubtleCrypto implementation found");try{let r=await a.importKey("raw",dy(e),{name:"AES-CBC",length:128},!0,["encrypt","decrypt"]),[n,o]=t.split("."),i=await a.decrypt({name:"AES-CBC",iv:dy(n)},r,dy(o));return new TextDecoder().decode(i)}catch{throw new Error("Failed to decrypt")}}function Eu(t){return typeof t=="string"?t:JSON.stringify(t)}function va(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 C1(){let t;try{t="1.6.4"}catch{t=""}return t}function _1(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 h1(t){return typeof t=="object"&&t!==null}function Yf(t){return t.urlPatterns&&t.variations.some(e=>h1(e)&&"urlRedirect"in e)?"redirect":t.variations.some(e=>h1(e)&&(e.domMutations||"js"in e||"css"in e))?"visual":"unknown"}async function Kf(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 Rt={staleTTL:1e3*60,maxAge:1e3*60*60*4,cacheKey:"gbFeaturesCache",backgroundSync:!0,maxEntries:10,disableIdleStreams:!1,idleStreamInterval:2e4,disableCache:!1},fr=g1(),bs={fetchFeaturesCall:({host:t,clientKey:e,headers:a})=>fr.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 fr.fetch(`${t}/api/eval/${e}`,n)},eventSourceCall:({host:t,clientKey:e,headers:a})=>a?new fr.EventSource(`${t}/sub/${e}`,{headers:a}):new fr.EventSource(`${t}/sub/${e}`),startIdleListener:()=>{let t;if(!(typeof window<"u"&&typeof document<"u"))return;let a=()=>{document.visibilityState==="visible"?(window.clearTimeout(t),AO()):document.visibilityState==="hidden"&&(t=window.setTimeout(IO,Rt.idleStreamInterval))};return document.addEventListener("visibilitychange",a),()=>document.removeEventListener("visibilitychange",a)},stopIdleListener:()=>{}};try{globalThis.localStorage&&(fr.localStorage=globalThis.localStorage)}catch{}var Ss=new Map,w1=!1,Yr=new Map,Qf=new Map,Cs=new Map,_s=new Set;function I1(t){Object.assign(Rt,t),Rt.backgroundSync||yy()}async function A1({instance:t,timeout:e,skipCache:a,allowStale:r,backgroundSync:n}){return n||(Rt.backgroundSync=!1),kO({instance:t,allowStale:r,timeout:e,skipCache:a})}function LO(t){let e=Tu(t),a=Ss.get(e)||new Set;a.add(t),Ss.set(e,a)}function k1(t){Ss.forEach(e=>e.delete(t))}function IO(){Cs.forEach(t=>{t&&(t.state="idle",gy(t))})}function AO(){Cs.forEach(t=>{t&&t.state==="idle"&&vy(t)})}async function L1(){try{if(!fr.localStorage)return;await fr.localStorage.setItem(Rt.cacheKey,JSON.stringify(Array.from(Yr.entries())))}catch{}}async function kO({instance:t,allowStale:e,timeout:a,skipCache:r}){let n=Tu(t),o=hy(t),i=new Date,s=new Date(i.getTime()-Rt.maxAge+Rt.staleTTL);await EO();let l=!Rt.disableCache&&!r?Yr.get(o):void 0;return l&&(e||l.staleAt>i)&&l.staleAt>s?(l.sse&&_s.add(n),l.staleAt<i?py(t):my(t),{data:l.data,success:!0,source:"cache"}):await Kf(py(t),a)||{data:null,success:!1,source:"timeout",error:new Error("Timeout")}}function Tu(t){let[e,a]=t.getApiInfo();return`${e}||${a}`}function hy(t){let e=Tu(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 EO(){if(!w1){w1=!0;try{if(fr.localStorage){let t=await fr.localStorage.getItem(Rt.cacheKey);if(!Rt.disableCache&&t){let e=JSON.parse(t);e&&Array.isArray(e)&&e.forEach(([a,r])=>{Yr.set(a,{...r,staleAt:new Date(r.staleAt)})}),E1()}}}catch{}if(!Rt.disableIdleStreams){let t=bs.startIdleListener();t&&(bs.stopIdleListener=t)}}}function E1(){let t=Array.from(Yr.entries()).map(([a,r])=>({key:a,staleAt:r.staleAt.getTime()})).sort((a,r)=>a.staleAt-r.staleAt),e=Math.min(Math.max(0,Yr.size-Rt.maxEntries),Yr.size);for(let a=0;a<e;a++)Yr.delete(t[a].key)}function T1(t,e,a){let r=a.dateUpdated||"",n=new Date(Date.now()+Rt.staleTTL),o=Rt.disableCache?void 0:Yr.get(e);if(o&&r&&o.version===r){o.staleAt=n,L1();return}Rt.disableCache||(Yr.set(e,{data:a,version:r,staleAt:n,sse:_s.has(t)}),E1()),L1();let i=Ss.get(t);i&&i.forEach(s=>TO(s,a))}async function TO(t,e){await t.setPayload(e||t.getPayload())}async function py(t){let{apiHost:e,apiRequestHeaders:a}=t.getApiHosts(),r=t.getClientKey(),n="isRemoteEval"in t&&t.isRemoteEval(),o=Tu(t),i=hy(t),s=Qf.get(i);return s||(s=(n?bs.fetchRemoteEvalCall({host:e,clientKey:r,payload:{attributes:t.getAttributes(),forcedVariations:t.getForcedVariations(),forcedFeatures:Array.from(t.getForcedFeatures().entries()),url:t.getUrl()},headers:a}):bs.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"&&_s.add(o),u.json()}).then(u=>(T1(o,i,u),my(t),Qf.delete(i),{data:u,success:!0,source:"network"})).catch(u=>(Qf.delete(i),{data:null,source:"error",success:!1,error:u})),Qf.set(i,s)),s}function my(t,e=!1){let a=Tu(t),r=hy(t),{streamingHost:n,streamingHostRequestHeaders:o}=t.getApiHosts(),i=t.getClientKey();if(e&&_s.add(a),Rt.backgroundSync&&_s.has(a)&&fr.EventSource){if(Cs.has(a))return;let s={src:null,host:n,clientKey:i,headers:o,cb:l=>{try{if(l.type==="features-updated"){let u=Ss.get(a);u&&u.forEach(c=>{py(c)})}else if(l.type==="features"){let u=JSON.parse(l.data);T1(a,r,u)}s.errors=0}catch{R1(s)}},errors:0,state:"active"};Cs.set(a,s),vy(s)}}function R1(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);gy(t),setTimeout(()=>{["idle","active"].includes(t.state)||vy(t)},Math.min(e,3e5))}}function gy(t){t.src&&(t.src.onopen=null,t.src.onerror=null,t.src.close(),t.src=null,t.state==="active"&&(t.state="disabled"))}function vy(t){t.src=bs.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=()=>R1(t),t.src.onopen=()=>{t.errors=0}}function RO(t,e){gy(t),Cs.delete(e)}function yy(){_s.clear(),Cs.forEach(RO),Ss.clear(),bs.stopIdleListener()}function Jf(t,e){if(e.streaming){if(!t.getClientKey())throw new Error("Must specify clientKey to enable streaming");e.payload&&my(t,!0),LO(t)}}var MO=/^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/,Sy={revert:function(){}},rp=new Map,Cy=new Set;function DO(t){return t==="html"?{childList:!0,subtree:!0,attributes:!0,characterData:!0}:{childList:!1,subtree:!1,attributes:!0,attributeFilter:[t]}}function np(t){var e=rp.get(t);return e||(e={element:t,attributes:{}},rp.set(t,e)),e}function op(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,DO(e)),i}function ip(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,M1()):t!==a&&(e.isDirty=!0,M1())}function OO(t){var e=t.originalValue;t.mutations.forEach(function(a){return e=a.mutate(e)}),ip(ZO(e),t)}function BO(t){var e=new Set(t.originalValue.split(/\s+/).filter(Boolean));t.mutations.forEach(function(a){return a.mutate(e)}),ip(Array.from(e).filter(Boolean).join(" "),t)}function FO(t){var e=t.originalValue;t.mutations.forEach(function(a){return e=a.mutate(e)}),ip(e,t)}function NO(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 PO(t){var e=t.originalValue;t.mutations.forEach(function(a){var r=a.mutate(),n=NO(r);e=n||e}),ip(e,t)}var HO=function(e){return e.innerHTML},UO=function(e,a){return e.innerHTML=a};function O1(t){var e=np(t);return e.html||(e.html=op(t,"html",HO,UO,OO)),e.html}var qO=function(e){return{parentNode:e.parentElement,insertBeforeNode:e.nextElementSibling}},zO=function(e,a){a.insertBeforeNode&&!a.parentNode.contains(a.insertBeforeNode)||a.parentNode.insertBefore(e,a.insertBeforeNode)};function B1(t){var e=np(t);return e.position||(e.position=op(t,"position",qO,zO,PO)),e.position}var VO=function(e,a){return a?e.className=a:e.removeAttribute("class")},$O=function(e){return e.className};function F1(t){var e=np(t);return e.classes||(e.classes=op(t,"class",$O,VO,BO)),e.classes}var jO=function(e){return function(a){var r;return(r=a.getAttribute(e))!=null?r:null}},GO=function(e){return function(a,r){return r!==null?a.setAttribute(e,r):a.removeAttribute(e)}};function N1(t,e){var a=np(t);return a.attributes[e]||(a.attributes[e]=op(t,e,jO(e),GO(e),FO)),a.attributes[e]}function WO(t,e){var a=rp.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 ep;function ZO(t){return ep||(ep=document.createElement("div")),ep.innerHTML=t,ep.innerHTML}function tp(t,e,a){if(a.isDirty){a.isDirty=!1;var r=a.virtualValue;a.mutations.length||WO(t,e),a.setValue(t,r)}}function XO(t,e){t.html&&tp(e,"html",t.html),t.classes&&tp(e,"class",t.classes),t.position&&tp(e,"position",t.position),Object.keys(t.attributes).forEach(function(a){tp(e,a,t.attributes[a])})}function M1(){rp.forEach(XO)}function YO(t,e){var a=null;t.kind==="html"?a=O1(e):t.kind==="class"?a=F1(e):t.kind==="attribute"?a=N1(e,t.attribute):t.kind==="position"&&(a=B1(e)),a&&(a.mutations.push(t),a.mutationRunner(a))}function KO(t,e){var a=null;if(t.kind==="html"?a=O1(e):t.kind==="class"?a=F1(e):t.kind==="attribute"?a=N1(e,t.attribute):t.kind==="position"&&(a=B1(e)),!!a){var r=a.mutations.indexOf(t);r!==-1&&a.mutations.splice(r,1),a.mutationRunner(a)}}function P1(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),YO(t,r))})}}function QO(t){t.elements.forEach(function(e){return KO(t,e)}),t.elements.clear(),Cy.delete(t)}function D1(){Cy.forEach(P1)}var xy;function JO(){typeof document>"u"||(xy||(xy=new MutationObserver(function(){D1()})),D1(),xy.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}JO();function sp(t){return typeof document>"u"?Sy:(Cy.add(t),P1(t),{revert:function(){QO(t)}})}function by(t,e){return sp({kind:"html",elements:new Set,mutate:e,selector:t})}function H1(t,e){return sp({kind:"position",elements:new Set,mutate:e,selector:t})}function Ru(t,e){return sp({kind:"class",elements:new Set,mutate:e,selector:t})}function ap(t,e,a){return MO.test(e)?e==="class"||e==="className"?Ru(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)})}):sp({kind:"attribute",attribute:e,elements:new Set,mutate:a,selector:t}):Sy}function eB(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 by(e,function(s){return s+(r??"")});if(a==="set")return by(e,function(){return r??""})}else if(n==="class"){if(a==="append")return Ru(e,function(s){r&&s.add(r)});if(a==="remove")return Ru(e,function(s){r&&s.delete(r)});if(a==="set")return Ru(e,function(s){s.clear(),r&&s.add(r)})}else if(n==="position"){if(a==="set"&&o)return H1(e,function(){return{insertBeforeSelector:i,parentSelector:o}})}else{if(a==="append")return ap(e,n,function(s){return s!==null?s+(r??""):r??""});if(a==="set")return ap(e,n,function(){return r??""});if(a==="remove")return ap(e,n,function(){return null})}return Sy}var tB={html:by,classes:Ru,attribute:ap,position:H1,declarative:eB},U1=tB;var _y={};function Qn(t,e,a){a=a||{};for(let[r,n]of Object.entries(e))switch(r){case"$or":if(!V1(t,n,a))return!1;break;case"$nor":if(V1(t,n,a))return!1;break;case"$and":if(!iB(t,n,a))return!1;break;case"$not":if(Qn(t,n,a))return!1;break;default:if(!Mu(n,aB(t,r),a))return!1}return!0}function aB(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 q1(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 Mu(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)||!$1(t))return JSON.stringify(e)===JSON.stringify(t);for(let n in t)if(!oB(n,e,t[n],a))return!1;return!0}function $1(t){let e=Object.keys(t);return e.length>0&&e.filter(a=>a[0]==="$").length===e.length}function rB(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 nB(t,e,a){if(!Array.isArray(t))return!1;let r=$1(e)?n=>Mu(e,n,a):n=>Qn(n,e,a);for(let n=0;n<t.length;n++)if(t[n]&&r(t[n]))return!0;return!1}function ws(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 z1(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(Mu(e[n],t[i],a,r)){o=!0;break}if(!o)return!1}return!0}function oB(t,e,a,r){switch(t){case"$veq":return va(e)===va(a);case"$vne":return va(e)!==va(a);case"$vgt":return va(e)>va(a);case"$vgte":return va(e)>=va(a);case"$vlt":return va(e)<va(a);case"$vlte":return va(e)<=va(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)?ws(e,a):!1;case"$ini":return Array.isArray(a)?ws(e,a,!0):!1;case"$inGroup":return ws(e,r[a]||[]);case"$notInGroup":return!ws(e,r[a]||[]);case"$nin":return Array.isArray(a)?!ws(e,a):!1;case"$nini":return Array.isArray(a)?!ws(e,a,!0):!1;case"$not":return!Mu(a,e,r);case"$size":return Array.isArray(e)?Mu(a,e.length,r):!1;case"$elemMatch":return nB(e,a,r);case"$all":return Array.isArray(a)?z1(e,a,r):!1;case"$alli":return Array.isArray(a)?z1(e,a,r,!0):!1;case"$regex":try{return q1(a).test(e)}catch{return!1}case"$regexi":try{return q1(a,!0).test(e)}catch{return!1}case"$type":return rB(e)===a;default:return console.error("Unknown operator: "+t),!1}}function V1(t,e,a){if(!e.length)return!0;for(let r=0;r<e.length;r++)if(Qn(t,e[r],a))return!0;return!1}function iB(t,e,a){for(let r=0;r<e.length;r++)if(!Qn(t,e[r],a))return!1;return!0}var sB="Feature Evaluated",lB="Experiment Viewed";function uB(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 cB(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 Ls(t){try{await t()}catch{}}function j1(t,e,a){if(t.user.trackedExperiments){let n=cp(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(Ls(()=>n(e,a,t.user)))}if(t.user.trackingCallback){let n=t.user.trackingCallback;r.push(Ls(()=>n(e,a)))}if(t.global.eventLogger){let n=t.global.eventLogger;r.push(Ls(()=>n(lB,{experimentId:e.key,variationId:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue},t.user)))}return r}function dB(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;Ls(()=>r(e,a,t.user))}if(t.user.onFeatureUsage){let r=t.user.onFeatureUsage;Ls(()=>r(e,a))}if(t.global.eventLogger){let r=t.global.eventLogger;Ls(()=>r(sB,{feature:e,source:a.source,value:a.value,ruleId:a.source==="defaultValue"?"$default":a.ruleId||"",variationId:a.experimentResult?a.experimentResult.key:""},t.user))}}function lp(t,e){if(e.stack.evaluatedFeatures.has(t))return Jn(e,t,null,"cyclicPrerequisite");e.stack.evaluatedFeatures.add(t),e.stack.id=t;let a=uB(e);if(a.has(t))return Jn(e,t,a.get(t),"override");if(!e.global.features||!e.global.features[t])return Jn(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=lp(l.id,e);if(u.source==="cyclicPrerequisite")return Jn(e,t,null,"cyclicPrerequisite");let c={value:u.value};if(!Qn(c,l.condition||{})){if(l.gate)return Jn(e,t,null,"prerequisite");continue e}}if(o.filters&&Z1(o.filters,e))continue;if("force"in o){if(o.condition&&!W1(o.condition,e)||!fB(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=>{!j1(e,l.experiment,l.result).length&&e.global.saveDeferredTrack&&e.global.saveDeferredTrack({experiment:l.experiment,result:l.result})}),Jn(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}=up(i,t,e);if(e.global.onExperimentEval&&e.global.onExperimentEval(i,s),s.inExperiment&&!s.passthrough)return Jn(e,t,s.value,"experiment",o.id,i,s)}}return Jn(e,t,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function up(t,e,a){let r=t.key,n=t.variations.length;if(n<2)return{result:$e(a,t,-1,!1,e)};if(a.global.enabled===!1||a.user.enabled===!1)return{result:$e(a,t,-1,!1,e)};if(t=pB(t,a),t.urlPatterns&&!Xf(a.user.url||"",t.urlPatterns))return{result:$e(a,t,-1,!1,e)};let o=b1(r,a.user.url||"",n);if(o!==null)return{result:$e(a,t,o,!1,e)};let i=cB(a);if(r in i){let x=i[r];return{result:$e(a,t,x,!1,e)}}if(t.status==="draft"||t.active===!1)return{result:$e(a,t,-1,!1,e)};let{hashAttribute:s,hashValue:l}=Zo(a,t.hashAttribute,a.user.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0);if(!l)return{result:$e(a,t,-1,!1,e)};let u=-1,c=!1,d=!1;if(a.user.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing){let{variation:x,versionIsBlocked:f}=gB({ctx:a,expKey:t.key,expBucketVersion:t.bucketVersion,expHashAttribute:t.hashAttribute,expFallbackAttribute:t.fallbackAttribute,expMinBucketVersion:t.minBucketVersion,expMeta:t.meta});c=x>=0,u=x,d=!!f}if(!c){if(t.filters){if(Z1(t.filters,a))return{result:$e(a,t,-1,!1,e)}}else if(t.namespace&&!v1(l,t.namespace))return{result:$e(a,t,-1,!1,e)};if(t.include&&!S1(t.include))return{result:$e(a,t,-1,!1,e)};if(t.condition&&!W1(t.condition,a))return{result:$e(a,t,-1,!1,e)};if(t.parentConditions){let x=new Set(a.stack.evaluatedFeatures);for(let f of t.parentConditions){a.stack.evaluatedFeatures=new Set(x);let g=lp(f.id,a);if(g.source==="cyclicPrerequisite")return{result:$e(a,t,-1,!1,e)};let v={value:g.value};if(!Qn(v,f.condition||{}))return{result:$e(a,t,-1,!1,e)}}}if(t.groups&&!mB(t.groups,a))return{result:$e(a,t,-1,!1,e)}}if(t.url&&!hB(t.url,a))return{result:$e(a,t,-1,!1,e)};let h=ku(t.seed||r,l,t.hashVersion||1);if(h===null)return{result:$e(a,t,-1,!1,e)};if(!c){let x=t.ranges||x1(n,t.coverage===void 0?1:t.coverage,t.weights);u=y1(h,x)}if(d)return{result:$e(a,t,-1,!1,e,void 0,!0)};if(u<0)return{result:$e(a,t,-1,!1,e)};if("force"in t)return{result:$e(a,t,t.force===void 0?-1:t.force,!1,e)};if(a.global.qaMode||a.user.qaMode)return{result:$e(a,t,-1,!1,e)};if(t.status==="stopped")return{result:$e(a,t,-1,!1,e)};let m=$e(a,t,u,!0,e,h,c);if(a.user.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing){let{changed:x,key:f,doc:g}=yB(a,s,Eu(l),{[wy(t.key,t.bucketVersion)]:m.key});x&&(a.user.stickyBucketAssignmentDocs=a.user.stickyBucketAssignmentDocs||{},a.user.stickyBucketAssignmentDocs[f]=g,a.user.saveStickyBucketAssignmentDoc(g))}let S=j1(a,t,m);S.length===0&&a.global.saveDeferredTrack&&a.global.saveDeferredTrack({experiment:t,result:m});let b=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:m,trackingCall:b}}function Jn(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"&&dB(t,e,s),s}function G1(t){return{...t.user.attributes,...t.user.attributeOverrides}}function W1(t,e){return Qn(G1(e),t,e.global.savedGroups||{})}function Z1(t,e){return t.some(a=>{let{hashValue:r}=Zo(e,a.attribute);if(!r)return!0;let n=ku(a.seed,r,a.hashVersion||2);return n===null?!0:!a.ranges.some(o=>Zf(n,o))})}function fB(t,e,a,r,n,o,i){if(!n&&o===void 0)return!0;if(!n&&o===0)return!1;let{hashValue:s}=Zo(t,a,r);if(!s)return!1;let l=ku(e,s,i||1);return l===null?!1:n?Zf(l,n):o!==void 0?l<=o:!0}function $e(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}=Zo(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 pB(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=fy(t.url))),t}function Zo(t,e,a){let r=e||"id",n="",o=G1(t);return o[r]&&(n=o[r]),!n&&a&&(o[a]&&(n=o[a]),n&&(r=a)),{hashAttribute:r,hashValue:n}}function hB(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 mB(t,e){let a=e.global.groups||{};for(let r=0;r<t.length;r++)if(a[t[r]])return!0;return!1}function gB({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=wy(e,a),l=vB(t,r,n);if(o>0)for(let d=0;d<o;d++){let h=wy(e,d);if(l[h]!==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 wy(t,e){return e=e||0,`${t}__${e}`}function Ly(t,e){return`${t}||${e}`}function vB(t,e,a){if(!t.user.stickyBucketAssignmentDocs)return{};let{hashAttribute:r,hashValue:n}=Zo(t,e),o=Ly(r,Eu(n)),{hashAttribute:i,hashValue:s}=Zo(t,a),l=s?Ly(i,Eu(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 yB(t,e,a,r){let n=Ly(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 xB(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 X1(t,e,a){let r=Iy(t,a);return e.getAllAssignments(r)}function Iy(t,e){let a={};return xB(t,e).forEach(n=>{let{hashValue:o}=Zo(t,n);a[n]=Eu(o)}),a}async function Y1(t,e,a){if(t={...t},t.encryptedFeatures){try{t.features=JSON.parse(await Wo(t.encryptedFeatures,e,a))}catch(r){console.error(r)}delete t.encryptedFeatures}if(t.encryptedExperiments){try{t.experiments=JSON.parse(await Wo(t.encryptedExperiments,e,a))}catch(r){console.error(r)}delete t.encryptedExperiments}if(t.encryptedSavedGroups){try{t.savedGroups=JSON.parse(await Wo(t.encryptedSavedGroups,e,a))}catch(r){console.error(r)}delete t.encryptedSavedGroups}return t}function K1(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 cp(t,e){return e.hashAttribute+e.hashValue+t.key+e.variationId}var Is=typeof window<"u"&&typeof document<"u",bB=C1(),Du=class{constructor(e){if(e=e||{},this.version=bB,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),Is&&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 Y1(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,Jf(this,e),this}async init(e){if(this._initialized=!0,e=e||{},e.cacheSettings&&I1(e.cacheSettings),e.payload)return await this.setPayload(e.payload),Jf(this,e),{success:!0,source:"init"};{let{data:a,...r}=await this._refresh({...e,allowStale:!0});return Jf(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 K1(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 A1({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 Wo(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 Wo(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,k1(this),e.destroyAllStreams&&yy(),this.logs=[],Is&&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}=up(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=$e(this._getEvalContext(),e,-1,!1,""):({result:o,trackingCall:i}=up(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=Yf(e);if(l==="redirect"&&o.value.urlRedirect&&e.urlPatterns){let u=e.persistQueryString?_1(this._getContextUrl(),o.value.urlRedirect):o.value.urlRedirect;if(Xf(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(Is)Promise.all([...i?[Kf(i,this._options.maxNavigateDelay??1e3)]:[],new Promise(h=>window.setTimeout(h,this._options.navigateDelay??d))]).then(()=>{try{c(u)}catch(h){console.error(h)}});else try{c(u)}catch(h){console.error(h)}}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&&Yf(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 lp(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=>[cp(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(cp(e.experiment,e.result),e)}_getContextUrl(){return this._options.url||(Is?window.location.href:"")}_isAutoExperimentBlockedByContext(e){let a=Yf(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}:Is?{navigate:e=>{window.location.replace(e)},delay:100}:{navigate:null,delay:0}}_applyDOMChanges(e){if(!Is)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(U1.declarative(r).revert)}),()=>{a.forEach(r=>r())}}async refreshStickyBuckets(e){if(this._options.stickyBucketService){let a=this._getEvalContext(),r=await X1(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=Iy(r,a);return e.getAllAssignmentsSync(n)}inDevMode(){return!!this._options.enableDevMode}};var SB="https://experiment.syntrologie.com",Ay=class{constructor(e={}){$(this,"gb");$(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 Du({...e,apiHost:e.apiHost??SB,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(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 dp(t={}){return new Ay(t)}var Q1="syntro_session_metrics",Ou=class{constructor(e={}){$(this,"metrics",new Map);$(this,"experiments");$(this,"attributePrefix");$(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(Q1);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(Q1,JSON.stringify(e))}catch(e){console.warn("[SessionMetricTracker] Failed to save to sessionStorage:",e)}}};function fp(t={}){return new Ou(t)}var p={};xS(p,{BRAND:()=>WB,DIRTY:()=>Xo,EMPTY_PATH:()=>LB,INVALID:()=>J,NEVER:()=>RF,OK:()=>Mt,ParseStatus:()=>wt,Schema:()=>ue,ZodAny:()=>ao,ZodArray:()=>en,ZodBigInt:()=>Ko,ZodBoolean:()=>Qo,ZodBranded:()=>Fu,ZodCatch:()=>ui,ZodDate:()=>Jo,ZodDefault:()=>li,ZodDiscriminatedUnion:()=>mp,ZodEffects:()=>Na,ZodEnum:()=>ii,ZodError:()=>Qt,ZodFirstPartyTypeKind:()=>ee,ZodFunction:()=>vp,ZodIntersection:()=>ri,ZodIssueCode:()=>O,ZodLazy:()=>ni,ZodLiteral:()=>oi,ZodMap:()=>Ms,ZodNaN:()=>Os,ZodNativeEnum:()=>si,ZodNever:()=>Ja,ZodNull:()=>ti,ZodNullable:()=>mr,ZodNumber:()=>Yo,ZodObject:()=>Jt,ZodOptional:()=>Ba,ZodParsedType:()=>V,ZodPipeline:()=>Nu,ZodPromise:()=>ro,ZodReadonly:()=>ci,ZodRecord:()=>gp,ZodSchema:()=>ue,ZodSet:()=>Ds,ZodString:()=>to,ZodSymbol:()=>Ts,ZodTransformer:()=>Na,ZodTuple:()=>hr,ZodType:()=>ue,ZodUndefined:()=>ei,ZodUnion:()=>ai,ZodUnknown:()=>Jr,ZodVoid:()=>Rs,addIssueToContext:()=>H,any:()=>aF,array:()=>iF,bigint:()=>KB,boolean:()=>uA,coerce:()=>TF,custom:()=>iA,date:()=>QB,datetimeRegex:()=>nA,defaultErrorMap:()=>Kr,discriminatedUnion:()=>cF,effect:()=>CF,enum:()=>xF,function:()=>gF,getErrorMap:()=>As,getParsedType:()=>pr,instanceof:()=>XB,intersection:()=>dF,isAborted:()=>pp,isAsync:()=>ks,isDirty:()=>hp,isValid:()=>eo,late:()=>ZB,lazy:()=>vF,literal:()=>yF,makeIssue:()=>Bu,map:()=>hF,nan:()=>YB,nativeEnum:()=>bF,never:()=>nF,null:()=>tF,nullable:()=>wF,number:()=>lA,object:()=>sF,objectUtil:()=>ky,oboolean:()=>EF,onumber:()=>kF,optional:()=>_F,ostring:()=>AF,pipeline:()=>IF,preprocess:()=>LF,promise:()=>SF,quotelessJson:()=>CB,record:()=>pF,set:()=>mF,setErrorMap:()=>wB,strictObject:()=>lF,string:()=>sA,symbol:()=>JB,transformer:()=>CF,tuple:()=>fF,undefined:()=>eF,union:()=>uF,unknown:()=>rF,util:()=>fe,void:()=>oF});var fe;(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})(fe||(fe={}));var ky;(function(t){t.mergeShapes=(e,a)=>({...e,...a})})(ky||(ky={}));var V=fe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),pr=t=>{switch(typeof t){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(t)?V.nan:V.number;case"boolean":return V.boolean;case"function":return V.function;case"bigint":return V.bigint;case"symbol":return V.symbol;case"object":return Array.isArray(t)?V.array:t===null?V.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?V.promise:typeof Map<"u"&&t instanceof Map?V.map:typeof Set<"u"&&t instanceof Set?V.set:typeof Date<"u"&&t instanceof Date?V.date:V.object;default:return V.unknown}};var O=fe.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"]),CB=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Qt=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,fe.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()}};Qt.create=t=>new Qt(t);var _B=(t,e)=>{let a;switch(t.code){case O.invalid_type:t.received===V.undefined?a="Required":a=`Expected ${t.expected}, received ${t.received}`;break;case O.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(t.expected,fe.jsonStringifyReplacer)}`;break;case O.unrecognized_keys:a=`Unrecognized key(s) in object: ${fe.joinValues(t.keys,", ")}`;break;case O.invalid_union:a="Invalid input";break;case O.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${fe.joinValues(t.options)}`;break;case O.invalid_enum_value:a=`Invalid enum value. Expected ${fe.joinValues(t.options)}, received '${t.received}'`;break;case O.invalid_arguments:a="Invalid function arguments";break;case O.invalid_return_type:a="Invalid function return type";break;case O.invalid_date:a="Invalid date";break;case O.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}"`:fe.assertNever(t.validation):t.validation!=="regex"?a=`Invalid ${t.validation}`:a="Invalid";break;case O.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 O.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 O.custom:a="Invalid input";break;case O.invalid_intersection_types:a="Intersection results could not be merged";break;case O.not_multiple_of:a=`Number must be a multiple of ${t.multipleOf}`;break;case O.not_finite:a="Number must be finite";break;default:a=e.defaultError,fe.assertNever(t)}return{message:a}},Kr=_B;var J1=Kr;function wB(t){J1=t}function As(){return J1}var Bu=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}},LB=[];function H(t,e){let a=As(),r=Bu({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,a,a===Kr?void 0:Kr].filter(n=>!!n)});t.common.issues.push(r)}var wt=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"}),Xo=t=>({status:"dirty",value:t}),Mt=t=>({status:"valid",value:t}),pp=t=>t.status==="aborted",hp=t=>t.status==="dirty",eo=t=>t.status==="valid",ks=t=>typeof Promise<"u"&&t instanceof Promise;var Z;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Z||(Z={}));var Fa=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}},eA=(t,e)=>{if(eo(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 Qt(t.common.issues);return this._error=a,this._error}}};function le(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 ue=class{get description(){return this._def.description}_getType(e){return pr(e.data)}_getOrReturnCtx(e,a){return a||{common:e.parent.common,data:e.data,parsedType:pr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new wt,ctx:{common:e.parent.common,data:e.data,parsedType:pr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let a=this._parse(e);if(ks(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:pr(e)},n=this._parseSync({data:e,path:r.path,parent:r});return eA(r,n)}"~validate"(e){let a={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pr(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:a});return eo(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=>eo(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:pr(e)},n=this._parse({data:e,path:r.path,parent:r}),o=await(ks(n)?n:Promise.resolve(n));return eA(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:O.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 Na({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 Ba.create(this,this._def)}nullable(){return mr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return en.create(this)}promise(){return ro.create(this,this._def)}or(e){return ai.create([this,e],this._def)}and(e){return ri.create(this,e,this._def)}transform(e){return new Na({...le(this._def),schema:this,typeName:ee.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let a=typeof e=="function"?e:()=>e;return new li({...le(this._def),innerType:this,defaultValue:a,typeName:ee.ZodDefault})}brand(){return new Fu({typeName:ee.ZodBranded,type:this,...le(this._def)})}catch(e){let a=typeof e=="function"?e:()=>e;return new ui({...le(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 Nu.create(this,e)}readonly(){return ci.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},IB=/^c[^\s-]{8,}$/i,AB=/^[0-9a-z]+$/,kB=/^[0-9A-HJKMNP-TV-Z]{26}$/i,EB=/^[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,TB=/^[a-z0-9_-]{21}$/i,RB=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,MB=/^[-+]?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)?)??$/,DB=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,OB="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ey,BB=/^(?:(?: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])$/,FB=/^(?:(?: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])$/,NB=/^(([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]))$/,PB=/^(([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])$/,HB=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,UB=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,aA="((\\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])))",qB=new RegExp(`^${aA}$`);function rA(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 zB(t){return new RegExp(`^${rA(t)}$`)}function nA(t){let e=`${aA}T${rA(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 VB(t,e){return!!((e==="v4"||!e)&&BB.test(t)||(e==="v6"||!e)&&NB.test(t))}function $B(t,e){if(!RB.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 jB(t,e){return!!((e==="v4"||!e)&&FB.test(t)||(e==="v6"||!e)&&PB.test(t))}var to=class t extends ue{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==V.string){let o=this._getOrReturnCtx(e);return H(o,{code:O.invalid_type,expected:V.string,received:o.parsedType}),J}let r=new wt,n;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(n=this._getOrReturnCtx(e,n),H(n,{code:O.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),H(n,{code:O.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?H(n,{code:O.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):s&&H(n,{code:O.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")DB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"email",code:O.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Ey||(Ey=new RegExp(OB,"u")),Ey.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"emoji",code:O.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")EB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"uuid",code:O.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")TB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"nanoid",code:O.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")IB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"cuid",code:O.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")AB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"cuid2",code:O.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")kB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"ulid",code:O.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),H(n,{validation:"url",code:O.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),H(n,{validation:"regex",code:O.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),H(n,{code:O.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),H(n,{code:O.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(n=this._getOrReturnCtx(e,n),H(n,{code:O.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?nA(o).test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{code:O.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?qB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{code:O.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?zB(o).test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{code:O.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?MB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"duration",code:O.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?VB(e.data,o.version)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"ip",code:O.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?$B(e.data,o.alg)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"jwt",code:O.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?jB(e.data,o.version)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"cidr",code:O.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?HB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"base64",code:O.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?UB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"base64url",code:O.invalid_string,message:o.message}),r.dirty()):fe.assertNever(o);return{status:r.value,value:e.data}}_regex(e,a,r){return this.refinement(n=>e.test(n),{validation:a,code:O.invalid_string,...Z.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Z.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,...Z.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,...Z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Z.errToObj(e)})}regex(e,a){return this._addCheck({kind:"regex",regex:e,...Z.errToObj(a)})}includes(e,a){return this._addCheck({kind:"includes",value:e,position:a?.position,...Z.errToObj(a?.message)})}startsWith(e,a){return this._addCheck({kind:"startsWith",value:e,...Z.errToObj(a)})}endsWith(e,a){return this._addCheck({kind:"endsWith",value:e,...Z.errToObj(a)})}min(e,a){return this._addCheck({kind:"min",value:e,...Z.errToObj(a)})}max(e,a){return this._addCheck({kind:"max",value:e,...Z.errToObj(a)})}length(e,a){return this._addCheck({kind:"length",value:e,...Z.errToObj(a)})}nonempty(e){return this.min(1,Z.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}};to.create=t=>new to({checks:[],typeName:ee.ZodString,coerce:t?.coerce??!1,...le(t)});function GB(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 Yo=class t extends ue{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)!==V.number){let o=this._getOrReturnCtx(e);return H(o,{code:O.invalid_type,expected:V.number,received:o.parsedType}),J}let r,n=new wt;for(let o of this._def.checks)o.kind==="int"?fe.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{code:O.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),H(r,{code:O.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),H(r,{code:O.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()):o.kind==="multipleOf"?GB(e.data,o.value)!==0&&(r=this._getOrReturnCtx(e,r),H(r,{code:O.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{code:O.not_finite,message:o.message}),n.dirty()):fe.assertNever(o);return{status:n.value,value:e.data}}gte(e,a){return this.setLimit("min",e,!0,Z.toString(a))}gt(e,a){return this.setLimit("min",e,!1,Z.toString(a))}lte(e,a){return this.setLimit("max",e,!0,Z.toString(a))}lt(e,a){return this.setLimit("max",e,!1,Z.toString(a))}setLimit(e,a,r,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:a,inclusive:r,message:Z.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Z.toString(e)})}multipleOf(e,a){return this._addCheck({kind:"multipleOf",value:e,message:Z.toString(a)})}finite(e){return this._addCheck({kind:"finite",message:Z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Z.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"&&fe.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)}};Yo.create=t=>new Yo({checks:[],typeName:ee.ZodNumber,coerce:t?.coerce||!1,...le(t)});var Ko=class t extends ue{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)!==V.bigint)return this._getInvalidInput(e);let r,n=new wt;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),H(r,{code:O.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),H(r,{code:O.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),H(r,{code:O.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()):fe.assertNever(o);return{status:n.value,value:e.data}}_getInvalidInput(e){let a=this._getOrReturnCtx(e);return H(a,{code:O.invalid_type,expected:V.bigint,received:a.parsedType}),J}gte(e,a){return this.setLimit("min",e,!0,Z.toString(a))}gt(e,a){return this.setLimit("min",e,!1,Z.toString(a))}lte(e,a){return this.setLimit("max",e,!0,Z.toString(a))}lt(e,a){return this.setLimit("max",e,!1,Z.toString(a))}setLimit(e,a,r,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:a,inclusive:r,message:Z.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:Z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Z.toString(e)})}multipleOf(e,a){return this._addCheck({kind:"multipleOf",value:e,message:Z.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}};Ko.create=t=>new Ko({checks:[],typeName:ee.ZodBigInt,coerce:t?.coerce??!1,...le(t)});var Qo=class extends ue{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==V.boolean){let r=this._getOrReturnCtx(e);return H(r,{code:O.invalid_type,expected:V.boolean,received:r.parsedType}),J}return Mt(e.data)}};Qo.create=t=>new Qo({typeName:ee.ZodBoolean,coerce:t?.coerce||!1,...le(t)});var Jo=class t extends ue{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==V.date){let o=this._getOrReturnCtx(e);return H(o,{code:O.invalid_type,expected:V.date,received:o.parsedType}),J}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return H(o,{code:O.invalid_date}),J}let r=new wt,n;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(n=this._getOrReturnCtx(e,n),H(n,{code:O.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),H(n,{code:O.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):fe.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:Z.toString(a)})}max(e,a){return this._addCheck({kind:"max",value:e.getTime(),message:Z.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}};Jo.create=t=>new Jo({checks:[],coerce:t?.coerce||!1,typeName:ee.ZodDate,...le(t)});var Ts=class extends ue{_parse(e){if(this._getType(e)!==V.symbol){let r=this._getOrReturnCtx(e);return H(r,{code:O.invalid_type,expected:V.symbol,received:r.parsedType}),J}return Mt(e.data)}};Ts.create=t=>new Ts({typeName:ee.ZodSymbol,...le(t)});var ei=class extends ue{_parse(e){if(this._getType(e)!==V.undefined){let r=this._getOrReturnCtx(e);return H(r,{code:O.invalid_type,expected:V.undefined,received:r.parsedType}),J}return Mt(e.data)}};ei.create=t=>new ei({typeName:ee.ZodUndefined,...le(t)});var ti=class extends ue{_parse(e){if(this._getType(e)!==V.null){let r=this._getOrReturnCtx(e);return H(r,{code:O.invalid_type,expected:V.null,received:r.parsedType}),J}return Mt(e.data)}};ti.create=t=>new ti({typeName:ee.ZodNull,...le(t)});var ao=class extends ue{constructor(){super(...arguments),this._any=!0}_parse(e){return Mt(e.data)}};ao.create=t=>new ao({typeName:ee.ZodAny,...le(t)});var Jr=class extends ue{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Mt(e.data)}};Jr.create=t=>new Jr({typeName:ee.ZodUnknown,...le(t)});var Ja=class extends ue{_parse(e){let a=this._getOrReturnCtx(e);return H(a,{code:O.invalid_type,expected:V.never,received:a.parsedType}),J}};Ja.create=t=>new Ja({typeName:ee.ZodNever,...le(t)});var Rs=class extends ue{_parse(e){if(this._getType(e)!==V.undefined){let r=this._getOrReturnCtx(e);return H(r,{code:O.invalid_type,expected:V.void,received:r.parsedType}),J}return Mt(e.data)}};Rs.create=t=>new Rs({typeName:ee.ZodVoid,...le(t)});var en=class t extends ue{_parse(e){let{ctx:a,status:r}=this._processInputParams(e),n=this._def;if(a.parsedType!==V.array)return H(a,{code:O.invalid_type,expected:V.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)&&(H(a,{code:i?O.too_big:O.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&&(H(a,{code:O.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&&(H(a,{code:O.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 Fa(a,i,a.path,s)))).then(i=>wt.mergeArray(r,i));let o=[...a.data].map((i,s)=>n.type._parseSync(new Fa(a,i,a.path,s)));return wt.mergeArray(r,o)}get element(){return this._def.type}min(e,a){return new t({...this._def,minLength:{value:e,message:Z.toString(a)}})}max(e,a){return new t({...this._def,maxLength:{value:e,message:Z.toString(a)}})}length(e,a){return new t({...this._def,exactLength:{value:e,message:Z.toString(a)}})}nonempty(e){return this.min(1,e)}};en.create=(t,e)=>new en({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ee.ZodArray,...le(e)});function Es(t){if(t instanceof Jt){let e={};for(let a in t.shape){let r=t.shape[a];e[a]=Ba.create(Es(r))}return new Jt({...t._def,shape:()=>e})}else return t instanceof en?new en({...t._def,type:Es(t.element)}):t instanceof Ba?Ba.create(Es(t.unwrap())):t instanceof mr?mr.create(Es(t.unwrap())):t instanceof hr?hr.create(t.items.map(e=>Es(e))):t}var Jt=class t extends ue{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=fe.objectKeys(e);return this._cached={shape:e,keys:a},this._cached}_parse(e){if(this._getType(e)!==V.object){let u=this._getOrReturnCtx(e);return H(u,{code:O.invalid_type,expected:V.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 Ja&&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 Fa(n,d,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof Ja){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&&(H(n,{code:O.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 Fa(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,h=await c.value;u.push({key:d,value:h,alwaysSet:c.alwaysSet})}return u}).then(u=>wt.mergeObjectSync(r,u)):wt.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return Z.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:Z.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 fe.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 fe.objectKeys(this.shape))e[r]||(a[r]=this.shape[r]);return new t({...this._def,shape:()=>a})}deepPartial(){return Es(this)}partial(e){let a={};for(let r of fe.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 fe.objectKeys(this.shape))if(e&&!e[r])a[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Ba;)o=o._def.innerType;a[r]=o}return new t({...this._def,shape:()=>a})}keyof(){return oA(fe.objectKeys(this.shape))}};Jt.create=(t,e)=>new Jt({shape:()=>t,unknownKeys:"strip",catchall:Ja.create(),typeName:ee.ZodObject,...le(e)});Jt.strictCreate=(t,e)=>new Jt({shape:()=>t,unknownKeys:"strict",catchall:Ja.create(),typeName:ee.ZodObject,...le(e)});Jt.lazycreate=(t,e)=>new Jt({shape:t,unknownKeys:"strip",catchall:Ja.create(),typeName:ee.ZodObject,...le(e)});var ai=class extends ue{_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 Qt(s.ctx.common.issues));return H(a,{code:O.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 Qt(l));return H(a,{code:O.invalid_union,unionErrors:s}),J}}get options(){return this._def.options}};ai.create=(t,e)=>new ai({options:t,typeName:ee.ZodUnion,...le(e)});var Qr=t=>t instanceof ni?Qr(t.schema):t instanceof Na?Qr(t.innerType()):t instanceof oi?[t.value]:t instanceof ii?t.options:t instanceof si?fe.objectValues(t.enum):t instanceof li?Qr(t._def.innerType):t instanceof ei?[void 0]:t instanceof ti?[null]:t instanceof Ba?[void 0,...Qr(t.unwrap())]:t instanceof mr?[null,...Qr(t.unwrap())]:t instanceof Fu||t instanceof ci?Qr(t.unwrap()):t instanceof ui?Qr(t._def.innerType):[],mp=class t extends ue{_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==V.object)return H(a,{code:O.invalid_type,expected:V.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}):(H(a,{code:O.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=Qr(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,...le(r)})}};function Ty(t,e){let a=pr(t),r=pr(e);if(t===e)return{valid:!0,data:t};if(a===V.object&&r===V.object){let n=fe.objectKeys(e),o=fe.objectKeys(t).filter(s=>n.indexOf(s)!==-1),i={...t,...e};for(let s of o){let l=Ty(t[s],e[s]);if(!l.valid)return{valid:!1};i[s]=l.data}return{valid:!0,data:i}}else if(a===V.array&&r===V.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=Ty(i,s);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return a===V.date&&r===V.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var ri=class extends ue{_parse(e){let{status:a,ctx:r}=this._processInputParams(e),n=(o,i)=>{if(pp(o)||pp(i))return J;let s=Ty(o.value,i.value);return s.valid?((hp(o)||hp(i))&&a.dirty(),{status:a.value,value:s.data}):(H(r,{code:O.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}))}};ri.create=(t,e,a)=>new ri({left:t,right:e,typeName:ee.ZodIntersection,...le(a)});var hr=class t extends ue{_parse(e){let{status:a,ctx:r}=this._processInputParams(e);if(r.parsedType!==V.array)return H(r,{code:O.invalid_type,expected:V.array,received:r.parsedType}),J;if(r.data.length<this._def.items.length)return H(r,{code:O.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&r.data.length>this._def.items.length&&(H(r,{code:O.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 Fa(r,i,r.path,s)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>wt.mergeArray(a,i)):wt.mergeArray(a,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};hr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new hr({items:t,typeName:ee.ZodTuple,rest:null,...le(e)})};var gp=class t extends ue{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!==V.object)return H(r,{code:O.invalid_type,expected:V.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 Fa(r,s,r.path,s)),value:i._parse(new Fa(r,r.data[s],r.path,s)),alwaysSet:s in r.data});return r.common.async?wt.mergeObjectAsync(a,n):wt.mergeObjectSync(a,n)}get element(){return this._def.valueType}static create(e,a,r){return a instanceof ue?new t({keyType:e,valueType:a,typeName:ee.ZodRecord,...le(r)}):new t({keyType:to.create(),valueType:e,typeName:ee.ZodRecord,...le(a)})}},Ms=class extends ue{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!==V.map)return H(r,{code:O.invalid_type,expected:V.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 Fa(r,s,r.path,[u,"key"])),value:o._parse(new Fa(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}}}};Ms.create=(t,e,a)=>new Ms({valueType:e,keyType:t,typeName:ee.ZodMap,...le(a)});var Ds=class t extends ue{_parse(e){let{status:a,ctx:r}=this._processInputParams(e);if(r.parsedType!==V.set)return H(r,{code:O.invalid_type,expected:V.set,received:r.parsedType}),J;let n=this._def;n.minSize!==null&&r.data.size<n.minSize.value&&(H(r,{code:O.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&&(H(r,{code:O.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 Fa(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:Z.toString(a)}})}max(e,a){return new t({...this._def,maxSize:{value:e,message:Z.toString(a)}})}size(e,a){return this.min(e,a).max(e,a)}nonempty(e){return this.min(1,e)}};Ds.create=(t,e)=>new Ds({valueType:t,minSize:null,maxSize:null,typeName:ee.ZodSet,...le(e)});var vp=class t extends ue{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==V.function)return H(a,{code:O.invalid_type,expected:V.function,received:a.parsedType}),J;function r(s,l){return Bu({data:s,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,As(),Kr].filter(u=>!!u),issueData:{code:O.invalid_arguments,argumentsError:l}})}function n(s,l){return Bu({data:s,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,As(),Kr].filter(u=>!!u),issueData:{code:O.invalid_return_type,returnTypeError:l}})}let o={errorMap:a.common.contextualErrorMap},i=a.data;if(this._def.returns instanceof ro){let s=this;return Mt(async function(...l){let u=new Qt([]),c=await s._def.args.parseAsync(l,o).catch(m=>{throw u.addIssue(r(l,m)),u}),d=await Reflect.apply(i,this,c);return await s._def.returns._def.type.parseAsync(d,o).catch(m=>{throw u.addIssue(n(d,m)),u})})}else{let s=this;return Mt(function(...l){let u=s._def.args.safeParse(l,o);if(!u.success)throw new Qt([r(l,u.error)]);let c=Reflect.apply(i,this,u.data),d=s._def.returns.safeParse(c,o);if(!d.success)throw new Qt([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:hr.create(e).rest(Jr.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||hr.create([]).rest(Jr.create()),returns:a||Jr.create(),typeName:ee.ZodFunction,...le(r)})}},ni=class extends ue{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})}};ni.create=(t,e)=>new ni({getter:t,typeName:ee.ZodLazy,...le(e)});var oi=class extends ue{_parse(e){if(e.data!==this._def.value){let a=this._getOrReturnCtx(e);return H(a,{received:a.data,code:O.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}};oi.create=(t,e)=>new oi({value:t,typeName:ee.ZodLiteral,...le(e)});function oA(t,e){return new ii({values:t,typeName:ee.ZodEnum,...le(e)})}var ii=class t extends ue{_parse(e){if(typeof e.data!="string"){let a=this._getOrReturnCtx(e),r=this._def.values;return H(a,{expected:fe.joinValues(r),received:a.parsedType,code:O.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 H(a,{received:a.data,code:O.invalid_enum_value,options:r}),J}return Mt(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})}};ii.create=oA;var si=class extends ue{_parse(e){let a=fe.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==V.string&&r.parsedType!==V.number){let n=fe.objectValues(a);return H(r,{expected:fe.joinValues(n),received:r.parsedType,code:O.invalid_type}),J}if(this._cache||(this._cache=new Set(fe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=fe.objectValues(a);return H(r,{received:r.data,code:O.invalid_enum_value,options:n}),J}return Mt(e.data)}get enum(){return this._def.values}};si.create=(t,e)=>new si({values:t,typeName:ee.ZodNativeEnum,...le(e)});var ro=class extends ue{unwrap(){return this._def.type}_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==V.promise&&a.common.async===!1)return H(a,{code:O.invalid_type,expected:V.promise,received:a.parsedType}),J;let r=a.parsedType===V.promise?a.data:Promise.resolve(a.data);return Mt(r.then(n=>this._def.type.parseAsync(n,{path:a.path,errorMap:a.common.contextualErrorMap})))}};ro.create=(t,e)=>new ro({type:t,typeName:ee.ZodPromise,...le(e)});var Na=class extends ue{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=>{H(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"?Xo(l.value):a.value==="dirty"?Xo(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"?Xo(s.value):a.value==="dirty"?Xo(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(!eo(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=>eo(i)?Promise.resolve(n.transform(i.value,o)).then(s=>({status:a.value,value:s})):J);fe.assertNever(n)}};Na.create=(t,e,a)=>new Na({schema:t,typeName:ee.ZodEffects,effect:e,...le(a)});Na.createWithPreprocess=(t,e,a)=>new Na({schema:e,effect:{type:"preprocess",transform:t},typeName:ee.ZodEffects,...le(a)});var Ba=class extends ue{_parse(e){return this._getType(e)===V.undefined?Mt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ba.create=(t,e)=>new Ba({innerType:t,typeName:ee.ZodOptional,...le(e)});var mr=class extends ue{_parse(e){return this._getType(e)===V.null?Mt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};mr.create=(t,e)=>new mr({innerType:t,typeName:ee.ZodNullable,...le(e)});var li=class extends ue{_parse(e){let{ctx:a}=this._processInputParams(e),r=a.data;return a.parsedType===V.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:a.path,parent:a})}removeDefault(){return this._def.innerType}};li.create=(t,e)=>new li({innerType:t,typeName:ee.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...le(e)});var ui=class extends ue{_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 ks(n)?n.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Qt(r.common.issues)},input:r.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Qt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};ui.create=(t,e)=>new ui({innerType:t,typeName:ee.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...le(e)});var Os=class extends ue{_parse(e){if(this._getType(e)!==V.nan){let r=this._getOrReturnCtx(e);return H(r,{code:O.invalid_type,expected:V.nan,received:r.parsedType}),J}return{status:"valid",value:e.data}}};Os.create=t=>new Os({typeName:ee.ZodNaN,...le(t)});var WB=Symbol("zod_brand"),Fu=class extends ue{_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}},Nu=class t extends ue{_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(),Xo(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})}},ci=class extends ue{_parse(e){let a=this._def.innerType._parse(e),r=n=>(eo(n)&&(n.value=Object.freeze(n.value)),n);return ks(a)?a.then(n=>r(n)):r(a)}unwrap(){return this._def.innerType}};ci.create=(t,e)=>new ci({innerType:t,typeName:ee.ZodReadonly,...le(e)});function tA(t,e){let a=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof a=="string"?{message:a}:a}function iA(t,e={},a){return t?ao.create().superRefine((r,n)=>{let o=t(r);if(o instanceof Promise)return o.then(i=>{if(!i){let s=tA(e,r),l=s.fatal??a??!0;n.addIssue({code:"custom",...s,fatal:l})}});if(!o){let i=tA(e,r),s=i.fatal??a??!0;n.addIssue({code:"custom",...i,fatal:s})}}):ao.create()}var ZB={object:Jt.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 XB=(t,e={message:`Input not instance of ${t.name}`})=>iA(a=>a instanceof t,e),sA=to.create,lA=Yo.create,YB=Os.create,KB=Ko.create,uA=Qo.create,QB=Jo.create,JB=Ts.create,eF=ei.create,tF=ti.create,aF=ao.create,rF=Jr.create,nF=Ja.create,oF=Rs.create,iF=en.create,sF=Jt.create,lF=Jt.strictCreate,uF=ai.create,cF=mp.create,dF=ri.create,fF=hr.create,pF=gp.create,hF=Ms.create,mF=Ds.create,gF=vp.create,vF=ni.create,yF=oi.create,xF=ii.create,bF=si.create,SF=ro.create,CF=Na.create,_F=Ba.create,wF=mr.create,LF=Na.createWithPreprocess,IF=Nu.create,AF=()=>sA().optional(),kF=()=>lA().optional(),EF=()=>uA().optional(),TF={string:(t=>to.create({...t,coerce:!0})),number:(t=>Yo.create({...t,coerce:!0})),boolean:(t=>Qo.create({...t,coerce:!0})),bigint:(t=>Ko.create({...t,coerce:!0})),date:(t=>Jo.create({...t,coerce:!0}))};var RF=J;var Ry=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()})]),cA=p.object({kind:p.literal("tooltip"),id:p.string(),anchor:Ry,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()}),dA=p.object({kind:p.literal("highlight"),id:p.string(),anchor:Ry,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()}),yp=p.object({id:p.string(),version:p.number(),routes:p.array(p.string()).optional(),steps:p.array(p.union([cA,dA]))});function MF(t){return yp.parse(t)}var DF=({configUri:t,experiments:e,featureKey:a="smart-canvas-overlay-uri",credentials:r="include"}={})=>async()=>{let n=Rf({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 yp.parse(i)};var xp=K(We(),1),fA=K(sl(),1);function OF({element:t,children:e}){let[a,r]=(0,xp.useState)(null);return(0,xp.useLayoutEffect)(()=>{if(!t){r(null);return}return r(t.getMountNode()),()=>r(null)},[t]),a?(0,fA.createPortal)(e,a):null}function BF(){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e="";for(let a=0;a<16;a++)e+=t[Math.floor(Math.random()*t.length)];return e}var My=class{constructor(){$(this,"sessionId");this.sessionId=BF(),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 bp(){return new My}var E=typeof window<"u"?window:void 0,It=typeof globalThis<"u"?globalThis:E;typeof self>"u"&&(It.self=It),typeof File>"u"&&(It.File=function(){});var lk=Array.prototype,pA=lk.forEach,hA=lk.indexOf,ya=It?.navigator,q=It?.document,ta=It?.location,Zy=It?.fetch,Xy=It!=null&&It.XMLHttpRequest&&"withCredentials"in new It.XMLHttpRequest?It.XMLHttpRequest:void 0,mA=It?.AbortController,ea=ya?.userAgent,ae=E??{},an={DEBUG:!1,LIB_VERSION:"1.302.2"};function gA(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 vA(t){return function(){var e=this,a=arguments;return new Promise((function(r,n){var o=t.apply(e,a);function i(l){gA(o,r,n,i,s,"next",l)}function s(l){gA(o,r,n,i,s,"throw",l)}i(void 0)}))}}function G(){return G=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},G.apply(null,arguments)}function uk(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 FF=["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"],yA=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var a=t.toLowerCase();return FF.concat(e).some((r=>{var n=r.toLowerCase();return a.indexOf(n)!==-1}))},NF=["$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 pe(t,e){return t.indexOf(e)!==-1}var Qp=function(t){return t.trim()},Yy=function(t){return t.replace(/^\$/,"")},PF=Array.isArray,ck=Object.prototype,dk=ck.hasOwnProperty,Jp=ck.toString,Te=PF||function(t){return Jp.call(t)==="[object Array]"},uo=t=>typeof t=="function",mt=t=>t===Object(t)&&!Te(t),Ps=t=>{if(mt(t)){for(var e in t)if(dk.call(t,e))return!1;return!0}return!1},U=t=>t===void 0,ut=t=>Jp.call(t)=="[object String]",Ky=t=>ut(t)&&t.trim().length===0,sn=t=>t===null,Ie=t=>U(t)||sn(t),xr=t=>Jp.call(t)=="[object Number]",co=t=>Jp.call(t)==="[object Boolean]",HF=t=>t instanceof FormData,UF=t=>pe(NF,t);function Qy(t){return t===null||typeof t!="object"}function Rp(t,e){return Object.prototype.toString.call(t)==="[object "+e+"]"}function fk(t){return!U(Event)&&(function(e,a){try{return e instanceof a}catch{return!1}})(t,Event)}var qF=[!0,"true",1,"1","yes"],Dy=t=>pe(qF,t),zF=[!1,"false",0,"0","no"];function gr(t,e,a,r,n){return e>a&&(r.warn("min cannot be greater than max."),e=a),xr(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),gr(n||a,e,a,r))}var Jy=class{constructor(e){this.t={},this.i=e.i,this.o=gr(e.bucketSize,0,100,e.h),this.m=gr(e.refillRate,0,this.o,e.h),this.S=gr(e.refillInterval,0,864e5,e.h)}$(e,a){var r=a-e.lastAccess,n=Math.floor(r/this.S);if(n>0){var o=n*this.m;e.tokens=Math.min(e.tokens+o,this.o),e.lastAccess=e.lastAccess+n*this.S}}consumeRateLimit(e){var a,r=Date.now(),n=String(e),o=this.t[n];return o?this.$(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={}}},Sp,xA,Oy,VF=t=>t instanceof Error;function $F(t){var e=globalThis._posthogChunkIds;if(e){var a=Object.keys(e);return Oy&&a.length===xA||(xA=a.length,Oy=a.reduce(((r,n)=>{Sp||(Sp={});var o=Sp[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,Sp[n]=[u,c];break}}return r}),{})),Oy}}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 vA((function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&Te(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)),G({},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 vA((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,G({},a,{handled:!0}))),s}buildParsingContext(){return{chunkIdMap:$F(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 G({},a,{syntheticException:r==0?a.syntheticException:void 0,mechanism:e,apply:o=>n(o,r),next:o=>n(o,r+1)})}},zs="?";function tx(t,e,a,r,n){var o={platform:t,filename:e,function:a==="<anonymous>"?zs:a,in_app:!0};return U(r)||(o.lineno=r),U(n)||(o.colno=n),o}var pk=(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]:zs,a?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},jF=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,GF=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,WF=/\((\S*)(?::(\d+))(?::(\d+))\)/,ZF=(t,e)=>{var a=jF.exec(t);if(a){var[,r,n,o]=a;return tx(e,r,zs,+n,+o)}var i=GF.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var s=WF.exec(i[2]);s&&(i[2]=s[1],i[3]=s[2],i[4]=s[3])}var[l,u]=pk(i[1]||zs,i[2]);return tx(e,u,l,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},XF=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,YF=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,KF=(t,e)=>{var a=XF.exec(t);if(a){if(a[3]&&a[3].indexOf(" > eval")>-1){var r=YF.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]||zs;return[o,n]=pk(o,n),tx(e,n,o,a[4]?+a[4]:void 0,a[5]?+a[5]:void 0)}},bA=/\(error: (.*)\)/,SA=50;function QF(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(`
459
+ `,Oa,Wn,Zn,Wr,Zr,Xn,Xr,Gf=class extends HTMLElement{constructor(){super();pn(this,Oa);pn(this,Wn);pn(this,Zn);pn(this,Wr);pn(this,Zr);pn(this,Xn,null);pn(this,Xr,null);ar(this,Oa,this.attachShadow({mode:"open",delegatesFocus:!0})),ar(this,Wn,document.createElement("div")),ge(this,Wn).setAttribute("part","mount"),ge(this,Oa).appendChild(ge(this,Wn)),ar(this,Zn,document.createElement("div")),ge(this,Zn).id="portalRoot",ge(this,Oa).appendChild(ge(this,Zn)),ar(this,Wr,document.createElement("div")),ge(this,Wr).id="overlayContainer",Object.assign(ge(this,Wr).style,{position:"fixed",inset:"0",zIndex:"2147483645",pointerEvents:"none"}),ge(this,Oa).appendChild(ge(this,Wr)),ar(this,Zr,Gv()),this.applyBaseStyles()}connectedCallback(){this.style.setProperty("font-family","inherit")}disconnectedCallback(){ge(this,Xn)?.unmount(),ar(this,Xn,null)}getMountNode(){return ge(this,Wn)}getController(){return ge(this,Zr)}getPortalRoot(){return ge(this,Zn)}getOverlayContainer(){return ge(this,Wr)}getShadowRoot(){return ge(this,Oa)}open(){ge(this,Zr).setOpen(!0)}close(){ge(this,Zr).setOpen(!1)}toggle(){ge(this,Zr).toggle()}setOverrideFetcher(a){ge(this,Xr)&&(ar(this,Xr,{...ge(this,Xr),fetcher:a}),this.render())}mountReactApp(a){ar(this,Xr,a),this.render()}render(){!this.isConnected||!ge(this,Xr)||(ge(this,Xn)||ar(this,Xn,(0,p1.createRoot)(ge(this,Wn))),ge(this,Xn).render((0,ly.jsx)(Wv,{shadowRoot:ge(this,Oa),portalRoot:ge(this,Zn),overlayContainer:ge(this,Wr),children:(0,ly.jsx)(sy,{...ge(this,Xr),controller:ge(this,Zr),canvasHost:this})})))}applyBaseStyles(){if(ge(this,Oa).adoptedStyleSheets!==void 0){let a=new CSSStyleSheet;a.replaceSync(f1),ge(this,Oa).adoptedStyleSheets=[a]}else{let a=document.createElement("style");a.textContent=f1,ge(this,Oa).appendChild(a)}}};Oa=new WeakMap,Wn=new WeakMap,Zn=new WeakMap,Wr=new WeakMap,Zr=new WeakMap,Xn=new WeakMap,Xr=new WeakMap;var uy=()=>{typeof window>"u"||customElements.get(d1)||customElements.define(d1,Gf)};var Wf=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 x=typeof t.antiFlicker=="object"?t.antiFlicker:{};e=MI(x)}let a=null,r=null,n=null,{runtime:o}=t;async function i(x){!o?.actions||x.length===0||(n?.isApplied()&&await n.revertAll(),n=await o.actions.applyBatch(x))}async function s(){n?.isApplied()&&(await n.revertAll(),n=null)}if(t.fetcher)try{r=t.fetcher,console.log("[SmartCanvas] Fetching initial config...");let x=await t.fetcher();a=x,console.log("[SmartCanvas] Config fetched:",`tiles=${x.tiles?.length??0},`,`actions=${x.actions?.length??0},`,`theme=${x.theme?.mode??"default"}`),x.actions?.length&&console.log("[SmartCanvas] Actions to apply:",x.actions.map((f,g)=>`[${g}] ${f.kind}${f.anchorId?` anchor="${typeof f.anchorId=="string"?f.anchorId:f.anchorId.selector}"`:""}${f.label?` "${f.label}"`:""}`).join(", ")),x.actions&&x.actions.length>0&&o?.actions&&(await i(x.actions),console.log("[SmartCanvas] Initial actions applied successfully")),x.tiles&&o?.accumulator&&xu(x.tiles,o.accumulator,x.actions)}catch(x){console.error("[SmartCanvas] Error fetching/applying initial config:",x)}e&&e();let l=PI();uy();let u=document.createElement("smart-canvas");if(VI(u.getOverlayContainer()),t.tokens)for(let[x,f]of Object.entries(t.tokens))u.style.setProperty(x,f);let c=()=>{let x=t.target??document.body;x&&x.appendChild(u)};document.body?c():document.addEventListener("DOMContentLoaded",c,{once:!0}),l&&(console.log(`[SmartCanvas] Loading editor SDK for ${l} mode`),HI(t.editorUrl).catch(console.error));let d=t.integrations?.experiments,h=t.integrations?.telemetry,m=t.fetcher??Vo({configUri:t.configUri,experiments:d,featureKey:t.configUriFeatureKey,credentials:t.fetchCredentials});r||(r=m);let S={fetcher:m,pollIntervalMs:t.pollIntervalMs,experiments:d,telemetry:h,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 b={el:u,open:()=>u.open(),close:()=>u.close(),destroy:()=>{s(),u.remove()},setTokens:x=>{for(let[f,g]of Object.entries(x))u.style.setProperty(f,g)},getConfig:async()=>{if(r)try{let x=await r();return a=x,x}catch(x){console.error("[SmartCanvas] Error fetching config:",x)}return a??{tiles:[],actions:[],fetchedAt:""}},setEnabled:async x=>{x?a&&await i(a.actions):await s()},setOverrideFetcher:x=>{r=x,u.setOverrideFetcher(x),o?.accumulator&&x().then(f=>{f?.tiles&&xu(f.tiles,o.accumulator,f.actions)}).catch(()=>{})},registerTelemetryProperties:x=>{h?.register?.(x)},getSessionId:()=>h?.getSessionId?.(),startSessionRecording:()=>{h?.startSessionRecording?.()},track:(x,f)=>h?.track?(h.track(x,f),!0):!1,runtime:o};if(typeof window<"u"){let x=window.SynOS;x&&(x.handle=b)}return b};typeof window<"u"&&(window.SmartCanvas={async create(t){return Wf(t)}});var Kn=K(We(),1);var Yn=K(Me(),1);function gO({tiles:t,intervalMs:e=7e3,telemetry:a}){let[r,n]=(0,Kn.useState)(0),o=(0,Kn.useMemo)(()=>[...t].sort((i,s)=>(i.priority??0)-(s.priority??0)),[t]);return(0,Kn.useEffect)(()=>{a?.trackCanvasOpened("wheel")},[a]),(0,Kn.useEffect)(()=>{if(o.length<=1)return;let i=setInterval(()=>{n(s=>(s+1)%o.length)},e);return()=>clearInterval(i)},[o,e]),(0,Kn.useEffect)(()=>{let i=o[r];i&&a?.trackRectangleViewed(i.id,"wheel")},[r,o,a]),o.length?(0,Yn.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,Yn.jsx)("div",{style:{display:"flex",transition:"transform 700ms ease-out",transform:`translateX(-${r*100}%)`,width:`${o.length*100}%`},children:o.map(i=>(0,Yn.jsx)("div",{style:{width:"100%",flexShrink:0,padding:"0 1rem"},children:(0,Yn.jsx)(vs,{config:i,surface:"wheel",telemetry:a})},i.id))}),(0,Yn.jsx)("div",{style:{marginTop:"1rem",display:"flex",justifyContent:"center",gap:"0.5rem"},children:o.map((i,s)=>(0,Yn.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 xs(t){let e=t.split(".");return{major:parseInt(e[0]||"0",10),minor:parseInt(e[1]||"0",10)}}function vO(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=xs(n),i=xs(jr);return o.major>i.major&&e.push(`Config schema v${n} is newer than SDK v${jr}. 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${jr}. Migrating config to current version.`),{valid:!0,warnings:e,errors:a,migratedConfig:yO(r,n)}):{valid:!0,warnings:e,errors:a}}function yO(t,e){let a={...t};return xs(e).major===1&&(a=xO(a)),a.schemaVersion=jr,a}function xO(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 bO(t){if(!t||typeof t!="object")return!1;let e=t,a=e.schemaVersion||"1.0",r=xs(a),n=xs(jr);return r.major<n.major||!e.schemaVersion}var m1={fetch:globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,SubtleCrypto:globalThis.crypto?globalThis.crypto.subtle:void 0,EventSource:globalThis.EventSource};function g1(){return m1}function cy(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 ku(t,e,a){return a===2?cy(cy(t+e)+"")%1e4/1e4:a===1?cy(e+t)%1e3/1e3:null}function SO(t){return t<=0?[]:new Array(t).fill(1/t)}function Zf(t,e){return t>=e[0]&&t<e[1]}function v1(t,e){let a=ku("__"+e[0],t,1);return a===null?!1:a>=e[1]&&a<e[2]}function y1(t,e){for(let a=0;a<e.length;a++)if(Zf(t,e[a]))return a;return-1}function fy(t){try{let e=t.replace(/([^\\])\//g,"$1\\/");return new RegExp(e)}catch(e){console.error(e);return}}function Xf(t,e){if(!e.length)return!1;let a=!1,r=!1;for(let n=0;n<e.length;n++){let o=wO(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 CO(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 _O(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=>!CO(n[0],n[1],n[2]))}catch{return!1}}function wO(t,e,a){try{let r=new URL(t,"https://_");if(e==="regex"){let n=fy(a);return n?n.test(r.href)||n.test(r.href.substring(r.origin.length)):!1}else if(e==="simple")return _O(r,a);return!1}catch{return!1}}function x1(t,e,a){e=e===void 0?1:e,e<0?e=0:e>1&&(e=1);let r=SO(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 b1(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 S1(t){try{return t()}catch(e){return console.error(e),!1}}var dy=t=>Uint8Array.from(atob(t),e=>e.charCodeAt(0));async function Wo(t,e,a){if(e=e||"",a=a||globalThis.crypto&&globalThis.crypto.subtle||m1.SubtleCrypto,!a)throw new Error("No SubtleCrypto implementation found");try{let r=await a.importKey("raw",dy(e),{name:"AES-CBC",length:128},!0,["encrypt","decrypt"]),[n,o]=t.split("."),i=await a.decrypt({name:"AES-CBC",iv:dy(n)},r,dy(o));return new TextDecoder().decode(i)}catch{throw new Error("Failed to decrypt")}}function Eu(t){return typeof t=="string"?t:JSON.stringify(t)}function va(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 C1(){let t;try{t="1.6.4"}catch{t=""}return t}function _1(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 h1(t){return typeof t=="object"&&t!==null}function Yf(t){return t.urlPatterns&&t.variations.some(e=>h1(e)&&"urlRedirect"in e)?"redirect":t.variations.some(e=>h1(e)&&(e.domMutations||"js"in e||"css"in e))?"visual":"unknown"}async function Kf(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 Rt={staleTTL:1e3*60,maxAge:1e3*60*60*4,cacheKey:"gbFeaturesCache",backgroundSync:!0,maxEntries:10,disableIdleStreams:!1,idleStreamInterval:2e4,disableCache:!1},fr=g1(),bs={fetchFeaturesCall:({host:t,clientKey:e,headers:a})=>fr.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 fr.fetch(`${t}/api/eval/${e}`,n)},eventSourceCall:({host:t,clientKey:e,headers:a})=>a?new fr.EventSource(`${t}/sub/${e}`,{headers:a}):new fr.EventSource(`${t}/sub/${e}`),startIdleListener:()=>{let t;if(!(typeof window<"u"&&typeof document<"u"))return;let a=()=>{document.visibilityState==="visible"?(window.clearTimeout(t),AO()):document.visibilityState==="hidden"&&(t=window.setTimeout(IO,Rt.idleStreamInterval))};return document.addEventListener("visibilitychange",a),()=>document.removeEventListener("visibilitychange",a)},stopIdleListener:()=>{}};try{globalThis.localStorage&&(fr.localStorage=globalThis.localStorage)}catch{}var Ss=new Map,w1=!1,Yr=new Map,Qf=new Map,Cs=new Map,_s=new Set;function I1(t){Object.assign(Rt,t),Rt.backgroundSync||yy()}async function A1({instance:t,timeout:e,skipCache:a,allowStale:r,backgroundSync:n}){return n||(Rt.backgroundSync=!1),kO({instance:t,allowStale:r,timeout:e,skipCache:a})}function LO(t){let e=Tu(t),a=Ss.get(e)||new Set;a.add(t),Ss.set(e,a)}function k1(t){Ss.forEach(e=>e.delete(t))}function IO(){Cs.forEach(t=>{t&&(t.state="idle",gy(t))})}function AO(){Cs.forEach(t=>{t&&t.state==="idle"&&vy(t)})}async function L1(){try{if(!fr.localStorage)return;await fr.localStorage.setItem(Rt.cacheKey,JSON.stringify(Array.from(Yr.entries())))}catch{}}async function kO({instance:t,allowStale:e,timeout:a,skipCache:r}){let n=Tu(t),o=hy(t),i=new Date,s=new Date(i.getTime()-Rt.maxAge+Rt.staleTTL);await EO();let l=!Rt.disableCache&&!r?Yr.get(o):void 0;return l&&(e||l.staleAt>i)&&l.staleAt>s?(l.sse&&_s.add(n),l.staleAt<i?py(t):my(t),{data:l.data,success:!0,source:"cache"}):await Kf(py(t),a)||{data:null,success:!1,source:"timeout",error:new Error("Timeout")}}function Tu(t){let[e,a]=t.getApiInfo();return`${e}||${a}`}function hy(t){let e=Tu(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 EO(){if(!w1){w1=!0;try{if(fr.localStorage){let t=await fr.localStorage.getItem(Rt.cacheKey);if(!Rt.disableCache&&t){let e=JSON.parse(t);e&&Array.isArray(e)&&e.forEach(([a,r])=>{Yr.set(a,{...r,staleAt:new Date(r.staleAt)})}),E1()}}}catch{}if(!Rt.disableIdleStreams){let t=bs.startIdleListener();t&&(bs.stopIdleListener=t)}}}function E1(){let t=Array.from(Yr.entries()).map(([a,r])=>({key:a,staleAt:r.staleAt.getTime()})).sort((a,r)=>a.staleAt-r.staleAt),e=Math.min(Math.max(0,Yr.size-Rt.maxEntries),Yr.size);for(let a=0;a<e;a++)Yr.delete(t[a].key)}function T1(t,e,a){let r=a.dateUpdated||"",n=new Date(Date.now()+Rt.staleTTL),o=Rt.disableCache?void 0:Yr.get(e);if(o&&r&&o.version===r){o.staleAt=n,L1();return}Rt.disableCache||(Yr.set(e,{data:a,version:r,staleAt:n,sse:_s.has(t)}),E1()),L1();let i=Ss.get(t);i&&i.forEach(s=>TO(s,a))}async function TO(t,e){await t.setPayload(e||t.getPayload())}async function py(t){let{apiHost:e,apiRequestHeaders:a}=t.getApiHosts(),r=t.getClientKey(),n="isRemoteEval"in t&&t.isRemoteEval(),o=Tu(t),i=hy(t),s=Qf.get(i);return s||(s=(n?bs.fetchRemoteEvalCall({host:e,clientKey:r,payload:{attributes:t.getAttributes(),forcedVariations:t.getForcedVariations(),forcedFeatures:Array.from(t.getForcedFeatures().entries()),url:t.getUrl()},headers:a}):bs.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"&&_s.add(o),u.json()}).then(u=>(T1(o,i,u),my(t),Qf.delete(i),{data:u,success:!0,source:"network"})).catch(u=>(Qf.delete(i),{data:null,source:"error",success:!1,error:u})),Qf.set(i,s)),s}function my(t,e=!1){let a=Tu(t),r=hy(t),{streamingHost:n,streamingHostRequestHeaders:o}=t.getApiHosts(),i=t.getClientKey();if(e&&_s.add(a),Rt.backgroundSync&&_s.has(a)&&fr.EventSource){if(Cs.has(a))return;let s={src:null,host:n,clientKey:i,headers:o,cb:l=>{try{if(l.type==="features-updated"){let u=Ss.get(a);u&&u.forEach(c=>{py(c)})}else if(l.type==="features"){let u=JSON.parse(l.data);T1(a,r,u)}s.errors=0}catch{R1(s)}},errors:0,state:"active"};Cs.set(a,s),vy(s)}}function R1(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);gy(t),setTimeout(()=>{["idle","active"].includes(t.state)||vy(t)},Math.min(e,3e5))}}function gy(t){t.src&&(t.src.onopen=null,t.src.onerror=null,t.src.close(),t.src=null,t.state==="active"&&(t.state="disabled"))}function vy(t){t.src=bs.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=()=>R1(t),t.src.onopen=()=>{t.errors=0}}function RO(t,e){gy(t),Cs.delete(e)}function yy(){_s.clear(),Cs.forEach(RO),Ss.clear(),bs.stopIdleListener()}function Jf(t,e){if(e.streaming){if(!t.getClientKey())throw new Error("Must specify clientKey to enable streaming");e.payload&&my(t,!0),LO(t)}}var MO=/^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/,Sy={revert:function(){}},rp=new Map,Cy=new Set;function DO(t){return t==="html"?{childList:!0,subtree:!0,attributes:!0,characterData:!0}:{childList:!1,subtree:!1,attributes:!0,attributeFilter:[t]}}function np(t){var e=rp.get(t);return e||(e={element:t,attributes:{}},rp.set(t,e)),e}function op(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,DO(e)),i}function ip(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,M1()):t!==a&&(e.isDirty=!0,M1())}function OO(t){var e=t.originalValue;t.mutations.forEach(function(a){return e=a.mutate(e)}),ip(ZO(e),t)}function BO(t){var e=new Set(t.originalValue.split(/\s+/).filter(Boolean));t.mutations.forEach(function(a){return a.mutate(e)}),ip(Array.from(e).filter(Boolean).join(" "),t)}function FO(t){var e=t.originalValue;t.mutations.forEach(function(a){return e=a.mutate(e)}),ip(e,t)}function NO(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 PO(t){var e=t.originalValue;t.mutations.forEach(function(a){var r=a.mutate(),n=NO(r);e=n||e}),ip(e,t)}var HO=function(e){return e.innerHTML},UO=function(e,a){return e.innerHTML=a};function O1(t){var e=np(t);return e.html||(e.html=op(t,"html",HO,UO,OO)),e.html}var qO=function(e){return{parentNode:e.parentElement,insertBeforeNode:e.nextElementSibling}},zO=function(e,a){a.insertBeforeNode&&!a.parentNode.contains(a.insertBeforeNode)||a.parentNode.insertBefore(e,a.insertBeforeNode)};function B1(t){var e=np(t);return e.position||(e.position=op(t,"position",qO,zO,PO)),e.position}var VO=function(e,a){return a?e.className=a:e.removeAttribute("class")},$O=function(e){return e.className};function F1(t){var e=np(t);return e.classes||(e.classes=op(t,"class",$O,VO,BO)),e.classes}var jO=function(e){return function(a){var r;return(r=a.getAttribute(e))!=null?r:null}},GO=function(e){return function(a,r){return r!==null?a.setAttribute(e,r):a.removeAttribute(e)}};function N1(t,e){var a=np(t);return a.attributes[e]||(a.attributes[e]=op(t,e,jO(e),GO(e),FO)),a.attributes[e]}function WO(t,e){var a=rp.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 ep;function ZO(t){return ep||(ep=document.createElement("div")),ep.innerHTML=t,ep.innerHTML}function tp(t,e,a){if(a.isDirty){a.isDirty=!1;var r=a.virtualValue;a.mutations.length||WO(t,e),a.setValue(t,r)}}function XO(t,e){t.html&&tp(e,"html",t.html),t.classes&&tp(e,"class",t.classes),t.position&&tp(e,"position",t.position),Object.keys(t.attributes).forEach(function(a){tp(e,a,t.attributes[a])})}function M1(){rp.forEach(XO)}function YO(t,e){var a=null;t.kind==="html"?a=O1(e):t.kind==="class"?a=F1(e):t.kind==="attribute"?a=N1(e,t.attribute):t.kind==="position"&&(a=B1(e)),a&&(a.mutations.push(t),a.mutationRunner(a))}function KO(t,e){var a=null;if(t.kind==="html"?a=O1(e):t.kind==="class"?a=F1(e):t.kind==="attribute"?a=N1(e,t.attribute):t.kind==="position"&&(a=B1(e)),!!a){var r=a.mutations.indexOf(t);r!==-1&&a.mutations.splice(r,1),a.mutationRunner(a)}}function P1(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),YO(t,r))})}}function QO(t){t.elements.forEach(function(e){return KO(t,e)}),t.elements.clear(),Cy.delete(t)}function D1(){Cy.forEach(P1)}var xy;function JO(){typeof document>"u"||(xy||(xy=new MutationObserver(function(){D1()})),D1(),xy.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}JO();function sp(t){return typeof document>"u"?Sy:(Cy.add(t),P1(t),{revert:function(){QO(t)}})}function by(t,e){return sp({kind:"html",elements:new Set,mutate:e,selector:t})}function H1(t,e){return sp({kind:"position",elements:new Set,mutate:e,selector:t})}function Ru(t,e){return sp({kind:"class",elements:new Set,mutate:e,selector:t})}function ap(t,e,a){return MO.test(e)?e==="class"||e==="className"?Ru(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)})}):sp({kind:"attribute",attribute:e,elements:new Set,mutate:a,selector:t}):Sy}function eB(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 by(e,function(s){return s+(r??"")});if(a==="set")return by(e,function(){return r??""})}else if(n==="class"){if(a==="append")return Ru(e,function(s){r&&s.add(r)});if(a==="remove")return Ru(e,function(s){r&&s.delete(r)});if(a==="set")return Ru(e,function(s){s.clear(),r&&s.add(r)})}else if(n==="position"){if(a==="set"&&o)return H1(e,function(){return{insertBeforeSelector:i,parentSelector:o}})}else{if(a==="append")return ap(e,n,function(s){return s!==null?s+(r??""):r??""});if(a==="set")return ap(e,n,function(){return r??""});if(a==="remove")return ap(e,n,function(){return null})}return Sy}var tB={html:by,classes:Ru,attribute:ap,position:H1,declarative:eB},U1=tB;var _y={};function Qn(t,e,a){a=a||{};for(let[r,n]of Object.entries(e))switch(r){case"$or":if(!V1(t,n,a))return!1;break;case"$nor":if(V1(t,n,a))return!1;break;case"$and":if(!iB(t,n,a))return!1;break;case"$not":if(Qn(t,n,a))return!1;break;default:if(!Mu(n,aB(t,r),a))return!1}return!0}function aB(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 q1(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 Mu(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)||!$1(t))return JSON.stringify(e)===JSON.stringify(t);for(let n in t)if(!oB(n,e,t[n],a))return!1;return!0}function $1(t){let e=Object.keys(t);return e.length>0&&e.filter(a=>a[0]==="$").length===e.length}function rB(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 nB(t,e,a){if(!Array.isArray(t))return!1;let r=$1(e)?n=>Mu(e,n,a):n=>Qn(n,e,a);for(let n=0;n<t.length;n++)if(t[n]&&r(t[n]))return!0;return!1}function ws(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 z1(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(Mu(e[n],t[i],a,r)){o=!0;break}if(!o)return!1}return!0}function oB(t,e,a,r){switch(t){case"$veq":return va(e)===va(a);case"$vne":return va(e)!==va(a);case"$vgt":return va(e)>va(a);case"$vgte":return va(e)>=va(a);case"$vlt":return va(e)<va(a);case"$vlte":return va(e)<=va(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)?ws(e,a):!1;case"$ini":return Array.isArray(a)?ws(e,a,!0):!1;case"$inGroup":return ws(e,r[a]||[]);case"$notInGroup":return!ws(e,r[a]||[]);case"$nin":return Array.isArray(a)?!ws(e,a):!1;case"$nini":return Array.isArray(a)?!ws(e,a,!0):!1;case"$not":return!Mu(a,e,r);case"$size":return Array.isArray(e)?Mu(a,e.length,r):!1;case"$elemMatch":return nB(e,a,r);case"$all":return Array.isArray(a)?z1(e,a,r):!1;case"$alli":return Array.isArray(a)?z1(e,a,r,!0):!1;case"$regex":try{return q1(a).test(e)}catch{return!1}case"$regexi":try{return q1(a,!0).test(e)}catch{return!1}case"$type":return rB(e)===a;default:return console.error("Unknown operator: "+t),!1}}function V1(t,e,a){if(!e.length)return!0;for(let r=0;r<e.length;r++)if(Qn(t,e[r],a))return!0;return!1}function iB(t,e,a){for(let r=0;r<e.length;r++)if(!Qn(t,e[r],a))return!1;return!0}var sB="Feature Evaluated",lB="Experiment Viewed";function uB(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 cB(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 Ls(t){try{await t()}catch{}}function j1(t,e,a){if(t.user.trackedExperiments){let n=cp(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(Ls(()=>n(e,a,t.user)))}if(t.user.trackingCallback){let n=t.user.trackingCallback;r.push(Ls(()=>n(e,a)))}if(t.global.eventLogger){let n=t.global.eventLogger;r.push(Ls(()=>n(lB,{experimentId:e.key,variationId:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue},t.user)))}return r}function dB(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;Ls(()=>r(e,a,t.user))}if(t.user.onFeatureUsage){let r=t.user.onFeatureUsage;Ls(()=>r(e,a))}if(t.global.eventLogger){let r=t.global.eventLogger;Ls(()=>r(sB,{feature:e,source:a.source,value:a.value,ruleId:a.source==="defaultValue"?"$default":a.ruleId||"",variationId:a.experimentResult?a.experimentResult.key:""},t.user))}}function lp(t,e){if(e.stack.evaluatedFeatures.has(t))return Jn(e,t,null,"cyclicPrerequisite");e.stack.evaluatedFeatures.add(t),e.stack.id=t;let a=uB(e);if(a.has(t))return Jn(e,t,a.get(t),"override");if(!e.global.features||!e.global.features[t])return Jn(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=lp(l.id,e);if(u.source==="cyclicPrerequisite")return Jn(e,t,null,"cyclicPrerequisite");let c={value:u.value};if(!Qn(c,l.condition||{})){if(l.gate)return Jn(e,t,null,"prerequisite");continue e}}if(o.filters&&Z1(o.filters,e))continue;if("force"in o){if(o.condition&&!W1(o.condition,e)||!fB(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=>{!j1(e,l.experiment,l.result).length&&e.global.saveDeferredTrack&&e.global.saveDeferredTrack({experiment:l.experiment,result:l.result})}),Jn(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}=up(i,t,e);if(e.global.onExperimentEval&&e.global.onExperimentEval(i,s),s.inExperiment&&!s.passthrough)return Jn(e,t,s.value,"experiment",o.id,i,s)}}return Jn(e,t,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function up(t,e,a){let r=t.key,n=t.variations.length;if(n<2)return{result:$e(a,t,-1,!1,e)};if(a.global.enabled===!1||a.user.enabled===!1)return{result:$e(a,t,-1,!1,e)};if(t=pB(t,a),t.urlPatterns&&!Xf(a.user.url||"",t.urlPatterns))return{result:$e(a,t,-1,!1,e)};let o=b1(r,a.user.url||"",n);if(o!==null)return{result:$e(a,t,o,!1,e)};let i=cB(a);if(r in i){let x=i[r];return{result:$e(a,t,x,!1,e)}}if(t.status==="draft"||t.active===!1)return{result:$e(a,t,-1,!1,e)};let{hashAttribute:s,hashValue:l}=Zo(a,t.hashAttribute,a.user.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0);if(!l)return{result:$e(a,t,-1,!1,e)};let u=-1,c=!1,d=!1;if(a.user.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing){let{variation:x,versionIsBlocked:f}=gB({ctx:a,expKey:t.key,expBucketVersion:t.bucketVersion,expHashAttribute:t.hashAttribute,expFallbackAttribute:t.fallbackAttribute,expMinBucketVersion:t.minBucketVersion,expMeta:t.meta});c=x>=0,u=x,d=!!f}if(!c){if(t.filters){if(Z1(t.filters,a))return{result:$e(a,t,-1,!1,e)}}else if(t.namespace&&!v1(l,t.namespace))return{result:$e(a,t,-1,!1,e)};if(t.include&&!S1(t.include))return{result:$e(a,t,-1,!1,e)};if(t.condition&&!W1(t.condition,a))return{result:$e(a,t,-1,!1,e)};if(t.parentConditions){let x=new Set(a.stack.evaluatedFeatures);for(let f of t.parentConditions){a.stack.evaluatedFeatures=new Set(x);let g=lp(f.id,a);if(g.source==="cyclicPrerequisite")return{result:$e(a,t,-1,!1,e)};let v={value:g.value};if(!Qn(v,f.condition||{}))return{result:$e(a,t,-1,!1,e)}}}if(t.groups&&!mB(t.groups,a))return{result:$e(a,t,-1,!1,e)}}if(t.url&&!hB(t.url,a))return{result:$e(a,t,-1,!1,e)};let h=ku(t.seed||r,l,t.hashVersion||1);if(h===null)return{result:$e(a,t,-1,!1,e)};if(!c){let x=t.ranges||x1(n,t.coverage===void 0?1:t.coverage,t.weights);u=y1(h,x)}if(d)return{result:$e(a,t,-1,!1,e,void 0,!0)};if(u<0)return{result:$e(a,t,-1,!1,e)};if("force"in t)return{result:$e(a,t,t.force===void 0?-1:t.force,!1,e)};if(a.global.qaMode||a.user.qaMode)return{result:$e(a,t,-1,!1,e)};if(t.status==="stopped")return{result:$e(a,t,-1,!1,e)};let m=$e(a,t,u,!0,e,h,c);if(a.user.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing){let{changed:x,key:f,doc:g}=yB(a,s,Eu(l),{[wy(t.key,t.bucketVersion)]:m.key});x&&(a.user.stickyBucketAssignmentDocs=a.user.stickyBucketAssignmentDocs||{},a.user.stickyBucketAssignmentDocs[f]=g,a.user.saveStickyBucketAssignmentDoc(g))}let S=j1(a,t,m);S.length===0&&a.global.saveDeferredTrack&&a.global.saveDeferredTrack({experiment:t,result:m});let b=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:m,trackingCall:b}}function Jn(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"&&dB(t,e,s),s}function G1(t){return{...t.user.attributes,...t.user.attributeOverrides}}function W1(t,e){return Qn(G1(e),t,e.global.savedGroups||{})}function Z1(t,e){return t.some(a=>{let{hashValue:r}=Zo(e,a.attribute);if(!r)return!0;let n=ku(a.seed,r,a.hashVersion||2);return n===null?!0:!a.ranges.some(o=>Zf(n,o))})}function fB(t,e,a,r,n,o,i){if(!n&&o===void 0)return!0;if(!n&&o===0)return!1;let{hashValue:s}=Zo(t,a,r);if(!s)return!1;let l=ku(e,s,i||1);return l===null?!1:n?Zf(l,n):o!==void 0?l<=o:!0}function $e(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}=Zo(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 pB(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=fy(t.url))),t}function Zo(t,e,a){let r=e||"id",n="",o=G1(t);return o[r]&&(n=o[r]),!n&&a&&(o[a]&&(n=o[a]),n&&(r=a)),{hashAttribute:r,hashValue:n}}function hB(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 mB(t,e){let a=e.global.groups||{};for(let r=0;r<t.length;r++)if(a[t[r]])return!0;return!1}function gB({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=wy(e,a),l=vB(t,r,n);if(o>0)for(let d=0;d<o;d++){let h=wy(e,d);if(l[h]!==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 wy(t,e){return e=e||0,`${t}__${e}`}function Ly(t,e){return`${t}||${e}`}function vB(t,e,a){if(!t.user.stickyBucketAssignmentDocs)return{};let{hashAttribute:r,hashValue:n}=Zo(t,e),o=Ly(r,Eu(n)),{hashAttribute:i,hashValue:s}=Zo(t,a),l=s?Ly(i,Eu(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 yB(t,e,a,r){let n=Ly(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 xB(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 X1(t,e,a){let r=Iy(t,a);return e.getAllAssignments(r)}function Iy(t,e){let a={};return xB(t,e).forEach(n=>{let{hashValue:o}=Zo(t,n);a[n]=Eu(o)}),a}async function Y1(t,e,a){if(t={...t},t.encryptedFeatures){try{t.features=JSON.parse(await Wo(t.encryptedFeatures,e,a))}catch(r){console.error(r)}delete t.encryptedFeatures}if(t.encryptedExperiments){try{t.experiments=JSON.parse(await Wo(t.encryptedExperiments,e,a))}catch(r){console.error(r)}delete t.encryptedExperiments}if(t.encryptedSavedGroups){try{t.savedGroups=JSON.parse(await Wo(t.encryptedSavedGroups,e,a))}catch(r){console.error(r)}delete t.encryptedSavedGroups}return t}function K1(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 cp(t,e){return e.hashAttribute+e.hashValue+t.key+e.variationId}var Is=typeof window<"u"&&typeof document<"u",bB=C1(),Du=class{constructor(e){if(e=e||{},this.version=bB,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),Is&&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 Y1(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,Jf(this,e),this}async init(e){if(this._initialized=!0,e=e||{},e.cacheSettings&&I1(e.cacheSettings),e.payload)return await this.setPayload(e.payload),Jf(this,e),{success:!0,source:"init"};{let{data:a,...r}=await this._refresh({...e,allowStale:!0});return Jf(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 K1(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 A1({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 Wo(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 Wo(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,k1(this),e.destroyAllStreams&&yy(),this.logs=[],Is&&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}=up(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=$e(this._getEvalContext(),e,-1,!1,""):({result:o,trackingCall:i}=up(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=Yf(e);if(l==="redirect"&&o.value.urlRedirect&&e.urlPatterns){let u=e.persistQueryString?_1(this._getContextUrl(),o.value.urlRedirect):o.value.urlRedirect;if(Xf(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(Is)Promise.all([...i?[Kf(i,this._options.maxNavigateDelay??1e3)]:[],new Promise(h=>window.setTimeout(h,this._options.navigateDelay??d))]).then(()=>{try{c(u)}catch(h){console.error(h)}});else try{c(u)}catch(h){console.error(h)}}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&&Yf(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 lp(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=>[cp(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(cp(e.experiment,e.result),e)}_getContextUrl(){return this._options.url||(Is?window.location.href:"")}_isAutoExperimentBlockedByContext(e){let a=Yf(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}:Is?{navigate:e=>{window.location.replace(e)},delay:100}:{navigate:null,delay:0}}_applyDOMChanges(e){if(!Is)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(U1.declarative(r).revert)}),()=>{a.forEach(r=>r())}}async refreshStickyBuckets(e){if(this._options.stickyBucketService){let a=this._getEvalContext(),r=await X1(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=Iy(r,a);return e.getAllAssignmentsSync(n)}inDevMode(){return!!this._options.enableDevMode}};var SB="https://experiment.syntrologie.com",Ay=class{constructor(e={}){$(this,"gb");$(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 Du({...e,apiHost:e.apiHost??SB,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 dp(t={}){return new Ay(t)}var Q1="syntro_session_metrics",Ou=class{constructor(e={}){$(this,"metrics",new Map);$(this,"experiments");$(this,"attributePrefix");$(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(Q1);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(Q1,JSON.stringify(e))}catch(e){console.warn("[SessionMetricTracker] Failed to save to sessionStorage:",e)}}};function fp(t={}){return new Ou(t)}var p={};xS(p,{BRAND:()=>WB,DIRTY:()=>Xo,EMPTY_PATH:()=>LB,INVALID:()=>J,NEVER:()=>RF,OK:()=>Mt,ParseStatus:()=>wt,Schema:()=>ue,ZodAny:()=>ao,ZodArray:()=>en,ZodBigInt:()=>Ko,ZodBoolean:()=>Qo,ZodBranded:()=>Fu,ZodCatch:()=>ui,ZodDate:()=>Jo,ZodDefault:()=>li,ZodDiscriminatedUnion:()=>mp,ZodEffects:()=>Na,ZodEnum:()=>ii,ZodError:()=>Qt,ZodFirstPartyTypeKind:()=>ee,ZodFunction:()=>vp,ZodIntersection:()=>ri,ZodIssueCode:()=>O,ZodLazy:()=>ni,ZodLiteral:()=>oi,ZodMap:()=>Ms,ZodNaN:()=>Os,ZodNativeEnum:()=>si,ZodNever:()=>Ja,ZodNull:()=>ti,ZodNullable:()=>mr,ZodNumber:()=>Yo,ZodObject:()=>Jt,ZodOptional:()=>Ba,ZodParsedType:()=>V,ZodPipeline:()=>Nu,ZodPromise:()=>ro,ZodReadonly:()=>ci,ZodRecord:()=>gp,ZodSchema:()=>ue,ZodSet:()=>Ds,ZodString:()=>to,ZodSymbol:()=>Ts,ZodTransformer:()=>Na,ZodTuple:()=>hr,ZodType:()=>ue,ZodUndefined:()=>ei,ZodUnion:()=>ai,ZodUnknown:()=>Jr,ZodVoid:()=>Rs,addIssueToContext:()=>H,any:()=>aF,array:()=>iF,bigint:()=>KB,boolean:()=>uA,coerce:()=>TF,custom:()=>iA,date:()=>QB,datetimeRegex:()=>nA,defaultErrorMap:()=>Kr,discriminatedUnion:()=>cF,effect:()=>CF,enum:()=>xF,function:()=>gF,getErrorMap:()=>As,getParsedType:()=>pr,instanceof:()=>XB,intersection:()=>dF,isAborted:()=>pp,isAsync:()=>ks,isDirty:()=>hp,isValid:()=>eo,late:()=>ZB,lazy:()=>vF,literal:()=>yF,makeIssue:()=>Bu,map:()=>hF,nan:()=>YB,nativeEnum:()=>bF,never:()=>nF,null:()=>tF,nullable:()=>wF,number:()=>lA,object:()=>sF,objectUtil:()=>ky,oboolean:()=>EF,onumber:()=>kF,optional:()=>_F,ostring:()=>AF,pipeline:()=>IF,preprocess:()=>LF,promise:()=>SF,quotelessJson:()=>CB,record:()=>pF,set:()=>mF,setErrorMap:()=>wB,strictObject:()=>lF,string:()=>sA,symbol:()=>JB,transformer:()=>CF,tuple:()=>fF,undefined:()=>eF,union:()=>uF,unknown:()=>rF,util:()=>fe,void:()=>oF});var fe;(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})(fe||(fe={}));var ky;(function(t){t.mergeShapes=(e,a)=>({...e,...a})})(ky||(ky={}));var V=fe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),pr=t=>{switch(typeof t){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(t)?V.nan:V.number;case"boolean":return V.boolean;case"function":return V.function;case"bigint":return V.bigint;case"symbol":return V.symbol;case"object":return Array.isArray(t)?V.array:t===null?V.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?V.promise:typeof Map<"u"&&t instanceof Map?V.map:typeof Set<"u"&&t instanceof Set?V.set:typeof Date<"u"&&t instanceof Date?V.date:V.object;default:return V.unknown}};var O=fe.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"]),CB=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Qt=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,fe.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()}};Qt.create=t=>new Qt(t);var _B=(t,e)=>{let a;switch(t.code){case O.invalid_type:t.received===V.undefined?a="Required":a=`Expected ${t.expected}, received ${t.received}`;break;case O.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(t.expected,fe.jsonStringifyReplacer)}`;break;case O.unrecognized_keys:a=`Unrecognized key(s) in object: ${fe.joinValues(t.keys,", ")}`;break;case O.invalid_union:a="Invalid input";break;case O.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${fe.joinValues(t.options)}`;break;case O.invalid_enum_value:a=`Invalid enum value. Expected ${fe.joinValues(t.options)}, received '${t.received}'`;break;case O.invalid_arguments:a="Invalid function arguments";break;case O.invalid_return_type:a="Invalid function return type";break;case O.invalid_date:a="Invalid date";break;case O.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}"`:fe.assertNever(t.validation):t.validation!=="regex"?a=`Invalid ${t.validation}`:a="Invalid";break;case O.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 O.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 O.custom:a="Invalid input";break;case O.invalid_intersection_types:a="Intersection results could not be merged";break;case O.not_multiple_of:a=`Number must be a multiple of ${t.multipleOf}`;break;case O.not_finite:a="Number must be finite";break;default:a=e.defaultError,fe.assertNever(t)}return{message:a}},Kr=_B;var J1=Kr;function wB(t){J1=t}function As(){return J1}var Bu=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}},LB=[];function H(t,e){let a=As(),r=Bu({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,a,a===Kr?void 0:Kr].filter(n=>!!n)});t.common.issues.push(r)}var wt=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"}),Xo=t=>({status:"dirty",value:t}),Mt=t=>({status:"valid",value:t}),pp=t=>t.status==="aborted",hp=t=>t.status==="dirty",eo=t=>t.status==="valid",ks=t=>typeof Promise<"u"&&t instanceof Promise;var Z;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Z||(Z={}));var Fa=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}},eA=(t,e)=>{if(eo(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 Qt(t.common.issues);return this._error=a,this._error}}};function le(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 ue=class{get description(){return this._def.description}_getType(e){return pr(e.data)}_getOrReturnCtx(e,a){return a||{common:e.parent.common,data:e.data,parsedType:pr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new wt,ctx:{common:e.parent.common,data:e.data,parsedType:pr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let a=this._parse(e);if(ks(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:pr(e)},n=this._parseSync({data:e,path:r.path,parent:r});return eA(r,n)}"~validate"(e){let a={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pr(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:a});return eo(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=>eo(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:pr(e)},n=this._parse({data:e,path:r.path,parent:r}),o=await(ks(n)?n:Promise.resolve(n));return eA(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:O.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 Na({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 Ba.create(this,this._def)}nullable(){return mr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return en.create(this)}promise(){return ro.create(this,this._def)}or(e){return ai.create([this,e],this._def)}and(e){return ri.create(this,e,this._def)}transform(e){return new Na({...le(this._def),schema:this,typeName:ee.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let a=typeof e=="function"?e:()=>e;return new li({...le(this._def),innerType:this,defaultValue:a,typeName:ee.ZodDefault})}brand(){return new Fu({typeName:ee.ZodBranded,type:this,...le(this._def)})}catch(e){let a=typeof e=="function"?e:()=>e;return new ui({...le(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 Nu.create(this,e)}readonly(){return ci.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},IB=/^c[^\s-]{8,}$/i,AB=/^[0-9a-z]+$/,kB=/^[0-9A-HJKMNP-TV-Z]{26}$/i,EB=/^[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,TB=/^[a-z0-9_-]{21}$/i,RB=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,MB=/^[-+]?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)?)??$/,DB=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,OB="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ey,BB=/^(?:(?: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])$/,FB=/^(?:(?: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])$/,NB=/^(([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]))$/,PB=/^(([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])$/,HB=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,UB=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,aA="((\\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])))",qB=new RegExp(`^${aA}$`);function rA(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 zB(t){return new RegExp(`^${rA(t)}$`)}function nA(t){let e=`${aA}T${rA(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 VB(t,e){return!!((e==="v4"||!e)&&BB.test(t)||(e==="v6"||!e)&&NB.test(t))}function $B(t,e){if(!RB.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 jB(t,e){return!!((e==="v4"||!e)&&FB.test(t)||(e==="v6"||!e)&&PB.test(t))}var to=class t extends ue{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==V.string){let o=this._getOrReturnCtx(e);return H(o,{code:O.invalid_type,expected:V.string,received:o.parsedType}),J}let r=new wt,n;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(n=this._getOrReturnCtx(e,n),H(n,{code:O.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),H(n,{code:O.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?H(n,{code:O.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):s&&H(n,{code:O.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")DB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"email",code:O.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Ey||(Ey=new RegExp(OB,"u")),Ey.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"emoji",code:O.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")EB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"uuid",code:O.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")TB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"nanoid",code:O.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")IB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"cuid",code:O.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")AB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"cuid2",code:O.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")kB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"ulid",code:O.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),H(n,{validation:"url",code:O.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),H(n,{validation:"regex",code:O.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),H(n,{code:O.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),H(n,{code:O.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(n=this._getOrReturnCtx(e,n),H(n,{code:O.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?nA(o).test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{code:O.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?qB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{code:O.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?zB(o).test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{code:O.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?MB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"duration",code:O.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?VB(e.data,o.version)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"ip",code:O.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?$B(e.data,o.alg)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"jwt",code:O.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?jB(e.data,o.version)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"cidr",code:O.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?HB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"base64",code:O.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?UB.test(e.data)||(n=this._getOrReturnCtx(e,n),H(n,{validation:"base64url",code:O.invalid_string,message:o.message}),r.dirty()):fe.assertNever(o);return{status:r.value,value:e.data}}_regex(e,a,r){return this.refinement(n=>e.test(n),{validation:a,code:O.invalid_string,...Z.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Z.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,...Z.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,...Z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Z.errToObj(e)})}regex(e,a){return this._addCheck({kind:"regex",regex:e,...Z.errToObj(a)})}includes(e,a){return this._addCheck({kind:"includes",value:e,position:a?.position,...Z.errToObj(a?.message)})}startsWith(e,a){return this._addCheck({kind:"startsWith",value:e,...Z.errToObj(a)})}endsWith(e,a){return this._addCheck({kind:"endsWith",value:e,...Z.errToObj(a)})}min(e,a){return this._addCheck({kind:"min",value:e,...Z.errToObj(a)})}max(e,a){return this._addCheck({kind:"max",value:e,...Z.errToObj(a)})}length(e,a){return this._addCheck({kind:"length",value:e,...Z.errToObj(a)})}nonempty(e){return this.min(1,Z.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}};to.create=t=>new to({checks:[],typeName:ee.ZodString,coerce:t?.coerce??!1,...le(t)});function GB(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 Yo=class t extends ue{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)!==V.number){let o=this._getOrReturnCtx(e);return H(o,{code:O.invalid_type,expected:V.number,received:o.parsedType}),J}let r,n=new wt;for(let o of this._def.checks)o.kind==="int"?fe.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{code:O.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),H(r,{code:O.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),H(r,{code:O.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()):o.kind==="multipleOf"?GB(e.data,o.value)!==0&&(r=this._getOrReturnCtx(e,r),H(r,{code:O.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{code:O.not_finite,message:o.message}),n.dirty()):fe.assertNever(o);return{status:n.value,value:e.data}}gte(e,a){return this.setLimit("min",e,!0,Z.toString(a))}gt(e,a){return this.setLimit("min",e,!1,Z.toString(a))}lte(e,a){return this.setLimit("max",e,!0,Z.toString(a))}lt(e,a){return this.setLimit("max",e,!1,Z.toString(a))}setLimit(e,a,r,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:a,inclusive:r,message:Z.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Z.toString(e)})}multipleOf(e,a){return this._addCheck({kind:"multipleOf",value:e,message:Z.toString(a)})}finite(e){return this._addCheck({kind:"finite",message:Z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Z.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"&&fe.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)}};Yo.create=t=>new Yo({checks:[],typeName:ee.ZodNumber,coerce:t?.coerce||!1,...le(t)});var Ko=class t extends ue{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)!==V.bigint)return this._getInvalidInput(e);let r,n=new wt;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),H(r,{code:O.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),H(r,{code:O.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),H(r,{code:O.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()):fe.assertNever(o);return{status:n.value,value:e.data}}_getInvalidInput(e){let a=this._getOrReturnCtx(e);return H(a,{code:O.invalid_type,expected:V.bigint,received:a.parsedType}),J}gte(e,a){return this.setLimit("min",e,!0,Z.toString(a))}gt(e,a){return this.setLimit("min",e,!1,Z.toString(a))}lte(e,a){return this.setLimit("max",e,!0,Z.toString(a))}lt(e,a){return this.setLimit("max",e,!1,Z.toString(a))}setLimit(e,a,r,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:a,inclusive:r,message:Z.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:Z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Z.toString(e)})}multipleOf(e,a){return this._addCheck({kind:"multipleOf",value:e,message:Z.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}};Ko.create=t=>new Ko({checks:[],typeName:ee.ZodBigInt,coerce:t?.coerce??!1,...le(t)});var Qo=class extends ue{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==V.boolean){let r=this._getOrReturnCtx(e);return H(r,{code:O.invalid_type,expected:V.boolean,received:r.parsedType}),J}return Mt(e.data)}};Qo.create=t=>new Qo({typeName:ee.ZodBoolean,coerce:t?.coerce||!1,...le(t)});var Jo=class t extends ue{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==V.date){let o=this._getOrReturnCtx(e);return H(o,{code:O.invalid_type,expected:V.date,received:o.parsedType}),J}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return H(o,{code:O.invalid_date}),J}let r=new wt,n;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(n=this._getOrReturnCtx(e,n),H(n,{code:O.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),H(n,{code:O.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):fe.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:Z.toString(a)})}max(e,a){return this._addCheck({kind:"max",value:e.getTime(),message:Z.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}};Jo.create=t=>new Jo({checks:[],coerce:t?.coerce||!1,typeName:ee.ZodDate,...le(t)});var Ts=class extends ue{_parse(e){if(this._getType(e)!==V.symbol){let r=this._getOrReturnCtx(e);return H(r,{code:O.invalid_type,expected:V.symbol,received:r.parsedType}),J}return Mt(e.data)}};Ts.create=t=>new Ts({typeName:ee.ZodSymbol,...le(t)});var ei=class extends ue{_parse(e){if(this._getType(e)!==V.undefined){let r=this._getOrReturnCtx(e);return H(r,{code:O.invalid_type,expected:V.undefined,received:r.parsedType}),J}return Mt(e.data)}};ei.create=t=>new ei({typeName:ee.ZodUndefined,...le(t)});var ti=class extends ue{_parse(e){if(this._getType(e)!==V.null){let r=this._getOrReturnCtx(e);return H(r,{code:O.invalid_type,expected:V.null,received:r.parsedType}),J}return Mt(e.data)}};ti.create=t=>new ti({typeName:ee.ZodNull,...le(t)});var ao=class extends ue{constructor(){super(...arguments),this._any=!0}_parse(e){return Mt(e.data)}};ao.create=t=>new ao({typeName:ee.ZodAny,...le(t)});var Jr=class extends ue{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Mt(e.data)}};Jr.create=t=>new Jr({typeName:ee.ZodUnknown,...le(t)});var Ja=class extends ue{_parse(e){let a=this._getOrReturnCtx(e);return H(a,{code:O.invalid_type,expected:V.never,received:a.parsedType}),J}};Ja.create=t=>new Ja({typeName:ee.ZodNever,...le(t)});var Rs=class extends ue{_parse(e){if(this._getType(e)!==V.undefined){let r=this._getOrReturnCtx(e);return H(r,{code:O.invalid_type,expected:V.void,received:r.parsedType}),J}return Mt(e.data)}};Rs.create=t=>new Rs({typeName:ee.ZodVoid,...le(t)});var en=class t extends ue{_parse(e){let{ctx:a,status:r}=this._processInputParams(e),n=this._def;if(a.parsedType!==V.array)return H(a,{code:O.invalid_type,expected:V.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)&&(H(a,{code:i?O.too_big:O.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&&(H(a,{code:O.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&&(H(a,{code:O.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 Fa(a,i,a.path,s)))).then(i=>wt.mergeArray(r,i));let o=[...a.data].map((i,s)=>n.type._parseSync(new Fa(a,i,a.path,s)));return wt.mergeArray(r,o)}get element(){return this._def.type}min(e,a){return new t({...this._def,minLength:{value:e,message:Z.toString(a)}})}max(e,a){return new t({...this._def,maxLength:{value:e,message:Z.toString(a)}})}length(e,a){return new t({...this._def,exactLength:{value:e,message:Z.toString(a)}})}nonempty(e){return this.min(1,e)}};en.create=(t,e)=>new en({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ee.ZodArray,...le(e)});function Es(t){if(t instanceof Jt){let e={};for(let a in t.shape){let r=t.shape[a];e[a]=Ba.create(Es(r))}return new Jt({...t._def,shape:()=>e})}else return t instanceof en?new en({...t._def,type:Es(t.element)}):t instanceof Ba?Ba.create(Es(t.unwrap())):t instanceof mr?mr.create(Es(t.unwrap())):t instanceof hr?hr.create(t.items.map(e=>Es(e))):t}var Jt=class t extends ue{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=fe.objectKeys(e);return this._cached={shape:e,keys:a},this._cached}_parse(e){if(this._getType(e)!==V.object){let u=this._getOrReturnCtx(e);return H(u,{code:O.invalid_type,expected:V.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 Ja&&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 Fa(n,d,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof Ja){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&&(H(n,{code:O.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 Fa(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,h=await c.value;u.push({key:d,value:h,alwaysSet:c.alwaysSet})}return u}).then(u=>wt.mergeObjectSync(r,u)):wt.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return Z.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:Z.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 fe.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 fe.objectKeys(this.shape))e[r]||(a[r]=this.shape[r]);return new t({...this._def,shape:()=>a})}deepPartial(){return Es(this)}partial(e){let a={};for(let r of fe.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 fe.objectKeys(this.shape))if(e&&!e[r])a[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Ba;)o=o._def.innerType;a[r]=o}return new t({...this._def,shape:()=>a})}keyof(){return oA(fe.objectKeys(this.shape))}};Jt.create=(t,e)=>new Jt({shape:()=>t,unknownKeys:"strip",catchall:Ja.create(),typeName:ee.ZodObject,...le(e)});Jt.strictCreate=(t,e)=>new Jt({shape:()=>t,unknownKeys:"strict",catchall:Ja.create(),typeName:ee.ZodObject,...le(e)});Jt.lazycreate=(t,e)=>new Jt({shape:t,unknownKeys:"strip",catchall:Ja.create(),typeName:ee.ZodObject,...le(e)});var ai=class extends ue{_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 Qt(s.ctx.common.issues));return H(a,{code:O.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 Qt(l));return H(a,{code:O.invalid_union,unionErrors:s}),J}}get options(){return this._def.options}};ai.create=(t,e)=>new ai({options:t,typeName:ee.ZodUnion,...le(e)});var Qr=t=>t instanceof ni?Qr(t.schema):t instanceof Na?Qr(t.innerType()):t instanceof oi?[t.value]:t instanceof ii?t.options:t instanceof si?fe.objectValues(t.enum):t instanceof li?Qr(t._def.innerType):t instanceof ei?[void 0]:t instanceof ti?[null]:t instanceof Ba?[void 0,...Qr(t.unwrap())]:t instanceof mr?[null,...Qr(t.unwrap())]:t instanceof Fu||t instanceof ci?Qr(t.unwrap()):t instanceof ui?Qr(t._def.innerType):[],mp=class t extends ue{_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==V.object)return H(a,{code:O.invalid_type,expected:V.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}):(H(a,{code:O.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=Qr(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,...le(r)})}};function Ty(t,e){let a=pr(t),r=pr(e);if(t===e)return{valid:!0,data:t};if(a===V.object&&r===V.object){let n=fe.objectKeys(e),o=fe.objectKeys(t).filter(s=>n.indexOf(s)!==-1),i={...t,...e};for(let s of o){let l=Ty(t[s],e[s]);if(!l.valid)return{valid:!1};i[s]=l.data}return{valid:!0,data:i}}else if(a===V.array&&r===V.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=Ty(i,s);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return a===V.date&&r===V.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var ri=class extends ue{_parse(e){let{status:a,ctx:r}=this._processInputParams(e),n=(o,i)=>{if(pp(o)||pp(i))return J;let s=Ty(o.value,i.value);return s.valid?((hp(o)||hp(i))&&a.dirty(),{status:a.value,value:s.data}):(H(r,{code:O.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}))}};ri.create=(t,e,a)=>new ri({left:t,right:e,typeName:ee.ZodIntersection,...le(a)});var hr=class t extends ue{_parse(e){let{status:a,ctx:r}=this._processInputParams(e);if(r.parsedType!==V.array)return H(r,{code:O.invalid_type,expected:V.array,received:r.parsedType}),J;if(r.data.length<this._def.items.length)return H(r,{code:O.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&r.data.length>this._def.items.length&&(H(r,{code:O.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 Fa(r,i,r.path,s)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>wt.mergeArray(a,i)):wt.mergeArray(a,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};hr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new hr({items:t,typeName:ee.ZodTuple,rest:null,...le(e)})};var gp=class t extends ue{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!==V.object)return H(r,{code:O.invalid_type,expected:V.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 Fa(r,s,r.path,s)),value:i._parse(new Fa(r,r.data[s],r.path,s)),alwaysSet:s in r.data});return r.common.async?wt.mergeObjectAsync(a,n):wt.mergeObjectSync(a,n)}get element(){return this._def.valueType}static create(e,a,r){return a instanceof ue?new t({keyType:e,valueType:a,typeName:ee.ZodRecord,...le(r)}):new t({keyType:to.create(),valueType:e,typeName:ee.ZodRecord,...le(a)})}},Ms=class extends ue{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!==V.map)return H(r,{code:O.invalid_type,expected:V.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 Fa(r,s,r.path,[u,"key"])),value:o._parse(new Fa(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}}}};Ms.create=(t,e,a)=>new Ms({valueType:e,keyType:t,typeName:ee.ZodMap,...le(a)});var Ds=class t extends ue{_parse(e){let{status:a,ctx:r}=this._processInputParams(e);if(r.parsedType!==V.set)return H(r,{code:O.invalid_type,expected:V.set,received:r.parsedType}),J;let n=this._def;n.minSize!==null&&r.data.size<n.minSize.value&&(H(r,{code:O.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&&(H(r,{code:O.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 Fa(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:Z.toString(a)}})}max(e,a){return new t({...this._def,maxSize:{value:e,message:Z.toString(a)}})}size(e,a){return this.min(e,a).max(e,a)}nonempty(e){return this.min(1,e)}};Ds.create=(t,e)=>new Ds({valueType:t,minSize:null,maxSize:null,typeName:ee.ZodSet,...le(e)});var vp=class t extends ue{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==V.function)return H(a,{code:O.invalid_type,expected:V.function,received:a.parsedType}),J;function r(s,l){return Bu({data:s,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,As(),Kr].filter(u=>!!u),issueData:{code:O.invalid_arguments,argumentsError:l}})}function n(s,l){return Bu({data:s,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,As(),Kr].filter(u=>!!u),issueData:{code:O.invalid_return_type,returnTypeError:l}})}let o={errorMap:a.common.contextualErrorMap},i=a.data;if(this._def.returns instanceof ro){let s=this;return Mt(async function(...l){let u=new Qt([]),c=await s._def.args.parseAsync(l,o).catch(m=>{throw u.addIssue(r(l,m)),u}),d=await Reflect.apply(i,this,c);return await s._def.returns._def.type.parseAsync(d,o).catch(m=>{throw u.addIssue(n(d,m)),u})})}else{let s=this;return Mt(function(...l){let u=s._def.args.safeParse(l,o);if(!u.success)throw new Qt([r(l,u.error)]);let c=Reflect.apply(i,this,u.data),d=s._def.returns.safeParse(c,o);if(!d.success)throw new Qt([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:hr.create(e).rest(Jr.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||hr.create([]).rest(Jr.create()),returns:a||Jr.create(),typeName:ee.ZodFunction,...le(r)})}},ni=class extends ue{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})}};ni.create=(t,e)=>new ni({getter:t,typeName:ee.ZodLazy,...le(e)});var oi=class extends ue{_parse(e){if(e.data!==this._def.value){let a=this._getOrReturnCtx(e);return H(a,{received:a.data,code:O.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}};oi.create=(t,e)=>new oi({value:t,typeName:ee.ZodLiteral,...le(e)});function oA(t,e){return new ii({values:t,typeName:ee.ZodEnum,...le(e)})}var ii=class t extends ue{_parse(e){if(typeof e.data!="string"){let a=this._getOrReturnCtx(e),r=this._def.values;return H(a,{expected:fe.joinValues(r),received:a.parsedType,code:O.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 H(a,{received:a.data,code:O.invalid_enum_value,options:r}),J}return Mt(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})}};ii.create=oA;var si=class extends ue{_parse(e){let a=fe.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==V.string&&r.parsedType!==V.number){let n=fe.objectValues(a);return H(r,{expected:fe.joinValues(n),received:r.parsedType,code:O.invalid_type}),J}if(this._cache||(this._cache=new Set(fe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=fe.objectValues(a);return H(r,{received:r.data,code:O.invalid_enum_value,options:n}),J}return Mt(e.data)}get enum(){return this._def.values}};si.create=(t,e)=>new si({values:t,typeName:ee.ZodNativeEnum,...le(e)});var ro=class extends ue{unwrap(){return this._def.type}_parse(e){let{ctx:a}=this._processInputParams(e);if(a.parsedType!==V.promise&&a.common.async===!1)return H(a,{code:O.invalid_type,expected:V.promise,received:a.parsedType}),J;let r=a.parsedType===V.promise?a.data:Promise.resolve(a.data);return Mt(r.then(n=>this._def.type.parseAsync(n,{path:a.path,errorMap:a.common.contextualErrorMap})))}};ro.create=(t,e)=>new ro({type:t,typeName:ee.ZodPromise,...le(e)});var Na=class extends ue{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=>{H(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"?Xo(l.value):a.value==="dirty"?Xo(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"?Xo(s.value):a.value==="dirty"?Xo(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(!eo(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=>eo(i)?Promise.resolve(n.transform(i.value,o)).then(s=>({status:a.value,value:s})):J);fe.assertNever(n)}};Na.create=(t,e,a)=>new Na({schema:t,typeName:ee.ZodEffects,effect:e,...le(a)});Na.createWithPreprocess=(t,e,a)=>new Na({schema:e,effect:{type:"preprocess",transform:t},typeName:ee.ZodEffects,...le(a)});var Ba=class extends ue{_parse(e){return this._getType(e)===V.undefined?Mt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ba.create=(t,e)=>new Ba({innerType:t,typeName:ee.ZodOptional,...le(e)});var mr=class extends ue{_parse(e){return this._getType(e)===V.null?Mt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};mr.create=(t,e)=>new mr({innerType:t,typeName:ee.ZodNullable,...le(e)});var li=class extends ue{_parse(e){let{ctx:a}=this._processInputParams(e),r=a.data;return a.parsedType===V.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:a.path,parent:a})}removeDefault(){return this._def.innerType}};li.create=(t,e)=>new li({innerType:t,typeName:ee.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...le(e)});var ui=class extends ue{_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 ks(n)?n.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Qt(r.common.issues)},input:r.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Qt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};ui.create=(t,e)=>new ui({innerType:t,typeName:ee.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...le(e)});var Os=class extends ue{_parse(e){if(this._getType(e)!==V.nan){let r=this._getOrReturnCtx(e);return H(r,{code:O.invalid_type,expected:V.nan,received:r.parsedType}),J}return{status:"valid",value:e.data}}};Os.create=t=>new Os({typeName:ee.ZodNaN,...le(t)});var WB=Symbol("zod_brand"),Fu=class extends ue{_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}},Nu=class t extends ue{_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(),Xo(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})}},ci=class extends ue{_parse(e){let a=this._def.innerType._parse(e),r=n=>(eo(n)&&(n.value=Object.freeze(n.value)),n);return ks(a)?a.then(n=>r(n)):r(a)}unwrap(){return this._def.innerType}};ci.create=(t,e)=>new ci({innerType:t,typeName:ee.ZodReadonly,...le(e)});function tA(t,e){let a=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof a=="string"?{message:a}:a}function iA(t,e={},a){return t?ao.create().superRefine((r,n)=>{let o=t(r);if(o instanceof Promise)return o.then(i=>{if(!i){let s=tA(e,r),l=s.fatal??a??!0;n.addIssue({code:"custom",...s,fatal:l})}});if(!o){let i=tA(e,r),s=i.fatal??a??!0;n.addIssue({code:"custom",...i,fatal:s})}}):ao.create()}var ZB={object:Jt.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 XB=(t,e={message:`Input not instance of ${t.name}`})=>iA(a=>a instanceof t,e),sA=to.create,lA=Yo.create,YB=Os.create,KB=Ko.create,uA=Qo.create,QB=Jo.create,JB=Ts.create,eF=ei.create,tF=ti.create,aF=ao.create,rF=Jr.create,nF=Ja.create,oF=Rs.create,iF=en.create,sF=Jt.create,lF=Jt.strictCreate,uF=ai.create,cF=mp.create,dF=ri.create,fF=hr.create,pF=gp.create,hF=Ms.create,mF=Ds.create,gF=vp.create,vF=ni.create,yF=oi.create,xF=ii.create,bF=si.create,SF=ro.create,CF=Na.create,_F=Ba.create,wF=mr.create,LF=Na.createWithPreprocess,IF=Nu.create,AF=()=>sA().optional(),kF=()=>lA().optional(),EF=()=>uA().optional(),TF={string:(t=>to.create({...t,coerce:!0})),number:(t=>Yo.create({...t,coerce:!0})),boolean:(t=>Qo.create({...t,coerce:!0})),bigint:(t=>Ko.create({...t,coerce:!0})),date:(t=>Jo.create({...t,coerce:!0}))};var RF=J;var Ry=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()})]),cA=p.object({kind:p.literal("tooltip"),id:p.string(),anchor:Ry,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()}),dA=p.object({kind:p.literal("highlight"),id:p.string(),anchor:Ry,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()}),yp=p.object({id:p.string(),version:p.number(),routes:p.array(p.string()).optional(),steps:p.array(p.union([cA,dA]))});function MF(t){return yp.parse(t)}var DF=({configUri:t,experiments:e,featureKey:a="smart-canvas-overlay-uri",credentials:r="include"}={})=>async()=>{let n=Rf({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 yp.parse(i)};var xp=K(We(),1),fA=K(sl(),1);function OF({element:t,children:e}){let[a,r]=(0,xp.useState)(null);return(0,xp.useLayoutEffect)(()=>{if(!t){r(null);return}return r(t.getMountNode()),()=>r(null)},[t]),a?(0,fA.createPortal)(e,a):null}function BF(){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e="";for(let a=0;a<16;a++)e+=t[Math.floor(Math.random()*t.length)];return e}var My=class{constructor(){$(this,"sessionId");this.sessionId=BF(),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 bp(){return new My}var E=typeof window<"u"?window:void 0,It=typeof globalThis<"u"?globalThis:E;typeof self>"u"&&(It.self=It),typeof File>"u"&&(It.File=function(){});var lk=Array.prototype,pA=lk.forEach,hA=lk.indexOf,ya=It?.navigator,q=It?.document,ta=It?.location,Zy=It?.fetch,Xy=It!=null&&It.XMLHttpRequest&&"withCredentials"in new It.XMLHttpRequest?It.XMLHttpRequest:void 0,mA=It?.AbortController,ea=ya?.userAgent,ae=E??{},an={DEBUG:!1,LIB_VERSION:"1.302.2"};function gA(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 vA(t){return function(){var e=this,a=arguments;return new Promise((function(r,n){var o=t.apply(e,a);function i(l){gA(o,r,n,i,s,"next",l)}function s(l){gA(o,r,n,i,s,"throw",l)}i(void 0)}))}}function G(){return G=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},G.apply(null,arguments)}function uk(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 FF=["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"],yA=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var a=t.toLowerCase();return FF.concat(e).some((r=>{var n=r.toLowerCase();return a.indexOf(n)!==-1}))},NF=["$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 pe(t,e){return t.indexOf(e)!==-1}var Qp=function(t){return t.trim()},Yy=function(t){return t.replace(/^\$/,"")},PF=Array.isArray,ck=Object.prototype,dk=ck.hasOwnProperty,Jp=ck.toString,Te=PF||function(t){return Jp.call(t)==="[object Array]"},uo=t=>typeof t=="function",mt=t=>t===Object(t)&&!Te(t),Ps=t=>{if(mt(t)){for(var e in t)if(dk.call(t,e))return!1;return!0}return!1},U=t=>t===void 0,ut=t=>Jp.call(t)=="[object String]",Ky=t=>ut(t)&&t.trim().length===0,sn=t=>t===null,Ie=t=>U(t)||sn(t),xr=t=>Jp.call(t)=="[object Number]",co=t=>Jp.call(t)==="[object Boolean]",HF=t=>t instanceof FormData,UF=t=>pe(NF,t);function Qy(t){return t===null||typeof t!="object"}function Rp(t,e){return Object.prototype.toString.call(t)==="[object "+e+"]"}function fk(t){return!U(Event)&&(function(e,a){try{return e instanceof a}catch{return!1}})(t,Event)}var qF=[!0,"true",1,"1","yes"],Dy=t=>pe(qF,t),zF=[!1,"false",0,"0","no"];function gr(t,e,a,r,n){return e>a&&(r.warn("min cannot be greater than max."),e=a),xr(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),gr(n||a,e,a,r))}var Jy=class{constructor(e){this.t={},this.i=e.i,this.o=gr(e.bucketSize,0,100,e.h),this.m=gr(e.refillRate,0,this.o,e.h),this.S=gr(e.refillInterval,0,864e5,e.h)}$(e,a){var r=a-e.lastAccess,n=Math.floor(r/this.S);if(n>0){var o=n*this.m;e.tokens=Math.min(e.tokens+o,this.o),e.lastAccess=e.lastAccess+n*this.S}}consumeRateLimit(e){var a,r=Date.now(),n=String(e),o=this.t[n];return o?this.$(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={}}},Sp,xA,Oy,VF=t=>t instanceof Error;function $F(t){var e=globalThis._posthogChunkIds;if(e){var a=Object.keys(e);return Oy&&a.length===xA||(xA=a.length,Oy=a.reduce(((r,n)=>{Sp||(Sp={});var o=Sp[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,Sp[n]=[u,c];break}}return r}),{})),Oy}}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 vA((function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&Te(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)),G({},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 vA((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,G({},a,{handled:!0}))),s}buildParsingContext(){return{chunkIdMap:$F(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 G({},a,{syntheticException:r==0?a.syntheticException:void 0,mechanism:e,apply:o=>n(o,r),next:o=>n(o,r+1)})}},zs="?";function tx(t,e,a,r,n){var o={platform:t,filename:e,function:a==="<anonymous>"?zs:a,in_app:!0};return U(r)||(o.lineno=r),U(n)||(o.colno=n),o}var pk=(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]:zs,a?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},jF=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,GF=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,WF=/\((\S*)(?::(\d+))(?::(\d+))\)/,ZF=(t,e)=>{var a=jF.exec(t);if(a){var[,r,n,o]=a;return tx(e,r,zs,+n,+o)}var i=GF.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var s=WF.exec(i[2]);s&&(i[2]=s[1],i[3]=s[2],i[4]=s[3])}var[l,u]=pk(i[1]||zs,i[2]);return tx(e,u,l,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},XF=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,YF=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,KF=(t,e)=>{var a=XF.exec(t);if(a){if(a[3]&&a[3].indexOf(" > eval")>-1){var r=YF.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]||zs;return[o,n]=pk(o,n),tx(e,n,o,a[4]?+a[4]:void 0,a[5]?+a[5]:void 0)}},bA=/\(error: (.*)\)/,SA=50;function QF(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(`
460
460
  `),l=o;l<s.length;l++){var u=s[l];if(!(u.length>1024)){var c=bA.test(u)?u.replace(bA,"$1"):u;if(!c.match(/\S*Error: /)){for(var d of a){var h=d(c,t);if(h){i.push(h);break}}if(i.length>=SA)break}}}return(function(m){if(!m.length)return[];var S=Array.from(m);return S.reverse(),S.slice(0,SA).map((b=>{return G({},b,{filename:b.filename||(x=S,x[x.length-1]||{}).filename,function:b.function||zs});var x}))})(i)}}var ax=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,a){var r=ut(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 Rp(e,"DOMException")}isDOMError(e){return Rp(e,"DOMError")}},rx=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}},nx=class{constructor(){}match(e){return Rp(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}}},JF=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,ox=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(JF);return n&&(a=n[1],r=n[2]),[a,r]}},eN=["fatal","error","warning","log","info","debug"];function hk(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 ix=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 fk(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: "+hk(e)}isSeverityLevel(e){return ut(e)&&!Ky(e)&&eN.indexOf(e)>=0}getErrorPropertyFromObject(e){for(var a in e)if(Object.prototype.hasOwnProperty.call(e,a)){var r=e[a];if(VF(r))return r}}getObjectClassName(e){try{var a=Object.getPrototypeOf(e);return a?a.constructor.name:void 0}catch{return}}},sx=class{match(e){return fk(e)}coerce(e,a){var r,n=e.constructor.name;return{type:n,value:n+" captured as exception with keys: "+hk(e),stack:(r=a.syntheticException)==null?void 0:r.stack,synthetic:!0}}},lx=class{match(e){return Qy(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}}},ux=class{match(e){return Rp(e,"PromiseRejectionEvent")}coerce(e,a){var r,n=this.getUnhandledRejectionReason(e);return Qy(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(Qy(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}},mk=function(t,e){var{debugEnabled:a}=e===void 0?{}:e,r={k:function(n){if(E&&(an.DEBUG||ae.POSTHOG_DEBUG||a)&&!U(E.console)&&E.console){for(var o=("__rrweb_original__"in E.console[n])?E.console[n].__rrweb_original__:E.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)=>mk(t+" "+n,o)};return r},z=mk("[PostHog.js]"),ct=z.createLogger,tN=ct("[ExternalScriptsLoader]"),CA=(t,e,a)=>{if(t.config.disable_external_dependency_loading)return tN.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");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)};ae.__PosthogExtensions__=ae.__PosthogExtensions__||{},ae.__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);CA(t,o,a)},ae.__PosthogExtensions__.loadSiteApp=(t,e,a)=>{var r=t.requestRouter.endpointFor("api",e);CA(t,r,a)};var Mp={};function fo(t,e,a){if(Te(t)){if(pA&&t.forEach===pA)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)===Mp)return}}}function De(t,e,a){if(!Ie(t)){if(Te(t))return fo(t,e,a);if(HF(t)){for(var r of t.entries())if(e.call(a,r[1],r[0])===Mp)return}else for(var n in t)if(dk.call(t,n)&&e.call(a,t[n],n)===Mp)return}}var Je=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 fo(a,(function(n){for(var o in n)n[o]!==void 0&&(t[o]=n[o])})),t},js=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 fo(a,(function(n){fo(n,(function(o){t.push(o)}))})),t};function kp(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 _A=function(t){try{return t()}catch{return}},aN=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){z.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),z.critical(n)}}},nb=function(t){var e={};return De(t,(function(a,r){(ut(a)&&a.length>0||xr(a))&&(e[r]=a)})),e};function rN(t,e){return a=t,r=o=>ut(o)&&!sn(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),Te(i)?(l=[],fo(i,(u=>{l.push(o(u))}))):(l={},De(i,((u,c)=>{n.has(u)||(l[c]=o(u,c))}))),l);var l})(a);var a,r,n}var nN=["herokuapp.com","vercel.app","netlify.app"];function oN(t){var e=t?.hostname;if(!ut(e))return!1;var a=e.split(".").slice(-2).join(".");for(var r of nN)if(a===r)return!1;return!0}function gk(t,e){for(var a=0;a<t.length;a++)if(e(t[a]))return t[a]}function nt(t,e,a,r){var{capture:n=!1,passive:o=!0}=r??{};t?.addEventListener(e,a,{capture:n,passive:o})}var vk="$people_distinct_id",Wu="__alias",Zu="__timers",wA="$autocapture_disabled_server_side",cx="$heatmaps_enabled_server_side",LA="$exception_capture_enabled_server_side",dx="$error_tracking_suppression_rules",IA="$error_tracking_capture_extension_exceptions",AA="$web_vitals_enabled_server_side",yk="$dead_clicks_enabled_server_side",kA="$web_vitals_allowed_metrics",By="$session_recording_remote_config",Dp="$sesid",xk="$session_is_sampled",Hs="$enabled_feature_flags",Xu="$early_access_features",fx="$feature_flag_details",Yu="$stored_person_properties",pi="$stored_group_properties",px="$surveys",Cp="$surveys_activated",Op="$flag_call_reported",rn="$user_state",hx="$client_session_props",mx="$capture_rate_limit",gx="$initial_campaign_params",vx="$initial_referrer_info",Bp="$initial_person_info",Fp="$epp",bk="__POSTHOG_TOOLBAR__",Pu="$posthog_cookieless",iN=[vk,Wu,"__cmpns",Zu,"$session_recording_enabled_server_side",cx,Dp,Hs,dx,rn,Xu,fx,pi,Yu,px,Op,hx,mx,gx,vx,Fp,Bp];function EA(t){return t instanceof Element&&(t.id===bk||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function eh(t){return!!t&&t.nodeType===1}function po(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function Sk(t){return!!t&&t.nodeType===3}function Ck(t){return!!t&&t.nodeType===11}function ob(t){return t?Qp(t).split(/\s+/):[]}function TA(t){var e=E?.location.href;return!!(e&&t&&t.some((a=>e.match(a))))}function Np(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 ob(e)}function _k(t){return Ie(t)?null:Qp(t).split(/(\s+)/).filter((e=>rc(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function uc(t){var e="";return yx(t)&&!kk(t)&&t.childNodes&&t.childNodes.length&&De(t.childNodes,(function(a){var r;Sk(a)&&a.textContent&&(e+=(r=_k(a.textContent))!==null&&r!==void 0?r:"")})),Qp(e)}function wk(t){return U(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null;var e}var ib=["a","button","form","input","select","textarea","label"];function Lk(t,e){if(U(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 Ik(t){var e=t.parentNode;return!(!e||!eh(e))&&e}var sN=["next","previous","prev",">","<"],RA=10,MA=[".ph-no-rageclick",".ph-no-capture"];function lN(t,e){if(!E||sb(t))return!1;var a,r,n;if(co(e)?(a=!!e&&MA,r=void 0):(a=(n=e?.css_selector_ignorelist)!==null&&n!==void 0?n:MA,r=e?.content_ignorelist),a===!1)return!1;var{targetElementList:o}=Ak(t,!1);return!(function(i,s){if(i===!1||U(i))return!1;var l;if(i===!0)l=sN;else{if(!Te(i))return!1;if(i.length>RA)return z.error("[PostHog] content_ignorelist array cannot exceed "+RA+" 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((h=>c.includes(h)||d.includes(h)))}))})(r,o.map((i=>{var s;return{safeText:uc(i).toLowerCase(),ariaLabel:((s=i.getAttribute("aria-label"))==null?void 0:s.toLowerCase().trim())||""}})))&&!Lk(o,a)}var sb=t=>!t||po(t,"html")||!eh(t),Ak=(t,e)=>{if(!E||sb(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var a=!1,r=[t],n=t;n.parentNode&&!po(n,"body");)if(Ck(n.parentNode))r.push(n.parentNode.host),n=n.parentNode.host;else{var o=Ik(n);if(!o)break;if(e||ib.indexOf(o.tagName.toLowerCase())>-1)a=!0;else{var i=E.getComputedStyle(o);i&&i.getPropertyValue("cursor")==="pointer"&&(a=!0)}r.push(o),n=o}return{parentIsUsefulElement:a,targetElementList:r}};function uN(t,e,a,r,n){var o,i,s,l;if(a===void 0&&(a=void 0),!E||sb(t)||(o=a)!=null&&o.url_allowlist&&!TA(a.url_allowlist)||(i=a)!=null&&i.url_ignorelist&&TA(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}=Ak(t,r);if(!(function(S,b){var x=b?.element_allowlist;if(U(x))return!0;var f,g=function(y){if(x.some((_=>y.tagName.toLowerCase()===_)))return{v:!0}};for(var v of S)if(f=g(v))return f.v;return!1})(d,a)||!Lk(d,(l=a)==null?void 0:l.css_selector_allowlist))return!1;var h=E.getComputedStyle(t);if(h&&h.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;var m=t.tagName.toLowerCase();switch(m){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&&(ib.indexOf(m)>-1||t.getAttribute("contenteditable")==="true")}}function yx(t){for(var e=t;e.parentNode&&!po(e,"body");e=e.parentNode){var a=Np(e);if(pe(a,"ph-sensitive")||pe(a,"ph-no-capture"))return!1}if(pe(Np(t),"ph-include"))return!0;var r=t.type||"";if(ut(r))switch(r.toLowerCase()){case"hidden":case"password":return!1}var n=t.name||t.id||"";return!(ut(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 kk(t){return!!(po(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||po(t,"select")||po(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Ek="(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})",cN=new RegExp("^(?:"+Ek+")$"),dN=new RegExp(Ek),Tk="\\d{3}-?\\d{2}-?\\d{4}",fN=new RegExp("^("+Tk+")$"),pN=new RegExp("("+Tk+")");function rc(t,e){return e===void 0&&(e=!0),!(Ie(t)||ut(t)&&(t=Qp(t),(e?cN:dN).test((t||"").replace(/[- ]/g,""))||(e?fN:pN).test(t)))}function Rk(t){var e=uc(t);return rc(e=(e+" "+Mk(t)).trim())?e:""}function Mk(t){var e="";return t&&t.childNodes&&t.childNodes.length&&De(t.childNodes,(function(a){var r;if(a&&((r=a.tagName)==null?void 0:r.toLowerCase())==="span")try{var n=uc(a);e=(e+" "+n).trim(),a.childNodes&&a.childNodes.length&&(e=(e+" "+Mk(a)).trim())}catch(o){z.error("[AutoCapture]",o)}})),e}function hN(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=G({},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 kp(l).sort(((c,d)=>{var[h]=c,[m]=d;return h.localeCompare(m)})).forEach((c=>{var[d,h]=c;return u[DA(d.toString())]=DA(h.toString())})),i+=":",i+=kp(u).map((c=>{var[d,h]=c;return d+'="'+h+'"'})).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:mN(a),attr_id:a.attr__id,nth_child:a.nth_child,nth_of_type:a.nth_of_type,attributes:{}};return kp(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 DA(t){return t.replace(/"|\\"/g,'\\"')}function mN(t){var e=t.attr__class;return e?Te(e)?e:ob(e):void 0}var Pp=class{constructor(e){this.disabled=e===!1;var a=mt(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}},Fy="$copy_autocapture",on=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({});var Hp=t=>{var e=q?.createElement("a");return U(e)?null:(e.href=t,e)},gN=function(t,e){var a,r;e===void 0&&(e="&");var n=[];return De(t,(function(o,i){U(o)||U(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)},Up=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(!Te(a)||a.length<2)return"";var i=a[1];try{i=decodeURIComponent(i)}catch{z.error("Skipping decoding for malformed query param: "+i)}return i.replace(/\+/g," ")},cc=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 h=u[d].split("=");Te(h)&&(e.includes(h[0])?c.push(h[0]+"="+a):c.push(u[d]))}var m=l;return s!=null&&(m+="?"+c.join("&")),o!=null&&(m+="#"+o),m},qp=function(t,e){var a=t.match(new RegExp(e+"=([^&]*)"));return a?a[1]:null},OA=ct("[AutoCapture]");function Ny(t,e){return e.length>t?e.slice(0,t)+"...":e}function vN(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!eh(e));return e}function yN(t,e,a,r){var n=t.tagName.toLowerCase(),o={tag_name:n};ib.indexOf(n)>-1&&!a&&(n.toLowerCase()==="a"||n.toLowerCase()==="button"?o.$el_text=Ny(1024,Rk(t)):o.$el_text=Ny(1024,uc(t)));var i=Np(t);i.length>0&&(o.classes=i.filter((function(c){return c!==""}))),De(t.attributes,(function(c){var d;if((!kk(t)||["name","id","class","aria-label"].indexOf(c.name)!==-1)&&(r==null||!r.includes(c.name))&&!e&&rc(c.value)&&(d=c.name,!ut(d)||d.substring(0,10)!=="_ngcontent"&&d.substring(0,7)!=="_nghost")){var h=c.value;c.name==="class"&&(h=ob(h).join(" ")),o["attr__"+c.name]=Ny(1024,h)}}));for(var s=1,l=1,u=t;u=vN(u);)s++,u.tagName===t.tagName&&l++;return o.nth_child=s,o.nth_of_type=l,o}function xN(t,e){for(var a,r,{e:n,maskAllElementAttributes:o,maskAllText:i,elementAttributeIgnoreList:s,elementsChainAsString:l}=e,u=[t],c=t;c.parentNode&&!po(c,"body");)Ck(c.parentNode)?(u.push(c.parentNode.host),c=c.parentNode.host):(u.push(c.parentNode),c=c.parentNode);var d,h=[],m={},S=!1,b=!1;if(De(u,(y=>{var _=yx(y);y.tagName.toLowerCase()==="a"&&(S=y.getAttribute("href"),S=_&&S&&rc(S)&&S),pe(Np(y),"ph-no-capture")&&(b=!0),h.push(yN(y,o,i,s));var w=(function(C){if(!yx(C))return{};var L={};return De(C.attributes,(function(k){if(k.name&&k.name.indexOf("data-ph-capture-attribute")===0){var A=k.name.replace("data-ph-capture-attribute-",""),M=k.value;A&&M&&rc(M)&&(L[A]=M)}})),L})(y);Je(m,w)})),b)return{props:{},explicitNoCapture:b};if(i||(t.tagName.toLowerCase()==="a"||t.tagName.toLowerCase()==="button"?h[0].$el_text=Rk(t):h[0].$el_text=uc(t)),S){var x,f;h[0].attr__href=S;var g=(x=Hp(S))==null?void 0:x.host,v=E==null||(f=E.location)==null?void 0:f.host;g&&v&&g!==v&&(d=S)}return{props:Je({$event_type:n.type,$ce_version:1},l?{}:{$elements:h},{$elements_chain:hN(h)},(a=h[0])!=null&&a.$el_text?{$el_text:(r=h[0])==null?void 0:r.$el_text}:{},d&&n.type==="click"?{$external_click_url:d}:{},m)}}var xx=class{constructor(e){this.P=!1,this.T=null,this.R=!1,this.instance=e,this.rageclicks=new Pp(e.config.rageclick),this.I=null}get F(){var e,a,r=mt(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}C(){if(this.isBrowserSupported()){if(E&&q){var e=r=>{r=r||E?.event;try{this.M(r)}catch(n){OA.error("Failed to capture event",n)}};if(nt(q,"submit",e,{capture:!0}),nt(q,"change",e,{capture:!0}),nt(q,"click",e,{capture:!0}),this.F.capture_copied_text){var a=r=>{r=r||E?.event,this.M(r,Fy)};nt(q,"copy",a,{capture:!0}),nt(q,"cut",a,{capture:!0})}}}else OA.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.P&&(this.C(),this.P=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this.R=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[wA]:!!e.autocapture_opt_out}),this.T=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this.I=e}getElementSelectors(e){var a,r=[];return(a=this.I)==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[wA],n=this.T;if(sn(n)&&!co(r)&&!this.instance.O())return!1;var o=(a=this.T)!==null&&a!==void 0?a:!!r;return!!this.instance.config.autocapture&&!o}M(e,a){if(a===void 0&&(a="$autocapture"),this.isEnabled){var r,n=wk(e);Sk(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())&&lN(n,this.instance.config.rageclick)&&this.M(e,"$rageclick");var o=a===Fy;if(n&&uN(n,e,this.F,o,o?["copy","cut"]:void 0)){var{props:i,explicitNoCapture:s}=xN(n,{e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.F.element_attribute_ignorelist,elementsChainAsString:this.R});if(s)return!1;var l=this.getElementSelectors(n);if(l&&l.length>0&&(i.$element_selectors=l),a===Fy){var u,c=_k(E==null||(u=E.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 uo(q?.querySelectorAll)}};Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return xr(t)&&isFinite(t)&&Math.floor(t)===t});var BA="0123456789abcdef",bx=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+BA.charAt(this.bytes[a]>>>4)+BA.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}},Sx=class{constructor(){this.A=0,this.D=0,this.j=new Cx}generate(){var e=this.generateOrAbort();if(U(e)){this.A=0;var a=this.generateOrAbort();if(U(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.D++,this.D>4398046511103&&(this.A++,this.L())}return bx.fromFieldsV7(this.A,Math.trunc(this.D/Math.pow(2,30)),this.D&Math.pow(2,30)-1,this.j.nextUint32())}L(){this.D=1024*this.j.nextUint32()+(1023&this.j.nextUint32())}},FA,Dk=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};E&&!U(E.crypto)&&crypto.getRandomValues&&(Dk=t=>crypto.getRandomValues(t));var Cx=class{constructor(){this.N=new Uint32Array(8),this.U=1/0}nextUint32(){return this.U>=this.N.length&&(Dk(this.N),this.U=0),this.N[this.U++]}},lo=()=>bN().toString(),bN=()=>(FA||(FA=new Sx)).generate(),Hu="",SN=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function CN(t,e){if(e){var a=(function(n,o){if(o===void 0&&(o=q),Hu)return Hu;if(!o||["localhost","127.0.0.1"].includes(n))return"";for(var i=n.split("."),s=Math.min(i.length,8),l="dmn_chk_"+lo();!Hu&&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",Hu=u)}return Hu})(t);if(!a){var r=(n=>{var o=n.match(SN);return o?o[0]:""})(t);r!==a&&z.info("Warning: cookie subdomain discovery mismatch",r,a),a=r}return a?"; domain=."+a:""}return""}var yr={H:()=>!!q,B:function(t){z.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(yr.q(t))||{}}catch{}return e},G:function(t,e,a,r,n){if(q)try{var o="",i="",s=CN(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&&z.warn("cookieStore warning: large cookie, len="+u.length),q.cookie=u,u}catch{return}},V:function(t,e){if(q!=null&&q.cookie)try{yr.G(t,"",-1,e)}catch{return}}},Py=null,Ge={H:function(){if(!sn(Py))return Py;var t=!0;if(U(E))t=!1;else try{var e="__mplssupport__";Ge.G(e,"xyz"),Ge.q(e)!=='"xyz"'&&(t=!1),Ge.V(e)}catch{t=!1}return t||z.error("localStorage unsupported; falling back to cookie store"),Py=t,t},B:function(t){z.error("localStorage error: "+t)},q:function(t){try{return E?.localStorage.getItem(t)}catch(e){Ge.B(e)}return null},W:function(t){try{return JSON.parse(Ge.q(t))||{}}catch{}return null},G:function(t,e){try{E?.localStorage.setItem(t,JSON.stringify(e))}catch(a){Ge.B(a)}},V:function(t){try{E?.localStorage.removeItem(t)}catch(e){Ge.B(e)}}},_N=["distinct_id",Dp,xk,Fp,Bp],_p=G({},Ge,{W:function(t){try{var e={};try{e=yr.W(t)||{}}catch{}var a=Je(e,JSON.parse(Ge.q(t)||"{}"));return Ge.G(t,a),a}catch{}return null},G:function(t,e,a,r,n,o){try{Ge.G(t,e,void 0,void 0,o);var i={};_N.forEach((s=>{e[s]&&(i[s]=e[s])})),Object.keys(i).length&&yr.G(t,i,a,r,n,o)}catch(s){Ge.B(s)}},V:function(t,e){try{E?.localStorage.removeItem(t),yr.V(t,e)}catch(a){Ge.B(a)}}}),wp={},wN={H:function(){return!0},B:function(t){z.error("memoryStorage error: "+t)},q:function(t){return wp[t]||null},W:function(t){return wp[t]||null},G:function(t,e){wp[t]=e},V:function(t){delete wp[t]}},di=null,Lt={H:function(){if(!sn(di))return di;if(di=!0,U(E))di=!1;else try{var t="__support__";Lt.G(t,"xyz"),Lt.q(t)!=='"xyz"'&&(di=!1),Lt.V(t)}catch{di=!1}return di},B:function(t){z.error("sessionStorage error: ",t)},q:function(t){try{return E?.sessionStorage.getItem(t)}catch(e){Lt.B(e)}return null},W:function(t){try{return JSON.parse(Lt.q(t))||null}catch{}return null},G:function(t,e){try{E?.sessionStorage.setItem(t,JSON.stringify(e))}catch(a){Lt.B(a)}},V:function(t){try{E?.sessionStorage.removeItem(t)}catch(e){Lt.B(e)}}},nn=(function(t){return t[t.PENDING=-1]="PENDING",t[t.DENIED=0]="DENIED",t[t.GRANTED=1]="GRANTED",t})({}),_x=class{constructor(e){this._instance=e}get F(){return this._instance.config}get consent(){return this.J()?nn.DENIED:this.K}isOptedOut(){return this.F.cookieless_mode==="always"||this.consent===nn.DENIED||this.consent===nn.PENDING&&(this.F.opt_out_capturing_by_default||this.F.cookieless_mode==="on_reject")}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===nn.DENIED}optInOut(e){this.Y.G(this.X,e?1:0,this.F.cookie_expiration,this.F.cross_subdomain_cookie,this.F.secure_cookie)}reset(){this.Y.V(this.X,this.F.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 Dy(e)?nn.GRANTED:pe(zF,e)?nn.DENIED:nn.PENDING}get Y(){if(!this.Z){var e=this.F.opt_out_capturing_persistence_type;this.Z=e==="localStorage"?Ge:yr;var a=e==="localStorage"?yr:Ge;a.q(this.X)&&(this.Z.q(this.X)||this.optInOut(Dy(a.q(this.X))),a.V(this.X,this.F.cross_subdomain_cookie))}return this.Z}J(){return!!this.F.respect_dnt&&!!gk([ya?.doNotTrack,ya?.msDoNotTrack,ae.doNotTrack],(e=>Dy(e)))}},Lp=ct("[Dead Clicks]"),LN=()=>!0,IN=t=>{var e,a=!((e=t.instance.persistence)==null||!e.get_property(yk)),r=t.instance.config.capture_dead_clicks;return co(r)?r:!!mt(r)||a},zp=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({[yk]:e?.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.it((()=>{this.et()}))}it(e){var a,r;(a=ae.__PosthogExtensions__)!=null&&a.initDeadClicksAutocapture&&e(),(r=ae.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",(n=>{n?Lp.error("failed to load script",n):e()}))}et(){var e;if(q){if(!this.tt&&(e=ae.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var a=mt(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};a.__onCapture=this.onCapture,this.tt=ae.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,a),this.tt.start(q),Lp.info("starting...")}}else Lp.error("`document` not found. Cannot start.")}stop(){this.tt&&(this.tt.stop(),this.tt=void 0,Lp.info("stopping..."))}},Uu=ct("[ExceptionAutocapture]"),wx=class{constructor(e){var a,r,n;this.rt=()=>{var o;if(E&&this.isEnabled&&(o=ae.__PosthogExtensions__)!=null&&o.errorWrappingFunctions){var i=ae.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,s=ae.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,l=ae.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.st&&this.F.capture_unhandled_errors&&(this.st=i(this.captureException.bind(this))),!this.nt&&this.F.capture_unhandled_rejections&&(this.nt=s(this.captureException.bind(this))),!this.ot&&this.F.capture_console_errors&&(this.ot=l(this.captureException.bind(this)))}catch(u){Uu.error("failed to start",u),this.lt()}}},this._instance=e,this.ut=!((a=this._instance.persistence)==null||!a.props[LA]),this.F=this.ht(),this.vt=new Jy({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:Uu}),this.startIfEnabled()}ht(){var e=this._instance.config.capture_exceptions,a={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return mt(e)?a=G({},a,e):(U(e)?this.ut:e)&&(a=G({},a,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),a}get isEnabled(){return this.F.capture_console_errors||this.F.capture_unhandled_errors||this.F.capture_unhandled_rejections}startIfEnabled(){this.isEnabled&&(Uu.info("enabled"),this.it(this.rt))}it(e){var a,r;(a=ae.__PosthogExtensions__)!=null&&a.errorWrappingFunctions&&e(),(r=ae.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"exception-autocapture",(n=>{if(n)return Uu.error("failed to load script",n);e()}))}lt(){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.ut=!!a||!1,this.F=this.ht(),this._instance.persistence&&this._instance.persistence.register({[LA]:this.ut}),this.startIfEnabled()}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.vt.consumeRateLimit(n)?Uu.info("Skipping exception capture because of client rate limiting.",{exception:n}):this._instance.exceptions.sendExceptionEvent(e)}};function NA(t,e,a){try{if(!(e in t))return()=>{};var r=t[e],n=a(r);return uo(n)&&(n.prototype=n.prototype||{},Object.defineProperties(n,{__posthog_wrapped__:{enumerable:!1,value:!0}})),t[e]=n,()=>{t[e]=r}}catch{return()=>{}}}var Lx=class{constructor(e){var a;this._instance=e,this.dt=(E==null||(a=E.location)==null?void 0:a.pathname)||""}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(z.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.ct&&this.ct(),this.ct=void 0,z.info("History API monitoring stopped")}monitorHistoryChanges(){var e,a;if(E&&E.history){var r=this;(e=E.history.pushState)!=null&&e.__posthog_wrapped__||NA(E.history,"pushState",(n=>function(o,i,s){n.call(this,o,i,s),r.ft("pushState")})),(a=E.history.replaceState)!=null&&a.__posthog_wrapped__||NA(E.history,"replaceState",(n=>function(o,i,s){n.call(this,o,i,s),r.ft("replaceState")})),this.gt()}}ft(e){try{var a,r=E==null||(a=E.location)==null?void 0:a.pathname;if(!r)return;r!==this.dt&&this.isEnabled&&this._instance.capture("$pageview",{navigation_type:e}),this.dt=r}catch(n){z.error("Error capturing "+e+" pageview",n)}}gt(){if(!this.ct){var e=()=>{this.ft("popstate")};nt(E,"popstate",e),this.ct=()=>{E&&E.removeEventListener("popstate",e)}}}},Hy=ct("[SegmentIntegration]");function AN(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()||lo();r.config.get_device_id=u,l.id()&&(r.register({distinct_id:l.id(),$device_id:u()}),r.persistence.set_property(rn,"identified")),n()},s=o.user();"then"in s&&uo(s.then)?s.then((l=>i(l))):i(s)})(t,(()=>{a.register((r=>{Promise&&Promise.resolve||Hy.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()||(Hy.info("No userId set, resetting PostHog"),r.reset()),o.event.userId&&o.event.userId!==r.get_distinct_id()&&(Hy.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 Ok="posthog-js";function Bk(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,h;if(!(o==="*"||o.includes(s.level))||!t.__loaded)return s;s.tags||(s.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());s.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(s.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var S=((l=s.exception)==null?void 0:l.values)||[],b=S.map((f=>G({},f,{stacktrace:f.stacktrace?G({},f.stacktrace,{type:"raw",frames:(f.stacktrace.frames||[]).map((g=>G({},g,{platform:"web:javascript"})))}):void 0}))),x={$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:b,$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:(h=S[0])==null?void 0:h.type,$sentry_tags:s.tags};return a&&r&&(x.$sentry_url=(n||"https://sentry.io/organizations/")+a+"/issues/?project="+r+"&query="+s.event_id),i&&t.exceptions.sendExceptionEvent(x),s}}var Ix=class{constructor(e,a,r,n,o,i){this.name=Ok,this.setupOnce=function(s){s(Bk(e,{organization:a,projectId:r,prefix:n,severityAllowList:o,sendExceptionsToPostHog:i==null||i}))}}},kN=E!=null&&E.location?qp(E.location.hash,"__posthog")||qp(location.hash,"state"):null,PA="_postHogToolbarParams",HA=ct("[Toolbar]"),so=(function(t){return t[t.UNINITIALIZED=0]="UNINITIALIZED",t[t.LOADING=1]="LOADING",t[t.LOADED=2]="LOADED",t})(so||{}),Ax=class{constructor(e){this.instance=e}_t(e){ae.ph_toolbar_state=e}yt(){var e;return(e=ae.ph_toolbar_state)!==null&&e!==void 0?e:so.UNINITIALIZED}maybeLoadToolbar(e,a,r){if(e===void 0&&(e=void 0),a===void 0&&(a=void 0),r===void 0&&(r=void 0),!E||!q)return!1;e=e??E.location,r=r??E.history;try{if(!a){try{E.localStorage.setItem("test","test"),E.localStorage.removeItem("test")}catch{return!1}a=E?.localStorage}var n,o=kN||qp(e.hash,"__posthog")||qp(e.hash,"state"),i=o?_A((()=>JSON.parse(atob(decodeURIComponent(o)))))||_A((()=>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(PA)||"{}")).source="localstorage",delete n.userIntent),!(!n.token||this.instance.config.token!==n.token)&&(this.loadToolbar(n),!0)}catch{return!1}}bt(e){var a=ae.ph_load_toolbar||ae.ph_load_editor;!Ie(a)&&uo(a)?a(e,this.instance):HA.warn("No toolbar load function found")}loadToolbar(e){var a=!(q==null||!q.getElementById(bk));if(!E||a)return!1;var r=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,n=G({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},r?{instrument:!1}:{});if(E.localStorage.setItem(PA,JSON.stringify(G({},n,{source:void 0}))),this.yt()===so.LOADED)this.bt(n);else if(this.yt()===so.UNINITIALIZED){var o;this._t(so.LOADING),(o=ae.__PosthogExtensions__)==null||o.loadExternalDependency==null||o.loadExternalDependency(this.instance,"toolbar",(i=>{if(i)return HA.error("[Toolbar] Failed to load",i),void this._t(so.UNINITIALIZED);this._t(so.LOADED),this.bt(n)})),nt(E,"turbolinks:load",(()=>{this._t(so.UNINITIALIZED),this.loadToolbar(n)}))}return!0}wt(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)}},EN=ct("[TracingHeaders]"),kx=class{constructor(e){this.xt=void 0,this.St=void 0,this.rt=()=>{var a,r;U(this.xt)&&((a=ae.__PosthogExtensions__)==null||(a=a.tracingHeadersPatchFns)==null||a._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),U(this.St)&&((r=ae.__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=ae.__PosthogExtensions__)!=null&&a.tracingHeadersPatchFns&&e(),(r=ae.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"tracing-headers",(n=>{if(n)return EN.error("failed to load script",n);e()}))}startIfEnabledOrStop(){var e,a;this._instance.config.__add_tracing_headers?this.it(this.rt):((e=this.xt)==null||e.call(this),(a=this.St)==null||a.call(this),this.xt=void 0,this.St=void 0)}},Pa="Mobile",Vp="iOS",vr="Android",nc="Tablet",Fk=vr+" "+nc,Nk="iPad",Pk="Apple",Hk=Pk+" Watch",oc="Safari",Vs="BlackBerry",Uk="Samsung",qk=Uk+"Browser",zk=Uk+" Internet",hi="Chrome",TN=hi+" OS",Vk=hi+" "+Vp,lb="Internet Explorer",$k=lb+" "+Pa,ub="Opera",RN=ub+" Mini",cb="Edge",jk="Microsoft "+cb,Us="Firefox",Gk=Us+" "+Vp,ic="Nintendo",sc="PlayStation",qs="Xbox",Wk=vr+" "+Pa,Zk=Pa+" "+oc,Ku="Windows",Ex=Ku+" Phone",UA="Nokia",Tx="Ouya",Xk="Generic",MN=Xk+" "+Pa.toLowerCase(),Yk=Xk+" "+nc.toLowerCase(),Rx="Konqueror",Ht="(\\d+(\\.\\d+)?)",Uy=new RegExp("Version/"+Ht),DN=new RegExp(qs,"i"),ON=new RegExp(sc+" \\w+","i"),BN=new RegExp(ic+" \\w+","i"),db=new RegExp(Vs+"|PlayBook|BB10","i"),FN={"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"},NN=(t,e)=>e&&pe(e,Pk)||(function(a){return pe(a,oc)&&!pe(a,hi)&&!pe(a,vr)})(t),Kk=function(t,e){return e=e||"",pe(t," OPR/")&&pe(t,"Mini")?RN:pe(t," OPR/")?ub:db.test(t)?Vs:pe(t,"IE"+Pa)||pe(t,"WPDesktop")?$k:pe(t,qk)?zk:pe(t,cb)||pe(t,"Edg/")?jk:pe(t,"FBIOS")?"Facebook "+Pa:pe(t,"UCWEB")||pe(t,"UCBrowser")?"UC Browser":pe(t,"CriOS")?Vk:pe(t,"CrMo")||pe(t,hi)?hi:pe(t,vr)&&pe(t,oc)?Wk:pe(t,"FxiOS")?Gk:pe(t.toLowerCase(),Rx.toLowerCase())?Rx:NN(t,e)?pe(t,Pa)?Zk:oc:pe(t,Us)?Us:pe(t,"MSIE")||pe(t,"Trident/")?lb:pe(t,"Gecko")?Us:""},PN={[$k]:[new RegExp("rv:"+Ht)],[jk]:[new RegExp(cb+"?\\/"+Ht)],[hi]:[new RegExp("("+hi+"|CrMo)\\/"+Ht)],[Vk]:[new RegExp("CriOS\\/"+Ht)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Ht)],[oc]:[Uy],[Zk]:[Uy],[ub]:[new RegExp("(Opera|OPR)\\/"+Ht)],[Us]:[new RegExp(Us+"\\/"+Ht)],[Gk]:[new RegExp("FxiOS\\/"+Ht)],[Rx]:[new RegExp("Konqueror[:/]?"+Ht,"i")],[Vs]:[new RegExp(Vs+" "+Ht),Uy],[Wk]:[new RegExp("android\\s"+Ht,"i")],[zk]:[new RegExp(qk+"\\/"+Ht)],[lb]:[new RegExp("(rv:|MSIE )"+Ht)],Mozilla:[new RegExp("rv:"+Ht)]},HN=function(t,e){var a=Kk(t,e),r=PN[a];if(U(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},qA=[[new RegExp(qs+"; "+qs+" (.*?)[);]","i"),t=>[qs,t&&t[1]||""]],[new RegExp(ic,"i"),[ic,""]],[new RegExp(sc,"i"),[sc,""]],[db,[Vs,""]],[new RegExp(Ku,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Ex,""];if(new RegExp(Pa).test(e)&&!/IEMobile\b/.test(e))return[Ku+" "+Pa,""];var a=/Windows NT ([0-9.]+)/i.exec(e);if(a&&a[1]){var r=a[1],n=FN[r]||"";return/arm/i.test(e)&&(n="RT"),[Ku,n]}return[Ku,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){var e=[t[3],t[4],t[5]||"0"];return[Vp,e.join(".")]}return[Vp,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=U(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+vr+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+vr+")","i"),t=>{if(t&&t[2]){var e=[t[2],t[3],t[4]||"0"];return[vr,e.join(".")]}return[vr,""]}],[/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/,[TN,""]],[/Linux|debian/i,["Linux",""]]],zA=function(t){return BN.test(t)?ic:ON.test(t)?sc:DN.test(t)?qs:new RegExp(Tx,"i").test(t)?Tx:new RegExp("("+Ex+"|WPDesktop)","i").test(t)?Ex:/iPad/.test(t)?Nk:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Hk:db.test(t)?Vs:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(UA,"i").test(t)?UA:/(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(Pa).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)?vr:Fk:vr:new RegExp("(pda|"+Pa+")","i").test(t)?MN:new RegExp(nc,"i").test(t)&&!new RegExp(nc+" pc","i").test(t)?Yk:""},Ip="https?://(.*)",Gs=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],UN=js(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],Gs),dc="<masked>",qN=["li_fat_id"];function Qk(t,e,a){if(!q)return{};var r,n=e?js([],Gs,a||[]):[],o=Jk(cc(q.URL,n,dc),t),i=(r={},De(qN,(function(s){var l=yr.q(s);r[s]=l||null})),r);return Je(i,o)}function Jk(t,e){var a=UN.concat(e||[]),r={};return De(a,(function(n){var o=Up(t,n);r[n]=o||null})),r}function eE(t){var e=(function(o){return o?o.search(Ip+"google.([^/?]*)")===0?"google":o.search(Ip+"bing.com")===0?"bing":o.search(Ip+"yahoo.com")===0?"yahoo":o.search(Ip+"duckduckgo.com")===0?"duckduckgo":null:null})(t),a=e!="yahoo"?"q":"p",r={};if(!sn(e)){r.$search_engine=e;var n=q?Up(q.referrer,a):"";n.length&&(r.ph_keyword=n)}return r}function VA(){return navigator.language||navigator.userLanguage}function tE(){return q?.referrer||"$direct"}function aE(t,e){var a=t?js([],Gs,e||[]):[],r=ta?.href.substring(0,1e3);return{r:tE().substring(0,1e3),u:r?cc(r,a,dc):void 0}}function rE(t){var e,{r:a,u:r}=t,n={$referrer:a,$referring_domain:a==null?void 0:a=="$direct"?"$direct":(e=Hp(a))==null?void 0:e.host};if(r){n.$current_url=r;var o=Hp(r);n.$host=o?.host,n.$pathname=o?.pathname;var i=Jk(r);Je(n,i)}if(a){var s=eE(a);Je(n,s)}return n}function nE(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function zN(){try{return new Date().getTimezoneOffset()}catch{return}}function VN(t,e){if(!ea)return{};var a,r,n,o=t?js([],Gs,e||[]):[],[i,s]=(function(l){for(var u=0;u<qA.length;u++){var[c,d]=qA[u],h=c.exec(l),m=h&&(uo(d)?d(h,l):d);if(m)return m}return["",""]})(ea);return Je(nb({$os:i,$os_version:s,$browser:Kk(ea,navigator.vendor),$device:zA(ea),$device_type:(r=ea,n=zA(r),n===Nk||n===Fk||n==="Kobo"||n==="Kindle Fire"||n===Yk?nc:n===ic||n===qs||n===sc||n===Tx?"Console":n===Hk?"Wearable":n?Pa:"Desktop"),$timezone:nE(),$timezone_offset:zN()}),{$current_url:cc(ta?.href,o,dc),$host:ta?.host,$pathname:ta?.pathname,$raw_user_agent:ea.length>1e3?ea.substring(0,997)+"...":ea,$browser_version:HN(ea,navigator.vendor),$browser_language:VA(),$browser_language_prefix:(a=VA(),typeof a=="string"?a.split("-")[0]:void 0),$screen_height:E?.screen.height,$screen_width:E?.screen.width,$viewport_height:E?.innerHeight,$viewport_width:E?.innerWidth,$lib:"web",$lib_version:an.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})}var no=ct("[Web Vitals]"),$A=9e5,Mx=class{constructor(e){var a;this.Et=!1,this.P=!1,this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.$t=()=>{clearTimeout(this.kt),this.N.metrics.length!==0&&(this._instance.capture("$web_vitals",this.N.metrics.reduce(((r,n)=>G({},r,{["$web_vitals_"+n.name+"_event"]:G({},n),["$web_vitals_"+n.name+"_value"]:n.value})),{})),this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.Pt=r=>{var n,o=(n=this._instance.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0);if(U(o))no.error("Could not read session ID. Dropping metrics!");else{this.N=this.N||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var i=this.Tt();U(i)||(Ie(r?.name)||Ie(r?.value)?no.error("Invalid metric received",r):this.Rt&&r.value>=this.Rt?no.error("Ignoring metric with value >= "+this.Rt,r):(this.N.url!==i&&(this.$t(),this.kt=setTimeout(this.$t,this.flushToCaptureTimeoutMs)),U(this.N.url)&&(this.N.url=i),this.N.firstMetricTimestamp=U(this.N.firstMetricTimestamp)?Date.now():this.N.firstMetricTimestamp,r.attribution&&r.attribution.interactionTargetElement&&(r.attribution.interactionTargetElement=void 0),this.N.metrics.push(G({},r,{$current_url:i,$session_id:o.sessionId,$window_id:o.windowId,timestamp:Date.now()})),this.N.metrics.length===this.allowedMetrics.length&&this.$t()))}},this.rt=()=>{var r,n,o,i,s=ae.__PosthogExtensions__;U(s)||U(s.postHogWebVitalsCallbacks)||({onLCP:r,onCLS:n,onFCP:o,onINP:i}=s.postHogWebVitalsCallbacks),r&&n&&o&&i?(this.allowedMetrics.indexOf("LCP")>-1&&r(this.Pt.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&n(this.Pt.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&o(this.Pt.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&i(this.Pt.bind(this)),this.P=!0):no.error("web vitals callbacks not loaded - not starting")},this._instance=e,this.Et=!((a=this._instance.persistence)==null||!a.props[AA]),this.startIfEnabled()}get allowedMetrics(){var e,a,r=mt(this._instance.config.capture_performance)?(e=this._instance.config.capture_performance)==null?void 0:e.web_vitals_allowed_metrics:void 0;return U(r)?((a=this._instance.persistence)==null?void 0:a.props[kA])||["CLS","FCP","INP","LCP"]:r}get flushToCaptureTimeoutMs(){return(mt(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get Rt(){var e=mt(this._instance.config.capture_performance)&&xr(this._instance.config.capture_performance.__web_vitals_max_value)?this._instance.config.capture_performance.__web_vitals_max_value:$A;return 0<e&&e<=6e4?$A:e}get isEnabled(){var e=ta?.protocol;if(e!=="http:"&&e!=="https:")return no.info("Web Vitals are disabled on non-http/https protocols"),!1;var a=mt(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals:co(this._instance.config.capture_performance)?this._instance.config.capture_performance:void 0;return co(a)?a:this.Et}startIfEnabled(){this.isEnabled&&!this.P&&(no.info("enabled, starting..."),this.it(this.rt))}onRemoteConfig(e){var a=mt(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=mt(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[AA]:a}),this._instance.persistence.register({[kA]:r})),this.Et=a,this.startIfEnabled()}it(e){var a,r;(a=ae.__PosthogExtensions__)!=null&&a.postHogWebVitalsCallbacks&&e(),(r=ae.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"web-vitals",(n=>{n?no.error("failed to load script",n):e()}))}Tt(){var e=E?E.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?js([],Gs,r||[]):[];return cc(e,n,dc)}no.error("Could not determine current URL")}},$N=ct("[Heatmaps]");function jA(t){return mt(t)&&"clientX"in t&&"clientY"in t&&xr(t.clientX)&&xr(t.clientY)}var Dx=class{constructor(e){var a;this.Et=!1,this.P=!1,this.It=null,this.instance=e,this.Et=!((a=this.instance.persistence)==null||!a.props[cx]),this.rageclicks=new Pp(e.config.rageclick)}get flushIntervalMilliseconds(){var e=5e3;return mt(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 U(this.instance.config.capture_heatmaps)?U(this.instance.config.enable_heatmaps)?this.Et:this.instance.config.enable_heatmaps:this.instance.config.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.P)return;$N.info("starting..."),this.Ft(),this.Ct()}else{var e;clearInterval((e=this.It)!==null&&e!==void 0?e:void 0),this.Mt(),this.getAndClearBuffer()}}onRemoteConfig(e){var a=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[cx]:a}),this.Et=a,this.startIfEnabled()}getAndClearBuffer(){var e=this.N;return this.N=void 0,e}Ot(e){this.At(e.originalEvent,"deadclick")}Ct(){this.It&&clearInterval(this.It),this.It=(function(e){return e?.visibilityState==="visible"})(q)?setInterval(this.Dt.bind(this),this.flushIntervalMilliseconds):null}Ft(){E&&q&&(this.jt=this.Dt.bind(this),nt(E,"beforeunload",this.jt),this.Lt=e=>this.At(e||E?.event),nt(q,"click",this.Lt,{capture:!0}),this.Nt=e=>this.Ut(e||E?.event),nt(q,"mousemove",this.Nt,{capture:!0}),this.zt=new zp(this.instance,LN,this.Ot.bind(this)),this.zt.startIfEnabled(),this.Ht=this.Ct.bind(this),nt(q,"visibilitychange",this.Ht),this.P=!0)}Mt(){var e;E&&q&&(this.jt&&E.removeEventListener("beforeunload",this.jt),this.Lt&&q.removeEventListener("click",this.Lt,{capture:!0}),this.Nt&&q.removeEventListener("mousemove",this.Nt,{capture:!0}),this.Ht&&q.removeEventListener("visibilitychange",this.Ht),clearTimeout(this.Bt),(e=this.zt)==null||e.stop(),this.P=!1)}qt(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&&eh(c)&&!po(c,"body");){if(c===u)return!1;if(pe(l,E?.getComputedStyle(c).position))return!0;c=Ik(c)}return!1})(wk(e),["fixed","sticky"],o);return{x:e.clientX+(i?0:n),y:e.clientY+(i?0:r),target_fixed:i,type:a}}At(e,a){var r;if(a===void 0&&(a="click"),!EA(e.target)&&jA(e)){var n=this.qt(e,a);(r=this.rageclicks)!=null&&r.isRageClick(e.clientX,e.clientY,new Date().getTime())&&this.Wt(G({},n,{type:"rageclick"})),this.Wt(n)}}Ut(e){!EA(e.target)&&jA(e)&&(clearTimeout(this.Bt),this.Bt=setTimeout((()=>{this.Wt(this.qt(e,"mousemove"))}),500))}Wt(e){if(E){var a=E.location.href,r=this.instance.config.mask_personal_data_properties,n=this.instance.config.custom_personal_data_properties,o=r?js([],Gs,n||[]):[],i=cc(a,o,dc);this.N=this.N||{},this.N[i]||(this.N[i]=[]),this.N[i].push(e)}}Dt(){this.N&&!Ps(this.N)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},Ox=class{constructor(e){this._instance=e}doPageView(e,a){var r,n=this.Gt(e,a);return this.Vt={pathname:(r=E?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:a,timestamp:e},this._instance.scrollManager.resetContext(),n}doPageLeave(e){var a;return this.Gt(e,(a=this.Vt)==null?void 0:a.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.Vt)==null?void 0:e.pageViewId}}Gt(e,a){var r=this.Vt;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(!(U(i)||U(s)||U(l)||U(u)||U(c)||U(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 h=i<=1?1:gr(s/i,0,1,z),m=i<=1?1:gr(l/i,0,1,z),S=u<=1?1:gr(c/u,0,1,z),b=u<=1?1:gr(d/u,0,1,z);n=Je(n,{$prev_pageview_last_scroll:s,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:m,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:S,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:b})}}return r.pathname&&(n.$prev_pageview_pathname=r.pathname),r.timestamp&&(n.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),n}},Ha=Uint8Array,Ut=Uint16Array,$s=Uint32Array,fb=new Ha([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]),pb=new Ha([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]),GA=new Ha([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),oE=function(t,e){for(var a=new Ut(31),r=0;r<31;++r)a[r]=e+=1<<t[r-1];var n=new $s(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]},iE=oE(fb,2),jN=iE[0],Bx=iE[1];jN[28]=258,Bx[258]=28;for(Fx=oE(pb,0)[1],$p=new Ut(32768),Oe=0;Oe<32768;++Oe)oo=(43690&Oe)>>>1|(21845&Oe)<<1,oo=(61680&(oo=(52428&oo)>>>2|(13107&oo)<<2))>>>4|(3855&oo)<<4,$p[Oe]=((65280&oo)>>>8|(255&oo)<<8)>>>1;var oo,Fx,$p,Oe,ec=function(t,e,a){for(var r=t.length,n=0,o=new Ut(e);n<r;++n)++o[t[n]-1];var i,s=new Ut(e);for(n=0;n<e;++n)s[n]=s[n-1]+o[n-1]<<1;if(a){i=new Ut(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,h=d|(1<<c)-1;d<=h;++d)i[$p[d]>>>l]=u}else for(i=new Ut(r),n=0;n<r;++n)i[n]=$p[s[t[n]-1]++]>>>15-t[n];return i},mi=new Ha(288);for(Oe=0;Oe<144;++Oe)mi[Oe]=8;for(Oe=144;Oe<256;++Oe)mi[Oe]=9;for(Oe=256;Oe<280;++Oe)mi[Oe]=7;for(Oe=280;Oe<288;++Oe)mi[Oe]=8;var jp=new Ha(32);for(Oe=0;Oe<32;++Oe)jp[Oe]=5;var GN=ec(mi,9,0),WN=ec(jp,5,0),sE=function(t){return(t/8>>0)+(7&t&&1)},lE=function(t,e,a){(a==null||a>t.length)&&(a=t.length);var r=new(t instanceof Ut?Ut:t instanceof $s?$s:Ha)(a-e);return r.set(t.subarray(e,a)),r},tn=function(t,e,a){a<<=7&e;var r=e/8>>0;t[r]|=a,t[r+1]|=a>>>8},qu=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},qy=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 Ha(0),0];if(n==1){var i=new Ha(a[0].s+1);return i[a[0].s]=1,[i,1]}a.sort((function(_,w){return _.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 h=o[0].s;for(r=1;r<n;++r)o[r].s>h&&(h=o[r].s);var m=new Ut(h+1),S=Nx(a[c-1],m,0);if(S>e){r=0;var b=0,x=S-e,f=1<<x;for(o.sort((function(_,w){return m[w.s]-m[_.s]||_.f-w.f}));r<n;++r){var g=o[r].s;if(!(m[g]>e))break;b+=f-(1<<S-m[g]),m[g]=e}for(b>>>=x;b>0;){var v=o[r].s;m[v]<e?b-=1<<e-m[v]++-1:++r}for(;r>=0&&b;--r){var y=o[r].s;m[y]==e&&(--m[y],++b)}S=e}return[new Ha(m),S]},Nx=function(t,e,a){return t.s==-1?Math.max(Nx(t.l,e,a+1),Nx(t.r,e,a+1)):e[t.s]=a},WA=function(t){for(var e=t.length;e&&!t[--e];);for(var a=new Ut(++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]},zu=function(t,e){for(var a=0,r=0;r<e.length;++r)a+=t[r]*e[r];return a},Px=function(t,e,a){var r=a.length,n=sE(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)},ZA=function(t,e,a,r,n,o,i,s,l,u,c){tn(e,c++,a),++n[256];for(var d=qy(n,15),h=d[0],m=d[1],S=qy(o,15),b=S[0],x=S[1],f=WA(h),g=f[0],v=f[1],y=WA(b),_=y[0],w=y[1],C=new Ut(19),L=0;L<g.length;++L)C[31&g[L]]++;for(L=0;L<_.length;++L)C[31&_[L]]++;for(var k=qy(C,7),A=k[0],M=k[1],T=19;T>4&&!A[GA[T-1]];--T);var R,B,F,P,Y=u+5<<3,N=zu(n,mi)+zu(o,jp)+i,W=zu(n,h)+zu(o,b)+i+14+3*T+zu(C,A)+(2*C[16]+3*C[17]+7*C[18]);if(Y<=N&&Y<=W)return Px(e,c,t.subarray(l,l+u));if(tn(e,c,1+(W<N)),c+=2,W<N){R=ec(h,m,0),B=h,F=ec(b,x,0),P=b;var Q=ec(A,M,0);for(tn(e,c,v-257),tn(e,c+5,w-1),tn(e,c+10,T-4),c+=14,L=0;L<T;++L)tn(e,c+3*L,A[GA[L]]);c+=3*T;for(var aa=[g,_],dt=0;dt<2;++dt){var qt=aa[dt];for(L=0;L<qt.length;++L){var j=31&qt[L];tn(e,c,Q[j]),c+=A[j],j>15&&(tn(e,c,qt[L]>>>5&127),c+=qt[L]>>>12)}}}else R=GN,B=mi,F=WN,P=jp;for(L=0;L<s;++L)if(r[L]>255){j=r[L]>>>18&31,qu(e,c,R[j+257]),c+=B[j+257],j>7&&(tn(e,c,r[L]>>>23&31),c+=fb[j]);var ne=31&r[L];qu(e,c,F[ne]),c+=P[ne],ne>3&&(qu(e,c,r[L]>>>5&8191),c+=pb[ne])}else qu(e,c,R[r[L]]),c+=B[r[L]];return qu(e,c,R[256]),c+B[256]},ZN=new $s([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),XN=(function(){for(var t=new $s(256),e=0;e<256;++e){for(var a=e,r=9;--r;)a=(1&a&&3988292384)^a>>>1;t[e]=a}return t})(),YN=function(t,e,a,r,n){return(function(o,i,s,l,u,c){var d=o.length,h=new Ha(l+d+5*(1+Math.floor(d/7e3))+u),m=h.subarray(l,h.length-u),S=0;if(!i||d<8)for(var b=0;b<=d;b+=65535){var x=b+65535;x<d?S=Px(m,S,o.subarray(b,x)):(m[b]=c,S=Px(m,S,o.subarray(b,d)))}else{for(var f=ZN[i-1],g=f>>>13,v=8191&f,y=(1<<s)-1,_=new Ut(32768),w=new Ut(y+1),C=Math.ceil(s/3),L=2*C,k=function(Hh){return(o[Hh]^o[Hh+1]<<C^o[Hh+2]<<L)&y},A=new $s(25e3),M=new Ut(288),T=new Ut(32),R=0,B=0,F=(b=0,0),P=0,Y=0;b<d;++b){var N=k(b),W=32767&b,Q=w[N];if(_[W]=Q,w[N]=W,P<=b){var aa=d-b;if((R>7e3||F>24576)&&aa>423){S=ZA(o,m,0,A,M,T,B,F,Y,b-Y,S),F=R=B=0,Y=b;for(var dt=0;dt<286;++dt)M[dt]=0;for(dt=0;dt<30;++dt)T[dt]=0}var qt=2,j=0,ne=v,At=W-Q&32767;if(aa>2&&N==k(b-At))for(var dn=Math.min(g,aa)-1,Fh=Math.min(32767,b),Nh=Math.min(258,aa);At<=Fh&&--ne&&W!=Q;){if(o[b+qt]==o[b+qt-At]){for(var fn=0;fn<Nh&&o[b+fn]==o[b+fn-At];++fn);if(fn>qt){if(qt=fn,j=At,fn>dn)break;var YE=Math.min(At,fn-2),hS=0;for(dt=0;dt<YE;++dt){var Ph=b-At+dt+32768&32767,mS=Ph-_[Ph]+32768&32767;mS>hS&&(hS=mS,Q=Ph)}}}At+=(W=Q)-(Q=_[W])+32768&32767}if(j){A[F++]=268435456|Bx[qt]<<18|Fx[j];var gS=31&Bx[qt],vS=31&Fx[j];B+=fb[gS]+pb[vS],++M[257+gS],++T[vS],P=b+qt,++R}else A[F++]=o[b],++M[o[b]]}}S=ZA(o,m,c,A,M,T,B,F,Y,b-Y,S)}return lE(h,0,l+sE(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)},zy=function(t,e,a){for(;a;++e)t[e]=a,a>>>=8};function KN(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=XN[255&u^l[c]]^u>>>8;s=u},d:function(){return 4294967295^s}}})(),r=t.length;a.p(t);var n,o=YN(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&&zy(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),zy(o,i-8,a.d()),zy(o,i-4,r),o}var QN=function(t){var e,a,r,n,o="";for(e=a=0,r=(t=(t+"").replace(/\r\n/g,`
461
461
  `).replace(/\r/g,`
462
462
  `)).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),sn(s)||(a>e&&(o+=t.substring(e,a)),o+=s,e=a=n+1)}return a>e&&(o+=t.substring(e,t.length)),o},JN=!!Xy||!!Zy,XA="text/plain",Gp=function(t,e,a){var r;a===void 0&&(a=!0);var[n,o]=t.split("?"),i=G({},e),s=(r=o?.split("&").map((u=>{var c,[d,h]=u.split("="),m=a&&(c=i[d])!==null&&c!==void 0?c:h;return delete i[d],d+"="+m})))!==null&&r!==void 0?r:[],l=gN(i);return l&&s.push(l),n+"?"+s.join("&")},Qu=(t,e)=>JSON.stringify(t,((a,r)=>typeof r=="bigint"?r.toString():r),e),Vy=t=>{var{data:e,compression:a}=t;if(e){if(a===on.GZipJS){var r=KN((function(l,u){var c=l.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(l);for(var d=new Ha(l.length+(l.length>>>1)),h=0,m=function(f){d[h++]=f},S=0;S<c;++S){if(h+5>d.length){var b=new Ha(h+8+(c-S<<1));b.set(d),d=b}var x=l.charCodeAt(S);x<128||u?m(x):x<2048?(m(192|x>>>6),m(128|63&x)):x>55295&&x<57344?(m(240|(x=65536+(1047552&x)|1023&l.charCodeAt(++S))>>>18),m(128|x>>>12&63),m(128|x>>>6&63),m(128|63&x)):(m(224|x>>>12),m(128|x>>>6&63),m(128|63&x))}return lE(d,0,h)})(Qu(e)),{mtime:0}),n=new Blob([r],{type:XA});return{contentType:XA,body:n,estimatedSize:n.size}}if(a===on.Base64){var o=(function(l){var u,c,d,h,m,S="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b=0,x=0,f="",g=[];if(!l)return l;l=QN(l);do u=(m=l.charCodeAt(b++)<<16|l.charCodeAt(b++)<<8|l.charCodeAt(b++))>>18&63,c=m>>12&63,d=m>>6&63,h=63&m,g[x++]=S.charAt(u)+S.charAt(c)+S.charAt(d)+S.charAt(h);while(b<l.length);switch(f=g.join(""),l.length%3){case 1:f=f.slice(0,-2)+"==";break;case 2:f=f.slice(0,-1)+"="}return f})(Qu(e)),i=(l=>"data="+encodeURIComponent(typeof l=="string"?l:Qu(l)))(o);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}var s=Qu(e);return{contentType:"application/json",body:s,estimatedSize:new Blob([s]).size}}},Ep=[];Zy&&Ep.push({transport:"fetch",method:t=>{var e,a,{contentType:r,body:n,estimatedSize:o}=(e=Vy(t))!==null&&e!==void 0?e:{},i=new Headers;De(t.headers,(function(c,d){i.append(d,c)})),r&&i.append("Content-Type",r);var s=t.url,l=null;if(mA){var u=new mA;l={signal:u.signal,timeout:setTimeout((()=>u.abort()),t.timeout)}}Zy(s,G({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 h={statusCode:c.status,text:d};if(c.status===200)try{h.json=JSON.parse(d)}catch(m){z.error(m)}t.callback==null||t.callback(h)})))).catch((c=>{z.error(c),t.callback==null||t.callback({statusCode:0,text:c})})).finally((()=>l?clearTimeout(l.timeout):null))}}),Xy&&Ep.push({transport:"XHR",method:t=>{var e,a=new Xy;a.open(t.method||"GET",t.url,!0);var{contentType:r,body:n}=(e=Vy(t))!==null&&e!==void 0?e:{};De(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)}}),ya!=null&&ya.sendBeacon&&Ep.push({transport:"sendBeacon",method:t=>{var e=Gp(t.url,{beacon:"1"});try{var a,{contentType:r,body:n}=(a=Vy(t))!==null&&a!==void 0?a:{},o=typeof n=="string"?new Blob([n],{type:r}):n;ya.sendBeacon(e,o)}catch{}}});var Wp=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 YA(t,e,a){return Qu({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:a})}var uE={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=>Wp(a,r))))),not_regex:(t,e)=>e.every((a=>t.every((r=>!Wp(a,r))))),icontains:(t,e)=>e.map(Ap).some((a=>t.map(Ap).some((r=>a.includes(r))))),not_icontains:(t,e)=>e.map(Ap).every((a=>t.map(Ap).every((r=>!a.includes(r)))))},Ap=t=>t.toLowerCase();function cE(t,e){return!t||Object.entries(t).every((a=>{var[r,n]=a,o=e?.[r];if(U(o)||sn(o))return!1;var i=[String(o)],s=uE[n.operator];return!!s&&s(n.values,i)}))}var $y=ct("[Error tracking]"),Hx=class{constructor(e){var a,r;this.Jt=[],this.Kt=new ex([new ax,new ux,new nx,new rx,new sx,new ix,new ox,new lx],QF("web:javascript",ZF,KF)),this._instance=e,this.Jt=(a=(r=this._instance.persistence)==null?void 0:r.get_property(dx))!==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.Jt=o,this._instance.persistence&&this._instance.persistence.register({[dx]:this.Jt,[IA]:i})}get Yt(){var e,a=!!this._instance.get_property(IA),r=this._instance.config.error_tracking.captureExtensionExceptions;return(e=r??a)!==null&&e!==void 0&&e}buildProperties(e,a){return this.Kt.buildFromUnknown(e,{syntheticException:a?.syntheticException,mechanism:{handled:a?.handled}})}sendExceptionEvent(e){var a=e.$exception_list;if(this.Xt(a)){if(this.Qt(a))return void $y.info("Skipping exception capture because a suppression rule matched");if(!this.Yt&&this.Zt(a))return void $y.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ti(a))return void $y.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent"})}Qt(e){if(e.length===0)return!1;var a=e.reduce(((r,n)=>{var{type:o,value:i}=n;return ut(o)&&o.length>0&&r.$exception_types.push(o),ut(i)&&i.length>0&&r.$exception_values.push(i),r}),{$exception_types:[],$exception_values:[]});return this.Jt.some((r=>{var n=r.values.map((o=>{var i,s=uE[o.operator],l=Te(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)}))}Zt(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://")))}ti(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}Xt(e){return!Ie(e)&&Te(e)}},er=ct("[FeatureFlags]"),Vu=ct("[FeatureFlags]",{debugEnabled:!0}),jy="$active_feature_flags",Bs="$override_feature_flags",KA="$feature_flag_payloads",$u="$override_feature_flag_payloads",QA="$feature_flag_request_id",JA="$feature_flag_evaluated_at",ek=t=>{var e={};for(var[a,r]of kp(t||{}))r&&(e[a]=r);return e},eP=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]})))):er.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),t},tP=(function(t){return t.FeatureFlags="feature_flags",t.Recordings="recordings",t})({}),Ux=class{constructor(e){this.ii=!1,this.ei=!1,this.ri=!1,this.si=!1,this.ni=!1,this.oi=!1,this.ai=!1,this._instance=e,this.featureFlagEventHandlers=[]}li(){var e=this._instance.config.evaluation_environments;return e!=null&&e.length?e.filter((a=>{var r=a&&typeof a=="string"&&a.trim().length>0;return r||er.error("Invalid evaluation environment found:",a,"Expected non-empty string"),r})):[]}ui(){return this.li().length>0}flags(){if(this._instance.config.__preview_remote_config)this.oi=!0;else{var e=!this.hi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.vi({disableFlags:e})}}get hasLoadedFlags(){return this.ei}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(fx),a=this._instance.get_property(Bs),r=this._instance.get_property($u);if(!r&&!a)return e||{};var n=Je({},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=U(c)?(s=u?.enabled)!==null&&s!==void 0&&s:!!c,h=U(c)?u.variant:typeof c=="string"?c:void 0,m=r?.[i],S=G({},u,{enabled:d,variant:d?h??u?.variant:void 0});d!==u?.enabled&&(S.original_enabled=u?.enabled),h!==u?.variant&&(S.original_variant=u?.variant),m&&(S.metadata=G({},u?.metadata,{payload:m,original_payload:u==null||(l=u.metadata)==null?void 0:l.payload})),n[i]=S}return this.ii||(er.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:r,finalDetails:n}),this.ii=!0),n}getFlagVariants(){var e=this._instance.get_property(Hs),a=this._instance.get_property(Bs);if(!a)return e||{};for(var r=Je({},e),n=Object.keys(a),o=0;o<n.length;o++)r[n[o]]=a[n[o]];return this.ii||(er.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:a,finalFlags:r}),this.ii=!0),r}getFlagPayloads(){var e=this._instance.get_property(KA),a=this._instance.get_property($u);if(!a)return e||{};for(var r=Je({},e||{}),n=Object.keys(a),o=0;o<n.length;o++)r[n[o]]=a[n[o]];return this.ii||(er.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:a,finalPayloads:r}),this.ii=!0),r}reloadFeatureFlags(){this.si||this._instance.config.advanced_disable_feature_flags||this.hi||(this.hi=setTimeout((()=>{this.vi()}),5))}di(){clearTimeout(this.hi),this.hi=void 0}ensureFlagsLoaded(){this.ei||this.ri||this.hi||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.si=e}vi(e){var a;if(this.di(),!this._instance.O())if(this.ri)this.ni=!0;else{var r={token:this._instance.config.token,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:G({},((a=this._instance.persistence)==null?void 0:a.get_initial_props())||{},this._instance.get_property(Yu)||{}),group_properties:this._instance.get_property(pi)};(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(r.disable_flags=!0),this.ui()&&(r.evaluation_environments=this.li());var n=this._instance.config.__preview_remote_config,o=n?"/flags/?v=2":"/flags/?v=2&config=true",i=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",s=this._instance.requestRouter.endpointFor("flags",o+i);n&&(r.timezone=nE()),this.ri=!0,this._instance.ci({method:"POST",url:s,data:r,compression:this._instance.config.disable_compression?void 0:on.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:l=>{var u,c,d=!0;if(l.statusCode===200&&(this.ni||(this.$anon_distinct_id=void 0),d=!1),this.ri=!1,this.oi||(this.oi=!0,this._instance.fi((c=l.json)!==null&&c!==void 0?c:{})),!r.disable_flags||this.ni)if(this.ai=!d,l.json&&(u=l.json.quotaLimited)!=null&&u.includes(tP.FeatureFlags))er.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 h;r.disable_flags||this.receivedFeatureFlags((h=l.json)!==null&&h!==void 0?h:{},d),this.ni&&(this.ni=!1,this.vi())}}})}}getFeatureFlag(e,a){if(a===void 0&&(a={}),this.ei||this.getFlags()&&this.getFlags().length>0){var r=this.getFlagVariants()[e],n=""+r,o=this._instance.get_property(QA)||void 0,i=this._instance.get_property(JA)||void 0,s=this._instance.get_property(Op)||{};if((a.send_event||!("send_event"in a))&&(!(e in s)||!s[e].includes(n))){var l,u,c,d,h,m,S,b,x;Te(s[e])?s[e].push(n):s[e]=[n],(l=this._instance.persistence)==null||l.register({[Op]:s});var f=this.getFeatureFlagDetails(e),g={$feature_flag:e,$feature_flag_response:r,$feature_flag_payload:this.getFeatureFlagPayload(e)||null,$feature_flag_request_id:o,$feature_flag_evaluated_at:i,$feature_flag_bootstrapped_response:((u=this._instance.config.bootstrap)==null||(u=u.featureFlags)==null?void 0:u[e])||null,$feature_flag_bootstrapped_payload:((c=this._instance.config.bootstrap)==null||(c=c.featureFlagPayloads)==null?void 0:c[e])||null,$used_bootstrap_value:!this.ai};U(f==null||(d=f.metadata)==null?void 0:d.version)||(g.$feature_flag_version=f.metadata.version);var v,y=(h=f==null||(m=f.reason)==null?void 0:m.description)!==null&&h!==void 0?h:f==null||(S=f.reason)==null?void 0:S.code;y&&(g.$feature_flag_reason=y),f!=null&&(b=f.metadata)!=null&&b.id&&(g.$feature_flag_id=f.metadata.id),U(f?.original_variant)&&U(f?.original_enabled)||(g.$feature_flag_original_response=U(f.original_variant)?f.original_enabled:f.original_variant),f!=null&&(x=f.metadata)!=null&&x.original_payload&&(g.$feature_flag_original_payload=f==null||(v=f.metadata)==null?void 0:v.original_payload),this._instance.capture("$feature_flag_called",g)}return r}er.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){return this.getFlagPayloads()[e]}getRemoteConfigPayload(e,a){var r=this._instance.config.token,n={distinct_id:this._instance.get_distinct_id(),token:r};this.ui()&&(n.evaluation_environments=this.li()),this._instance.ci({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2&config=true"),data:n,compression:this._instance.config.disable_compression?void 0:on.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.ei||this.getFlags()&&this.getFlags().length>0){var r=this.getFeatureFlag(e,a);return U(r)?void 0:!!r}er.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.ei=!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=eP(i),h=d.flags,m=d.featureFlags,S=d.featureFlagPayloads;if(m){var b=i.requestId,x=i.evaluatedAt;if(Te(m)){er.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var f={};if(m)for(var g=0;g<m.length;g++)f[m[g]]=!0;s&&s.register({[jy]:m,[Hs]:f})}else{var v=m,y=S,_=h;i.errorsWhileComputingFlags&&(v=G({},l,v),y=G({},u,y),_=G({},c,_)),s&&s.register(G({[jy]:Object.keys(ek(v)),[Hs]:v||{},[KA]:y||{},[fx]:_||{}},b?{[QA]:b}:{},x?{[JA]:x}:{}))}}})(e,this._instance.persistence,r,n,o),this.pi(a)}}override(e,a){a===void 0&&(a=!1),er.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:a})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return er.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister(Bs),this._instance.persistence.unregister($u),this.pi(),Vu.info("All overrides cleared");if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var a,r=e;if(this.ii=!!((a=r.suppressWarning)!==null&&a!==void 0&&a),"flags"in r){if(r.flags===!1)this._instance.persistence.unregister(Bs),Vu.info("Flag overrides cleared");else if(r.flags){if(Te(r.flags)){for(var n={},o=0;o<r.flags.length;o++)n[r.flags[o]]=!0;this._instance.persistence.register({[Bs]:n})}else this._instance.persistence.register({[Bs]:r.flags});Vu.info("Flag overrides set",{flags:r.flags})}}return"payloads"in r&&(r.payloads===!1?(this._instance.persistence.unregister($u),Vu.info("Payload overrides cleared")):r.payloads&&(this._instance.persistence.register({[$u]:r.payloads}),Vu.info("Payload overrides set",{payloads:r.payloads}))),void this.pi()}this.pi()}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.ei){var{flags:a,flagVariants:r}=this.gi();e(a,r)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,a,r){var n,o=(this._instance.get_property(Xu)||[]).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=G({},this.getFlagVariants(),{[e]:a});(n=this._instance.persistence)==null||n.register({[jy]:Object.keys(ek(l)),[Hs]:l}),this.pi()}getEarlyAccessFeatures(e,a,r){a===void 0&&(a=!1);var n=this._instance.get_property(Xu),o=r?"&"+r.map((i=>"stage="+i)).join("&"):"";if(n&&!a)return e(n);this._instance.ci({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(Xu),(l=this._instance.persistence)==null||l.register({[Xu]:u}),e(u)}}})}gi(){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)),{})}}pi(e){var{flags:a,flagVariants:r}=this.gi();this.featureFlagEventHandlers.forEach((n=>n(a,r,{errorsLoading:e})))}setPersonPropertiesForFlags(e,a){a===void 0&&(a=!0);var r=this._instance.get_property(Yu)||{};this._instance.register({[Yu]:G({},r,e)}),a&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(Yu)}setGroupPropertiesForFlags(e,a){a===void 0&&(a=!0);var r=this._instance.get_property(pi)||{};Object.keys(r).length!==0&&Object.keys(r).forEach((n=>{r[n]=G({},r[n],e[n]),delete e[n]})),this._instance.register({[pi]:G({},r,e)}),a&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var a=this._instance.get_property(pi)||{};this._instance.register({[pi]:G({},a,{[e]:{}})})}else this._instance.unregister(pi)}reset(){this.ei=!1,this.ri=!1,this.si=!1,this.ni=!1,this.oi=!1,this.ai=!1,this.$anon_distinct_id=void 0,this.di(),this.ii=!1}},aP=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],tc=class{constructor(e,a){this.F=e,this.props={},this.mi=!1,this.yi=(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.bi(e),this.load(),e.debug&&z.info("Persistence loaded",e.persistence,G({},this.props)),this.update_config(e,e,a),this.save()}isDisabled(){return!!this.wi}bi(e){aP.indexOf(e.persistence.toLowerCase())===-1&&(z.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var a=e.persistence.toLowerCase();return a==="localstorage"&&Ge.H()?Ge:a==="localstorage+cookie"&&_p.H()?_p:a==="sessionstorage"&&Lt.H()?Lt:a==="memory"?wN:a==="cookie"?yr:_p.H()?_p:yr}properties(){var e={};return De(this.props,(function(a,r){if(r===Hs&&mt(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,(sn(i=iN)?l:hA&&i.indexOf===hA?i.indexOf(s)!=-1:(De(i,(function(u){if(l||(l=u===s))return Mp})),l))||(e[r]=a);var i,s,l})),e}load(){if(!this.wi){var e=this.Y.W(this.yi);e&&(this.props=Je({},e))}}save(){this.wi||this.Y.G(this.yi,this.props,this.xi,this.Si,this.Ei,this.F.debug)}remove(){this.Y.V(this.yi,!1),this.Y.V(this.yi,!0)}clear(){this.remove(),this.props={}}register_once(e,a,r){if(mt(e)){U(a)&&(a="None"),this.xi=U(r)?this.$i:r;var n=!1;if(De(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(mt(e)){this.xi=U(a)?this.$i:a;var r=!1;if(De(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.mi){var e=Qk(this.F.custom_campaign_params,this.F.mask_personal_data_properties,this.F.custom_personal_data_properties);Ps(nb(e))||this.register(e),this.mi=!0}}update_search_keyword(){var e;this.register((e=q?.referrer)?eE(e):{})}update_referrer_info(){var e;this.register_once({$referrer:tE(),$referring_domain:q!=null&&q.referrer&&((e=Hp(q.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[gx]||this.props[vx]||this.register_once({[Bp]:aE(this.F.mask_personal_data_properties,this.F.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};De([vx,gx],(i=>{var s=this.props[i];s&&De(s,(function(l,u){e["$initial_"+Yy(u)]=l}))}));var a,r,n=this.props[Bp];if(n){var o=(a=rE(n),r={},De(a,(function(i,s){r["$initial_"+Yy(s)]=i})),r);Je(e,o)}return e}safe_merge(e){return De(this.props,(function(a,r){r in e||(e[r]=a)})),e}update_config(e,a,r){if(this.$i=this.xi=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){var n=this.bi(e),o=this.props;this.clear(),this.Y=n,this.props=o,this.save()}}set_disabled(e){this.wi=e,this.wi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Si&&(this.Si=e,this.remove(),this.save())}set_secure(e){e!==this.Ei&&(this.Ei=e,this.remove(),this.save())}set_event_timer(e,a){var r=this.props[Zu]||{};r[e]=a,this.props[Zu]=r,this.save()}remove_event_timer(e){var a=(this.props[Zu]||{})[e];return U(a)||(delete this.props[Zu][e],this.save()),a}get_property(e){return this.props[e]}set_property(e,a){this.props[e]=a,this.save()}},ju=(function(t){return t.Activation="events",t.Cancellation="cancelEvents",t})({}),sz=(function(t){return t.Button="button",t.Tab="tab",t.Selector="selector",t})({}),lz=(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})({}),uz=(function(t){return t.Top="top",t.Left="left",t.Right="right",t.Bottom="bottom",t})({}),Gy=(function(t){return t.Popover="popover",t.API="api",t.Widget="widget",t.ExternalSurvey="external_survey",t})({}),cz=(function(t){return t.Open="open",t.MultipleChoice="multiple_choice",t.SingleChoice="single_choice",t.Rating="rating",t.Link="link",t})({}),dz=(function(t){return t.NextQuestion="next_question",t.End="end",t.ResponseBased="response_based",t.SpecificQuestion="specific_question",t})({}),fz=(function(t){return t.Once="once",t.Recurring="recurring",t.Always="always",t})({}),Tp=(function(t){return t.SHOWN="survey shown",t.DISMISSED="survey dismissed",t.SENT="survey sent",t})({}),tk=(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})({}),dE=(function(t){return t.Popover="popover",t.Inline="inline",t})({}),lc=class{constructor(){this.ki={},this.ki={}}on(e,a){return this.ki[e]||(this.ki[e]=[]),this.ki[e].push(a),()=>{this.ki[e]=this.ki[e].filter((r=>r!==a))}}emit(e,a){for(var r of this.ki[e]||[])r(a);for(var n of this.ki["*"]||[])n(e,a)}};function Fs(t,e,a){if(Ie(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 qx=class{constructor(e){this.Pi=new lc,this.Ti=(a,r)=>this.Ri(a,r)&&this.Ii(a,r)&&this.Fi(a,r)&&this.Ci(a,r),this.Ri=(a,r)=>r==null||!r.event||a?.event===r?.event,this._instance=e,this.Mi=new Set,this.Oi=new Set}init(){var e;if(!U((e=this._instance)==null?void 0:e.Ai)){var a;(a=this._instance)==null||a.Ai(((r,n)=>{this.on(r,n)}))}}register(e){var a,r;if(!U((a=this._instance)==null?void 0:a.Ai)&&(e.forEach((i=>{var s,l;(s=this.Oi)==null||s.add(i),(l=i.steps)==null||l.forEach((u=>{var c;(c=this.Mi)==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.Mi.has(e)||this.Mi.has(a?.event))&&this.Oi&&((r=this.Oi)==null?void 0:r.size)>0&&this.Oi.forEach((n=>{this.Di(a,n)&&this.Pi.emit("actionCaptured",n.name)}))}ji(e){this.onAction("actionCaptured",(a=>e(a)))}Di(e,a){if(a?.steps==null)return!1;for(var r of a.steps)if(this.Ti(e,r))return!0;return!1}onAction(e,a){return this.Pi.on(e,a)}Ii(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"||!Fs(n,a.url,a.url_matching||"contains"))return!1}return!0}Fi(e,a){return!!this.Li(e,a)&&!!this.Ni(e,a)&&!!this.Ui(e,a)}Li(e,a){var r;if(a==null||!a.href)return!0;var n=this.zi(e);if(n.length>0)return n.some((s=>Fs(s.href,a.href,a.href_matching||"exact")));var o,i=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!i&&Fs((o=i.match(/(?::|")href="(.*?)"/))?o[1]:"",a.href,a.href_matching||"exact")}Ni(e,a){var r;if(a==null||!a.text)return!0;var n=this.zi(e);if(n.length>0)return n.some((u=>Fs(u.text,a.text,a.text_matching||"exact")||Fs(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=[],h=/(?::|")text="(.*?)"/g;!Ie(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),i=a.text,s=a.text_matching||"exact",o.some((u=>Fs(u,i,s))))}Ui(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}zi(e){var a;return(e==null||(a=e.properties)==null?void 0:a.$elements)==null?[]:e?.properties.$elements}Ci(e,a){return a==null||!a.properties||a.properties.length===0||cE(a.properties.reduce(((r,n)=>{var o=Te(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)}},_e=ct("[Surveys]"),zx="seenSurvey_",rP=(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},ak=t=>{var e=""+zx+t.id;return t.current_iteration&&t.current_iteration>0&&(e=""+zx+t.id+"_"+t.current_iteration),e},nP=[Gy.Popover,Gy.Widget,Gy.API],oP={ignoreConditions:!1,ignoreDelay:!1,displayType:dE.Popover},Vx=class{constructor(e){this._instance=e,this.Hi=new Map,this.Bi=new Map,this.qi=new Map}Wi(e,a){return!!e&&cE(e.propertyFilters,a?.properties)}Gi(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}Vi(e,a,r){var n,o=(r===ju.Activation?this.Hi:this.Bi).get(e),i=[];return(n=this._instance)==null||n.getSurveys((s=>{i=s.filter((l=>o?.includes(l.id)))})),i.filter((s=>{var l,u=(l=s.conditions)==null||(l=l[r])==null||(l=l.values)==null?void 0:l.find((c=>c.name===e));return this.Wi(u,a)}))}register(e){var a;U((a=this._instance)==null?void 0:a.Ai)||(this.Ji(e),this.Ki(e))}Ki(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.Yi==null&&(this.Yi=new qx(this._instance),this.Yi.init(),this.Yi.ji((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.Yi)==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.qi.get(u.name);c&&c.push(r.id),this.qi.set(u.name,c||[r.id])}})))})))}Ji(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.Ai(((o,i)=>{this.onEvent(o,i)})),this.Hi=this.Gi(e,ju.Activation),this.Bi=this.Gi(e,ju.Cancellation))}onEvent(e,a){var r,n=((r=this._instance)==null||(r=r.persistence)==null?void 0:r.props[Cp])||[];if(Tp.SHOWN===e&&a&&n.length>0){var o;_e.info("survey event matched, removing survey from activated surveys",{event:e,eventPayload:a,existingActivatedSurveys:n});var i=a==null||(o=a.properties)==null?void 0:o.$survey_id;if(i){var s=n.indexOf(i);s>=0&&(n.splice(s,1),this.Xi(n))}}else{if(this.Bi.has(e)){var l=this.Vi(e,a,ju.Cancellation);l.length>0&&(_e.info("cancel event matched, cancelling surveys",{event:e,surveysToCancel:l.map((c=>c.id))}),l.forEach((c=>{var d,h=n.indexOf(c.id);h>=0&&n.splice(h,1),(d=this._instance)==null||d.cancelPendingSurvey(c.id)})),this.Xi(n))}if(this.Hi.has(e)){_e.info("survey event name matched",{event:e,eventPayload:a,surveys:this.Hi.get(e)});var u=this.Vi(e,a,ju.Activation);this.Xi(n.concat(u.map((c=>c.id))||[]))}}}onAction(e){var a,r=((a=this._instance)==null||(a=a.persistence)==null?void 0:a.props[Cp])||[];this.qi.has(e)&&this.Xi(r.concat(this.qi.get(e)||[]))}Xi(e){var a;_e.info("updating activated surveys",{activatedSurveys:e}),(a=this._instance)==null||(a=a.persistence)==null||a.register({[Cp]:[...new Set(e)]})}getSurveys(){var e,a=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[Cp];return a||[]}getEventToSurveys(){return this.Hi}Qi(){return this.Yi}},$x=class{constructor(e){this.Zi=void 0,this._surveyManager=null,this.te=!1,this.ie=!1,this.ee=[],this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var a=e.surveys;if(Ie(a))return _e.warn("Flags not loaded yet. Not loading surveys.");var r=Te(a);this.Zi=r?a.length>0:a,_e.info("flags response received, isSurveysEnabled: "+this.Zi),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],a=0;a<localStorage.length;a++){var r=localStorage.key(a);(r!=null&&r.startsWith(zx)||r!=null&&r.startsWith("inProgressSurvey_"))&&e.push(r)}e.forEach((n=>localStorage.removeItem(n)))}loadIfEnabled(){if(!this._surveyManager)if(this.ie)_e.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)_e.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())_e.info("Not loading surveys in cookieless mode without consent.");else{var e=ae?.__PosthogExtensions__;if(e){if(!U(this.Zi)||this._instance.config.advanced_enable_surveys){var a=this.Zi||this._instance.config.advanced_enable_surveys;this.ie=!0;try{var r=e.generateSurveys;if(r)return void this.re(r,a);var n=e.loadExternalDependency;if(!n)return void this.se("PostHog loadExternalDependency extension not found.");n(this._instance,"surveys",(o=>{o||!e.generateSurveys?this.se("Could not load surveys script",o):this.re(e.generateSurveys,a)}))}catch(o){throw this.se("Error initializing surveys",o),o}finally{this.ie=!1}}}else _e.error("PostHog Extensions not found.")}}re(e,a){this._surveyManager=e(this._instance,a),this._surveyEventReceiver=new Vx(this._instance),_e.info("Surveys loaded successfully"),this.ne({isLoaded:!0})}se(e,a){_e.error(e,a),this.ne({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.ee.push(e),this._surveyManager&&this.ne({isLoaded:!0}),()=>{this.ee=this.ee.filter((a=>a!==e))}}getSurveys(e,a){if(a===void 0&&(a=!1),this._instance.config.disable_surveys)return _e.info("Disabled. Not loading surveys."),e([]);var r=this._instance.get_property(px);if(r&&!a)return e(r,{isLoaded:!0});if(this.te)return e([],{isLoaded:!1,error:"Surveys are already being loaded"});try{this.te=!0,this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:n=>{var o;this.te=!1;var i=n.statusCode;if(i!==200||!n.json){var s="Surveys API could not be loaded, status: "+i;return _e.error(s),e([],{isLoaded:!1,error:s})}var l,u=n.json.surveys||[],c=u.filter((d=>(function(h){return!(!h.start_date||h.end_date)})(d)&&((function(h){var m;return!((m=h.conditions)==null||(m=m.events)==null||(m=m.values)==null||!m.length)})(d)||(function(h){var m;return!((m=h.conditions)==null||(m=m.actions)==null||(m=m.values)==null||!m.length)})(d))));return c.length>0&&((l=this._surveyEventReceiver)==null||l.register(c)),(o=this._instance.persistence)==null||o.register({[px]:u}),e(u,{isLoaded:!0})}})}catch(n){throw this.te=!1,n}}ne(e){for(var a of this.ee)try{if(!e.isLoaded)return a([],e);this.getSurveys(a)}catch(r){_e.error("Error in survey callback",r)}}getActiveMatchingSurveys(e,a){if(a===void 0&&(a=!1),!Ie(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,a);_e.warn("init was not called")}oe(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}ae(e){if(Ie(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var a=typeof e=="string"?this.oe(e):e;return a?this._surveyManager.checkSurveyEligibility(a):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(Ie(this._surveyManager))return _e.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var a=this.ae(e);return{visible:a.eligible,disabledReason:a.reason}}canRenderSurveyAsync(e,a){return Ie(this._surveyManager)?(_e.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.ae(i);r({visible:s.eligible,disabledReason:s.reason})}else r({visible:!1,disabledReason:"Survey not found"})}),a)}))}renderSurvey(e,a){var r;if(Ie(this._surveyManager))_e.warn("init was not called");else{var n=typeof e=="string"?this.oe(e):e;if(n!=null&&n.id)if(nP.includes(n.type)){var o=q?.querySelector(a);if(o)return(r=n.appearance)!=null&&r.surveyPopupDelaySeconds?(_e.info("Rendering survey "+n.id+" with delay of "+n.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var i,s;_e.info("Rendering survey "+n.id+" with delay of "+((i=n.appearance)==null?void 0:i.surveyPopupDelaySeconds)+" seconds"),(s=this._surveyManager)==null||s.renderSurvey(n,o),_e.info("Survey "+n.id+" rendered")}),1e3*n.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(n,o);_e.warn("Survey element not found")}else _e.warn("Surveys of type "+n.type+" cannot be rendered in the app");else _e.warn("Survey not found")}}displaySurvey(e,a){var r;if(Ie(this._surveyManager))_e.warn("init was not called");else{var n=this.oe(e);if(n){var o=n;if((r=n.appearance)!=null&&r.surveyPopupDelaySeconds&&a.ignoreDelay&&(o=G({},n,{appearance:G({},n.appearance,{surveyPopupDelaySeconds:0})})),a.ignoreConditions===!1){var i=this.canRenderSurvey(n);if(!i.visible)return void _e.warn("Survey is not eligible to be displayed: ",i.disabledReason)}a.displayType!==dE.Inline?this._surveyManager.handlePopoverSurvey(o):this.renderSurvey(o,a.selector)}else _e.warn("Survey not found")}}cancelPendingSurvey(e){Ie(this._surveyManager)?_e.warn("init was not called"):this._surveyManager.cancelSurvey(e)}},rk=ct("[RateLimiter]"),jx=class{constructor(e){var a,r;this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var o=n.text;if(o&&o.length)try{(JSON.parse(o).quota_limited||[]).forEach((i=>{rk.info((i||"events")+" is quota limited."),this.serverLimits[i]=new Date().getTime()+6e4}))}catch(i){return void rk.warn('could not rate limit - continuing. Error: "'+i?.message+'"',{text:o})}},this.instance=e,this.captureEventsPerSecond=((a=e.config.rate_limiting)==null?void 0:a.events_per_second)||10,this.captureEventsBurstLimit=Math.max(((r=e.config.rate_limiting)==null?void 0:r.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond),this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}clientRateLimitContext(e){var a,r,n;e===void 0&&(e=!1);var o=new Date().getTime(),i=(a=(r=this.instance.persistence)==null?void 0:r.get_property(mx))!==null&&a!==void 0?a:{tokens:this.captureEventsBurstLimit,last:o};i.tokens+=(o-i.last)/1e3*this.captureEventsPerSecond,i.last=o,i.tokens>this.captureEventsBurstLimit&&(i.tokens=this.captureEventsBurstLimit);var s=i.tokens<1;return s||e||(i.tokens=Math.max(0,i.tokens-1)),!s||this.lastEventRateLimited||e||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+this.captureEventsPerSecond+" events per second and "+this.captureEventsBurstLimit+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=s,(n=this.instance.persistence)==null||n.set_property(mx,i),{isRateLimited:s,remainingTokens:i.tokens}}isServerRateLimited(e){var a=this.serverLimits[e||"events"]||!1;return a!==!1&&new Date().getTime()<a}},fi=ct("[RemoteConfig]"),Gx=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=ae._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.config}le(e){var a,r;(a=ae.__PosthogExtensions__)!=null&&a.loadExternalDependency?(r=ae.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"remote-config",(()=>e(this.remoteConfig))):(fi.error("PostHog Extensions not found. Cannot load remote config."),e())}ue(e){this._instance.ci({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 fi.info("Using preloaded remote config",this.remoteConfig),void this.fi(this.remoteConfig);if(this._instance.O())return void fi.warn("Remote config is disabled. Falling back to local config.");this.le((e=>{if(!e)return fi.info("No config found after loading remote JS config. Falling back to JSON."),void this.ue((a=>{this.fi(a)}));this.fi(e)}))}catch(e){fi.error("Error loading remote config",e)}}fi(e){e?this._instance.config.__preview_remote_config?(this._instance.fi(e),e.hasFeatureFlags!==!1&&this._instance.featureFlags.ensureFlagsLoaded()):fi.info("__preview_remote_config is disabled. Logging config instead",e):fi.error("Failed to fetch remote config from PostHog.")}},Wx=3e3,Zx=class{constructor(e,a){this.he=!0,this.ve=[],this.de=gr(a?.flush_interval_ms||Wx,250,5e3,z.createLogger("flush interval"),Wx),this.ce=e}enqueue(e){this.ve.push(e),this.fe||this.pe()}unload(){this.ge();var e=this.ve.length>0?this._e():{},a=Object.values(e);[...a.filter((r=>r.url.indexOf("/e")===0)),...a.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.ce(G({},r,{transport:"sendBeacon"}))}))}enable(){this.he=!1,this.pe()}pe(){var e=this;this.he||(this.fe=setTimeout((()=>{if(this.ge(),this.ve.length>0){var a=this._e(),r=function(){var o=a[n],i=new Date().getTime();o.data&&Te(o.data)&&De(o.data,(s=>{s.offset=Math.abs(s.timestamp-i),delete s.timestamp})),e.ce(o)};for(var n in a)r()}}),this.de))}ge(){clearTimeout(this.fe),this.fe=void 0}_e(){var e={};return De(this.ve,(a=>{var r,n=a,o=(n?n.batchKey:null)||n.url;U(e[o])&&(e[o]=G({},n,{data:[]})),(r=e[o].data)==null||r.push(n.data)})),this.ve=[],e}},iP=["retriesPerformedSoFar"],Xx=class{constructor(e){this.me=!1,this.ye=3e3,this.ve=[],this._instance=e,this.ve=[],this.be=!0,!U(E)&&"onLine"in E.navigator&&(this.be=E.navigator.onLine,this.we=()=>{this.be=!0,this.Dt()},this.xe=()=>{this.be=!1},nt(E,"online",this.we),nt(E,"offline",this.xe))}get length(){return this.ve.length}retriableRequest(e){var{retriesPerformedSoFar:a}=e,r=uk(e,iP);xr(a)&&a>0&&(r.url=Gp(r.url,{retry_count:a})),this._instance.ci(G({},r,{callback:n=>{n.statusCode!==200&&(n.statusCode<400||n.statusCode>=500)&&(a??0)<10?this.Se(G({retriesPerformedSoFar:a},r)):r.callback==null||r.callback(n)}}))}Se(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.ve.push({retryAt:n,requestOptions:e});var o="Enqueued failed request for retry in "+r;navigator.onLine||(o+=" (Browser is offline)"),z.warn(o),this.me||(this.me=!0,this.Ee())}Ee(){if(this.$e&&clearTimeout(this.$e),this.ve.length===0)return this.me=!1,void(this.$e=void 0);this.$e=setTimeout((()=>{this.be&&this.ve.length>0&&this.Dt(),this.Ee()}),this.ye)}Dt(){var e=Date.now(),a=[],r=this.ve.filter((o=>o.retryAt<e||(a.push(o),!1)));if(this.ve=a,r.length>0)for(var{requestOptions:n}of r)this.retriableRequest(n)}unload(){for(var{requestOptions:e}of(this.$e&&(clearTimeout(this.$e),this.$e=void 0),this.me=!1,U(E)||(this.we&&(E.removeEventListener("online",this.we),this.we=void 0),this.xe&&(E.removeEventListener("offline",this.xe),this.xe=void 0)),this.ve))try{this._instance.ci(G({},e,{transport:"sendBeacon"}))}catch(a){z.error(a)}this.ve=[]}},Yx=class{constructor(e){this.ke=()=>{var a,r,n,o;this.Pe||(this.Pe={});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.Pe.lastScrollY=Math.ceil(s),this.Pe.maxScrollY=Math.max(s,(a=this.Pe.maxScrollY)!==null&&a!==void 0?a:0),this.Pe.maxScrollHeight=Math.max(l,(r=this.Pe.maxScrollHeight)!==null&&r!==void 0?r:0),this.Pe.lastContentY=u,this.Pe.maxContentY=Math.max(u,(n=this.Pe.maxContentY)!==null&&n!==void 0?n:0),this.Pe.maxContentHeight=Math.max(c,(o=this.Pe.maxContentHeight)!==null&&o!==void 0?o:0)},this._instance=e}getContext(){return this.Pe}resetContext(){var e=this.Pe;return setTimeout(this.ke,0),e}startMeasuringScrollPosition(){nt(E,"scroll",this.ke,{capture:!0}),nt(E,"scrollend",this.ke,{capture:!0}),nt(E,"resize",this.ke)}scrollElement(){if(!this._instance.config.scroll_root_selector)return E?.document.documentElement;var e=Te(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=E?.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 E&&(E.scrollY||E.pageYOffset||E.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return E&&(E.scrollX||E.pageXOffset||E.document.documentElement.scrollLeft)||0}},sP=t=>aE(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties),Zp=class{constructor(e,a,r,n){this.Te=o=>{var i=this.Re();if(!i||i.sessionId!==o){var s={sessionId:o,props:this.Ie(this._instance)};this.Fe.register({[hx]:s})}},this._instance=e,this.Ce=a,this.Fe=r,this.Ie=n||sP,this.Ce.onSessionId(this.Te)}Re(){return this.Fe.props[hx]}getSetOnceProps(){var e,a=(e=this.Re())==null?void 0:e.props;return a?"r"in a?rE(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 De(nb(this.getSetOnceProps()),((a,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+Yy(r)]=a})),e}},Wy=ct("[SessionId]"),Xp=class{on(e,a){return this.Me.on(e,a)}constructor(e,a,r){var n;if(this.Oe=[],this.Ae=void 0,this.Me=new lc,this.De=(c,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.F=e.config,this.Fe=e.persistence,this.je=void 0,this.Le=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.Ne=a||lo,this.Ue=r||lo;var o=this.F.persistence_name||this.F.token,i=this.F.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*gr(i,60,36e3,Wy.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.ze(),this.He="ph_"+o+"_window_id",this.Be="ph_"+o+"_primary_window_exists",this.qe()){var s=Lt.W(this.He),l=Lt.W(this.Be);s&&!l?this.je=s:Lt.V(this.He),Lt.G(this.Be,!0)}if((n=this.F.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.F.bootstrap.sessionID);this.We(this.F.bootstrap.sessionID,new Date().getTime(),u)}catch(c){Wy.error("Invalid sessionID in bootstrap",c)}this.Ge()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return U(this.Oe)&&(this.Oe=[]),this.Oe.push(e),this.Le&&e(this.Le,this.je),()=>{this.Oe=this.Oe.filter((a=>a!==e))}}qe(){return this.F.persistence!=="memory"&&!this.Fe.wi&&Lt.H()}Ve(e){e!==this.je&&(this.je=e,this.qe()&&Lt.G(this.He,e))}Je(){return this.je?this.je:this.qe()?Lt.W(this.He):null}We(e,a,r){e===this.Le&&a===this._sessionActivityTimestamp&&r===this._sessionStartTimestamp||(this._sessionStartTimestamp=r,this._sessionActivityTimestamp=a,this.Le=e,this.Fe.register({[Dp]:[a,e,r]}))}Ke(){var e=this.Fe.props[Dp];return Te(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.We(null,null,null)}destroy(){clearTimeout(this.Ye),this.Ye=void 0,this.Ae&&E&&(E.removeEventListener("beforeunload",this.Ae,{capture:!1}),this.Ae=void 0),this.Oe=[]}Ge(){this.Ae=()=>{this.qe()&&Lt.V(this.Be)},nt(E,"beforeunload",this.Ae,{capture:!1})}checkAndGetSessionAndWindowId(e,a){if(e===void 0&&(e=!1),a===void 0&&(a=null),this.F.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.Ke(),s=this.Je(),l=xr(i)&&i>0&&Math.abs(r-i)>864e5,u=!1,c=!o,d=!c&&!e&&this.De(r,n);c||d||l?(o=this.Ne(),s=this.Ue(),Wy.info("new session ID generated",{sessionId:o,windowId:s,changeReason:{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}}),i=r,u=!0):s||(s=this.Ue(),u=!0);var h=n===0||!e||l?r:n,m=i===0?new Date().getTime():i;return this.Ve(s),this.We(o,h,m),e||this.ze(),u&&this.Oe.forEach((S=>S(o,s,u?{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}:void 0))),{sessionId:o,windowId:s,sessionStartTimestamp:m,changeReason:u?{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:n}}ze(){clearTimeout(this.Ye),this.Ye=setTimeout((()=>{var[e]=this.Ke();if(this.De(new Date().getTime(),e)){var a=this.Le;this.resetSessionId(),this.Me.emit("forcedIdleReset",{idleSessionId:a})}}),1.1*this.sessionTimeoutMs)}},lP=["$set_once","$set"],io=ct("[SiteApps]"),Kx=class{constructor(e){this._instance=e,this.Xe=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Qe(e,a){if(a){var r=this.globalsForEvent(a);this.Xe.push(r),this.Xe.length>1e3&&(this.Xe=this.Xe.slice(10))}}get siteAppLoaders(){var e;return(e=ae._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance.Ai(this.Qe.bind(this));this.Ze=()=>{e(),this.Xe=[],this.Ze=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[h,m]of Object.entries(d))u[h]={id:c[h],type:h,properties:m};var{$set_once:S,$set:b}=e;return{event:G({},uk(e,lP),{properties:G({},e.properties,b?{$set:G({},(a=(r=e.properties)==null?void 0:r.$set)!==null&&a!==void 0?a:{},b)}:{},S?{$set_once:G({},(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.Xe.length&&(io.info("Processing "+this.Xe.length+" events for site app with id "+e.id),this.Xe.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.Ze)==null||s.call(this))},n=!1,o=s=>{a.errored=!s,a.loaded=!0,io.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){io.error("Error while initializing PostHog app with config id "+e.id,s),o(!1)}if(n&&a.loaded)try{r()}catch(s){io.error("Error while processing buffered events PostHog app with config id "+e.id,s),a.errored=!0}}tr(){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)}ir(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){io.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.tr(),void this._instance.on("eventCaptured",(u=>this.ir(u)))):void io.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((r=this.Ze)==null||r.call(this),(n=e.siteApps)!=null&&n.length)if(this.isEnabled){var i=function(u){var c;ae["__$$ph_site_app_"+u]=o._instance,(c=ae.__PosthogExtensions__)==null||c.loadSiteApp==null||c.loadSiteApp(o._instance,l,(d=>{if(d)return io.error("Error while initializing PostHog app with config id "+u,d)}))};for(var{id:s,url:l}of e.siteApps)i(s)}else io.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}},fE=function(t,e){if(!t)return!1;var a=t.userAgent;if(a&&yA(a,e))return!0;try{var r=t?.userAgentData;if(r!=null&&r.brands&&r.brands.some((n=>yA(n?.brand,e))))return!0}catch{}return!!t.webdriver},Ju=(function(t){return t.US="us",t.EU="eu",t.CUSTOM="custom",t})({}),nk="i.posthog.com",Qx=class{constructor(e){this.er={},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("."+nk,".posthog.com")),a==="https://app.posthog.com"?"https://us.posthog.com":a}get region(){return this.er[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.er[this.apiHost]=Ju.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.er[this.apiHost]=Ju.EU:this.er[this.apiHost]=Ju.CUSTOM),this.er[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===Ju.CUSTOM)return this.apiHost+a;var r=nk+a;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}},uP={icontains:(t,e)=>!!E&&e.href.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>!!E&&e.href.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>!!E&&Wp(e.href,t),not_regex:(t,e)=>!!E&&!Wp(e.href,t),exact:(t,e)=>e.href===t,is_not:(t,e)=>e.href!==t},Jx=class t{constructor(e){var a=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),a.getWebExperiments((n=>{t.rr("retrieved web experiments from the server"),a.sr=new Map,n.forEach((o=>{if(o.feature_flag_key){var i;a.sr&&(t.rr("setting flag key ",o.feature_flag_key," to web experiment ",o),(i=a.sr)==null||i.set(o.feature_flag_key,o));var s=a._instance.getFeatureFlag(o.feature_flag_key);ut(s)&&o.variants[s]&&a.nr(o.name,s,o.variants[s].transforms)}else if(o.variants)for(var l in o.variants){var u=o.variants[l];t.ar(u)&&a.nr(o.name,l,u.transforms)}}))}),r)},this._instance=e,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}onFeatureFlags(e){if(this._is_bot())t.rr("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(Ie(this.sr))return this.sr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();t.rr("applying feature flags",e),e.forEach((a=>{var r;if(this.sr&&(r=this.sr)!=null&&r.has(a)){var n,o=this._instance.getFeatureFlag(a),i=(n=this.sr)==null?void 0:n.get(a);o&&i!=null&&i.variants[o]&&this.nr(i.name,o,i.variants[o].transforms)}}))}}previewWebExperiment(){var e=t.getWindowLocation();if(e!=null&&e.search){var a=Up(e?.search,"__experiment_id"),r=Up(e?.search,"__experiment_variant");a&&r&&(t.rr("previewing web experiments "+a+" && "+r),this.getWebExperiments((n=>{this.lr(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.ci({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)}})}lr(e,a,r){var n=r.filter((o=>o.id===e));n&&n.length>0&&(t.rr("Previewing web experiment ["+n[0].name+"] with variant ["+a+"]"),this.nr(n[0].name,a,n[0].variants[a].transforms))}static ar(e){return!Ie(e.conditions)&&t.ur(e)&&t.hr(e)}static ur(e){var a;if(Ie(e.conditions)||Ie((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||uP[(n=(o=e.conditions)==null?void 0:o.urlMatchType)!==null&&n!==void 0?n:"icontains"](e.conditions.url,i))}static getWindowLocation(){return E?.location}static hr(e){var a;if(Ie(e.conditions)||Ie((a=e.conditions)==null?void 0:a.utm))return!0;var r=Qk();if(r.utm_source){var n,o,i,s,l,u,c,d,h=(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,m=(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,b=(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 h&&S&&b&&m}return!1}static rr(e){for(var a=arguments.length,r=new Array(a>1?a-1:0),n=1;n<a;n++)r[n-1]=arguments[n];z.info("[WebExperiments] "+e,r)}nr(e,a,r){this._is_bot()?t.rr("Refusing to render web experiment since the viewer is a likely bot"):a!=="control"?r.forEach((n=>{if(n.selector){var o;t.rr("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.rr("Control variants leave the page unmodified.")}_is_bot(){return ya&&this._instance?fE(ya,this._instance.config.custom_blocked_useragents):void 0}},cP=ct("[PostHog ExternalIntegrations]"),dP={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},eb=class{constructor(e){this._instance=e}it(e,a){var r;(r=ae.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,(n=>{if(n)return cP.error("failed to load script",n);a()}))}startIfEnabledOrStop(){var e=this,a=function(i){var s,l,u;!n||(s=ae.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[i]||e.it(dP[i],(()=>{var c;(c=ae.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[i])==null||c.start(e._instance)})),!n&&(l=ae.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[i]&&((u=ae.__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]",Gu=ct(tb),Yp=class{get started(){var e;return!((e=this.vr)==null||!e.isStarted)}get status(){return this.vr?this.vr.status:this.dr&&!this.cr?"disabled":"lazy_loading"}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.dr=!1,this.pr=void 0,this._instance=e,!this._instance.sessionManager)throw Gu.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 cr(){var e,a=!((e=this._instance.get_property(By))==null||!e.enabled),r=!this._instance.config.disable_session_recording,n=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return E&&a&&r&&!n}startIfEnabledOrStop(e){var a;if(!this.cr||(a=this.vr)==null||!a.isStarted){var r=!U(Object.assign)&&!U(Array.from);this.cr&&r?(this.gr(e),Gu.info("starting")):this.stopRecording()}}gr(e){var a,r,n;this.cr&&(ae!=null&&(a=ae.__PosthogExtensions__)!=null&&(a=a.rrweb)!=null&&a.record&&(r=ae.__PosthogExtensions__)!=null&&r.initSessionRecording?this._r(e):(n=ae.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,this.mr,(o=>{if(o)return Gu.error("could not load recorder",o);this._r(e)})))}stopRecording(){var e,a;(e=this.pr)==null||e.call(this),this.pr=void 0,(a=this.vr)==null||a.stop()}yr(){var e;(e=this._instance.persistence)==null||e.unregister(xk)}br(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=Ie(s)?null:parseFloat(s);Ie(l)&&this.yr();var u=i?.minimumDurationMilliseconds;n.register({[By]:G({enabled:!!i},i,{networkPayloadCapture:G({capturePerformance:e.capturePerformance},i?.networkPayloadCapture),canvasRecording:{enabled:i?.recordCanvas,fps:i?.canvasFps,quality:i?.canvasQuality},sampleRate:l,minimumDurationMilliseconds:U(u)?null:u,endpoint:i?.endpoint,triggerMatchType:i?.triggerMatchType,masking:i?.masking,urlTriggers:i?.urlTriggers})})};o(),(a=this.pr)==null||a.call(this),this.pr=(r=this._instance.sessionManager)==null?void 0:r.onSessionId(o)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.br(e),this.dr=!0,this.startIfEnabledOrStop()):this.dr=!0:Gu.info("skipping remote config with no sessionRecording",e)}log(e,a){var r;a===void 0&&(a="log"),(r=this.vr)!=null&&r.log?this.vr.log(e,a):Gu.warn("log called before recorder was ready")}get mr(){var e,a,r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(By);return(r==null||(a=r.scriptConfig)==null?void 0:a.script)||"lazy-recorder"}_r(e){var a,r;if((a=ae.__PosthogExtensions__)==null||!a.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.vr||(this.vr=(r=ae.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance),this.vr._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.vr.start(e)}onRRwebEmit(e){var a;(a=this.vr)==null||a.onRRwebEmit==null||a.onRRwebEmit(e)}overrideLinkedFlag(){var e,a;this.vr||(a=this._instance.persistence)==null||a.register({$replay_override_linked_flag:!0}),(e=this.vr)==null||e.overrideLinkedFlag()}overrideSampling(){var e,a;this.vr||(a=this._instance.persistence)==null||a.register({$replay_override_sampling:!0}),(e=this.vr)==null||e.overrideSampling()}overrideTrigger(e){var a,r;this.vr||(r=this._instance.persistence)==null||r.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(a=this.vr)==null||a.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.vr)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,a){var r;return!((r=this.vr)==null||!r.tryAddCustomEvent(e,a))}},ac={},ab=()=>{},Ns="posthog",pE=!JN&&ea?.indexOf("MSIE")===-1&&ea?.indexOf("Mozilla")===-1,ok=t=>{var e;return G({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:oN(q?.location),persistence:"localStorage+cookie",persistence_name:"",loaded:ab,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:ta&&ut(ta?.search)&&ta.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_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(E==null||(e=E.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;z.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:Wx},error_tracking:{},_onCapture:ab,__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}:{}}))(t))},ik=t=>{var e={};U(t.process_person)||(e.person_profiles=t.process_person),U(t.xhr_headers)||(e.request_headers=t.xhr_headers),U(t.cookie_name)||(e.persistence_name=t.cookie_name),U(t.disable_cookie)||(e.disable_persistence=t.disable_cookie),U(t.store_google)||(e.save_campaign_params=t.store_google),U(t.verbose)||(e.debug=t.verbose);var a=Je({},e,t);return Te(t.property_blacklist)&&(U(t.property_denylist)?a.property_denylist=t.property_blacklist:Te(t.property_denylist)?a.property_denylist=[...t.property_blacklist,...t.property_denylist]:z.error("Invalid value for property_denylist config: "+t.property_denylist)),a},rb=class{constructor(){this.__forceAllowLocalhost=!1}get wr(){return this.__forceAllowLocalhost}set wr(e){z.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},Kp=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 rb,this.Sr=!1,this.version=an.LIB_VERSION,this.Er=new lc,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=ok(),this.SentryIntegration=Ix,this.sentryIntegration=e=>(function(a,r){var n=Bk(a,r);return{name:Ok,processEvent:o=>n(o)}})(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.$r=!1,this.kr=null,this.Pr=null,this.Tr=null,this.featureFlags=new Ux(this),this.toolbar=new Ax(this),this.scrollManager=new Yx(this),this.pageViewManager=new Ox(this),this.surveys=new $x(this),this.experiments=new Jx(this),this.exceptions=new Hx(this),this.rateLimiter=new jx(this),this.requestRouter=new Qx(this),this.consent=new _x(this),this.externalIntegrations=new eb(this),this.people={set:(e,a,r)=>{var n=ut(e)?{[e]:a}:e;this.setPersonProperties(n),r?.({})},set_once:(e,a,r)=>{var n=ut(e)?{[e]:a}:e;this.setPersonProperties(void 0,n),r?.({})}},this.on("eventCaptured",(e=>z.info('send "'+e?.event+'"',e)))}init(e,a,r){if(r&&r!==Ns){var n,o=(n=ac[r])!==null&&n!==void 0?n:new t;return o._init(e,a,r),ac[r]=o,ac[Ns][r]=o,o}return this._init(e,a,r)}_init(e,a,r){var n;if(a===void 0&&(a={}),U(e)||Ky(e))return z.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.Rr(a.debug),this.Ir=a,this.Fr=[],a.person_profiles&&(this.Pr=a.person_profiles),this.set_config(Je({},ok(a.defaults),ik(a),{name:r,token:e})),this.config.on_xhr_error&&z.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=a.disable_compression?void 0:on.GZipJS;var o=this.Cr();this.persistence=new tc(this.config,o),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new tc(G({},this.config,{persistence:"sessionStorage"}),o);var i=G({},this.persistence.props),s=G({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Mr=new Zx((g=>this.Or(g)),this.config.request_queue_config),this.Ar=new Xx(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 Xp(this),this.sessionPropsManager=new Zp(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?(z.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Dr(l)}),0)):(z.info("Initializing extensions synchronously"),this.Dr(l)),an.DEBUG=an.DEBUG||this.config.debug,an.DEBUG&&z.info("Starting in debug mode",{this:this,config:a,thisC:G({},this.config),p:i,s}),((n=a.bootstrap)==null?void 0:n.distinctID)!==void 0){var u,c,d=this.config.get_device_id(lo()),h=(u=a.bootstrap)!=null&&u.isIdentifiedID?d:a.bootstrap.distinctID;this.persistence.set_property(rn,(c=a.bootstrap)!=null&&c.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:a.bootstrap.distinctID,$device_id:h})}if(this.jr()){var m,S,b=Object.keys(((m=a.bootstrap)==null?void 0:m.featureFlags)||{}).filter((g=>{var v;return!((v=a.bootstrap)==null||(v=v.featureFlags)==null||!v[g])})).reduce(((g,v)=>{var y;return g[v]=((y=a.bootstrap)==null||(y=y.featureFlags)==null?void 0:y[v])||!1,g}),{}),x=Object.keys(((S=a.bootstrap)==null?void 0:S.featureFlagPayloads)||{}).filter((g=>b[g])).reduce(((g,v)=>{var y,_;return(y=a.bootstrap)!=null&&(y=y.featureFlagPayloads)!=null&&y[v]&&(g[v]=(_=a.bootstrap)==null||(_=_.featureFlagPayloads)==null?void 0:_[v]),g}),{});this.featureFlags.receivedFeatureFlags({featureFlags:b,featureFlagPayloads:x})}if(l)this.register_once({distinct_id:Pu,$device_id:null},"");else if(!this.get_distinct_id()){var f=this.config.get_device_id(lo());this.register_once({distinct_id:f,$device_id:f},""),this.persistence.set_property(rn,"anonymous")}return nt(E,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),a.segment?AN(this,(()=>this.Lr())):this.Lr(),uo(this.config._onCapture)&&this.config._onCapture!==ab&&(z.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(g=>this.config._onCapture(g.event,g)))),this.config.ip&&z.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}Dr(e){var a=performance.now();this.historyAutocapture=new Lx(this),this.historyAutocapture.startIfEnabled();var r=[];r.push((()=>{new kx(this).startIfEnabledOrStop()})),r.push((()=>{var n;this.siteApps=new Kx(this),(n=this.siteApps)==null||n.init()})),e||r.push((()=>{this.sessionRecording=new Yp(this),this.sessionRecording.startIfEnabledOrStop()})),this.config.disable_scroll_properties||r.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),r.push((()=>{this.autocapture=new xx(this),this.autocapture.startIfEnabled()})),r.push((()=>{this.surveys.loadIfEnabled()})),r.push((()=>{this.heatmaps=new Dx(this),this.heatmaps.startIfEnabled()})),r.push((()=>{this.webVitalsAutocapture=new Mx(this)})),r.push((()=>{this.exceptionObserver=new wx(this),this.exceptionObserver.startIfEnabled()})),r.push((()=>{this.deadClicksAutocapture=new zp(this,IN),this.deadClicksAutocapture.startIfEnabled()})),r.push((()=>{if(this.Nr){var n=this.Nr;this.Nr=void 0,this.fi(n)}})),this.Ur(r,a)}Ur(e,a){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-a>=30&&e.length>0)return void setTimeout((()=>{this.Ur(e,a)}),0);var r=e.shift();if(r)try{r()}catch(o){z.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&&z.info("PostHog extensions initialized ("+n+"ms)")}fi(e){var a,r,n,o,i,s,l,u;if(!q||!q.body)return z.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.fi(e)}),500);this.config.__preview_deferred_init_extensions&&(this.Nr=e),this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=pe(e.supportedCompression,on.GZipJS)?on.GZipJS:pe(e.supportedCompression,on.Base64)?on.Base64:void 0),(a=e.analytics)!=null&&a.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Pr?this.Pr:"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),(s=this.webVitalsAutocapture)==null||s.onRemoteConfig(e),(l=this.exceptionObserver)==null||l.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(u=this.deadClicksAutocapture)==null||u.onRemoteConfig(e)}Lr(){try{this.config.loaded(this)}catch(e){z.critical("`loaded` function failed",e)}this.zr(),this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.Hr()}),1),new Gx(this).load(),this.featureFlags.flags()}zr(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.Mr)==null||e.enable())}_dom_loaded(){this.is_capturing()&&fo(this.__request_queue,(e=>this.Or(e))),this.__request_queue=[],this.zr()}_handle_unload(){var e,a;this.config.request_batching?(this.Br()&&this.capture("$pageleave"),(e=this.Mr)==null||e.unload(),(a=this.Ar)==null||a.unload()):this.Br()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}ci(e){this.__loaded&&(pE?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=Gp(e.url,{ip:this.config.ip?1:0}),e.headers=G({},this.config.request_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=G({},a);i.timeout=i.timeout||6e4,i.url=Gp(i.url,{_:new Date().getTime().toString(),ver:an.LIB_VERSION,compression:i.compression});var s=(r=i.transport)!==null&&r!==void 0?r:"fetch",l=Ep.filter((c=>!i.disableTransport||!c.transport||!i.disableTransport.includes(c.transport))),u=(n=(o=gk(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)})(G({},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)}}))))}Or(e){this.Ar?this.Ar.retriableRequest(e):this.ci(e)}_execute_array(e){var a,r=[],n=[],o=[];fo(e,(s=>{s&&(a=s[0],Te(a)?o.push(s):uo(s)?s.call(this):Te(s)&&a==="alias"?r.push(s):Te(s)&&a.indexOf("capture")!==-1&&uo(this[a])?o.push(s):n.push(s))}));var i=function(s,l){fo(s,(function(u){if(Te(u[0])){var c=l;De(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)}jr(){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.Mr){if(this.is_capturing())if(!U(e)&&ut(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&&!ut(a?.$current_url)&&(z.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=lo(),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,h=this.qr(r?.$set_once);if(h&&(c.$set_once=h),(c=rN(c,r!=null&&r._noTruncate?null:this.config.properties_string_max_length)).timestamp=l,U(r?.timestamp)||(c.properties.$event_time_override_provided=!0,c.properties.$event_time_override_system_time=s),e===Tp.DISMISSED||e===Tp.SENT){var m=a?.[tk.SURVEY_ID],S=a?.[tk.SURVEY_ITERATION];d={id:m,current_iteration:S},localStorage.getItem(ak(d))||localStorage.setItem(ak(d),"true"),c.$set=G({},c.$set,{[rP({id:m,current_iteration:S},e===Tp.SENT?"responded":"dismissed")]:!0})}var b=G({},c.properties.$set,c.$set);if(Ps(b)||this.setPersonPropertiesForFlags(b),!Ie(this.config.before_send)){var x=this.Wr(c);if(!x)return;c=x}this.Er.emit("eventCaptured",c);var f={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.Or(f):this.Mr.enqueue(f),c}z.critical("This capture call is ignored due to client rate limiting.")}}else z.error("No event name provided to posthog.capture")}else z.uninitializedWarning("posthog.capture")}Ai(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=G({},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=G({},this.persistence.properties(),this.sessionPersistence.properties());return s.distinct_id=l.distinct_id,(!ut(s.distinct_id)&&!xr(s.distinct_id)||Ky(s.distinct_id))&&z.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),s}var u,c=VN(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:d,windowId:h}=this.sessionManager.checkAndGetSessionAndWindowId(o,r.getTime());s.$session_id=d,s.$window_id=h}this.sessionPropsManager&&Je(s,this.sessionPropsManager.getSessionProps());try{var m;this.sessionRecording&&Je(s,this.sessionRecording.sdkDebugProperties),s.$sdk_debug_retry_queue_size=(m=this.Ar)==null?void 0:m.length}catch(f){s.$sdk_debug_error_capturing_properties=String(f)}if(this.requestRouter.region===Ju.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=Je(s,u),e==="$pageview"&&q&&(s.title=q.title),!U(i)){var S=r.getTime()-i;s.$duration=parseFloat((S/1e3).toFixed(3))}ea&&this.config.opt_out_useragent_filter&&(s.$browser_type=this._is_bot()?"bot":"browser"),(s=Je({},c,this.persistence.properties(),this.sessionPersistence.properties(),s)).$is_identified=this._isIdentified(),Te(this.config.property_denylist)?De(this.config.property_denylist,(function(f){delete s[f]})):z.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&(z.error("sanitize_properties is deprecated. Use before_send instead"),s=b(s,e));var x=this.Gr();return s.$process_person_profile=x,x&&!o&&this.Vr("_calculate_event_properties"),s}qr(e){var a;if(!this.persistence||!this.Gr()||this.Sr)return e;var r=this.persistence.get_initial_props(),n=(a=this.sessionPropsManager)==null?void 0:a.getSetOnceProps(),o=Je({},r,n||{},e||{}),i=this.config.sanitize_properties;return i&&(z.error("sanitize_properties is deprecated. Use before_send instead"),o=i(o,"$set_once")),this.Sr=!0,Ps(o)?void 0:o}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)}Jr(e,a){this.register({[e]:a})}getFeatureFlag(e,a){return this.featureFlags.getFeatureFlag(e,a)}getFeatureFlagPayload(e){var a=this.featureFlags.getFeatureFlagPayload(e);try{return JSON.parse(a)}catch{return a}}isFeatureEnabled(e,a){return this.featureFlags.isFeatureEnabled(e,a)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}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.Er.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=oP),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 z.uninitializedWarning("posthog.identify");if(xr(e)&&(e=e.toString(),z.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()))z.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!==Pu){if(this.Vr("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(Wu)&&(this.unregister(Wu),this.register({distinct_id:e}));var i=(this.persistence.get_property(rn)||"anonymous")==="anonymous";e!==n&&i?(this.persistence.set_property(rn,"identified"),this.setPersonPropertiesForFlags(G({},r||{},a||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:n},{$set:a||{},$set_once:r||{}}),this.Tr=YA(e,a,r),this.featureFlags.setAnonymousDistinctId(n)):(a||r)&&this.setPersonProperties(a,r),e!==n&&(this.reloadFeatureFlags(),this.unregister(Op))}}else z.critical('The string "'+Pu+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else z.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,a){if((e||a)&&this.Vr("posthog.setPersonProperties")){var r=YA(this.get_distinct_id(),e,a);this.Tr!==r?(this.setPersonPropertiesForFlags(G({},a||{},e||{})),this.capture("$set",{$set:e||{},$set_once:a||{}}),this.Tr=r):z.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,a,r){if(e&&a){if(this.Vr("posthog.group")){var n=this.getGroups();n[e]!==a&&this.resetGroupPropertiesForFlags(e),this.register({$groups:G({},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 z.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.Vr("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,a)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var a,r,n,o;if(z.info("reset"),!this.__loaded)return z.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(rn,"anonymous"),(o=this.sessionManager)==null||o.resetSessionId(),this.Tr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:Pu,$device_id:null},"");else{var s=this.config.get_device_id(lo());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(vk)?(z.critical("Attempting to create alias for existing People user - aborting."),-2):this.Vr("posthog.alias")?(U(a)&&(a=this.get_distinct_id()),e!==a?(this.Jr(Wu,e),this.capture("$create_alias",{alias:e,distinct_id:a})):(z.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var a=G({},this.config);if(mt(e)){var r,n,o,i,s;Je(this.config,ik(e));var l=this.Cr();(r=this.persistence)==null||r.update_config(this.config,a,l),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new tc(G({},this.config,{persistence:"sessionStorage"}),l);var u=this.Rr(this.config.debug);co(u)&&(this.config.debug=u),co(this.config.debug)&&(this.config.debug?(an.DEBUG=!0,Ge.H()&&Ge.G("ph_debug","true"),z.info("set_config",{config:e,oldConfig:a,newConfig:G({},this.config)})):(an.DEBUG=!1,Ge.H()&&Ge.V("ph_debug"))),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),(o=this.autocapture)==null||o.startIfEnabled(),(i=this.heatmaps)==null||i.startIfEnabled(),this.surveys.loadIfEnabled(),this.Kr(),(s=this.externalIntegrations)==null||s.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(G({},n,a))}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:Ns;return a!==Ns&&(a=Ns+"."+a),a}_isIdentified(){var e,a;return((e=this.persistence)==null?void 0:e.get_property(rn))==="identified"||((a=this.sessionPersistence)==null?void 0:a.get_property(rn))==="identified"}Gr(){var e,a;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&Ps(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Wu])&&((a=this.persistence)==null||(a=a.props)==null||!a[Fp]))}Br(){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.Gr()||this.Vr("posthog.createPersonProfile")&&this.setPersonProperties({},{})}Vr(e){return this.config.person_profiles==="never"?(z.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Jr(Fp,!0),!0)}Cr(){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}Kr(){var e,a,r,n,o=this.Cr();return((e=this.persistence)==null?void 0:e.wi)!==o&&((r=this.persistence)==null||r.set_disabled(o)),((a=this.sessionPersistence)==null?void 0:a.wi)!==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;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(r=this.sessionManager)==null||r.destroy(),this.sessionManager=new Xp(this),this.persistence&&(this.sessionPropsManager=new Zp(this,this.sessionManager,this.persistence)),this.sessionRecording=new Yp(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this.Kr(),this.zr(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(U(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((n=e?.captureEventName)!==null&&n!==void 0?n:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hr()}else z.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,a;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this.Kr(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:Pu,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(a=this.sessionRecording)==null||a.stopRecording(),this.sessionRecording=void 0,this.Hr())):z.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===nn.GRANTED?"granted":e===nn.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.Kr()}_is_bot(){return ya?fE(ya,this.config.custom_blocked_useragents):void 0}Hr(){q&&(q.visibilityState==="visible"?this.$r||(this.$r=!0,this.capture("$pageview",{title:q.title},{send_instantly:!0}),this.kr&&(q.removeEventListener("visibilitychange",this.kr),this.kr=null)):this.kr||(this.kr=this.Hr.bind(this),nt(q,"visibilitychange",this.kr)))}debug(e){e===!1?(E?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(E?.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}))}O(){var e,a,r,n,o,i,s,l=this.Ir||{};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?(z.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=z,i=(a="advanced_disable_flags")in(e=l)&&!U(e[a]),s=r in e&&!U(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)}Wr(e){if(Ie(this.config.before_send))return e;var a=Te(this.config.before_send)?this.config.before_send:[this.config.before_send],r=e;for(var n of a){if(r=n(r),Ie(r)){var o="Event '"+e.event+"' was rejected in beforeSend function";return UF(e.event)?z.warn(o+". This can cause unexpected behavior."):z.info(o),null}r.properties&&!Ps(r.properties)||z.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return r}getPageViewId(){var e;return(e=this.pageViewManager.Vt)==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)})}Rr(e){var a=co(e)&&!e,r=Ge.H()&&Ge.q("ph_debug")==="true";return!a&&(!!r||e)}};(function(t,e){for(var a=0;a<e.length;a++)t.prototype[e[a]]=aN(t.prototype[e[a]])})(Kp,["identify"]);var sk,hE=(sk=ac[Ns]=new Kp,(function(){function t(){t.done||(t.done=!0,pE=!1,De(ac,(function(e){e._dom_loaded()})))}q!=null&&q.addEventListener?q.readyState==="complete"?t():nt(q,"DOMContentLoaded",t,{capture:!1}):E&&z.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),sk);var hb=class{constructor(e={}){this.options=e;$(this,"client");$(this,"featureFlagsCallback");$(this,"captureCallback");$(this,"consentUnsub");if(this.client=e.client,this.featureFlagsCallback=e.onFeatureFlagsLoaded,this.captureCallback=e.onCapture,!this.client&&e.consent&&e.requireExplicitConsent&&typeof window<"u"&&e.apiKey){let a=e.consent;a.getStatus()==="granted"&&this.initPostHog(),this.consentUnsub=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"}`;this.client=hE.init(e.apiKey,{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??!0,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:n=>{if(a&&this.featureFlagsCallback){n.onFeatureFlags(()=>{let i=this.getAllFeatureFlags();i&&this.featureFlagsCallback&&this.featureFlagsCallback(i)});let o=this.getAllFeatureFlags();o&&Object.keys(o).length>0&&this.featureFlagsCallback(o)}this.captureCallback&&n.on("eventCaptured",o=>{let i=typeof o=="string"?o:o?.event,s=typeof o=="string"?void 0:o?.properties;typeof i=="string"&&this.captureCallback?.(i,s)})}},r)}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 th(t={}){return new hb(t)}var mb=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{}}}},vb=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 fc=class{constructor(){$(this,"executors",new Map);for(let{kind:e,executor:a}of Iv)this.registerCore(e,a);for(let{kind:e,executor:a}of Nv)this.registerCore(e,a);this.registerCore("core:mountWidget",async()=>{throw new Error("core:mountWidget must be handled by ActionEngine")}),this.registerCore("core:sequence",mb),this.registerCore("core:parallel",gb),this.registerCore("core:wait",vb)}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)}},br=new fc;function mE(t){return br.get(t)}function ah(t){return br.has(t)}var fP=new Set(["onclick","onerror","onload","onmouseover","onfocus","onblur","onchange","onsubmit","onkeydown","onkeyup","onkeypress"]),gE=5e4,vE=50;function ln(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(!ah(r)&&r!=="core:mountWidget"){let n=br.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":ho(t,e,a);break;case"overlays:badge":ho(t,e,a),pP(t,e,a);break;case"overlays:tooltip":ho(t,e,a),hP(t,e,a);break;case"overlays:modal":LP(t,e,a);break;case"content:insertHtml":ho(t,e,a),mP(t,e,a);break;case"content:setText":ho(t,e,a),gP(t,e,a);break;case"content:setAttr":ho(t,e,a),vP(t,e,a);break;case"content:addClass":case"content:removeClass":ho(t,e,a),yP(t,e,a);break;case"content:setStyle":ho(t,e,a),xP(t,e,a);break;case"core:mountWidget":bP(t,e,a);break;case"core:wait":SP(t,e,a);break;case"core:sequence":CP(t,e,a);break;case"core:parallel":_P(t,e,a);break;case"core:tour":IP(t,e,a);break;case"navigation:navigate":wP(t,e,a);break}return{valid:e.length===0,errors:e,warnings:a}}function ho(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 pP(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 hP(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 mP(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>gE&&e.push({code:"HTML_TOO_LONG",message:`HTML content exceeds maximum length of ${gE}`,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 gP(t,e,a){(t.text===void 0||t.text===null)&&e.push({code:"MISSING_TEXT",message:"setText action requires 'text' property",field:"text"})}function vP(t,e,a){!t.attr||typeof t.attr!="string"?e.push({code:"MISSING_ATTR",message:"setAttr action requires 'attr' property",field:"attr"}):(fP.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 yP(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 xP(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>vE&&e.push({code:"TOO_MANY_STYLES",message:`Too many styles (${r}). Maximum is ${vE}`,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 bP(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 SP(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 CP(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=ln(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 _P(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=ln(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 wP(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 LP(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 IP(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=ln(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`})}}function rh(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=ln(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 AP=0;function nh(t){let{overlayRoot:e,eventBus:a,surfaces:r,anchorResolver:n,waitForAnchor:o,adaptiveId:i,executorRegistry:s=br,subscribeNavigation:l,runtime:u}=t,c=new Map,d=new Map;function h(){return`action-${++AP}`}function m(C,L){a&&a.publish(C,L)}function S(){return{overlayRoot:e,resolveAnchor:n,waitForAnchor:o,generateId:h,publishEvent:m,adaptiveId:i,applyAction:g,subscribeEvent:a?(C,L)=>a.subscribe({names:[C]},k=>L(k.props)):void 0,subscribeNavigation:l}}async function b(C,L){if(!r)throw new Error("Surfaces provider required for core:mountWidget actions");let k=r.mount(C.slot,{type:"widget",widgetId:C.widget.widgetId,config:C.widget.props},{priority:C.widget.priority});return L.publishEvent("action.applied",{id:L.generateId(),kind:"core:mountWidget",slot:C.slot,widgetId:C.widget.widgetId}),{cleanup:()=>{k.unmount()},updateFn:A=>{if("widget"in A&&A.widget){let M=A.widget;M.props&&k.update({type:"widget",widgetId:C.widget.widgetId,config:M.props})}}}}async function x(C,L){if(C.kind==="core:mountWidget")return b(C,L);let k=s.get(C.kind);if(!k){let A="list"in s?s.list():"(list unavailable)";throw console.error(`[ActionEngine] No executor for kind="${C.kind}".`,`Registered: [${A}]`),new Error(`No executor for action kind: ${C.kind}`)}return k(C,L)}function f(C,L,k,A){if(!u)return;let M=[],T=async()=>{let R=c.get(C);if(!R)return;let F=u.evaluateSync(k).value;if(R.state==="applied"&&!F){try{await R.cleanup()}catch(P){console.error(`[ActionEngine] Error reverting conditional action ${C}:`,P)}R.state="deferred",R.cleanup=()=>{},R.updateFn=void 0,m("action.deferred",{id:C,kind:L.kind})}else if(R.state==="deferred"&&F)try{let P=S(),Y=await x(L,P);R.state="applied",R.cleanup=Y.cleanup,R.updateFn=Y.updateFn,R.appliedTs=Date.now(),m("action.applied",{id:C,kind:L.kind,anchorId:"anchorId"in L?L.anchorId:void 0})}catch(P){console.error(`[ActionEngine] Error applying deferred action ${C}:`,P),R.state="failed"}};u.context&&M.push(u.context.subscribe(T)),u.accumulator&&M.push(u.accumulator.subscribe(T)),d.set(C,M)}async function g(C){let L=ln(C);if(!L.valid){let F=L.errors.map(P=>P.message).join("; ");throw console.error(`[ActionEngine] Validation failed for action kind="${C?.kind}":`,F,C),new Error(`Action validation failed: ${F}`)}let k=h(),A=C.triggerWhen;if(A&&u&&!u.evaluateSync(A).value){let P={id:k,action:C,adaptiveId:i,appliedTs:Date.now(),state:"deferred",cleanup:()=>{}};c.set(k,P);let Y={id:k,action:C,async revert(){let N=c.get(k);if(!N)return;let W=d.get(k);if(W){for(let Q of W)Q();d.delete(k)}N.state="reverted",c.delete(k)},isApplied(){return c.get(k)?.state==="applied"},async update(N){let W=c.get(k);if(!W||W.state!=="applied")throw new Error("Cannot update action that is not applied");if(W.updateFn)await W.updateFn(N);else throw new Error(`Action kind ${C.kind} does not support updates`)},getState(){return c.get(k)?.state??"reverted"}};return f(k,C,A,Y),Y}let M=S(),T=await x(C,M),R={id:k,action:C,adaptiveId:i,appliedTs:Date.now(),state:"applied",cleanup:T.cleanup,updateFn:T.updateFn};c.set(k,R),m("action.applied",{id:k,kind:C.kind,anchorId:"anchorId"in C?C.anchorId:void 0});let B={id:k,action:C,async revert(){let F=c.get(k);if(!F||F.state!=="applied")return;let P=d.get(k);if(P){for(let Y of P)Y();d.delete(k)}try{await F.cleanup(),F.state="reverted",m("action.reverted",{id:k,kind:C.kind})}catch(Y){throw F.state="failed",m("action.failed",{id:k,kind:C.kind,error:String(Y)}),Y}finally{c.delete(k)}},isApplied(){return c.get(k)?.state==="applied"},async update(F){let P=c.get(k);if(!P||P.state!=="applied")throw new Error("Cannot update action that is not applied");if(P.updateFn)await P.updateFn(F);else throw new Error(`Action kind ${C.kind} does not support updates`)},getState(){return c.get(k)?.state??"reverted"}};return A&&u&&f(k,C,A,B),B}async function v(C){console.log(`[ActionEngine] applyBatch: ${C.length} action(s)`,C.map(R=>R.kind).join(", "));let L=rh(C);if(!L.valid){let R=L.errors.map(B=>B.message).join("; ");throw console.error(`[ActionEngine] Batch validation FAILED for ${C.length} action(s):`,R,`
463
463
  Actions:`,C.map((B,F)=>` [${F}] ${B.kind} ${B.anchorId?`anchor="${typeof B.anchorId=="string"?B.anchorId:B.anchorId.selector}"`:""} ${B.label?`label="${B.label}"`:""}`).join(`
464
- `)),new Error(`Batch validation failed: ${R}`)}let k=h(),A=[],M=[];try{for(let R of C){let B=await g(R);A.push(B),M.push(B)}}catch(R){console.error(`[ActionEngine] Batch apply FAILED at action ${M.length+1}/${C.length}.`,`Successfully applied: ${M.length}. Rolling back...`,R);for(let B of M)try{await B.revert()}catch{}throw R}return{id:k,handles:A,async revertAll(){for(let R=A.length-1;R>=0;R--)try{await A[R].revert()}catch(B){console.error(`[ActionEngine] Error reverting action ${A[R].id}:`,B)}},isApplied(){return A.every(R=>R.isApplied())}}}function y(C){return ln(C)}function _(){return Array.from(c.values()).map(C=>({id:C.id,action:C.action,adaptiveId:C.adaptiveId,appliedTs:C.appliedTs,state:C.state}))}function w(){for(let C of d.values())for(let L of C)try{L()}catch{}d.clear();for(let C of c.values())if(C.state==="applied")try{C.cleanup()}catch(L){console.error("[ActionEngine] Error during cleanup:",L)}c.clear()}return{apply:g,applyBatch:v,validate:y,getActive:_,destroy:w}}var kP=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),oh=p.object({type:p.literal("page_url"),url:p.string()}),ih=p.object({type:p.literal("route"),routeId:p.string()}),sh=p.object({type:p.literal("anchor_visible"),anchorId:p.string(),state:p.enum(["visible","present","absent"])}),lh=p.object({type:p.literal("event_occurred"),eventName:p.string(),withinMs:p.number().optional()}),uh=p.object({type:p.literal("state_equals"),key:p.string(),value:p.unknown()}),ch=p.object({type:p.literal("viewport"),minWidth:p.number().optional(),maxWidth:p.number().optional(),minHeight:p.number().optional(),maxHeight:p.number().optional()}),dh=p.object({type:p.literal("session_metric"),key:p.string(),operator:p.enum(["gte","lte","eq","gt","lt"]),threshold:p.number()}),fh=p.object({type:p.literal("dismissed"),key:p.string(),inverted:p.boolean().optional()}),ph=p.object({type:p.literal("cooldown_active"),key:p.string(),inverted:p.boolean().optional()}),hh=p.object({type:p.literal("frequency_limit"),key:p.string(),limit:p.number(),inverted:p.boolean().optional()}),Ws=p.object({equals:p.union([p.string(),p.number(),p.boolean()]).optional(),contains:p.string().optional()}),Zs=p.object({events:p.array(p.string()).min(1),match:p.record(p.string(),Ws).optional()}),mh=p.object({type:p.literal("event_count"),key:p.string(),operator:p.enum(["gte","lte","eq","gt","lt"]),count:p.number().int().min(0),withinMs:p.number().positive().optional(),counter:Zs.optional()}),un=p.discriminatedUnion("type",[oh,ih,sh,lh,uh,ch,dh,fh,ph,hh,mh]),Xs=p.object({conditions:p.array(un),value:p.unknown()}),Ys=p.object({type:p.literal("rules"),rules:p.array(Xs),default:p.unknown()}),Ks=p.object({type:p.literal("score"),field:p.string(),threshold:p.number(),above:p.unknown(),below:p.unknown()}),Qs=p.object({type:p.literal("model"),modelId:p.string(),inputs:p.array(p.string()),outputMapping:p.record(p.string(),p.unknown()),default:p.unknown()}),Js=p.object({type:p.literal("external"),endpoint:p.string(),method:p.enum(["GET","POST"]).optional(),default:p.unknown(),timeoutMs:p.number().optional()}),el=p.discriminatedUnion("type",[Ys,Ks,Qs,Js]),pc=el.nullable().optional(),EP=p.object({events:p.array(p.string()),urlContains:p.string().optional(),props:p.record(p.union([p.string(),p.number(),p.boolean()])).optional()}),TP=p.object({title:p.string().optional(),body:p.string().optional(),icon:p.string().optional()}).nullable().optional();var yb=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.")}),hc=p.object({routes:yb,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 RP(t){return un.safeParse(t)}function MP(t){return el.safeParse(t)}function DP(t){return hc.safeParse(t)}var OP=[{defName:"matchOp",schema:Ws},{defName:"counterDef",schema:Zs},{defName:"activationConfig",schema:hc},{defName:"routeFilter",schema:yb},{defName:"ruleStrategy",schema:Ys},{defName:"scoreStrategy",schema:Ks},{defName:"modelStrategy",schema:Qs},{defName:"externalStrategy",schema:Js},{defName:"rule",schema:Xs},{defName:"condition",schema:un}];var xb=p.object({tileId:p.string(),itemId:p.string().optional()}).strict(),BP=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:xb.optional()}).strict(),FP=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:hc.optional(),notifications:p.array(BP).optional()}).strict(),NP=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()}),PP=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()}),HP=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()}),UP=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()}),qP=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()}),zP=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()}),VP=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:NP.optional(),launcher:PP.optional(),tile:HP.optional(),overlay:UP.optional(),notification:qP.optional(),content:zP.optional()}).strict(),$P=p.object({enabled:p.boolean().optional(),label:p.string().optional(),icon:p.string().optional(),position:p.string().optional(),animate:p.boolean().optional(),animationStyle:p.enum(["pulse","bounce","glow"]).optional(),notificationCount:p.number().optional()}).strict(),$z=p.object({schemaVersion:p.string().optional(),fetchedAt:p.string().datetime(),configVersion:p.string().optional(),canvasTitle:p.string().optional(),tiles:p.array(FP),actions:p.array(p.any()),theme:VP.optional(),launcher:$P.optional(),meta:p.object({verificationSteps:p.array(p.union([p.string(),p.object({text:p.string(),check:un.optional()})])).optional()}).passthrough().optional()}).strict();var gt={triggerWhen:pc},xa=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),bb=p.object({color:p.string().optional(),scrimOpacity:p.number().min(0).max(1).optional(),paddingPx:p.number().optional(),radiusPx:p.number().optional()}).strict(),Sb=p.enum(["top-left","top-right","bottom-left","bottom-right"]),Cb=p.enum(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),vh=p.object({label:p.string(),actionId:p.string(),primary:p.boolean().optional()}).strict(),_b=p.object({title:p.string().optional(),body:p.string(),ctaButtons:p.array(vh).optional()}).strict(),wb=p.object({title:p.string().optional(),body:p.string()}).strict(),Lb=p.enum(["before","after","prepend","append","replace"]),Ib=p.enum(["immediate","hover","click"]),Ab=p.object({widgetId:p.string(),props:p.record(p.unknown()).optional(),priority:p.number().optional()}).strict(),kb=p.object({id:p.string(),action:p.any(),route:p.string().optional(),onAction:p.record(p.string()).optional()}).passthrough(),Eb=p.enum(["auto","smooth","instant"]),gh=p.enum(["start","center","end","nearest"]),Tb=p.object({kind:p.literal("content:setText"),anchorId:xa,text:p.string(),label:p.string().optional()}).extend(gt).strict(),Rb=p.object({kind:p.literal("content:setAttr"),anchorId:xa,attr:p.string(),value:p.string(),label:p.string().optional()}).extend(gt).strict(),Mb=p.object({kind:p.literal("content:addClass"),anchorId:xa,className:p.string(),label:p.string().optional()}).extend(gt).strict(),Db=p.object({kind:p.literal("content:removeClass"),anchorId:xa,className:p.string(),label:p.string().optional()}).extend(gt).strict(),Ob=p.object({kind:p.literal("content:setStyle"),anchorId:xa,styles:p.record(p.string()),label:p.string().optional()}).extend(gt).strict(),Bb=p.object({kind:p.literal("content:insertHtml"),anchorId:xa,html:p.string(),position:Lb,deepLink:xb.optional(),label:p.string().optional()}).extend(gt).strict(),Fb=p.object({kind:p.literal("overlays:highlight"),anchorId:xa,style:bb.optional(),duration:p.number().optional(),label:p.string().optional()}).extend(gt).strict(),Nb=p.object({kind:p.literal("overlays:pulse"),anchorId:xa,duration:p.number().optional(),label:p.string().optional()}).extend(gt).strict(),Pb=p.object({kind:p.literal("overlays:badge"),anchorId:xa,content:p.string(),position:Sb.optional(),label:p.string().optional()}).extend(gt).strict(),Hb=p.object({kind:p.literal("overlays:tooltip"),anchorId:xa,content:_b,trigger:Ib.optional(),placement:Cb.optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(gt).strict(),Ub=p.object({kind:p.literal("overlays:modal"),content:wb,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(vh).optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(gt).strict(),qb=p.object({kind:p.literal("navigation:scrollTo"),anchorId:xa,behavior:Eb.optional(),block:gh.optional(),inline:gh.optional(),label:p.string().optional()}).extend(gt).strict(),zb=p.object({kind:p.literal("navigation:navigate"),url:p.string(),target:p.enum(["_self","_blank"]).optional(),label:p.string().optional()}).extend(gt).strict(),Vb=p.object({kind:p.literal("core:mountWidget"),slot:p.string(),widget:Ab,label:p.string().optional()}).extend(gt).strict(),$b=p.object({kind:p.literal("core:wait"),durationMs:p.number().min(0).optional(),event:p.string().optional(),label:p.string().optional()}).extend(gt).strict(),jb=p.object({kind:p.literal("core:sequence"),actions:p.array(p.any()),label:p.string().optional()}).extend(gt).strict(),Gb=p.object({kind:p.literal("core:parallel"),actions:p.array(p.any()),waitFor:p.enum(["all","any"]).optional(),label:p.string().optional()}).extend(gt).strict(),Wb=p.object({kind:p.literal("core:tour"),tourId:p.string(),steps:p.array(kb).min(1),startStep:p.string().optional(),autoStart:p.boolean().optional(),label:p.string().optional()}).extend(gt).passthrough(),yE=[{defName:"setText",schema:Tb},{defName:"setAttr",schema:Rb},{defName:"addClass",schema:Mb},{defName:"removeClass",schema:Db},{defName:"setStyle",schema:Ob},{defName:"insertHtml",schema:Bb},{defName:"highlight",schema:Fb},{defName:"pulse",schema:Nb},{defName:"badge",schema:Pb},{defName:"tooltip",schema:Hb},{defName:"modal",schema:Ub},{defName:"scrollTo",schema:qb},{defName:"navigate",schema:zb},{defName:"mountWidget",schema:Vb},{defName:"wait",schema:$b},{defName:"sequence",schema:jb},{defName:"parallel",schema:Gb},{defName:"tour",schema:Wb}];function yh(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(x){if(!e)return null;try{return e.querySelector(x)}catch{return null}}function l(){for(let[x,f]of r){let g=s(x);if(g){for(let v of f)clearTimeout(v.timer),v.resolve(g);r.delete(x)}}for(let[x,f]of n){let g=s(x);if(g){for(let v of f)v.cancelled||v.cb(g);n.delete(x)}}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(x,f){let g=r.get(x);g&&(g.delete(f),g.size===0&&r.delete(x)),r.size===0&&n.size===0&&c()}function h(x,f){if(i)return Promise.reject(new Error("AnchorResolver destroyed"));let g=s(x);if(g)return Promise.resolve(g);let v=f??a;return new Promise((y,_)=>{let w={resolve:y,reject:_,timer:setTimeout(()=>{d(x,w),_(new Error(`waitFor("${x}") timed out after ${v}ms`))},v)},C=r.get(x);C||(C=new Set,r.set(x,C)),C.add(w),u()})}function m(x,f){if(i)return()=>{};let g=s(x);if(g)return f(g),()=>{};let v={cb:f,cancelled:!1},y=n.get(x);return y||(y=new Set,n.set(x,y)),y.add(v),u(),()=>{v.cancelled=!0;let _=n.get(x);_&&(_.delete(v),_.size===0&&n.delete(x)),r.size===0&&n.size===0&&c()}}function S(){let x=0;for(let f of r.values())x+=f.size;return x}function b(){i=!0,c();let x=new Error("AnchorResolver destroyed");for(let f of r.values())for(let g of f)clearTimeout(g.timer),g.reject(x);r.clear(),n.clear()}return{resolve:s,waitFor:h,onAppear:m,pendingCount:S,destroy:b}}function jP(){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 Zb(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(xE(a,r))return}if(e.include){for(let r of e.include)if(xE(a,r))return r;return}return a}function xE(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 mc=class{constructor(e){$(this,"context");$(this,"previousContext");$(this,"listeners",new Set);$(this,"telemetry");$(this,"routes");$(this,"navigation");$(this,"cleanupFns",[]);if(this.telemetry=e.telemetry,this.routes=e.routes,this.navigation=e.navigation,this.context=jP(),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=Zb(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=Zb(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=Zb(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 xh(t){return new mc(t)}var bE=p.object({url:p.string(),routeId:p.string().optional(),title:p.string().optional(),locale:p.string().optional()}),SE=p.object({url:p.string(),ts:p.number()}),CE=p.object({sessionId:p.string(),startTs:p.number(),pageHistory:p.array(SE).optional()}),_E=p.object({width:p.number(),height:p.number()}),wE=p.object({x:p.number(),y:p.number(),w:p.number(),h:p.number()}),LE=p.object({anchorId:p.string(),present:p.boolean(),visible:p.boolean().optional(),boundingBox:wE.optional()}),IE=p.record(p.string(),p.union([p.number(),p.string(),p.boolean(),p.undefined()])),AE=p.object({page:bE,session:CE,viewport:_E,anchors:p.array(LE).optional(),augmented:IE.optional()});function GP(t){return AE.safeParse(t)}function Xb(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=typeof t.anchorId=="string"?t.anchorId:t.anchorId?.selector??"",i=a.anchors?.find(s=>s.anchorId===o);switch(t.state){case"visible":return i?.visible===!0;case"present":return i?.present===!0;case"absent":return!i?.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 Yb(t,e){let a=[];for(let r of t.conditions){let n=Xb(r,e);if(a.push({condition:r,result:n}),!n)return{matched:!1,conditionResults:a}}return{matched:!0,conditionResults:a}}function gc(t,e){for(let a=0;a<t.rules.length;a++){let r=t.rules[a],{matched:n,conditionResults:o}=Yb(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 vc(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 kE(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 Kb(t,e,a={}){let r=kE(e,a);switch(t.type){case"rules":return gc(t,r);case"score":return vc(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 Qb(t,e,a={}){let r=kE(e,a);switch(t.type){case"rules":return gc(t,r);case"score":return vc(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 bh(t){return{evaluate:(e,a)=>Kb(e,a,t),evaluateSync:(e,a)=>Qb(e,a,t)}}function Sh(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 h=i.get(d.stateKey)||{count:0};h.count++,d.needsTimestamps&&(h.timestamps||(h.timestamps=[]),h.timestamps.push(u.ts),h.timestamps.length>200&&(h.timestamps=h.timestamps.slice(-200))),i.set(d.stateKey,h),c=!0}if(c)for(let d of n)try{d()}catch(h){console.error("[EventAccumulator] Subscriber error:",h)}}function l(){o||r.size===0||(o=e.subscribe(s))}return{register(u,c,d=!1){let h=`ev:${u}`,m=r.get(h);if(m){d&&!m.needsTimestamps&&(m.needsTimestamps=!0);return}r.set(h,{stateKey:h,needsTimestamps:d,predicate:c}),l()},getCount(u,c){let d=`ev:${u}`,h=i.get(d);if(!h)return 0;if(c===void 0||!h.timestamps)return h.count;let m=Date.now()-c;return h.timestamps.filter(S=>S>=m).length},subscribe(u){return n.add(u),()=>{n.delete(u)}},destroy(){o&&(o(),o=null),r.clear(),n.clear()}}}function Jb(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 yc=class{constructor(e={}){$(this,"subscriptions",new Set);$(this,"history",[]);$(this,"maxHistorySize");this.maxHistorySize=e.maxHistorySize??100}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:Go};this.publishEvent(n)}publishEvent(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift();for(let a of this.subscriptions)if(Jb(e,a.filter))try{a.callback(e)}catch(r){console.error("[EventBus] Subscriber error:",r)}}getRecent(e,a){let r=this.history;return e&&(r=r.filter(n=>Jb(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=>Jb(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 tl(t={}){return new yc(t)}var EE={$autocapture:"ui.click",$click:be.UI_CLICK,$scroll:be.UI_SCROLL,$input:be.UI_INPUT,$change:be.UI_CHANGE,$submit:be.UI_SUBMIT,$pageview:be.NAV_PAGE_VIEW,$pageleave:be.NAV_PAGE_LEAVE,$session_start:"session.start",$identify:"user.identify"};function WP(t){let e=t.event;if(typeof e!="string")return"posthog.unknown";if(EE[e])return EE[e];if(e==="$autocapture"){let a=t.properties?.$tag_name,r=t.properties?.$event_type;return r==="submit"?be.UI_SUBMIT:r==="change"?be.UI_CHANGE:a==="input"||a==="textarea"?be.UI_INPUT:be.UI_CLICK}return e.startsWith("$")?e.replace("$","posthog."):`posthog.${e}`}function ZP(t){let e={},a=t.properties||{},r=a.$elements;return a.$tag_name?e.tagName=a.$tag_name:r?.[0]?.tag_name&&(e.tagName=r[0].tag_name),a.$el_text&&(e.elementText=a.$el_text),r&&(e.elements=r),a.$current_url&&(e.url=a.$current_url),a.$pathname&&(e.pathname=a.$pathname),a.$host&&(e.host=a.$host),a.$viewport_width&&(e.viewportWidth=a.$viewport_width),a.$viewport_height&&(e.viewportHeight=a.$viewport_height),a.$session_id&&(e.sessionId=a.$session_id),a.$scroll_depth&&(e.scrollDepth=a.$scroll_depth),a.$scroll_percentage&&(e.scrollPercentage=a.$scroll_percentage),e.originalEvent=t.event,e}function eS(t){let e;return typeof t.timestamp=="number"?e=t.timestamp:typeof t.timestamp=="string"?e=new Date(t.timestamp).getTime():e=Date.now(),{ts:e,name:WP(t),source:"posthog",props:ZP(t),schemaVersion:Go}}function tS(t){let e=t.event;return!(typeof e!="string"||["$feature_flag_called","$feature_flags","$groups","$groupidentify","$set","$set_once","$unset","$create_alias","$capture_metrics","$performance_event","$web_vitals","$exception","$dead_click","$heatmap"].includes(e))}function Ch(t){return(e,a)=>{if(typeof e!="string")return;let r={event:e,properties:a,timestamp:Date.now()};if(tS(r)){let n=eS(r);t(n)}}}var aS=p.enum(["posthog","canvas","derived"]),TE=p.object({ts:p.number(),name:p.string(),source:aS,props:p.record(p.string(),p.unknown()).optional(),schemaVersion:p.string()}),RE=p.object({names:p.array(p.string()).optional(),patterns:p.array(p.string()).optional(),sources:p.array(aS).optional()});function XP(t){return TE.safeParse(t)}function YP(t){return RE.safeParse(t)}var al=class{constructor(){$(this,"listeners",new Set);$(this,"capturedPushState");$(this,"capturedReplaceState");$(this,"wasNative");$(this,"destroyed",!1);$(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 rS="cooldown:";function ME(t){return{set(e,a){let r=rS+e,n=Date.now()+a;t.set(r,n)},isActive(e){return this.remaining(e)>0},remaining(e){let a=rS+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=rS+e;t.remove(a)}}}var xc="dismissed:";function DE(t,e){return{mark(a,r=!1){let n=xc+a;(r?e:t).set(n,!0)},isDismissed(a){let r=xc+a;return t.has(r)||e.has(r)},clear(a){let r=xc+a;t.remove(r),e.remove(r)},clearAll(){for(let a of t.keys())a.startsWith(xc)&&t.remove(a);for(let a of e.keys())a.startsWith(xc)&&e.remove(a)}}}var nS="freq:";function OE(t){function e(a){let r=nS+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=nS+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=nS+a;t.remove(r)},hasReachedLimit(a,r){return this.count(a)>=r}}}var KP="syntro";function oS(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 bc(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 Sc=class{constructor(e={}){$(this,"session");$(this,"user");$(this,"dismissals");$(this,"cooldowns");$(this,"frequency");$(this,"namespace");$(this,"namespacedStorages",new Map);this.namespace=e.namespace??KP;let a=r=>typeof r=="object"&&r!==null&&typeof r.setItem=="function";typeof window<"u"?(this.session=a(window.sessionStorage)?oS(window.sessionStorage,this.namespace):bc(this.namespace),this.user=a(window.localStorage)?oS(window.localStorage,this.namespace):bc(this.namespace)):(this.session=bc(this.namespace),this.user=bc(this.namespace)),this.dismissals=DE(this.session,this.user),this.cooldowns=ME(this.user),this.frequency=OE(this.session)}ns(e){let a=`${this.namespace}:${e}`;if(!this.namespacedStorages.has(a)){let r=typeof window<"u"&&typeof sessionStorage<"u"?oS(sessionStorage,a):bc(a);this.namespacedStorages.set(a,r)}return this.namespacedStorages.get(a)}};function _h(t={}){return new Sc(t)}function rl(t){return t.startsWith("inline:")?"inline":t.startsWith("adjacent:")?"adjacent":"static"}function Cc(t){return t.startsWith("inline:")?t.slice(7):t.startsWith("adjacent:")?t.slice(9):null}var iS={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"}},nl={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:[]},BE={duration:200,easing:"cubic-bezier(0.16, 1, 0.3, 1)",fill:"forwards"};function wh(t,e,a){let r=iS[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 Lh(t,e,a){let r=a.placement==="auto"?"bottom":a.placement,n=[gf(a.offset?{mainAxis:a.offset.y,crossAxis:a.offset.x}:8)];return a.flip!==!1&&n.push(yf()),a.shift!==!1&&n.push(vf({padding:8})),t.style.position="absolute",t.style.zIndex="2147483646",mf(e,t,async()=>{let{x:i,y:s,strategy:l}=await xf(e,t,{placement:r,middleware:n});Object.assign(t.style,{position:l,left:`${i}px`,top:`${s}px`})})}function Ih(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 Ah(t,e){return e==="none"||nl[e].length===0?null:t.animate(nl[e],BE)}function kh(t,e){if(e==="none"||nl[e].length===0)return Promise.resolve();let a=[...nl[e]].reverse(),r=t.animate(a,BE);return new Promise(n=>{r.onfinish=()=>n(),r.oncancel=()=>n()})}function Eh(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 Th(t){switch(rl(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 FE(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(),h=c.startsWith("on"),m=(c==="href"||c==="src")&&d.startsWith("javascript:");(h||m)&&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 QP=0;function Rh(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-${++QP}`}function c(y,_){a&&a.publish(y,_)}function d(y){let _=l.get(y);if(_){let w=x(y);for(let C of _)try{C(w)}catch(L){console.error("[Surfaces] State callback error:",L)}}}let h=new Map;function m(y,_,w){switch(_.type){case"html":y.innerHTML=FE(_.content);return;case"widget":{if(o?.has(_.widgetId)){let C=o.mount(_.widgetId,y,_.config);return w&&h.set(w,C),()=>{C.unmount(),w&&h.delete(w)}}console.warn(`[Surfaces] Widget not found: ${_.widgetId}`),y.innerHTML=`<div data-widget-id="${_.widgetId}" data-widget-missing="true">Widget: ${_.widgetId}</div>`;return}case"custom":return _.mount(y);case"react":y.innerHTML="<div data-react-component>React Component</div>";return;default:console.warn("[Surfaces] Unknown content type");return}}function S(y,_,w){let C=u(),L=rl(y),k=w?.priority??0,A=w?.animation??n,M=w?.exclusive??!0,T=i.get(y);if(T&&M){if(T.options.priority>k)throw new Error(`Slot ${y} is occupied by higher priority content (${T.options.priority} > ${k})`);b(T)}let R=Eh(y,C);R.style.zIndex=String(Th(y));let B;if(L==="static")wh(R,y,w?.constraints),e.appendChild(R);else if(L==="inline"){let N=Cc(y);if(!N)throw new Error(`Invalid inline slot: ${y}`);if(!r)throw new Error("Anchor resolver required for inline slots");let W=r({selector:N,route:"**"});if(!W)throw new Error(`Anchor not found for inline slot: ${N}`);B=Ih(R,W)}else if(L==="adjacent"){let N=Cc(y);if(!N)throw new Error(`Invalid adjacent slot: ${y}`);if(!r)throw new Error("Anchor resolver required for adjacent slots");let W=r({selector:N,route:"**"});if(!W)throw new Error(`Anchor not found for adjacent slot: ${N}`);e.appendChild(R),B=Lh(R,W,w?.position??{placement:"bottom"})}let F=m(R,_,C);Ah(R,A);let P={id:C,slot:y,content:_,options:{priority:k,exclusive:M,animation:A,position:w?.position??{placement:"auto"},constraints:w?.constraints??{},adaptiveId:w?.adaptiveId,autoUnmountOnRouteChange:w?.autoUnmountOnRouteChange??!0},container:R,cleanup:()=>{B?.(),F?.()},mountedAt:Date.now()};return i.set(y,P),s.set(y,(s.get(y)??0)+1),c("surface.mounted",{slot:y,id:C,adaptiveId:w?.adaptiveId}),d(y),{id:C,update(N){let W=i.get(y);if(!W||W.id!==C)throw new Error("Mount no longer active");let Q=h.get(C);if(Q){if(N.type==="widget"){Q.update(N.config),W.content=N;return}Q.unmount(),h.delete(C)}W.container.innerHTML="";let aa=m(W.container,N,C);if(W.content=N,aa){let dt=W.cleanup;W.cleanup=()=>{dt?.(),aa()}}},setOptions(N){let W=i.get(y);if(!W||W.id!==C)throw new Error("Mount no longer active");N.priority!==void 0&&(W.options.priority=N.priority),N.animation!==void 0&&(W.options.animation=N.animation),N.constraints&&L==="static"&&(N.constraints.maxWidth&&(W.container.style.maxWidth=N.constraints.maxWidth),N.constraints.maxHeight&&(W.container.style.maxHeight=N.constraints.maxHeight),N.constraints.minWidth&&(W.container.style.minWidth=N.constraints.minWidth),N.constraints.minHeight&&(W.container.style.minHeight=N.constraints.minHeight)),d(y)},async unmount(){let N=i.get(y);!N||N.id!==C||await b(N)},isMounted(){return i.get(y)?.id===C},getContainer(){let N=i.get(y);return N?.id===C?N.container:null}}}async function b(y){await kh(y.container,y.options.animation),y.cleanup?.(),y.container.remove(),i.delete(y.slot),c("surface.unmounted",{slot:y.slot,id:y.id}),d(y.slot)}function x(y){let _=i.get(y);return{slot:y,occupied:!!_,currentPriority:_?.options.priority,currentAdaptiveId:_?.options.adaptiveId,mountCount:s.get(y)??0,currentMountId:_?.id}}function f(y,_){let w=l.get(y);return w||(w=new Set,l.set(y,w)),w.add(_),()=>{w?.delete(_),w?.size===0&&l.delete(y)}}function g(y,_){let w=i.get(y);return w?_!==void 0?_>=w.options.priority:!1:!0}function v(){for(let y of i.values())try{y.cleanup?.(),y.container.remove()}catch(_){console.error("[Surfaces] Error during cleanup:",_)}i.clear(),l.clear()}return{mount:S,getState:x,onStateChange:f,canMount:g,destroy:v}}var _c=class{constructor(){$(this,"widgets",new Map);$(this,"mountedWidgets",new Map);$(this,"mountIdCounter",0);$(this,"runtimeRef");$(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&&(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},h=n.widget.mount(a,d);c.cleanup=h??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()}},Mh=new _c;var lS="2.0.0";function JP(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(sS(r,n))return!1}if(e.include&&e.include.length>0){for(let n of e.include)if(sS(r,n))return!0;return!1}return!0}function sS(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 NE(t){let a=(typeof window<"u"?window.location.pathname:"/").replace(/\/$/,"")||"/";return(Array.isArray(t.route)?t.route:[t.route]).some(n=>sS(a,n))}function Dh(t={}){let{telemetry:e,sessionMetrics:a,routes:r,mode:n="production",namespace:o}=t,i=t.widgets??Mh,s=t.executors??br,l=t.apps??fs,u=new al,c=xh({telemetry:e,routes:r,navigation:u}),d=t.events??tl(),h=_h({namespace:o}),m=Sh({eventBus:d,stateStore:h}),S=bh({state:h,events:d,sessionMetrics:a,accumulator:m}),b=$I(),x=yh(),f=C=>NE(C)?x.resolve(C.selector):null,g=async(C,L)=>{if(!NE(C))return null;try{return await x.waitFor(C.selector,L)}catch{return null}},v=Rh({overlayRoot:b,eventBus:d,anchorResolver:f,widgetRegistry:i}),y=nh({overlayRoot:b,eventBus:d,surfaces:v,anchorResolver:f,waitForAnchor:g,executorRegistry:s,subscribeNavigation:C=>u.subscribe(C),runtime:{evaluateSync:C=>S.evaluateSync(C,c.get()),context:c,accumulator:m}}),_;if(a){a.increment("page_views");let C=typeof window<"u"?window.location.pathname:"/";_=u.subscribe((L,k)=>{if(k!=="replaceState")try{let A=new URL(L).pathname;A!==C&&(C=A,a.increment("page_views"))}catch{}})}let w={telemetry:e,context:c,events:d,state:h,sessionMetrics:a,actions:y,surfaces:v,widgets:i,executors:s,apps:l,accumulator:m,anchorResolver:x,navigation:u,version:lS,mode:n,async evaluate(C){return S.evaluate(C,c.get())},evaluateSync(C){return S.evaluateSync(C,c.get())},async filterTiles(C){let L=c.get().page.url,k=[];for(let A of C){let M=A.activation;if(!M){k.push(A);continue}if(JP(L,M.routes)){if(M.onlyIfPopulated){let T=A.props?.actions??[];if(T.length>0&&!T.some(B=>B.triggerWhen?S.evaluateSync(B.triggerWhen,c.get()).value:!0))continue}k.push(A)}}return k},setRoutes(C){c.setRoutes(C)},destroy(){l.unbind().catch(C=>{console.error("[Runtime] Error unbinding apps registry:",C)}),_?.(),x.destroy(),m.destroy(),u.destroy(),c.destroy(),y.destroy(),v.destroy()}};return l.bind(w),i.bindRuntime(w),w}var PE=p.object({value:p.unknown(),expiresAt:p.number().optional()}),HE=p.object({count:p.number(),resetAt:p.number().optional()});function eH(t){return PE.safeParse(t)}function tH(t){return HE.safeParse(t)}var UE={growthbook:t=>dp({...t,autoInit:!0})};function qE(t,e){let a=UE[t];if(!a)throw new Error(`Unknown experiment provider: ${t}. Supported: ${Object.keys(UE).join(", ")}`);return a(e)}var aH=["cdn.syntrologie.com","localhost","127.0.0.1"];function rH(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):aH.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 uS=class{constructor(e){$(this,"name","cdn");$(this,"url");$(this,"integrity");if(this.url=`${e.baseUrl}/${e.configId}.json`,this.integrity=e.integrity,!rH(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 nH(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 nH(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 zE(t){return new uS(t)}var oH="syntro_exp",iH="syntro_var",cS=class{constructor(e){$(this,"name","experiments");$(this,"client");$(this,"featureKey");$(this,"manifestKey");$(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(oH),i=n.get(iH);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){let n=this.fetchMultiFlag();if(n){let o=performance.now()-e;return{config:n,meta:{source:"experiments",fetchTimeMs:o,cached:!0}}}}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:kf(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.variantFlagPrefix&&this.client.getAllFeatures){let e=this.client.getAllFeatures();return Object.keys(e).filter(a=>a.startsWith(this.variantFlagPrefix))}return[]}};function VE(t){return new cS(t)}var sH="https://cdn.syntrologie.com/configs",$E={cdn:t=>{if(!t.configId)throw new Error("CDN fetcher requires 'configId' option");return zE({baseUrl:t.baseUrl??sH,configId:t.configId,integrity:t.integrity})},experiments:t=>{if(!t.featureKey)throw new Error("Experiments fetcher requires 'featureKey' option");return VE({featureKey:t.featureKey})}};function jE(t,e={}){let a=$E[t];if(!a)throw new Error(`Unknown config fetcher type: ${t}. Supported: ${Object.keys($E).join(", ")}`);return a(e)}var GE={posthog:t=>th(t),noop:()=>bp()};function WE(t,e){let a=GE[t];if(!a)throw new Error(`Unknown telemetry provider: ${t}. Supported: ${Object.keys(GE).join(", ")}`);return a(e)}var dS="syn_";function wc(t){if(!t.startsWith(dS))throw new Error("Invalid Syntro token: must start with 'syn_'");let a=t.slice(dS.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 Oh(t){let e=JSON.stringify(t),a=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return dS+a}function cn(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{}}function lH(){if(typeof window>"u")return X("Syntro Bootstrap","isEditorMode: not in browser"),!1;let t=$o(),a=!!($n()?.token&&t?.mode==="editor");return X("Syntro Bootstrap","isEditorMode:",a),a}function uH(){if(typeof window>"u")return X("Syntro Bootstrap","isAuditMode: not in browser"),!1;let t=$o(),a=!!($n()?.token&&t?.mode==="audit");return X("Syntro Bootstrap","isAuditMode:",a),a}function cH(){if(typeof window>"u")return X("Syntro Bootstrap","isReviewMode: not in browser"),!1;let t=$o(),a=!!($n()?.token&&t?.mode==="review");return X("Syntro Bootstrap","isReviewMode:",a),a}var ZE="syntro_segment_attributes";function dH(){if(typeof window>"u")return{};try{let t=localStorage.getItem(ZE);if(t){let e=JSON.parse(t);return X("Syntro Bootstrap","Loaded cached segment attributes:",e),e}}catch(t){ga("Syntro Bootstrap","Failed to load cached segment attributes:",t)}return{}}function fH(t){if(!(typeof window>"u"))try{localStorage.setItem(ZE,JSON.stringify(t)),X("Syntro Bootstrap","Cached segment attributes:",t)}catch(e){ga("Syntro Bootstrap","Failed to cache segment attributes:",e)}}function pH(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 hH(){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{t.page_url=window.location.href,t.page_path=window.location.pathname}catch{}return t}async function mH(t){jv(),X("Syntro Bootstrap","====== INIT ======"),X("Syntro Bootstrap","Options:",{hasToken:!!t.token,tokenPrefix:`${t.token?.slice(0,15)}...`,hasCanvasOptions:!!t.canvas});let e=lH(),a=uH(),r=cH(),n=e?"editor":a?"audit":r?"review":null;if(console.log(`[DIAG] Mode detection: editor=${e}, audit=${a}, review=${r}, sdkMode=${n}`),console.log("[DIAG] editorSource:",$n()),console.log("[DIAG] editorConf:",$o()),X("Syntro Bootstrap","SDK mode:",n??"normal"),!n&&typeof window<"u"){let T=!!window.__SYNTRO_EDITOR_PARAMS__,R=!!window.__SYNTRO_AUDIT_LEGEND__,B=!!window.__SYNTRO_REVIEW_DATA__;if(T||R||B){let F=[T&&"__SYNTRO_EDITOR_PARAMS__",R&&"__SYNTRO_AUDIT_LEGEND__",B&&"__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 o=t.token;if(!o&&n){let R=$o()?.syntro_token;R?.startsWith("syn_")&&(o=R,X("Syntro Bootstrap",`\u2713 Using syntro_token from editor_conf (${n} mode)`))}let i;if(o)if(o.startsWith("syn_"))X("Syntro Bootstrap","Token starts with syn_, decoding..."),i=wc(o),jv(i.d);else if(n)X("Syntro Bootstrap",`\u2713 Non-syn_ token allowed (${n} mode)`);else throw Ef("Syntro Bootstrap","\u274C Token does not start with syn_ and NOT in editor/audit/review mode!"),Ef("Syntro Bootstrap","Token received:",o),new Error("Invalid Syntro token: must start with 'syn_'");else if(n)X("Syntro Bootstrap",`\u2713 No token, but ${n} mode - proceeding`);else throw Ef("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 s=cn("NEXT_PUBLIC_SYNTRO_EXPERIMENT_HOST")||cn("VITE_SYNTRO_EXPERIMENT_HOST")||i?.eh,l=cn("NEXT_PUBLIC_SYNTRO_TELEMETRY_HOST")||cn("VITE_SYNTRO_TELEMETRY_HOST")||i?.th,u=cn("NEXT_PUBLIC_SYNTRO_EDITOR_URL")||cn("VITE_SYNTRO_EDITOR_URL")||t.canvas?.editorUrl,c=dH(),d=hH(),h={...d,...c};X("Syntro Bootstrap","Phase 1: Browser metadata:",d),X("Syntro Bootstrap","Phase 1: Cached segment attributes:",c);let m,S=tl();console.log("[Syntro Bootstrap] EventBus created");let b=Ch(T=>{S.publishEvent(T)}),x=T=>{X("Syntro Bootstrap","Phase 2: PostHog feature flags loaded");let R=pH(T);if(X("Syntro Bootstrap","Segment flags from PostHog:",R),fH(R),m){let B=g?.getAll?.()??{},F={...d,...B,...R};X("Syntro Bootstrap","Updating GrowthBook with attributes:",F),m.setAttributes?.(F)}},f;if(i?.t){let T=i.t==="noop"?"noop":"posthog";f=WE(T,{apiKey:i.t,apiHost:l,enableFeatureFlags:!0,onFeatureFlagsLoaded:x,onCapture:b}),console.log(`[Syntro Bootstrap] Telemetry client created (${T}) with EventBus wiring`)}let g;i?.e&&(m=qE("growthbook",{clientKey:i.e,apiHost:s,attributes:h,onExperimentViewed:f?.trackExperiment?(T,R,B)=>{f.trackExperiment(T,R,B)}:void 0})),g=fp({experiments:m,onMetricChange:(T,R)=>{X("Syntro Bootstrap",`Session metric changed: ${T} = ${R}`)}}),X("Syntro Bootstrap","SessionMetricTracker created");let v="production";e?v="editor":a?v="audit":cn("NODE_ENV")==="development"&&(v="development");let y=Dh({telemetry:f,sessionMetrics:g,mode:v,events:S});X("Syntro Bootstrap","Runtime created:",{version:y.version,mode:y.mode,hasContext:!!y.context,hasEvents:!!y.events,hasState:!!y.state}),X("Syntro Bootstrap","Core app executors already registered");let _=t.cdnBase||cn("NEXT_PUBLIC_SYNTRO_CDN_BASE")||cn("VITE_SYNTRO_CDN_BASE")||"https://cdn.syntrologie.com",w=Lf({cdnBase:_,registry:y.apps,onLoadStart:T=>{X("Syntro Bootstrap",`Loading app from CDN: ${T}`)},onLoadEnd:(T,R,B)=>{R?X("Syntro Bootstrap",`App loaded successfully: ${T}`):ga("Syntro Bootstrap",`Failed to load app: ${T}`,B)}});typeof window<"u"&&(window.SynOS={...window.SynOS,appRegistry:y.apps,runtime:y,version:y.version},X("Syntro Bootstrap","Global SynOS object exposed"));let C=y.apps.list?.()??[];console.log(`[DIAG] Activation loop: ${C.length} apps in registry:`,C.map(T=>`${T.manifest.id}(${T.state})`).join(", "));for(let T of C)if(T.state==="registered")try{await y.apps.activate(T.manifest.id),console.log(`[DIAG] Activated: ${T.manifest.id} \u2192 widgets: [${y.widgets.list().join(", ")}]`)}catch(R){console.error(`[DIAG] FAILED to activate: ${T.manifest.id}`,R),ga("Syntro Bootstrap",`Failed to auto-activate built-in app: ${T.manifest.id}`,R)}if(console.log(`[DIAG] Activation complete. Total widgets: [${y.widgets.list().join(", ")}]`),m?.refreshFeatures)try{await m.refreshFeatures(),X("Syntro Bootstrap","GrowthBook features loaded")}catch(T){ga("Syntro Bootstrap","Failed to load GrowthBook features:",T)}let L;if(t.fetcher)L=t.fetcher;else if(i?.f){let T=jE(i.f,i.o??{});L=async()=>{let R=await T.fetch();return{...R.config,tiles:R.config.tiles??[]}}}else m&&(L=Vo({experiments:m}));let k=new Set,A=L?async()=>{let T=await L();console.log("[Syntro Bootstrap] Config fetched:",`tiles=${T.tiles?.length??0},`,`actions=${T.actions?.length??0},`,`theme=${T.theme?.name??"none"}`),T.actions?.length>0&&console.log("[Syntro Bootstrap] Actions in config:",T.actions.map((F,P)=>`[${P}] ${F.kind}${F.anchorId?` anchor="${typeof F.anchorId=="string"?F.anchorId:F.anchorId.selector}"`:""}${F.label?` "${F.label}"`:""}`).join(", "));let R=T,B=w.getRequiredApps(R);return B.length>0?console.log("[Syntro Bootstrap] Required external apps:",B.join(", ")):X("Syntro Bootstrap","No external apps required (all executors are built-in)"),B.length>0&&await w.loadAppsForConfig(R).then(async P=>{let Y=P.filter(Q=>Q.success),N=P.filter(Q=>!Q.success);Y.length>0&&console.log(`[Syntro Bootstrap] Apps loaded from CDN: ${Y.map(Q=>Q.appId).join(", ")}`);let W=N.filter(Q=>!k.has(Q.appId));W.length>0&&(console.error("[Syntro Bootstrap] Apps FAILED to load from CDN:",W.map(Q=>`${Q.appId} (${Q.error})`).join(", ")),W.forEach(Q=>k.add(Q.appId)));for(let Q of B)if(y.apps.has(Q))try{await y.apps.activate(Q),console.log(`[Syntro Bootstrap] App activated: ${Q}`)}catch(aa){console.error(`[Syntro Bootstrap] Failed to activate app: ${Q}`,aa)}else console.error(`[Syntro Bootstrap] App "${Q}" required by config but NOT registered.`,`Available apps: [${Array.from(y.apps.list?.()??[]).join(", ")}]`)}),T}:void 0;return{canvas:await Wf({...t.canvas,fetcher:A,integrations:{experiments:m,telemetry:f},editorUrl:u,runtime:y}),runtime:y,experiments:m,telemetry:f,sessionMetrics:g,appLoader:w}}var fS={init:mH,encodeToken:Oh,decodeToken:wc};typeof window<"u"&&(window.Syntro=fS);var pS="2026-03-06T16:08:44.686Z (0412eafae8)";if(typeof window<"u"){console.log(`[Syntro Runtime] Build: ${pS}`);let t=window.SynOS,e=t?.appRegistry||fs;window.SynOS={...t,appRegistry:e,_runtimeBuild:pS,React:XE.default,ReactDOM:{...gH,createPortal:Bh.createPortal,flushSync:Bh.flushSync}},TI(e)}return rT(vH);})();
464
+ `)),new Error(`Batch validation failed: ${R}`)}let k=h(),A=[],M=[];try{for(let R of C){let B=await g(R);A.push(B),M.push(B)}}catch(R){console.error(`[ActionEngine] Batch apply FAILED at action ${M.length+1}/${C.length}.`,`Successfully applied: ${M.length}. Rolling back...`,R);for(let B of M)try{await B.revert()}catch{}throw R}return{id:k,handles:A,async revertAll(){for(let R=A.length-1;R>=0;R--)try{await A[R].revert()}catch(B){console.error(`[ActionEngine] Error reverting action ${A[R].id}:`,B)}},isApplied(){return A.every(R=>R.isApplied())}}}function y(C){return ln(C)}function _(){return Array.from(c.values()).map(C=>({id:C.id,action:C.action,adaptiveId:C.adaptiveId,appliedTs:C.appliedTs,state:C.state}))}function w(){for(let C of d.values())for(let L of C)try{L()}catch{}d.clear();for(let C of c.values())if(C.state==="applied")try{C.cleanup()}catch(L){console.error("[ActionEngine] Error during cleanup:",L)}c.clear()}return{apply:g,applyBatch:v,validate:y,getActive:_,destroy:w}}var kP=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),oh=p.object({type:p.literal("page_url"),url:p.string()}),ih=p.object({type:p.literal("route"),routeId:p.string()}),sh=p.object({type:p.literal("anchor_visible"),anchorId:p.string(),state:p.enum(["visible","present","absent"])}),lh=p.object({type:p.literal("event_occurred"),eventName:p.string(),withinMs:p.number().optional()}),uh=p.object({type:p.literal("state_equals"),key:p.string(),value:p.unknown()}),ch=p.object({type:p.literal("viewport"),minWidth:p.number().optional(),maxWidth:p.number().optional(),minHeight:p.number().optional(),maxHeight:p.number().optional()}),dh=p.object({type:p.literal("session_metric"),key:p.string(),operator:p.enum(["gte","lte","eq","gt","lt"]),threshold:p.number()}),fh=p.object({type:p.literal("dismissed"),key:p.string(),inverted:p.boolean().optional()}),ph=p.object({type:p.literal("cooldown_active"),key:p.string(),inverted:p.boolean().optional()}),hh=p.object({type:p.literal("frequency_limit"),key:p.string(),limit:p.number(),inverted:p.boolean().optional()}),Ws=p.object({equals:p.union([p.string(),p.number(),p.boolean()]).optional(),contains:p.string().optional()}),Zs=p.object({events:p.array(p.string()).min(1),match:p.record(p.string(),Ws).optional()}),mh=p.object({type:p.literal("event_count"),key:p.string(),operator:p.enum(["gte","lte","eq","gt","lt"]),count:p.number().int().min(0),withinMs:p.number().positive().optional(),counter:Zs.optional()}),un=p.discriminatedUnion("type",[oh,ih,sh,lh,uh,ch,dh,fh,ph,hh,mh]),Xs=p.object({conditions:p.array(un),value:p.unknown()}),Ys=p.object({type:p.literal("rules"),rules:p.array(Xs),default:p.unknown()}),Ks=p.object({type:p.literal("score"),field:p.string(),threshold:p.number(),above:p.unknown(),below:p.unknown()}),Qs=p.object({type:p.literal("model"),modelId:p.string(),inputs:p.array(p.string()),outputMapping:p.record(p.string(),p.unknown()),default:p.unknown()}),Js=p.object({type:p.literal("external"),endpoint:p.string(),method:p.enum(["GET","POST"]).optional(),default:p.unknown(),timeoutMs:p.number().optional()}),el=p.discriminatedUnion("type",[Ys,Ks,Qs,Js]),pc=el.nullable().optional(),EP=p.object({events:p.array(p.string()),urlContains:p.string().optional(),props:p.record(p.union([p.string(),p.number(),p.boolean()])).optional()}),TP=p.object({title:p.string().optional(),body:p.string().optional(),icon:p.string().optional()}).nullable().optional();var yb=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.")}),hc=p.object({routes:yb,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 RP(t){return un.safeParse(t)}function MP(t){return el.safeParse(t)}function DP(t){return hc.safeParse(t)}var OP=[{defName:"matchOp",schema:Ws},{defName:"counterDef",schema:Zs},{defName:"activationConfig",schema:hc},{defName:"routeFilter",schema:yb},{defName:"ruleStrategy",schema:Ys},{defName:"scoreStrategy",schema:Ks},{defName:"modelStrategy",schema:Qs},{defName:"externalStrategy",schema:Js},{defName:"rule",schema:Xs},{defName:"condition",schema:un}];var xb=p.object({tileId:p.string(),itemId:p.string().optional()}).strict(),BP=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:xb.optional()}).strict(),FP=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:hc.optional(),notifications:p.array(BP).optional()}).strict(),NP=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()}),PP=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()}),HP=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()}),UP=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()}),qP=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()}),zP=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()}),VP=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:NP.optional(),launcher:PP.optional(),tile:HP.optional(),overlay:UP.optional(),notification:qP.optional(),content:zP.optional()}).strict(),$P=p.object({enabled:p.boolean().optional(),label:p.string().optional(),icon:p.string().optional(),position:p.string().optional(),animate:p.boolean().optional(),animationStyle:p.enum(["pulse","bounce","glow"]).optional(),notificationCount:p.number().optional()}).strict(),$z=p.object({schemaVersion:p.string().optional(),fetchedAt:p.string().datetime(),configVersion:p.string().optional(),canvasTitle:p.string().optional(),tiles:p.array(FP),actions:p.array(p.any()),theme:VP.optional(),launcher:$P.optional(),meta:p.object({verificationSteps:p.array(p.union([p.string(),p.object({text:p.string(),check:un.optional()})])).optional()}).passthrough().optional()}).strict();var gt={triggerWhen:pc},xa=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),bb=p.object({color:p.string().optional(),scrimOpacity:p.number().min(0).max(1).optional(),paddingPx:p.number().optional(),radiusPx:p.number().optional()}).strict(),Sb=p.enum(["top-left","top-right","bottom-left","bottom-right"]),Cb=p.enum(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),vh=p.object({label:p.string(),actionId:p.string(),primary:p.boolean().optional()}).strict(),_b=p.object({title:p.string().optional(),body:p.string(),ctaButtons:p.array(vh).optional()}).strict(),wb=p.object({title:p.string().optional(),body:p.string()}).strict(),Lb=p.enum(["before","after","prepend","append","replace"]),Ib=p.enum(["immediate","hover","click"]),Ab=p.object({widgetId:p.string(),props:p.record(p.unknown()).optional(),priority:p.number().optional()}).strict(),kb=p.object({id:p.string(),action:p.any(),route:p.string().optional(),onAction:p.record(p.string()).optional()}).passthrough(),Eb=p.enum(["auto","smooth","instant"]),gh=p.enum(["start","center","end","nearest"]),Tb=p.object({kind:p.literal("content:setText"),anchorId:xa,text:p.string(),label:p.string().optional()}).extend(gt).strict(),Rb=p.object({kind:p.literal("content:setAttr"),anchorId:xa,attr:p.string(),value:p.string(),label:p.string().optional()}).extend(gt).strict(),Mb=p.object({kind:p.literal("content:addClass"),anchorId:xa,className:p.string(),label:p.string().optional()}).extend(gt).strict(),Db=p.object({kind:p.literal("content:removeClass"),anchorId:xa,className:p.string(),label:p.string().optional()}).extend(gt).strict(),Ob=p.object({kind:p.literal("content:setStyle"),anchorId:xa,styles:p.record(p.string()),label:p.string().optional()}).extend(gt).strict(),Bb=p.object({kind:p.literal("content:insertHtml"),anchorId:xa,html:p.string(),position:Lb,deepLink:xb.optional(),label:p.string().optional()}).extend(gt).strict(),Fb=p.object({kind:p.literal("overlays:highlight"),anchorId:xa,style:bb.optional(),duration:p.number().optional(),label:p.string().optional()}).extend(gt).strict(),Nb=p.object({kind:p.literal("overlays:pulse"),anchorId:xa,duration:p.number().optional(),label:p.string().optional()}).extend(gt).strict(),Pb=p.object({kind:p.literal("overlays:badge"),anchorId:xa,content:p.string(),position:Sb.optional(),label:p.string().optional()}).extend(gt).strict(),Hb=p.object({kind:p.literal("overlays:tooltip"),anchorId:xa,content:_b,trigger:Ib.optional(),placement:Cb.optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(gt).strict(),Ub=p.object({kind:p.literal("overlays:modal"),content:wb,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(vh).optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(gt).strict(),qb=p.object({kind:p.literal("navigation:scrollTo"),anchorId:xa,behavior:Eb.optional(),block:gh.optional(),inline:gh.optional(),label:p.string().optional()}).extend(gt).strict(),zb=p.object({kind:p.literal("navigation:navigate"),url:p.string(),target:p.enum(["_self","_blank"]).optional(),label:p.string().optional()}).extend(gt).strict(),Vb=p.object({kind:p.literal("core:mountWidget"),slot:p.string(),widget:Ab,label:p.string().optional()}).extend(gt).strict(),$b=p.object({kind:p.literal("core:wait"),durationMs:p.number().min(0).optional(),event:p.string().optional(),label:p.string().optional()}).extend(gt).strict(),jb=p.object({kind:p.literal("core:sequence"),actions:p.array(p.any()),label:p.string().optional()}).extend(gt).strict(),Gb=p.object({kind:p.literal("core:parallel"),actions:p.array(p.any()),waitFor:p.enum(["all","any"]).optional(),label:p.string().optional()}).extend(gt).strict(),Wb=p.object({kind:p.literal("core:tour"),tourId:p.string(),steps:p.array(kb).min(1),startStep:p.string().optional(),autoStart:p.boolean().optional(),label:p.string().optional()}).extend(gt).passthrough(),yE=[{defName:"setText",schema:Tb},{defName:"setAttr",schema:Rb},{defName:"addClass",schema:Mb},{defName:"removeClass",schema:Db},{defName:"setStyle",schema:Ob},{defName:"insertHtml",schema:Bb},{defName:"highlight",schema:Fb},{defName:"pulse",schema:Nb},{defName:"badge",schema:Pb},{defName:"tooltip",schema:Hb},{defName:"modal",schema:Ub},{defName:"scrollTo",schema:qb},{defName:"navigate",schema:zb},{defName:"mountWidget",schema:Vb},{defName:"wait",schema:$b},{defName:"sequence",schema:jb},{defName:"parallel",schema:Gb},{defName:"tour",schema:Wb}];function yh(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(x){if(!e)return null;try{return e.querySelector(x)}catch{return null}}function l(){for(let[x,f]of r){let g=s(x);if(g){for(let v of f)clearTimeout(v.timer),v.resolve(g);r.delete(x)}}for(let[x,f]of n){let g=s(x);if(g){for(let v of f)v.cancelled||v.cb(g);n.delete(x)}}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(x,f){let g=r.get(x);g&&(g.delete(f),g.size===0&&r.delete(x)),r.size===0&&n.size===0&&c()}function h(x,f){if(i)return Promise.reject(new Error("AnchorResolver destroyed"));let g=s(x);if(g)return Promise.resolve(g);let v=f??a;return new Promise((y,_)=>{let w={resolve:y,reject:_,timer:setTimeout(()=>{d(x,w),_(new Error(`waitFor("${x}") timed out after ${v}ms`))},v)},C=r.get(x);C||(C=new Set,r.set(x,C)),C.add(w),u()})}function m(x,f){if(i)return()=>{};let g=s(x);if(g)return f(g),()=>{};let v={cb:f,cancelled:!1},y=n.get(x);return y||(y=new Set,n.set(x,y)),y.add(v),u(),()=>{v.cancelled=!0;let _=n.get(x);_&&(_.delete(v),_.size===0&&n.delete(x)),r.size===0&&n.size===0&&c()}}function S(){let x=0;for(let f of r.values())x+=f.size;return x}function b(){i=!0,c();let x=new Error("AnchorResolver destroyed");for(let f of r.values())for(let g of f)clearTimeout(g.timer),g.reject(x);r.clear(),n.clear()}return{resolve:s,waitFor:h,onAppear:m,pendingCount:S,destroy:b}}function jP(){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 Zb(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(xE(a,r))return}if(e.include){for(let r of e.include)if(xE(a,r))return r;return}return a}function xE(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 mc=class{constructor(e){$(this,"context");$(this,"previousContext");$(this,"listeners",new Set);$(this,"telemetry");$(this,"routes");$(this,"navigation");$(this,"cleanupFns",[]);if(this.telemetry=e.telemetry,this.routes=e.routes,this.navigation=e.navigation,this.context=jP(),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=Zb(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=Zb(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=Zb(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 xh(t){return new mc(t)}var bE=p.object({url:p.string(),routeId:p.string().optional(),title:p.string().optional(),locale:p.string().optional()}),SE=p.object({url:p.string(),ts:p.number()}),CE=p.object({sessionId:p.string(),startTs:p.number(),pageHistory:p.array(SE).optional()}),_E=p.object({width:p.number(),height:p.number()}),wE=p.object({x:p.number(),y:p.number(),w:p.number(),h:p.number()}),LE=p.object({anchorId:p.string(),present:p.boolean(),visible:p.boolean().optional(),boundingBox:wE.optional()}),IE=p.record(p.string(),p.union([p.number(),p.string(),p.boolean(),p.undefined()])),AE=p.object({page:bE,session:CE,viewport:_E,anchors:p.array(LE).optional(),augmented:IE.optional()});function GP(t){return AE.safeParse(t)}function Xb(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=typeof t.anchorId=="string"?t.anchorId:t.anchorId?.selector??"",i=a.anchors?.find(s=>s.anchorId===o);switch(t.state){case"visible":return i?.visible===!0;case"present":return i?.present===!0;case"absent":return!i?.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 Yb(t,e){let a=[];for(let r of t.conditions){let n=Xb(r,e);if(a.push({condition:r,result:n}),!n)return{matched:!1,conditionResults:a}}return{matched:!0,conditionResults:a}}function gc(t,e){for(let a=0;a<t.rules.length;a++){let r=t.rules[a],{matched:n,conditionResults:o}=Yb(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 vc(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 kE(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 Kb(t,e,a={}){let r=kE(e,a);switch(t.type){case"rules":return gc(t,r);case"score":return vc(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 Qb(t,e,a={}){let r=kE(e,a);switch(t.type){case"rules":return gc(t,r);case"score":return vc(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 bh(t){return{evaluate:(e,a)=>Kb(e,a,t),evaluateSync:(e,a)=>Qb(e,a,t)}}function Sh(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 h=i.get(d.stateKey)||{count:0};h.count++,d.needsTimestamps&&(h.timestamps||(h.timestamps=[]),h.timestamps.push(u.ts),h.timestamps.length>200&&(h.timestamps=h.timestamps.slice(-200))),i.set(d.stateKey,h),c=!0}if(c)for(let d of n)try{d()}catch(h){console.error("[EventAccumulator] Subscriber error:",h)}}function l(){o||r.size===0||(o=e.subscribe(s))}return{register(u,c,d=!1){let h=`ev:${u}`,m=r.get(h);if(m){d&&!m.needsTimestamps&&(m.needsTimestamps=!0);return}r.set(h,{stateKey:h,needsTimestamps:d,predicate:c}),l()},getCount(u,c){let d=`ev:${u}`,h=i.get(d);if(!h)return 0;if(c===void 0||!h.timestamps)return h.count;let m=Date.now()-c;return h.timestamps.filter(S=>S>=m).length},subscribe(u){return n.add(u),()=>{n.delete(u)}},destroy(){o&&(o(),o=null),r.clear(),n.clear()}}}function Jb(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 yc=class{constructor(e={}){$(this,"subscriptions",new Set);$(this,"history",[]);$(this,"maxHistorySize");this.maxHistorySize=e.maxHistorySize??100}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:Go};this.publishEvent(n)}publishEvent(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift();for(let a of this.subscriptions)if(Jb(e,a.filter))try{a.callback(e)}catch(r){console.error("[EventBus] Subscriber error:",r)}}getRecent(e,a){let r=this.history;return e&&(r=r.filter(n=>Jb(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=>Jb(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 tl(t={}){return new yc(t)}var EE={$autocapture:"ui.click",$click:be.UI_CLICK,$scroll:be.UI_SCROLL,$input:be.UI_INPUT,$change:be.UI_CHANGE,$submit:be.UI_SUBMIT,$pageview:be.NAV_PAGE_VIEW,$pageleave:be.NAV_PAGE_LEAVE,$session_start:"session.start",$identify:"user.identify"};function WP(t){let e=t.event;if(typeof e!="string")return"posthog.unknown";if(EE[e])return EE[e];if(e==="$autocapture"){let a=t.properties?.$tag_name,r=t.properties?.$event_type;return r==="submit"?be.UI_SUBMIT:r==="change"?be.UI_CHANGE:a==="input"||a==="textarea"?be.UI_INPUT:be.UI_CLICK}return e.startsWith("$")?e.replace("$","posthog."):`posthog.${e}`}function ZP(t){let e={},a=t.properties||{},r=a.$elements;return a.$tag_name?e.tagName=a.$tag_name:r?.[0]?.tag_name&&(e.tagName=r[0].tag_name),a.$el_text&&(e.elementText=a.$el_text),r&&(e.elements=r),a.$current_url&&(e.url=a.$current_url),a.$pathname&&(e.pathname=a.$pathname),a.$host&&(e.host=a.$host),a.$viewport_width&&(e.viewportWidth=a.$viewport_width),a.$viewport_height&&(e.viewportHeight=a.$viewport_height),a.$session_id&&(e.sessionId=a.$session_id),a.$scroll_depth&&(e.scrollDepth=a.$scroll_depth),a.$scroll_percentage&&(e.scrollPercentage=a.$scroll_percentage),e.originalEvent=t.event,e}function eS(t){let e;return typeof t.timestamp=="number"?e=t.timestamp:typeof t.timestamp=="string"?e=new Date(t.timestamp).getTime():e=Date.now(),{ts:e,name:WP(t),source:"posthog",props:ZP(t),schemaVersion:Go}}function tS(t){let e=t.event;return!(typeof e!="string"||["$feature_flag_called","$feature_flags","$groups","$groupidentify","$set","$set_once","$unset","$create_alias","$capture_metrics","$performance_event","$web_vitals","$exception","$dead_click","$heatmap"].includes(e))}function Ch(t){return(e,a)=>{if(typeof e!="string")return;let r={event:e,properties:a,timestamp:Date.now()};if(tS(r)){let n=eS(r);t(n)}}}var aS=p.enum(["posthog","canvas","derived"]),TE=p.object({ts:p.number(),name:p.string(),source:aS,props:p.record(p.string(),p.unknown()).optional(),schemaVersion:p.string()}),RE=p.object({names:p.array(p.string()).optional(),patterns:p.array(p.string()).optional(),sources:p.array(aS).optional()});function XP(t){return TE.safeParse(t)}function YP(t){return RE.safeParse(t)}var al=class{constructor(){$(this,"listeners",new Set);$(this,"capturedPushState");$(this,"capturedReplaceState");$(this,"wasNative");$(this,"destroyed",!1);$(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 rS="cooldown:";function ME(t){return{set(e,a){let r=rS+e,n=Date.now()+a;t.set(r,n)},isActive(e){return this.remaining(e)>0},remaining(e){let a=rS+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=rS+e;t.remove(a)}}}var xc="dismissed:";function DE(t,e){return{mark(a,r=!1){let n=xc+a;(r?e:t).set(n,!0)},isDismissed(a){let r=xc+a;return t.has(r)||e.has(r)},clear(a){let r=xc+a;t.remove(r),e.remove(r)},clearAll(){for(let a of t.keys())a.startsWith(xc)&&t.remove(a);for(let a of e.keys())a.startsWith(xc)&&e.remove(a)}}}var nS="freq:";function OE(t){function e(a){let r=nS+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=nS+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=nS+a;t.remove(r)},hasReachedLimit(a,r){return this.count(a)>=r}}}var KP="syntro";function oS(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 bc(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 Sc=class{constructor(e={}){$(this,"session");$(this,"user");$(this,"dismissals");$(this,"cooldowns");$(this,"frequency");$(this,"namespace");$(this,"namespacedStorages",new Map);this.namespace=e.namespace??KP;let a=r=>typeof r=="object"&&r!==null&&typeof r.setItem=="function";typeof window<"u"?(this.session=a(window.sessionStorage)?oS(window.sessionStorage,this.namespace):bc(this.namespace),this.user=a(window.localStorage)?oS(window.localStorage,this.namespace):bc(this.namespace)):(this.session=bc(this.namespace),this.user=bc(this.namespace)),this.dismissals=DE(this.session,this.user),this.cooldowns=ME(this.user),this.frequency=OE(this.session)}ns(e){let a=`${this.namespace}:${e}`;if(!this.namespacedStorages.has(a)){let r=typeof window<"u"&&typeof sessionStorage<"u"?oS(sessionStorage,a):bc(a);this.namespacedStorages.set(a,r)}return this.namespacedStorages.get(a)}};function _h(t={}){return new Sc(t)}function rl(t){return t.startsWith("inline:")?"inline":t.startsWith("adjacent:")?"adjacent":"static"}function Cc(t){return t.startsWith("inline:")?t.slice(7):t.startsWith("adjacent:")?t.slice(9):null}var iS={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"}},nl={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:[]},BE={duration:200,easing:"cubic-bezier(0.16, 1, 0.3, 1)",fill:"forwards"};function wh(t,e,a){let r=iS[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 Lh(t,e,a){let r=a.placement==="auto"?"bottom":a.placement,n=[gf(a.offset?{mainAxis:a.offset.y,crossAxis:a.offset.x}:8)];return a.flip!==!1&&n.push(yf()),a.shift!==!1&&n.push(vf({padding:8})),t.style.position="absolute",t.style.zIndex="2147483646",mf(e,t,async()=>{let{x:i,y:s,strategy:l}=await xf(e,t,{placement:r,middleware:n});Object.assign(t.style,{position:l,left:`${i}px`,top:`${s}px`})})}function Ih(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 Ah(t,e){return e==="none"||nl[e].length===0?null:t.animate(nl[e],BE)}function kh(t,e){if(e==="none"||nl[e].length===0)return Promise.resolve();let a=[...nl[e]].reverse(),r=t.animate(a,BE);return new Promise(n=>{r.onfinish=()=>n(),r.oncancel=()=>n()})}function Eh(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 Th(t){switch(rl(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 FE(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(),h=c.startsWith("on"),m=(c==="href"||c==="src")&&d.startsWith("javascript:");(h||m)&&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 QP=0;function Rh(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-${++QP}`}function c(y,_){a&&a.publish(y,_)}function d(y){let _=l.get(y);if(_){let w=x(y);for(let C of _)try{C(w)}catch(L){console.error("[Surfaces] State callback error:",L)}}}let h=new Map;function m(y,_,w){switch(_.type){case"html":y.innerHTML=FE(_.content);return;case"widget":{if(o?.has(_.widgetId)){let C=o.mount(_.widgetId,y,_.config);return w&&h.set(w,C),()=>{C.unmount(),w&&h.delete(w)}}console.warn(`[Surfaces] Widget not found: ${_.widgetId}`),y.innerHTML=`<div data-widget-id="${_.widgetId}" data-widget-missing="true">Widget: ${_.widgetId}</div>`;return}case"custom":return _.mount(y);case"react":y.innerHTML="<div data-react-component>React Component</div>";return;default:console.warn("[Surfaces] Unknown content type");return}}function S(y,_,w){let C=u(),L=rl(y),k=w?.priority??0,A=w?.animation??n,M=w?.exclusive??!0,T=i.get(y);if(T&&M){if(T.options.priority>k)throw new Error(`Slot ${y} is occupied by higher priority content (${T.options.priority} > ${k})`);b(T)}let R=Eh(y,C);R.style.zIndex=String(Th(y));let B;if(L==="static")wh(R,y,w?.constraints),e.appendChild(R);else if(L==="inline"){let N=Cc(y);if(!N)throw new Error(`Invalid inline slot: ${y}`);if(!r)throw new Error("Anchor resolver required for inline slots");let W=r({selector:N,route:"**"});if(!W)throw new Error(`Anchor not found for inline slot: ${N}`);B=Ih(R,W)}else if(L==="adjacent"){let N=Cc(y);if(!N)throw new Error(`Invalid adjacent slot: ${y}`);if(!r)throw new Error("Anchor resolver required for adjacent slots");let W=r({selector:N,route:"**"});if(!W)throw new Error(`Anchor not found for adjacent slot: ${N}`);e.appendChild(R),B=Lh(R,W,w?.position??{placement:"bottom"})}let F=m(R,_,C);Ah(R,A);let P={id:C,slot:y,content:_,options:{priority:k,exclusive:M,animation:A,position:w?.position??{placement:"auto"},constraints:w?.constraints??{},adaptiveId:w?.adaptiveId,autoUnmountOnRouteChange:w?.autoUnmountOnRouteChange??!0},container:R,cleanup:()=>{B?.(),F?.()},mountedAt:Date.now()};return i.set(y,P),s.set(y,(s.get(y)??0)+1),c("surface.mounted",{slot:y,id:C,adaptiveId:w?.adaptiveId}),d(y),{id:C,update(N){let W=i.get(y);if(!W||W.id!==C)throw new Error("Mount no longer active");let Q=h.get(C);if(Q){if(N.type==="widget"){Q.update(N.config),W.content=N;return}Q.unmount(),h.delete(C)}W.container.innerHTML="";let aa=m(W.container,N,C);if(W.content=N,aa){let dt=W.cleanup;W.cleanup=()=>{dt?.(),aa()}}},setOptions(N){let W=i.get(y);if(!W||W.id!==C)throw new Error("Mount no longer active");N.priority!==void 0&&(W.options.priority=N.priority),N.animation!==void 0&&(W.options.animation=N.animation),N.constraints&&L==="static"&&(N.constraints.maxWidth&&(W.container.style.maxWidth=N.constraints.maxWidth),N.constraints.maxHeight&&(W.container.style.maxHeight=N.constraints.maxHeight),N.constraints.minWidth&&(W.container.style.minWidth=N.constraints.minWidth),N.constraints.minHeight&&(W.container.style.minHeight=N.constraints.minHeight)),d(y)},async unmount(){let N=i.get(y);!N||N.id!==C||await b(N)},isMounted(){return i.get(y)?.id===C},getContainer(){let N=i.get(y);return N?.id===C?N.container:null}}}async function b(y){await kh(y.container,y.options.animation),y.cleanup?.(),y.container.remove(),i.delete(y.slot),c("surface.unmounted",{slot:y.slot,id:y.id}),d(y.slot)}function x(y){let _=i.get(y);return{slot:y,occupied:!!_,currentPriority:_?.options.priority,currentAdaptiveId:_?.options.adaptiveId,mountCount:s.get(y)??0,currentMountId:_?.id}}function f(y,_){let w=l.get(y);return w||(w=new Set,l.set(y,w)),w.add(_),()=>{w?.delete(_),w?.size===0&&l.delete(y)}}function g(y,_){let w=i.get(y);return w?_!==void 0?_>=w.options.priority:!1:!0}function v(){for(let y of i.values())try{y.cleanup?.(),y.container.remove()}catch(_){console.error("[Surfaces] Error during cleanup:",_)}i.clear(),l.clear()}return{mount:S,getState:x,onStateChange:f,canMount:g,destroy:v}}var _c=class{constructor(){$(this,"widgets",new Map);$(this,"mountedWidgets",new Map);$(this,"mountIdCounter",0);$(this,"runtimeRef");$(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&&(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},h=n.widget.mount(a,d);c.cleanup=h??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()}},Mh=new _c;var lS="2.0.0";function JP(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(sS(r,n))return!1}if(e.include&&e.include.length>0){for(let n of e.include)if(sS(r,n))return!0;return!1}return!0}function sS(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 NE(t){let a=(typeof window<"u"?window.location.pathname:"/").replace(/\/$/,"")||"/";return(Array.isArray(t.route)?t.route:[t.route]).some(n=>sS(a,n))}function Dh(t={}){let{telemetry:e,sessionMetrics:a,routes:r,mode:n="production",namespace:o}=t,i=t.widgets??Mh,s=t.executors??br,l=t.apps??fs,u=new al,c=xh({telemetry:e,routes:r,navigation:u}),d=t.events??tl(),h=_h({namespace:o}),m=Sh({eventBus:d,stateStore:h}),S=bh({state:h,events:d,sessionMetrics:a,accumulator:m}),b=$I(),x=yh(),f=C=>NE(C)?x.resolve(C.selector):null,g=async(C,L)=>{if(!NE(C))return null;try{return await x.waitFor(C.selector,L)}catch{return null}},v=Rh({overlayRoot:b,eventBus:d,anchorResolver:f,widgetRegistry:i}),y=nh({overlayRoot:b,eventBus:d,surfaces:v,anchorResolver:f,waitForAnchor:g,executorRegistry:s,subscribeNavigation:C=>u.subscribe(C),runtime:{evaluateSync:C=>S.evaluateSync(C,c.get()),context:c,accumulator:m}}),_;if(a){a.increment("page_views");let C=typeof window<"u"?window.location.pathname:"/";_=u.subscribe((L,k)=>{if(k!=="replaceState")try{let A=new URL(L).pathname;A!==C&&(C=A,a.increment("page_views"))}catch{}})}let w={telemetry:e,context:c,events:d,state:h,sessionMetrics:a,actions:y,surfaces:v,widgets:i,executors:s,apps:l,accumulator:m,anchorResolver:x,navigation:u,version:lS,mode:n,async evaluate(C){return S.evaluate(C,c.get())},evaluateSync(C){return S.evaluateSync(C,c.get())},async filterTiles(C){let L=c.get().page.url,k=[];for(let A of C){let M=A.activation;if(!M){k.push(A);continue}if(JP(L,M.routes)){if(M.onlyIfPopulated){let T=A.props?.actions??[];if(T.length>0&&!T.some(B=>B.triggerWhen?S.evaluateSync(B.triggerWhen,c.get()).value:!0))continue}k.push(A)}}return k},setRoutes(C){c.setRoutes(C)},destroy(){l.unbind().catch(C=>{console.error("[Runtime] Error unbinding apps registry:",C)}),_?.(),x.destroy(),m.destroy(),u.destroy(),c.destroy(),y.destroy(),v.destroy()}};return l.bind(w),i.bindRuntime(w),w}var PE=p.object({value:p.unknown(),expiresAt:p.number().optional()}),HE=p.object({count:p.number(),resetAt:p.number().optional()});function eH(t){return PE.safeParse(t)}function tH(t){return HE.safeParse(t)}var UE={growthbook:t=>dp({...t,autoInit:!0})};function qE(t,e){let a=UE[t];if(!a)throw new Error(`Unknown experiment provider: ${t}. Supported: ${Object.keys(UE).join(", ")}`);return a(e)}var aH=["cdn.syntrologie.com","localhost","127.0.0.1"];function rH(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):aH.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 uS=class{constructor(e){$(this,"name","cdn");$(this,"url");$(this,"integrity");if(this.url=`${e.baseUrl}/${e.configId}.json`,this.integrity=e.integrity,!rH(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 nH(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 nH(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 zE(t){return new uS(t)}var oH="syntro_exp",iH="syntro_var",cS=class{constructor(e){$(this,"name","experiments");$(this,"client");$(this,"featureKey");$(this,"manifestKey");$(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(oH),i=n.get(iH);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}}}}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:kf(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 VE(t){return new cS(t)}var sH="https://cdn.syntrologie.com/configs",$E={cdn:t=>{if(!t.configId)throw new Error("CDN fetcher requires 'configId' option");return zE({baseUrl:t.baseUrl??sH,configId:t.configId,integrity:t.integrity})},experiments:t=>{if(!t.featureKey)throw new Error("Experiments fetcher requires 'featureKey' option");return VE({featureKey:t.featureKey})}};function jE(t,e={}){let a=$E[t];if(!a)throw new Error(`Unknown config fetcher type: ${t}. Supported: ${Object.keys($E).join(", ")}`);return a(e)}var GE={posthog:t=>th(t),noop:()=>bp()};function WE(t,e){let a=GE[t];if(!a)throw new Error(`Unknown telemetry provider: ${t}. Supported: ${Object.keys(GE).join(", ")}`);return a(e)}var dS="syn_";function wc(t){if(!t.startsWith(dS))throw new Error("Invalid Syntro token: must start with 'syn_'");let a=t.slice(dS.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 Oh(t){let e=JSON.stringify(t),a=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return dS+a}function cn(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{}}function lH(){if(typeof window>"u")return X("Syntro Bootstrap","isEditorMode: not in browser"),!1;let t=$o(),a=!!($n()?.token&&t?.mode==="editor");return X("Syntro Bootstrap","isEditorMode:",a),a}function uH(){if(typeof window>"u")return X("Syntro Bootstrap","isAuditMode: not in browser"),!1;let t=$o(),a=!!($n()?.token&&t?.mode==="audit");return X("Syntro Bootstrap","isAuditMode:",a),a}function cH(){if(typeof window>"u")return X("Syntro Bootstrap","isReviewMode: not in browser"),!1;let t=$o(),a=!!($n()?.token&&t?.mode==="review");return X("Syntro Bootstrap","isReviewMode:",a),a}var ZE="syntro_segment_attributes";function dH(){if(typeof window>"u")return{};try{let t=localStorage.getItem(ZE);if(t){let e=JSON.parse(t);return X("Syntro Bootstrap","Loaded cached segment attributes:",e),e}}catch(t){ga("Syntro Bootstrap","Failed to load cached segment attributes:",t)}return{}}function fH(t){if(!(typeof window>"u"))try{localStorage.setItem(ZE,JSON.stringify(t)),X("Syntro Bootstrap","Cached segment attributes:",t)}catch(e){ga("Syntro Bootstrap","Failed to cache segment attributes:",e)}}function pH(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 hH(){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{t.page_url=window.location.href,t.page_path=window.location.pathname}catch{}return t}async function mH(t){jv(),X("Syntro Bootstrap","====== INIT ======"),X("Syntro Bootstrap","Options:",{hasToken:!!t.token,tokenPrefix:`${t.token?.slice(0,15)}...`,hasCanvasOptions:!!t.canvas});let e=lH(),a=uH(),r=cH(),n=e?"editor":a?"audit":r?"review":null;if(console.log(`[DIAG] Mode detection: editor=${e}, audit=${a}, review=${r}, sdkMode=${n}`),console.log("[DIAG] editorSource:",$n()),console.log("[DIAG] editorConf:",$o()),X("Syntro Bootstrap","SDK mode:",n??"normal"),!n&&typeof window<"u"){let T=!!window.__SYNTRO_EDITOR_PARAMS__,R=!!window.__SYNTRO_AUDIT_LEGEND__,B=!!window.__SYNTRO_REVIEW_DATA__;if(T||R||B){let F=[T&&"__SYNTRO_EDITOR_PARAMS__",R&&"__SYNTRO_AUDIT_LEGEND__",B&&"__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 o=t.token;if(!o&&n){let R=$o()?.syntro_token;R?.startsWith("syn_")&&(o=R,X("Syntro Bootstrap",`\u2713 Using syntro_token from editor_conf (${n} mode)`))}let i;if(o)if(o.startsWith("syn_"))X("Syntro Bootstrap","Token starts with syn_, decoding..."),i=wc(o),jv(i.d);else if(n)X("Syntro Bootstrap",`\u2713 Non-syn_ token allowed (${n} mode)`);else throw Ef("Syntro Bootstrap","\u274C Token does not start with syn_ and NOT in editor/audit/review mode!"),Ef("Syntro Bootstrap","Token received:",o),new Error("Invalid Syntro token: must start with 'syn_'");else if(n)X("Syntro Bootstrap",`\u2713 No token, but ${n} mode - proceeding`);else throw Ef("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 s=cn("NEXT_PUBLIC_SYNTRO_EXPERIMENT_HOST")||cn("VITE_SYNTRO_EXPERIMENT_HOST")||i?.eh,l=cn("NEXT_PUBLIC_SYNTRO_TELEMETRY_HOST")||cn("VITE_SYNTRO_TELEMETRY_HOST")||i?.th,u=cn("NEXT_PUBLIC_SYNTRO_EDITOR_URL")||cn("VITE_SYNTRO_EDITOR_URL")||t.canvas?.editorUrl,c=dH(),d=hH(),h={...d,...c};X("Syntro Bootstrap","Phase 1: Browser metadata:",d),X("Syntro Bootstrap","Phase 1: Cached segment attributes:",c);let m,S=tl();console.log("[Syntro Bootstrap] EventBus created");let b=Ch(T=>{S.publishEvent(T)}),x=T=>{X("Syntro Bootstrap","Phase 2: PostHog feature flags loaded");let R=pH(T);if(X("Syntro Bootstrap","Segment flags from PostHog:",R),fH(R),m){let B=g?.getAll?.()??{},F={...d,...B,...R};X("Syntro Bootstrap","Updating GrowthBook with attributes:",F),m.setAttributes?.(F)}},f;if(i?.t){let T=i.t==="noop"?"noop":"posthog";f=WE(T,{apiKey:i.t,apiHost:l,enableFeatureFlags:!0,onFeatureFlagsLoaded:x,onCapture:b}),console.log(`[Syntro Bootstrap] Telemetry client created (${T}) with EventBus wiring`)}let g;i?.e&&(m=qE("growthbook",{clientKey:i.e,apiHost:s,attributes:h,onExperimentViewed:f?.trackExperiment?(T,R,B)=>{f.trackExperiment(T,R,B)}:void 0})),g=fp({experiments:m,onMetricChange:(T,R)=>{X("Syntro Bootstrap",`Session metric changed: ${T} = ${R}`)}}),X("Syntro Bootstrap","SessionMetricTracker created");let v="production";e?v="editor":a?v="audit":cn("NODE_ENV")==="development"&&(v="development");let y=Dh({telemetry:f,sessionMetrics:g,mode:v,events:S});X("Syntro Bootstrap","Runtime created:",{version:y.version,mode:y.mode,hasContext:!!y.context,hasEvents:!!y.events,hasState:!!y.state}),X("Syntro Bootstrap","Core app executors already registered");let _=t.cdnBase||cn("NEXT_PUBLIC_SYNTRO_CDN_BASE")||cn("VITE_SYNTRO_CDN_BASE")||"https://cdn.syntrologie.com",w=Lf({cdnBase:_,registry:y.apps,onLoadStart:T=>{X("Syntro Bootstrap",`Loading app from CDN: ${T}`)},onLoadEnd:(T,R,B)=>{R?X("Syntro Bootstrap",`App loaded successfully: ${T}`):ga("Syntro Bootstrap",`Failed to load app: ${T}`,B)}});typeof window<"u"&&(window.SynOS={...window.SynOS,appRegistry:y.apps,runtime:y,version:y.version},X("Syntro Bootstrap","Global SynOS object exposed"));let C=y.apps.list?.()??[];console.log(`[DIAG] Activation loop: ${C.length} apps in registry:`,C.map(T=>`${T.manifest.id}(${T.state})`).join(", "));for(let T of C)if(T.state==="registered")try{await y.apps.activate(T.manifest.id),console.log(`[DIAG] Activated: ${T.manifest.id} \u2192 widgets: [${y.widgets.list().join(", ")}]`)}catch(R){console.error(`[DIAG] FAILED to activate: ${T.manifest.id}`,R),ga("Syntro Bootstrap",`Failed to auto-activate built-in app: ${T.manifest.id}`,R)}if(console.log(`[DIAG] Activation complete. Total widgets: [${y.widgets.list().join(", ")}]`),m?.refreshFeatures)try{await m.refreshFeatures(),X("Syntro Bootstrap","GrowthBook features loaded")}catch(T){ga("Syntro Bootstrap","Failed to load GrowthBook features:",T)}let L;if(t.fetcher)L=t.fetcher;else if(i?.f){let T=jE(i.f,i.o??{});L=async()=>{let R=await T.fetch();return{...R.config,tiles:R.config.tiles??[]}}}else m&&(L=Vo({experiments:m}));let k=new Set,A=L?async()=>{let T=await L();console.log("[Syntro Bootstrap] Config fetched:",`tiles=${T.tiles?.length??0},`,`actions=${T.actions?.length??0},`,`theme=${T.theme?.name??"none"}`),T.actions?.length>0&&console.log("[Syntro Bootstrap] Actions in config:",T.actions.map((F,P)=>`[${P}] ${F.kind}${F.anchorId?` anchor="${typeof F.anchorId=="string"?F.anchorId:F.anchorId.selector}"`:""}${F.label?` "${F.label}"`:""}`).join(", "));let R=T,B=w.getRequiredApps(R);return B.length>0?console.log("[Syntro Bootstrap] Required external apps:",B.join(", ")):X("Syntro Bootstrap","No external apps required (all executors are built-in)"),B.length>0&&await w.loadAppsForConfig(R).then(async P=>{let Y=P.filter(Q=>Q.success),N=P.filter(Q=>!Q.success);Y.length>0&&console.log(`[Syntro Bootstrap] Apps loaded from CDN: ${Y.map(Q=>Q.appId).join(", ")}`);let W=N.filter(Q=>!k.has(Q.appId));W.length>0&&(console.error("[Syntro Bootstrap] Apps FAILED to load from CDN:",W.map(Q=>`${Q.appId} (${Q.error})`).join(", ")),W.forEach(Q=>k.add(Q.appId)));for(let Q of B)if(y.apps.has(Q))try{await y.apps.activate(Q),console.log(`[Syntro Bootstrap] App activated: ${Q}`)}catch(aa){console.error(`[Syntro Bootstrap] Failed to activate app: ${Q}`,aa)}else console.error(`[Syntro Bootstrap] App "${Q}" required by config but NOT registered.`,`Available apps: [${Array.from(y.apps.list?.()??[]).join(", ")}]`)}),T}:void 0;return{canvas:await Wf({...t.canvas,fetcher:A,integrations:{experiments:m,telemetry:f},editorUrl:u,runtime:y}),runtime:y,experiments:m,telemetry:f,sessionMetrics:g,appLoader:w}}var fS={init:mH,encodeToken:Oh,decodeToken:wc};typeof window<"u"&&(window.Syntro=fS);var pS="2026-03-06T19:12:21.408Z (fc4b2176dd)";if(typeof window<"u"){console.log(`[Syntro Runtime] Build: ${pS}`);let t=window.SynOS,e=t?.appRegistry||fs;window.SynOS={...t,appRegistry:e,_runtimeBuild:pS,React:XE.default,ReactDOM:{...gH,createPortal:Bh.createPortal,flushSync:Bh.flushSync}},TI(e)}return rT(vH);})();
465
465
  /*! Bundled license information:
466
466
 
467
467
  react/cjs/react.production.js: