@syntrologie/runtime-sdk 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-V4MDQX67.js → chunk-RUKIPJEJ.js} +2 -2
- package/dist/{chunk-V4MDQX67.js.map → chunk-RUKIPJEJ.js.map} +1 -1
- package/dist/index.js +1 -1
- package/dist/react.js +1 -1
- package/dist/smart-canvas.esm.js +2 -2
- package/dist/smart-canvas.esm.js.map +1 -1
- package/dist/smart-canvas.js +2 -2
- package/dist/smart-canvas.js.map +1 -1
- package/dist/smart-canvas.min.js +2 -2
- package/dist/smart-canvas.min.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/package.json +7 -7
package/dist/smart-canvas.esm.js
CHANGED
|
@@ -110,7 +110,7 @@ Error generating stack: `+i.message+`
|
|
|
110
110
|
s.textContent = '.${e} { ${n} }';
|
|
111
111
|
document.head.appendChild(s);
|
|
112
112
|
document.documentElement.className += ' ${e}';
|
|
113
|
-
})();`}function Nd(t,e,n="first-match"){for(let i of e){let r=t.getFeatureValue?.(i,null);if(!r||typeof r!="object")continue;let a=r,o=a.tiles&&a.tiles.length>0,s=a.actions&&a.actions.length>0;if(o||s)return{tiles:a.tiles??[],actions:a.actions??[],fetchedAt:a.fetchedAt??new Date().toISOString(),...a.schemaVersion&&{schemaVersion:a.schemaVersion},...a.configVersion&&{configVersion:a.configVersion},...a.canvasTitle&&{canvasTitle:a.canvasTitle},...a.theme&&{theme:a.theme},...a.launcher&&{launcher:a.launcher},...a.routes&&{routes:a.routes}}}return null}var sm=!1;function kw(){if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("syntro_debug")==="true"}catch{return!1}}function lm(t){if(kw()){sm=!0;return}sm=t??!1}function SM(){return kw()?!0:sm}function Z(t,e,n){SM()&&(n!==void 0?console.log(`[${t}]`,e,n):console.log(`[${t}]`,e))}function ln(t,e,n){n!==void 0?console.warn(`[${t}]`,e,n):console.warn(`[${t}]`,e)}function Dd(t,e,n){n!==void 0?console.error(`[${t}]`,e,n):console.error(`[${t}]`,e)}var cm="2.
|
|
113
|
+
})();`}function Nd(t,e,n="first-match"){for(let i of e){let r=t.getFeatureValue?.(i,null);if(!r||typeof r!="object")continue;let a=r,o=a.tiles&&a.tiles.length>0,s=a.actions&&a.actions.length>0;if(o||s)return{tiles:a.tiles??[],actions:a.actions??[],fetchedAt:a.fetchedAt??new Date().toISOString(),...a.schemaVersion&&{schemaVersion:a.schemaVersion},...a.configVersion&&{configVersion:a.configVersion},...a.canvasTitle&&{canvasTitle:a.canvasTitle},...a.theme&&{theme:a.theme},...a.launcher&&{launcher:a.launcher},...a.routes&&{routes:a.routes}}}return null}var sm=!1;function kw(){if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("syntro_debug")==="true"}catch{return!1}}function lm(t){if(kw()){sm=!0;return}sm=t??!1}function SM(){return kw()?!0:sm}function Z(t,e,n){SM()&&(n!==void 0?console.log(`[${t}]`,e,n):console.log(`[${t}]`,e))}function ln(t,e,n){n!==void 0?console.warn(`[${t}]`,e,n):console.warn(`[${t}]`,e)}function Dd(t,e,n){n!==void 0?console.error(`[${t}]`,e,n):console.error(`[${t}]`,e)}var cm="2.3.0";var Mr="2.0";var xM=["api.syntrologie.com","cdn.syntrologie.com","localhost","127.0.0.1"];function wM(t){try{let e=new URL(t),n=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!n?(console.warn("[SmartCanvas] Config URI must use HTTPS:",t),!1):xM.some(r=>e.hostname===r)?!0:(console.warn("[SmartCanvas] Config URI host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid config URI:",t),!1}}function EM(t){if(typeof window>"u")return!1;try{return new URL(t).origin===window.location.origin}catch{return!1}}var Rw="syntro_config_cache",CM=1440*60*1e3;function Ow(){try{return typeof localStorage<"u"&&localStorage!==null}catch{return!1}}function AM(t,e){if(Ow())try{let n={config:t,timestamp:Date.now(),sdkVersion:e};localStorage.setItem(Rw,JSON.stringify(n))}catch{}}function TM(t){if(!Ow())return null;try{let e=localStorage.getItem(Rw);if(!e)return null;let n=JSON.parse(e);return!n.config||typeof n.timestamp!="number"||!n.sdkVersion||n.sdkVersion!==t||Date.now()-n.timestamp>CM?null:n.config}catch{return null}}var um=({configUri:t,experiments:e,featureKey:n="smart-canvas-config-uri"})=>{if(t)return t;let i=e?.getFeatureValue?.(n,null);if(i)return i};function kM(t,e,n){if(e){let i=t.getFeatureValue?.(e,null);if(i&&typeof i=="object"){let r=i.variant_flags;if(r&&r.length>0)return r}}if(n&&t.getAllFeatures){let i=t.getAllFeatures();return Object.keys(i).filter(r=>r.startsWith(n))}return[]}var Jo=({configUri:t,experiments:e,featureKey:n,credentials:i,configFeatureKey:r="smart-canvas-config",manifestKey:a,variantFlagPrefix:o,sdkVersion:s})=>async()=>{if(e&&r){let u=e.getFeatureValue?.(r,null);if(u&&typeof u=="object")return Z("SmartCanvas Config","Resolved config directly from feature flag",u),u}if(e&&(a||o)){let u=kM(e,a,o);if(u.length>0){let f=Nd(e,u);if(f)return Z("SmartCanvas Config","Resolved config from variant flags",f),f}}let l=um({configUri:t,experiments:e,featureKey:n});if(!l)return Z("SmartCanvas Config","No config available \u2014 returning empty config"),{tiles:[],actions:[],fetchedAt:new Date().toISOString()};if(!wM(l))throw new Error(`SmartCanvas: config URI not allowed: ${l}`);let c=i??(EM(l)?"include":"omit");try{let u=await fetch(l,{credentials:c,headers:{"X-SDK-Version":cm,"X-SDK-Schema-Version":Mr}});if(!u.ok)throw new Error(`SmartCanvas: failed to fetch config (${u.status})`);let f=await u.json();return Z("SmartCanvas Config","Fetched config from URI",f),s&&AM(f,s),f}catch(u){if(s){let f=TM(s);if(f)return Z("SmartCanvas Config","Serving config from offline cache"),f}throw u}};var RM=["cdn.syntrologie.com","api.syntrologie.com","dev-api.syntrologie.com","localhost","127.0.0.1",".syntrologie.com"];function Mw(t){if(typeof window>"u")return null;let n=new URLSearchParams(window.location.search).get(t);if(!n)return null;try{let i=n.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(i))}catch(i){return ln("Syntro Runtime",`Failed to decode ${t}:`,i),null}}var es,ts;function Nr(){if(es==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.token)es={token:t.token,api_base:t.apiBase||""},console.log(`[DIAG] getEditorSource: from __SYNTRO_EDITOR_PARAMS__ (token=${es.token.slice(0,15)}...)`);else{let e=Mw("editor_source");e&&(es=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 es??null}function Ra(){if(ts==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.mode)ts={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=${ts.mode})`);else{let e=Mw("editor_conf");e&&(ts=e),console.log(`[DIAG] getEditorConf: from URL param \u2192 ${e?`mode=${e.mode}`:"NULL"}`)}}return ts??null}function OM(t){Z("Syntro Runtime","Validating editor URL:",t);try{if(t.startsWith("/"))return Z("Syntro Runtime","\u2713 Relative URL allowed (same-origin):",t),!0;let e=new URL(t),n=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!n?(ln("Syntro Runtime","\u274C Editor URL must use HTTPS:",t),!1):RM.some(r=>r.startsWith(".")?e.hostname.endsWith(r)||e.hostname===r.slice(1):e.hostname===r)?(Z("Syntro Runtime","\u2713 Editor URL validated"),!0):(ln("Syntro Runtime","\u274C Editor URL host not in allowlist:",e.hostname),!1)}catch(e){return ln("Syntro Runtime",`\u274C Invalid editor URL: ${t}`,e),!1}}var Nw=()=>{let t=Ra();return!Nr()?.token||!t?null:t.mode==="editor"||t.mode==="audit"||t.mode==="review"?t.mode:null};function MM(){return Nr()?.token??null}function NM(){return Nr()?.api_base??null}var jl=null,Dw=async t=>{if(Z("Syntro Runtime","====== LOAD EDITOR SDK ======"),typeof window>"u"){Z("Syntro Runtime","Not in browser - skipping editor SDK load");return}if(window.SyntroEditor){Z("Syntro Runtime","Editor SDK already loaded (window.SyntroEditor exists)");return}if(jl)return Z("Syntro Runtime","Editor SDK load already in progress, waiting..."),jl;let e=typeof t=="string"?{editorUrl:t}:t??{};if(e.editorUrl==="skip"){Z("Syntro Runtime",'editorUrl="skip" \u2014 deferring to caller'),Z("Syntro Runtime","================================");return}let n=NM(),r=(n?`${n}/api/editor/sdk/editor-sdk.js`:null)||e.editorUrl;if(!r){ln("Syntro Runtime","\u274C No editor SDK URL available (no api_base, no editorUrl option)"),Z("Syntro Runtime","================================");return}let a=MM();if(!a){ln("Syntro Runtime","\u274C No token found in editor_source."),Z("Syntro Runtime","================================");return}let o=`${r}?token=${encodeURIComponent(a)}`;if(Z("Syntro Runtime","Editor URL:",o),Z("Syntro Runtime","Options:",{hasIntegrity:!!e.integrity,hasEditorUrl:!!r,hasApiBase:!!n,tokenPrefix:`${a.slice(0,10)}...`}),!OM(r)){console.error("[Syntro Runtime] \u274C BLOCKED: Editor from untrusted URL:",r),Z("Syntro Runtime","================================");return}return Z("Syntro Runtime","\u2713 URL validated, injecting script tag..."),jl=new Promise((s,l)=>{let c=document.createElement("script");c.src=o,c.async=!0,e.integrity&&(c.integrity=e.integrity,c.crossOrigin="anonymous",Z("Syntro Runtime","SRI integrity check enabled")),c.onload=()=>{Z("Syntro Runtime","\u2713 Editor SDK script loaded successfully"),Z("Syntro Runtime","================================"),s()},c.onerror=u=>{console.error("[Syntro Runtime] \u274C Failed to load Editor SDK:",u),console.error("[Syntro Runtime] URL attempted:",o),Z("Syntro Runtime","================================"),jl=null,l(u)},document.head.appendChild(c),Z("Syntro Runtime","Script tag appended to <head>")}),jl};function Ld(t,e){for(let n of t){let i=n.props;if(!i)continue;let r=i.scope;if(!r?.events)continue;let a=i.actions;if(!a)continue;let o=new Set;for(let u of a)if(u.showWhen?.type==="rules")for(let f of u.showWhen.rules)for(let h of f.conditions)h.type==="event_count"&&h.key&&o.add(h.key);if(o.size===0)continue;let{events:s,urlContains:l,props:c}=r;for(let u of o)e.register(u,f=>{if(!s.includes(f.name)||l&&!String(f.props?.pathname??"").includes(l))return!1;if(c){for(let[h,g]of Object.entries(c))if(f.props?.[h]!==g)return!1}return!0})}}var ni=null;function Hw(t){ni&&ni!==t?t.appendChild(ni):ni=t;let e=t.getRootNode();e instanceof ShadowRoot&&DM(e)}function Iw(){return ni||(ni=document.createElement("div"),ni.id="syntro-overlays",Object.assign(ni.style,{position:"fixed",inset:"0",zIndex:"2147483647",pointerEvents:"none"}),document.body.appendChild(ni)),ni}var Lw=!1;function DM(t){if(Lw)return;let e=`
|
|
114
114
|
:host {
|
|
115
115
|
--syntro-surface: #0f1318;
|
|
116
116
|
--syntro-fg: #cbd0d7;
|
|
@@ -446,7 +446,7 @@ Actions that failed:`,JSON.stringify(x.actions,null,2))}}})(),()=>{G=!0,z.curren
|
|
|
446
446
|
`).replace(/\r/g,`
|
|
447
447
|
`)).length,r=0;r<i;r++){var o=t.charCodeAt(r),s=null;o<128?n++:s=o>127&&o<2048?String.fromCharCode(o>>6|192,63&o|128):String.fromCharCode(o>>12|224,o>>6&63|128,63&o|128),Wi(s)||(n>e&&(a+=t.substring(e,n)),a+=s,e=n=r+1)}return n>e&&(a+=t.substring(e,t.length)),a},jL=!!mv||!!gv,DC="text/plain",If=function(t,e,n){var i;n===void 0&&(n=!0);var[r,a]=t.split("?"),o=j({},e),s=(i=a?.split("&").map((c=>{var u,[f,h]=c.split("="),g=n&&(u=o[f])!==null&&u!==void 0?u:h;return delete o[f],f+"="+g})))!==null&&i!==void 0?i:[],l=oL(o);return l&&s.push(l),r+"?"+s.join("&")},vc=(t,e)=>JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e),uv=t=>{var{data:e,compression:n}=t;if(e){if(n===Yi.GZipJS){var i=FL((function(l,c){var u=l.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(l);for(var f=new Dn(l.length+(l.length>>>1)),h=0,g=function(d){f[h++]=d},_=0;_<u;++_){if(h+5>f.length){var b=new Dn(h+8+(u-_<<1));b.set(f),f=b}var w=l.charCodeAt(_);w<128||c?g(w):w<2048?(g(192|w>>>6),g(128|63&w)):w>55295&&w<57344?(g(240|(w=65536+(1047552&w)|1023&l.charCodeAt(++_))>>>18),g(128|w>>>12&63),g(128|w>>>6&63),g(128|63&w)):(g(224|w>>>12),g(128|w>>>6&63),g(128|63&w))}return GA(f,0,h)})(vc(e)),{mtime:0}),r=new Blob([i],{type:DC});return{contentType:DC,body:r,estimatedSize:r.size}}if(n===Yi.Base64){var a=(function(l){var c,u,f,h,g,_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b=0,w=0,d="",p=[];if(!l)return l;l=VL(l);do c=(g=l.charCodeAt(b++)<<16|l.charCodeAt(b++)<<8|l.charCodeAt(b++))>>18&63,u=g>>12&63,f=g>>6&63,h=63&g,p[w++]=_.charAt(c)+_.charAt(u)+_.charAt(f)+_.charAt(h);while(b<l.length);switch(d=p.join(""),l.length%3){case 1:d=d.slice(0,-2)+"==";break;case 2:d=d.slice(0,-1)+"="}return d})(vc(e)),o=(l=>"data="+encodeURIComponent(typeof l=="string"?l:vc(l)))(a);return{contentType:"application/x-www-form-urlencoded",body:o,estimatedSize:new Blob([o]).size}}var s=vc(e);return{contentType:"application/json",body:s,estimatedSize:new Blob([s]).size}}},bf=[];gv&&bf.push({transport:"fetch",method:t=>{var e,n,{contentType:i,body:r,estimatedSize:a}=(e=uv(t))!==null&&e!==void 0?e:{},o=new Headers;Re(t.headers,(function(u,f){o.append(f,u)})),i&&o.append("Content-Type",i);var s=t.url,l=null;if(JE){var c=new JE;l={signal:c.signal,timeout:setTimeout((()=>c.abort()),t.timeout)}}gv(s,j({method:t?.method||"GET",headers:o,keepalive:t.method==="POST"&&(a||0)<52428.8,body:r,signal:(n=l)==null?void 0:n.signal},t.fetchOptions)).then((u=>u.text().then((f=>{var h={statusCode:u.status,text:f};if(u.status===200)try{h.json=JSON.parse(f)}catch(g){$.error(g)}t.callback==null||t.callback(h)})))).catch((u=>{$.error(u),t.callback==null||t.callback({statusCode:0,text:u})})).finally((()=>l?clearTimeout(l.timeout):null))}}),mv&&bf.push({transport:"XHR",method:t=>{var e,n=new mv;n.open(t.method||"GET",t.url,!0);var{contentType:i,body:r}=(e=uv(t))!==null&&e!==void 0?e:{};Re(t.headers,(function(a,o){n.setRequestHeader(o,a)})),i&&n.setRequestHeader("Content-Type",i),t.timeout&&(n.timeout=t.timeout),t.disableXHRCredentials||(n.withCredentials=!0),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(r)}}),un!=null&&un.sendBeacon&&bf.push({transport:"sendBeacon",method:t=>{var e=If(t.url,{beacon:"1"});try{var n,{contentType:i,body:r}=(n=uv(t))!==null&&n!==void 0?n:{},a=typeof r=="string"?new Blob([r],{type:i}):r;un.sendBeacon(e,a)}catch{}}});var zf=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function LC(t,e,n){return vc({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var ZA={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>zf(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!zf(n,i))))),icontains:(t,e)=>e.map(vf).some((n=>t.map(vf).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(vf).every((n=>t.map(vf).every((i=>!n.includes(i)))))},vf=t=>t.toLowerCase();function YA(t,e){return!t||Object.entries(t).every((n=>{var[i,r]=n,a=e?.[i];if(I(a)||Wi(a))return!1;var o=[String(a)],s=ZA[r.operator];return!!s&&s(r.values,o)}))}var dv=st("[Error tracking]"),oy=class{constructor(e){var n,i;this.Jt=[],this.Kt=new Sv([new wv,new Ov,new Cv,new Ev,new kv,new Tv,new Av,new Rv],V4("web:javascript",B4,F4)),this._instance=e,this.Jt=(n=(i=this._instance.persistence)==null?void 0:i.get_property(Nv))!==null&&n!==void 0?n:[]}onRemoteConfig(e){var n,i,r,a=(n=(i=e.errorTracking)==null?void 0:i.suppressionRules)!==null&&n!==void 0?n:[],o=(r=e.errorTracking)==null?void 0:r.captureExtensionExceptions;this.Jt=a,this._instance.persistence&&this._instance.persistence.register({[Nv]:this.Jt,[uC]:o})}get Yt(){var e,n=!!this._instance.get_property(uC),i=this._instance.config.error_tracking.captureExtensionExceptions;return(e=i??n)!==null&&e!==void 0&&e}buildProperties(e,n){return this.Kt.buildFromUnknown(e,{syntheticException:n?.syntheticException,mechanism:{handled:n?.handled}})}sendExceptionEvent(e){var n=e.$exception_list;if(this.Xt(n)){if(this.Qt(n))return void dv.info("Skipping exception capture because a suppression rule matched");if(!this.Yt&&this.Zt(n))return void dv.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ti(n))return void dv.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 n=e.reduce(((i,r)=>{var{type:a,value:o}=r;return ot(a)&&a.length>0&&i.$exception_types.push(a),ot(o)&&o.length>0&&i.$exception_values.push(o),i}),{$exception_types:[],$exception_values:[]});return this.Jt.some((i=>{var r=i.values.map((a=>{var o,s=ZA[a.operator],l=Ae(a.value)?a.value:[a.value],c=(o=n[a.key])!==null&&o!==void 0?o:[];return l.length>0&&s(l,c)}));return i.type==="OR"?r.some(Boolean):r.every(Boolean)}))}Zt(e){return e.flatMap((n=>{var i,r;return(i=(r=n.stacktrace)==null?void 0:r.frames)!==null&&i!==void 0?i:[]})).some((n=>n.filename&&n.filename.startsWith("chrome-extension://")))}ti(e){if(e.length>0){var n,i,r,a,o=(n=(i=e[0].stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[],s=o[o.length-1];return(r=s==null||(a=s.filename)==null?void 0:a.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}Xt(e){return!Ee(e)&&Ae(e)}},Gn=st("[FeatureFlags]"),lc=st("[FeatureFlags]",{debugEnabled:!0}),fv="$active_feature_flags",bs="$override_feature_flags",HC="$feature_flag_payloads",cc="$override_feature_flag_payloads",IC="$feature_flag_request_id",zC="$feature_flag_evaluated_at",BC=t=>{var e={};for(var[n,i]of yf(t||{}))i&&(e[n]=i);return e},qL=t=>{var e=t.flags;return e?(t.featureFlags=Object.fromEntries(Object.keys(e).map((n=>{var i;return[n,(i=e[n].variant)!==null&&i!==void 0?i:e[n].enabled]}))),t.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter((n=>e[n].enabled)).filter((n=>{var i;return(i=e[n].metadata)==null?void 0:i.payload})).map((n=>{var i;return[n,(i=e[n].metadata)==null?void 0:i.payload]})))):Gn.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),t},PL=(function(t){return t.FeatureFlags="feature_flags",t.Recordings="recordings",t})({}),sy=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((n=>{var i=n&&typeof n=="string"&&n.trim().length>0;return i||Gn.error("Invalid evaluation environment found:",n,"Expected non-empty string"),i})):[]}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(Dv),n=this._instance.get_property(bs),i=this._instance.get_property(cc);if(!i&&!n)return e||{};var r=Ye({},e||{}),a=[...new Set([...Object.keys(i||{}),...Object.keys(n||{})])];for(var o of a){var s,l,c=r[o],u=n?.[o],f=I(u)?(s=c?.enabled)!==null&&s!==void 0&&s:!!u,h=I(u)?c.variant:typeof u=="string"?u:void 0,g=i?.[o],_=j({},c,{enabled:f,variant:f?h??c?.variant:void 0});f!==c?.enabled&&(_.original_enabled=c?.enabled),h!==c?.variant&&(_.original_variant=c?.variant),g&&(_.metadata=j({},c?.metadata,{payload:g,original_payload:c==null||(l=c.metadata)==null?void 0:l.payload})),r[o]=_}return this.ii||(Gn.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:i,finalDetails:r}),this.ii=!0),r}getFlagVariants(){var e=this._instance.get_property(ws),n=this._instance.get_property(bs);if(!n)return e||{};for(var i=Ye({},e),r=Object.keys(n),a=0;a<r.length;a++)i[r[a]]=n[r[a]];return this.ii||(Gn.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:n,finalFlags:i}),this.ii=!0),i}getFlagPayloads(){var e=this._instance.get_property(HC),n=this._instance.get_property(cc);if(!n)return e||{};for(var i=Ye({},e||{}),r=Object.keys(n),a=0;a<r.length;a++)i[r[a]]=n[r[a]];return this.ii||(Gn.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:n,finalPayloads:i}),this.ii=!0),i}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 n;if(this.di(),!this._instance.O())if(this.ri)this.ni=!0;else{var i={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:j({},((n=this._instance.persistence)==null?void 0:n.get_initial_props())||{},this._instance.get_property(gc)||{}),group_properties:this._instance.get_property(Ka)};(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(i.disable_flags=!0),this.ui()&&(i.evaluation_environments=this.li());var r=this._instance.config.__preview_remote_config,a=r?"/flags/?v=2":"/flags/?v=2&config=true",o=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",s=this._instance.requestRouter.endpointFor("flags",a+o);r&&(i.timezone=VA()),this.ri=!0,this._instance.ci({method:"POST",url:s,data:i,compression:this._instance.config.disable_compression?void 0:Yi.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:l=>{var c,u,f=!0;if(l.statusCode===200&&(this.ni||(this.$anon_distinct_id=void 0),f=!1),this.ri=!1,this.oi||(this.oi=!0,this._instance.fi((u=l.json)!==null&&u!==void 0?u:{})),!i.disable_flags||this.ni)if(this.ai=!f,l.json&&(c=l.json.quotaLimited)!=null&&c.includes(PL.FeatureFlags))Gn.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;i.disable_flags||this.receivedFeatureFlags((h=l.json)!==null&&h!==void 0?h:{},f),this.ni&&(this.ni=!1,this.vi())}}})}}getFeatureFlag(e,n){if(n===void 0&&(n={}),this.ei||this.getFlags()&&this.getFlags().length>0){var i=this.getFlagVariants()[e],r=""+i,a=this._instance.get_property(IC)||void 0,o=this._instance.get_property(zC)||void 0,s=this._instance.get_property(Ef)||{};if((n.send_event||!("send_event"in n))&&(!(e in s)||!s[e].includes(r))){var l,c,u,f,h,g,_,b,w;Ae(s[e])?s[e].push(r):s[e]=[r],(l=this._instance.persistence)==null||l.register({[Ef]:s});var d=this.getFeatureFlagDetails(e),p={$feature_flag:e,$feature_flag_response:i,$feature_flag_payload:this.getFeatureFlagPayload(e)||null,$feature_flag_request_id:a,$feature_flag_evaluated_at:o,$feature_flag_bootstrapped_response:((c=this._instance.config.bootstrap)==null||(c=c.featureFlags)==null?void 0:c[e])||null,$feature_flag_bootstrapped_payload:((u=this._instance.config.bootstrap)==null||(u=u.featureFlagPayloads)==null?void 0:u[e])||null,$used_bootstrap_value:!this.ai};I(d==null||(f=d.metadata)==null?void 0:f.version)||(p.$feature_flag_version=d.metadata.version);var m,v=(h=d==null||(g=d.reason)==null?void 0:g.description)!==null&&h!==void 0?h:d==null||(_=d.reason)==null?void 0:_.code;v&&(p.$feature_flag_reason=v),d!=null&&(b=d.metadata)!=null&&b.id&&(p.$feature_flag_id=d.metadata.id),I(d?.original_variant)&&I(d?.original_enabled)||(p.$feature_flag_original_response=I(d.original_variant)?d.original_enabled:d.original_variant),d!=null&&(w=d.metadata)!=null&&w.original_payload&&(p.$feature_flag_original_payload=d==null||(m=d.metadata)==null?void 0:m.original_payload),this._instance.capture("$feature_flag_called",p)}return i}Gn.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,n){var i=this._instance.config.token,r={distinct_id:this._instance.get_distinct_id(),token:i};this.ui()&&(r.evaluation_environments=this.li()),this._instance.ci({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2&config=true"),data:r,compression:this._instance.config.disable_compression?void 0:Yi.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:a=>{var o,s=(o=a.json)==null?void 0:o.featureFlagPayloads;n(s?.[e]||void 0)}})}isFeatureEnabled(e,n){if(n===void 0&&(n={}),this.ei||this.getFlags()&&this.getFlags().length>0){var i=this.getFeatureFlag(e,n);return I(i)?void 0:!!i}Gn.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((n=>n!==e))}receivedFeatureFlags(e,n){if(this._instance.persistence){this.ei=!0;var i=this.getFlagVariants(),r=this.getFlagPayloads(),a=this.getFlagsWithDetails();(function(o,s,l,c,u){l===void 0&&(l={}),c===void 0&&(c={}),u===void 0&&(u={});var f=qL(o),h=f.flags,g=f.featureFlags,_=f.featureFlagPayloads;if(g){var b=o.requestId,w=o.evaluatedAt;if(Ae(g)){Gn.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var d={};if(g)for(var p=0;p<g.length;p++)d[g[p]]=!0;s&&s.register({[fv]:g,[ws]:d})}else{var m=g,v=_,S=h;o.errorsWhileComputingFlags&&(m=j({},l,m),v=j({},c,v),S=j({},u,S)),s&&s.register(j({[fv]:Object.keys(BC(m)),[ws]:m||{},[HC]:v||{},[Dv]:S||{}},b?{[IC]:b}:{},w?{[zC]:w}:{}))}}})(e,this._instance.persistence,i,r,a),this.pi(n)}}override(e,n){n===void 0&&(n=!1),Gn.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:n})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return Gn.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister(bs),this._instance.persistence.unregister(cc),this.pi(),lc.info("All overrides cleared");if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var n,i=e;if(this.ii=!!((n=i.suppressWarning)!==null&&n!==void 0&&n),"flags"in i){if(i.flags===!1)this._instance.persistence.unregister(bs),lc.info("Flag overrides cleared");else if(i.flags){if(Ae(i.flags)){for(var r={},a=0;a<i.flags.length;a++)r[i.flags[a]]=!0;this._instance.persistence.register({[bs]:r})}else this._instance.persistence.register({[bs]:i.flags});lc.info("Flag overrides set",{flags:i.flags})}}return"payloads"in i&&(i.payloads===!1?(this._instance.persistence.unregister(cc),lc.info("Payload overrides cleared")):i.payloads&&(this._instance.persistence.register({[cc]:i.payloads}),lc.info("Payload overrides set",{payloads:i.payloads}))),void this.pi()}this.pi()}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.ei){var{flags:n,flagVariants:i}=this.gi();e(n,i)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,n,i){var r,a=(this._instance.get_property(hc)||[]).find((c=>c.flagKey===e)),o={["$feature_enrollment/"+e]:n},s={$feature_flag:e,$feature_enrollment:n,$set:o};a&&(s.$early_access_feature_name=a.name),i&&(s.$feature_enrollment_stage=i),this._instance.capture("$feature_enrollment_update",s),this.setPersonPropertiesForFlags(o,!1);var l=j({},this.getFlagVariants(),{[e]:n});(r=this._instance.persistence)==null||r.register({[fv]:Object.keys(BC(l)),[ws]:l}),this.pi()}getEarlyAccessFeatures(e,n,i){n===void 0&&(n=!1);var r=this._instance.get_property(hc),a=i?"&"+i.map((o=>"stage="+o)).join("&"):"";if(r&&!n)return e(r);this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+a),method:"GET",callback:o=>{var s,l;if(o.json){var c=o.json.earlyAccessFeatures;return(s=this._instance.persistence)==null||s.unregister(hc),(l=this._instance.persistence)==null||l.register({[hc]:c}),e(c)}}})}gi(){var e=this.getFlags(),n=this.getFlagVariants();return{flags:e.filter((i=>n[i])),flagVariants:Object.keys(n).filter((i=>n[i])).reduce(((i,r)=>(i[r]=n[r],i)),{})}}pi(e){var{flags:n,flagVariants:i}=this.gi();this.featureFlagEventHandlers.forEach((r=>r(n,i,{errorsLoading:e})))}setPersonPropertiesForFlags(e,n){n===void 0&&(n=!0);var i=this._instance.get_property(gc)||{};this._instance.register({[gc]:j({},i,e)}),n&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(gc)}setGroupPropertiesForFlags(e,n){n===void 0&&(n=!0);var i=this._instance.get_property(Ka)||{};Object.keys(i).length!==0&&Object.keys(i).forEach((r=>{i[r]=j({},i[r],e[r]),delete e[r]})),this._instance.register({[Ka]:j({},i,e)}),n&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var n=this._instance.get_property(Ka)||{};this._instance.register({[Ka]:j({},n,{[e]:{}})})}else this._instance.unregister(Ka)}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}},GL=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],_c=class{constructor(e,n){this.F=e,this.props={},this.mi=!1,this.yi=(i=>{var r="";return i.token&&(r=i.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),i.persistence_name?"ph_"+i.persistence_name:"ph_"+r+"_posthog"})(e),this.Y=this.bi(e),this.load(),e.debug&&$.info("Persistence loaded",e.persistence,j({},this.props)),this.update_config(e,e,n),this.save()}isDisabled(){return!!this.wi}bi(e){GL.indexOf(e.persistence.toLowerCase())===-1&&($.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n=e.persistence.toLowerCase();return n==="localstorage"&&Fe.H()?Fe:n==="localstorage+cookie"&&pf.H()?pf:n==="sessionstorage"&&_t.H()?_t:n==="memory"?hL:n==="cookie"?ci:pf.H()?pf:ci}properties(){var e={};return Re(this.props,(function(n,i){if(i===ws&&ft(n))for(var r=Object.keys(n),a=0;a<r.length;a++)e["$feature/"+r[a]]=n[r[a]];else s=i,l=!1,(Wi(o=K4)?l:QE&&o.indexOf===QE?o.indexOf(s)!=-1:(Re(o,(function(c){if(l||(l=c===s))return xf})),l))||(e[i]=n);var o,s,l})),e}load(){if(!this.wi){var e=this.Y.W(this.yi);e&&(this.props=Ye({},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,n,i){if(ft(e)){I(n)&&(n="None"),this.xi=I(i)?this.$i:i;var r=!1;if(Re(e,((a,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.props[o]=a,r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(ft(e)){this.xi=I(n)?this.$i:n;var i=!1;if(Re(e,((r,a)=>{e.hasOwnProperty(a)&&this.props[a]!==r&&(this.props[a]=r,i=!0)})),i)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=IA(this.F.custom_campaign_params,this.F.mask_personal_data_properties,this.F.custom_personal_data_properties);xs(Cy(e))||this.register(e),this.mi=!0}}update_search_keyword(){var e;this.register((e=B?.referrer)?BA(e):{})}update_referrer_info(){var e;this.register_once({$referrer:$A(),$referring_domain:B!=null&&B.referrer&&((e=Rf(B.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[zv]||this.props[Bv]||this.register_once({[Cf]:UA(this.F.mask_personal_data_properties,this.F.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};Re([Bv,zv],(o=>{var s=this.props[o];s&&Re(s,(function(l,c){e["$initial_"+vv(c)]=l}))}));var n,i,r=this.props[Cf];if(r){var a=(n=FA(r),i={},Re(n,(function(o,s){i["$initial_"+vv(s)]=o})),i);Ye(e,a)}return e}safe_merge(e){return Re(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){if(this.$i=this.xi=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==n.persistence){var r=this.bi(e),a=this.props;this.clear(),this.Y=r,this.props=a,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,n){var i=this.props[pc]||{};i[e]=n,this.props[pc]=i,this.save()}remove_event_timer(e){var n=(this.props[pc]||{})[e];return I(n)||(delete this.props[pc][e],this.save()),n}get_property(e){return this.props[e]}set_property(e,n){this.props[e]=n,this.save()}},uc=(function(t){return t.Activation="events",t.Cancellation="cancelEvents",t})({}),xB=(function(t){return t.Button="button",t.Tab="tab",t.Selector="selector",t})({}),wB=(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})({}),EB=(function(t){return t.Top="top",t.Left="left",t.Right="right",t.Bottom="bottom",t})({}),pv=(function(t){return t.Popover="popover",t.API="api",t.Widget="widget",t.ExternalSurvey="external_survey",t})({}),CB=(function(t){return t.Open="open",t.MultipleChoice="multiple_choice",t.SingleChoice="single_choice",t.Rating="rating",t.Link="link",t})({}),AB=(function(t){return t.NextQuestion="next_question",t.End="end",t.ResponseBased="response_based",t.SpecificQuestion="specific_question",t})({}),TB=(function(t){return t.Once="once",t.Recurring="recurring",t.Always="always",t})({}),_f=(function(t){return t.SHOWN="survey shown",t.DISMISSED="survey dismissed",t.SENT="survey sent",t})({}),$C=(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})({}),WA=(function(t){return t.Popover="popover",t.Inline="inline",t})({}),Tc=class{constructor(){this.ki={},this.ki={}}on(e,n){return this.ki[e]||(this.ki[e]=[]),this.ki[e].push(n),()=>{this.ki[e]=this.ki[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.ki[e]||[])i(n);for(var r of this.ki["*"]||[])r(e,n)}};function _s(t,e,n){if(Ee(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}var ly=class{constructor(e){this.Pi=new Tc,this.Ti=(n,i)=>this.Ri(n,i)&&this.Ii(n,i)&&this.Fi(n,i)&&this.Ci(n,i),this.Ri=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.Mi=new Set,this.Oi=new Set}init(){var e;if(!I((e=this._instance)==null?void 0:e.Ai)){var n;(n=this._instance)==null||n.Ai(((i,r)=>{this.on(i,r)}))}}register(e){var n,i;if(!I((n=this._instance)==null?void 0:n.Ai)&&(e.forEach((o=>{var s,l;(s=this.Oi)==null||s.add(o),(l=o.steps)==null||l.forEach((c=>{var u;(u=this.Mi)==null||u.add(c?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,a=new Set;e.forEach((o=>{var s;(s=o.steps)==null||s.forEach((l=>{l!=null&&l.selector&&a.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(a)}}on(e,n){var i;n!=null&&e.length!=0&&(this.Mi.has(e)||this.Mi.has(n?.event))&&this.Oi&&((i=this.Oi)==null?void 0:i.size)>0&&this.Oi.forEach((r=>{this.Di(n,r)&&this.Pi.emit("actionCaptured",r.name)}))}ji(e){this.onAction("actionCaptured",(n=>e(n)))}Di(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.Ti(e,i))return!0;return!1}onAction(e,n){return this.Pi.on(e,n)}Ii(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!_s(r,n.url,n.url_matching||"contains"))return!1}return!0}Fi(e,n){return!!this.Li(e,n)&&!!this.Ni(e,n)&&!!this.Ui(e,n)}Li(e,n){var i;if(n==null||!n.href)return!0;var r=this.zi(e);if(r.length>0)return r.some((s=>_s(s.href,n.href,n.href_matching||"exact")));var a,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&_s((a=o.match(/(?::|")href="(.*?)"/))?a[1]:"",n.href,n.href_matching||"exact")}Ni(e,n){var i;if(n==null||!n.text)return!0;var r=this.zi(e);if(r.length>0)return r.some((c=>_s(c.text,n.text,n.text_matching||"exact")||_s(c.$el_text,n.text,n.text_matching||"exact")));var a,o,s,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(a=(function(c){for(var u,f=[],h=/(?::|")text="(.*?)"/g;!Ee(u=h.exec(c));)f.includes(u[1])||f.push(u[1]);return f})(l),o=n.text,s=n.text_matching||"exact",a.some((c=>_s(c,o,s))))}Ui(e,n){var i,r;if(n==null||!n.selector)return!0;var a=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(a!=null&&a.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}zi(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}Ci(e,n){return n==null||!n.properties||n.properties.length===0||YA(n.properties.reduce(((i,r)=>{var a=Ae(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:a,operator:r.operator||"exact"},i}),{}),e?.properties)}},Se=st("[Surveys]"),cy="seenSurvey_",ZL=(t,e)=>{var n="$survey_"+e+"/"+t.id;return t.current_iteration&&t.current_iteration>0&&(n="$survey_"+e+"/"+t.id+"/"+t.current_iteration),n},UC=t=>{var e=""+cy+t.id;return t.current_iteration&&t.current_iteration>0&&(e=""+cy+t.id+"_"+t.current_iteration),e},YL=[pv.Popover,pv.Widget,pv.API],WL={ignoreConditions:!1,ignoreDelay:!1,displayType:WA.Popover},uy=class{constructor(e){this._instance=e,this.Hi=new Map,this.Bi=new Map,this.qi=new Map}Wi(e,n){return!!e&&YA(e.propertyFilters,n?.properties)}Gi(e,n){var i=new Map;return e.forEach((r=>{var a;(a=r.conditions)==null||(a=a[n])==null||(a=a.values)==null||a.forEach((o=>{if(o!=null&&o.name){var s=i.get(o.name)||[];s.push(r.id),i.set(o.name,s)}}))})),i}Vi(e,n,i){var r,a=(i===uc.Activation?this.Hi:this.Bi).get(e),o=[];return(r=this._instance)==null||r.getSurveys((s=>{o=s.filter((l=>a?.includes(l.id)))})),o.filter((s=>{var l,c=(l=s.conditions)==null||(l=l[i])==null||(l=l.values)==null?void 0:l.find((u=>u.name===e));return this.Wi(c,n)}))}register(e){var n;I((n=this._instance)==null?void 0:n.Ai)||(this.Ji(e),this.Ki(e))}Ki(e){var n=e.filter((i=>{var r,a;return((r=i.conditions)==null?void 0:r.actions)&&((a=i.conditions)==null||(a=a.actions)==null||(a=a.values)==null?void 0:a.length)>0}));n.length!==0&&(this.Yi==null&&(this.Yi=new ly(this._instance),this.Yi.init(),this.Yi.ji((i=>{this.onAction(i)}))),n.forEach((i=>{var r,a,o,s,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(a=i.conditions)!=null&&(a=a.actions)!=null&&a.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((s=this.Yi)==null||s.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((c=>{if(c&&c.name){var u=this.qi.get(c.name);u&&u.push(i.id),this.qi.set(c.name,u||[i.id])}})))})))}Ji(e){var n,i=e.filter((a=>{var o,s;return((o=a.conditions)==null?void 0:o.events)&&((s=a.conditions)==null||(s=s.events)==null||(s=s.values)==null?void 0:s.length)>0})),r=e.filter((a=>{var o,s;return((o=a.conditions)==null?void 0:o.cancelEvents)&&((s=a.conditions)==null||(s=s.cancelEvents)==null||(s=s.values)==null?void 0:s.length)>0}));(i.length!==0||r.length!==0)&&((n=this._instance)==null||n.Ai(((a,o)=>{this.onEvent(a,o)})),this.Hi=this.Gi(e,uc.Activation),this.Bi=this.Gi(e,uc.Cancellation))}onEvent(e,n){var i,r=((i=this._instance)==null||(i=i.persistence)==null?void 0:i.props[ff])||[];if(_f.SHOWN===e&&n&&r.length>0){var a;Se.info("survey event matched, removing survey from activated surveys",{event:e,eventPayload:n,existingActivatedSurveys:r});var o=n==null||(a=n.properties)==null?void 0:a.$survey_id;if(o){var s=r.indexOf(o);s>=0&&(r.splice(s,1),this.Xi(r))}}else{if(this.Bi.has(e)){var l=this.Vi(e,n,uc.Cancellation);l.length>0&&(Se.info("cancel event matched, cancelling surveys",{event:e,surveysToCancel:l.map((u=>u.id))}),l.forEach((u=>{var f,h=r.indexOf(u.id);h>=0&&r.splice(h,1),(f=this._instance)==null||f.cancelPendingSurvey(u.id)})),this.Xi(r))}if(this.Hi.has(e)){Se.info("survey event name matched",{event:e,eventPayload:n,surveys:this.Hi.get(e)});var c=this.Vi(e,n,uc.Activation);this.Xi(r.concat(c.map((u=>u.id))||[]))}}}onAction(e){var n,i=((n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[ff])||[];this.qi.has(e)&&this.Xi(i.concat(this.qi.get(e)||[]))}Xi(e){var n;Se.info("updating activated surveys",{activatedSurveys:e}),(n=this._instance)==null||(n=n.persistence)==null||n.register({[ff]:[...new Set(e)]})}getSurveys(){var e,n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[ff];return n||[]}getEventToSurveys(){return this.Hi}Qi(){return this.Yi}},dy=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 n=e.surveys;if(Ee(n))return Se.warn("Flags not loaded yet. Not loading surveys.");var i=Ae(n);this.Zi=i?n.length>0:n,Se.info("flags response received, isSurveysEnabled: "+this.Zi),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;n<localStorage.length;n++){var i=localStorage.key(n);(i!=null&&i.startsWith(cy)||i!=null&&i.startsWith("inProgressSurvey_"))&&e.push(i)}e.forEach((r=>localStorage.removeItem(r)))}loadIfEnabled(){if(!this._surveyManager)if(this.ie)Se.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)Se.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())Se.info("Not loading surveys in cookieless mode without consent.");else{var e=X?.__PosthogExtensions__;if(e){if(!I(this.Zi)||this._instance.config.advanced_enable_surveys){var n=this.Zi||this._instance.config.advanced_enable_surveys;this.ie=!0;try{var i=e.generateSurveys;if(i)return void this.re(i,n);var r=e.loadExternalDependency;if(!r)return void this.se("PostHog loadExternalDependency extension not found.");r(this._instance,"surveys",(a=>{a||!e.generateSurveys?this.se("Could not load surveys script",a):this.re(e.generateSurveys,n)}))}catch(a){throw this.se("Error initializing surveys",a),a}finally{this.ie=!1}}}else Se.error("PostHog Extensions not found.")}}re(e,n){this._surveyManager=e(this._instance,n),this._surveyEventReceiver=new uy(this._instance),Se.info("Surveys loaded successfully"),this.ne({isLoaded:!0})}se(e,n){Se.error(e,n),this.ne({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.ee.push(e),this._surveyManager&&this.ne({isLoaded:!0}),()=>{this.ee=this.ee.filter((n=>n!==e))}}getSurveys(e,n){if(n===void 0&&(n=!1),this._instance.config.disable_surveys)return Se.info("Disabled. Not loading surveys."),e([]);var i=this._instance.get_property(Lv);if(i&&!n)return e(i,{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:r=>{var a;this.te=!1;var o=r.statusCode;if(o!==200||!r.json){var s="Surveys API could not be loaded, status: "+o;return Se.error(s),e([],{isLoaded:!1,error:s})}var l,c=r.json.surveys||[],u=c.filter((f=>(function(h){return!(!h.start_date||h.end_date)})(f)&&((function(h){var g;return!((g=h.conditions)==null||(g=g.events)==null||(g=g.values)==null||!g.length)})(f)||(function(h){var g;return!((g=h.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(f))));return u.length>0&&((l=this._surveyEventReceiver)==null||l.register(u)),(a=this._instance.persistence)==null||a.register({[Lv]:c}),e(c,{isLoaded:!0})}})}catch(r){throw this.te=!1,r}}ne(e){for(var n of this.ee)try{if(!e.isLoaded)return n([],e);this.getSurveys(n)}catch(i){Se.error("Error in survey callback",i)}}getActiveMatchingSurveys(e,n){if(n===void 0&&(n=!1),!Ee(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,n);Se.warn("init was not called")}oe(e){var n=null;return this.getSurveys((i=>{var r;n=(r=i.find((a=>a.id===e)))!==null&&r!==void 0?r:null})),n}ae(e){if(Ee(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var n=typeof e=="string"?this.oe(e):e;return n?this._surveyManager.checkSurveyEligibility(n):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(Ee(this._surveyManager))return Se.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var n=this.ae(e);return{visible:n.eligible,disabledReason:n.reason}}canRenderSurveyAsync(e,n){return Ee(this._surveyManager)?(Se.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise((i=>{this.getSurveys((r=>{var a,o=(a=r.find((l=>l.id===e)))!==null&&a!==void 0?a:null;if(o){var s=this.ae(o);i({visible:s.eligible,disabledReason:s.reason})}else i({visible:!1,disabledReason:"Survey not found"})}),n)}))}renderSurvey(e,n){var i;if(Ee(this._surveyManager))Se.warn("init was not called");else{var r=typeof e=="string"?this.oe(e):e;if(r!=null&&r.id)if(YL.includes(r.type)){var a=B?.querySelector(n);if(a)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Se.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,s;Se.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(s=this._surveyManager)==null||s.renderSurvey(r,a),Se.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,a);Se.warn("Survey element not found")}else Se.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Se.warn("Survey not found")}}displaySurvey(e,n){var i;if(Ee(this._surveyManager))Se.warn("init was not called");else{var r=this.oe(e);if(r){var a=r;if((i=r.appearance)!=null&&i.surveyPopupDelaySeconds&&n.ignoreDelay&&(a=j({},r,{appearance:j({},r.appearance,{surveyPopupDelaySeconds:0})})),n.ignoreConditions===!1){var o=this.canRenderSurvey(r);if(!o.visible)return void Se.warn("Survey is not eligible to be displayed: ",o.disabledReason)}n.displayType!==WA.Inline?this._surveyManager.handlePopoverSurvey(a):this.renderSurvey(a,n.selector)}else Se.warn("Survey not found")}}cancelPendingSurvey(e){Ee(this._surveyManager)?Se.warn("init was not called"):this._surveyManager.cancelSurvey(e)}},FC=st("[RateLimiter]"),fy=class{constructor(e){var n,i;this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=r=>{var a=r.text;if(a&&a.length)try{(JSON.parse(a).quota_limited||[]).forEach((o=>{FC.info((o||"events")+" is quota limited."),this.serverLimits[o]=new Date().getTime()+6e4}))}catch(o){return void FC.warn('could not rate limit - continuing. Error: "'+o?.message+'"',{text:a})}},this.instance=e,this.captureEventsPerSecond=((n=e.config.rate_limiting)==null?void 0:n.events_per_second)||10,this.captureEventsBurstLimit=Math.max(((i=e.config.rate_limiting)==null?void 0:i.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond),this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var a=new Date().getTime(),o=(n=(i=this.instance.persistence)==null?void 0:i.get_property(Iv))!==null&&n!==void 0?n:{tokens:this.captureEventsBurstLimit,last:a};o.tokens+=(a-o.last)/1e3*this.captureEventsPerSecond,o.last=a,o.tokens>this.captureEventsBurstLimit&&(o.tokens=this.captureEventsBurstLimit);var s=o.tokens<1;return s||e||(o.tokens=Math.max(0,o.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,(r=this.instance.persistence)==null||r.set_property(Iv,o),{isRateLimited:s,remainingTokens:o.tokens}}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()<n}},Wa=st("[RemoteConfig]"),py=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=X._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.config}le(e){var n,i;(n=X.__PosthogExtensions__)!=null&&n.loadExternalDependency?(i=X.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,"remote-config",(()=>e(this.remoteConfig))):(Wa.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:n=>{e(n.json)}})}load(){try{if(this.remoteConfig)return Wa.info("Using preloaded remote config",this.remoteConfig),void this.fi(this.remoteConfig);if(this._instance.O())return void Wa.warn("Remote config is disabled. Falling back to local config.");this.le((e=>{if(!e)return Wa.info("No config found after loading remote JS config. Falling back to JSON."),void this.ue((n=>{this.fi(n)}));this.fi(e)}))}catch(e){Wa.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()):Wa.info("__preview_remote_config is disabled. Logging config instead",e):Wa.error("Failed to fetch remote config from PostHog.")}},hy=3e3,gy=class{constructor(e,n){this.he=!0,this.ve=[],this.de=si(n?.flush_interval_ms||hy,250,5e3,$.createLogger("flush interval"),hy),this.ce=e}enqueue(e){this.ve.push(e),this.fe||this.pe()}unload(){this.ge();var e=this.ve.length>0?this._e():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.ce(j({},i,{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 n=this._e(),i=function(){var a=n[r],o=new Date().getTime();a.data&&Ae(a.data)&&Re(a.data,(s=>{s.offset=Math.abs(s.timestamp-o),delete s.timestamp})),e.ce(a)};for(var r in n)i()}}),this.de))}ge(){clearTimeout(this.fe),this.fe=void 0}_e(){var e={};return Re(this.ve,(n=>{var i,r=n,a=(r?r.batchKey:null)||r.url;I(e[a])&&(e[a]=j({},r,{data:[]})),(i=e[a].data)==null||i.push(r.data)})),this.ve=[],e}},KL=["retriesPerformedSoFar"],my=class{constructor(e){this.me=!1,this.ye=3e3,this.ve=[],this._instance=e,this.ve=[],this.be=!0,!I(R)&&"onLine"in R.navigator&&(this.be=R.navigator.onLine,this.we=()=>{this.be=!0,this.Dt()},this.xe=()=>{this.be=!1},tt(R,"online",this.we),tt(R,"offline",this.xe))}get length(){return this.ve.length}retriableRequest(e){var{retriesPerformedSoFar:n}=e,i=ZC(e,KL);ui(n)&&n>0&&(i.url=If(i.url,{retry_count:n})),this._instance.ci(j({},i,{callback:r=>{r.statusCode!==200&&(r.statusCode<400||r.statusCode>=500)&&(n??0)<10?this.Se(j({retriesPerformedSoFar:n},i)):i.callback==null||i.callback(r)}}))}Se(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var s=3e3*Math.pow(2,o),l=s/2,c=Math.min(18e5,s),u=(Math.random()-.5)*(c-l);return Math.ceil(c+u)})(n),r=Date.now()+i;this.ve.push({retryAt:r,requestOptions:e});var a="Enqueued failed request for retry in "+i;navigator.onLine||(a+=" (Browser is offline)"),$.warn(a),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(),n=[],i=this.ve.filter((a=>a.retryAt<e||(n.push(a),!1)));if(this.ve=n,i.length>0)for(var{requestOptions:r}of i)this.retriableRequest(r)}unload(){for(var{requestOptions:e}of(this.$e&&(clearTimeout(this.$e),this.$e=void 0),this.me=!1,I(R)||(this.we&&(R.removeEventListener("online",this.we),this.we=void 0),this.xe&&(R.removeEventListener("offline",this.xe),this.xe=void 0)),this.ve))try{this._instance.ci(j({},e,{transport:"sendBeacon"}))}catch(n){$.error(n)}this.ve=[]}},vy=class{constructor(e){this.ke=()=>{var n,i,r,a;this.Pe||(this.Pe={});var o=this.scrollElement(),s=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,c=s+(o?.clientHeight||0),u=o?.scrollHeight||0;this.Pe.lastScrollY=Math.ceil(s),this.Pe.maxScrollY=Math.max(s,(n=this.Pe.maxScrollY)!==null&&n!==void 0?n:0),this.Pe.maxScrollHeight=Math.max(l,(i=this.Pe.maxScrollHeight)!==null&&i!==void 0?i:0),this.Pe.lastContentY=c,this.Pe.maxContentY=Math.max(c,(r=this.Pe.maxContentY)!==null&&r!==void 0?r:0),this.Pe.maxContentHeight=Math.max(u,(a=this.Pe.maxContentHeight)!==null&&a!==void 0?a:0)},this._instance=e}getContext(){return this.Pe}resetContext(){var e=this.Pe;return setTimeout(this.ke,0),e}startMeasuringScrollPosition(){tt(R,"scroll",this.ke,{capture:!0}),tt(R,"scrollend",this.ke,{capture:!0}),tt(R,"resize",this.ke)}scrollElement(){if(!this._instance.config.scroll_root_selector)return R?.document.documentElement;var e=Ae(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var n of e){var i=R?.document.querySelector(n);if(i)return i}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return R&&(R.scrollY||R.pageYOffset||R.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return R&&(R.scrollX||R.pageXOffset||R.document.documentElement.scrollLeft)||0}},XL=t=>UA(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties),Bf=class{constructor(e,n,i,r){this.Te=a=>{var o=this.Re();if(!o||o.sessionId!==a){var s={sessionId:a,props:this.Ie(this._instance)};this.Fe.register({[Hv]:s})}},this._instance=e,this.Ce=n,this.Fe=i,this.Ie=r||XL,this.Ce.onSessionId(this.Te)}Re(){return this.Fe.props[Hv]}getSetOnceProps(){var e,n=(e=this.Re())==null?void 0:e.props;return n?"r"in n?FA(n):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return Re(Cy(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+vv(i)]=n})),e}},hv=st("[SessionId]"),$f=class{on(e,n){return this.Me.on(e,n)}constructor(e,n,i){var r;if(this.Oe=[],this.Ae=void 0,this.Me=new Tc,this.De=(u,f)=>Math.abs(u-f)>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=n||Wr,this.Ue=i||Wr;var a=this.F.persistence_name||this.F.token,o=this.F.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*si(o,60,36e3,hv.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.ze(),this.He="ph_"+a+"_window_id",this.Be="ph_"+a+"_primary_window_exists",this.qe()){var s=_t.W(this.He),l=_t.W(this.Be);s&&!l?this.je=s:_t.V(this.He),_t.G(this.Be,!0)}if((r=this.F.bootstrap)!=null&&r.sessionID)try{var c=(u=>{var f=u.replace(/-/g,"");if(f.length!==32)throw new Error("Not a valid UUID");if(f[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(f.substring(0,12),16)})(this.F.bootstrap.sessionID);this.We(this.F.bootstrap.sessionID,new Date().getTime(),c)}catch(u){hv.error("Invalid sessionID in bootstrap",u)}this.Ge()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return I(this.Oe)&&(this.Oe=[]),this.Oe.push(e),this.Le&&e(this.Le,this.je),()=>{this.Oe=this.Oe.filter((n=>n!==e))}}qe(){return this.F.persistence!=="memory"&&!this.Fe.wi&&_t.H()}Ve(e){e!==this.je&&(this.je=e,this.qe()&&_t.G(this.He,e))}Je(){return this.je?this.je:this.qe()?_t.W(this.He):null}We(e,n,i){e===this.Le&&n===this._sessionActivityTimestamp&&i===this._sessionStartTimestamp||(this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Le=e,this.Fe.register({[wf]:[n,e,i]}))}Ke(){var e=this.Fe.props[wf];return Ae(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&&R&&(R.removeEventListener("beforeunload",this.Ae,{capture:!1}),this.Ae=void 0),this.Oe=[]}Ge(){this.Ae=()=>{this.qe()&&_t.V(this.Be)},tt(R,"beforeunload",this.Ae,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.F.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),[r,a,o]=this.Ke(),s=this.Je(),l=ui(o)&&o>0&&Math.abs(i-o)>864e5,c=!1,u=!a,f=!u&&!e&&this.De(i,r);u||f||l?(a=this.Ne(),s=this.Ue(),hv.info("new session ID generated",{sessionId:a,windowId:s,changeReason:{noSessionId:u,activityTimeout:f,sessionPastMaximumLength:l}}),o=i,c=!0):s||(s=this.Ue(),c=!0);var h=r===0||!e||l?i:r,g=o===0?new Date().getTime():o;return this.Ve(s),this.We(a,h,g),e||this.ze(),c&&this.Oe.forEach((_=>_(a,s,c?{noSessionId:u,activityTimeout:f,sessionPastMaximumLength:l}:void 0))),{sessionId:a,windowId:s,sessionStartTimestamp:g,changeReason:c?{noSessionId:u,activityTimeout:f,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:r}}ze(){clearTimeout(this.Ye),this.Ye=setTimeout((()=>{var[e]=this.Ke();if(this.De(new Date().getTime(),e)){var n=this.Le;this.resetSessionId(),this.Me.emit("forcedIdleReset",{idleSessionId:n})}}),1.1*this.sessionTimeoutMs)}},QL=["$set_once","$set"],Zr=st("[SiteApps]"),yy=class{constructor(e){this._instance=e,this.Xe=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Qe(e,n){if(n){var i=this.globalsForEvent(n);this.Xe.push(i),this.Xe.length>1e3&&(this.Xe=this.Xe.slice(10))}}get siteAppLoaders(){var e;return(e=X._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 n,i,r,a,o,s,l;if(!e)throw new Error("Event payload is required");var c={},u=this._instance.get_property("$groups")||[],f=this._instance.get_property("$stored_group_properties")||{};for(var[h,g]of Object.entries(f))c[h]={id:u[h],type:h,properties:g};var{$set_once:_,$set:b}=e;return{event:j({},ZC(e,QL),{properties:j({},e.properties,b?{$set:j({},(n=(i=e.properties)==null?void 0:i.$set)!==null&&n!==void 0?n:{},b)}:{},_?{$set_once:j({},(r=(a=e.properties)==null?void 0:a.$set_once)!==null&&r!==void 0?r:{},_)}:{}),elements_chain:(o=(s=e.properties)==null?void 0:s.$elements_chain)!==null&&o!==void 0?o:"",distinct_id:(l=e.properties)==null?void 0:l.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:c}}setupSiteApp(e){var n=this.apps[e.id],i=()=>{var s;!n.errored&&this.Xe.length&&(Zr.info("Processing "+this.Xe.length+" events for site app with id "+e.id),this.Xe.forEach((l=>n.processEvent==null?void 0:n.processEvent(l))),n.processedBuffer=!0),Object.values(this.apps).every((l=>l.processedBuffer||l.errored))&&((s=this.Ze)==null||s.call(this))},r=!1,a=s=>{n.errored=!s,n.loaded=!0,Zr.info("Site app with id "+e.id+" "+(s?"loaded":"errored")),r&&i()};try{var{processEvent:o}=e.init({posthog:this._instance,callback:s=>{a(s)}});o&&(n.processEvent=o),r=!0}catch(s){Zr.error("Error while initializing PostHog app with config id "+e.id,s),a(!1)}if(r&&n.loaded)try{i()}catch(s){Zr.error("Error while processing buffered events PostHog app with config id "+e.id,s),n.errored=!0}}tr(){var e=this.siteAppLoaders||[];for(var n of e)this.apps[n.id]={id:n.id,loaded:!1,errored:!1,processedBuffer:!1};for(var i of e)this.setupSiteApp(i)}ir(e){if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(e);for(var i of Object.values(this.apps))try{i.processEvent==null||i.processEvent(n)}catch(r){Zr.error("Error while processing event "+e.event+" for site app "+i.id,r)}}}onRemoteConfig(e){var n,i,r,a=this;if((n=this.siteAppLoaders)!=null&&n.length)return this.isEnabled?(this.tr(),void this._instance.on("eventCaptured",(c=>this.ir(c)))):void Zr.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((i=this.Ze)==null||i.call(this),(r=e.siteApps)!=null&&r.length)if(this.isEnabled){var o=function(c){var u;X["__$$ph_site_app_"+c]=a._instance,(u=X.__PosthogExtensions__)==null||u.loadSiteApp==null||u.loadSiteApp(a._instance,l,(f=>{if(f)return Zr.error("Error while initializing PostHog app with config id "+c,f)}))};for(var{id:s,url:l}of e.siteApps)o(s)}else Zr.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}},KA=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&nC(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>nC(r?.brand,e))))return!0}catch{}return!!t.webdriver},yc=(function(t){return t.US="us",t.EU="eu",t.CUSTOM="custom",t})({}),VC="i.posthog.com",by=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,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+VC,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.er[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.er[this.apiHost]=yc.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.er[this.apiHost]=yc.EU:this.er[this.apiHost]=yc.CUSTOM),this.er[this.apiHost]}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(this.region===yc.CUSTOM)return this.apiHost+n;var i=VC+n;switch(e){case"assets":return"https://"+this.region+"-assets."+i;case"api":return"https://"+this.region+"."+i}}},JL={icontains:(t,e)=>!!R&&e.href.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>!!R&&e.href.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>!!R&&zf(e.href,t),not_regex:(t,e)=>!!R&&!zf(e.href,t),exact:(t,e)=>e.href===t,is_not:(t,e)=>e.href!==t},_y=class t{constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{t.rr("retrieved web experiments from the server"),n.sr=new Map,r.forEach((a=>{if(a.feature_flag_key){var o;n.sr&&(t.rr("setting flag key ",a.feature_flag_key," to web experiment ",a),(o=n.sr)==null||o.set(a.feature_flag_key,a));var s=n._instance.getFeatureFlag(a.feature_flag_key);ot(s)&&a.variants[s]&&n.nr(a.name,s,a.variants[s].transforms)}else if(a.variants)for(var l in a.variants){var c=a.variants[l];t.ar(c)&&n.nr(a.name,l,c.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}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(Ee(this.sr))return this.sr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();t.rr("applying feature flags",e),e.forEach((n=>{var i;if(this.sr&&(i=this.sr)!=null&&i.has(n)){var r,a=this._instance.getFeatureFlag(n),o=(r=this.sr)==null?void 0:r.get(n);a&&o!=null&&o.variants[a]&&this.nr(o.name,a,o.variants[a].transforms)}}))}}previewWebExperiment(){var e=t.getWindowLocation();if(e!=null&&e.search){var n=Of(e?.search,"__experiment_id"),i=Of(e?.search,"__experiment_variant");n&&i&&(t.rr("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.lr(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this._instance.config.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:a=>{if(a.statusCode!==200||!a.json)return e([]);var o=a.json.experiments||[];return e(o)}})}lr(e,n,i){var r=i.filter((a=>a.id===e));r&&r.length>0&&(t.rr("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.nr(r[0].name,n,r[0].variants[n].transforms))}static ar(e){return!Ee(e.conditions)&&t.ur(e)&&t.hr(e)}static ur(e){var n;if(Ee(e.conditions)||Ee((n=e.conditions)==null?void 0:n.url))return!0;var i,r,a,o=t.getWindowLocation();return!!o&&((i=e.conditions)==null||!i.url||JL[(r=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&r!==void 0?r:"icontains"](e.conditions.url,o))}static getWindowLocation(){return R?.location}static hr(e){var n;if(Ee(e.conditions)||Ee((n=e.conditions)==null?void 0:n.utm))return!0;var i=IA();if(i.utm_source){var r,a,o,s,l,c,u,f,h=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_campaign)==i.utm_campaign,g=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_source)==i.utm_source,_=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((c=e.conditions)==null||(c=c.utm)==null?void 0:c.utm_medium)==i.utm_medium,b=(u=e.conditions)==null||(u=u.utm)==null||!u.utm_term||((f=e.conditions)==null||(f=f.utm)==null?void 0:f.utm_term)==i.utm_term;return h&&_&&b&&g}return!1}static rr(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];$.info("[WebExperiments] "+e,i)}nr(e,n,i){this._is_bot()?t.rr("Refusing to render web experiment since the viewer is a likely bot"):n!=="control"?i.forEach((r=>{if(r.selector){var a;t.rr("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(a=document)==null?void 0:a.querySelectorAll(r.selector);o?.forEach((s=>{var l=s;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):t.rr("Control variants leave the page unmodified.")}_is_bot(){return un&&this._instance?KA(un,this._instance.config.custom_blocked_useragents):void 0}},e3=st("[PostHog ExternalIntegrations]"),t3={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},Sy=class{constructor(e){this._instance=e}it(e,n){var i;(i=X.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return e3.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(o){var s,l,c;!r||(s=X.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[o]||e.it(t3[o],(()=>{var u;(u=X.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[o])==null||u.start(e._instance)})),!r&&(l=X.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[o]&&((c=X.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[o])==null||c.stop())};for(var[i,r]of Object.entries((a=this._instance.config.integrations)!==null&&a!==void 0?a:{})){var a;n(i)}}},xy="[SessionRecording]",dc=st(xy),Uf=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 dc.error("started without valid sessionManager"),new Error(xy+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(xy+' cannot be used with cookieless_mode="always"')}get cr(){var e,n=!((e=this._instance.get_property(nv))==null||!e.enabled),i=!this._instance.config.disable_session_recording,r=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return R&&n&&i&&!r}startIfEnabledOrStop(e){var n;if(!this.cr||(n=this.vr)==null||!n.isStarted){var i=!I(Object.assign)&&!I(Array.from);this.cr&&i?(this.gr(e),dc.info("starting")):this.stopRecording()}}gr(e){var n,i,r;this.cr&&(X!=null&&(n=X.__PosthogExtensions__)!=null&&(n=n.rrweb)!=null&&n.record&&(i=X.__PosthogExtensions__)!=null&&i.initSessionRecording?this._r(e):(r=X.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.mr,(a=>{if(a)return dc.error("could not load recorder",a);this._r(e)})))}stopRecording(){var e,n;(e=this.pr)==null||e.call(this),this.pr=void 0,(n=this.vr)==null||n.stop()}yr(){var e;(e=this._instance.persistence)==null||e.unregister(iA)}br(e){if(this._instance.persistence){var n,i,r=this._instance.persistence,a=()=>{var o=e.sessionRecording===!1?void 0:e.sessionRecording,s=o?.sampleRate,l=Ee(s)?null:parseFloat(s);Ee(l)&&this.yr();var c=o?.minimumDurationMilliseconds;r.register({[nv]:j({enabled:!!o},o,{networkPayloadCapture:j({capturePerformance:e.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:l,minimumDurationMilliseconds:I(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers})})};a(),(n=this.pr)==null||n.call(this),this.pr=(i=this._instance.sessionManager)==null?void 0:i.onSessionId(a)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.br(e),this.dr=!0,this.startIfEnabledOrStop()):this.dr=!0:dc.info("skipping remote config with no sessionRecording",e)}log(e,n){var i;n===void 0&&(n="log"),(i=this.vr)!=null&&i.log?this.vr.log(e,n):dc.warn("log called before recorder was ready")}get mr(){var e,n,i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(nv);return(i==null||(n=i.scriptConfig)==null?void 0:n.script)||"lazy-recorder"}_r(e){var n,i;if((n=X.__PosthogExtensions__)==null||!n.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.vr||(this.vr=(i=X.__PosthogExtensions__)==null?void 0:i.initSessionRecording(this._instance),this.vr._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.vr.start(e)}onRRwebEmit(e){var n;(n=this.vr)==null||n.onRRwebEmit==null||n.onRRwebEmit(e)}overrideLinkedFlag(){var e,n;this.vr||(n=this._instance.persistence)==null||n.register({$replay_override_linked_flag:!0}),(e=this.vr)==null||e.overrideLinkedFlag()}overrideSampling(){var e,n;this.vr||(n=this._instance.persistence)==null||n.register({$replay_override_sampling:!0}),(e=this.vr)==null||e.overrideSampling()}overrideTrigger(e){var n,i;this.vr||(i=this._instance.persistence)==null||i.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(n=this.vr)==null||n.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.vr)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,n){var i;return!((i=this.vr)==null||!i.tryAddCustomEvent(e,n))}},Sc={},wy=()=>{},Ss="posthog",XA=!jL&&Gt?.indexOf("MSIE")===-1&&Gt?.indexOf("Mozilla")===-1,jC=t=>{var e;return j({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:W4(B?.location),persistence:"localStorage+cookie",persistence_name:"",loaded:wy,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:Zt&&ot(Zt?.search)&&Zt.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:(R==null||(e=R.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:n=>{var i="Bad HTTP status: "+n.statusCode+" "+n.text;$.error(i)},get_device_id:n=>n,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:hy},error_tracking:{},_onCapture:wy,__preview_eager_load_replay:!1},(n=>({rageclick:!(n&&n>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(n&&n>="2025-05-24")||"history_change",session_recording:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{}}))(t))},qC=t=>{var e={};I(t.process_person)||(e.person_profiles=t.process_person),I(t.xhr_headers)||(e.request_headers=t.xhr_headers),I(t.cookie_name)||(e.persistence_name=t.cookie_name),I(t.disable_cookie)||(e.disable_persistence=t.disable_cookie),I(t.store_google)||(e.save_campaign_params=t.store_google),I(t.verbose)||(e.debug=t.verbose);var n=Ye({},e,t);return Ae(t.property_blacklist)&&(I(t.property_denylist)?n.property_denylist=t.property_blacklist:Ae(t.property_denylist)?n.property_denylist=[...t.property_blacklist,...t.property_denylist]:$.error("Invalid value for property_denylist config: "+t.property_denylist)),n},Ey=class{constructor(){this.__forceAllowLocalhost=!1}get wr(){return this.__forceAllowLocalhost}set wr(e){$.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},Ff=class t{get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new Ey,this.Sr=!1,this.version=Pi.LIB_VERSION,this.Er=new Tc,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=jC(),this.SentryIntegration=Zv,this.sentryIntegration=e=>(function(n,i){var r=bA(n,i);return{name:yA,processEvent:a=>r(a)}})(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 sy(this),this.toolbar=new Yv(this),this.scrollManager=new vy(this),this.pageViewManager=new ty(this),this.surveys=new dy(this),this.experiments=new _y(this),this.exceptions=new oy(this),this.rateLimiter=new fy(this),this.requestRouter=new by(this),this.consent=new qv(this),this.externalIntegrations=new Sy(this),this.people={set:(e,n,i)=>{var r=ot(e)?{[e]:n}:e;this.setPersonProperties(r),i?.({})},set_once:(e,n,i)=>{var r=ot(e)?{[e]:n}:e;this.setPersonProperties(void 0,r),i?.({})}},this.on("eventCaptured",(e=>$.info('send "'+e?.event+'"',e)))}init(e,n,i){if(i&&i!==Ss){var r,a=(r=Sc[i])!==null&&r!==void 0?r:new t;return a._init(e,n,i),Sc[i]=a,Sc[Ss][i]=a,a}return this._init(e,n,i)}_init(e,n,i){var r;if(n===void 0&&(n={}),I(e)||yv(e))return $.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},n.debug=this.Rr(n.debug),this.Ir=n,this.Fr=[],n.person_profiles&&(this.Pr=n.person_profiles),this.set_config(Ye({},jC(n.defaults),qC(n),{name:i,token:e})),this.config.on_xhr_error&&$.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Yi.GZipJS;var a=this.Cr();this.persistence=new _c(this.config,a),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new _c(j({},this.config,{persistence:"sessionStorage"}),a);var o=j({},this.persistence.props),s=j({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Mr=new gy((p=>this.Or(p)),this.config.request_queue_config),this.Ar=new my(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 $f(this),this.sessionPropsManager=new Bf(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?($.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Dr(l)}),0)):($.info("Initializing extensions synchronously"),this.Dr(l)),Pi.DEBUG=Pi.DEBUG||this.config.debug,Pi.DEBUG&&$.info("Starting in debug mode",{this:this,config:n,thisC:j({},this.config),p:o,s}),((r=n.bootstrap)==null?void 0:r.distinctID)!==void 0){var c,u,f=this.config.get_device_id(Wr()),h=(c=n.bootstrap)!=null&&c.isIdentifiedID?f:n.bootstrap.distinctID;this.persistence.set_property(Gi,(u=n.bootstrap)!=null&&u.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:n.bootstrap.distinctID,$device_id:h})}if(this.jr()){var g,_,b=Object.keys(((g=n.bootstrap)==null?void 0:g.featureFlags)||{}).filter((p=>{var m;return!((m=n.bootstrap)==null||(m=m.featureFlags)==null||!m[p])})).reduce(((p,m)=>{var v;return p[m]=((v=n.bootstrap)==null||(v=v.featureFlags)==null?void 0:v[m])||!1,p}),{}),w=Object.keys(((_=n.bootstrap)==null?void 0:_.featureFlagPayloads)||{}).filter((p=>b[p])).reduce(((p,m)=>{var v,S;return(v=n.bootstrap)!=null&&(v=v.featureFlagPayloads)!=null&&v[m]&&(p[m]=(S=n.bootstrap)==null||(S=S.featureFlagPayloads)==null?void 0:S[m]),p}),{});this.featureFlags.receivedFeatureFlags({featureFlags:b,featureFlagPayloads:w})}if(l)this.register_once({distinct_id:ic,$device_id:null},"");else if(!this.get_distinct_id()){var d=this.config.get_device_id(Wr());this.register_once({distinct_id:d,$device_id:d},""),this.persistence.set_property(Gi,"anonymous")}return tt(R,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),n.segment?vL(this,(()=>this.Lr())):this.Lr(),Kr(this.config._onCapture)&&this.config._onCapture!==wy&&($.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(p=>this.config._onCapture(p.event,p)))),this.config.ip&&$.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this}Dr(e){var n=performance.now();this.historyAutocapture=new Gv(this),this.historyAutocapture.startIfEnabled();var i=[];i.push((()=>{new Wv(this).startIfEnabledOrStop()})),i.push((()=>{var r;this.siteApps=new yy(this),(r=this.siteApps)==null||r.init()})),e||i.push((()=>{this.sessionRecording=new Uf(this),this.sessionRecording.startIfEnabledOrStop()})),this.config.disable_scroll_properties||i.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),i.push((()=>{this.autocapture=new Uv(this),this.autocapture.startIfEnabled()})),i.push((()=>{this.surveys.loadIfEnabled()})),i.push((()=>{this.heatmaps=new ey(this),this.heatmaps.startIfEnabled()})),i.push((()=>{this.webVitalsAutocapture=new Jv(this)})),i.push((()=>{this.exceptionObserver=new Pv(this),this.exceptionObserver.startIfEnabled()})),i.push((()=>{this.deadClicksAutocapture=new Nf(this,mL),this.deadClicksAutocapture.startIfEnabled()})),i.push((()=>{if(this.Nr){var r=this.Nr;this.Nr=void 0,this.fi(r)}})),this.Ur(i,n)}Ur(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.Ur(e,n)}),0);var i=e.shift();if(i)try{i()}catch(a){$.error("Error initializing extension:",a)}}var r=Math.round(performance.now()-n);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:r}),this.config.__preview_deferred_init_extensions&&$.info("PostHog extensions initialized ("+r+"ms)")}fi(e){var n,i,r,a,o,s,l,c;if(!B||!B.body)return $.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=ce(e.supportedCompression,Yi.GZipJS)?Yi.GZipJS:ce(e.supportedCompression,Yi.Base64)?Yi.Base64:void 0),(n=e.analytics)!=null&&n.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Pr?this.Pr:"identified_only"}),(i=this.siteApps)==null||i.onRemoteConfig(e),(r=this.sessionRecording)==null||r.onRemoteConfig(e),(a=this.autocapture)==null||a.onRemoteConfig(e),(o=this.heatmaps)==null||o.onRemoteConfig(e),this.surveys.onRemoteConfig(e),(s=this.webVitalsAutocapture)==null||s.onRemoteConfig(e),(l=this.exceptionObserver)==null||l.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(c=this.deadClicksAutocapture)==null||c.onRemoteConfig(e)}Lr(){try{this.config.loaded(this)}catch(e){$.critical("`loaded` function failed",e)}this.zr(),this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.Hr()}),1),new py(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()&&Qr(this.__request_queue,(e=>this.Or(e))),this.__request_queue=[],this.zr()}_handle_unload(){var e,n;this.config.request_batching?(this.Br()&&this.capture("$pageleave"),(e=this.Mr)==null||e.unload(),(n=this.Ar)==null||n.unload()):this.Br()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}ci(e){this.__loaded&&(XA?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=If(e.url,{ip:this.config.ip?1:0}),e.headers=j({},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,(n=>{var i,r,a,o=j({},n);o.timeout=o.timeout||6e4,o.url=If(o.url,{_:new Date().getTime().toString(),ver:Pi.LIB_VERSION,compression:o.compression});var s=(i=o.transport)!==null&&i!==void 0?i:"fetch",l=bf.filter((u=>!o.disableTransport||!u.transport||!o.disableTransport.includes(u.transport))),c=(r=(a=eA(l,(u=>u.transport===s)))==null?void 0:a.method)!==null&&r!==void 0?r:l[0].method;if(!c)throw new Error("No available transport method");c(o)})(j({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),n.statusCode>=400&&((i=(r=this.config).on_request_error)==null||i.call(r,n)),e.callback==null||e.callback(n)}}))))}Or(e){this.Ar?this.Ar.retriableRequest(e):this.ci(e)}_execute_array(e){var n,i=[],r=[],a=[];Qr(e,(s=>{s&&(n=s[0],Ae(n)?a.push(s):Kr(s)?s.call(this):Ae(s)&&n==="alias"?i.push(s):Ae(s)&&n.indexOf("capture")!==-1&&Kr(this[n])?a.push(s):r.push(s))}));var o=function(s,l){Qr(s,(function(c){if(Ae(c[0])){var u=l;Re(c,(function(f){u=u[f[0]].apply(u,f.slice(1))}))}else this[c[0]].apply(this,c.slice(1))}),l)};o(i,this),o(r,this),o(a,this)}jr(){var e,n;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((n=this.config.bootstrap)==null?void 0:n.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,n,i){var r;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Mr){if(this.is_capturing())if(!I(e)&&ot(e)){var a=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(a&&!this.config.__preview_capture_bot_pageviews)){var o=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(o==null||!o.isRateLimited){n!=null&&n.$current_url&&!ot(n?.$current_url)&&($.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$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=i?.timestamp||s,c=Wr(),u={uuid:c,event:e,properties:this.calculateEventProperties(e,n||{},l,c)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&a&&(u.event="$bot_pageview",u.properties.$browser_type="bot"),o&&(u.properties.$lib_rate_limit_remaining_tokens=o.remainingTokens),i?.$set&&(u.$set=i?.$set);var f,h=this.qr(i?.$set_once);if(h&&(u.$set_once=h),(u=Z4(u,i!=null&&i._noTruncate?null:this.config.properties_string_max_length)).timestamp=l,I(i?.timestamp)||(u.properties.$event_time_override_provided=!0,u.properties.$event_time_override_system_time=s),e===_f.DISMISSED||e===_f.SENT){var g=n?.[$C.SURVEY_ID],_=n?.[$C.SURVEY_ITERATION];f={id:g,current_iteration:_},localStorage.getItem(UC(f))||localStorage.setItem(UC(f),"true"),u.$set=j({},u.$set,{[ZL({id:g,current_iteration:_},e===_f.SENT?"responded":"dismissed")]:!0})}var b=j({},u.properties.$set,u.$set);if(xs(b)||this.setPersonPropertiesForFlags(b),!Ee(this.config.before_send)){var w=this.Wr(u);if(!w)return;u=w}this.Er.emit("eventCaptured",u);var d={method:"POST",url:(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:u,compression:"best-available",batchKey:i?._batchKey};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Or(d):this.Mr.enqueue(d),u}$.critical("This capture call is ignored due to client rate limiting.")}}else $.error("No event name provided to posthog.capture")}else $.uninitializedWarning("posthog.capture")}Ai(e){return this.on("eventCaptured",(n=>e(n.event,n)))}calculateEventProperties(e,n,i,r,a){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=a?void 0:this.persistence.remove_event_timer(e),s=j({},n);if(s.token=this.config.token,s.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(s.$cookieless_mode=!0),e==="$snapshot"){var l=j({},this.persistence.properties(),this.sessionPersistence.properties());return s.distinct_id=l.distinct_id,(!ot(s.distinct_id)&&!ui(s.distinct_id)||yv(s.distinct_id))&&$.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),s}var c,u=DL(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:f,windowId:h}=this.sessionManager.checkAndGetSessionAndWindowId(a,i.getTime());s.$session_id=f,s.$window_id=h}this.sessionPropsManager&&Ye(s,this.sessionPropsManager.getSessionProps());try{var g;this.sessionRecording&&Ye(s,this.sessionRecording.sdkDebugProperties),s.$sdk_debug_retry_queue_size=(g=this.Ar)==null?void 0:g.length}catch(d){s.$sdk_debug_error_capturing_properties=String(d)}if(this.requestRouter.region===yc.CUSTOM&&(s.$lib_custom_api_host=this.config.api_host),c=e!=="$pageview"||a?e!=="$pageleave"||a?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),s=Ye(s,c),e==="$pageview"&&B&&(s.title=B.title),!I(o)){var _=i.getTime()-o;s.$duration=parseFloat((_/1e3).toFixed(3))}Gt&&this.config.opt_out_useragent_filter&&(s.$browser_type=this._is_bot()?"bot":"browser"),(s=Ye({},u,this.persistence.properties(),this.sessionPersistence.properties(),s)).$is_identified=this._isIdentified(),Ae(this.config.property_denylist)?Re(this.config.property_denylist,(function(d){delete s[d]})):$.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&&($.error("sanitize_properties is deprecated. Use before_send instead"),s=b(s,e));var w=this.Gr();return s.$process_person_profile=w,w&&!a&&this.Vr("_calculate_event_properties"),s}qr(e){var n;if(!this.persistence||!this.Gr()||this.Sr)return e;var i=this.persistence.get_initial_props(),r=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),a=Ye({},i,r||{},e||{}),o=this.config.sanitize_properties;return o&&($.error("sanitize_properties is deprecated. Use before_send instead"),a=o(a,"$set_once")),this.Sr=!0,xs(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e)}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e)}Jr(e,n){this.register({[e]:n})}getFeatureFlag(e,n){return this.featureFlags.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n=this.featureFlags.getFeatureFlagPayload(e);try{return JSON.parse(n)}catch{return n}}isFeatureEnabled(e,n){return this.featureFlags.isFeatureEnabled(e,n)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateEarlyAccessFeatureEnrollment(e,n,i){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){return n===void 0&&(n=!1),this.featureFlags.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.Er.on(e,n)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys.getSurveys(e,n)}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys.getActiveMatchingSurveys(e,n)}renderSurvey(e,n){this.surveys.renderSurvey(e,n)}displaySurvey(e,n){n===void 0&&(n=WL),this.surveys.displaySurvey(e,n)}cancelPendingSurvey(e){this.surveys.cancelPendingSurvey(e)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,n){return n===void 0&&(n=!1),this.surveys.canRenderSurveyAsync(e,n)}identify(e,n,i){if(!this.__loaded||!this.persistence)return $.uninitializedWarning("posthog.identify");if(ui(e)&&(e=e.toString(),$.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))$.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(e!==ic){if(this.Vr("posthog.identify")){var r=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var a=r;this.register_once({$had_persisted_distinct_id:!0,$device_id:a},"")}e!==r&&e!==this.get_property(fc)&&(this.unregister(fc),this.register({distinct_id:e}));var o=(this.persistence.get_property(Gi)||"anonymous")==="anonymous";e!==r&&o?(this.persistence.set_property(Gi,"identified"),this.setPersonPropertiesForFlags(j({},i||{},n||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Tr=LC(e,n,i),this.featureFlags.setAnonymousDistinctId(r)):(n||i)&&this.setPersonProperties(n,i),e!==r&&(this.reloadFeatureFlags(),this.unregister(Ef))}}else $.critical('The string "'+ic+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else $.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,n){if((e||n)&&this.Vr("posthog.setPersonProperties")){var i=LC(this.get_distinct_id(),e,n);this.Tr!==i?(this.setPersonPropertiesForFlags(j({},n||{},e||{})),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Tr=i):$.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,n,i){if(e&&n){if(this.Vr("posthog.group")){var r=this.getGroups();r[e]!==n&&this.resetGroupPropertiesForFlags(e),this.register({$groups:j({},r,{[e]:n})}),i&&(this.capture("$groupidentify",{$group_type:e,$group_key:n,$group_set:i}),this.setGroupPropertiesForFlags({[e]:i})),r[e]===n||i||this.reloadFeatureFlags()}}else $.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){n===void 0&&(n=!0),this.featureFlags.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,n){n===void 0&&(n=!0),this.Vr("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,n)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var n,i,r,a;if($.info("reset"),!this.__loaded)return $.uninitializedWarning("posthog.reset");var o=this.get_property("$device_id");if(this.consent.reset(),(n=this.persistence)==null||n.clear(),(i=this.sessionPersistence)==null||i.clear(),this.surveys.reset(),this.featureFlags.reset(),(r=this.persistence)==null||r.set_property(Gi,"anonymous"),(a=this.sessionManager)==null||a.resetSessionId(),this.Tr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:ic,$device_id:null},"");else{var s=this.config.get_device_id(Wr());this.register_once({distinct_id:s,$device_id:e?s:o},"")}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,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:n,sessionStartTimestamp:i}=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n);if(e!=null&&e.withTimestamp&&i){var a,o=(a=e.timestampLookBack)!==null&&a!==void 0?a:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(tA)?($.critical("Attempting to create alias for existing People user - aborting."),-2):this.Vr("posthog.alias")?(I(n)&&(n=this.get_distinct_id()),e!==n?(this.Jr(fc,e),this.capture("$create_alias",{alias:e,distinct_id:n})):($.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=j({},this.config);if(ft(e)){var i,r,a,o,s;Ye(this.config,qC(e));var l=this.Cr();(i=this.persistence)==null||i.update_config(this.config,n,l),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new _c(j({},this.config,{persistence:"sessionStorage"}),l);var c=this.Rr(this.config.debug);Xr(c)&&(this.config.debug=c),Xr(this.config.debug)&&(this.config.debug?(Pi.DEBUG=!0,Fe.H()&&Fe.G("ph_debug","true"),$.info("set_config",{config:e,oldConfig:n,newConfig:j({},this.config)})):(Pi.DEBUG=!1,Fe.H()&&Fe.V("ph_debug"))),(r=this.sessionRecording)==null||r.startIfEnabledOrStop(),(a=this.autocapture)==null||a.startIfEnabled(),(o=this.heatmaps)==null||o.startIfEnabled(),this.surveys.loadIfEnabled(),this.Kr(),(s=this.externalIntegrations)==null||s.startIfEnabledOrStop()}}startSessionRecording(e){var n=e===!0,i={sampling:n||!(e==null||!e.sampling),linked_flag:n||!(e==null||!e.linked_flag),url_trigger:n||!(e==null||!e.url_trigger),event_trigger:n||!(e==null||!e.event_trigger)};if(Object.values(i).some(Boolean)){var r,a,o,s,l;(r=this.sessionManager)==null||r.checkAndGetSessionAndWindowId(),i.sampling&&((a=this.sessionRecording)==null||a.overrideSampling()),i.linked_flag&&((o=this.sessionRecording)==null||o.overrideLinkedFlag()),i.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),i.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,n){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(j({},r,n))}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Ss;return n!==Ss&&(n=Ss+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(Gi))==="identified"||((n=this.sessionPersistence)==null?void 0:n.get_property(Gi))==="identified"}Gr(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&xs(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[fc])&&((n=this.persistence)==null||(n=n.props)==null||!n[Af]))}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"?($.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Jr(Af,!0),!0)}Cr(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),n=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!n}Kr(){var e,n,i,r,a=this.Cr();return((e=this.persistence)==null?void 0:e.wi)!==a&&((i=this.persistence)==null||i.set_disabled(a)),((n=this.sessionPersistence)==null?void 0:n.wi)!==a&&((r=this.sessionPersistence)==null||r.set_disabled(a)),a}opt_in_capturing(e){var n;if(this.config.cookieless_mode!=="always"){var i,r;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(i=this.sessionManager)==null||i.destroy(),this.sessionManager=new $f(this),this.persistence&&(this.sessionPropsManager=new Bf(this,this.sessionManager,this.persistence)),this.sessionRecording=new Uf(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this.Kr(),this.zr(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(I(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((r=e?.captureEventName)!==null&&r!==void 0?r:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hr()}else $.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,n;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:ic,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(n=this.sessionRecording)==null||n.stopRecording(),this.sessionRecording=void 0,this.Hr())):$.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===Zi.GRANTED?"granted":e===Zi.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 un?KA(un,this.config.custom_blocked_useragents):void 0}Hr(){B&&(B.visibilityState==="visible"?this.$r||(this.$r=!0,this.capture("$pageview",{title:B.title},{send_instantly:!0}),this.kr&&(B.removeEventListener("visibilitychange",this.kr),this.kr=null)):this.kr||(this.kr=this.Hr.bind(this),tt(B,"visibilitychange",this.kr)))}debug(e){e===!1?(R?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(R?.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,n,i,r,a,o,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?($.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):(i="advanced_disable_decide",r=!1,a=$,o=(n="advanced_disable_flags")in(e=l)&&!I(e[n]),s=i in e&&!I(e[i]),o?e[n]:s?(a&&a.warn("Config field '"+i+"' is deprecated. Please use '"+n+"' instead. The old field will be removed in a future major version."),e[i]):r)}Wr(e){if(Ee(this.config.before_send))return e;var n=Ae(this.config.before_send)?this.config.before_send:[this.config.before_send],i=e;for(var r of n){if(i=r(i),Ee(i)){var a="Event '"+e.event+"' was rejected in beforeSend function";return O4(e.event)?$.warn(a+". This can cause unexpected behavior."):$.info(a),null}i.properties&&!xs(i.properties)||$.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return i}getPageViewId(){var e;return(e=this.pageViewManager.Vt)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Rr(e){var n=Xr(e)&&!e,i=Fe.H()&&Fe.q("ph_debug")==="true";return!n&&(!!i||e)}};(function(t,e){for(var n=0;n<e.length;n++)t.prototype[e[n]]=G4(t.prototype[e[n]])})(Ff,["identify"]);var PC,QA=(PC=Sc[Ss]=new Ff,(function(){function t(){t.done||(t.done=!0,XA=!1,Re(Sc,(function(e){e._dom_loaded()})))}B!=null&&B.addEventListener?B.readyState==="complete"?t():tt(B,"DOMContentLoaded",t,{capture:!1}):R&&$.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),PC);var Hy=class{constructor(e={}){this.options=e;V(this,"client");V(this,"featureFlagsCallback");V(this,"captureCallback");V(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 n=e.consent;n.getStatus()==="granted"&&this.initPostHog(),this.consentUnsub=n.subscribe(r=>{r==="granted"?this.client?this.client.opt_in_capturing():this.initPostHog():r==="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 n=e.enableFeatureFlags??!0,i=`syntro_${e.apiKey.slice(-6)||"sdk"}`;this.client=QA.init(e.apiKey,{api_host:e.apiHost??"https://telemetry.syntrologie.com",advanced_disable_feature_flags:!n,advanced_disable_feature_flags_on_first_load:!n,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:r=>{if(n&&this.featureFlagsCallback){r.onFeatureFlags(()=>{let o=this.getAllFeatureFlags();o&&this.featureFlagsCallback&&this.featureFlagsCallback(o)});let a=this.getAllFeatureFlags();a&&Object.keys(a).length>0&&this.featureFlagsCallback(a)}this.captureCallback&&r.on("eventCaptured",a=>{let o=typeof a=="string"?a:a?.event,s=typeof a=="string"?void 0:a?.properties;typeof o=="string"&&this.captureCallback?.(o,s)})}},i)}getAllFeatureFlags(){return this.client?.featureFlags?.getFlagVariants?.()}getSegmentFlags(){let e=this.getAllFeatureFlags();if(!e)return{};let n={};for(let[i,r]of Object.entries(e))i.startsWith("in_segment_")&&(n[i]=r===!0);return n}identify(e,n){this.client?.identify(e,n)}alias(e,n){this.client?.alias(e,n)}track(e,n){this.client?.capture(e,n)}trackCanvasOpened(e){this.track("shadow_canvas_opened",{surface:e})}trackCanvasClosed(e){this.track("shadow_canvas_closed",{surface:e})}trackRectangleViewed(e,n){this.track("shadow_canvas_rectangle_viewed",{rectangleId:e,surface:n})}trackAction(e,n,i){this.track("shadow_canvas_action",{action:e,rectangleId:n,surface:i})}register(e){this.client?.register?.(e)}getSessionId(){return this.client?.get_session_id?.()}startSessionRecording(){this.client?.startSessionRecording?.()}trackExperiment(e,n,i){let r=`$experiment_${e}`;this.register({[r]:i??`variation_${n}`,[`${r}_id`]:n}),this.track("$experiment_started",{$experiment_key:e,$experiment_variation_id:n,$experiment_variation_name:i??`variation_${n}`})}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 Iy(t={}){return new Hy(t)}var zy=async(t,e)=>{let n=[];if(e.applyAction)for(let i of t.actions){let r=await e.applyAction(i);n.push(r)}return{cleanup:async()=>{for(let i=n.length-1;i>=0;i--)try{await n[i].revert()}catch{}}}},By=async(t,e)=>{let n=[];if(e.applyAction){let i=t.actions.map(r=>e.applyAction(r));if(t.waitFor==="any"){let r=await Promise.race(i);n.push(r);let a=await Promise.allSettled(i);for(let o of a)o.status==="fulfilled"&&o.value!==r&&n.push(o.value)}else{let r=await Promise.all(i);n.push(...r)}}return{cleanup:async()=>{for(let i of n)try{await i.revert()}catch{}}}},$y=async(t,e)=>{let n,i,r=!1,a={cleanup:()=>{r=!0,i&&clearTimeout(i),n&&n()}};return t.event&&e.subscribeEvent?await new Promise(o=>{n=e.subscribeEvent(t.event,()=>{r||o()}),t.durationMs!==void 0&&(i=setTimeout(()=>{r||o()},t.durationMs))}):t.durationMs!==void 0&&await new Promise(o=>{i=setTimeout(()=>{r||o()},t.durationMs)}),a};var Fy="syntro_active_tour",Pf=new Map;function n3(t){try{let e=localStorage.getItem(Fy);if(!e)return null;let n=JSON.parse(e);return n.tourId!==t?null:n}catch{return null}}function Uy(t){try{localStorage.setItem(Fy,JSON.stringify(t))}catch{}}function i3(){try{localStorage.removeItem(Fy)}catch{}}function Mc(){return window.location.pathname}function r3(t){if(!t.route)return!0;let e=Mc();return t.route.includes("*")?new RegExp(`^${t.route.replace(/\*/g,".*")}$`).test(e):e===t.route}var Vy=async(t,e)=>{let{tourId:n,steps:i,startStep:r,autoStart:a=!0}=t;if(i.length===0)throw new Error(`Tour "${n}" has no steps`);if(Pf.has(n))return{cleanup:async()=>{let m=Pf.get(n);m&&await m.cleanup()}};if(!e.applyAction)throw new Error("Tour executor requires applyAction in context");let o=n3(n),s=!!o;if(!s&&!a)return{cleanup:()=>{}};o||(o={tourId:n,currentStepId:r||i[0].id,startedAt:Date.now()},Uy(o));let l=i.findIndex(m=>m.id===o.currentStepId);if(l===-1){let m=r||i[0].id;l=i.findIndex(v=>v.id===m),l===-1&&(l=0),o.currentStepId=i[l].id,Uy(o)}let c=i[l];if(!r3(c))return e.publishEvent("tour.waiting_for_route",{tourId:n,stepId:c.id,expectedRoute:c.route,currentRoute:Mc()}),{cleanup:()=>{}};let u=!1,f=null,h=null,g=null,_=async()=>{h&&(h(),h=null),f?.isApplied()&&(await f.revert(),f=null)},b=async m=>{if(u)return;if(await _(),m==="end"){i3(),e.publishEvent("tour.completed",{tourId:n,totalSteps:i.length}),u=!0;return}let v=i.find(S=>S.id===m);if(!v){console.error(`[Tour] Step "${m}" not found`);return}if(o.currentStepId=m,Uy(o),e.publishEvent("tour.step_changed",{tourId:n,previousStepId:c.id,nextStepId:m}),v.route&&v.route!==Mc()){e.publishEvent("tour.awaiting_navigation",{tourId:n,stepId:m,targetRoute:v.route});return}await w(v)},w=async m=>{if(!u){e.publishEvent("tour.step_started",{tourId:n,stepId:m.id,stepIndex:i.findIndex(v=>v.id===m.id),totalSteps:i.length});try{f=await e.applyAction(m.action)}catch(v){console.error(`[Tour] Failed to execute step "${m.id}":`,v),e.publishEvent("tour.step_failed",{tourId:n,stepId:m.id,error:String(v)});return}if(m.onAction&&e.subscribeEvent){h=e.subscribeEvent("action.modal_cta_clicked",T=>{let A=T?.actionId;if(A&&m.onAction){let k=m.onAction[A];k&&b(k)}});let v=e.subscribeEvent("action.tooltip_cta_clicked",T=>{let A=T?.actionId;if(A&&m.onAction){let k=m.onAction[A];k&&b(k)}}),S=h;h=()=>{S(),v()}}}};g=(()=>{let m=Mc(),v=()=>{let A=Mc();A!==m&&(m=A,e.publishEvent("tour.route_changed",{tourId:n,newRoute:A}))};if(e.subscribeNavigation)return e.subscribeNavigation(()=>v());window.addEventListener("popstate",v);let S=history.pushState.bind(history),T=history.replaceState.bind(history);return history.pushState=(...A)=>{S(...A),queueMicrotask(v)},history.replaceState=(...A)=>{T(...A),queueMicrotask(v)},()=>{window.removeEventListener("popstate",v),history.pushState=S,history.replaceState=T}})(),s?e.publishEvent("tour.resumed",{tourId:n,stepId:o.currentStepId}):e.publishEvent("tour.started",{tourId:n,totalSteps:i.length,startStepId:o.currentStepId}),await w(c);let p=async()=>{u=!0,Pf.delete(n),await _(),g&&g(),e.publishEvent("tour.paused",{tourId:n,stepId:o.currentStepId})};return Pf.set(n,{cleanup:p}),{cleanup:p}};var Gf=class{constructor(){V(this,"executors",new Map);for(let{kind:e,executor:n}of qg)this.registerCore(e,n);for(let{kind:e,executor:n}of Xg)this.registerCore(e,n);this.registerCore("core:mountWidget",async()=>{throw new Error("core:mountWidget must be handled by ActionEngine")}),this.registerCore("core:sequence",zy),this.registerCore("core:parallel",By),this.registerCore("core:wait",$y),this.registerCore("core:tour",Vy)}registerCore(e,n,i){this.executors.set(e,{kind:e,executor:n,schema:i,source:"core",isBuiltIn:!0})}register(e,n,i,r="custom",a=!1){if(this.executors.has(e)){if(this.executors.get(e).isBuiltIn)return;console.warn(`[ExecutorRegistry] Overriding executor for kind: ${e} (source: ${r})`)}console.log(`[ExecutorRegistry] Registered executor: ${e} (source: ${r})`),this.executors.set(e,{kind:e,executor:n,schema:i,source:r,isBuiltIn:a})}unregister(e){let n=this.executors.get(e);return n?n.isBuiltIn?(console.warn(`[ExecutorRegistry] Cannot unregister built-in executor: ${e}`),!1):(this.executors.delete(e),!0):!1}unregisterBySource(e){for(let[n,i]of this.executors.entries())i.source===e&&this.executors.delete(n)}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 n=[];if(!e||typeof e!="object")return n.push({code:"INVALID_ACTION",message:"Action must be an object"}),{valid:!1,errors:n,warnings:[]};let{kind:i}=e;if(!i||typeof i!="string")return n.push({code:"MISSING_KIND",message:"Action must have a 'kind' property"}),{valid:!1,errors:n,warnings:[]};let r=this.executors.get(i);if(!r)return n.push({code:"UNKNOWN_KIND",message:`Unknown action kind: ${i}`,field:"kind"}),{valid:!1,errors:n,warnings:[]};if(r.schema){let a=r.schema.safeParse(e);if(!a.success){for(let o of a.error.issues)n.push({code:"SCHEMA_VALIDATION_ERROR",message:o.message,field:o.path.join(".")});return{valid:!1,errors:n,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)}},Ki=new Gf;function a3(t){return Ki.get(t)}function jy(t){return Ki.has(t)}var o3=new Set(["onclick","onerror","onload","onmouseover","onfocus","onblur","onchange","onsubmit","onkeydown","onkeyup","onkeypress"]),JA=5e4,eT=50;function ta(t){let e=[],n=[];if(!t||typeof t!="object")return e.push({code:"INVALID_ACTION",message:"Action must be an object"}),{valid:!1,errors:e,warnings:n};let{kind:i}=t;if(!i||typeof i!="string")return e.push({code:"MISSING_KIND",message:"Action must have a 'kind' property"}),{valid:!1,errors:e,warnings:n};if(!jy(i)&&i!=="core:mountWidget"){let r=Ki.list();return console.error(`[ActionValidation] Unknown action kind: "${i}". Registered kinds (${r.length}): [${r.join(", ")}]. This usually means the app that provides "${i}" hasn't been activated yet, or the executor was never registered in ExecutorRegistry.`),e.push({code:"UNKNOWN_KIND",message:`Unknown action kind: ${i}`,field:"kind"}),{valid:!1,errors:e,warnings:n}}switch(i){case"overlays:highlight":case"overlays:pulse":case"navigation:scrollTo":ea(t,e,n);break;case"overlays:badge":ea(t,e,n),s3(t,e,n);break;case"overlays:tooltip":ea(t,e,n),l3(t,e,n);break;case"overlays:modal":b3(t,e,n);break;case"content:insertHtml":ea(t,e,n),c3(t,e,n);break;case"content:setText":ea(t,e,n),u3(t,e,n);break;case"content:setAttr":ea(t,e,n),d3(t,e,n);break;case"content:addClass":case"content:removeClass":ea(t,e,n),f3(t,e,n);break;case"content:setStyle":ea(t,e,n),p3(t,e,n);break;case"core:mountWidget":h3(t,e,n);break;case"core:wait":g3(t,e,n);break;case"core:sequence":m3(t,e,n);break;case"core:parallel":v3(t,e,n);break;case"core:tour":_3(t,e,n);break;case"navigation:navigate":y3(t,e,n);break}return{valid:e.length===0,errors:e,warnings:n}}function ea(t,e,n){!t.anchorId||typeof t.anchorId!="string"?e.push({code:"MISSING_ANCHOR_ID",message:"Action requires an 'anchorId' property",field:"anchorId"}):t.anchorId.length>200&&n.push({code:"LONG_ANCHOR_ID",message:"Anchor ID is unusually long",suggestion:"Consider using a shorter, more descriptive ID"})}function s3(t,e,n){!t.content||typeof t.content!="string"?e.push({code:"MISSING_CONTENT",message:"Badge action requires 'content' property",field:"content"}):t.content.length>100&&n.push({code:"LONG_BADGE_CONTENT",message:"Badge content is quite long",suggestion:"Keep badge content short (under 100 characters)"})}function l3(t,e,n){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 c3(t,e,n){!t.html||typeof t.html!="string"?e.push({code:"MISSING_HTML",message:"insertHtml action requires 'html' property",field:"html"}):t.html.length>JA&&e.push({code:"HTML_TOO_LONG",message:`HTML content exceeds maximum length of ${JA}`,field:"html"});let i=["before","after","prepend","append","replace"];(!t.position||!i.includes(t.position))&&e.push({code:"INVALID_POSITION",message:`Position must be one of: ${i.join(", ")}`,field:"position"})}function u3(t,e,n){(t.text===void 0||t.text===null)&&e.push({code:"MISSING_TEXT",message:"setText action requires 'text' property",field:"text"})}function d3(t,e,n){!t.attr||typeof t.attr!="string"?e.push({code:"MISSING_ATTR",message:"setAttr action requires 'attr' property",field:"attr"}):(o3.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 f3(t,e,n){!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)||n.push({code:"INVALID_CLASS_NAME",message:"Class name contains unusual characters",suggestion:"Use alphanumeric characters, hyphens, and underscores"})}function p3(t,e,n){if(!t.styles||typeof t.styles!="object")e.push({code:"MISSING_STYLES",message:"setStyle action requires 'styles' object",field:"styles"});else{let i=Object.keys(t.styles).length;i>eT&&e.push({code:"TOO_MANY_STYLES",message:`Too many styles (${i}). Maximum is ${eT}`,field:"styles"});for(let[r,a]of Object.entries(t.styles))typeof a=="string"&&a.includes("expression(")&&e.push({code:"DANGEROUS_STYLE",message:`Style expressions are not allowed: ${r}`,field:`styles.${r}`})}}function h3(t,e,n){(!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 g3(t,e,n){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 m3(t,e,n){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&&n.push({code:"EMPTY_SEQUENCE",message:"sequence has no actions",suggestion:"Add at least one action to the sequence"});for(let i=0;i<t.actions.length;i++){let r=ta(t.actions[i]);for(let a of r.errors)e.push({...a,field:`actions[${i}]${a.field?`.${a.field}`:""}`});for(let a of r.warnings)n.push(a)}}function v3(t,e,n){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&&n.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 i=0;i<t.actions.length;i++){let r=ta(t.actions[i]);for(let a of r.errors)e.push({...a,field:`actions[${i}]${a.field?`.${a.field}`:""}`});for(let a of r.warnings)n.push(a)}}function y3(t,e,n){if(!t.url||typeof t.url!="string")e.push({code:"MISSING_URL",message:"navigate action requires 'url' property",field:"url"});else{let i=t.url.trim().toLowerCase();i.startsWith("javascript:")&&e.push({code:"DANGEROUS_URL",message:"javascript: URLs are not allowed",field:"url"}),i.startsWith("data:")&&n.push({code:"DATA_URL",message:"data: URLs may have limited support",suggestion:"Consider using a regular URL instead"})}}function b3(t,e,n){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 i=0;i<t.ctaButtons.length;i++){let r=t.ctaButtons[i];(!r.label||typeof r.label!="string")&&e.push({code:"MISSING_BUTTON_LABEL",message:`CTA button at index ${i} requires 'label' property`,field:`ctaButtons[${i}].label`}),(!r.actionId||typeof r.actionId!="string")&&e.push({code:"MISSING_BUTTON_ACTION_ID",message:`CTA button at index ${i} requires 'actionId' property`,field:`ctaButtons[${i}].actionId`})}}function _3(t,e,n){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 i=new Set;for(let r=0;r<t.steps.length;r++){let a=t.steps[r];if(!a.id||typeof a.id!="string"?e.push({code:"MISSING_STEP_ID",message:`Step at index ${r} requires 'id' property`,field:`steps[${r}].id`}):(i.has(a.id)&&e.push({code:"DUPLICATE_STEP_ID",message:`Duplicate step ID: ${a.id}`,field:`steps[${r}].id`}),i.add(a.id)),!a.action)e.push({code:"MISSING_STEP_ACTION",message:`Step at index ${r} requires 'action' property`,field:`steps[${r}].action`});else{let o=ta(a.action);for(let s of o.errors)e.push({...s,field:`steps[${r}].action${s.field?`.${s.field}`:""}`});for(let s of o.warnings)n.push(s)}if(a.onAction)for(let[o,s]of Object.entries(a.onAction))s!=="end"&&!t.steps.some(l=>l.id===s)&&n.push({code:"UNKNOWN_TARGET_STEP",message:`Step "${a.id}" references unknown target step: ${s}`,suggestion:`Make sure step "${s}" exists in the tour`})}}function qy(t){let e=[],n=[];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:n};for(let i=0;i<t.length;i++){let r=ta(t[i]);if(!r.valid){let a=t[i];console.error(`[ActionValidation] Action [${i}] failed validation:`,`kind="${a?.kind??"undefined"}"`,r.errors.map(o=>`${o.code}: ${o.message}`).join("; "),a)}for(let a of r.errors)e.push({...a,field:a.field?`[${i}].${a.field}`:`[${i}]`});for(let a of r.warnings)n.push({...a,suggestion:a.suggestion?`Action ${i}: ${a.suggestion}`:void 0})}return e.length>0&&console.error(`[ActionValidation] Batch validation failed: ${e.length} error(s) in ${t.length} action(s).`,e.map(i=>`${i.field??"?"}: ${i.message}`).join(" | ")),{valid:e.length===0,errors:e,warnings:n}}var S3=0;function Py(t){let{overlayRoot:e,eventBus:n,surfaces:i,anchorResolver:r,adaptiveId:a,executorRegistry:o=Ki,subscribeNavigation:s}=t,l=new Map;function c(){return`action-${++S3}`}function u(p,m){n&&n.publish(p,m)}function f(){return{overlayRoot:e,resolveAnchor:r,generateId:c,publishEvent:u,adaptiveId:a,applyAction:g,subscribeEvent:n?(p,m)=>n.subscribe({names:[p]},v=>m(v.props)):void 0,subscribeNavigation:s}}async function h(p,m){if(!i)throw new Error("Surfaces provider required for core:mountWidget actions");let v=i.mount(p.slot,{type:"widget",widgetId:p.widget.widgetId,config:p.widget.props},{priority:p.widget.priority});return m.publishEvent("action.applied",{id:m.generateId(),kind:"core:mountWidget",slot:p.slot,widgetId:p.widget.widgetId}),{cleanup:()=>{v.unmount()},updateFn:S=>{if("widget"in S&&S.widget){let T=S.widget;T.props&&v.update({type:"widget",widgetId:p.widget.widgetId,config:T.props})}}}}async function g(p){let m=ta(p);if(!m.valid){let C=m.errors.map(x=>x.message).join("; ");throw console.error(`[ActionEngine] Validation failed for action kind="${p?.kind}":`,C,p),new Error(`Action validation failed: ${C}`)}let v=c(),S=f(),T;if(p.kind==="core:mountWidget")T=await h(p,S);else{let C=o.get(p.kind);if(!C){let x="list"in o?o.list():"(list unavailable)";throw console.error(`[ActionEngine] No executor for kind="${p.kind}".`,`Registered: [${x}]`),new Error(`No executor for action kind: ${p.kind}`)}T=await C(p,S)}let A={id:v,action:p,adaptiveId:a,appliedTs:Date.now(),state:"applied",cleanup:T.cleanup,updateFn:T.updateFn};return l.set(v,A),u("action.applied",{id:v,kind:p.kind,anchorId:"anchorId"in p?p.anchorId:void 0}),{id:v,action:p,async revert(){let C=l.get(v);if(!(!C||C.state!=="applied"))try{await C.cleanup(),C.state="reverted",u("action.reverted",{id:v,kind:p.kind})}catch(x){throw C.state="failed",u("action.failed",{id:v,kind:p.kind,error:String(x)}),x}finally{l.delete(v)}},isApplied(){return l.get(v)?.state==="applied"},async update(C){let x=l.get(v);if(!x||x.state!=="applied")throw new Error("Cannot update action that is not applied");if(x.updateFn)await x.updateFn(C);else throw new Error(`Action kind ${p.kind} does not support updates`)},getState(){return l.get(v)?.state??"reverted"}}}async function _(p){console.log(`[ActionEngine] applyBatch: ${p.length} action(s)`,p.map(k=>k.kind).join(", "));let m=qy(p);if(!m.valid){let k=m.errors.map(C=>C.message).join("; ");throw console.error(`[ActionEngine] Batch validation FAILED for ${p.length} action(s):`,k,`
|
|
448
448
|
Actions:`,p.map((C,x)=>` [${x}] ${C.kind} ${C.anchorId?`anchor="${C.anchorId}"`:""} ${C.label?`label="${C.label}"`:""}`).join(`
|
|
449
|
-
`)),new Error(`Batch validation failed: ${k}`)}let v=c(),S=[],T=[];try{for(let k of p){let C=await g(k);S.push(C),T.push(C)}}catch(k){console.error(`[ActionEngine] Batch apply FAILED at action ${T.length+1}/${p.length}.`,`Successfully applied: ${T.length}. Rolling back...`,k);for(let C of T)try{await C.revert()}catch{}throw k}return{id:v,handles:S,async revertAll(){for(let k=S.length-1;k>=0;k--)try{await S[k].revert()}catch(C){console.error(`[ActionEngine] Error reverting action ${S[k].id}:`,C)}},isApplied(){return S.every(k=>k.isApplied())}}}function b(p){return ta(p)}function w(){return Array.from(l.values()).map(p=>({id:p.id,action:p.action,adaptiveId:p.adaptiveId,appliedTs:p.appliedTs,state:p.state}))}function d(){for(let p of l.values())if(p.state==="applied")try{p.cleanup()}catch(m){console.error("[ActionEngine] Error during cleanup:",m)}l.clear()}return{apply:g,applyBatch:_,validate:b,getActive:w,destroy:d}}var tT=y.object({color:y.string().optional(),scrimOpacity:y.number().min(0).max(1).optional(),paddingPx:y.number().optional(),radiusPx:y.number().optional()}).strict(),nT=y.enum(["top-left","top-right","bottom-left","bottom-right"]),iT=y.enum(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),Zy=y.object({label:y.string(),actionId:y.string(),primary:y.boolean().optional()}).strict(),rT=y.object({title:y.string().optional(),body:y.string(),ctaButtons:y.array(Zy).optional()}).strict(),aT=y.object({title:y.string().optional(),body:y.string()}).strict(),oT=y.enum(["before","after","prepend","append","replace"]),sT=y.enum(["immediate","hover","click"]),lT=y.object({widgetId:y.string(),props:y.record(y.unknown()).optional(),priority:y.number().optional()}).strict(),cT=y.object({id:y.string(),action:y.any(),route:y.string().optional(),onAction:y.record(y.string()).optional()}).strict(),uT=y.enum(["auto","smooth","instant"]),Gy=y.enum(["start","center","end","nearest"]),dT=y.object({kind:y.literal("content:setText"),anchorId:y.string(),text:y.string(),label:y.string().optional()}).strict(),fT=y.object({kind:y.literal("content:setAttr"),anchorId:y.string(),attr:y.string(),value:y.string(),label:y.string().optional()}).strict(),pT=y.object({kind:y.literal("content:addClass"),anchorId:y.string(),className:y.string(),label:y.string().optional()}).strict(),hT=y.object({kind:y.literal("content:removeClass"),anchorId:y.string(),className:y.string(),label:y.string().optional()}).strict(),gT=y.object({kind:y.literal("content:setStyle"),anchorId:y.string(),styles:y.record(y.string()),label:y.string().optional()}).strict(),mT=y.object({kind:y.literal("content:insertHtml"),anchorId:y.string(),html:y.string(),position:oT,label:y.string().optional()}).strict(),vT=y.object({kind:y.literal("overlays:highlight"),anchorId:y.string(),style:tT.optional(),duration:y.number().optional(),label:y.string().optional()}).strict(),yT=y.object({kind:y.literal("overlays:pulse"),anchorId:y.string(),duration:y.number().optional(),label:y.string().optional()}).strict(),bT=y.object({kind:y.literal("overlays:badge"),anchorId:y.string(),content:y.string(),position:nT.optional(),label:y.string().optional()}).strict(),_T=y.object({kind:y.literal("overlays:tooltip"),anchorId:y.string(),content:rT,trigger:sT.optional(),placement:iT.optional(),waitFor:y.string().optional(),label:y.string().optional()}).strict(),ST=y.object({kind:y.literal("overlays:modal"),content:aT,size:y.enum(["sm","md","lg"]).optional(),blocking:y.boolean().optional(),scrim:y.object({opacity:y.number().min(0).max(1).optional()}).strict().optional(),dismiss:y.object({onEsc:y.boolean().optional(),closeButton:y.boolean().optional(),timeoutMs:y.number().min(0).optional()}).strict().optional(),ctaButtons:y.array(Zy).optional(),waitFor:y.string().optional(),label:y.string().optional()}).strict(),xT=y.object({kind:y.literal("navigation:scrollTo"),anchorId:y.string(),behavior:uT.optional(),block:Gy.optional(),inline:Gy.optional(),label:y.string().optional()}).strict(),wT=y.object({kind:y.literal("navigation:navigate"),url:y.string(),target:y.enum(["_self","_blank"]).optional(),label:y.string().optional()}).strict(),ET=y.object({kind:y.literal("core:mountWidget"),slot:y.string(),widget:lT,label:y.string().optional()}).strict(),CT=y.object({kind:y.literal("core:wait"),durationMs:y.number().min(0).optional(),event:y.string().optional(),label:y.string().optional()}).strict(),AT=y.object({kind:y.literal("core:sequence"),actions:y.array(y.any()),label:y.string().optional()}).strict(),TT=y.object({kind:y.literal("core:parallel"),actions:y.array(y.any()),waitFor:y.enum(["all","any"]).optional(),label:y.string().optional()}).strict(),kT=y.object({kind:y.literal("core:tour"),tourId:y.string(),steps:y.array(cT).min(1),startStep:y.string().optional(),autoStart:y.boolean().optional(),label:y.string().optional()}).strict(),x3=[{defName:"setText",schema:dT},{defName:"setAttr",schema:fT},{defName:"addClass",schema:pT},{defName:"removeClass",schema:hT},{defName:"setStyle",schema:gT},{defName:"insertHtml",schema:mT},{defName:"highlight",schema:vT},{defName:"pulse",schema:yT},{defName:"badge",schema:bT},{defName:"tooltip",schema:_T},{defName:"modal",schema:ST},{defName:"scrollTo",schema:xT},{defName:"navigate",schema:wT},{defName:"mountWidget",schema:ET},{defName:"wait",schema:CT},{defName:"sequence",schema:AT},{defName:"parallel",schema:TT},{defName:"tour",schema:kT}];function w3(){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 Yy(t,e){if(!e)return;let n;try{n=new URL(t).pathname}catch{n=t}if(e.exclude){for(let i of e.exclude)if(RT(n,i))return}if(e.include){for(let i of e.include)if(RT(n,i))return i;return}return n}function RT(t,e){let n=t.replace(/\/$/,"")||"/",i=e.replace(/\/$/,"")||"/";if(n===i)return!0;let r=i.replace(/:[^/]+/g,"[^/]+").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(n)}var Zf=class{constructor(e={}){V(this,"context");V(this,"previousContext");V(this,"listeners",new Set);V(this,"telemetry");V(this,"routes");V(this,"navigation");V(this,"cleanupFns",[]);if(this.telemetry=e.telemetry,this.routes=e.routes,this.navigation=e.navigation,this.context=w3(),this.previousContext={...this.context},e.telemetry?.getSessionId){let n=e.telemetry.getSessionId();n&&(this.context.session.sessionId=n)}e.initialPageHistory&&(this.context.session.pageHistory=e.initialPageHistory),this.context.page.routeId=Yy(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 n=Yy(this.context.page.url,this.routes);n!==this.context.page.routeId&&this.updateContext({page:{...this.context.page,routeId:n}})}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,n=()=>{clearTimeout(e),e=setTimeout(()=>{this.updateViewport()},100)};if(window.addEventListener("resize",n),this.cleanupFns.push(()=>window.removeEventListener("resize",n)),this.navigation){let i=this.navigation.subscribe(()=>this.updatePage());this.cleanupFns.push(i)}else{let i=()=>{this.updatePage()};window.addEventListener("popstate",i),this.cleanupFns.push(()=>window.removeEventListener("popstate",i));let r=history.pushState.bind(history),a=history.replaceState.bind(history);history.pushState=(...o)=>{r(...o),queueMicrotask(()=>this.updatePage())},history.replaceState=(...o)=>{a(...o),queueMicrotask(()=>this.updatePage())},this.cleanupFns.push(()=>{history.pushState=r,history.replaceState=a})}}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:n}=document,i=Yy(e,this.routes),r={url:e,title:n,routeId:i};(r.url!==this.context.page.url||r.title!==this.context.page.title||r.routeId!==this.context.page.routeId)&&(r.url!==this.context.page.url&&this.addPageToHistory(r.url),this.updateContext({page:r}))}addPageToHistory(e){let n={url:e,ts:Date.now()},i=[...this.context.session.pageHistory||[],n];i.length>50&&i.shift(),this.context.session.pageHistory=i}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(n){console.error("[ContextManager] Listener error:",n)}}};function Wy(t={}){return new Zf(t)}var E3=y.object({url:y.string(),routeId:y.string().optional(),title:y.string().optional(),locale:y.string().optional()}),C3=y.object({url:y.string(),ts:y.number()}),A3=y.object({sessionId:y.string(),startTs:y.number(),pageHistory:y.array(C3).optional()}),T3=y.object({width:y.number(),height:y.number()}),k3=y.object({x:y.number(),y:y.number(),w:y.number(),h:y.number()}),R3=y.object({anchorId:y.string(),present:y.boolean(),visible:y.boolean().optional(),boundingBox:k3.optional()}),O3=y.record(y.string(),y.union([y.number(),y.string(),y.boolean(),y.undefined()])),M3=y.object({page:E3,session:A3,viewport:T3,anchors:y.array(R3).optional(),augmented:O3.optional()});function l$(t){return M3.safeParse(t)}function OT(t,e){let{context:n,state:i,events:r}=e;switch(t.type){case"page_url":{let{url:a}=t,o=n.page.url,s=a.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*");return new RegExp(`^${s}$`).test(o)}case"route":return n.page.routeId===t.routeId;case"anchor_visible":{let a=n.anchors?.find(o=>o.anchorId===t.anchorId);switch(t.state){case"visible":return a?.visible===!0;case"present":return a?.present===!0;case"absent":return!a?.present;default:return!1}}case"event_occurred":{if(!r)return!1;let a=t.withinMs??6e4;return r.hasRecentEvent(t.eventName,a)}case"state_equals":return!1;case"viewport":{let{width:a,height:o}=n.viewport;return!(t.minWidth!==void 0&&a<t.minWidth||t.maxWidth!==void 0&&a>t.maxWidth||t.minHeight!==void 0&&o<t.minHeight||t.maxHeight!==void 0&&o>t.maxHeight)}case"session_metric":{if(!i)return!1;let a=i.getSessionMetric(t.key),{operator:o,threshold:s}=t;switch(o){case"gte":return a>=s;case"lte":return a<=s;case"eq":return a===s;case"gt":return a>s;case"lt":return a<s;default:return!1}}case"dismissed":{if(!i)return t.inverted??!1;let a=i.isDismissed(t.key);return t.inverted?!a:a}case"cooldown_active":{if(!i)return t.inverted??!1;let a=i.isCooldownActive(t.key);return t.inverted?!a:a}case"frequency_limit":{if(!i)return t.inverted??!1;let o=i.getFrequencyCount(t.key)>=t.limit;return t.inverted?!o:o}case"event_count":{if(!e.accumulator)return!1;let a=t,o=e.accumulator.getCount(a.key,a.withinMs);switch(a.operator){case"gte":return o>=a.count;case"lte":return o<=a.count;case"eq":return o===a.count;case"gt":return o>a.count;case"lt":return o<a.count;default:return!1}}default:return console.warn("[RuleStrategy] Unknown condition type:",t.type),!1}}function MT(t,e){let n=[];for(let i of t.conditions){let r=OT(i,e);if(n.push({condition:i,result:r}),!r)return{matched:!1,conditionResults:n}}return{matched:!0,conditionResults:n}}function Yf(t,e){for(let n=0;n<t.rules.length;n++){let i=t.rules[n],{matched:r,conditionResults:a}=MT(i,e);if(r)return{value:i.value,isFallback:!1,matchInfo:{strategyType:"rules",matchedRuleIndex:n,evaluatedConditions:a}}}return{value:t.default,isFallback:!0,matchInfo:{strategyType:"rules"}}}function Wf(t,e){let{context:n}=e,i=n.augmented?.[t.field];return i===void 0||typeof i!="number"?{value:t.below,isFallback:!0,matchInfo:{strategyType:"score"}}:{value:i>=t.threshold?t.above:t.below,isFallback:!1,matchInfo:{strategyType:"score"}}}function NT(t,e){let{state:n,events:i,sessionMetrics:r,accumulator:a}=e;return{context:t,state:n?{isDismissed:o=>n.dismissals.isDismissed(o),isCooldownActive:o=>n.cooldowns.isActive(o),getFrequencyCount:o=>n.frequency.count(o),getSessionMetric:o=>r?.get(o)??0}:void 0,events:i?{hasRecentEvent:(o,s)=>i.hasRecentEvent(o,s)}:void 0,accumulator:a?{getCount:(o,s)=>a.getCount(o,s)}:void 0}}async function DT(t,e,n={}){let i=NT(e,n);switch(t.type){case"rules":return Yf(t,i);case"score":return Wf(t,i);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 LT(t,e,n={}){let i=NT(e,n);switch(t.type){case"rules":return Yf(t,i);case"score":return Wf(t,i);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 Ky(t){return{evaluate:(e,n)=>DT(e,n,t),evaluateSync:(e,n)=>LT(e,n,t)}}var N3=y.object({type:y.literal("page_url"),url:y.string()}),D3=y.object({type:y.literal("route"),routeId:y.string()}),L3=y.object({type:y.literal("anchor_visible"),anchorId:y.string(),state:y.enum(["visible","present","absent"])}),H3=y.object({type:y.literal("event_occurred"),eventName:y.string(),withinMs:y.number().optional()}),I3=y.object({type:y.literal("state_equals"),key:y.string(),value:y.unknown()}),z3=y.object({type:y.literal("viewport"),minWidth:y.number().optional(),maxWidth:y.number().optional(),minHeight:y.number().optional(),maxHeight:y.number().optional()}),B3=y.object({type:y.literal("session_metric"),key:y.string(),operator:y.enum(["gte","lte","eq","gt","lt"]),threshold:y.number()}),$3=y.object({type:y.literal("dismissed"),key:y.string(),inverted:y.boolean().optional()}),U3=y.object({type:y.literal("cooldown_active"),key:y.string(),inverted:y.boolean().optional()}),F3=y.object({type:y.literal("frequency_limit"),key:y.string(),limit:y.number(),inverted:y.boolean().optional()}),V3=y.object({type:y.literal("event_count"),key:y.string(),operator:y.enum(["gte","lte","eq","gt","lt"]),count:y.number().int().min(0),withinMs:y.number().positive().optional()}),HT=y.discriminatedUnion("type",[N3,D3,L3,H3,I3,z3,B3,$3,U3,F3,V3]),j3=y.object({conditions:y.array(HT),value:y.unknown()}),q3=y.object({type:y.literal("rules"),rules:y.array(j3),default:y.unknown()}),P3=y.object({type:y.literal("score"),field:y.string(),threshold:y.number(),above:y.unknown(),below:y.unknown()}),G3=y.object({type:y.literal("model"),modelId:y.string(),inputs:y.array(y.string()),outputMapping:y.record(y.string(),y.unknown()),default:y.unknown()}),Z3=y.object({type:y.literal("external"),endpoint:y.string(),method:y.enum(["GET","POST"]).optional(),default:y.unknown(),timeoutMs:y.number().optional()}),IT=y.discriminatedUnion("type",[q3,P3,G3,Z3]),Y3=y.object({include:y.array(y.string()).optional(),exclude:y.array(y.string()).optional()}),W3=y.object({routes:Y3.optional(),strategy:IT.optional()});function _$(t){return HT.safeParse(t)}function S$(t){return IT.safeParse(t)}function x$(t){return W3.safeParse(t)}function Xy(t){let{eventBus:e,stateStore:n}=t,i=new Map,r=new Set,a=null,o=n.ns("accumulator");function s(c){let u=!1;for(let f of i.values()){if(!f.predicate(c))continue;let h=o.get(f.stateKey)||{count:0};h.count++,f.needsTimestamps&&(h.timestamps||(h.timestamps=[]),h.timestamps.push(c.ts),h.timestamps.length>200&&(h.timestamps=h.timestamps.slice(-200))),o.set(f.stateKey,h),u=!0}if(u)for(let f of r)try{f()}catch(h){console.error("[EventAccumulator] Subscriber error:",h)}}function l(){a||i.size===0||(a=e.subscribe(s))}return{register(c,u,f=!1){let h=`ev:${c}`,g=i.get(h);if(g){f&&!g.needsTimestamps&&(g.needsTimestamps=!0);return}i.set(h,{stateKey:h,needsTimestamps:f,predicate:u}),l()},getCount(c,u){let f=`ev:${c}`,h=o.get(f);if(!h)return 0;if(u===void 0||!h.timestamps)return h.count;let g=Date.now()-u;return h.timestamps.filter(_=>_>=g).length},subscribe(c){return r.add(c),()=>{r.delete(c)}},destroy(){a&&(a(),a=null),i.clear(),r.clear()}}}function Qy(t,e){return e?!(e.names&&e.names.length>0&&!e.names.includes(t.name)||e.patterns&&e.patterns.length>0&&!e.patterns.some(i=>{try{return new RegExp(i).test(t.name)}catch{return!1}})||e.sources&&e.sources.length>0&&!e.sources.includes(t.source)):!0}var Kf=class{constructor(e={}){V(this,"subscriptions",new Set);V(this,"history",[]);V(this,"maxHistorySize");this.maxHistorySize=e.maxHistorySize??100}subscribe(e,n){let i,r;typeof e=="function"?(i=void 0,r=e):(i=e,r=n);let a={filter:i,callback:r};return this.subscriptions.add(a),()=>{this.subscriptions.delete(a)}}publish(e,n,i="canvas"){let r={ts:Date.now(),name:e,source:i,props:n,schemaVersion:ns};this.publishEvent(r)}publishEvent(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift();for(let n of this.subscriptions)if(Qy(e,n.filter))try{n.callback(e)}catch(i){console.error("[EventBus] Subscriber error:",i)}}getRecent(e,n){let i=this.history;return e&&(i=i.filter(r=>Qy(r,e))),n&&n>0&&(i=i.slice(-n)),i}hasRecentEvent(e,n,i){let r=Date.now()-n;return this.history.some(a=>a.name===e&&a.ts>=r&&(i===void 0||a.source===i))}countRecentEvents(e,n){let i=this.history.filter(r=>Qy(r,e));if(n!==void 0){let r=Date.now()-n;i=i.filter(a=>a.ts>=r)}return i.length}clearHistory(){this.history=[]}getSubscriberCount(){return this.subscriptions.size}};function Nc(t={}){return new Kf(t)}var zT={$autocapture:"ui.click",$click:_e.UI_CLICK,$scroll:_e.UI_SCROLL,$input:_e.UI_INPUT,$change:_e.UI_CHANGE,$submit:_e.UI_SUBMIT,$pageview:_e.NAV_PAGE_VIEW,$pageleave:_e.NAV_PAGE_LEAVE,$session_start:"session.start",$identify:"user.identify"};function K3(t){let e=t.event;if(typeof e!="string")return"posthog.unknown";if(zT[e])return zT[e];if(e==="$autocapture"){let n=t.properties?.$tag_name,i=t.properties?.$event_type;return i==="submit"?_e.UI_SUBMIT:i==="change"?_e.UI_CHANGE:n==="input"||n==="textarea"?_e.UI_INPUT:_e.UI_CLICK}return e.startsWith("$")?e.replace("$","posthog."):`posthog.${e}`}function X3(t){let e={},n=t.properties||{},i=n.$elements;return n.$tag_name?e.tagName=n.$tag_name:i?.[0]?.tag_name&&(e.tagName=i[0].tag_name),n.$el_text&&(e.elementText=n.$el_text),i&&(e.elements=i),n.$current_url&&(e.url=n.$current_url),n.$pathname&&(e.pathname=n.$pathname),n.$host&&(e.host=n.$host),n.$viewport_width&&(e.viewportWidth=n.$viewport_width),n.$viewport_height&&(e.viewportHeight=n.$viewport_height),n.$session_id&&(e.sessionId=n.$session_id),n.$scroll_depth&&(e.scrollDepth=n.$scroll_depth),n.$scroll_percentage&&(e.scrollPercentage=n.$scroll_percentage),e.originalEvent=t.event,e}function BT(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:K3(t),source:"posthog",props:X3(t),schemaVersion:ns}}function $T(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 Jy(t){return(e,n)=>{if(typeof e!="string")return;let i={event:e,properties:n,timestamp:Date.now()};if($T(i)){let r=BT(i);t(r)}}}var UT=y.enum(["posthog","canvas","derived"]),Q3=y.object({ts:y.number(),name:y.string(),source:UT,props:y.record(y.string(),y.unknown()).optional(),schemaVersion:y.string()}),J3=y.object({names:y.array(y.string()).optional(),patterns:y.array(y.string()).optional(),sources:y.array(UT).optional()});function z$(t){return Q3.safeParse(t)}function B$(t){return J3.safeParse(t)}var Dc=class{constructor(){V(this,"listeners",new Set);V(this,"capturedPushState");V(this,"capturedReplaceState");V(this,"wasNative");V(this,"destroyed",!1);V(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,n){if(!this.destroyed)for(let i of this.listeners)try{i(e,n)}catch{}}isNativeFunction(e){try{return Function.prototype.toString.call(e).includes("[native code]")}catch{return!1}}};var eb="cooldown:";function FT(t){return{set(e,n){let i=eb+e,r=Date.now()+n;t.set(i,r)},isActive(e){return this.remaining(e)>0},remaining(e){let n=eb+e,i=t.get(n);if(i===void 0)return 0;let r=i-Date.now();return r<=0?(t.remove(n),0):r},clear(e){let n=eb+e;t.remove(n)}}}var Lc="dismissed:";function VT(t,e){return{mark(n,i=!1){let r=Lc+n;(i?e:t).set(r,!0)},isDismissed(n){let i=Lc+n;return t.has(i)||e.has(i)},clear(n){let i=Lc+n;t.remove(i),e.remove(i)},clearAll(){for(let n of t.keys())n.startsWith(Lc)&&t.remove(n);for(let n of e.keys())n.startsWith(Lc)&&e.remove(n)}}}var tb="freq:";function jT(t){function e(n){let i=tb+n,r=t.get(i);if(r){if(r.resetAt&&Date.now()>=r.resetAt){t.remove(i);return}return r}}return{increment(n,i){let r=tb+n,a=e(n),o=(a?.count??0)+1,s={count:o,resetAt:a?.resetAt??(i?Date.now()+i:void 0)};return t.set(r,s),o},count(n){return e(n)?.count??0},reset(n){let i=tb+n;t.remove(i)},hasReachedLimit(n,i){return this.count(n)>=i}}}var e5="syntro";function nb(t,e){let n=`${e}:`;return{get(i){if(t)try{let r=t.getItem(n+i);if(!r)return;let a=JSON.parse(r);if(a.expiresAt&&Date.now()>=a.expiresAt){t.removeItem(n+i);return}return a.value}catch{return}},set(i,r,a){if(t)try{let o={value:r,expiresAt:a?Date.now()+a:void 0};t.setItem(n+i,JSON.stringify(o))}catch(o){console.warn("[StateStore] Failed to save:",o)}},remove(i){t&&t.removeItem(n+i)},has(i){return t?this.get(i)!==void 0:!1},keys(){if(!t)return[];let i=[];for(let r=0;r<t.length;r++){let a=t.key(r);a?.startsWith(n)&&i.push(a.slice(n.length))}return i},clear(){if(!t)return;let i=this.keys();for(let r of i)t.removeItem(n+r)}}}function ib(t){let e=new Map,n=`${t}:`;return{get(i){let r=e.get(n+i);if(r){if(r.expiresAt&&Date.now()>=r.expiresAt){e.delete(n+i);return}return r.value}},set(i,r,a){e.set(n+i,{value:r,expiresAt:a?Date.now()+a:void 0})},remove(i){e.delete(n+i)},has(i){return this.get(i)!==void 0},keys(){let i=[];for(let r of e.keys())r.startsWith(n)&&i.push(r.slice(n.length));return i},clear(){for(let i of e.keys())i.startsWith(n)&&e.delete(i)}}}var Xf=class{constructor(e={}){V(this,"session");V(this,"user");V(this,"dismissals");V(this,"cooldowns");V(this,"frequency");V(this,"namespace");V(this,"namespacedStorages",new Map);this.namespace=e.namespace??e5,typeof window<"u"?(this.session=nb(typeof sessionStorage<"u"?sessionStorage:void 0,this.namespace),this.user=nb(typeof localStorage<"u"?localStorage:void 0,this.namespace)):(this.session=ib(this.namespace),this.user=ib(this.namespace)),this.dismissals=VT(this.session,this.user),this.cooldowns=FT(this.user),this.frequency=jT(this.session)}ns(e){let n=`${this.namespace}:${e}`;if(!this.namespacedStorages.has(n)){let i=typeof window<"u"&&typeof sessionStorage<"u"?nb(sessionStorage,n):ib(n);this.namespacedStorages.set(n,i)}return this.namespacedStorages.get(n)}};function rb(t={}){return new Xf(t)}function Hc(t){return t.startsWith("inline:")?"inline":t.startsWith("adjacent:")?"adjacent":"static"}function Qf(t){return t.startsWith("inline:")?t.slice(7):t.startsWith("adjacent:")?t.slice(9):null}var qT={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"}},Ic={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:[]},PT={duration:200,easing:"cubic-bezier(0.16, 1, 0.3, 1)",fill:"forwards"};function ab(t,e,n){let i=qT[e];Object.assign(t.style,i),n&&(n.maxWidth&&(t.style.maxWidth=n.maxWidth),n.maxHeight&&(t.style.maxHeight=n.maxHeight),n.minWidth&&(t.style.minWidth=n.minWidth),n.minHeight&&(t.style.minHeight=n.minHeight))}function ob(t,e,n){let i=n.placement==="auto"?"bottom":n.placement,r=[Ed(n.offset?{mainAxis:n.offset.y,crossAxis:n.offset.x}:8)];return n.flip!==!1&&r.push(Ad()),n.shift!==!1&&r.push(Cd({padding:8})),t.style.position="absolute",t.style.zIndex="2147483646",wd(e,t,async()=>{let{x:o,y:s,strategy:l}=await Td(e,t,{placement:i,middleware:r});Object.assign(t.style,{position:l,left:`${o}px`,top:`${s}px`})})}function sb(t,e,n="append"){return t.style.position="relative",t.style.display="inline-block",n==="prepend"?e.insertBefore(t,e.firstChild):e.appendChild(t),()=>{t.remove()}}function lb(t,e){return e==="none"||Ic[e].length===0?null:t.animate(Ic[e],PT)}function cb(t,e){if(e==="none"||Ic[e].length===0)return Promise.resolve();let n=[...Ic[e]].reverse(),i=t.animate(n,PT);return new Promise(r=>{i.onfinish=()=>r(),i.oncancel=()=>r()})}function ub(t,e){let n=document.createElement("div");return n.setAttribute("data-syntro-surface",t),n.setAttribute("data-syntro-mount-id",e),n.className="syntro-surface",Object.assign(n.style,{pointerEvents:"auto",boxSizing:"border-box",overflow:"auto"}),n}function db(t){switch(Hc(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 GT(t){if(typeof window.Sanitizer=="function")try{let l=new window.Sanitizer({}).sanitizeToFragment(t),c=document.createElement("div");return c.append(l),c.innerHTML}catch{}let n=document.createElement("template");n.innerHTML=t;let i=n.content,r=document.createTreeWalker(i,NodeFilter.SHOW_ELEMENT,null),a=new Set(["b","strong","i","em","u","span","div","p","br","ul","ol","li","code","pre","small","sup","sub","a","button"]),o=[];for(;r.nextNode();){let s=r.currentNode,l=s.tagName.toLowerCase();if(!a.has(l)){o.push(s);continue}for(let c of Array.from(s.attributes)){let u=c.name.toLowerCase(),f=c.value.trim().toLowerCase(),h=u.startsWith("on"),g=(u==="href"||u==="src")&&f.startsWith("javascript:");(h||g)&&s.removeAttribute(c.name)}}for(let s of o){for(;s.firstChild;)s.parentNode?.insertBefore(s.firstChild,s);s.remove()}return n.innerHTML=(i.firstChild,n.innerHTML)}var t5=0;function fb(t){let{overlayRoot:e,eventBus:n,anchorResolver:i,defaultAnimation:r="fade",widgetRegistry:a}=t,o=new Map,s=new Map,l=new Map;function c(){return`mount-${++t5}`}function u(v,S){n&&n.publish(v,S)}function f(v){let S=l.get(v);if(S){let T=w(v);for(let A of S)try{A(T)}catch(k){console.error("[Surfaces] State callback error:",k)}}}let h=new Map;function g(v,S,T){switch(S.type){case"html":v.innerHTML=GT(S.content);return;case"widget":{if(a?.has(S.widgetId)){let A=a.mount(S.widgetId,v,S.config);return T&&h.set(T,A),()=>{A.unmount(),T&&h.delete(T)}}console.warn(`[Surfaces] Widget not found: ${S.widgetId}`),v.innerHTML=`<div data-widget-id="${S.widgetId}" data-widget-missing="true">Widget: ${S.widgetId}</div>`;return}case"custom":return S.mount(v);case"react":v.innerHTML="<div data-react-component>React Component</div>";return;default:console.warn("[Surfaces] Unknown content type");return}}function _(v,S,T){let A=c(),k=Hc(v),C=T?.priority??0,x=T?.animation??r,M=T?.exclusive??!0,z=o.get(v);if(z&&M){if(z.options.priority>C)throw new Error(`Slot ${v} is occupied by higher priority content (${z.options.priority} > ${C})`);b(z)}let F=ub(v,A);F.style.zIndex=String(db(v));let P;if(k==="static")ab(F,v,T?.constraints),e.appendChild(F);else if(k==="inline"){let D=Qf(v);if(!D)throw new Error(`Invalid inline slot: ${v}`);if(!i)throw new Error("Anchor resolver required for inline slots");let L=i(D);if(!L)throw new Error(`Anchor not found for inline slot: ${D}`);P=sb(F,L)}else if(k==="adjacent"){let D=Qf(v);if(!D)throw new Error(`Invalid adjacent slot: ${v}`);if(!i)throw new Error("Anchor resolver required for adjacent slots");let L=i(D);if(!L)throw new Error(`Anchor not found for adjacent slot: ${D}`);e.appendChild(F),P=ob(F,L,T?.position??{placement:"bottom"})}let J=g(F,S,A);lb(F,x);let G={id:A,slot:v,content:S,options:{priority:C,exclusive:M,animation:x,position:T?.position??{placement:"auto"},constraints:T?.constraints??{},adaptiveId:T?.adaptiveId,autoUnmountOnRouteChange:T?.autoUnmountOnRouteChange??!0},container:F,cleanup:()=>{P?.(),J?.()},mountedAt:Date.now()};return o.set(v,G),s.set(v,(s.get(v)??0)+1),u("surface.mounted",{slot:v,id:A,adaptiveId:T?.adaptiveId}),f(v),{id:A,update(D){let L=o.get(v);if(!L||L.id!==A)throw new Error("Mount no longer active");let ue=h.get(A);if(ue){if(D.type==="widget"){ue.update(D.config),L.content=D;return}ue.unmount(),h.delete(A)}L.container.innerHTML="";let dn=g(L.container,D,A);if(L.content=D,dn){let We=L.cleanup;L.cleanup=()=>{We?.(),dn()}}},setOptions(D){let L=o.get(v);if(!L||L.id!==A)throw new Error("Mount no longer active");D.priority!==void 0&&(L.options.priority=D.priority),D.animation!==void 0&&(L.options.animation=D.animation),D.constraints&&k==="static"&&(D.constraints.maxWidth&&(L.container.style.maxWidth=D.constraints.maxWidth),D.constraints.maxHeight&&(L.container.style.maxHeight=D.constraints.maxHeight),D.constraints.minWidth&&(L.container.style.minWidth=D.constraints.minWidth),D.constraints.minHeight&&(L.container.style.minHeight=D.constraints.minHeight)),f(v)},async unmount(){let D=o.get(v);!D||D.id!==A||await b(D)},isMounted(){return o.get(v)?.id===A},getContainer(){let D=o.get(v);return D?.id===A?D.container:null}}}async function b(v){await cb(v.container,v.options.animation),v.cleanup?.(),v.container.remove(),o.delete(v.slot),u("surface.unmounted",{slot:v.slot,id:v.id}),f(v.slot)}function w(v){let S=o.get(v);return{slot:v,occupied:!!S,currentPriority:S?.options.priority,currentAdaptiveId:S?.options.adaptiveId,mountCount:s.get(v)??0,currentMountId:S?.id}}function d(v,S){let T=l.get(v);return T||(T=new Set,l.set(v,T)),T.add(S),()=>{T?.delete(S),T?.size===0&&l.delete(v)}}function p(v,S){let T=o.get(v);return T?S!==void 0?S>=T.options.priority:!1:!0}function m(){for(let v of o.values())try{v.cleanup?.(),v.container.remove()}catch(S){console.error("[Surfaces] Error during cleanup:",S)}o.clear(),l.clear()}return{mount:_,getState:w,onStateChange:d,canMount:p,destroy:m}}var Jf=class{constructor(){V(this,"widgets",new Map);V(this,"mountedWidgets",new Map);V(this,"mountIdCounter",0);V(this,"runtimeRef");V(this,"listeners",new Set)}bindRuntime(e){this.runtimeRef=e}register(e,n,i="custom",r){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:n,source:i,metadata:r}),this.notify({type:"registered",widgetId:e})}unregister(e){let n=this.widgets.get(e);return n?n.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[n,i]of this.widgets.entries())i.source===e&&this.widgets.delete(n)}get(e){return this.widgets.get(e)?.widget}getRegistration(e){return this.widgets.get(e)}has(e){return this.widgets.has(e)}mount(e,n,i){let r=this.widgets.get(e);if(!r)throw new Error(`Widget not found: ${e}`);let a=`widget-mount-${++this.mountIdCounter}`;n.setAttribute("data-widget-mount-id",a),n.setAttribute("data-widget-id",e);let o={...i,runtime:this.runtimeRef},s=r.widget.mount(n,o);return this.mountedWidgets.set(a,{cleanup:s??void 0,container:n}),{widgetId:e,container:n,unmount:()=>{let c=this.mountedWidgets.get(a);c&&(c.cleanup?.(),this.mountedWidgets.delete(a),n.removeAttribute("data-widget-mount-id"),n.removeAttribute("data-widget-id"),n.innerHTML="")},update:c=>{if(r.widget.update)r.widget.update(n,c);else{let u=this.mountedWidgets.get(a);if(u){u.cleanup?.(),n.innerHTML="";let f={...c,runtime:this.runtimeRef},h=r.widget.mount(n,f);u.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(n=>n.source===e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(let n of this.listeners)try{n(e)}catch(i){console.error("[WidgetRegistry] Listener error:",i)}}destroy(){for(let[e,n]of this.mountedWidgets.entries())n.cleanup?.(),n.container.innerHTML="";this.mountedWidgets.clear()}},pb=new Jf;var YT="2.0.0";function n5(t,e){if(!e)return!0;let n;try{n=new URL(t).pathname}catch{n=t}let i=n.replace(/\/$/,"")||"/";if(e.exclude){for(let r of e.exclude)if(ZT(i,r))return!1}if(e.include&&e.include.length>0){for(let r of e.include)if(ZT(i,r))return!0;return!1}return!0}function ZT(t,e){let n=e.replace(/\/$/,"")||"/";if(t===n)return!0;let i=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/:[^/]+/g,"[^/]+");return new RegExp(`^${i}$`).test(t)}function i5(t){try{return document.querySelector(t)}catch{return null}}function hb(t={}){let{telemetry:e,sessionMetrics:n,routes:i,mode:r="production",namespace:a}=t,o=t.widgets??pb,s=t.executors??Ki,l=t.apps??Fl,c=new Dc,u=Wy({telemetry:e,routes:i,navigation:c}),f=t.events??Nc(),h=rb({namespace:a}),g=Xy({eventBus:f,stateStore:h}),_=Ky({state:h,events:f,sessionMetrics:n,accumulator:g}),b=Iw(),w=v=>i5(v),d=fb({overlayRoot:b,eventBus:f,anchorResolver:w,widgetRegistry:o}),p=Py({overlayRoot:b,eventBus:f,surfaces:d,anchorResolver:w,executorRegistry:s,subscribeNavigation:v=>c.subscribe(v)}),m={telemetry:e,context:u,events:f,state:h,sessionMetrics:n,actions:p,surfaces:d,widgets:o,executors:s,apps:l,accumulator:g,navigation:c,version:YT,mode:r,async evaluate(v){return _.evaluate(v,u.get())},evaluateSync(v){return _.evaluateSync(v,u.get())},async filterTiles(v){let S=u.get().page.url,T=[];for(let A of v){let k=A.activation;if(!k){T.push(A);continue}if(!n5(S,k.routes))continue;if(!k.strategy){T.push(A);continue}(await this.evaluate(k.strategy)).value&&T.push(A)}return T},setRoutes(v){u.setRoutes(v)},destroy(){l.unbind().catch(v=>{console.error("[Runtime] Error unbinding apps registry:",v)}),g.destroy(),c.destroy(),u.destroy(),p.destroy(),d.destroy()}};return l.bind(m),o.bindRuntime(m),m}var r5=y.object({value:y.unknown(),expiresAt:y.number().optional()}),a5=y.object({count:y.number(),resetAt:y.number().optional()});function U8(t){return r5.safeParse(t)}function F8(t){return a5.safeParse(t)}var WT={growthbook:t=>Gm({...t,autoInit:!0})};function KT(t,e){let n=WT[t];if(!n)throw new Error(`Unknown experiment provider: ${t}. Supported: ${Object.keys(WT).join(", ")}`);return n(e)}var o5=["cdn.syntrologie.com","localhost","127.0.0.1"];function s5(t){try{let e=new URL(t),n=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!n?(console.warn("[SmartCanvas] CDN URL must use HTTPS:",t),!1):o5.some(r=>e.hostname===r)?!0:(console.warn("[SmartCanvas] CDN host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid CDN URL:",t),!1}}var gb=class{constructor(e){V(this,"name","cdn");V(this,"url");V(this,"integrity");if(this.url=`${e.baseUrl}/${e.configId}.json`,this.integrity=e.integrity,!s5(this.url))throw new Error(`[SmartCanvas] CDN URL not allowed: ${this.url}`)}async fetch(){let e=performance.now(),n=await fetch(this.url,{credentials:"omit",cache:"default"});if(!n.ok)throw new Error(`[SmartCanvas] Failed to fetch config from CDN (${n.status})`);let i=await n.text();if(this.integrity){let l=await l5(i),c=this.integrity.replace("sha384-","");if(l!==c)throw new Error(`[SmartCanvas] Config integrity check failed. Expected ${c}, got ${l}`)}let r=JSON.parse(i),a=performance.now()-e,o=n.headers.get("cache-control"),s=n.headers.get("age");return{config:r,meta:{source:"cdn",fetchTimeMs:a,cached:o?.includes("public")??!1,cacheAge:s?parseInt(s,10):void 0}}}};async function l5(t){let n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-384",n),r=new Uint8Array(i);return btoa(String.fromCharCode(...r))}function XT(t){return new gb(t)}var c5="syntro_exp",u5="syntro_var",mb=class{constructor(e){V(this,"name","experiments");V(this,"client");V(this,"featureKey");V(this,"manifestKey");V(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 r=new URLSearchParams(window.location.search),a=r.get(c5),o=r.get(u5);if(a&&o!==null&&this.client.setForcedVariations){let s=parseInt(o,10);Number.isNaN(s)||(console.log(`[SmartCanvas] Preview mode: forcing "${a}" to variation ${s}`),this.client.setForcedVariations({[a]:s}))}}if(this.manifestKey||this.variantFlagPrefix){let r=this.fetchMultiFlag();if(r){let a=performance.now()-e;return{config:r,meta:{source:"experiments",fetchTimeMs:a,cached:!0}}}}let n=this.client.getFeatureValue?.(this.featureKey,null);if(!n||typeof n!="object")throw new Error(`[SmartCanvas] Feature "${this.featureKey}" not found or invalid. Ensure the feature is configured in your experiment platform.`);let i=performance.now()-e;return{config:n,meta:{source:"experiments",fetchTimeMs:i,cached:!0}}}fetchMultiFlag(){let e=this.getVariantFlagKeys();return!e||e.length===0?null:Nd(this.client,e)}getVariantFlagKeys(){if(this.manifestKey){let e=this.client.getFeatureValue?.(this.manifestKey,null);if(e&&typeof e=="object"){let n=e.variant_flags;if(n&&n.length>0)return n}}if(this.variantFlagPrefix&&this.client.getAllFeatures){let e=this.client.getAllFeatures();return Object.keys(e).filter(n=>n.startsWith(this.variantFlagPrefix))}return[]}};function QT(t){return new mb(t)}var d5="https://cdn.syntrologie.com/configs",JT={cdn:t=>{if(!t.configId)throw new Error("CDN fetcher requires 'configId' option");return XT({baseUrl:t.baseUrl??d5,configId:t.configId,integrity:t.integrity})},experiments:t=>{if(!t.featureKey)throw new Error("Experiments fetcher requires 'featureKey' option");return QT({featureKey:t.featureKey})}};function ek(t,e={}){let n=JT[t];if(!n)throw new Error(`Unknown config fetcher type: ${t}. Supported: ${Object.keys(JT).join(", ")}`);return n(e)}var tk={posthog:t=>Iy(t),noop:()=>Jm()};function nk(t,e){let n=tk[t];if(!n)throw new Error(`Unknown telemetry provider: ${t}. Supported: ${Object.keys(tk).join(", ")}`);return n(e)}var vb="syn_";function ep(t){if(!t.startsWith(vb))throw new Error("Invalid Syntro token: must start with 'syn_'");let n=t.slice(vb.length).replace(/-/g,"+").replace(/_/g,"/"),i=atob(n),r=JSON.parse(i);if(r.v!==1)throw new Error(`Unsupported token version: ${r.v}`);return r}function yb(t){let e=JSON.stringify(t),n=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return vb+n}function Xi(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 f5(){if(typeof window>"u")return Z("Syntro Bootstrap","isEditorMode: not in browser"),!1;let t=Ra(),n=!!(Nr()?.token&&t?.mode==="editor");return Z("Syntro Bootstrap","isEditorMode:",n),n}function p5(){if(typeof window>"u")return Z("Syntro Bootstrap","isAuditMode: not in browser"),!1;let t=Ra(),n=!!(Nr()?.token&&t?.mode==="audit");return Z("Syntro Bootstrap","isAuditMode:",n),n}function h5(){if(typeof window>"u")return Z("Syntro Bootstrap","isReviewMode: not in browser"),!1;let t=Ra(),n=!!(Nr()?.token&&t?.mode==="review");return Z("Syntro Bootstrap","isReviewMode:",n),n}var ik="syntro_segment_attributes";function g5(){if(typeof window>"u")return{};try{let t=localStorage.getItem(ik);if(t){let e=JSON.parse(t);return Z("Syntro Bootstrap","Loaded cached segment attributes:",e),e}}catch(t){ln("Syntro Bootstrap","Failed to load cached segment attributes:",t)}return{}}function m5(t){if(!(typeof window>"u"))try{localStorage.setItem(ik,JSON.stringify(t)),Z("Syntro Bootstrap","Cached segment attributes:",t)}catch(e){ln("Syntro Bootstrap","Failed to cache segment attributes:",e)}}function v5(t){if(!t)return{};let e={};for(let[n,i]of Object.entries(t))n.startsWith("in_segment_")&&(e[n]=i===!0);return e}async function y5(t){lm(),Z("Syntro Bootstrap","====== INIT ======"),Z("Syntro Bootstrap","Options:",{hasToken:!!t.token,tokenPrefix:`${t.token?.slice(0,15)}...`,hasCanvasOptions:!!t.canvas});let e=f5(),n=p5(),i=h5(),r=e?"editor":n?"audit":i?"review":null;if(console.log(`[DIAG] Mode detection: editor=${e}, audit=${n}, review=${i}, sdkMode=${r}`),console.log("[DIAG] editorSource:",Nr()),console.log("[DIAG] editorConf:",Ra()),Z("Syntro Bootstrap","SDK mode:",r??"normal"),!r&&typeof window<"u"){let x=!!window.__SYNTRO_EDITOR_PARAMS__,M=!!window.__SYNTRO_AUDIT_LEGEND__,z=!!window.__SYNTRO_REVIEW_DATA__;if(x||M||z){let F=[x&&"__SYNTRO_EDITOR_PARAMS__",M&&"__SYNTRO_AUDIT_LEGEND__",z&&"__SYNTRO_REVIEW_DATA__"].filter(Boolean);console.warn(`[Syntro Bootstrap] \u26A0 Mode detection returned null but mode-specific globals found: ${F.join(", ")}. This suggests URL params were lost (redirect?) but the service worker injected mode data. Check if replaceState failed or if page JS changed the URL before init().`)}}console.log(`[DIAG] Token resolution: options.token=${t.token?t.token.slice(0,15)+"...":"null"}`);let a=t.token;if(!a&&r){let M=Ra()?.syntro_token;M?.startsWith("syn_")&&(a=M,Z("Syntro Bootstrap",`\u2713 Using syntro_token from editor_conf (${r} mode)`))}let o;if(a)if(a.startsWith("syn_"))Z("Syntro Bootstrap","Token starts with syn_, decoding..."),o=ep(a),lm(o.d);else if(r)Z("Syntro Bootstrap",`\u2713 Non-syn_ token allowed (${r} mode)`);else throw Dd("Syntro Bootstrap","\u274C Token does not start with syn_ and NOT in editor/audit/review mode!"),Dd("Syntro Bootstrap","Token received:",a),new Error("Invalid Syntro token: must start with 'syn_'");else if(r)Z("Syntro Bootstrap",`\u2713 No token, but ${r} mode - proceeding`);else throw Dd("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=Xi("NEXT_PUBLIC_SYNTRO_EXPERIMENT_HOST")||Xi("VITE_SYNTRO_EXPERIMENT_HOST")||o?.eh,l=Xi("NEXT_PUBLIC_SYNTRO_TELEMETRY_HOST")||Xi("VITE_SYNTRO_TELEMETRY_HOST")||o?.th,c=Xi("NEXT_PUBLIC_SYNTRO_EDITOR_URL")||Xi("VITE_SYNTRO_EDITOR_URL")||t.canvas?.editorUrl,u=g5();Z("Syntro Bootstrap","Phase 1: Using cached segment attributes:",u);let f,h=Nc();console.log("[Syntro Bootstrap] EventBus created");let g=Jy(x=>{h.publishEvent(x)}),_=x=>{Z("Syntro Bootstrap","Phase 2: PostHog feature flags loaded");let M=v5(x);if(Z("Syntro Bootstrap","Segment flags from PostHog:",M),m5(M),f){let F={...w?.getAll?.()??{},...M};Z("Syntro Bootstrap","Updating GrowthBook with attributes:",F),f.setAttributes?.(F)}},b;if(o?.t){let x=o.t==="noop"?"noop":"posthog";b=nk(x,{apiKey:o.t,apiHost:l,enableFeatureFlags:!0,onFeatureFlagsLoaded:_,onCapture:g}),console.log(`[Syntro Bootstrap] Telemetry client created (${x}) with EventBus wiring`)}let w;o?.e&&(f=KT("growthbook",{clientKey:o.e,apiHost:s,attributes:u,onExperimentViewed:b?.trackExperiment?(x,M,z)=>{b.trackExperiment(x,M,z)}:void 0})),t.enableSessionMetrics&&(w=Zm({experiments:f,onMetricChange:(x,M)=>{Z("Syntro Bootstrap",`Session metric changed: ${x} = ${M}`)}}),Z("Syntro Bootstrap","SessionMetricTracker created"));let d="production";e?d="editor":n?d="audit":Xi("NODE_ENV")==="development"&&(d="development");let p=hb({telemetry:b,sessionMetrics:w,mode:d,events:h});Z("Syntro Bootstrap","Runtime created:",{version:p.version,mode:p.mode,hasContext:!!p.context,hasEvents:!!p.events,hasState:!!p.state}),Z("Syntro Bootstrap","Core app executors already registered");let m=t.cdnBase||Xi("NEXT_PUBLIC_SYNTRO_CDN_BASE")||Xi("VITE_SYNTRO_CDN_BASE")||"https://cdn.syntrologie.com",v=nm({cdnBase:m,registry:p.apps,onLoadStart:x=>{Z("Syntro Bootstrap",`Loading app from CDN: ${x}`)},onLoadEnd:(x,M,z)=>{M?Z("Syntro Bootstrap",`App loaded successfully: ${x}`):ln("Syntro Bootstrap",`Failed to load app: ${x}`,z)}});typeof window<"u"&&(window.SynOS={...window.SynOS,appRegistry:p.apps,runtime:p,version:p.version},Z("Syntro Bootstrap","Global SynOS object exposed"));let S=p.apps.list?.()??[];console.log(`[DIAG] Activation loop: ${S.length} apps in registry:`,S.map(x=>`${x.manifest.id}(${x.state})`).join(", "));for(let x of S)if(x.state==="registered")try{await p.apps.activate(x.manifest.id),console.log(`[DIAG] Activated: ${x.manifest.id} \u2192 widgets: [${p.widgets.list().join(", ")}]`)}catch(M){console.error(`[DIAG] FAILED to activate: ${x.manifest.id}`,M),ln("Syntro Bootstrap",`Failed to auto-activate built-in app: ${x.manifest.id}`,M)}if(console.log(`[DIAG] Activation complete. Total widgets: [${p.widgets.list().join(", ")}]`),f?.refreshFeatures)try{await f.refreshFeatures(),Z("Syntro Bootstrap","GrowthBook features loaded")}catch(x){ln("Syntro Bootstrap","Failed to load GrowthBook features:",x)}let T;if(t.fetcher)T=t.fetcher;else if(o?.f){let x=ek(o.f,o.o??{});T=async()=>{let M=await x.fetch();return{...M.config,tiles:M.config.tiles??[]}}}else f&&(T=Jo({experiments:f}));let A=new Set,k=T?async()=>{let x=await T();console.log("[Syntro Bootstrap] Config fetched:",`tiles=${x.tiles?.length??0},`,`actions=${x.actions?.length??0},`,`theme=${x.theme?.name??"none"}`),x.actions?.length>0&&console.log("[Syntro Bootstrap] Actions in config:",x.actions.map((F,P)=>`[${P}] ${F.kind}${F.anchorId?` anchor="${F.anchorId}"`:""}${F.label?` "${F.label}"`:""}`).join(", "));let M=x,z=v.getRequiredApps(M);return z.length>0?console.log("[Syntro Bootstrap] Required external apps:",z.join(", ")):Z("Syntro Bootstrap","No external apps required (all executors are built-in)"),z.length>0&&await v.loadAppsForConfig(M).then(async P=>{let J=P.filter(D=>D.success),G=P.filter(D=>!D.success);J.length>0&&console.log(`[Syntro Bootstrap] Apps loaded from CDN: ${J.map(D=>D.appId).join(", ")}`);let pe=G.filter(D=>!A.has(D.appId));pe.length>0&&(console.error("[Syntro Bootstrap] Apps FAILED to load from CDN:",pe.map(D=>`${D.appId} (${D.error})`).join(", ")),pe.forEach(D=>A.add(D.appId)));for(let D of z)if(p.apps.has(D))try{await p.apps.activate(D),console.log(`[Syntro Bootstrap] App activated: ${D}`)}catch(L){console.error(`[Syntro Bootstrap] Failed to activate app: ${D}`,L)}else console.error(`[Syntro Bootstrap] App "${D}" required by config but NOT registered.`,`Available apps: [${Array.from(p.apps.list?.()??[]).join(", ")}]`)}),x}:void 0;return{canvas:await Tm({...t.canvas,fetcher:k,integrations:{experiments:f,telemetry:b},editorUrl:c,runtime:p}),runtime:p,experiments:f,telemetry:b,sessionMetrics:w,appLoader:v}}var rk={init:y5,encodeToken:yb,decodeToken:ep};typeof window<"u"&&(window.Syntro=rk);var ak="2026-02-26T00:05:29.265Z (80f166c0b)";if(typeof window<"u"){console.log(`[Syntro Runtime] Build: ${ak}`);let t=window.SynOS,e=t?.appRegistry||Fl;window.SynOS={...t,appRegistry:e,_runtimeBuild:ak,React:ok.default,ReactDOM:{...b5,createPortal:tp.createPortal,flushSync:tp.flushSync}},Cw(e)}export{Ic as ANIMATION_KEYFRAMES,W3 as ActivationConfigZ,pT as AddClassZ,R3 as AnchorStateZ,L3 as AnchorVisibleConditionZ,kd as AppRegistry,O3 as AugmentationZ,nT as BadgePositionZ,bT as BadgeZ,k3 as BoundingBoxZ,ql as CanvasEvents,Xm as CanvasRecipeZ,HT as ConditionZ,Zf as ContextManager,U3 as CooldownActiveConditionZ,Zy as CtaButtonZ,vm as DEFAULT_COOLDOWN,mm as DEFAULT_TTL,IT as DecisionStrategyZ,$3 as DismissedConditionZ,ns as EVENT_SCHEMA_VERSION,Kf as EventBus,V3 as EventCountConditionZ,J3 as EventFilterZ,H3 as EventOccurredConditionZ,UT as EventSourceZ,Gf as ExecutorRegistry,Z3 as ExternalStrategyZ,a5 as FrequencyEntryZ,F3 as FrequencyLimitConditionZ,E4 as HighlightStepZ,tT as HighlightStyleZ,vT as HighlightZ,mT as InsertHtmlZ,oT as InsertPositionZ,gm as MAX_VISIBLE_TOASTS,aT as ModalContentZ,ST as ModalZ,G3 as ModelStrategyZ,ET as MountWidgetZ,wT as NavigateZ,Dc as NavigationMonitor,Q3 as NormalizedEventZ,hm as NotificationToastStack,E3 as PageContextZ,C3 as PageHistoryEntryZ,N3 as PageUrlConditionZ,TT as ParallelZ,iT as PlacementZ,yT as PulseZ,ak as RUNTIME_SDK_BUILD,YT as RUNTIME_VERSION,hT as RemoveClassZ,D3 as RouteConditionZ,Y3 as RouteFilterZ,q3 as RuleStrategyZ,j3 as RuleZ,M3 as RuntimeContextZ,xm as RuntimeProvider,Mr as SDK_SCHEMA_VERSION,cm as SDK_VERSION,qT as STATIC_SLOT_STYLES,P3 as ScoreStrategyZ,uT as ScrollBehaviorZ,Gy as ScrollLogicalPositionZ,xT as ScrollToZ,WE as SelectorZ,AT as SequenceZ,A3 as SessionContextZ,B3 as SessionMetricConditionZ,rf as SessionMetricTracker,fT as SetAttrZ,gT as SetStyleZ,dT as SetTextZ,qw as ShadowCanvasOverlay,$w as ShadowRootProvider,Yw as SmartCanvasApp,dm as SmartCanvasController,Cm as SmartCanvasElement,yB as SmartCanvasPortal,_e as StandardEvents,I3 as StateEqualsConditionZ,Xf as StateStore,r5 as StoredValueZ,rk as Syntro,Pl as TileCard,sz as TileWheel,rT as TooltipContentZ,w4 as TooltipStepZ,sT as TooltipTriggerZ,_T as TooltipZ,cT as TourStepForSchemaZ,kT as TourZ,z3 as ViewportConditionZ,T3 as ViewportContextZ,CT as WaitZ,lT as WidgetConfigZ,Jf as WidgetRegistry,Fl as appRegistry,ab as applyStaticSlotStyles,em as cleanupAppContext,Pg as contentRuntime,x3 as coreActionStepSchemas,Py as createActionEngine,Jg as createAppContext,nm as createAppLoader,Jo as createCanvasConfigFetcher,Wy as createContextManager,Ky as createDecisionEngine,Xy as createEventAccumulator,Nc as createEventBus,Gm as createGrowthBookClient,Jm as createNoopClient,mB as createOverlayRecipeFetcher,Iy as createPostHogClient,Jy as createPostHogNormalizer,Zm as createSessionMetricTracker,Tm as createSmartCanvas,zw as createSmartCanvasController,hb as createSmartCanvasRuntime,rb as createStateStore,ub as createSurfaceContainer,fb as createSurfaces,ep as decodeToken,yb as encodeToken,DT as evaluate,OT as evaluateCondition,MT as evaluateRule,Yf as evaluateRuleStrategy,Wf as evaluateScoreStrategy,LT as evaluateSync,Ki as executorRegistry,_M as getAntiFlickerSnippet,sw as getAppIdFromActionKind,tm as getAppIdFromWidgetId,a3 as getExecutor,Qf as getSlotAnchorId,Hc as getSlotType,db as getSlotZIndex,jy as hasExecutor,zd as interpolateTemplate,ow as isCoreActionKind,ym as matchEvent,dz as needsMigration,BT as normalizePostHogEvent,Qg as overlaysRuntime,Zl as parseVersion,lb as playEnterAnimation,cb as playExitAnimation,Ld as registerConfigPredicates,Qw as registerSmartCanvasElement,um as resolveConfigUri,ob as setupAdjacentPositioning,sb as setupInlinePositioning,$T as shouldNormalizeEvent,iN as useDecision,bm as useNotifications,_m as useNotifyWatcher,wm as usePageContext,Hi as useRuntime,$d as useRuntimeContext,tN as useRuntimeEvents,nN as useRuntimeState,JM as useSessionContext,Pw as useShadowCanvasConfig,Id as useShadowRoot,eN as useViewportContext,ta as validateAction,qy as validateActions,x$ as validateActivationConfig,_$ as validateCondition,uz as validateConfig,B$ as validateEventFilter,F8 as validateFrequencyEntry,z$ as validateNormalizedEvent,fB as validateRecipe,l$ as validateRuntimeContext,U8 as validateStoredValue,S$ as validateStrategy,pb as widgetRegistry};
|
|
449
|
+
`)),new Error(`Batch validation failed: ${k}`)}let v=c(),S=[],T=[];try{for(let k of p){let C=await g(k);S.push(C),T.push(C)}}catch(k){console.error(`[ActionEngine] Batch apply FAILED at action ${T.length+1}/${p.length}.`,`Successfully applied: ${T.length}. Rolling back...`,k);for(let C of T)try{await C.revert()}catch{}throw k}return{id:v,handles:S,async revertAll(){for(let k=S.length-1;k>=0;k--)try{await S[k].revert()}catch(C){console.error(`[ActionEngine] Error reverting action ${S[k].id}:`,C)}},isApplied(){return S.every(k=>k.isApplied())}}}function b(p){return ta(p)}function w(){return Array.from(l.values()).map(p=>({id:p.id,action:p.action,adaptiveId:p.adaptiveId,appliedTs:p.appliedTs,state:p.state}))}function d(){for(let p of l.values())if(p.state==="applied")try{p.cleanup()}catch(m){console.error("[ActionEngine] Error during cleanup:",m)}l.clear()}return{apply:g,applyBatch:_,validate:b,getActive:w,destroy:d}}var tT=y.object({color:y.string().optional(),scrimOpacity:y.number().min(0).max(1).optional(),paddingPx:y.number().optional(),radiusPx:y.number().optional()}).strict(),nT=y.enum(["top-left","top-right","bottom-left","bottom-right"]),iT=y.enum(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),Zy=y.object({label:y.string(),actionId:y.string(),primary:y.boolean().optional()}).strict(),rT=y.object({title:y.string().optional(),body:y.string(),ctaButtons:y.array(Zy).optional()}).strict(),aT=y.object({title:y.string().optional(),body:y.string()}).strict(),oT=y.enum(["before","after","prepend","append","replace"]),sT=y.enum(["immediate","hover","click"]),lT=y.object({widgetId:y.string(),props:y.record(y.unknown()).optional(),priority:y.number().optional()}).strict(),cT=y.object({id:y.string(),action:y.any(),route:y.string().optional(),onAction:y.record(y.string()).optional()}).strict(),uT=y.enum(["auto","smooth","instant"]),Gy=y.enum(["start","center","end","nearest"]),dT=y.object({kind:y.literal("content:setText"),anchorId:y.string(),text:y.string(),label:y.string().optional()}).strict(),fT=y.object({kind:y.literal("content:setAttr"),anchorId:y.string(),attr:y.string(),value:y.string(),label:y.string().optional()}).strict(),pT=y.object({kind:y.literal("content:addClass"),anchorId:y.string(),className:y.string(),label:y.string().optional()}).strict(),hT=y.object({kind:y.literal("content:removeClass"),anchorId:y.string(),className:y.string(),label:y.string().optional()}).strict(),gT=y.object({kind:y.literal("content:setStyle"),anchorId:y.string(),styles:y.record(y.string()),label:y.string().optional()}).strict(),mT=y.object({kind:y.literal("content:insertHtml"),anchorId:y.string(),html:y.string(),position:oT,label:y.string().optional()}).strict(),vT=y.object({kind:y.literal("overlays:highlight"),anchorId:y.string(),style:tT.optional(),duration:y.number().optional(),label:y.string().optional()}).strict(),yT=y.object({kind:y.literal("overlays:pulse"),anchorId:y.string(),duration:y.number().optional(),label:y.string().optional()}).strict(),bT=y.object({kind:y.literal("overlays:badge"),anchorId:y.string(),content:y.string(),position:nT.optional(),label:y.string().optional()}).strict(),_T=y.object({kind:y.literal("overlays:tooltip"),anchorId:y.string(),content:rT,trigger:sT.optional(),placement:iT.optional(),waitFor:y.string().optional(),label:y.string().optional()}).strict(),ST=y.object({kind:y.literal("overlays:modal"),content:aT,size:y.enum(["sm","md","lg"]).optional(),blocking:y.boolean().optional(),scrim:y.object({opacity:y.number().min(0).max(1).optional()}).strict().optional(),dismiss:y.object({onEsc:y.boolean().optional(),closeButton:y.boolean().optional(),timeoutMs:y.number().min(0).optional()}).strict().optional(),ctaButtons:y.array(Zy).optional(),waitFor:y.string().optional(),label:y.string().optional()}).strict(),xT=y.object({kind:y.literal("navigation:scrollTo"),anchorId:y.string(),behavior:uT.optional(),block:Gy.optional(),inline:Gy.optional(),label:y.string().optional()}).strict(),wT=y.object({kind:y.literal("navigation:navigate"),url:y.string(),target:y.enum(["_self","_blank"]).optional(),label:y.string().optional()}).strict(),ET=y.object({kind:y.literal("core:mountWidget"),slot:y.string(),widget:lT,label:y.string().optional()}).strict(),CT=y.object({kind:y.literal("core:wait"),durationMs:y.number().min(0).optional(),event:y.string().optional(),label:y.string().optional()}).strict(),AT=y.object({kind:y.literal("core:sequence"),actions:y.array(y.any()),label:y.string().optional()}).strict(),TT=y.object({kind:y.literal("core:parallel"),actions:y.array(y.any()),waitFor:y.enum(["all","any"]).optional(),label:y.string().optional()}).strict(),kT=y.object({kind:y.literal("core:tour"),tourId:y.string(),steps:y.array(cT).min(1),startStep:y.string().optional(),autoStart:y.boolean().optional(),label:y.string().optional()}).strict(),x3=[{defName:"setText",schema:dT},{defName:"setAttr",schema:fT},{defName:"addClass",schema:pT},{defName:"removeClass",schema:hT},{defName:"setStyle",schema:gT},{defName:"insertHtml",schema:mT},{defName:"highlight",schema:vT},{defName:"pulse",schema:yT},{defName:"badge",schema:bT},{defName:"tooltip",schema:_T},{defName:"modal",schema:ST},{defName:"scrollTo",schema:xT},{defName:"navigate",schema:wT},{defName:"mountWidget",schema:ET},{defName:"wait",schema:CT},{defName:"sequence",schema:AT},{defName:"parallel",schema:TT},{defName:"tour",schema:kT}];function w3(){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 Yy(t,e){if(!e)return;let n;try{n=new URL(t).pathname}catch{n=t}if(e.exclude){for(let i of e.exclude)if(RT(n,i))return}if(e.include){for(let i of e.include)if(RT(n,i))return i;return}return n}function RT(t,e){let n=t.replace(/\/$/,"")||"/",i=e.replace(/\/$/,"")||"/";if(n===i)return!0;let r=i.replace(/:[^/]+/g,"[^/]+").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(n)}var Zf=class{constructor(e={}){V(this,"context");V(this,"previousContext");V(this,"listeners",new Set);V(this,"telemetry");V(this,"routes");V(this,"navigation");V(this,"cleanupFns",[]);if(this.telemetry=e.telemetry,this.routes=e.routes,this.navigation=e.navigation,this.context=w3(),this.previousContext={...this.context},e.telemetry?.getSessionId){let n=e.telemetry.getSessionId();n&&(this.context.session.sessionId=n)}e.initialPageHistory&&(this.context.session.pageHistory=e.initialPageHistory),this.context.page.routeId=Yy(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 n=Yy(this.context.page.url,this.routes);n!==this.context.page.routeId&&this.updateContext({page:{...this.context.page,routeId:n}})}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,n=()=>{clearTimeout(e),e=setTimeout(()=>{this.updateViewport()},100)};if(window.addEventListener("resize",n),this.cleanupFns.push(()=>window.removeEventListener("resize",n)),this.navigation){let i=this.navigation.subscribe(()=>this.updatePage());this.cleanupFns.push(i)}else{let i=()=>{this.updatePage()};window.addEventListener("popstate",i),this.cleanupFns.push(()=>window.removeEventListener("popstate",i));let r=history.pushState.bind(history),a=history.replaceState.bind(history);history.pushState=(...o)=>{r(...o),queueMicrotask(()=>this.updatePage())},history.replaceState=(...o)=>{a(...o),queueMicrotask(()=>this.updatePage())},this.cleanupFns.push(()=>{history.pushState=r,history.replaceState=a})}}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:n}=document,i=Yy(e,this.routes),r={url:e,title:n,routeId:i};(r.url!==this.context.page.url||r.title!==this.context.page.title||r.routeId!==this.context.page.routeId)&&(r.url!==this.context.page.url&&this.addPageToHistory(r.url),this.updateContext({page:r}))}addPageToHistory(e){let n={url:e,ts:Date.now()},i=[...this.context.session.pageHistory||[],n];i.length>50&&i.shift(),this.context.session.pageHistory=i}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(n){console.error("[ContextManager] Listener error:",n)}}};function Wy(t={}){return new Zf(t)}var E3=y.object({url:y.string(),routeId:y.string().optional(),title:y.string().optional(),locale:y.string().optional()}),C3=y.object({url:y.string(),ts:y.number()}),A3=y.object({sessionId:y.string(),startTs:y.number(),pageHistory:y.array(C3).optional()}),T3=y.object({width:y.number(),height:y.number()}),k3=y.object({x:y.number(),y:y.number(),w:y.number(),h:y.number()}),R3=y.object({anchorId:y.string(),present:y.boolean(),visible:y.boolean().optional(),boundingBox:k3.optional()}),O3=y.record(y.string(),y.union([y.number(),y.string(),y.boolean(),y.undefined()])),M3=y.object({page:E3,session:A3,viewport:T3,anchors:y.array(R3).optional(),augmented:O3.optional()});function l$(t){return M3.safeParse(t)}function OT(t,e){let{context:n,state:i,events:r}=e;switch(t.type){case"page_url":{let{url:a}=t,o=n.page.url,s=a.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*");return new RegExp(`^${s}$`).test(o)}case"route":return n.page.routeId===t.routeId;case"anchor_visible":{let a=n.anchors?.find(o=>o.anchorId===t.anchorId);switch(t.state){case"visible":return a?.visible===!0;case"present":return a?.present===!0;case"absent":return!a?.present;default:return!1}}case"event_occurred":{if(!r)return!1;let a=t.withinMs??6e4;return r.hasRecentEvent(t.eventName,a)}case"state_equals":return!1;case"viewport":{let{width:a,height:o}=n.viewport;return!(t.minWidth!==void 0&&a<t.minWidth||t.maxWidth!==void 0&&a>t.maxWidth||t.minHeight!==void 0&&o<t.minHeight||t.maxHeight!==void 0&&o>t.maxHeight)}case"session_metric":{if(!i)return!1;let a=i.getSessionMetric(t.key),{operator:o,threshold:s}=t;switch(o){case"gte":return a>=s;case"lte":return a<=s;case"eq":return a===s;case"gt":return a>s;case"lt":return a<s;default:return!1}}case"dismissed":{if(!i)return t.inverted??!1;let a=i.isDismissed(t.key);return t.inverted?!a:a}case"cooldown_active":{if(!i)return t.inverted??!1;let a=i.isCooldownActive(t.key);return t.inverted?!a:a}case"frequency_limit":{if(!i)return t.inverted??!1;let o=i.getFrequencyCount(t.key)>=t.limit;return t.inverted?!o:o}case"event_count":{if(!e.accumulator)return!1;let a=t,o=e.accumulator.getCount(a.key,a.withinMs);switch(a.operator){case"gte":return o>=a.count;case"lte":return o<=a.count;case"eq":return o===a.count;case"gt":return o>a.count;case"lt":return o<a.count;default:return!1}}default:return console.warn("[RuleStrategy] Unknown condition type:",t.type),!1}}function MT(t,e){let n=[];for(let i of t.conditions){let r=OT(i,e);if(n.push({condition:i,result:r}),!r)return{matched:!1,conditionResults:n}}return{matched:!0,conditionResults:n}}function Yf(t,e){for(let n=0;n<t.rules.length;n++){let i=t.rules[n],{matched:r,conditionResults:a}=MT(i,e);if(r)return{value:i.value,isFallback:!1,matchInfo:{strategyType:"rules",matchedRuleIndex:n,evaluatedConditions:a}}}return{value:t.default,isFallback:!0,matchInfo:{strategyType:"rules"}}}function Wf(t,e){let{context:n}=e,i=n.augmented?.[t.field];return i===void 0||typeof i!="number"?{value:t.below,isFallback:!0,matchInfo:{strategyType:"score"}}:{value:i>=t.threshold?t.above:t.below,isFallback:!1,matchInfo:{strategyType:"score"}}}function NT(t,e){let{state:n,events:i,sessionMetrics:r,accumulator:a}=e;return{context:t,state:n?{isDismissed:o=>n.dismissals.isDismissed(o),isCooldownActive:o=>n.cooldowns.isActive(o),getFrequencyCount:o=>n.frequency.count(o),getSessionMetric:o=>r?.get(o)??0}:void 0,events:i?{hasRecentEvent:(o,s)=>i.hasRecentEvent(o,s)}:void 0,accumulator:a?{getCount:(o,s)=>a.getCount(o,s)}:void 0}}async function DT(t,e,n={}){let i=NT(e,n);switch(t.type){case"rules":return Yf(t,i);case"score":return Wf(t,i);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 LT(t,e,n={}){let i=NT(e,n);switch(t.type){case"rules":return Yf(t,i);case"score":return Wf(t,i);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 Ky(t){return{evaluate:(e,n)=>DT(e,n,t),evaluateSync:(e,n)=>LT(e,n,t)}}var N3=y.object({type:y.literal("page_url"),url:y.string()}),D3=y.object({type:y.literal("route"),routeId:y.string()}),L3=y.object({type:y.literal("anchor_visible"),anchorId:y.string(),state:y.enum(["visible","present","absent"])}),H3=y.object({type:y.literal("event_occurred"),eventName:y.string(),withinMs:y.number().optional()}),I3=y.object({type:y.literal("state_equals"),key:y.string(),value:y.unknown()}),z3=y.object({type:y.literal("viewport"),minWidth:y.number().optional(),maxWidth:y.number().optional(),minHeight:y.number().optional(),maxHeight:y.number().optional()}),B3=y.object({type:y.literal("session_metric"),key:y.string(),operator:y.enum(["gte","lte","eq","gt","lt"]),threshold:y.number()}),$3=y.object({type:y.literal("dismissed"),key:y.string(),inverted:y.boolean().optional()}),U3=y.object({type:y.literal("cooldown_active"),key:y.string(),inverted:y.boolean().optional()}),F3=y.object({type:y.literal("frequency_limit"),key:y.string(),limit:y.number(),inverted:y.boolean().optional()}),V3=y.object({type:y.literal("event_count"),key:y.string(),operator:y.enum(["gte","lte","eq","gt","lt"]),count:y.number().int().min(0),withinMs:y.number().positive().optional()}),HT=y.discriminatedUnion("type",[N3,D3,L3,H3,I3,z3,B3,$3,U3,F3,V3]),j3=y.object({conditions:y.array(HT),value:y.unknown()}),q3=y.object({type:y.literal("rules"),rules:y.array(j3),default:y.unknown()}),P3=y.object({type:y.literal("score"),field:y.string(),threshold:y.number(),above:y.unknown(),below:y.unknown()}),G3=y.object({type:y.literal("model"),modelId:y.string(),inputs:y.array(y.string()),outputMapping:y.record(y.string(),y.unknown()),default:y.unknown()}),Z3=y.object({type:y.literal("external"),endpoint:y.string(),method:y.enum(["GET","POST"]).optional(),default:y.unknown(),timeoutMs:y.number().optional()}),IT=y.discriminatedUnion("type",[q3,P3,G3,Z3]),Y3=y.object({include:y.array(y.string()).optional(),exclude:y.array(y.string()).optional()}),W3=y.object({routes:Y3.optional(),strategy:IT.optional()});function _$(t){return HT.safeParse(t)}function S$(t){return IT.safeParse(t)}function x$(t){return W3.safeParse(t)}function Xy(t){let{eventBus:e,stateStore:n}=t,i=new Map,r=new Set,a=null,o=n.ns("accumulator");function s(c){let u=!1;for(let f of i.values()){if(!f.predicate(c))continue;let h=o.get(f.stateKey)||{count:0};h.count++,f.needsTimestamps&&(h.timestamps||(h.timestamps=[]),h.timestamps.push(c.ts),h.timestamps.length>200&&(h.timestamps=h.timestamps.slice(-200))),o.set(f.stateKey,h),u=!0}if(u)for(let f of r)try{f()}catch(h){console.error("[EventAccumulator] Subscriber error:",h)}}function l(){a||i.size===0||(a=e.subscribe(s))}return{register(c,u,f=!1){let h=`ev:${c}`,g=i.get(h);if(g){f&&!g.needsTimestamps&&(g.needsTimestamps=!0);return}i.set(h,{stateKey:h,needsTimestamps:f,predicate:u}),l()},getCount(c,u){let f=`ev:${c}`,h=o.get(f);if(!h)return 0;if(u===void 0||!h.timestamps)return h.count;let g=Date.now()-u;return h.timestamps.filter(_=>_>=g).length},subscribe(c){return r.add(c),()=>{r.delete(c)}},destroy(){a&&(a(),a=null),i.clear(),r.clear()}}}function Qy(t,e){return e?!(e.names&&e.names.length>0&&!e.names.includes(t.name)||e.patterns&&e.patterns.length>0&&!e.patterns.some(i=>{try{return new RegExp(i).test(t.name)}catch{return!1}})||e.sources&&e.sources.length>0&&!e.sources.includes(t.source)):!0}var Kf=class{constructor(e={}){V(this,"subscriptions",new Set);V(this,"history",[]);V(this,"maxHistorySize");this.maxHistorySize=e.maxHistorySize??100}subscribe(e,n){let i,r;typeof e=="function"?(i=void 0,r=e):(i=e,r=n);let a={filter:i,callback:r};return this.subscriptions.add(a),()=>{this.subscriptions.delete(a)}}publish(e,n,i="canvas"){let r={ts:Date.now(),name:e,source:i,props:n,schemaVersion:ns};this.publishEvent(r)}publishEvent(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift();for(let n of this.subscriptions)if(Qy(e,n.filter))try{n.callback(e)}catch(i){console.error("[EventBus] Subscriber error:",i)}}getRecent(e,n){let i=this.history;return e&&(i=i.filter(r=>Qy(r,e))),n&&n>0&&(i=i.slice(-n)),i}hasRecentEvent(e,n,i){let r=Date.now()-n;return this.history.some(a=>a.name===e&&a.ts>=r&&(i===void 0||a.source===i))}countRecentEvents(e,n){let i=this.history.filter(r=>Qy(r,e));if(n!==void 0){let r=Date.now()-n;i=i.filter(a=>a.ts>=r)}return i.length}clearHistory(){this.history=[]}getSubscriberCount(){return this.subscriptions.size}};function Nc(t={}){return new Kf(t)}var zT={$autocapture:"ui.click",$click:_e.UI_CLICK,$scroll:_e.UI_SCROLL,$input:_e.UI_INPUT,$change:_e.UI_CHANGE,$submit:_e.UI_SUBMIT,$pageview:_e.NAV_PAGE_VIEW,$pageleave:_e.NAV_PAGE_LEAVE,$session_start:"session.start",$identify:"user.identify"};function K3(t){let e=t.event;if(typeof e!="string")return"posthog.unknown";if(zT[e])return zT[e];if(e==="$autocapture"){let n=t.properties?.$tag_name,i=t.properties?.$event_type;return i==="submit"?_e.UI_SUBMIT:i==="change"?_e.UI_CHANGE:n==="input"||n==="textarea"?_e.UI_INPUT:_e.UI_CLICK}return e.startsWith("$")?e.replace("$","posthog."):`posthog.${e}`}function X3(t){let e={},n=t.properties||{},i=n.$elements;return n.$tag_name?e.tagName=n.$tag_name:i?.[0]?.tag_name&&(e.tagName=i[0].tag_name),n.$el_text&&(e.elementText=n.$el_text),i&&(e.elements=i),n.$current_url&&(e.url=n.$current_url),n.$pathname&&(e.pathname=n.$pathname),n.$host&&(e.host=n.$host),n.$viewport_width&&(e.viewportWidth=n.$viewport_width),n.$viewport_height&&(e.viewportHeight=n.$viewport_height),n.$session_id&&(e.sessionId=n.$session_id),n.$scroll_depth&&(e.scrollDepth=n.$scroll_depth),n.$scroll_percentage&&(e.scrollPercentage=n.$scroll_percentage),e.originalEvent=t.event,e}function BT(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:K3(t),source:"posthog",props:X3(t),schemaVersion:ns}}function $T(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 Jy(t){return(e,n)=>{if(typeof e!="string")return;let i={event:e,properties:n,timestamp:Date.now()};if($T(i)){let r=BT(i);t(r)}}}var UT=y.enum(["posthog","canvas","derived"]),Q3=y.object({ts:y.number(),name:y.string(),source:UT,props:y.record(y.string(),y.unknown()).optional(),schemaVersion:y.string()}),J3=y.object({names:y.array(y.string()).optional(),patterns:y.array(y.string()).optional(),sources:y.array(UT).optional()});function z$(t){return Q3.safeParse(t)}function B$(t){return J3.safeParse(t)}var Dc=class{constructor(){V(this,"listeners",new Set);V(this,"capturedPushState");V(this,"capturedReplaceState");V(this,"wasNative");V(this,"destroyed",!1);V(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,n){if(!this.destroyed)for(let i of this.listeners)try{i(e,n)}catch{}}isNativeFunction(e){try{return Function.prototype.toString.call(e).includes("[native code]")}catch{return!1}}};var eb="cooldown:";function FT(t){return{set(e,n){let i=eb+e,r=Date.now()+n;t.set(i,r)},isActive(e){return this.remaining(e)>0},remaining(e){let n=eb+e,i=t.get(n);if(i===void 0)return 0;let r=i-Date.now();return r<=0?(t.remove(n),0):r},clear(e){let n=eb+e;t.remove(n)}}}var Lc="dismissed:";function VT(t,e){return{mark(n,i=!1){let r=Lc+n;(i?e:t).set(r,!0)},isDismissed(n){let i=Lc+n;return t.has(i)||e.has(i)},clear(n){let i=Lc+n;t.remove(i),e.remove(i)},clearAll(){for(let n of t.keys())n.startsWith(Lc)&&t.remove(n);for(let n of e.keys())n.startsWith(Lc)&&e.remove(n)}}}var tb="freq:";function jT(t){function e(n){let i=tb+n,r=t.get(i);if(r){if(r.resetAt&&Date.now()>=r.resetAt){t.remove(i);return}return r}}return{increment(n,i){let r=tb+n,a=e(n),o=(a?.count??0)+1,s={count:o,resetAt:a?.resetAt??(i?Date.now()+i:void 0)};return t.set(r,s),o},count(n){return e(n)?.count??0},reset(n){let i=tb+n;t.remove(i)},hasReachedLimit(n,i){return this.count(n)>=i}}}var e5="syntro";function nb(t,e){let n=`${e}:`;return{get(i){if(t)try{let r=t.getItem(n+i);if(!r)return;let a=JSON.parse(r);if(a.expiresAt&&Date.now()>=a.expiresAt){t.removeItem(n+i);return}return a.value}catch{return}},set(i,r,a){if(t)try{let o={value:r,expiresAt:a?Date.now()+a:void 0};t.setItem(n+i,JSON.stringify(o))}catch(o){console.warn("[StateStore] Failed to save:",o)}},remove(i){t&&t.removeItem(n+i)},has(i){return t?this.get(i)!==void 0:!1},keys(){if(!t)return[];let i=[];for(let r=0;r<t.length;r++){let a=t.key(r);a?.startsWith(n)&&i.push(a.slice(n.length))}return i},clear(){if(!t)return;let i=this.keys();for(let r of i)t.removeItem(n+r)}}}function ib(t){let e=new Map,n=`${t}:`;return{get(i){let r=e.get(n+i);if(r){if(r.expiresAt&&Date.now()>=r.expiresAt){e.delete(n+i);return}return r.value}},set(i,r,a){e.set(n+i,{value:r,expiresAt:a?Date.now()+a:void 0})},remove(i){e.delete(n+i)},has(i){return this.get(i)!==void 0},keys(){let i=[];for(let r of e.keys())r.startsWith(n)&&i.push(r.slice(n.length));return i},clear(){for(let i of e.keys())i.startsWith(n)&&e.delete(i)}}}var Xf=class{constructor(e={}){V(this,"session");V(this,"user");V(this,"dismissals");V(this,"cooldowns");V(this,"frequency");V(this,"namespace");V(this,"namespacedStorages",new Map);this.namespace=e.namespace??e5,typeof window<"u"?(this.session=nb(typeof sessionStorage<"u"?sessionStorage:void 0,this.namespace),this.user=nb(typeof localStorage<"u"?localStorage:void 0,this.namespace)):(this.session=ib(this.namespace),this.user=ib(this.namespace)),this.dismissals=VT(this.session,this.user),this.cooldowns=FT(this.user),this.frequency=jT(this.session)}ns(e){let n=`${this.namespace}:${e}`;if(!this.namespacedStorages.has(n)){let i=typeof window<"u"&&typeof sessionStorage<"u"?nb(sessionStorage,n):ib(n);this.namespacedStorages.set(n,i)}return this.namespacedStorages.get(n)}};function rb(t={}){return new Xf(t)}function Hc(t){return t.startsWith("inline:")?"inline":t.startsWith("adjacent:")?"adjacent":"static"}function Qf(t){return t.startsWith("inline:")?t.slice(7):t.startsWith("adjacent:")?t.slice(9):null}var qT={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"}},Ic={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:[]},PT={duration:200,easing:"cubic-bezier(0.16, 1, 0.3, 1)",fill:"forwards"};function ab(t,e,n){let i=qT[e];Object.assign(t.style,i),n&&(n.maxWidth&&(t.style.maxWidth=n.maxWidth),n.maxHeight&&(t.style.maxHeight=n.maxHeight),n.minWidth&&(t.style.minWidth=n.minWidth),n.minHeight&&(t.style.minHeight=n.minHeight))}function ob(t,e,n){let i=n.placement==="auto"?"bottom":n.placement,r=[Ed(n.offset?{mainAxis:n.offset.y,crossAxis:n.offset.x}:8)];return n.flip!==!1&&r.push(Ad()),n.shift!==!1&&r.push(Cd({padding:8})),t.style.position="absolute",t.style.zIndex="2147483646",wd(e,t,async()=>{let{x:o,y:s,strategy:l}=await Td(e,t,{placement:i,middleware:r});Object.assign(t.style,{position:l,left:`${o}px`,top:`${s}px`})})}function sb(t,e,n="append"){return t.style.position="relative",t.style.display="inline-block",n==="prepend"?e.insertBefore(t,e.firstChild):e.appendChild(t),()=>{t.remove()}}function lb(t,e){return e==="none"||Ic[e].length===0?null:t.animate(Ic[e],PT)}function cb(t,e){if(e==="none"||Ic[e].length===0)return Promise.resolve();let n=[...Ic[e]].reverse(),i=t.animate(n,PT);return new Promise(r=>{i.onfinish=()=>r(),i.oncancel=()=>r()})}function ub(t,e){let n=document.createElement("div");return n.setAttribute("data-syntro-surface",t),n.setAttribute("data-syntro-mount-id",e),n.className="syntro-surface",Object.assign(n.style,{pointerEvents:"auto",boxSizing:"border-box",overflow:"auto"}),n}function db(t){switch(Hc(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 GT(t){if(typeof window.Sanitizer=="function")try{let l=new window.Sanitizer({}).sanitizeToFragment(t),c=document.createElement("div");return c.append(l),c.innerHTML}catch{}let n=document.createElement("template");n.innerHTML=t;let i=n.content,r=document.createTreeWalker(i,NodeFilter.SHOW_ELEMENT,null),a=new Set(["b","strong","i","em","u","span","div","p","br","ul","ol","li","code","pre","small","sup","sub","a","button"]),o=[];for(;r.nextNode();){let s=r.currentNode,l=s.tagName.toLowerCase();if(!a.has(l)){o.push(s);continue}for(let c of Array.from(s.attributes)){let u=c.name.toLowerCase(),f=c.value.trim().toLowerCase(),h=u.startsWith("on"),g=(u==="href"||u==="src")&&f.startsWith("javascript:");(h||g)&&s.removeAttribute(c.name)}}for(let s of o){for(;s.firstChild;)s.parentNode?.insertBefore(s.firstChild,s);s.remove()}return n.innerHTML=(i.firstChild,n.innerHTML)}var t5=0;function fb(t){let{overlayRoot:e,eventBus:n,anchorResolver:i,defaultAnimation:r="fade",widgetRegistry:a}=t,o=new Map,s=new Map,l=new Map;function c(){return`mount-${++t5}`}function u(v,S){n&&n.publish(v,S)}function f(v){let S=l.get(v);if(S){let T=w(v);for(let A of S)try{A(T)}catch(k){console.error("[Surfaces] State callback error:",k)}}}let h=new Map;function g(v,S,T){switch(S.type){case"html":v.innerHTML=GT(S.content);return;case"widget":{if(a?.has(S.widgetId)){let A=a.mount(S.widgetId,v,S.config);return T&&h.set(T,A),()=>{A.unmount(),T&&h.delete(T)}}console.warn(`[Surfaces] Widget not found: ${S.widgetId}`),v.innerHTML=`<div data-widget-id="${S.widgetId}" data-widget-missing="true">Widget: ${S.widgetId}</div>`;return}case"custom":return S.mount(v);case"react":v.innerHTML="<div data-react-component>React Component</div>";return;default:console.warn("[Surfaces] Unknown content type");return}}function _(v,S,T){let A=c(),k=Hc(v),C=T?.priority??0,x=T?.animation??r,M=T?.exclusive??!0,z=o.get(v);if(z&&M){if(z.options.priority>C)throw new Error(`Slot ${v} is occupied by higher priority content (${z.options.priority} > ${C})`);b(z)}let F=ub(v,A);F.style.zIndex=String(db(v));let P;if(k==="static")ab(F,v,T?.constraints),e.appendChild(F);else if(k==="inline"){let D=Qf(v);if(!D)throw new Error(`Invalid inline slot: ${v}`);if(!i)throw new Error("Anchor resolver required for inline slots");let L=i(D);if(!L)throw new Error(`Anchor not found for inline slot: ${D}`);P=sb(F,L)}else if(k==="adjacent"){let D=Qf(v);if(!D)throw new Error(`Invalid adjacent slot: ${v}`);if(!i)throw new Error("Anchor resolver required for adjacent slots");let L=i(D);if(!L)throw new Error(`Anchor not found for adjacent slot: ${D}`);e.appendChild(F),P=ob(F,L,T?.position??{placement:"bottom"})}let J=g(F,S,A);lb(F,x);let G={id:A,slot:v,content:S,options:{priority:C,exclusive:M,animation:x,position:T?.position??{placement:"auto"},constraints:T?.constraints??{},adaptiveId:T?.adaptiveId,autoUnmountOnRouteChange:T?.autoUnmountOnRouteChange??!0},container:F,cleanup:()=>{P?.(),J?.()},mountedAt:Date.now()};return o.set(v,G),s.set(v,(s.get(v)??0)+1),u("surface.mounted",{slot:v,id:A,adaptiveId:T?.adaptiveId}),f(v),{id:A,update(D){let L=o.get(v);if(!L||L.id!==A)throw new Error("Mount no longer active");let ue=h.get(A);if(ue){if(D.type==="widget"){ue.update(D.config),L.content=D;return}ue.unmount(),h.delete(A)}L.container.innerHTML="";let dn=g(L.container,D,A);if(L.content=D,dn){let We=L.cleanup;L.cleanup=()=>{We?.(),dn()}}},setOptions(D){let L=o.get(v);if(!L||L.id!==A)throw new Error("Mount no longer active");D.priority!==void 0&&(L.options.priority=D.priority),D.animation!==void 0&&(L.options.animation=D.animation),D.constraints&&k==="static"&&(D.constraints.maxWidth&&(L.container.style.maxWidth=D.constraints.maxWidth),D.constraints.maxHeight&&(L.container.style.maxHeight=D.constraints.maxHeight),D.constraints.minWidth&&(L.container.style.minWidth=D.constraints.minWidth),D.constraints.minHeight&&(L.container.style.minHeight=D.constraints.minHeight)),f(v)},async unmount(){let D=o.get(v);!D||D.id!==A||await b(D)},isMounted(){return o.get(v)?.id===A},getContainer(){let D=o.get(v);return D?.id===A?D.container:null}}}async function b(v){await cb(v.container,v.options.animation),v.cleanup?.(),v.container.remove(),o.delete(v.slot),u("surface.unmounted",{slot:v.slot,id:v.id}),f(v.slot)}function w(v){let S=o.get(v);return{slot:v,occupied:!!S,currentPriority:S?.options.priority,currentAdaptiveId:S?.options.adaptiveId,mountCount:s.get(v)??0,currentMountId:S?.id}}function d(v,S){let T=l.get(v);return T||(T=new Set,l.set(v,T)),T.add(S),()=>{T?.delete(S),T?.size===0&&l.delete(v)}}function p(v,S){let T=o.get(v);return T?S!==void 0?S>=T.options.priority:!1:!0}function m(){for(let v of o.values())try{v.cleanup?.(),v.container.remove()}catch(S){console.error("[Surfaces] Error during cleanup:",S)}o.clear(),l.clear()}return{mount:_,getState:w,onStateChange:d,canMount:p,destroy:m}}var Jf=class{constructor(){V(this,"widgets",new Map);V(this,"mountedWidgets",new Map);V(this,"mountIdCounter",0);V(this,"runtimeRef");V(this,"listeners",new Set)}bindRuntime(e){this.runtimeRef=e}register(e,n,i="custom",r){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:n,source:i,metadata:r}),this.notify({type:"registered",widgetId:e})}unregister(e){let n=this.widgets.get(e);return n?n.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[n,i]of this.widgets.entries())i.source===e&&this.widgets.delete(n)}get(e){return this.widgets.get(e)?.widget}getRegistration(e){return this.widgets.get(e)}has(e){return this.widgets.has(e)}mount(e,n,i){let r=this.widgets.get(e);if(!r)throw new Error(`Widget not found: ${e}`);let a=`widget-mount-${++this.mountIdCounter}`;n.setAttribute("data-widget-mount-id",a),n.setAttribute("data-widget-id",e);let o={...i,runtime:this.runtimeRef},s=r.widget.mount(n,o);return this.mountedWidgets.set(a,{cleanup:s??void 0,container:n}),{widgetId:e,container:n,unmount:()=>{let c=this.mountedWidgets.get(a);c&&(c.cleanup?.(),this.mountedWidgets.delete(a),n.removeAttribute("data-widget-mount-id"),n.removeAttribute("data-widget-id"),n.innerHTML="")},update:c=>{if(r.widget.update)r.widget.update(n,c);else{let u=this.mountedWidgets.get(a);if(u){u.cleanup?.(),n.innerHTML="";let f={...c,runtime:this.runtimeRef},h=r.widget.mount(n,f);u.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(n=>n.source===e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(let n of this.listeners)try{n(e)}catch(i){console.error("[WidgetRegistry] Listener error:",i)}}destroy(){for(let[e,n]of this.mountedWidgets.entries())n.cleanup?.(),n.container.innerHTML="";this.mountedWidgets.clear()}},pb=new Jf;var YT="2.0.0";function n5(t,e){if(!e)return!0;let n;try{n=new URL(t).pathname}catch{n=t}let i=n.replace(/\/$/,"")||"/";if(e.exclude){for(let r of e.exclude)if(ZT(i,r))return!1}if(e.include&&e.include.length>0){for(let r of e.include)if(ZT(i,r))return!0;return!1}return!0}function ZT(t,e){let n=e.replace(/\/$/,"")||"/";if(t===n)return!0;let i=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/:[^/]+/g,"[^/]+");return new RegExp(`^${i}$`).test(t)}function i5(t){try{return document.querySelector(t)}catch{return null}}function hb(t={}){let{telemetry:e,sessionMetrics:n,routes:i,mode:r="production",namespace:a}=t,o=t.widgets??pb,s=t.executors??Ki,l=t.apps??Fl,c=new Dc,u=Wy({telemetry:e,routes:i,navigation:c}),f=t.events??Nc(),h=rb({namespace:a}),g=Xy({eventBus:f,stateStore:h}),_=Ky({state:h,events:f,sessionMetrics:n,accumulator:g}),b=Iw(),w=v=>i5(v),d=fb({overlayRoot:b,eventBus:f,anchorResolver:w,widgetRegistry:o}),p=Py({overlayRoot:b,eventBus:f,surfaces:d,anchorResolver:w,executorRegistry:s,subscribeNavigation:v=>c.subscribe(v)}),m={telemetry:e,context:u,events:f,state:h,sessionMetrics:n,actions:p,surfaces:d,widgets:o,executors:s,apps:l,accumulator:g,navigation:c,version:YT,mode:r,async evaluate(v){return _.evaluate(v,u.get())},evaluateSync(v){return _.evaluateSync(v,u.get())},async filterTiles(v){let S=u.get().page.url,T=[];for(let A of v){let k=A.activation;if(!k){T.push(A);continue}if(!n5(S,k.routes))continue;if(!k.strategy){T.push(A);continue}(await this.evaluate(k.strategy)).value&&T.push(A)}return T},setRoutes(v){u.setRoutes(v)},destroy(){l.unbind().catch(v=>{console.error("[Runtime] Error unbinding apps registry:",v)}),g.destroy(),c.destroy(),u.destroy(),p.destroy(),d.destroy()}};return l.bind(m),o.bindRuntime(m),m}var r5=y.object({value:y.unknown(),expiresAt:y.number().optional()}),a5=y.object({count:y.number(),resetAt:y.number().optional()});function U8(t){return r5.safeParse(t)}function F8(t){return a5.safeParse(t)}var WT={growthbook:t=>Gm({...t,autoInit:!0})};function KT(t,e){let n=WT[t];if(!n)throw new Error(`Unknown experiment provider: ${t}. Supported: ${Object.keys(WT).join(", ")}`);return n(e)}var o5=["cdn.syntrologie.com","localhost","127.0.0.1"];function s5(t){try{let e=new URL(t),n=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!n?(console.warn("[SmartCanvas] CDN URL must use HTTPS:",t),!1):o5.some(r=>e.hostname===r)?!0:(console.warn("[SmartCanvas] CDN host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid CDN URL:",t),!1}}var gb=class{constructor(e){V(this,"name","cdn");V(this,"url");V(this,"integrity");if(this.url=`${e.baseUrl}/${e.configId}.json`,this.integrity=e.integrity,!s5(this.url))throw new Error(`[SmartCanvas] CDN URL not allowed: ${this.url}`)}async fetch(){let e=performance.now(),n=await fetch(this.url,{credentials:"omit",cache:"default"});if(!n.ok)throw new Error(`[SmartCanvas] Failed to fetch config from CDN (${n.status})`);let i=await n.text();if(this.integrity){let l=await l5(i),c=this.integrity.replace("sha384-","");if(l!==c)throw new Error(`[SmartCanvas] Config integrity check failed. Expected ${c}, got ${l}`)}let r=JSON.parse(i),a=performance.now()-e,o=n.headers.get("cache-control"),s=n.headers.get("age");return{config:r,meta:{source:"cdn",fetchTimeMs:a,cached:o?.includes("public")??!1,cacheAge:s?parseInt(s,10):void 0}}}};async function l5(t){let n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-384",n),r=new Uint8Array(i);return btoa(String.fromCharCode(...r))}function XT(t){return new gb(t)}var c5="syntro_exp",u5="syntro_var",mb=class{constructor(e){V(this,"name","experiments");V(this,"client");V(this,"featureKey");V(this,"manifestKey");V(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 r=new URLSearchParams(window.location.search),a=r.get(c5),o=r.get(u5);if(a&&o!==null&&this.client.setForcedVariations){let s=parseInt(o,10);Number.isNaN(s)||(console.log(`[SmartCanvas] Preview mode: forcing "${a}" to variation ${s}`),this.client.setForcedVariations({[a]:s}))}}if(this.manifestKey||this.variantFlagPrefix){let r=this.fetchMultiFlag();if(r){let a=performance.now()-e;return{config:r,meta:{source:"experiments",fetchTimeMs:a,cached:!0}}}}let n=this.client.getFeatureValue?.(this.featureKey,null);if(!n||typeof n!="object")throw new Error(`[SmartCanvas] Feature "${this.featureKey}" not found or invalid. Ensure the feature is configured in your experiment platform.`);let i=performance.now()-e;return{config:n,meta:{source:"experiments",fetchTimeMs:i,cached:!0}}}fetchMultiFlag(){let e=this.getVariantFlagKeys();return!e||e.length===0?null:Nd(this.client,e)}getVariantFlagKeys(){if(this.manifestKey){let e=this.client.getFeatureValue?.(this.manifestKey,null);if(e&&typeof e=="object"){let n=e.variant_flags;if(n&&n.length>0)return n}}if(this.variantFlagPrefix&&this.client.getAllFeatures){let e=this.client.getAllFeatures();return Object.keys(e).filter(n=>n.startsWith(this.variantFlagPrefix))}return[]}};function QT(t){return new mb(t)}var d5="https://cdn.syntrologie.com/configs",JT={cdn:t=>{if(!t.configId)throw new Error("CDN fetcher requires 'configId' option");return XT({baseUrl:t.baseUrl??d5,configId:t.configId,integrity:t.integrity})},experiments:t=>{if(!t.featureKey)throw new Error("Experiments fetcher requires 'featureKey' option");return QT({featureKey:t.featureKey})}};function ek(t,e={}){let n=JT[t];if(!n)throw new Error(`Unknown config fetcher type: ${t}. Supported: ${Object.keys(JT).join(", ")}`);return n(e)}var tk={posthog:t=>Iy(t),noop:()=>Jm()};function nk(t,e){let n=tk[t];if(!n)throw new Error(`Unknown telemetry provider: ${t}. Supported: ${Object.keys(tk).join(", ")}`);return n(e)}var vb="syn_";function ep(t){if(!t.startsWith(vb))throw new Error("Invalid Syntro token: must start with 'syn_'");let n=t.slice(vb.length).replace(/-/g,"+").replace(/_/g,"/"),i=atob(n),r=JSON.parse(i);if(r.v!==1)throw new Error(`Unsupported token version: ${r.v}`);return r}function yb(t){let e=JSON.stringify(t),n=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return vb+n}function Xi(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 f5(){if(typeof window>"u")return Z("Syntro Bootstrap","isEditorMode: not in browser"),!1;let t=Ra(),n=!!(Nr()?.token&&t?.mode==="editor");return Z("Syntro Bootstrap","isEditorMode:",n),n}function p5(){if(typeof window>"u")return Z("Syntro Bootstrap","isAuditMode: not in browser"),!1;let t=Ra(),n=!!(Nr()?.token&&t?.mode==="audit");return Z("Syntro Bootstrap","isAuditMode:",n),n}function h5(){if(typeof window>"u")return Z("Syntro Bootstrap","isReviewMode: not in browser"),!1;let t=Ra(),n=!!(Nr()?.token&&t?.mode==="review");return Z("Syntro Bootstrap","isReviewMode:",n),n}var ik="syntro_segment_attributes";function g5(){if(typeof window>"u")return{};try{let t=localStorage.getItem(ik);if(t){let e=JSON.parse(t);return Z("Syntro Bootstrap","Loaded cached segment attributes:",e),e}}catch(t){ln("Syntro Bootstrap","Failed to load cached segment attributes:",t)}return{}}function m5(t){if(!(typeof window>"u"))try{localStorage.setItem(ik,JSON.stringify(t)),Z("Syntro Bootstrap","Cached segment attributes:",t)}catch(e){ln("Syntro Bootstrap","Failed to cache segment attributes:",e)}}function v5(t){if(!t)return{};let e={};for(let[n,i]of Object.entries(t))n.startsWith("in_segment_")&&(e[n]=i===!0);return e}async function y5(t){lm(),Z("Syntro Bootstrap","====== INIT ======"),Z("Syntro Bootstrap","Options:",{hasToken:!!t.token,tokenPrefix:`${t.token?.slice(0,15)}...`,hasCanvasOptions:!!t.canvas});let e=f5(),n=p5(),i=h5(),r=e?"editor":n?"audit":i?"review":null;if(console.log(`[DIAG] Mode detection: editor=${e}, audit=${n}, review=${i}, sdkMode=${r}`),console.log("[DIAG] editorSource:",Nr()),console.log("[DIAG] editorConf:",Ra()),Z("Syntro Bootstrap","SDK mode:",r??"normal"),!r&&typeof window<"u"){let x=!!window.__SYNTRO_EDITOR_PARAMS__,M=!!window.__SYNTRO_AUDIT_LEGEND__,z=!!window.__SYNTRO_REVIEW_DATA__;if(x||M||z){let F=[x&&"__SYNTRO_EDITOR_PARAMS__",M&&"__SYNTRO_AUDIT_LEGEND__",z&&"__SYNTRO_REVIEW_DATA__"].filter(Boolean);console.warn(`[Syntro Bootstrap] \u26A0 Mode detection returned null but mode-specific globals found: ${F.join(", ")}. This suggests URL params were lost (redirect?) but the service worker injected mode data. Check if replaceState failed or if page JS changed the URL before init().`)}}console.log(`[DIAG] Token resolution: options.token=${t.token?t.token.slice(0,15)+"...":"null"}`);let a=t.token;if(!a&&r){let M=Ra()?.syntro_token;M?.startsWith("syn_")&&(a=M,Z("Syntro Bootstrap",`\u2713 Using syntro_token from editor_conf (${r} mode)`))}let o;if(a)if(a.startsWith("syn_"))Z("Syntro Bootstrap","Token starts with syn_, decoding..."),o=ep(a),lm(o.d);else if(r)Z("Syntro Bootstrap",`\u2713 Non-syn_ token allowed (${r} mode)`);else throw Dd("Syntro Bootstrap","\u274C Token does not start with syn_ and NOT in editor/audit/review mode!"),Dd("Syntro Bootstrap","Token received:",a),new Error("Invalid Syntro token: must start with 'syn_'");else if(r)Z("Syntro Bootstrap",`\u2713 No token, but ${r} mode - proceeding`);else throw Dd("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=Xi("NEXT_PUBLIC_SYNTRO_EXPERIMENT_HOST")||Xi("VITE_SYNTRO_EXPERIMENT_HOST")||o?.eh,l=Xi("NEXT_PUBLIC_SYNTRO_TELEMETRY_HOST")||Xi("VITE_SYNTRO_TELEMETRY_HOST")||o?.th,c=Xi("NEXT_PUBLIC_SYNTRO_EDITOR_URL")||Xi("VITE_SYNTRO_EDITOR_URL")||t.canvas?.editorUrl,u=g5();Z("Syntro Bootstrap","Phase 1: Using cached segment attributes:",u);let f,h=Nc();console.log("[Syntro Bootstrap] EventBus created");let g=Jy(x=>{h.publishEvent(x)}),_=x=>{Z("Syntro Bootstrap","Phase 2: PostHog feature flags loaded");let M=v5(x);if(Z("Syntro Bootstrap","Segment flags from PostHog:",M),m5(M),f){let F={...w?.getAll?.()??{},...M};Z("Syntro Bootstrap","Updating GrowthBook with attributes:",F),f.setAttributes?.(F)}},b;if(o?.t){let x=o.t==="noop"?"noop":"posthog";b=nk(x,{apiKey:o.t,apiHost:l,enableFeatureFlags:!0,onFeatureFlagsLoaded:_,onCapture:g}),console.log(`[Syntro Bootstrap] Telemetry client created (${x}) with EventBus wiring`)}let w;o?.e&&(f=KT("growthbook",{clientKey:o.e,apiHost:s,attributes:u,onExperimentViewed:b?.trackExperiment?(x,M,z)=>{b.trackExperiment(x,M,z)}:void 0})),t.enableSessionMetrics&&(w=Zm({experiments:f,onMetricChange:(x,M)=>{Z("Syntro Bootstrap",`Session metric changed: ${x} = ${M}`)}}),Z("Syntro Bootstrap","SessionMetricTracker created"));let d="production";e?d="editor":n?d="audit":Xi("NODE_ENV")==="development"&&(d="development");let p=hb({telemetry:b,sessionMetrics:w,mode:d,events:h});Z("Syntro Bootstrap","Runtime created:",{version:p.version,mode:p.mode,hasContext:!!p.context,hasEvents:!!p.events,hasState:!!p.state}),Z("Syntro Bootstrap","Core app executors already registered");let m=t.cdnBase||Xi("NEXT_PUBLIC_SYNTRO_CDN_BASE")||Xi("VITE_SYNTRO_CDN_BASE")||"https://cdn.syntrologie.com",v=nm({cdnBase:m,registry:p.apps,onLoadStart:x=>{Z("Syntro Bootstrap",`Loading app from CDN: ${x}`)},onLoadEnd:(x,M,z)=>{M?Z("Syntro Bootstrap",`App loaded successfully: ${x}`):ln("Syntro Bootstrap",`Failed to load app: ${x}`,z)}});typeof window<"u"&&(window.SynOS={...window.SynOS,appRegistry:p.apps,runtime:p,version:p.version},Z("Syntro Bootstrap","Global SynOS object exposed"));let S=p.apps.list?.()??[];console.log(`[DIAG] Activation loop: ${S.length} apps in registry:`,S.map(x=>`${x.manifest.id}(${x.state})`).join(", "));for(let x of S)if(x.state==="registered")try{await p.apps.activate(x.manifest.id),console.log(`[DIAG] Activated: ${x.manifest.id} \u2192 widgets: [${p.widgets.list().join(", ")}]`)}catch(M){console.error(`[DIAG] FAILED to activate: ${x.manifest.id}`,M),ln("Syntro Bootstrap",`Failed to auto-activate built-in app: ${x.manifest.id}`,M)}if(console.log(`[DIAG] Activation complete. Total widgets: [${p.widgets.list().join(", ")}]`),f?.refreshFeatures)try{await f.refreshFeatures(),Z("Syntro Bootstrap","GrowthBook features loaded")}catch(x){ln("Syntro Bootstrap","Failed to load GrowthBook features:",x)}let T;if(t.fetcher)T=t.fetcher;else if(o?.f){let x=ek(o.f,o.o??{});T=async()=>{let M=await x.fetch();return{...M.config,tiles:M.config.tiles??[]}}}else f&&(T=Jo({experiments:f}));let A=new Set,k=T?async()=>{let x=await T();console.log("[Syntro Bootstrap] Config fetched:",`tiles=${x.tiles?.length??0},`,`actions=${x.actions?.length??0},`,`theme=${x.theme?.name??"none"}`),x.actions?.length>0&&console.log("[Syntro Bootstrap] Actions in config:",x.actions.map((F,P)=>`[${P}] ${F.kind}${F.anchorId?` anchor="${F.anchorId}"`:""}${F.label?` "${F.label}"`:""}`).join(", "));let M=x,z=v.getRequiredApps(M);return z.length>0?console.log("[Syntro Bootstrap] Required external apps:",z.join(", ")):Z("Syntro Bootstrap","No external apps required (all executors are built-in)"),z.length>0&&await v.loadAppsForConfig(M).then(async P=>{let J=P.filter(D=>D.success),G=P.filter(D=>!D.success);J.length>0&&console.log(`[Syntro Bootstrap] Apps loaded from CDN: ${J.map(D=>D.appId).join(", ")}`);let pe=G.filter(D=>!A.has(D.appId));pe.length>0&&(console.error("[Syntro Bootstrap] Apps FAILED to load from CDN:",pe.map(D=>`${D.appId} (${D.error})`).join(", ")),pe.forEach(D=>A.add(D.appId)));for(let D of z)if(p.apps.has(D))try{await p.apps.activate(D),console.log(`[Syntro Bootstrap] App activated: ${D}`)}catch(L){console.error(`[Syntro Bootstrap] Failed to activate app: ${D}`,L)}else console.error(`[Syntro Bootstrap] App "${D}" required by config but NOT registered.`,`Available apps: [${Array.from(p.apps.list?.()??[]).join(", ")}]`)}),x}:void 0;return{canvas:await Tm({...t.canvas,fetcher:k,integrations:{experiments:f,telemetry:b},editorUrl:c,runtime:p}),runtime:p,experiments:f,telemetry:b,sessionMetrics:w,appLoader:v}}var rk={init:y5,encodeToken:yb,decodeToken:ep};typeof window<"u"&&(window.Syntro=rk);var ak="2026-02-26T00:14:39.554Z (610e0365d)";if(typeof window<"u"){console.log(`[Syntro Runtime] Build: ${ak}`);let t=window.SynOS,e=t?.appRegistry||Fl;window.SynOS={...t,appRegistry:e,_runtimeBuild:ak,React:ok.default,ReactDOM:{...b5,createPortal:tp.createPortal,flushSync:tp.flushSync}},Cw(e)}export{Ic as ANIMATION_KEYFRAMES,W3 as ActivationConfigZ,pT as AddClassZ,R3 as AnchorStateZ,L3 as AnchorVisibleConditionZ,kd as AppRegistry,O3 as AugmentationZ,nT as BadgePositionZ,bT as BadgeZ,k3 as BoundingBoxZ,ql as CanvasEvents,Xm as CanvasRecipeZ,HT as ConditionZ,Zf as ContextManager,U3 as CooldownActiveConditionZ,Zy as CtaButtonZ,vm as DEFAULT_COOLDOWN,mm as DEFAULT_TTL,IT as DecisionStrategyZ,$3 as DismissedConditionZ,ns as EVENT_SCHEMA_VERSION,Kf as EventBus,V3 as EventCountConditionZ,J3 as EventFilterZ,H3 as EventOccurredConditionZ,UT as EventSourceZ,Gf as ExecutorRegistry,Z3 as ExternalStrategyZ,a5 as FrequencyEntryZ,F3 as FrequencyLimitConditionZ,E4 as HighlightStepZ,tT as HighlightStyleZ,vT as HighlightZ,mT as InsertHtmlZ,oT as InsertPositionZ,gm as MAX_VISIBLE_TOASTS,aT as ModalContentZ,ST as ModalZ,G3 as ModelStrategyZ,ET as MountWidgetZ,wT as NavigateZ,Dc as NavigationMonitor,Q3 as NormalizedEventZ,hm as NotificationToastStack,E3 as PageContextZ,C3 as PageHistoryEntryZ,N3 as PageUrlConditionZ,TT as ParallelZ,iT as PlacementZ,yT as PulseZ,ak as RUNTIME_SDK_BUILD,YT as RUNTIME_VERSION,hT as RemoveClassZ,D3 as RouteConditionZ,Y3 as RouteFilterZ,q3 as RuleStrategyZ,j3 as RuleZ,M3 as RuntimeContextZ,xm as RuntimeProvider,Mr as SDK_SCHEMA_VERSION,cm as SDK_VERSION,qT as STATIC_SLOT_STYLES,P3 as ScoreStrategyZ,uT as ScrollBehaviorZ,Gy as ScrollLogicalPositionZ,xT as ScrollToZ,WE as SelectorZ,AT as SequenceZ,A3 as SessionContextZ,B3 as SessionMetricConditionZ,rf as SessionMetricTracker,fT as SetAttrZ,gT as SetStyleZ,dT as SetTextZ,qw as ShadowCanvasOverlay,$w as ShadowRootProvider,Yw as SmartCanvasApp,dm as SmartCanvasController,Cm as SmartCanvasElement,yB as SmartCanvasPortal,_e as StandardEvents,I3 as StateEqualsConditionZ,Xf as StateStore,r5 as StoredValueZ,rk as Syntro,Pl as TileCard,sz as TileWheel,rT as TooltipContentZ,w4 as TooltipStepZ,sT as TooltipTriggerZ,_T as TooltipZ,cT as TourStepForSchemaZ,kT as TourZ,z3 as ViewportConditionZ,T3 as ViewportContextZ,CT as WaitZ,lT as WidgetConfigZ,Jf as WidgetRegistry,Fl as appRegistry,ab as applyStaticSlotStyles,em as cleanupAppContext,Pg as contentRuntime,x3 as coreActionStepSchemas,Py as createActionEngine,Jg as createAppContext,nm as createAppLoader,Jo as createCanvasConfigFetcher,Wy as createContextManager,Ky as createDecisionEngine,Xy as createEventAccumulator,Nc as createEventBus,Gm as createGrowthBookClient,Jm as createNoopClient,mB as createOverlayRecipeFetcher,Iy as createPostHogClient,Jy as createPostHogNormalizer,Zm as createSessionMetricTracker,Tm as createSmartCanvas,zw as createSmartCanvasController,hb as createSmartCanvasRuntime,rb as createStateStore,ub as createSurfaceContainer,fb as createSurfaces,ep as decodeToken,yb as encodeToken,DT as evaluate,OT as evaluateCondition,MT as evaluateRule,Yf as evaluateRuleStrategy,Wf as evaluateScoreStrategy,LT as evaluateSync,Ki as executorRegistry,_M as getAntiFlickerSnippet,sw as getAppIdFromActionKind,tm as getAppIdFromWidgetId,a3 as getExecutor,Qf as getSlotAnchorId,Hc as getSlotType,db as getSlotZIndex,jy as hasExecutor,zd as interpolateTemplate,ow as isCoreActionKind,ym as matchEvent,dz as needsMigration,BT as normalizePostHogEvent,Qg as overlaysRuntime,Zl as parseVersion,lb as playEnterAnimation,cb as playExitAnimation,Ld as registerConfigPredicates,Qw as registerSmartCanvasElement,um as resolveConfigUri,ob as setupAdjacentPositioning,sb as setupInlinePositioning,$T as shouldNormalizeEvent,iN as useDecision,bm as useNotifications,_m as useNotifyWatcher,wm as usePageContext,Hi as useRuntime,$d as useRuntimeContext,tN as useRuntimeEvents,nN as useRuntimeState,JM as useSessionContext,Pw as useShadowCanvasConfig,Id as useShadowRoot,eN as useViewportContext,ta as validateAction,qy as validateActions,x$ as validateActivationConfig,_$ as validateCondition,uz as validateConfig,B$ as validateEventFilter,F8 as validateFrequencyEntry,z$ as validateNormalizedEvent,fB as validateRecipe,l$ as validateRuntimeContext,U8 as validateStoredValue,S$ as validateStrategy,pb as widgetRegistry};
|
|
450
450
|
/*! Bundled license information:
|
|
451
451
|
|
|
452
452
|
react/cjs/react.production.js:
|