@syntrologie/runtime-sdk 2.7.0 → 2.8.0-canary.2
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/CAPABILITIES.md +1 -1
- package/dist/{chunk-UUFNSBJN.js → chunk-V5KPS4PK.js} +2 -2
- package/dist/{chunk-UUFNSBJN.js.map → chunk-V5KPS4PK.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 +2 -2
- 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 +2 -2
- package/dist/version.d.ts +1 -1
- package/package.json +7 -7
package/dist/smart-canvas.esm.js
CHANGED
|
@@ -126,7 +126,7 @@ Error generating stack: `+r.message+`
|
|
|
126
126
|
s.textContent = '.${e} { ${a} }';
|
|
127
127
|
document.head.appendChild(s);
|
|
128
128
|
document.documentElement.className += ' ${e}';
|
|
129
|
-
})();`}function of(t,e,a="first-match"){for(let r of e){let n=t.getFeatureValue?.(r,null);if(!n||typeof n!="object")continue;let o=n,i=o.tiles&&o.tiles.length>0,s=o.actions&&o.actions.length>0;if(i||s)return{tiles:o.tiles??[],actions:o.actions??[],fetchedAt:o.fetchedAt??new Date().toISOString(),...o.schemaVersion&&{schemaVersion:o.schemaVersion},...o.configVersion&&{configVersion:o.configVersion},...o.canvasTitle&&{canvasTitle:o.canvasTitle},...o.theme&&{theme:o.theme},...o.launcher&&{launcher:o.launcher}}}return null}var jg=!1;function HL(){if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("syntro_debug")==="true"}catch{return!1}}function Gg(t){if(HL()){jg=!0;return}jg=t??!1}function tD(){return HL()?!0:jg}function Y(t,e,a){tD()&&(a!==void 0?console.log(`[${t}]`,e,a):console.log(`[${t}]`,e))}function ma(t,e,a){a!==void 0?console.warn(`[${t}]`,e,a):console.warn(`[${t}]`,e)}function sf(t,e,a){a!==void 0?console.error(`[${t}]`,e,a):console.error(`[${t}]`,e)}var Wg="2.
|
|
129
|
+
})();`}function of(t,e,a="first-match"){for(let r of e){let n=t.getFeatureValue?.(r,null);if(!n||typeof n!="object")continue;let o=n,i=o.tiles&&o.tiles.length>0,s=o.actions&&o.actions.length>0;if(i||s)return{tiles:o.tiles??[],actions:o.actions??[],fetchedAt:o.fetchedAt??new Date().toISOString(),...o.schemaVersion&&{schemaVersion:o.schemaVersion},...o.configVersion&&{configVersion:o.configVersion},...o.canvasTitle&&{canvasTitle:o.canvasTitle},...o.theme&&{theme:o.theme},...o.launcher&&{launcher:o.launcher}}}return null}var jg=!1;function HL(){if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("syntro_debug")==="true"}catch{return!1}}function Gg(t){if(HL()){jg=!0;return}jg=t??!1}function tD(){return HL()?!0:jg}function Y(t,e,a){tD()&&(a!==void 0?console.log(`[${t}]`,e,a):console.log(`[${t}]`,e))}function ma(t,e,a){a!==void 0?console.warn(`[${t}]`,e,a):console.warn(`[${t}]`,e)}function sf(t,e,a){a!==void 0?console.error(`[${t}]`,e,a):console.error(`[${t}]`,e)}var Wg="2.8.0-canary.2";var qn="2.0";var aD=["api.syntrologie.com","cdn.syntrologie.com","localhost","127.0.0.1"];function rD(t){try{let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(console.warn("[SmartCanvas] Config URI must use HTTPS:",t),!1):aD.some(n=>e.hostname===n)?!0:(console.warn("[SmartCanvas] Config URI host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid config URI:",t),!1}}function nD(t){if(typeof window>"u")return!1;try{return new URL(t).origin===window.location.origin}catch{return!1}}var UL="syntro_config_cache",oD=1440*60*1e3;function qL(){try{return typeof localStorage<"u"&&localStorage!==null}catch{return!1}}function iD(t,e){if(qL())try{let a={config:t,timestamp:Date.now(),sdkVersion:e};localStorage.setItem(UL,JSON.stringify(a))}catch{}}function sD(t){if(!qL())return null;try{let e=localStorage.getItem(UL);if(!e)return null;let a=JSON.parse(e);return!a.config||typeof a.timestamp!="number"||!a.sdkVersion||a.sdkVersion!==t||Date.now()-a.timestamp>oD?null:a.config}catch{return null}}var Zg=({configUri:t,experiments:e,featureKey:a="smart-canvas-config-uri"})=>{if(t)return t;let r=e?.getFeatureValue?.(a,null);if(r)return r};function lD(t,e,a){if(e){let r=t.getFeatureValue?.(e,null);if(r&&typeof r=="object"){let n=r.variant_flags;if(n&&n.length>0)return n}}if(t.getAllFeatures){let r=t.getAllFeatures();return a?Object.keys(r).filter(n=>n.startsWith(a)):Object.keys(r)}return[]}var ls=({configUri:t,experiments:e,featureKey:a,credentials:r,configFeatureKey:n="smart-canvas-config",manifestKey:o,variantFlagPrefix:i,sdkVersion:s})=>async()=>{if(e&&n){let c=e.getFeatureValue?.(n,null);if(c&&typeof c=="object")return Y("SmartCanvas Config","Resolved config directly from feature flag",c),c}if(e&&(o||i||e.getAllFeatures)){let c=lD(e,o,i);if(c.length>0){let d=of(e,c);if(d)return Y("SmartCanvas Config","Resolved config from variant flags",d),d}}let l=Zg({configUri:t,experiments:e,featureKey:a});if(!l)return Y("SmartCanvas Config","No config available \u2014 returning empty config"),{tiles:[],actions:[],fetchedAt:new Date().toISOString()};if(!rD(l))throw new Error(`SmartCanvas: config URI not allowed: ${l}`);let u=r??(nD(l)?"include":"omit");try{let c=await fetch(l,{credentials:u,headers:{"X-SDK-Version":Wg,"X-SDK-Schema-Version":qn}});if(!c.ok)throw new Error(`SmartCanvas: failed to fetch config (${c.status})`);let d=await c.json();return Y("SmartCanvas Config","Fetched config from URI",d),s&&iD(d,s),d}catch(c){if(s){let d=sD(s);if(d)return Y("SmartCanvas Config","Serving config from offline cache"),d}throw c}};var uD=["cdn.syntrologie.com","api.syntrologie.com","dev-api.syntrologie.com","localhost","127.0.0.1",".syntrologie.com"];function zL(t){if(typeof window>"u")return null;let a=new URLSearchParams(window.location.search).get(t);if(!a)return null;try{let r=a.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(r))}catch(r){return ma("Syntro Runtime",`Failed to decode ${t}:`,r),null}}var us,cs;function eu(){if(us==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.token)us={token:t.token,api_base:t.apiBase||""},console.log(`[DIAG] getEditorSource: from __SYNTRO_EDITOR_PARAMS__ (token=${us.token.slice(0,15)}...)`);else{let e=zL("editor_source");e&&(us=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 us??null}function lf(){if(cs==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.mode)cs={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=${cs.mode})`);else{let e=zL("editor_conf");e&&(cs=e),console.log(`[DIAG] getEditorConf: from URL param \u2192 ${e?`mode=${e.mode}`:"NULL"}`)}}return cs??null}function cD(t){Y("Syntro Runtime","Validating editor URL:",t);try{if(t.startsWith("/"))return Y("Syntro Runtime","\u2713 Relative URL allowed (same-origin):",t),!0;let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(ma("Syntro Runtime","\u274C Editor URL must use HTTPS:",t),!1):uD.some(n=>n.startsWith(".")?e.hostname.endsWith(n)||e.hostname===n.slice(1):e.hostname===n)?(Y("Syntro Runtime","\u2713 Editor URL validated"),!0):(ma("Syntro Runtime","\u274C Editor URL host not in allowlist:",e.hostname),!1)}catch(e){return ma("Syntro Runtime",`\u274C Invalid editor URL: ${t}`,e),!1}}var uf=()=>{let t=lf();return!eu()?.token||!t?.mode?null:t.mode};function dD(){return eu()?.token??null}function fD(){return eu()?.api_base??null}var Jl=null,VL=async t=>{if(Y("Syntro Runtime","====== LOAD EDITOR SDK ======"),typeof window>"u"){Y("Syntro Runtime","Not in browser - skipping editor SDK load");return}if(window.SyntroEditor){Y("Syntro Runtime","Editor SDK already loaded (window.SyntroEditor exists)");return}if(Jl)return Y("Syntro Runtime","Editor SDK load already in progress, waiting..."),Jl;let e=typeof t=="string"?{editorUrl:t}:t??{};if(e.editorUrl==="skip"){Y("Syntro Runtime",'editorUrl="skip" \u2014 deferring to caller'),Y("Syntro Runtime","================================");return}let a=fD(),n=(a?`${a}/api/editor/sdk/editor-sdk.js`:null)||e.editorUrl;if(!n){ma("Syntro Runtime","\u274C No editor SDK URL available (no api_base, no editorUrl option)"),Y("Syntro Runtime","================================");return}let o=dD();if(!o){ma("Syntro Runtime","\u274C No token found in editor_source."),Y("Syntro Runtime","================================");return}let i=`${n}?token=${encodeURIComponent(o)}`;if(Y("Syntro Runtime","Editor URL:",i),Y("Syntro Runtime","Options:",{hasIntegrity:!!e.integrity,hasEditorUrl:!!n,hasApiBase:!!a,tokenPrefix:`${o.slice(0,10)}...`}),!cD(n)){console.error("[Syntro Runtime] \u274C BLOCKED: Editor from untrusted URL:",n),Y("Syntro Runtime","================================");return}return Y("Syntro Runtime","\u2713 URL validated, injecting script tag..."),Jl=new Promise((s,l)=>{let u=document.createElement("script");u.src=i,u.async=!0,e.integrity&&(u.integrity=e.integrity,u.crossOrigin="anonymous",Y("Syntro Runtime","SRI integrity check enabled")),u.onload=()=>{Y("Syntro Runtime","\u2713 Editor SDK script loaded successfully"),Y("Syntro Runtime","================================"),s()},u.onerror=c=>{console.error("[Syntro Runtime] \u274C Failed to load Editor SDK:",c),console.error("[Syntro Runtime] URL attempted:",i),Y("Syntro Runtime","================================"),Jl=null,l(c)},document.head.appendChild(u),Y("Syntro Runtime","Script tag appended to <head>")}),Jl};var pD=new Set(["tag_name","$el_text"]);function hD(t){return pD.has(t)||t.startsWith("attr__")}function $L(t,e){return t.equals!==void 0?e===t.equals:t.contains!==void 0?typeof e=="string"&&e.includes(t.contains):!1}function mD(t){let{events:e,match:a}=t;return r=>{if(!e.includes(r.name))return!1;if(a){for(let[n,o]of Object.entries(a))if(hD(n)){let i=r.props?.elements;if(!i||!i.some(l=>$L(o,l[n])))return!1}else if(!$L(o,r.props?.[n]))return!1}return!0}}function jL(t,e){for(let a of t.rules)for(let r of a.conditions)if(r.type==="event_count"&&r.key){let n=r.counter,o=n?mD(n):()=>!0;e.register(r.key,o)}}function cf(t,e,a){for(let r of t){let n=r.props;if(!n)continue;let o=n.actions;if(o)for(let i of o)i.triggerWhen?.type==="rules"&&jL(i.triggerWhen,e)}if(a)for(let r of a){let n=r;n.triggerWhen?.type==="rules"&&jL(n.triggerWhen,e)}}var cr=null;function WL(t){cr&&cr!==t?t.appendChild(cr):cr=t;let e=t.getRootNode();e instanceof ShadowRoot&&gD(e)}function ZL(){return cr||(cr=document.createElement("div"),cr.id="syntro-overlays",Object.assign(cr.style,{position:"fixed",inset:"0",zIndex:"2147483645",pointerEvents:"none"}),document.body.appendChild(cr)),cr}var GL=!1;function gD(t){if(GL)return;let e=`
|
|
130
130
|
:host {
|
|
131
131
|
--syntro-surface: var(--sc-overlay-background, #0f1318);
|
|
132
132
|
--syntro-fg: var(--sc-overlay-text-color, #cbd0d7);
|
|
@@ -461,7 +461,7 @@ ${l}
|
|
|
461
461
|
`).replace(/\r/g,`
|
|
462
462
|
`)).length,n=0;n<r;n++){var i=t.charCodeAt(n),s=null;i<128?a++:s=i>127&&i<2048?String.fromCharCode(i>>6|192,63&i|128):String.fromCharCode(i>>12|224,i>>6&63|128,63&i|128),nn(s)||(a>e&&(o+=t.substring(e,a)),o+=s,e=a=n+1)}return a>e&&(o+=t.substring(e,t.length)),o},MN=!!sy||!!iy,J1="text/plain",fp=function(t,e,a){var r;a===void 0&&(a=!0);var[n,o]=t.split("?"),i=W({},e),s=(r=o?.split("&").map((u=>{var c,[d,h]=u.split("="),g=a&&(c=i[d])!==null&&c!==void 0?c:h;return delete i[d],d+"="+g})))!==null&&r!==void 0?r:[],l=XF(i);return l&&s.push(l),n+"?"+s.join("&")},Du=(t,e)=>JSON.stringify(t,((a,r)=>typeof r=="bigint"?r.toString():r),e),ty=t=>{var{data:e,compression:a}=t;if(e){if(a===rn.GZipJS){var r=TN((function(l,u){var c=l.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(l);for(var d=new Na(l.length+(l.length>>>1)),h=0,g=function(f){d[h++]=f},S=0;S<c;++S){if(h+5>d.length){var b=new Na(h+8+(c-S<<1));b.set(d),d=b}var x=l.charCodeAt(S);x<128||u?g(x):x<2048?(g(192|x>>>6),g(128|63&x)):x>55295&&x<57344?(g(240|(x=65536+(1047552&x)|1023&l.charCodeAt(++S))>>>18),g(128|x>>>12&63),g(128|x>>>6&63),g(128|63&x)):(g(224|x>>>12),g(128|x>>>6&63),g(128|63&x))}return fk(d,0,h)})(Du(e)),{mtime:0}),n=new Blob([r],{type:J1});return{contentType:J1,body:n,estimatedSize:n.size}}if(a===rn.Base64){var o=(function(l){var u,c,d,h,g,S="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b=0,x=0,f="",m=[];if(!l)return l;l=RN(l);do u=(g=l.charCodeAt(b++)<<16|l.charCodeAt(b++)<<8|l.charCodeAt(b++))>>18&63,c=g>>12&63,d=g>>6&63,h=63&g,m[x++]=S.charAt(u)+S.charAt(c)+S.charAt(d)+S.charAt(h);while(b<l.length);switch(f=m.join(""),l.length%3){case 1:f=f.slice(0,-2)+"==";break;case 2:f=f.slice(0,-1)+"="}return f})(Du(e)),i=(l=>"data="+encodeURIComponent(typeof l=="string"?l:Du(l)))(o);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}var s=Du(e);return{contentType:"application/json",body:s,estimatedSize:new Blob([s]).size}}},Xf=[];iy&&Xf.push({transport:"fetch",method:t=>{var e,a,{contentType:r,body:n,estimatedSize:o}=(e=ty(t))!==null&&e!==void 0?e:{},i=new Headers;De(t.headers,(function(c,d){i.append(d,c)})),r&&i.append("Content-Type",r);var s=t.url,l=null;if(x1){var u=new x1;l={signal:u.signal,timeout:setTimeout((()=>u.abort()),t.timeout)}}iy(s,W({method:t?.method||"GET",headers:i,keepalive:t.method==="POST"&&(o||0)<52428.8,body:n,signal:(a=l)==null?void 0:a.signal},t.fetchOptions)).then((c=>c.text().then((d=>{var h={statusCode:c.status,text:d};if(c.status===200)try{h.json=JSON.parse(d)}catch(g){z.error(g)}t.callback==null||t.callback(h)})))).catch((c=>{z.error(c),t.callback==null||t.callback({statusCode:0,text:c})})).finally((()=>l?clearTimeout(l.timeout):null))}}),sy&&Xf.push({transport:"XHR",method:t=>{var e,a=new sy;a.open(t.method||"GET",t.url,!0);var{contentType:r,body:n}=(e=ty(t))!==null&&e!==void 0?e:{};De(t.headers,(function(o,i){a.setRequestHeader(i,o)})),r&&a.setRequestHeader("Content-Type",r),t.timeout&&(a.timeout=t.timeout),t.disableXHRCredentials||(a.withCredentials=!0),a.onreadystatechange=()=>{if(a.readyState===4){var o={statusCode:a.status,text:a.responseText};if(a.status===200)try{o.json=JSON.parse(a.responseText)}catch{}t.callback==null||t.callback(o)}},a.send(n)}}),va!=null&&va.sendBeacon&&Xf.push({transport:"sendBeacon",method:t=>{var e=fp(t.url,{beacon:"1"});try{var a,{contentType:r,body:n}=(a=ty(t))!==null&&a!==void 0?a:{},o=typeof n=="string"?new Blob([n],{type:r}):n;va.sendBeacon(e,o)}catch{}}});var pp=function(t,e){if(!(function(a){try{new RegExp(a)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function eA(t,e,a){return Du({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:a})}var pk={exact:(t,e)=>e.some((a=>t.some((r=>a===r)))),is_not:(t,e)=>e.every((a=>t.every((r=>a!==r)))),regex:(t,e)=>e.some((a=>t.some((r=>pp(a,r))))),not_regex:(t,e)=>e.every((a=>t.every((r=>!pp(a,r))))),icontains:(t,e)=>e.map(Wf).some((a=>t.map(Wf).some((r=>a.includes(r))))),not_icontains:(t,e)=>e.map(Wf).every((a=>t.map(Wf).every((r=>!a.includes(r)))))},Wf=t=>t.toLowerCase();function hk(t,e){return!t||Object.entries(t).every((a=>{var[r,n]=a,o=e?.[r];if(U(o)||nn(o))return!1;var i=[String(o)],s=pk[n.operator];return!!s&&s(n.values,i)}))}var ay=ct("[Error tracking]"),Ky=class{constructor(e){var a,r;this.Jt=[],this.Kt=new fy([new hy,new Sy,new gy,new my,new xy,new yy,new vy,new by],RF("web:javascript",AF,TF)),this._instance=e,this.Jt=(a=(r=this._instance.persistence)==null?void 0:r.get_property(_y))!==null&&a!==void 0?a:[]}onRemoteConfig(e){var a,r,n,o=(a=(r=e.errorTracking)==null?void 0:r.suppressionRules)!==null&&a!==void 0?a:[],i=(n=e.errorTracking)==null?void 0:n.captureExtensionExceptions;this.Jt=o,this._instance.persistence&&this._instance.persistence.register({[_y]:this.Jt,[T1]:i})}get Yt(){var e,a=!!this._instance.get_property(T1),r=this._instance.config.error_tracking.captureExtensionExceptions;return(e=r??a)!==null&&e!==void 0&&e}buildProperties(e,a){return this.Kt.buildFromUnknown(e,{syntheticException:a?.syntheticException,mechanism:{handled:a?.handled}})}sendExceptionEvent(e){var a=e.$exception_list;if(this.Xt(a)){if(this.Qt(a))return void ay.info("Skipping exception capture because a suppression rule matched");if(!this.Yt&&this.Zt(a))return void ay.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ti(a))return void ay.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent"})}Qt(e){if(e.length===0)return!1;var a=e.reduce(((r,n)=>{var{type:o,value:i}=n;return ut(o)&&o.length>0&&r.$exception_types.push(o),ut(i)&&i.length>0&&r.$exception_values.push(i),r}),{$exception_types:[],$exception_values:[]});return this.Jt.some((r=>{var n=r.values.map((o=>{var i,s=pk[o.operator],l=Te(o.value)?o.value:[o.value],u=(i=a[o.key])!==null&&i!==void 0?i:[];return l.length>0&&s(l,u)}));return r.type==="OR"?n.some(Boolean):n.every(Boolean)}))}Zt(e){return e.flatMap((a=>{var r,n;return(r=(n=a.stacktrace)==null?void 0:n.frames)!==null&&r!==void 0?r:[]})).some((a=>a.filename&&a.filename.startsWith("chrome-extension://")))}ti(e){if(e.length>0){var a,r,n,o,i=(a=(r=e[0].stacktrace)==null?void 0:r.frames)!==null&&a!==void 0?a:[],s=i[i.length-1];return(n=s==null||(o=s.filename)==null?void 0:o.includes("posthog.com/static"))!==null&&n!==void 0&&n}return!1}Xt(e){return!Ie(e)&&Te(e)}},er=ct("[FeatureFlags]"),wu=ct("[FeatureFlags]",{debugEnabled:!0}),ry="$active_feature_flags",Es="$override_feature_flags",tA="$feature_flag_payloads",Lu="$override_feature_flag_payloads",aA="$feature_flag_request_id",rA="$feature_flag_evaluated_at",nA=t=>{var e={};for(var[a,r]of Zf(t||{}))r&&(e[a]=r);return e},DN=t=>{var e=t.flags;return e?(t.featureFlags=Object.fromEntries(Object.keys(e).map((a=>{var r;return[a,(r=e[a].variant)!==null&&r!==void 0?r:e[a].enabled]}))),t.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter((a=>e[a].enabled)).filter((a=>{var r;return(r=e[a].metadata)==null?void 0:r.payload})).map((a=>{var r;return[a,(r=e[a].metadata)==null?void 0:r.payload]})))):er.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),t},ON=(function(t){return t.FeatureFlags="feature_flags",t.Recordings="recordings",t})({}),Qy=class{constructor(e){this.ii=!1,this.ei=!1,this.ri=!1,this.si=!1,this.ni=!1,this.oi=!1,this.ai=!1,this._instance=e,this.featureFlagEventHandlers=[]}li(){var e=this._instance.config.evaluation_environments;return e!=null&&e.length?e.filter((a=>{var r=a&&typeof a=="string"&&a.trim().length>0;return r||er.error("Invalid evaluation environment found:",a,"Expected non-empty string"),r})):[]}ui(){return this.li().length>0}flags(){if(this._instance.config.__preview_remote_config)this.oi=!0;else{var e=!this.hi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.vi({disableFlags:e})}}get hasLoadedFlags(){return this.ei}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(wy),a=this._instance.get_property(Es),r=this._instance.get_property(Lu);if(!r&&!a)return e||{};var n=Je({},e||{}),o=[...new Set([...Object.keys(r||{}),...Object.keys(a||{})])];for(var i of o){var s,l,u=n[i],c=a?.[i],d=U(c)?(s=u?.enabled)!==null&&s!==void 0&&s:!!c,h=U(c)?u.variant:typeof c=="string"?c:void 0,g=r?.[i],S=W({},u,{enabled:d,variant:d?h??u?.variant:void 0});d!==u?.enabled&&(S.original_enabled=u?.enabled),h!==u?.variant&&(S.original_variant=u?.variant),g&&(S.metadata=W({},u?.metadata,{payload:g,original_payload:u==null||(l=u.metadata)==null?void 0:l.payload})),n[i]=S}return this.ii||(er.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:r,finalDetails:n}),this.ii=!0),n}getFlagVariants(){var e=this._instance.get_property(Ds),a=this._instance.get_property(Es);if(!a)return e||{};for(var r=Je({},e),n=Object.keys(a),o=0;o<n.length;o++)r[n[o]]=a[n[o]];return this.ii||(er.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:a,finalFlags:r}),this.ii=!0),r}getFlagPayloads(){var e=this._instance.get_property(tA),a=this._instance.get_property(Lu);if(!a)return e||{};for(var r=Je({},e||{}),n=Object.keys(a),o=0;o<n.length;o++)r[n[o]]=a[n[o]];return this.ii||(er.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:a,finalPayloads:r}),this.ii=!0),r}reloadFeatureFlags(){this.si||this._instance.config.advanced_disable_feature_flags||this.hi||(this.hi=setTimeout((()=>{this.vi()}),5))}di(){clearTimeout(this.hi),this.hi=void 0}ensureFlagsLoaded(){this.ei||this.ri||this.hi||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.si=e}vi(e){var a;if(this.di(),!this._instance.O())if(this.ri)this.ni=!0;else{var r={token:this._instance.config.token,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:W({},((a=this._instance.persistence)==null?void 0:a.get_initial_props())||{},this._instance.get_property(Ru)||{}),group_properties:this._instance.get_property(li)};(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(r.disable_flags=!0),this.ui()&&(r.evaluation_environments=this.li());var n=this._instance.config.__preview_remote_config,o=n?"/flags/?v=2":"/flags/?v=2&config=true",i=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",s=this._instance.requestRouter.endpointFor("flags",o+i);n&&(r.timezone=lk()),this.ri=!0,this._instance.ci({method:"POST",url:s,data:r,compression:this._instance.config.disable_compression?void 0:rn.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:l=>{var u,c,d=!0;if(l.statusCode===200&&(this.ni||(this.$anon_distinct_id=void 0),d=!1),this.ri=!1,this.oi||(this.oi=!0,this._instance.fi((c=l.json)!==null&&c!==void 0?c:{})),!r.disable_flags||this.ni)if(this.ai=!d,l.json&&(u=l.json.quotaLimited)!=null&&u.includes(ON.FeatureFlags))er.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more.");else{var h;r.disable_flags||this.receivedFeatureFlags((h=l.json)!==null&&h!==void 0?h:{},d),this.ni&&(this.ni=!1,this.vi())}}})}}getFeatureFlag(e,a){if(a===void 0&&(a={}),this.ei||this.getFlags()&&this.getFlags().length>0){var r=this.getFlagVariants()[e],n=""+r,o=this._instance.get_property(aA)||void 0,i=this._instance.get_property(rA)||void 0,s=this._instance.get_property(ep)||{};if((a.send_event||!("send_event"in a))&&(!(e in s)||!s[e].includes(n))){var l,u,c,d,h,g,S,b,x;Te(s[e])?s[e].push(n):s[e]=[n],(l=this._instance.persistence)==null||l.register({[ep]:s});var f=this.getFeatureFlagDetails(e),m={$feature_flag:e,$feature_flag_response:r,$feature_flag_payload:this.getFeatureFlagPayload(e)||null,$feature_flag_request_id:o,$feature_flag_evaluated_at:i,$feature_flag_bootstrapped_response:((u=this._instance.config.bootstrap)==null||(u=u.featureFlags)==null?void 0:u[e])||null,$feature_flag_bootstrapped_payload:((c=this._instance.config.bootstrap)==null||(c=c.featureFlagPayloads)==null?void 0:c[e])||null,$used_bootstrap_value:!this.ai};U(f==null||(d=f.metadata)==null?void 0:d.version)||(m.$feature_flag_version=f.metadata.version);var v,y=(h=f==null||(g=f.reason)==null?void 0:g.description)!==null&&h!==void 0?h:f==null||(S=f.reason)==null?void 0:S.code;y&&(m.$feature_flag_reason=y),f!=null&&(b=f.metadata)!=null&&b.id&&(m.$feature_flag_id=f.metadata.id),U(f?.original_variant)&&U(f?.original_enabled)||(m.$feature_flag_original_response=U(f.original_variant)?f.original_enabled:f.original_variant),f!=null&&(x=f.metadata)!=null&&x.original_payload&&(m.$feature_flag_original_payload=f==null||(v=f.metadata)==null?void 0:v.original_payload),this._instance.capture("$feature_flag_called",m)}return r}er.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){return this.getFlagPayloads()[e]}getRemoteConfigPayload(e,a){var r=this._instance.config.token,n={distinct_id:this._instance.get_distinct_id(),token:r};this.ui()&&(n.evaluation_environments=this.li()),this._instance.ci({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2&config=true"),data:n,compression:this._instance.config.disable_compression?void 0:rn.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:o=>{var i,s=(i=o.json)==null?void 0:i.featureFlagPayloads;a(s?.[e]||void 0)}})}isFeatureEnabled(e,a){if(a===void 0&&(a={}),this.ei||this.getFlags()&&this.getFlags().length>0){var r=this.getFeatureFlag(e,a);return U(r)?void 0:!!r}er.warn('isFeatureEnabled for key "'+e+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((a=>a!==e))}receivedFeatureFlags(e,a){if(this._instance.persistence){this.ei=!0;var r=this.getFlagVariants(),n=this.getFlagPayloads(),o=this.getFlagsWithDetails();(function(i,s,l,u,c){l===void 0&&(l={}),u===void 0&&(u={}),c===void 0&&(c={});var d=DN(i),h=d.flags,g=d.featureFlags,S=d.featureFlagPayloads;if(g){var b=i.requestId,x=i.evaluatedAt;if(Te(g)){er.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var f={};if(g)for(var m=0;m<g.length;m++)f[g[m]]=!0;s&&s.register({[ry]:g,[Ds]:f})}else{var v=g,y=S,_=h;i.errorsWhileComputingFlags&&(v=W({},l,v),y=W({},u,y),_=W({},c,_)),s&&s.register(W({[ry]:Object.keys(nA(v)),[Ds]:v||{},[tA]:y||{},[wy]:_||{}},b?{[aA]:b}:{},x?{[rA]:x}:{}))}}})(e,this._instance.persistence,r,n,o),this.pi(a)}}override(e,a){a===void 0&&(a=!1),er.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:a})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return er.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister(Es),this._instance.persistence.unregister(Lu),this.pi(),wu.info("All overrides cleared");if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var a,r=e;if(this.ii=!!((a=r.suppressWarning)!==null&&a!==void 0&&a),"flags"in r){if(r.flags===!1)this._instance.persistence.unregister(Es),wu.info("Flag overrides cleared");else if(r.flags){if(Te(r.flags)){for(var n={},o=0;o<r.flags.length;o++)n[r.flags[o]]=!0;this._instance.persistence.register({[Es]:n})}else this._instance.persistence.register({[Es]:r.flags});wu.info("Flag overrides set",{flags:r.flags})}}return"payloads"in r&&(r.payloads===!1?(this._instance.persistence.unregister(Lu),wu.info("Payload overrides cleared")):r.payloads&&(this._instance.persistence.register({[Lu]:r.payloads}),wu.info("Payload overrides set",{payloads:r.payloads}))),void this.pi()}this.pi()}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.ei){var{flags:a,flagVariants:r}=this.gi();e(a,r)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,a,r){var n,o=(this._instance.get_property(Tu)||[]).find((u=>u.flagKey===e)),i={["$feature_enrollment/"+e]:a},s={$feature_flag:e,$feature_enrollment:a,$set:i};o&&(s.$early_access_feature_name=o.name),r&&(s.$feature_enrollment_stage=r),this._instance.capture("$feature_enrollment_update",s),this.setPersonPropertiesForFlags(i,!1);var l=W({},this.getFlagVariants(),{[e]:a});(n=this._instance.persistence)==null||n.register({[ry]:Object.keys(nA(l)),[Ds]:l}),this.pi()}getEarlyAccessFeatures(e,a,r){a===void 0&&(a=!1);var n=this._instance.get_property(Tu),o=r?"&"+r.map((i=>"stage="+i)).join("&"):"";if(n&&!a)return e(n);this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+o),method:"GET",callback:i=>{var s,l;if(i.json){var u=i.json.earlyAccessFeatures;return(s=this._instance.persistence)==null||s.unregister(Tu),(l=this._instance.persistence)==null||l.register({[Tu]:u}),e(u)}}})}gi(){var e=this.getFlags(),a=this.getFlagVariants();return{flags:e.filter((r=>a[r])),flagVariants:Object.keys(a).filter((r=>a[r])).reduce(((r,n)=>(r[n]=a[n],r)),{})}}pi(e){var{flags:a,flagVariants:r}=this.gi();this.featureFlagEventHandlers.forEach((n=>n(a,r,{errorsLoading:e})))}setPersonPropertiesForFlags(e,a){a===void 0&&(a=!0);var r=this._instance.get_property(Ru)||{};this._instance.register({[Ru]:W({},r,e)}),a&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(Ru)}setGroupPropertiesForFlags(e,a){a===void 0&&(a=!0);var r=this._instance.get_property(li)||{};Object.keys(r).length!==0&&Object.keys(r).forEach((n=>{r[n]=W({},r[n],e[n]),delete e[n]})),this._instance.register({[li]:W({},r,e)}),a&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var a=this._instance.get_property(li)||{};this._instance.register({[li]:W({},a,{[e]:{}})})}else this._instance.unregister(li)}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}},BN=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Fu=class{constructor(e,a){this.F=e,this.props={},this.mi=!1,this.yi=(r=>{var n="";return r.token&&(n=r.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),r.persistence_name?"ph_"+r.persistence_name:"ph_"+n+"_posthog"})(e),this.Y=this.bi(e),this.load(),e.debug&&z.info("Persistence loaded",e.persistence,W({},this.props)),this.update_config(e,e,a),this.save()}isDisabled(){return!!this.wi}bi(e){BN.indexOf(e.persistence.toLowerCase())===-1&&(z.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var a=e.persistence.toLowerCase();return a==="localstorage"&&Ge.H()?Ge:a==="localstorage+cookie"&&Vf.H()?Vf:a==="sessionstorage"&&Lt.H()?Lt:a==="memory"?rN:a==="cookie"?vr:Vf.H()?Vf:vr}properties(){var e={};return De(this.props,(function(a,r){if(r===Ds&&mt(a))for(var n=Object.keys(a),o=0;o<n.length;o++)e["$feature/"+n[o]]=a[n[o]];else s=r,l=!1,(nn(i=HF)?l:y1&&i.indexOf===y1?i.indexOf(s)!=-1:(De(i,(function(u){if(l||(l=u===s))return Qf})),l))||(e[r]=a);var i,s,l})),e}load(){if(!this.wi){var e=this.Y.W(this.yi);e&&(this.props=Je({},e))}}save(){this.wi||this.Y.G(this.yi,this.props,this.xi,this.Si,this.Ei,this.F.debug)}remove(){this.Y.V(this.yi,!1),this.Y.V(this.yi,!0)}clear(){this.remove(),this.props={}}register_once(e,a,r){if(mt(e)){U(a)&&(a="None"),this.xi=U(r)?this.$i:r;var n=!1;if(De(e,((o,i)=>{this.props.hasOwnProperty(i)&&this.props[i]!==a||(this.props[i]=o,n=!0)})),n)return this.save(),!0}return!1}register(e,a){if(mt(e)){this.xi=U(a)?this.$i:a;var r=!1;if(De(e,((n,o)=>{e.hasOwnProperty(o)&&this.props[o]!==n&&(this.props[o]=n,r=!0)})),r)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.mi){var e=ak(this.F.custom_campaign_params,this.F.mask_personal_data_properties,this.F.custom_personal_data_properties);Ms(gx(e))||this.register(e),this.mi=!0}}update_search_keyword(){var e;this.register((e=q?.referrer)?nk(e):{})}update_referrer_info(){var e;this.register_once({$referrer:ok(),$referring_domain:q!=null&&q.referrer&&((e=op(q.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[ky]||this.props[Ey]||this.register_once({[tp]:ik(this.F.mask_personal_data_properties,this.F.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};De([Ey,ky],(i=>{var s=this.props[i];s&&De(s,(function(l,u){e["$initial_"+ly(u)]=l}))}));var a,r,n=this.props[tp];if(n){var o=(a=sk(n),r={},De(a,(function(i,s){r["$initial_"+ly(s)]=i})),r);Je(e,o)}return e}safe_merge(e){return De(this.props,(function(a,r){r in e||(e[r]=a)})),e}update_config(e,a,r){if(this.$i=this.xi=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==a.persistence){var n=this.bi(e),o=this.props;this.clear(),this.Y=n,this.props=o,this.save()}}set_disabled(e){this.wi=e,this.wi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Si&&(this.Si=e,this.remove(),this.save())}set_secure(e){e!==this.Ei&&(this.Ei=e,this.remove(),this.save())}set_event_timer(e,a){var r=this.props[Eu]||{};r[e]=a,this.props[Eu]=r,this.save()}remove_event_timer(e){var a=(this.props[Eu]||{})[e];return U(a)||(delete this.props[Eu][e],this.save()),a}get_property(e){return this.props[e]}set_property(e,a){this.props[e]=a,this.save()}},Iu=(function(t){return t.Activation="events",t.Cancellation="cancelEvents",t})({}),W5=(function(t){return t.Button="button",t.Tab="tab",t.Selector="selector",t})({}),Z5=(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})({}),X5=(function(t){return t.Top="top",t.Left="left",t.Right="right",t.Bottom="bottom",t})({}),ny=(function(t){return t.Popover="popover",t.API="api",t.Widget="widget",t.ExternalSurvey="external_survey",t})({}),Y5=(function(t){return t.Open="open",t.MultipleChoice="multiple_choice",t.SingleChoice="single_choice",t.Rating="rating",t.Link="link",t})({}),K5=(function(t){return t.NextQuestion="next_question",t.End="end",t.ResponseBased="response_based",t.SpecificQuestion="specific_question",t})({}),Q5=(function(t){return t.Once="once",t.Recurring="recurring",t.Always="always",t})({}),Yf=(function(t){return t.SHOWN="survey shown",t.DISMISSED="survey dismissed",t.SENT="survey sent",t})({}),oA=(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})({}),mk=(function(t){return t.Popover="popover",t.Inline="inline",t})({}),Vu=class{constructor(){this.ki={},this.ki={}}on(e,a){return this.ki[e]||(this.ki[e]=[]),this.ki[e].push(a),()=>{this.ki[e]=this.ki[e].filter((r=>r!==a))}}emit(e,a){for(var r of this.ki[e]||[])r(a);for(var n of this.ki["*"]||[])n(e,a)}};function Ts(t,e,a){if(Ie(t))return!1;switch(a){case"exact":return t===e;case"contains":var r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}var Jy=class{constructor(e){this.Pi=new Vu,this.Ti=(a,r)=>this.Ri(a,r)&&this.Ii(a,r)&&this.Fi(a,r)&&this.Ci(a,r),this.Ri=(a,r)=>r==null||!r.event||a?.event===r?.event,this._instance=e,this.Mi=new Set,this.Oi=new Set}init(){var e;if(!U((e=this._instance)==null?void 0:e.Ai)){var a;(a=this._instance)==null||a.Ai(((r,n)=>{this.on(r,n)}))}}register(e){var a,r;if(!U((a=this._instance)==null?void 0:a.Ai)&&(e.forEach((i=>{var s,l;(s=this.Oi)==null||s.add(i),(l=i.steps)==null||l.forEach((u=>{var c;(c=this.Mi)==null||c.add(u?.event||"")}))})),(r=this._instance)!=null&&r.autocapture)){var n,o=new Set;e.forEach((i=>{var s;(s=i.steps)==null||s.forEach((l=>{l!=null&&l.selector&&o.add(l?.selector)}))})),(n=this._instance)==null||n.autocapture.setElementSelectors(o)}}on(e,a){var r;a!=null&&e.length!=0&&(this.Mi.has(e)||this.Mi.has(a?.event))&&this.Oi&&((r=this.Oi)==null?void 0:r.size)>0&&this.Oi.forEach((n=>{this.Di(a,n)&&this.Pi.emit("actionCaptured",n.name)}))}ji(e){this.onAction("actionCaptured",(a=>e(a)))}Di(e,a){if(a?.steps==null)return!1;for(var r of a.steps)if(this.Ti(e,r))return!0;return!1}onAction(e,a){return this.Pi.on(e,a)}Ii(e,a){if(a!=null&&a.url){var r,n=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!n||typeof n!="string"||!Ts(n,a.url,a.url_matching||"contains"))return!1}return!0}Fi(e,a){return!!this.Li(e,a)&&!!this.Ni(e,a)&&!!this.Ui(e,a)}Li(e,a){var r;if(a==null||!a.href)return!0;var n=this.zi(e);if(n.length>0)return n.some((s=>Ts(s.href,a.href,a.href_matching||"exact")));var o,i=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!i&&Ts((o=i.match(/(?::|")href="(.*?)"/))?o[1]:"",a.href,a.href_matching||"exact")}Ni(e,a){var r;if(a==null||!a.text)return!0;var n=this.zi(e);if(n.length>0)return n.some((u=>Ts(u.text,a.text,a.text_matching||"exact")||Ts(u.$el_text,a.text,a.text_matching||"exact")));var o,i,s,l=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(o=(function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!Ie(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d})(l),i=a.text,s=a.text_matching||"exact",o.some((u=>Ts(u,i,s))))}Ui(e,a){var r,n;if(a==null||!a.selector)return!0;var o=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(o!=null&&o.includes(a.selector))return!0;var i=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";if(a.selector_regex&&i)try{return new RegExp(a.selector_regex).test(i)}catch{return!1}return!1}zi(e){var a;return(e==null||(a=e.properties)==null?void 0:a.$elements)==null?[]:e?.properties.$elements}Ci(e,a){return a==null||!a.properties||a.properties.length===0||hk(a.properties.reduce(((r,n)=>{var o=Te(n.value)?n.value.map(String):n.value!=null?[String(n.value)]:[];return r[n.key]={values:o,operator:n.operator||"exact"},r}),{}),e?.properties)}},_e=ct("[Surveys]"),ex="seenSurvey_",FN=(t,e)=>{var a="$survey_"+e+"/"+t.id;return t.current_iteration&&t.current_iteration>0&&(a="$survey_"+e+"/"+t.id+"/"+t.current_iteration),a},iA=t=>{var e=""+ex+t.id;return t.current_iteration&&t.current_iteration>0&&(e=""+ex+t.id+"_"+t.current_iteration),e},NN=[ny.Popover,ny.Widget,ny.API],PN={ignoreConditions:!1,ignoreDelay:!1,displayType:mk.Popover},tx=class{constructor(e){this._instance=e,this.Hi=new Map,this.Bi=new Map,this.qi=new Map}Wi(e,a){return!!e&&hk(e.propertyFilters,a?.properties)}Gi(e,a){var r=new Map;return e.forEach((n=>{var o;(o=n.conditions)==null||(o=o[a])==null||(o=o.values)==null||o.forEach((i=>{if(i!=null&&i.name){var s=r.get(i.name)||[];s.push(n.id),r.set(i.name,s)}}))})),r}Vi(e,a,r){var n,o=(r===Iu.Activation?this.Hi:this.Bi).get(e),i=[];return(n=this._instance)==null||n.getSurveys((s=>{i=s.filter((l=>o?.includes(l.id)))})),i.filter((s=>{var l,u=(l=s.conditions)==null||(l=l[r])==null||(l=l.values)==null?void 0:l.find((c=>c.name===e));return this.Wi(u,a)}))}register(e){var a;U((a=this._instance)==null?void 0:a.Ai)||(this.Ji(e),this.Ki(e))}Ki(e){var a=e.filter((r=>{var n,o;return((n=r.conditions)==null?void 0:n.actions)&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0}));a.length!==0&&(this.Yi==null&&(this.Yi=new Jy(this._instance),this.Yi.init(),this.Yi.ji((r=>{this.onAction(r)}))),a.forEach((r=>{var n,o,i,s,l;r.conditions&&(n=r.conditions)!=null&&n.actions&&(o=r.conditions)!=null&&(o=o.actions)!=null&&o.values&&((i=r.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0&&((s=this.Yi)==null||s.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var c=this.qi.get(u.name);c&&c.push(r.id),this.qi.set(u.name,c||[r.id])}})))})))}Ji(e){var a,r=e.filter((o=>{var i,s;return((i=o.conditions)==null?void 0:i.events)&&((s=o.conditions)==null||(s=s.events)==null||(s=s.values)==null?void 0:s.length)>0})),n=e.filter((o=>{var i,s;return((i=o.conditions)==null?void 0:i.cancelEvents)&&((s=o.conditions)==null||(s=s.cancelEvents)==null||(s=s.values)==null?void 0:s.length)>0}));(r.length!==0||n.length!==0)&&((a=this._instance)==null||a.Ai(((o,i)=>{this.onEvent(o,i)})),this.Hi=this.Gi(e,Iu.Activation),this.Bi=this.Gi(e,Iu.Cancellation))}onEvent(e,a){var r,n=((r=this._instance)==null||(r=r.persistence)==null?void 0:r.props[zf])||[];if(Yf.SHOWN===e&&a&&n.length>0){var o;_e.info("survey event matched, removing survey from activated surveys",{event:e,eventPayload:a,existingActivatedSurveys:n});var i=a==null||(o=a.properties)==null?void 0:o.$survey_id;if(i){var s=n.indexOf(i);s>=0&&(n.splice(s,1),this.Xi(n))}}else{if(this.Bi.has(e)){var l=this.Vi(e,a,Iu.Cancellation);l.length>0&&(_e.info("cancel event matched, cancelling surveys",{event:e,surveysToCancel:l.map((c=>c.id))}),l.forEach((c=>{var d,h=n.indexOf(c.id);h>=0&&n.splice(h,1),(d=this._instance)==null||d.cancelPendingSurvey(c.id)})),this.Xi(n))}if(this.Hi.has(e)){_e.info("survey event name matched",{event:e,eventPayload:a,surveys:this.Hi.get(e)});var u=this.Vi(e,a,Iu.Activation);this.Xi(n.concat(u.map((c=>c.id))||[]))}}}onAction(e){var a,r=((a=this._instance)==null||(a=a.persistence)==null?void 0:a.props[zf])||[];this.qi.has(e)&&this.Xi(r.concat(this.qi.get(e)||[]))}Xi(e){var a;_e.info("updating activated surveys",{activatedSurveys:e}),(a=this._instance)==null||(a=a.persistence)==null||a.register({[zf]:[...new Set(e)]})}getSurveys(){var e,a=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[zf];return a||[]}getEventToSurveys(){return this.Hi}Qi(){return this.Yi}},ax=class{constructor(e){this.Zi=void 0,this._surveyManager=null,this.te=!1,this.ie=!1,this.ee=[],this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var a=e.surveys;if(Ie(a))return _e.warn("Flags not loaded yet. Not loading surveys.");var r=Te(a);this.Zi=r?a.length>0:a,_e.info("flags response received, isSurveysEnabled: "+this.Zi),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],a=0;a<localStorage.length;a++){var r=localStorage.key(a);(r!=null&&r.startsWith(ex)||r!=null&&r.startsWith("inProgressSurvey_"))&&e.push(r)}e.forEach((n=>localStorage.removeItem(n)))}loadIfEnabled(){if(!this._surveyManager)if(this.ie)_e.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)_e.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())_e.info("Not loading surveys in cookieless mode without consent.");else{var e=te?.__PosthogExtensions__;if(e){if(!U(this.Zi)||this._instance.config.advanced_enable_surveys){var a=this.Zi||this._instance.config.advanced_enable_surveys;this.ie=!0;try{var r=e.generateSurveys;if(r)return void this.re(r,a);var n=e.loadExternalDependency;if(!n)return void this.se("PostHog loadExternalDependency extension not found.");n(this._instance,"surveys",(o=>{o||!e.generateSurveys?this.se("Could not load surveys script",o):this.re(e.generateSurveys,a)}))}catch(o){throw this.se("Error initializing surveys",o),o}finally{this.ie=!1}}}else _e.error("PostHog Extensions not found.")}}re(e,a){this._surveyManager=e(this._instance,a),this._surveyEventReceiver=new tx(this._instance),_e.info("Surveys loaded successfully"),this.ne({isLoaded:!0})}se(e,a){_e.error(e,a),this.ne({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.ee.push(e),this._surveyManager&&this.ne({isLoaded:!0}),()=>{this.ee=this.ee.filter((a=>a!==e))}}getSurveys(e,a){if(a===void 0&&(a=!1),this._instance.config.disable_surveys)return _e.info("Disabled. Not loading surveys."),e([]);var r=this._instance.get_property(Ly);if(r&&!a)return e(r,{isLoaded:!0});if(this.te)return e([],{isLoaded:!1,error:"Surveys are already being loaded"});try{this.te=!0,this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:n=>{var o;this.te=!1;var i=n.statusCode;if(i!==200||!n.json){var s="Surveys API could not be loaded, status: "+i;return _e.error(s),e([],{isLoaded:!1,error:s})}var l,u=n.json.surveys||[],c=u.filter((d=>(function(h){return!(!h.start_date||h.end_date)})(d)&&((function(h){var g;return!((g=h.conditions)==null||(g=g.events)==null||(g=g.values)==null||!g.length)})(d)||(function(h){var g;return!((g=h.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(d))));return c.length>0&&((l=this._surveyEventReceiver)==null||l.register(c)),(o=this._instance.persistence)==null||o.register({[Ly]:u}),e(u,{isLoaded:!0})}})}catch(n){throw this.te=!1,n}}ne(e){for(var a of this.ee)try{if(!e.isLoaded)return a([],e);this.getSurveys(a)}catch(r){_e.error("Error in survey callback",r)}}getActiveMatchingSurveys(e,a){if(a===void 0&&(a=!1),!Ie(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,a);_e.warn("init was not called")}oe(e){var a=null;return this.getSurveys((r=>{var n;a=(n=r.find((o=>o.id===e)))!==null&&n!==void 0?n:null})),a}ae(e){if(Ie(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var a=typeof e=="string"?this.oe(e):e;return a?this._surveyManager.checkSurveyEligibility(a):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(Ie(this._surveyManager))return _e.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var a=this.ae(e);return{visible:a.eligible,disabledReason:a.reason}}canRenderSurveyAsync(e,a){return Ie(this._surveyManager)?(_e.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise((r=>{this.getSurveys((n=>{var o,i=(o=n.find((l=>l.id===e)))!==null&&o!==void 0?o:null;if(i){var s=this.ae(i);r({visible:s.eligible,disabledReason:s.reason})}else r({visible:!1,disabledReason:"Survey not found"})}),a)}))}renderSurvey(e,a){var r;if(Ie(this._surveyManager))_e.warn("init was not called");else{var n=typeof e=="string"?this.oe(e):e;if(n!=null&&n.id)if(NN.includes(n.type)){var o=q?.querySelector(a);if(o)return(r=n.appearance)!=null&&r.surveyPopupDelaySeconds?(_e.info("Rendering survey "+n.id+" with delay of "+n.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var i,s;_e.info("Rendering survey "+n.id+" with delay of "+((i=n.appearance)==null?void 0:i.surveyPopupDelaySeconds)+" seconds"),(s=this._surveyManager)==null||s.renderSurvey(n,o),_e.info("Survey "+n.id+" rendered")}),1e3*n.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(n,o);_e.warn("Survey element not found")}else _e.warn("Surveys of type "+n.type+" cannot be rendered in the app");else _e.warn("Survey not found")}}displaySurvey(e,a){var r;if(Ie(this._surveyManager))_e.warn("init was not called");else{var n=this.oe(e);if(n){var o=n;if((r=n.appearance)!=null&&r.surveyPopupDelaySeconds&&a.ignoreDelay&&(o=W({},n,{appearance:W({},n.appearance,{surveyPopupDelaySeconds:0})})),a.ignoreConditions===!1){var i=this.canRenderSurvey(n);if(!i.visible)return void _e.warn("Survey is not eligible to be displayed: ",i.disabledReason)}a.displayType!==mk.Inline?this._surveyManager.handlePopoverSurvey(o):this.renderSurvey(o,a.selector)}else _e.warn("Survey not found")}}cancelPendingSurvey(e){Ie(this._surveyManager)?_e.warn("init was not called"):this._surveyManager.cancelSurvey(e)}},sA=ct("[RateLimiter]"),rx=class{constructor(e){var a,r;this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var o=n.text;if(o&&o.length)try{(JSON.parse(o).quota_limited||[]).forEach((i=>{sA.info((i||"events")+" is quota limited."),this.serverLimits[i]=new Date().getTime()+6e4}))}catch(i){return void sA.warn('could not rate limit - continuing. Error: "'+i?.message+'"',{text:o})}},this.instance=e,this.captureEventsPerSecond=((a=e.config.rate_limiting)==null?void 0:a.events_per_second)||10,this.captureEventsBurstLimit=Math.max(((r=e.config.rate_limiting)==null?void 0:r.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond),this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}clientRateLimitContext(e){var a,r,n;e===void 0&&(e=!1);var o=new Date().getTime(),i=(a=(r=this.instance.persistence)==null?void 0:r.get_property(Ay))!==null&&a!==void 0?a:{tokens:this.captureEventsBurstLimit,last:o};i.tokens+=(o-i.last)/1e3*this.captureEventsPerSecond,i.last=o,i.tokens>this.captureEventsBurstLimit&&(i.tokens=this.captureEventsBurstLimit);var s=i.tokens<1;return s||e||(i.tokens=Math.max(0,i.tokens-1)),!s||this.lastEventRateLimited||e||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+this.captureEventsPerSecond+" events per second and "+this.captureEventsBurstLimit+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=s,(n=this.instance.persistence)==null||n.set_property(Ay,i),{isRateLimited:s,remainingTokens:i.tokens}}isServerRateLimited(e){var a=this.serverLimits[e||"events"]||!1;return a!==!1&&new Date().getTime()<a}},si=ct("[RemoteConfig]"),nx=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=te._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.config}le(e){var a,r;(a=te.__PosthogExtensions__)!=null&&a.loadExternalDependency?(r=te.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"remote-config",(()=>e(this.remoteConfig))):(si.error("PostHog Extensions not found. Cannot load remote config."),e())}ue(e){this._instance.ci({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:a=>{e(a.json)}})}load(){try{if(this.remoteConfig)return si.info("Using preloaded remote config",this.remoteConfig),void this.fi(this.remoteConfig);if(this._instance.O())return void si.warn("Remote config is disabled. Falling back to local config.");this.le((e=>{if(!e)return si.info("No config found after loading remote JS config. Falling back to JSON."),void this.ue((a=>{this.fi(a)}));this.fi(e)}))}catch(e){si.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()):si.info("__preview_remote_config is disabled. Logging config instead",e):si.error("Failed to fetch remote config from PostHog.")}},ox=3e3,ix=class{constructor(e,a){this.he=!0,this.ve=[],this.de=mr(a?.flush_interval_ms||ox,250,5e3,z.createLogger("flush interval"),ox),this.ce=e}enqueue(e){this.ve.push(e),this.fe||this.pe()}unload(){this.ge();var e=this.ve.length>0?this._e():{},a=Object.values(e);[...a.filter((r=>r.url.indexOf("/e")===0)),...a.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.ce(W({},r,{transport:"sendBeacon"}))}))}enable(){this.he=!1,this.pe()}pe(){var e=this;this.he||(this.fe=setTimeout((()=>{if(this.ge(),this.ve.length>0){var a=this._e(),r=function(){var o=a[n],i=new Date().getTime();o.data&&Te(o.data)&&De(o.data,(s=>{s.offset=Math.abs(s.timestamp-i),delete s.timestamp})),e.ce(o)};for(var n in a)r()}}),this.de))}ge(){clearTimeout(this.fe),this.fe=void 0}_e(){var e={};return De(this.ve,(a=>{var r,n=a,o=(n?n.batchKey:null)||n.url;U(e[o])&&(e[o]=W({},n,{data:[]})),(r=e[o].data)==null||r.push(n.data)})),this.ve=[],e}},HN=["retriesPerformedSoFar"],sx=class{constructor(e){this.me=!1,this.ye=3e3,this.ve=[],this._instance=e,this.ve=[],this.be=!0,!U(E)&&"onLine"in E.navigator&&(this.be=E.navigator.onLine,this.we=()=>{this.be=!0,this.Dt()},this.xe=()=>{this.be=!1},nt(E,"online",this.we),nt(E,"offline",this.xe))}get length(){return this.ve.length}retriableRequest(e){var{retriesPerformedSoFar:a}=e,r=pA(e,HN);yr(a)&&a>0&&(r.url=fp(r.url,{retry_count:a})),this._instance.ci(W({},r,{callback:n=>{n.statusCode!==200&&(n.statusCode<400||n.statusCode>=500)&&(a??0)<10?this.Se(W({retriesPerformedSoFar:a},r)):r.callback==null||r.callback(n)}}))}Se(e){var a=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=a+1;var r=(function(i){var s=3e3*Math.pow(2,i),l=s/2,u=Math.min(18e5,s),c=(Math.random()-.5)*(u-l);return Math.ceil(u+c)})(a),n=Date.now()+r;this.ve.push({retryAt:n,requestOptions:e});var o="Enqueued failed request for retry in "+r;navigator.onLine||(o+=" (Browser is offline)"),z.warn(o),this.me||(this.me=!0,this.Ee())}Ee(){if(this.$e&&clearTimeout(this.$e),this.ve.length===0)return this.me=!1,void(this.$e=void 0);this.$e=setTimeout((()=>{this.be&&this.ve.length>0&&this.Dt(),this.Ee()}),this.ye)}Dt(){var e=Date.now(),a=[],r=this.ve.filter((o=>o.retryAt<e||(a.push(o),!1)));if(this.ve=a,r.length>0)for(var{requestOptions:n}of r)this.retriableRequest(n)}unload(){for(var{requestOptions:e}of(this.$e&&(clearTimeout(this.$e),this.$e=void 0),this.me=!1,U(E)||(this.we&&(E.removeEventListener("online",this.we),this.we=void 0),this.xe&&(E.removeEventListener("offline",this.xe),this.xe=void 0)),this.ve))try{this._instance.ci(W({},e,{transport:"sendBeacon"}))}catch(a){z.error(a)}this.ve=[]}},lx=class{constructor(e){this.ke=()=>{var a,r,n,o;this.Pe||(this.Pe={});var i=this.scrollElement(),s=this.scrollY(),l=i?Math.max(0,i.scrollHeight-i.clientHeight):0,u=s+(i?.clientHeight||0),c=i?.scrollHeight||0;this.Pe.lastScrollY=Math.ceil(s),this.Pe.maxScrollY=Math.max(s,(a=this.Pe.maxScrollY)!==null&&a!==void 0?a:0),this.Pe.maxScrollHeight=Math.max(l,(r=this.Pe.maxScrollHeight)!==null&&r!==void 0?r:0),this.Pe.lastContentY=u,this.Pe.maxContentY=Math.max(u,(n=this.Pe.maxContentY)!==null&&n!==void 0?n:0),this.Pe.maxContentHeight=Math.max(c,(o=this.Pe.maxContentHeight)!==null&&o!==void 0?o:0)},this._instance=e}getContext(){return this.Pe}resetContext(){var e=this.Pe;return setTimeout(this.ke,0),e}startMeasuringScrollPosition(){nt(E,"scroll",this.ke,{capture:!0}),nt(E,"scrollend",this.ke,{capture:!0}),nt(E,"resize",this.ke)}scrollElement(){if(!this._instance.config.scroll_root_selector)return E?.document.documentElement;var e=Te(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var a of e){var r=E?.document.querySelector(a);if(r)return r}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return E&&(E.scrollY||E.pageYOffset||E.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return E&&(E.scrollX||E.pageXOffset||E.document.documentElement.scrollLeft)||0}},UN=t=>ik(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties),hp=class{constructor(e,a,r,n){this.Te=o=>{var i=this.Re();if(!i||i.sessionId!==o){var s={sessionId:o,props:this.Ie(this._instance)};this.Fe.register({[Iy]:s})}},this._instance=e,this.Ce=a,this.Fe=r,this.Ie=n||UN,this.Ce.onSessionId(this.Te)}Re(){return this.Fe.props[Iy]}getSetOnceProps(){var e,a=(e=this.Re())==null?void 0:e.props;return a?"r"in a?sk(a):{$referring_domain:a.referringDomain,$pathname:a.initialPathName,utm_source:a.utm_source,utm_campaign:a.utm_campaign,utm_medium:a.utm_medium,utm_content:a.utm_content,utm_term:a.utm_term}:{}}getSessionProps(){var e={};return De(gx(this.getSetOnceProps()),((a,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+ly(r)]=a})),e}},oy=ct("[SessionId]"),mp=class{on(e,a){return this.Me.on(e,a)}constructor(e,a,r){var n;if(this.Oe=[],this.Ae=void 0,this.Me=new Vu,this.De=(c,d)=>Math.abs(c-d)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.F=e.config,this.Fe=e.persistence,this.je=void 0,this.Le=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.Ne=a||oo,this.Ue=r||oo;var o=this.F.persistence_name||this.F.token,i=this.F.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*mr(i,60,36e3,oy.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.ze(),this.He="ph_"+o+"_window_id",this.Be="ph_"+o+"_primary_window_exists",this.qe()){var s=Lt.W(this.He),l=Lt.W(this.Be);s&&!l?this.je=s:Lt.V(this.He),Lt.G(this.Be,!0)}if((n=this.F.bootstrap)!=null&&n.sessionID)try{var u=(c=>{var d=c.replace(/-/g,"");if(d.length!==32)throw new Error("Not a valid UUID");if(d[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(d.substring(0,12),16)})(this.F.bootstrap.sessionID);this.We(this.F.bootstrap.sessionID,new Date().getTime(),u)}catch(c){oy.error("Invalid sessionID in bootstrap",c)}this.Ge()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return U(this.Oe)&&(this.Oe=[]),this.Oe.push(e),this.Le&&e(this.Le,this.je),()=>{this.Oe=this.Oe.filter((a=>a!==e))}}qe(){return this.F.persistence!=="memory"&&!this.Fe.wi&&Lt.H()}Ve(e){e!==this.je&&(this.je=e,this.qe()&&Lt.G(this.He,e))}Je(){return this.je?this.je:this.qe()?Lt.W(this.He):null}We(e,a,r){e===this.Le&&a===this._sessionActivityTimestamp&&r===this._sessionStartTimestamp||(this._sessionStartTimestamp=r,this._sessionActivityTimestamp=a,this.Le=e,this.Fe.register({[Jf]:[a,e,r]}))}Ke(){var e=this.Fe.props[Jf];return Te(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.We(null,null,null)}destroy(){clearTimeout(this.Ye),this.Ye=void 0,this.Ae&&E&&(E.removeEventListener("beforeunload",this.Ae,{capture:!1}),this.Ae=void 0),this.Oe=[]}Ge(){this.Ae=()=>{this.qe()&&Lt.V(this.Be)},nt(E,"beforeunload",this.Ae,{capture:!1})}checkAndGetSessionAndWindowId(e,a){if(e===void 0&&(e=!1),a===void 0&&(a=null),this.F.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=a||new Date().getTime(),[n,o,i]=this.Ke(),s=this.Je(),l=yr(i)&&i>0&&Math.abs(r-i)>864e5,u=!1,c=!o,d=!c&&!e&&this.De(r,n);c||d||l?(o=this.Ne(),s=this.Ue(),oy.info("new session ID generated",{sessionId:o,windowId:s,changeReason:{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}}),i=r,u=!0):s||(s=this.Ue(),u=!0);var h=n===0||!e||l?r:n,g=i===0?new Date().getTime():i;return this.Ve(s),this.We(o,h,g),e||this.ze(),u&&this.Oe.forEach((S=>S(o,s,u?{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}:void 0))),{sessionId:o,windowId:s,sessionStartTimestamp:g,changeReason:u?{noSessionId:c,activityTimeout:d,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:n}}ze(){clearTimeout(this.Ye),this.Ye=setTimeout((()=>{var[e]=this.Ke();if(this.De(new Date().getTime(),e)){var a=this.Le;this.resetSessionId(),this.Me.emit("forcedIdleReset",{idleSessionId:a})}}),1.1*this.sessionTimeoutMs)}},qN=["$set_once","$set"],ro=ct("[SiteApps]"),ux=class{constructor(e){this._instance=e,this.Xe=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Qe(e,a){if(a){var r=this.globalsForEvent(a);this.Xe.push(r),this.Xe.length>1e3&&(this.Xe=this.Xe.slice(10))}}get siteAppLoaders(){var e;return(e=te._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance.Ai(this.Qe.bind(this));this.Ze=()=>{e(),this.Xe=[],this.Ze=void 0}}}globalsForEvent(e){var a,r,n,o,i,s,l;if(!e)throw new Error("Event payload is required");var u={},c=this._instance.get_property("$groups")||[],d=this._instance.get_property("$stored_group_properties")||{};for(var[h,g]of Object.entries(d))u[h]={id:c[h],type:h,properties:g};var{$set_once:S,$set:b}=e;return{event:W({},pA(e,qN),{properties:W({},e.properties,b?{$set:W({},(a=(r=e.properties)==null?void 0:r.$set)!==null&&a!==void 0?a:{},b)}:{},S?{$set_once:W({},(n=(o=e.properties)==null?void 0:o.$set_once)!==null&&n!==void 0?n:{},S)}:{}),elements_chain:(i=(s=e.properties)==null?void 0:s.$elements_chain)!==null&&i!==void 0?i:"",distinct_id:(l=e.properties)==null?void 0:l.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:u}}setupSiteApp(e){var a=this.apps[e.id],r=()=>{var s;!a.errored&&this.Xe.length&&(ro.info("Processing "+this.Xe.length+" events for site app with id "+e.id),this.Xe.forEach((l=>a.processEvent==null?void 0:a.processEvent(l))),a.processedBuffer=!0),Object.values(this.apps).every((l=>l.processedBuffer||l.errored))&&((s=this.Ze)==null||s.call(this))},n=!1,o=s=>{a.errored=!s,a.loaded=!0,ro.info("Site app with id "+e.id+" "+(s?"loaded":"errored")),n&&r()};try{var{processEvent:i}=e.init({posthog:this._instance,callback:s=>{o(s)}});i&&(a.processEvent=i),n=!0}catch(s){ro.error("Error while initializing PostHog app with config id "+e.id,s),o(!1)}if(n&&a.loaded)try{r()}catch(s){ro.error("Error while processing buffered events PostHog app with config id "+e.id,s),a.errored=!0}}tr(){var e=this.siteAppLoaders||[];for(var a of e)this.apps[a.id]={id:a.id,loaded:!1,errored:!1,processedBuffer:!1};for(var r of e)this.setupSiteApp(r)}ir(e){if(Object.keys(this.apps).length!==0){var a=this.globalsForEvent(e);for(var r of Object.values(this.apps))try{r.processEvent==null||r.processEvent(a)}catch(n){ro.error("Error while processing event "+e.event+" for site app "+r.id,n)}}}onRemoteConfig(e){var a,r,n,o=this;if((a=this.siteAppLoaders)!=null&&a.length)return this.isEnabled?(this.tr(),void this._instance.on("eventCaptured",(u=>this.ir(u)))):void ro.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((r=this.Ze)==null||r.call(this),(n=e.siteApps)!=null&&n.length)if(this.isEnabled){var i=function(u){var c;te["__$$ph_site_app_"+u]=o._instance,(c=te.__PosthogExtensions__)==null||c.loadSiteApp==null||c.loadSiteApp(o._instance,l,(d=>{if(d)return ro.error("Error while initializing PostHog app with config id "+u,d)}))};for(var{id:s,url:l}of e.siteApps)i(s)}else ro.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}},gk=function(t,e){if(!t)return!1;var a=t.userAgent;if(a&&C1(a,e))return!0;try{var r=t?.userAgentData;if(r!=null&&r.brands&&r.brands.some((n=>C1(n?.brand,e))))return!0}catch{}return!!t.webdriver},Ou=(function(t){return t.US="us",t.EU="eu",t.CUSTOM="custom",t})({}),lA="i.posthog.com",cx=class{constructor(e){this.er={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,a=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return a||(a=this.apiHost.replace("."+lA,".posthog.com")),a==="https://app.posthog.com"?"https://us.posthog.com":a}get region(){return this.er[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.er[this.apiHost]=Ou.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.er[this.apiHost]=Ou.EU:this.er[this.apiHost]=Ou.CUSTOM),this.er[this.apiHost]}endpointFor(e,a){if(a===void 0&&(a=""),a&&(a=a[0]==="/"?a:"/"+a),e==="ui")return this.uiHost+a;if(e==="flags")return this.flagsApiHost+a;if(this.region===Ou.CUSTOM)return this.apiHost+a;var r=lA+a;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}},zN={icontains:(t,e)=>!!E&&e.href.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>!!E&&e.href.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>!!E&&pp(e.href,t),not_regex:(t,e)=>!!E&&!pp(e.href,t),exact:(t,e)=>e.href===t,is_not:(t,e)=>e.href!==t},dx=class t{constructor(e){var a=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),a.getWebExperiments((n=>{t.rr("retrieved web experiments from the server"),a.sr=new Map,n.forEach((o=>{if(o.feature_flag_key){var i;a.sr&&(t.rr("setting flag key ",o.feature_flag_key," to web experiment ",o),(i=a.sr)==null||i.set(o.feature_flag_key,o));var s=a._instance.getFeatureFlag(o.feature_flag_key);ut(s)&&o.variants[s]&&a.nr(o.name,s,o.variants[s].transforms)}else if(o.variants)for(var l in o.variants){var u=o.variants[l];t.ar(u)&&a.nr(o.name,l,u.transforms)}}))}),r)},this._instance=e,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}onFeatureFlags(e){if(this._is_bot())t.rr("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(Ie(this.sr))return this.sr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();t.rr("applying feature flags",e),e.forEach((a=>{var r;if(this.sr&&(r=this.sr)!=null&&r.has(a)){var n,o=this._instance.getFeatureFlag(a),i=(n=this.sr)==null?void 0:n.get(a);o&&i!=null&&i.variants[o]&&this.nr(i.name,o,i.variants[o].transforms)}}))}}previewWebExperiment(){var e=t.getWindowLocation();if(e!=null&&e.search){var a=ip(e?.search,"__experiment_id"),r=ip(e?.search,"__experiment_variant");a&&r&&(t.rr("previewing web experiments "+a+" && "+r),this.getWebExperiments((n=>{this.lr(parseInt(a),r,n)}),!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,a,r){if(this._instance.config.disable_web_experiments&&!r)return e([]);var n=this._instance.get_property("$web_experiments");if(n&&!a)return e(n);this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:o=>{if(o.statusCode!==200||!o.json)return e([]);var i=o.json.experiments||[];return e(i)}})}lr(e,a,r){var n=r.filter((o=>o.id===e));n&&n.length>0&&(t.rr("Previewing web experiment ["+n[0].name+"] with variant ["+a+"]"),this.nr(n[0].name,a,n[0].variants[a].transforms))}static ar(e){return!Ie(e.conditions)&&t.ur(e)&&t.hr(e)}static ur(e){var a;if(Ie(e.conditions)||Ie((a=e.conditions)==null?void 0:a.url))return!0;var r,n,o,i=t.getWindowLocation();return!!i&&((r=e.conditions)==null||!r.url||zN[(n=(o=e.conditions)==null?void 0:o.urlMatchType)!==null&&n!==void 0?n:"icontains"](e.conditions.url,i))}static getWindowLocation(){return E?.location}static hr(e){var a;if(Ie(e.conditions)||Ie((a=e.conditions)==null?void 0:a.utm))return!0;var r=ak();if(r.utm_source){var n,o,i,s,l,u,c,d,h=(n=e.conditions)==null||(n=n.utm)==null||!n.utm_campaign||((o=e.conditions)==null||(o=o.utm)==null?void 0:o.utm_campaign)==r.utm_campaign,g=(i=e.conditions)==null||(i=i.utm)==null||!i.utm_source||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_source)==r.utm_source,S=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,b=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==r.utm_term;return h&&S&&b&&g}return!1}static rr(e){for(var a=arguments.length,r=new Array(a>1?a-1:0),n=1;n<a;n++)r[n-1]=arguments[n];z.info("[WebExperiments] "+e,r)}nr(e,a,r){this._is_bot()?t.rr("Refusing to render web experiment since the viewer is a likely bot"):a!=="control"?r.forEach((n=>{if(n.selector){var o;t.rr("applying transform of variant "+a+" for experiment "+e+" ",n);var i=(o=document)==null?void 0:o.querySelectorAll(n.selector);i?.forEach((s=>{var l=s;n.html&&(l.innerHTML=n.html),n.css&&l.setAttribute("style",n.css)}))}})):t.rr("Control variants leave the page unmodified.")}_is_bot(){return va&&this._instance?gk(va,this._instance.config.custom_blocked_useragents):void 0}},VN=ct("[PostHog ExternalIntegrations]"),$N={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},fx=class{constructor(e){this._instance=e}it(e,a){var r;(r=te.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,(n=>{if(n)return VN.error("failed to load script",n);a()}))}startIfEnabledOrStop(){var e=this,a=function(i){var s,l,u;!n||(s=te.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[i]||e.it($N[i],(()=>{var c;(c=te.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[i])==null||c.start(e._instance)})),!n&&(l=te.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[i]&&((u=te.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[i])==null||u.stop())};for(var[r,n]of Object.entries((o=this._instance.config.integrations)!==null&&o!==void 0?o:{})){var o;a(r)}}},px="[SessionRecording]",Au=ct(px),gp=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 Au.error("started without valid sessionManager"),new Error(px+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(px+' cannot be used with cookieless_mode="always"')}get cr(){var e,a=!((e=this._instance.get_property(Wv))==null||!e.enabled),r=!this._instance.config.disable_session_recording,n=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return E&&a&&r&&!n}startIfEnabledOrStop(e){var a;if(!this.cr||(a=this.vr)==null||!a.isStarted){var r=!U(Object.assign)&&!U(Array.from);this.cr&&r?(this.gr(e),Au.info("starting")):this.stopRecording()}}gr(e){var a,r,n;this.cr&&(te!=null&&(a=te.__PosthogExtensions__)!=null&&(a=a.rrweb)!=null&&a.record&&(r=te.__PosthogExtensions__)!=null&&r.initSessionRecording?this._r(e):(n=te.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,this.mr,(o=>{if(o)return Au.error("could not load recorder",o);this._r(e)})))}stopRecording(){var e,a;(e=this.pr)==null||e.call(this),this.pr=void 0,(a=this.vr)==null||a.stop()}yr(){var e;(e=this._instance.persistence)==null||e.unregister(_A)}br(e){if(this._instance.persistence){var a,r,n=this._instance.persistence,o=()=>{var i=e.sessionRecording===!1?void 0:e.sessionRecording,s=i?.sampleRate,l=Ie(s)?null:parseFloat(s);Ie(l)&&this.yr();var u=i?.minimumDurationMilliseconds;n.register({[Wv]:W({enabled:!!i},i,{networkPayloadCapture:W({capturePerformance:e.capturePerformance},i?.networkPayloadCapture),canvasRecording:{enabled:i?.recordCanvas,fps:i?.canvasFps,quality:i?.canvasQuality},sampleRate:l,minimumDurationMilliseconds:U(u)?null:u,endpoint:i?.endpoint,triggerMatchType:i?.triggerMatchType,masking:i?.masking,urlTriggers:i?.urlTriggers})})};o(),(a=this.pr)==null||a.call(this),this.pr=(r=this._instance.sessionManager)==null?void 0:r.onSessionId(o)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.br(e),this.dr=!0,this.startIfEnabledOrStop()):this.dr=!0:Au.info("skipping remote config with no sessionRecording",e)}log(e,a){var r;a===void 0&&(a="log"),(r=this.vr)!=null&&r.log?this.vr.log(e,a):Au.warn("log called before recorder was ready")}get mr(){var e,a,r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(Wv);return(r==null||(a=r.scriptConfig)==null?void 0:a.script)||"lazy-recorder"}_r(e){var a,r;if((a=te.__PosthogExtensions__)==null||!a.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.vr||(this.vr=(r=te.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance),this.vr._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.vr.start(e)}onRRwebEmit(e){var a;(a=this.vr)==null||a.onRRwebEmit==null||a.onRRwebEmit(e)}overrideLinkedFlag(){var e,a;this.vr||(a=this._instance.persistence)==null||a.register({$replay_override_linked_flag:!0}),(e=this.vr)==null||e.overrideLinkedFlag()}overrideSampling(){var e,a;this.vr||(a=this._instance.persistence)==null||a.register({$replay_override_sampling:!0}),(e=this.vr)==null||e.overrideSampling()}overrideTrigger(e){var a,r;this.vr||(r=this._instance.persistence)==null||r.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(a=this.vr)==null||a.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.vr)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,a){var r;return!((r=this.vr)==null||!r.tryAddCustomEvent(e,a))}},Nu={},hx=()=>{},Rs="posthog",vk=!MN&&ea?.indexOf("MSIE")===-1&&ea?.indexOf("Mozilla")===-1,uA=t=>{var e;return W({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:PF(q?.location),persistence:"localStorage+cookie",persistence_name:"",loaded:hx,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,debug:ta&&ut(ta?.search)&&ta.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(E==null||(e=E.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:a=>{var r="Bad HTTP status: "+a.statusCode+" "+a.text;z.error(r)},get_device_id:a=>a,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:ox},error_tracking:{},_onCapture:hx,__preview_eager_load_replay:!1},(a=>({rageclick:!(a&&a>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(a&&a>="2025-05-24")||"history_change",session_recording:a&&a>="2025-11-30"?{strictMinimumDuration:!0}:{}}))(t))},cA=t=>{var e={};U(t.process_person)||(e.person_profiles=t.process_person),U(t.xhr_headers)||(e.request_headers=t.xhr_headers),U(t.cookie_name)||(e.persistence_name=t.cookie_name),U(t.disable_cookie)||(e.disable_persistence=t.disable_cookie),U(t.store_google)||(e.save_campaign_params=t.store_google),U(t.verbose)||(e.debug=t.verbose);var a=Je({},e,t);return Te(t.property_blacklist)&&(U(t.property_denylist)?a.property_denylist=t.property_blacklist:Te(t.property_denylist)?a.property_denylist=[...t.property_blacklist,...t.property_denylist]:z.error("Invalid value for property_denylist config: "+t.property_denylist)),a},mx=class{constructor(){this.__forceAllowLocalhost=!1}get wr(){return this.__forceAllowLocalhost}set wr(e){z.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},vp=class t{get decideEndpointWasHit(){var e,a;return(e=(a=this.featureFlags)==null?void 0:a.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,a;return(e=(a=this.featureFlags)==null?void 0:a.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new mx,this.Sr=!1,this.version=en.LIB_VERSION,this.Er=new Vu,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=uA(),this.SentryIntegration=Py,this.sentryIntegration=e=>(function(a,r){var n=HA(a,r);return{name:PA,processEvent:o=>n(o)}})(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.$r=!1,this.kr=null,this.Pr=null,this.Tr=null,this.featureFlags=new Qy(this),this.toolbar=new Hy(this),this.scrollManager=new lx(this),this.pageViewManager=new Gy(this),this.surveys=new ax(this),this.experiments=new dx(this),this.exceptions=new Ky(this),this.rateLimiter=new rx(this),this.requestRouter=new cx(this),this.consent=new By(this),this.externalIntegrations=new fx(this),this.people={set:(e,a,r)=>{var n=ut(e)?{[e]:a}:e;this.setPersonProperties(n),r?.({})},set_once:(e,a,r)=>{var n=ut(e)?{[e]:a}:e;this.setPersonProperties(void 0,n),r?.({})}},this.on("eventCaptured",(e=>z.info('send "'+e?.event+'"',e)))}init(e,a,r){if(r&&r!==Rs){var n,o=(n=Nu[r])!==null&&n!==void 0?n:new t;return o._init(e,a,r),Nu[r]=o,Nu[Rs][r]=o,o}return this._init(e,a,r)}_init(e,a,r){var n;if(a===void 0&&(a={}),U(e)||uy(e))return z.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},a.debug=this.Rr(a.debug),this.Ir=a,this.Fr=[],a.person_profiles&&(this.Pr=a.person_profiles),this.set_config(Je({},uA(a.defaults),cA(a),{name:r,token:e})),this.config.on_xhr_error&&z.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=a.disable_compression?void 0:rn.GZipJS;var o=this.Cr();this.persistence=new Fu(this.config,o),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Fu(W({},this.config,{persistence:"sessionStorage"}),o);var i=W({},this.persistence.props),s=W({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Mr=new ix((m=>this.Or(m)),this.config.request_queue_config),this.Ar=new sx(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 mp(this),this.sessionPropsManager=new hp(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?(z.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Dr(l)}),0)):(z.info("Initializing extensions synchronously"),this.Dr(l)),en.DEBUG=en.DEBUG||this.config.debug,en.DEBUG&&z.info("Starting in debug mode",{this:this,config:a,thisC:W({},this.config),p:i,s}),((n=a.bootstrap)==null?void 0:n.distinctID)!==void 0){var u,c,d=this.config.get_device_id(oo()),h=(u=a.bootstrap)!=null&&u.isIdentifiedID?d:a.bootstrap.distinctID;this.persistence.set_property(tn,(c=a.bootstrap)!=null&&c.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:a.bootstrap.distinctID,$device_id:h})}if(this.jr()){var g,S,b=Object.keys(((g=a.bootstrap)==null?void 0:g.featureFlags)||{}).filter((m=>{var v;return!((v=a.bootstrap)==null||(v=v.featureFlags)==null||!v[m])})).reduce(((m,v)=>{var y;return m[v]=((y=a.bootstrap)==null||(y=y.featureFlags)==null?void 0:y[v])||!1,m}),{}),x=Object.keys(((S=a.bootstrap)==null?void 0:S.featureFlagPayloads)||{}).filter((m=>b[m])).reduce(((m,v)=>{var y,_;return(y=a.bootstrap)!=null&&(y=y.featureFlagPayloads)!=null&&y[v]&&(m[v]=(_=a.bootstrap)==null||(_=_.featureFlagPayloads)==null?void 0:_[v]),m}),{});this.featureFlags.receivedFeatureFlags({featureFlags:b,featureFlagPayloads:x})}if(l)this.register_once({distinct_id:xu,$device_id:null},"");else if(!this.get_distinct_id()){var f=this.config.get_device_id(oo());this.register_once({distinct_id:f,$device_id:f},""),this.persistence.set_property(tn,"anonymous")}return nt(E,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),a.segment?iN(this,(()=>this.Lr())):this.Lr(),io(this.config._onCapture)&&this.config._onCapture!==hx&&(z.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(m=>this.config._onCapture(m.event,m)))),this.config.ip&&z.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this}Dr(e){var a=performance.now();this.historyAutocapture=new Ny(this),this.historyAutocapture.startIfEnabled();var r=[];r.push((()=>{new Uy(this).startIfEnabledOrStop()})),r.push((()=>{var n;this.siteApps=new ux(this),(n=this.siteApps)==null||n.init()})),e||r.push((()=>{this.sessionRecording=new gp(this),this.sessionRecording.startIfEnabledOrStop()})),this.config.disable_scroll_properties||r.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),r.push((()=>{this.autocapture=new Ry(this),this.autocapture.startIfEnabled()})),r.push((()=>{this.surveys.loadIfEnabled()})),r.push((()=>{this.heatmaps=new jy(this),this.heatmaps.startIfEnabled()})),r.push((()=>{this.webVitalsAutocapture=new $y(this)})),r.push((()=>{this.exceptionObserver=new Fy(this),this.exceptionObserver.startIfEnabled()})),r.push((()=>{this.deadClicksAutocapture=new lp(this,oN),this.deadClicksAutocapture.startIfEnabled()})),r.push((()=>{if(this.Nr){var n=this.Nr;this.Nr=void 0,this.fi(n)}})),this.Ur(r,a)}Ur(e,a){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-a>=30&&e.length>0)return void setTimeout((()=>{this.Ur(e,a)}),0);var r=e.shift();if(r)try{r()}catch(o){z.error("Error initializing extension:",o)}}var n=Math.round(performance.now()-a);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:n}),this.config.__preview_deferred_init_extensions&&z.info("PostHog extensions initialized ("+n+"ms)")}fi(e){var a,r,n,o,i,s,l,u;if(!q||!q.body)return z.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.fi(e)}),500);this.config.__preview_deferred_init_extensions&&(this.Nr=e),this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=fe(e.supportedCompression,rn.GZipJS)?rn.GZipJS:fe(e.supportedCompression,rn.Base64)?rn.Base64:void 0),(a=e.analytics)!=null&&a.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Pr?this.Pr:"identified_only"}),(r=this.siteApps)==null||r.onRemoteConfig(e),(n=this.sessionRecording)==null||n.onRemoteConfig(e),(o=this.autocapture)==null||o.onRemoteConfig(e),(i=this.heatmaps)==null||i.onRemoteConfig(e),this.surveys.onRemoteConfig(e),(s=this.webVitalsAutocapture)==null||s.onRemoteConfig(e),(l=this.exceptionObserver)==null||l.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(u=this.deadClicksAutocapture)==null||u.onRemoteConfig(e)}Lr(){try{this.config.loaded(this)}catch(e){z.critical("`loaded` function failed",e)}this.zr(),this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.Hr()}),1),new nx(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()&&lo(this.__request_queue,(e=>this.Or(e))),this.__request_queue=[],this.zr()}_handle_unload(){var e,a;this.config.request_batching?(this.Br()&&this.capture("$pageleave"),(e=this.Mr)==null||e.unload(),(a=this.Ar)==null||a.unload()):this.Br()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}ci(e){this.__loaded&&(vk?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=fp(e.url,{ip:this.config.ip?1:0}),e.headers=W({},this.config.request_headers),e.compression=e.compression==="best-available"?this.compression:e.compression,e.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(a=>{var r,n,o,i=W({},a);i.timeout=i.timeout||6e4,i.url=fp(i.url,{_:new Date().getTime().toString(),ver:en.LIB_VERSION,compression:i.compression});var s=(r=i.transport)!==null&&r!==void 0?r:"fetch",l=Xf.filter((c=>!i.disableTransport||!c.transport||!i.disableTransport.includes(c.transport))),u=(n=(o=bA(l,(c=>c.transport===s)))==null?void 0:o.method)!==null&&n!==void 0?n:l[0].method;if(!u)throw new Error("No available transport method");u(i)})(W({},e,{callback:a=>{var r,n;this.rateLimiter.checkForLimiting(a),a.statusCode>=400&&((r=(n=this.config).on_request_error)==null||r.call(n,a)),e.callback==null||e.callback(a)}}))))}Or(e){this.Ar?this.Ar.retriableRequest(e):this.ci(e)}_execute_array(e){var a,r=[],n=[],o=[];lo(e,(s=>{s&&(a=s[0],Te(a)?o.push(s):io(s)?s.call(this):Te(s)&&a==="alias"?r.push(s):Te(s)&&a.indexOf("capture")!==-1&&io(this[a])?o.push(s):n.push(s))}));var i=function(s,l){lo(s,(function(u){if(Te(u[0])){var c=l;De(u,(function(d){c=c[d[0]].apply(c,d.slice(1))}))}else this[u[0]].apply(this,u.slice(1))}),l)};i(r,this),i(n,this),i(o,this)}jr(){var e,a;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((a=this.config.bootstrap)==null?void 0:a.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,a,r){var n;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Mr){if(this.is_capturing())if(!U(e)&&ut(e)){var o=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(o&&!this.config.__preview_capture_bot_pageviews)){var i=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(i==null||!i.isRateLimited){a!=null&&a.$current_url&&!ut(a?.$current_url)&&(z.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),a==null||delete a.$current_url),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var s=new Date,l=r?.timestamp||s,u=oo(),c={uuid:u,event:e,properties:this.calculateEventProperties(e,a||{},l,u)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&o&&(c.event="$bot_pageview",c.properties.$browser_type="bot"),i&&(c.properties.$lib_rate_limit_remaining_tokens=i.remainingTokens),r?.$set&&(c.$set=r?.$set);var d,h=this.qr(r?.$set_once);if(h&&(c.$set_once=h),(c=FF(c,r!=null&&r._noTruncate?null:this.config.properties_string_max_length)).timestamp=l,U(r?.timestamp)||(c.properties.$event_time_override_provided=!0,c.properties.$event_time_override_system_time=s),e===Yf.DISMISSED||e===Yf.SENT){var g=a?.[oA.SURVEY_ID],S=a?.[oA.SURVEY_ITERATION];d={id:g,current_iteration:S},localStorage.getItem(iA(d))||localStorage.setItem(iA(d),"true"),c.$set=W({},c.$set,{[FN({id:g,current_iteration:S},e===Yf.SENT?"responded":"dismissed")]:!0})}var b=W({},c.properties.$set,c.$set);if(Ms(b)||this.setPersonPropertiesForFlags(b),!Ie(this.config.before_send)){var x=this.Wr(c);if(!x)return;c=x}this.Er.emit("eventCaptured",c);var f={method:"POST",url:(n=r?._url)!==null&&n!==void 0?n:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:c,compression:"best-available",batchKey:r?._batchKey};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Or(f):this.Mr.enqueue(f),c}z.critical("This capture call is ignored due to client rate limiting.")}}else z.error("No event name provided to posthog.capture")}else z.uninitializedWarning("posthog.capture")}Ai(e){return this.on("eventCaptured",(a=>e(a.event,a)))}calculateEventProperties(e,a,r,n,o){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return a;var i=o?void 0:this.persistence.remove_event_timer(e),s=W({},a);if(s.token=this.config.token,s.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(s.$cookieless_mode=!0),e==="$snapshot"){var l=W({},this.persistence.properties(),this.sessionPersistence.properties());return s.distinct_id=l.distinct_id,(!ut(s.distinct_id)&&!yr(s.distinct_id)||uy(s.distinct_id))&&z.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),s}var u,c=CN(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:d,windowId:h}=this.sessionManager.checkAndGetSessionAndWindowId(o,r.getTime());s.$session_id=d,s.$window_id=h}this.sessionPropsManager&&Je(s,this.sessionPropsManager.getSessionProps());try{var g;this.sessionRecording&&Je(s,this.sessionRecording.sdkDebugProperties),s.$sdk_debug_retry_queue_size=(g=this.Ar)==null?void 0:g.length}catch(f){s.$sdk_debug_error_capturing_properties=String(f)}if(this.requestRouter.region===Ou.CUSTOM&&(s.$lib_custom_api_host=this.config.api_host),u=e!=="$pageview"||o?e!=="$pageleave"||o?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,n),s=Je(s,u),e==="$pageview"&&q&&(s.title=q.title),!U(i)){var S=r.getTime()-i;s.$duration=parseFloat((S/1e3).toFixed(3))}ea&&this.config.opt_out_useragent_filter&&(s.$browser_type=this._is_bot()?"bot":"browser"),(s=Je({},c,this.persistence.properties(),this.sessionPersistence.properties(),s)).$is_identified=this._isIdentified(),Te(this.config.property_denylist)?De(this.config.property_denylist,(function(f){delete s[f]})):z.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&(z.error("sanitize_properties is deprecated. Use before_send instead"),s=b(s,e));var x=this.Gr();return s.$process_person_profile=x,x&&!o&&this.Vr("_calculate_event_properties"),s}qr(e){var a;if(!this.persistence||!this.Gr()||this.Sr)return e;var r=this.persistence.get_initial_props(),n=(a=this.sessionPropsManager)==null?void 0:a.getSetOnceProps(),o=Je({},r,n||{},e||{}),i=this.config.sanitize_properties;return i&&(z.error("sanitize_properties is deprecated. Use before_send instead"),o=i(o,"$set_once")),this.Sr=!0,Ms(o)?void 0:o}register(e,a){var r;(r=this.persistence)==null||r.register(e,a)}register_once(e,a,r){var n;(n=this.persistence)==null||n.register_once(e,a,r)}register_for_session(e){var a;(a=this.sessionPersistence)==null||a.register(e)}unregister(e){var a;(a=this.persistence)==null||a.unregister(e)}unregister_for_session(e){var a;(a=this.sessionPersistence)==null||a.unregister(e)}Jr(e,a){this.register({[e]:a})}getFeatureFlag(e,a){return this.featureFlags.getFeatureFlag(e,a)}getFeatureFlagPayload(e){var a=this.featureFlags.getFeatureFlagPayload(e);try{return JSON.parse(a)}catch{return a}}isFeatureEnabled(e,a){return this.featureFlags.isFeatureEnabled(e,a)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateEarlyAccessFeatureEnrollment(e,a,r){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,a,r)}getEarlyAccessFeatures(e,a,r){return a===void 0&&(a=!1),this.featureFlags.getEarlyAccessFeatures(e,a,r)}on(e,a){return this.Er.on(e,a)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var a,r;return(a=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&a!==void 0?a:()=>{}}getSurveys(e,a){a===void 0&&(a=!1),this.surveys.getSurveys(e,a)}getActiveMatchingSurveys(e,a){a===void 0&&(a=!1),this.surveys.getActiveMatchingSurveys(e,a)}renderSurvey(e,a){this.surveys.renderSurvey(e,a)}displaySurvey(e,a){a===void 0&&(a=PN),this.surveys.displaySurvey(e,a)}cancelPendingSurvey(e){this.surveys.cancelPendingSurvey(e)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,a){return a===void 0&&(a=!1),this.surveys.canRenderSurveyAsync(e,a)}identify(e,a,r){if(!this.__loaded||!this.persistence)return z.uninitializedWarning("posthog.identify");if(yr(e)&&(e=e.toString(),z.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))z.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(e!==xu){if(this.Vr("posthog.identify")){var n=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var o=n;this.register_once({$had_persisted_distinct_id:!0,$device_id:o},"")}e!==n&&e!==this.get_property(ku)&&(this.unregister(ku),this.register({distinct_id:e}));var i=(this.persistence.get_property(tn)||"anonymous")==="anonymous";e!==n&&i?(this.persistence.set_property(tn,"identified"),this.setPersonPropertiesForFlags(W({},r||{},a||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:n},{$set:a||{},$set_once:r||{}}),this.Tr=eA(e,a,r),this.featureFlags.setAnonymousDistinctId(n)):(a||r)&&this.setPersonProperties(a,r),e!==n&&(this.reloadFeatureFlags(),this.unregister(ep))}}else z.critical('The string "'+xu+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else z.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,a){if((e||a)&&this.Vr("posthog.setPersonProperties")){var r=eA(this.get_distinct_id(),e,a);this.Tr!==r?(this.setPersonPropertiesForFlags(W({},a||{},e||{})),this.capture("$set",{$set:e||{},$set_once:a||{}}),this.Tr=r):z.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,a,r){if(e&&a){if(this.Vr("posthog.group")){var n=this.getGroups();n[e]!==a&&this.resetGroupPropertiesForFlags(e),this.register({$groups:W({},n,{[e]:a})}),r&&(this.capture("$groupidentify",{$group_type:e,$group_key:a,$group_set:r}),this.setGroupPropertiesForFlags({[e]:r})),n[e]===a||r||this.reloadFeatureFlags()}}else z.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,a){a===void 0&&(a=!0),this.featureFlags.setPersonPropertiesForFlags(e,a)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,a){a===void 0&&(a=!0),this.Vr("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,a)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var a,r,n,o;if(z.info("reset"),!this.__loaded)return z.uninitializedWarning("posthog.reset");var i=this.get_property("$device_id");if(this.consent.reset(),(a=this.persistence)==null||a.clear(),(r=this.sessionPersistence)==null||r.clear(),this.surveys.reset(),this.featureFlags.reset(),(n=this.persistence)==null||n.set_property(tn,"anonymous"),(o=this.sessionManager)==null||o.resetSessionId(),this.Tr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:xu,$device_id:null},"");else{var s=this.config.get_device_id(oo());this.register_once({distinct_id:s,$device_id:e?s:i},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,a;return(e=(a=this.sessionManager)==null?void 0:a.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:a,sessionStartTimestamp:r}=this.sessionManager.checkAndGetSessionAndWindowId(!0),n=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+a);if(e!=null&&e.withTimestamp&&r){var o,i=(o=e.timestampLookBack)!==null&&o!==void 0?o:10;if(!r)return n;n+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-i,0)}return n}alias(e,a){return e===this.get_property(SA)?(z.critical("Attempting to create alias for existing People user - aborting."),-2):this.Vr("posthog.alias")?(U(a)&&(a=this.get_distinct_id()),e!==a?(this.Jr(ku,e),this.capture("$create_alias",{alias:e,distinct_id:a})):(z.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var a=W({},this.config);if(mt(e)){var r,n,o,i,s;Je(this.config,cA(e));var l=this.Cr();(r=this.persistence)==null||r.update_config(this.config,a,l),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Fu(W({},this.config,{persistence:"sessionStorage"}),l);var u=this.Rr(this.config.debug);so(u)&&(this.config.debug=u),so(this.config.debug)&&(this.config.debug?(en.DEBUG=!0,Ge.H()&&Ge.G("ph_debug","true"),z.info("set_config",{config:e,oldConfig:a,newConfig:W({},this.config)})):(en.DEBUG=!1,Ge.H()&&Ge.V("ph_debug"))),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),(o=this.autocapture)==null||o.startIfEnabled(),(i=this.heatmaps)==null||i.startIfEnabled(),this.surveys.loadIfEnabled(),this.Kr(),(s=this.externalIntegrations)==null||s.startIfEnabledOrStop()}}startSessionRecording(e){var a=e===!0,r={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};if(Object.values(r).some(Boolean)){var n,o,i,s,l;(n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),r.sampling&&((o=this.sessionRecording)==null||o.overrideSampling()),r.linked_flag&&((i=this.sessionRecording)==null||i.overrideLinkedFlag()),r.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),r.event_trigger&&((l=this.sessionRecording)==null||l.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,a){var r=new Error("PostHog syntheticException"),n=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(W({},n,a))}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var a;return(a=this.persistence)==null?void 0:a.props[e]}getSessionProperty(e){var a;return(a=this.sessionPersistence)==null?void 0:a.props[e]}toString(){var e,a=(e=this.config.name)!==null&&e!==void 0?e:Rs;return a!==Rs&&(a=Rs+"."+a),a}_isIdentified(){var e,a;return((e=this.persistence)==null?void 0:e.get_property(tn))==="identified"||((a=this.sessionPersistence)==null?void 0:a.get_property(tn))==="identified"}Gr(){var e,a;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&Ms(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[ku])&&((a=this.persistence)==null||(a=a.props)==null||!a[ap]))}Br(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Gr()||this.Vr("posthog.createPersonProfile")&&this.setPersonProperties({},{})}Vr(e){return this.config.person_profiles==="never"?(z.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Jr(ap,!0),!0)}Cr(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),a=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!a}Kr(){var e,a,r,n,o=this.Cr();return((e=this.persistence)==null?void 0:e.wi)!==o&&((r=this.persistence)==null||r.set_disabled(o)),((a=this.sessionPersistence)==null?void 0:a.wi)!==o&&((n=this.sessionPersistence)==null||n.set_disabled(o)),o}opt_in_capturing(e){var a;if(this.config.cookieless_mode!=="always"){var r,n;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(r=this.sessionManager)==null||r.destroy(),this.sessionManager=new mp(this),this.persistence&&(this.sessionPropsManager=new hp(this,this.sessionManager,this.persistence)),this.sessionRecording=new gp(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this.Kr(),this.zr(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(U(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((n=e?.captureEventName)!==null&&n!==void 0?n:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hr()}else z.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,a;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this.Kr(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:xu,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(a=this.sessionRecording)==null||a.stopRecording(),this.sessionRecording=void 0,this.Hr())):z.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===an.GRANTED?"granted":e===an.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 va?gk(va,this.config.custom_blocked_useragents):void 0}Hr(){q&&(q.visibilityState==="visible"?this.$r||(this.$r=!0,this.capture("$pageview",{title:q.title},{send_instantly:!0}),this.kr&&(q.removeEventListener("visibilitychange",this.kr),this.kr=null)):this.kr||(this.kr=this.Hr.bind(this),nt(q,"visibilitychange",this.kr)))}debug(e){e===!1?(E?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(E?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}O(){var e,a,r,n,o,i,s,l=this.Ir||{};return"advanced_disable_flags"in l?!!l.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(z.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(r="advanced_disable_decide",n=!1,o=z,i=(a="advanced_disable_flags")in(e=l)&&!U(e[a]),s=r in e&&!U(e[r]),i?e[a]:s?(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+a+"' instead. The old field will be removed in a future major version."),e[r]):n)}Wr(e){if(Ie(this.config.before_send))return e;var a=Te(this.config.before_send)?this.config.before_send:[this.config.before_send],r=e;for(var n of a){if(r=n(r),Ie(r)){var o="Event '"+e.event+"' was rejected in beforeSend function";return xF(e.event)?z.warn(o+". This can cause unexpected behavior."):z.info(o),null}r.properties&&!Ms(r.properties)||z.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return r}getPageViewId(){var e;return(e=this.pageViewManager.Vt)==null?void 0:e.pageViewId}captureTraceFeedback(e,a){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:a})}captureTraceMetric(e,a,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:a,$ai_metric_value:String(r)})}Rr(e){var a=so(e)&&!e,r=Ge.H()&&Ge.q("ph_debug")==="true";return!a&&(!!r||e)}};(function(t,e){for(var a=0;a<e.length;a++)t.prototype[e[a]]=BF(t.prototype[e[a]])})(vp,["identify"]);var dA,yk=(dA=Nu[Rs]=new vp,(function(){function t(){t.done||(t.done=!0,vk=!1,De(Nu,(function(e){e._dom_loaded()})))}q!=null&&q.addEventListener?q.readyState==="complete"?t():nt(q,"DOMContentLoaded",t,{capture:!1}):E&&z.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),dA);var Ix=class{constructor(e={}){this.options=e;j(this,"client");j(this,"featureFlagsCallback");j(this,"captureCallback");j(this,"consentUnsub");if(this.client=e.client,this.featureFlagsCallback=e.onFeatureFlagsLoaded,this.captureCallback=e.onCapture,!this.client&&e.consent&&e.requireExplicitConsent&&typeof window<"u"&&e.apiKey){let a=e.consent;a.getStatus()==="granted"&&this.initPostHog(),this.consentUnsub=a.subscribe(n=>{n==="granted"?this.client?this.client.opt_in_capturing():this.initPostHog():n==="denied"&&this.client&&this.client.opt_out_capturing()});return}!this.client&&typeof window<"u"&&e.apiKey&&this.initPostHog()}initPostHog(){let e=this.options;if(!e.apiKey)return;let a=e.enableFeatureFlags??!0,r=`syntro_${e.apiKey.slice(-6)||"sdk"}`;this.client=yk.init(e.apiKey,{api_host:e.apiHost??"https://telemetry.syntrologie.com",advanced_disable_feature_flags:!a,advanced_disable_feature_flags_on_first_load:!a,autocapture:e.autocapture??!0,capture_pageview:e.capturePageview??!0,capture_pageleave:e.capturePageleave??!0,disable_session_recording:!(e.sessionRecording??!0),opt_out_useragent_filter:!0,session_recording:{recordCrossDomainIFrames:!0},capture_performance:!0,enable_recording_console_log:!0,loaded:n=>{if(a&&this.featureFlagsCallback){n.onFeatureFlags(()=>{let i=this.getAllFeatureFlags();i&&this.featureFlagsCallback&&this.featureFlagsCallback(i)});let o=this.getAllFeatureFlags();o&&Object.keys(o).length>0&&this.featureFlagsCallback(o)}this.captureCallback&&n.on("eventCaptured",o=>{let i=typeof o=="string"?o:o?.event,s=typeof o=="string"?void 0:o?.properties;typeof i=="string"&&this.captureCallback?.(i,s)})}},r)}getAllFeatureFlags(){return this.client?.featureFlags?.getFlagVariants?.()}getSegmentFlags(){let e=this.getAllFeatureFlags();if(!e)return{};let a={};for(let[r,n]of Object.entries(e))r.startsWith("in_segment_")&&(a[r]=n===!0);return a}identify(e,a){this.client?.identify(e,a)}alias(e,a){this.client?.alias(e,a)}track(e,a){this.client?.capture(e,a)}trackCanvasOpened(e){this.track("shadow_canvas_opened",{surface:e})}trackCanvasClosed(e){this.track("shadow_canvas_closed",{surface:e})}trackRectangleViewed(e,a){this.track("shadow_canvas_rectangle_viewed",{rectangleId:e,surface:a})}trackAction(e,a,r){this.track("shadow_canvas_action",{action:e,rectangleId:a,surface:r})}register(e){this.client?.register?.(e)}getSessionId(){return this.client?.get_session_id?.()}startSessionRecording(){this.client?.startSessionRecording?.()}trackExperiment(e,a,r){let n=`$experiment_${e}`;this.register({[n]:r??`variation_${a}`,[`${n}_id`]:a}),this.track("$experiment_started",{$experiment_key:e,$experiment_variation_id:a,$experiment_variation_name:r??`variation_${a}`})}setPersonProperties(e){this.client?.capture("$set",{$set:e})}setPersonPropertiesOnce(e){this.client?.capture("$set",{$set_once:e})}getDistinctId(){return this.client?.get_distinct_id?.()}};function Ax(t={}){return new Ix(t)}var kx=async(t,e)=>{let a=[];if(e.applyAction)for(let r of t.actions){let n=await e.applyAction(r);a.push(n)}return{cleanup:async()=>{for(let r=a.length-1;r>=0;r--)try{await a[r].revert()}catch{}}}},Ex=async(t,e)=>{let a=[];if(e.applyAction){let r=t.actions.map(n=>e.applyAction(n));if(t.waitFor==="any"){let n=await Promise.race(r);a.push(n);let o=await Promise.allSettled(r);for(let i of o)i.status==="fulfilled"&&i.value!==n&&a.push(i.value)}else{let n=await Promise.all(r);a.push(...n)}}return{cleanup:async()=>{for(let r of a)try{await r.revert()}catch{}}}},Tx=async(t,e)=>{let a,r,n=!1,o={cleanup:()=>{n=!0,r&&clearTimeout(r),a&&a()}};return t.event&&e.subscribeEvent?await new Promise(i=>{a=e.subscribeEvent(t.event,()=>{n||i()}),t.durationMs!==void 0&&(r=setTimeout(()=>{n||i()},t.durationMs))}):t.durationMs!==void 0&&await new Promise(i=>{r=setTimeout(()=>{n||i()},t.durationMs)}),o};var Sp=class{constructor(){j(this,"executors",new Map);for(let{kind:e,executor:a}of _g)this.registerCore(e,a);for(let{kind:e,executor:a}of Bg)this.registerCore(e,a);this.registerCore("core:mountWidget",async()=>{throw new Error("core:mountWidget must be handled by ActionEngine")}),this.registerCore("core:sequence",kx),this.registerCore("core:parallel",Ex),this.registerCore("core:wait",Tx)}registerCore(e,a,r){this.executors.set(e,{kind:e,executor:a,schema:r,source:"core",isBuiltIn:!0})}register(e,a,r,n="custom",o=!1){if(this.executors.has(e)){if(this.executors.get(e).isBuiltIn)return;console.warn(`[ExecutorRegistry] Overriding executor for kind: ${e} (source: ${n})`)}console.log(`[ExecutorRegistry] Registered executor: ${e} (source: ${n})`),this.executors.set(e,{kind:e,executor:a,schema:r,source:n,isBuiltIn:o})}unregister(e){let a=this.executors.get(e);return a?a.isBuiltIn?(console.warn(`[ExecutorRegistry] Cannot unregister built-in executor: ${e}`),!1):(this.executors.delete(e),!0):!1}unregisterBySource(e){for(let[a,r]of this.executors.entries())r.source===e&&this.executors.delete(a)}get(e){return this.executors.get(e)?.executor}getRegistration(e){return this.executors.get(e)}has(e){return this.executors.has(e)}validate(e){let a=[];if(!e||typeof e!="object")return a.push({code:"INVALID_ACTION",message:"Action must be an object"}),{valid:!1,errors:a,warnings:[]};let{kind:r}=e;if(!r||typeof r!="string")return a.push({code:"MISSING_KIND",message:"Action must have a 'kind' property"}),{valid:!1,errors:a,warnings:[]};let n=this.executors.get(r);if(!n)return a.push({code:"UNKNOWN_KIND",message:`Unknown action kind: ${r}`,field:"kind"}),{valid:!1,errors:a,warnings:[]};if(n.schema){let o=n.schema.safeParse(e);if(!o.success){for(let i of o.error.issues)a.push({code:"SCHEMA_VALIDATION_ERROR",message:i.message,field:i.path.join(".")});return{valid:!1,errors:a,warnings:[]}}}return{valid:!0,errors:[],warnings:[]}}list(){return Array.from(this.executors.keys())}listRegistrations(){return Array.from(this.executors.values())}getBuiltInKinds(){return Array.from(this.executors.entries()).filter(([,e])=>e.isBuiltIn).map(([e])=>e)}getCustomKinds(){return Array.from(this.executors.entries()).filter(([,e])=>!e.isBuiltIn).map(([e])=>e)}},on=new Sp;function jN(t){return on.get(t)}function Rx(t){return on.has(t)}var GN=new Set(["onclick","onerror","onload","onmouseover","onfocus","onblur","onchange","onsubmit","onkeydown","onkeyup","onkeypress"]),xk=5e4,bk=50;function fo(t){let e=[],a=[];if(!t||typeof t!="object")return e.push({code:"INVALID_ACTION",message:"Action must be an object"}),{valid:!1,errors:e,warnings:a};let{kind:r}=t;if(!r||typeof r!="string")return e.push({code:"MISSING_KIND",message:"Action must have a 'kind' property"}),{valid:!1,errors:e,warnings:a};if(!Rx(r)&&r!=="core:mountWidget"){let n=on.list();return console.error(`[ActionValidation] Unknown action kind: "${r}". Registered kinds (${n.length}): [${n.join(", ")}]. This usually means the app that provides "${r}" hasn't been activated yet, or the executor was never registered in ExecutorRegistry.`),e.push({code:"UNKNOWN_KIND",message:`Unknown action kind: ${r}`,field:"kind"}),{valid:!1,errors:e,warnings:a}}switch(r){case"overlays:highlight":case"overlays:pulse":case"navigation:scrollTo":co(t,e,a);break;case"overlays:badge":co(t,e,a),WN(t,e,a);break;case"overlays:tooltip":co(t,e,a),ZN(t,e,a);break;case"overlays:modal":oP(t,e,a);break;case"content:insertHtml":co(t,e,a),XN(t,e,a);break;case"content:setText":co(t,e,a),YN(t,e,a);break;case"content:setAttr":co(t,e,a),KN(t,e,a);break;case"content:addClass":case"content:removeClass":co(t,e,a),QN(t,e,a);break;case"content:setStyle":co(t,e,a),JN(t,e,a);break;case"core:mountWidget":eP(t,e,a);break;case"core:wait":tP(t,e,a);break;case"core:sequence":aP(t,e,a);break;case"core:parallel":rP(t,e,a);break;case"core:tour":iP(t,e,a);break;case"navigation:navigate":nP(t,e,a);break}return{valid:e.length===0,errors:e,warnings:a}}function co(t,e,a){let r=t.anchorId;if(!r||typeof r!="object"){e.push({code:"MISSING_ANCHOR_ID",message:"Action requires an 'anchorId' object with a 'selector' string",field:"anchorId"});return}if(!r.selector||typeof r.selector!="string"?e.push({code:"MISSING_ANCHOR_SELECTOR",message:"anchorId requires a 'selector' string",field:"anchorId.selector"}):r.selector.length>200&&a.push({code:"LONG_ANCHOR_ID",message:"Anchor selector is unusually long",suggestion:"Consider using a shorter, more descriptive selector"}),r.route===void 0||r.route===null)e.push({code:"MISSING_ANCHOR_ROUTE",message:`anchorId requires a 'route' (string or array of strings). Use "**" for all routes.`,field:"anchorId.route"});else{let n=Array.isArray(r.route)?r.route:[r.route];for(let o of n)if(typeof o!="string"){e.push({code:"INVALID_ANCHOR_ROUTE",message:"anchorId.route must be a string or array of strings",field:"anchorId.route"});break}}}function WN(t,e,a){!t.content||typeof t.content!="string"?e.push({code:"MISSING_CONTENT",message:"Badge action requires 'content' property",field:"content"}):t.content.length>100&&a.push({code:"LONG_BADGE_CONTENT",message:"Badge content is quite long",suggestion:"Keep badge content short (under 100 characters)"})}function ZN(t,e,a){if(!t.content||typeof t.content!="object"){e.push({code:"MISSING_CONTENT",message:"Tooltip action requires 'content' object",field:"content"});return}(!t.content.body||typeof t.content.body!="string")&&e.push({code:"MISSING_BODY",message:"Tooltip content requires 'body' property",field:"content.body"})}function XN(t,e,a){!t.html||typeof t.html!="string"?e.push({code:"MISSING_HTML",message:"insertHtml action requires 'html' property",field:"html"}):t.html.length>xk&&e.push({code:"HTML_TOO_LONG",message:`HTML content exceeds maximum length of ${xk}`,field:"html"});let r=["before","after","prepend","append","replace"];(!t.position||!r.includes(t.position))&&e.push({code:"INVALID_POSITION",message:`Position must be one of: ${r.join(", ")}`,field:"position"})}function YN(t,e,a){(t.text===void 0||t.text===null)&&e.push({code:"MISSING_TEXT",message:"setText action requires 'text' property",field:"text"})}function KN(t,e,a){!t.attr||typeof t.attr!="string"?e.push({code:"MISSING_ATTR",message:"setAttr action requires 'attr' property",field:"attr"}):(GN.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 QN(t,e,a){!t.className||typeof t.className!="string"?e.push({code:"MISSING_CLASS_NAME",message:"Class action requires 'className' property",field:"className"}):/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t.className)||a.push({code:"INVALID_CLASS_NAME",message:"Class name contains unusual characters",suggestion:"Use alphanumeric characters, hyphens, and underscores"})}function JN(t,e,a){if(!t.styles||typeof t.styles!="object")e.push({code:"MISSING_STYLES",message:"setStyle action requires 'styles' object",field:"styles"});else{let r=Object.keys(t.styles).length;r>bk&&e.push({code:"TOO_MANY_STYLES",message:`Too many styles (${r}). Maximum is ${bk}`,field:"styles"});for(let[n,o]of Object.entries(t.styles))typeof o=="string"&&o.includes("expression(")&&e.push({code:"DANGEROUS_STYLE",message:`Style expressions are not allowed: ${n}`,field:`styles.${n}`})}}function eP(t,e,a){(!t.slot||typeof t.slot!="string")&&e.push({code:"MISSING_SLOT",message:"mountWidget action requires 'slot' property",field:"slot"}),!t.widget||typeof t.widget!="object"?e.push({code:"MISSING_WIDGET",message:"mountWidget action requires 'widget' object",field:"widget"}):(!t.widget.widgetId||typeof t.widget.widgetId!="string")&&e.push({code:"MISSING_WIDGET_ID",message:"Widget must have a 'widgetId' property",field:"widget.widgetId"})}function tP(t,e,a){t.durationMs===void 0&&!t.event&&e.push({code:"MISSING_WAIT_CONFIG",message:"wait action requires either 'durationMs' or 'event' property"}),t.durationMs!==void 0&&t.durationMs<0&&e.push({code:"INVALID_DURATION",message:"durationMs must be a positive number",field:"durationMs"}),t.event!==void 0&&typeof t.event!="string"&&e.push({code:"INVALID_EVENT",message:"event must be a string",field:"event"})}function aP(t,e,a){if(!t.actions||!Array.isArray(t.actions)){e.push({code:"MISSING_ACTIONS",message:"sequence action requires 'actions' array",field:"actions"});return}t.actions.length===0&&a.push({code:"EMPTY_SEQUENCE",message:"sequence has no actions",suggestion:"Add at least one action to the sequence"});for(let r=0;r<t.actions.length;r++){let n=fo(t.actions[r]);for(let o of n.errors)e.push({...o,field:`actions[${r}]${o.field?`.${o.field}`:""}`});for(let o of n.warnings)a.push(o)}}function rP(t,e,a){if(!t.actions||!Array.isArray(t.actions)){e.push({code:"MISSING_ACTIONS",message:"parallel action requires 'actions' array",field:"actions"});return}t.actions.length===0&&a.push({code:"EMPTY_PARALLEL",message:"parallel has no actions",suggestion:"Add at least one action to the parallel group"}),t.waitFor&&!["all","any"].includes(t.waitFor)&&e.push({code:"INVALID_WAIT_FOR",message:"waitFor must be 'all' or 'any'",field:"waitFor"});for(let r=0;r<t.actions.length;r++){let n=fo(t.actions[r]);for(let o of n.errors)e.push({...o,field:`actions[${r}]${o.field?`.${o.field}`:""}`});for(let o of n.warnings)a.push(o)}}function nP(t,e,a){if(!t.url||typeof t.url!="string")e.push({code:"MISSING_URL",message:"navigate action requires 'url' property",field:"url"});else{let r=t.url.trim().toLowerCase();r.startsWith("javascript:")&&e.push({code:"DANGEROUS_URL",message:"javascript: URLs are not allowed",field:"url"}),r.startsWith("data:")&&a.push({code:"DATA_URL",message:"data: URLs may have limited support",suggestion:"Consider using a regular URL instead"})}}function oP(t,e,a){if(!t.content||typeof t.content!="object"){e.push({code:"MISSING_CONTENT",message:"Modal action requires 'content' object",field:"content"});return}if((!t.content.body||typeof t.content.body!="string")&&e.push({code:"MISSING_BODY",message:"Modal content requires 'body' property",field:"content.body"}),t.size&&!["sm","md","lg"].includes(t.size)&&e.push({code:"INVALID_SIZE",message:"Modal size must be 'sm', 'md', or 'lg'",field:"size"}),t.ctaButtons)if(!Array.isArray(t.ctaButtons))e.push({code:"INVALID_CTA_BUTTONS",message:"ctaButtons must be an array",field:"ctaButtons"});else for(let r=0;r<t.ctaButtons.length;r++){let n=t.ctaButtons[r];(!n.label||typeof n.label!="string")&&e.push({code:"MISSING_BUTTON_LABEL",message:`CTA button at index ${r} requires 'label' property`,field:`ctaButtons[${r}].label`}),(!n.actionId||typeof n.actionId!="string")&&e.push({code:"MISSING_BUTTON_ACTION_ID",message:`CTA button at index ${r} requires 'actionId' property`,field:`ctaButtons[${r}].actionId`})}}function iP(t,e,a){if((!t.tourId||typeof t.tourId!="string")&&e.push({code:"MISSING_TOUR_ID",message:"Tour action requires 'tourId' property",field:"tourId"}),!t.steps||!Array.isArray(t.steps)){e.push({code:"MISSING_STEPS",message:"Tour action requires 'steps' array",field:"steps"});return}t.steps.length===0&&e.push({code:"EMPTY_STEPS",message:"Tour must have at least one step",field:"steps"});let r=new Set;for(let n=0;n<t.steps.length;n++){let o=t.steps[n];if(!o.id||typeof o.id!="string"?e.push({code:"MISSING_STEP_ID",message:`Step at index ${n} requires 'id' property`,field:`steps[${n}].id`}):(r.has(o.id)&&e.push({code:"DUPLICATE_STEP_ID",message:`Duplicate step ID: ${o.id}`,field:`steps[${n}].id`}),r.add(o.id)),!o.action)e.push({code:"MISSING_STEP_ACTION",message:`Step at index ${n} requires 'action' property`,field:`steps[${n}].action`});else{let i=fo(o.action);for(let s of i.errors)e.push({...s,field:`steps[${n}].action${s.field?`.${s.field}`:""}`});for(let s of i.warnings)a.push(s)}if(o.onAction)for(let[i,s]of Object.entries(o.onAction))s!=="end"&&!t.steps.some(l=>l.id===s)&&a.push({code:"UNKNOWN_TARGET_STEP",message:`Step "${o.id}" references unknown target step: ${s}`,suggestion:`Make sure step "${s}" exists in the tour`})}}function Mx(t){let e=[],a=[];if(!Array.isArray(t))return console.error("[ActionValidation] validateActions called with non-array:",typeof t),e.push({code:"INVALID_ACTIONS",message:"Actions must be an array"}),{valid:!1,errors:e,warnings:a};for(let r=0;r<t.length;r++){let n=fo(t[r]);if(!n.valid){let o=t[r];console.error(`[ActionValidation] Action [${r}] failed validation:`,`kind="${o?.kind??"undefined"}"`,n.errors.map(i=>`${i.code}: ${i.message}`).join("; "),o)}for(let o of n.errors)e.push({...o,field:o.field?`[${r}].${o.field}`:`[${r}]`});for(let o of n.warnings)a.push({...o,suggestion:o.suggestion?`Action ${r}: ${o.suggestion}`:void 0})}return e.length>0&&console.error(`[ActionValidation] Batch validation failed: ${e.length} error(s) in ${t.length} action(s).`,e.map(r=>`${r.field??"?"}: ${r.message}`).join(" | ")),{valid:e.length===0,errors:e,warnings:a}}var sP=0;function Dx(t){let{overlayRoot:e,eventBus:a,surfaces:r,anchorResolver:n,waitForAnchor:o,adaptiveId:i,executorRegistry:s=on,subscribeNavigation:l,runtime:u}=t,c=new Map,d=new Map;function h(){return`action-${++sP}`}function g(C,k){a&&a.publish(C,k)}function S(){return{overlayRoot:e,resolveAnchor:n,waitForAnchor:o,generateId:h,publishEvent:g,adaptiveId:i,applyAction:m,subscribeEvent:a?(C,k)=>a.subscribe({names:[C]},w=>k(w.props)):void 0,subscribeNavigation:l}}async function b(C,k){if(!r)throw new Error("Surfaces provider required for core:mountWidget actions");let w=r.mount(C.slot,{type:"widget",widgetId:C.widget.widgetId,config:C.widget.props},{priority:C.widget.priority});return k.publishEvent("action.applied",{id:k.generateId(),kind:"core:mountWidget",slot:C.slot,widgetId:C.widget.widgetId}),{cleanup:()=>{w.unmount()},updateFn:I=>{if("widget"in I&&I.widget){let T=I.widget;T.props&&w.update({type:"widget",widgetId:C.widget.widgetId,config:T.props})}}}}async function x(C,k){if(C.kind==="core:mountWidget")return b(C,k);let w=s.get(C.kind);if(!w){let I="list"in s?s.list():"(list unavailable)";throw console.error(`[ActionEngine] No executor for kind="${C.kind}".`,`Registered: [${I}]`),new Error(`No executor for action kind: ${C.kind}`)}return w(C,k)}function f(C,k,w,I){if(!u)return;let T=[],D=async()=>{let M=c.get(C);if(!M)return;let F=u.evaluateSync(w).value;if(M.state==="applied"&&!F){try{await M.cleanup()}catch(H){console.error(`[ActionEngine] Error reverting conditional action ${C}:`,H)}M.state="deferred",M.cleanup=()=>{},M.updateFn=void 0,g("action.deferred",{id:C,kind:k.kind})}else if(M.state==="deferred"&&F)try{let H=S(),V=await x(k,H);M.state="applied",M.cleanup=V.cleanup,M.updateFn=V.updateFn,M.appliedTs=Date.now(),g("action.applied",{id:C,kind:k.kind,anchorId:"anchorId"in k?k.anchorId:void 0})}catch(H){console.error(`[ActionEngine] Error applying deferred action ${C}:`,H),M.state="failed"}};u.context&&T.push(u.context.subscribe(D)),u.accumulator&&T.push(u.accumulator.subscribe(D)),d.set(C,T)}async function m(C){let k=fo(C);if(!k.valid){let F=k.errors.map(H=>H.message).join("; ");throw console.error(`[ActionEngine] Validation failed for action kind="${C?.kind}":`,F,C),new Error(`Action validation failed: ${F}`)}let w=h(),I=C.triggerWhen;if(I&&u&&!u.evaluateSync(I).value){let H={id:w,action:C,adaptiveId:i,appliedTs:Date.now(),state:"deferred",cleanup:()=>{}};c.set(w,H);let V={id:w,action:C,async revert(){let N=c.get(w);if(!N)return;let X=d.get(w);if(X){for(let ve of X)ve();d.delete(w)}N.state="reverted",c.delete(w)},isApplied(){return c.get(w)?.state==="applied"},async update(N){let X=c.get(w);if(!X||X.state!=="applied")throw new Error("Cannot update action that is not applied");if(X.updateFn)await X.updateFn(N);else throw new Error(`Action kind ${C.kind} does not support updates`)},getState(){return c.get(w)?.state??"reverted"}};return f(w,C,I,V),V}let T=S(),D=await x(C,T),M={id:w,action:C,adaptiveId:i,appliedTs:Date.now(),state:"applied",cleanup:D.cleanup,updateFn:D.updateFn};c.set(w,M),g("action.applied",{id:w,kind:C.kind,anchorId:"anchorId"in C?C.anchorId:void 0});let B={id:w,action:C,async revert(){let F=c.get(w);if(!F||F.state!=="applied")return;let H=d.get(w);if(H){for(let V of H)V();d.delete(w)}try{await F.cleanup(),F.state="reverted",g("action.reverted",{id:w,kind:C.kind})}catch(V){throw F.state="failed",g("action.failed",{id:w,kind:C.kind,error:String(V)}),V}finally{c.delete(w)}},isApplied(){return c.get(w)?.state==="applied"},async update(F){let H=c.get(w);if(!H||H.state!=="applied")throw new Error("Cannot update action that is not applied");if(H.updateFn)await H.updateFn(F);else throw new Error(`Action kind ${C.kind} does not support updates`)},getState(){return c.get(w)?.state??"reverted"}};return I&&u&&f(w,C,I,B),B}async function v(C){console.log(`[ActionEngine] applyBatch: ${C.length} action(s)`,C.map(M=>M.kind).join(", "));let k=Mx(C);if(!k.valid){let M=k.errors.map(B=>B.message).join("; ");throw console.error(`[ActionEngine] Batch validation FAILED for ${C.length} action(s):`,M,`
|
|
463
463
|
Actions:`,C.map((B,F)=>` [${F}] ${B.kind} ${B.anchorId?`anchor="${typeof B.anchorId=="string"?B.anchorId:B.anchorId.selector}"`:""} ${B.label?`label="${B.label}"`:""}`).join(`
|
|
464
|
-
`)),new Error(`Batch validation failed: ${M}`)}let w=h(),I=[],T=[];try{for(let M of C){let B=await m(M);I.push(B),T.push(B)}}catch(M){console.error(`[ActionEngine] Batch apply FAILED at action ${T.length+1}/${C.length}.`,`Successfully applied: ${T.length}. Rolling back...`,M);for(let B of T)try{await B.revert()}catch{}throw M}return{id:w,handles:I,async revertAll(){for(let M=I.length-1;M>=0;M--)try{await I[M].revert()}catch(B){console.error(`[ActionEngine] Error reverting action ${I[M].id}:`,B)}},isApplied(){return I.every(M=>M.isApplied())}}}function y(C){return fo(C)}function _(){return Array.from(c.values()).map(C=>({id:C.id,action:C.action,adaptiveId:C.adaptiveId,appliedTs:C.appliedTs,state:C.state}))}function L(){for(let C of d.values())for(let k of C)try{k()}catch{}d.clear();for(let C of c.values())if(C.state==="applied")try{C.cleanup()}catch(k){console.error("[ActionEngine] Error during cleanup:",k)}c.clear()}return{apply:m,applyBatch:v,validate:y,getActive:_,destroy:L}}var lP=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),Ox=p.object({type:p.literal("page_url"),url:p.string()}),Bx=p.object({type:p.literal("route"),routeId:p.string()}),Fx=p.object({type:p.literal("anchor_visible"),anchorId:p.string(),state:p.enum(["visible","present","absent"])}),Nx=p.object({type:p.literal("event_occurred"),eventName:p.string(),withinMs:p.number().optional()}),Px=p.object({type:p.literal("state_equals"),key:p.string(),value:p.unknown()}),Hx=p.object({type:p.literal("viewport"),minWidth:p.number().optional(),maxWidth:p.number().optional(),minHeight:p.number().optional(),maxHeight:p.number().optional()}),Ux=p.object({type:p.literal("session_metric"),key:p.string(),operator:p.enum(["gte","lte","eq","gt","lt"]),threshold:p.number()}),qx=p.object({type:p.literal("dismissed"),key:p.string(),inverted:p.boolean().optional()}),zx=p.object({type:p.literal("cooldown_active"),key:p.string(),inverted:p.boolean().optional()}),Vx=p.object({type:p.literal("frequency_limit"),key:p.string(),limit:p.number(),inverted:p.boolean().optional()}),Wu=p.object({equals:p.union([p.string(),p.number(),p.boolean()]).optional(),contains:p.string().optional()}),Zu=p.object({events:p.array(p.string()).min(1),match:p.record(p.string(),Wu).optional()}),$x=p.object({type:p.literal("event_count"),key:p.string(),operator:p.enum(["gte","lte","eq","gt","lt"]),count:p.number().int().min(0),withinMs:p.number().positive().optional(),counter:Zu.optional()}),po=p.discriminatedUnion("type",[Ox,Bx,Fx,Nx,Px,Hx,Ux,qx,zx,Vx,$x]),Xu=p.object({conditions:p.array(po),value:p.unknown()}),Yu=p.object({type:p.literal("rules"),rules:p.array(Xu),default:p.unknown()}),Ku=p.object({type:p.literal("score"),field:p.string(),threshold:p.number(),above:p.unknown(),below:p.unknown()}),Qu=p.object({type:p.literal("model"),modelId:p.string(),inputs:p.array(p.string()),outputMapping:p.record(p.string(),p.unknown()),default:p.unknown()}),Ju=p.object({type:p.literal("external"),endpoint:p.string(),method:p.enum(["GET","POST"]).optional(),default:p.unknown(),timeoutMs:p.number().optional()}),ec=p.discriminatedUnion("type",[Yu,Ku,Qu,Ju]),Cp=ec.nullable().optional(),uP=p.object({events:p.array(p.string()),urlContains:p.string().optional(),props:p.record(p.union([p.string(),p.number(),p.boolean()])).optional()}),cP=p.object({title:p.string().optional(),body:p.string().optional(),icon:p.string().optional()}).nullable().optional();var Sk=p.object({include:p.array(p.string()).optional().describe("URL patterns where this tile appears. Supports *, **, :param wildcards. Use sparingly \u2014 mostly to isolate to specific webapp functionality. Omit to appear on all routes."),exclude:p.array(p.string()).optional().describe("URL patterns where this tile should NOT appear. Evaluated before include.")}),_p=p.object({routes:Sk,onlyIfPopulated:p.boolean().optional().describe("When true, tile is hidden if none of its props.actions[] have an active triggerWhen. Useful for tiles with all-deferred FAQ questions or nav tips. Default: false.")});function Iz(t){return po.safeParse(t)}function Az(t){return ec.safeParse(t)}function kz(t){return _p.safeParse(t)}var Ez=[{defName:"matchOp",schema:Wu},{defName:"counterDef",schema:Zu},{defName:"activationConfig",schema:_p},{defName:"routeFilter",schema:Sk},{defName:"ruleStrategy",schema:Yu},{defName:"scoreStrategy",schema:Ku},{defName:"modelStrategy",schema:Qu},{defName:"externalStrategy",schema:Ju},{defName:"rule",schema:Xu},{defName:"condition",schema:po}];var jx=p.object({tileId:p.string(),itemId:p.string().optional()}).strict(),dP=p.object({on:p.string(),title:p.string(),body:p.string().optional(),icon:p.string().optional(),ttl:p.number().optional(),cooldown:p.number().optional(),deepLink:jx.optional()}).strict(),fP=p.object({id:p.string(),title:p.string().optional(),subtitle:p.string().optional(),icon:p.string().optional(),priority:p.number().optional(),widget:p.string(),props:p.record(p.unknown()).optional(),activation:_p.optional(),notifications:p.array(dP).optional()}).strict(),pP=p.object({position:p.enum(["left","right"]).optional(),layout:p.enum(["overlay","push"]).optional(),background:p.string().optional(),blur:p.string().optional(),border:p.string().optional(),width:p.string().optional(),transitionDuration:p.string().optional(),transitionEasing:p.string().optional(),transitionFade:p.string().optional()}),hP=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),color:p.string().optional(),size:p.string().optional(),shadow:p.string().optional(),borderRadius:p.string().optional()}),mP=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),shadow:p.string().optional(),titleColor:p.string().optional(),textColor:p.string().optional(),iconBackground:p.string().optional(),iconShadow:p.string().optional(),headerPadding:p.string().optional(),bodyPadding:p.string().optional(),gap:p.string().optional()}),gP=p.object({background:p.string().optional(),textColor:p.string().optional(),titleColor:p.string().optional(),arrowColor:p.string().optional(),arrowSize:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),scrimOpacity:p.string().optional(),highlightRing:p.string().optional()}),vP=p.object({background:p.string().optional(),textColor:p.string().optional(),textSecondaryColor:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),successColor:p.string().optional(),warningColor:p.string().optional(),errorColor:p.string().optional(),iconBackground:p.string().optional(),progressGradient:p.string().optional()}),yP=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),textColor:p.string().optional(),textSecondaryColor:p.string().optional(),itemDivider:p.string().optional(),itemGap:p.string().optional(),itemPadding:p.string().optional(),itemFontSize:p.string().optional(),bodyPadding:p.string().optional(),bodyFontSize:p.string().optional(),categoryPadding:p.string().optional(),categoryGap:p.string().optional(),categoryFontSize:p.string().optional(),searchBackground:p.string().optional(),searchColor:p.string().optional(),chevronColor:p.string().optional()}),xP=p.object({mode:p.enum(["dark","light"]).optional(),fontFamily:p.string().optional(),colorPrimary:p.string().optional(),colorPrimaryHover:p.string().optional(),borderRadius:p.string().optional(),canvas:pP.optional(),launcher:hP.optional(),tile:mP.optional(),overlay:gP.optional(),notification:vP.optional(),content:yP.optional()}).strict(),bP=p.object({enabled:p.boolean().optional(),label:p.string().optional(),icon:p.string().optional(),position:p.string().optional(),animate:p.boolean().optional(),animationStyle:p.enum(["pulse","bounce","glow"]).optional(),notificationCount:p.number().optional()}).strict(),Oz=p.object({schemaVersion:p.string().optional(),fetchedAt:p.string().datetime(),configVersion:p.string().optional(),canvasTitle:p.string().optional(),tiles:p.array(fP),actions:p.array(p.any()),theme:xP.optional(),launcher:bP.optional(),meta:p.object({verificationSteps:p.array(p.union([p.string(),p.object({text:p.string(),check:po.optional()})])).optional()}).passthrough().optional()}).strict();var gt={triggerWhen:Cp},Pa=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),Ck=p.object({color:p.string().optional(),scrimOpacity:p.number().min(0).max(1).optional(),paddingPx:p.number().optional(),radiusPx:p.number().optional()}).strict(),_k=p.enum(["top-left","top-right","bottom-left","bottom-right"]),wk=p.enum(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),Wx=p.object({label:p.string(),actionId:p.string(),primary:p.boolean().optional()}).strict(),Lk=p.object({title:p.string().optional(),body:p.string(),ctaButtons:p.array(Wx).optional()}).strict(),Ik=p.object({title:p.string().optional(),body:p.string()}).strict(),Ak=p.enum(["before","after","prepend","append","replace"]),kk=p.enum(["immediate","hover","click"]),Ek=p.object({widgetId:p.string(),props:p.record(p.unknown()).optional(),priority:p.number().optional()}).strict(),Tk=p.object({id:p.string(),action:p.any(),route:p.string().optional(),onAction:p.record(p.string()).optional()}).passthrough(),Rk=p.enum(["auto","smooth","instant"]),Gx=p.enum(["start","center","end","nearest"]),Mk=p.object({kind:p.literal("content:setText"),anchorId:Pa,text:p.string(),label:p.string().optional()}).extend(gt).strict(),Dk=p.object({kind:p.literal("content:setAttr"),anchorId:Pa,attr:p.string(),value:p.string(),label:p.string().optional()}).extend(gt).strict(),Ok=p.object({kind:p.literal("content:addClass"),anchorId:Pa,className:p.string(),label:p.string().optional()}).extend(gt).strict(),Bk=p.object({kind:p.literal("content:removeClass"),anchorId:Pa,className:p.string(),label:p.string().optional()}).extend(gt).strict(),Fk=p.object({kind:p.literal("content:setStyle"),anchorId:Pa,styles:p.record(p.string()),label:p.string().optional()}).extend(gt).strict(),Nk=p.object({kind:p.literal("content:insertHtml"),anchorId:Pa,html:p.string(),position:Ak,deepLink:jx.optional(),label:p.string().optional()}).extend(gt).strict(),Pk=p.object({kind:p.literal("overlays:highlight"),anchorId:Pa,style:Ck.optional(),duration:p.number().optional(),label:p.string().optional()}).extend(gt).strict(),Hk=p.object({kind:p.literal("overlays:pulse"),anchorId:Pa,duration:p.number().optional(),label:p.string().optional()}).extend(gt).strict(),Uk=p.object({kind:p.literal("overlays:badge"),anchorId:Pa,content:p.string(),position:_k.optional(),label:p.string().optional()}).extend(gt).strict(),qk=p.object({kind:p.literal("overlays:tooltip"),anchorId:Pa,content:Lk,trigger:kk.optional(),placement:wk.optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(gt).strict(),zk=p.object({kind:p.literal("overlays:modal"),content:Ik,size:p.enum(["sm","md","lg"]).optional(),blocking:p.boolean().optional(),scrim:p.object({opacity:p.number().min(0).max(1).optional()}).strict().optional(),dismiss:p.object({onEsc:p.boolean().optional(),closeButton:p.boolean().optional(),timeoutMs:p.number().min(0).optional()}).strict().optional(),ctaButtons:p.array(Wx).optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(gt).strict(),Vk=p.object({kind:p.literal("navigation:scrollTo"),anchorId:Pa,behavior:Rk.optional(),block:Gx.optional(),inline:Gx.optional(),label:p.string().optional()}).extend(gt).strict(),$k=p.object({kind:p.literal("navigation:navigate"),url:p.string(),target:p.enum(["_self","_blank"]).optional(),label:p.string().optional()}).extend(gt).strict(),jk=p.object({kind:p.literal("core:mountWidget"),slot:p.string(),widget:Ek,label:p.string().optional()}).extend(gt).strict(),Gk=p.object({kind:p.literal("core:wait"),durationMs:p.number().min(0).optional(),event:p.string().optional(),label:p.string().optional()}).extend(gt).strict(),Wk=p.object({kind:p.literal("core:sequence"),actions:p.array(p.any()),label:p.string().optional()}).extend(gt).strict(),Zk=p.object({kind:p.literal("core:parallel"),actions:p.array(p.any()),waitFor:p.enum(["all","any"]).optional(),label:p.string().optional()}).extend(gt).strict(),Xk=p.object({kind:p.literal("core:tour"),tourId:p.string(),steps:p.array(Tk).min(1),startStep:p.string().optional(),autoStart:p.boolean().optional(),label:p.string().optional()}).extend(gt).passthrough(),SP=[{defName:"setText",schema:Mk},{defName:"setAttr",schema:Dk},{defName:"addClass",schema:Ok},{defName:"removeClass",schema:Bk},{defName:"setStyle",schema:Fk},{defName:"insertHtml",schema:Nk},{defName:"highlight",schema:Pk},{defName:"pulse",schema:Hk},{defName:"badge",schema:Uk},{defName:"tooltip",schema:qk},{defName:"modal",schema:zk},{defName:"scrollTo",schema:Vk},{defName:"navigate",schema:$k},{defName:"mountWidget",schema:jk},{defName:"wait",schema:Gk},{defName:"sequence",schema:Wk},{defName:"parallel",schema:Zk},{defName:"tour",schema:Xk}];function Zx(t){let e=t?.root??(typeof document<"u"?document.body:null),a=t?.defaultTimeoutMs??5e3,r=new Map,n=new Map,o=null,i=!1;function s(x){if(!e)return null;try{return e.querySelector(x)}catch{return null}}function l(){for(let[x,f]of r){let m=s(x);if(m){for(let v of f)clearTimeout(v.timer),v.resolve(m);r.delete(x)}}for(let[x,f]of n){let m=s(x);if(m){for(let v of f)v.cancelled||v.cb(m);n.delete(x)}}r.size===0&&n.size===0&&c()}function u(){o||i||typeof MutationObserver>"u"||!e||(o=new MutationObserver(()=>{l()}),o.observe(e,{childList:!0,subtree:!0}))}function c(){o&&(o.disconnect(),o=null)}function d(x,f){let m=r.get(x);m&&(m.delete(f),m.size===0&&r.delete(x)),r.size===0&&n.size===0&&c()}function h(x,f){if(i)return Promise.reject(new Error("AnchorResolver destroyed"));let m=s(x);if(m)return Promise.resolve(m);let v=f??a;return new Promise((y,_)=>{let L={resolve:y,reject:_,timer:setTimeout(()=>{d(x,L),_(new Error(`waitFor("${x}") timed out after ${v}ms`))},v)},C=r.get(x);C||(C=new Set,r.set(x,C)),C.add(L),u()})}function g(x,f){if(i)return()=>{};let m=s(x);if(m)return f(m),()=>{};let v={cb:f,cancelled:!1},y=n.get(x);return y||(y=new Set,n.set(x,y)),y.add(v),u(),()=>{v.cancelled=!0;let _=n.get(x);_&&(_.delete(v),_.size===0&&n.delete(x)),r.size===0&&n.size===0&&c()}}function S(){let x=0;for(let f of r.values())x+=f.size;return x}function b(){i=!0,c();let x=new Error("AnchorResolver destroyed");for(let f of r.values())for(let m of f)clearTimeout(m.timer),m.reject(x);r.clear(),n.clear()}return{resolve:s,waitFor:h,onAppear:g,pendingCount:S,destroy:b}}function CP(){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 Xx(t,e){if(!e)return;let a;try{a=new URL(t).pathname}catch{a=t}if(e.exclude){for(let r of e.exclude)if(Yk(a,r))return}if(e.include){for(let r of e.include)if(Yk(a,r))return r;return}return a}function Yk(t,e){let a=t.replace(/\/$/,"")||"/",r=e.replace(/\/$/,"")||"/";if(a===r)return!0;let n=r.replace(/:[^/]+/g,"[^/]+").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(a)}var wp=class{constructor(e){j(this,"context");j(this,"previousContext");j(this,"listeners",new Set);j(this,"telemetry");j(this,"routes");j(this,"navigation");j(this,"cleanupFns",[]);if(this.telemetry=e.telemetry,this.routes=e.routes,this.navigation=e.navigation,this.context=CP(),this.previousContext={...this.context},e.telemetry?.getSessionId){let a=e.telemetry.getSessionId();a&&(this.context.session.sessionId=a)}e.initialPageHistory&&(this.context.session.pageHistory=e.initialPageHistory),this.context.page.routeId=Xx(this.context.page.url,this.routes),this.addPageToHistory(this.context.page.url),typeof window<"u"&&this.setupBrowserListeners()}get(){return{...this.context}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setRoutes(e){this.routes=e;let a=Xx(this.context.page.url,this.routes);a!==this.context.page.routeId&&this.updateContext({page:{...this.context.page,routeId:a}})}setAnchors(e){this.updateContext({anchors:e})}setSessionId(e){e!==this.context.session.sessionId&&this.updateContext({session:{...this.context.session,sessionId:e}})}destroy(){for(let e of this.cleanupFns)e();this.cleanupFns=[],this.listeners.clear()}setupBrowserListeners(){let e,a=()=>{clearTimeout(e),e=setTimeout(()=>{this.updateViewport()},100)};window.addEventListener("resize",a),this.cleanupFns.push(()=>window.removeEventListener("resize",a));let r=this.navigation.subscribe(()=>this.updatePage());this.cleanupFns.push(r)}updateViewport(){let e={width:window.innerWidth,height:window.innerHeight};(e.width!==this.context.viewport.width||e.height!==this.context.viewport.height)&&this.updateContext({viewport:e})}updatePage(){let e=window.location.href,{title:a}=document,r=Xx(e,this.routes),n={url:e,title:a,routeId:r};(n.url!==this.context.page.url||n.title!==this.context.page.title||n.routeId!==this.context.page.routeId)&&(n.url!==this.context.page.url&&this.addPageToHistory(n.url),this.updateContext({page:n}))}addPageToHistory(e){let a={url:e,ts:Date.now()},r=[...this.context.session.pageHistory||[],a];r.length>50&&r.shift(),this.context.session.pageHistory=r}updateContext(e){this.previousContext={...this.context},this.context={...this.context,...e},this.notifyListeners()}notifyListeners(){for(let e of this.listeners)try{e(this.context,this.previousContext)}catch(a){console.error("[ContextManager] Listener error:",a)}}};function Yx(t){return new wp(t)}var _P=p.object({url:p.string(),routeId:p.string().optional(),title:p.string().optional(),locale:p.string().optional()}),wP=p.object({url:p.string(),ts:p.number()}),LP=p.object({sessionId:p.string(),startTs:p.number(),pageHistory:p.array(wP).optional()}),IP=p.object({width:p.number(),height:p.number()}),AP=p.object({x:p.number(),y:p.number(),w:p.number(),h:p.number()}),kP=p.object({anchorId:p.string(),present:p.boolean(),visible:p.boolean().optional(),boundingBox:AP.optional()}),EP=p.record(p.string(),p.union([p.number(),p.string(),p.boolean(),p.undefined()])),TP=p.object({page:_P,session:LP,viewport:IP,anchors:p.array(kP).optional(),augmented:EP.optional()});function Kz(t){return TP.safeParse(t)}function Kk(t,e){let{context:a,state:r,events:n}=e;switch(t.type){case"page_url":{let{url:o}=t,i=a.page.url.split("?")[0].split("#")[0],s=o.replace(/\*\*/g,"\0GLOBSTAR\0").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\0GLOBSTAR\0/g,".*");return new RegExp(`^${s}$`).test(i)}case"route":return a.page.routeId===t.routeId;case"anchor_visible":{let o=typeof t.anchorId=="string"?t.anchorId:t.anchorId?.selector??"",i=a.anchors?.find(s=>s.anchorId===o);switch(t.state){case"visible":return i?.visible===!0;case"present":return i?.present===!0;case"absent":return!i?.present;default:return!1}}case"event_occurred":{if(!n)return!1;let o=t.withinMs??6e4;return n.hasRecentEvent(t.eventName,o)}case"state_equals":return r?.getValue?r.getValue(t.key)===t.value:!1;case"viewport":{let{width:o,height:i}=a.viewport;return!(t.minWidth!==void 0&&o<t.minWidth||t.maxWidth!==void 0&&o>t.maxWidth||t.minHeight!==void 0&&i<t.minHeight||t.maxHeight!==void 0&&i>t.maxHeight)}case"session_metric":{if(!r)return!1;let o=r.getSessionMetric(t.key),{operator:i,threshold:s}=t;switch(i){case"gte":return o>=s;case"lte":return o<=s;case"eq":return o===s;case"gt":return o>s;case"lt":return o<s;default:return!1}}case"dismissed":{if(!r)return t.inverted??!1;let o=r.isDismissed(t.key);return t.inverted?!o:o}case"cooldown_active":{if(!r)return t.inverted??!1;let o=r.isCooldownActive(t.key);return t.inverted?!o:o}case"frequency_limit":{if(!r)return t.inverted??!1;let i=r.getFrequencyCount(t.key)>=t.limit;return t.inverted?!i:i}case"event_count":{if(!e.accumulator)return!1;let o=t,i=e.accumulator.getCount(o.key,o.withinMs);switch(o.operator){case"gte":return i>=o.count;case"lte":return i<=o.count;case"eq":return i===o.count;case"gt":return i>o.count;case"lt":return i<o.count;default:return!1}}default:return console.warn("[RuleStrategy] Unknown condition type:",t.type),!1}}function Qk(t,e){let a=[];for(let r of t.conditions){let n=Kk(r,e);if(a.push({condition:r,result:n}),!n)return{matched:!1,conditionResults:a}}return{matched:!0,conditionResults:a}}function Lp(t,e){for(let a=0;a<t.rules.length;a++){let r=t.rules[a],{matched:n,conditionResults:o}=Qk(r,e);if(n)return{value:r.value,isFallback:!1,matchInfo:{strategyType:"rules",matchedRuleIndex:a,evaluatedConditions:o}}}return{value:t.default,isFallback:!0,matchInfo:{strategyType:"rules"}}}function Ip(t,e){let{context:a}=e,r=a.augmented?.[t.field];return r===void 0||typeof r!="number"?{value:t.below,isFallback:!0,matchInfo:{strategyType:"score"}}:{value:r>=t.threshold?t.above:t.below,isFallback:!1,matchInfo:{strategyType:"score"}}}function Jk(t,e){let{state:a,events:r,sessionMetrics:n,accumulator:o}=e;return{context:t,state:a?{isDismissed:i=>a.dismissals.isDismissed(i),isCooldownActive:i=>a.cooldowns.isActive(i),getFrequencyCount:i=>a.frequency.count(i),getSessionMetric:i=>n?.get(i)??0,getValue:i=>a.session.get(i)??a.user.get(i)}:void 0,events:r?{hasRecentEvent:(i,s)=>r.hasRecentEvent(i,s)}:void 0,accumulator:o?{getCount:(i,s)=>o.getCount(i,s)}:void 0}}async function eE(t,e,a={}){let r=Jk(e,a);switch(t.type){case"rules":return Lp(t,r);case"score":return Ip(t,r);case"model":return{value:t.default,isFallback:!0,matchInfo:{strategyType:"model"}};case"external":return{value:t.default,isFallback:!0,matchInfo:{strategyType:"external"}};default:return console.warn("[DecisionEngine] Unknown strategy type:",t.type),{value:void 0,isFallback:!0,matchInfo:{strategyType:t.type}}}}function tE(t,e,a={}){let r=Jk(e,a);switch(t.type){case"rules":return Lp(t,r);case"score":return Ip(t,r);case"model":case"external":return{value:t.default,isFallback:!0,matchInfo:{strategyType:t.type}};default:return{value:void 0,isFallback:!0,matchInfo:{strategyType:t.type}}}}function Kx(t){return{evaluate:(e,a)=>eE(e,a,t),evaluateSync:(e,a)=>tE(e,a,t)}}function Qx(t){let{eventBus:e,stateStore:a}=t,r=new Map,n=new Set,o=null,i=a.ns("accumulator");function s(u){let c=!1;for(let d of r.values()){if(!d.predicate(u))continue;let h=i.get(d.stateKey)||{count:0};h.count++,d.needsTimestamps&&(h.timestamps||(h.timestamps=[]),h.timestamps.push(u.ts),h.timestamps.length>200&&(h.timestamps=h.timestamps.slice(-200))),i.set(d.stateKey,h),c=!0}if(c)for(let d of n)try{d()}catch(h){console.error("[EventAccumulator] Subscriber error:",h)}}function l(){o||r.size===0||(o=e.subscribe(s))}return{register(u,c,d=!1){let h=`ev:${u}`,g=r.get(h);if(g){d&&!g.needsTimestamps&&(g.needsTimestamps=!0);return}r.set(h,{stateKey:h,needsTimestamps:d,predicate:c}),l()},getCount(u,c){let d=`ev:${u}`,h=i.get(d);if(!h)return 0;if(c===void 0||!h.timestamps)return h.count;let g=Date.now()-c;return h.timestamps.filter(S=>S>=g).length},subscribe(u){return n.add(u),()=>{n.delete(u)}},destroy(){o&&(o(),o=null),r.clear(),n.clear()}}}function Jx(t,e){return e?!(e.names&&e.names.length>0&&!e.names.includes(t.name)||e.patterns&&e.patterns.length>0&&!e.patterns.some(r=>{try{return new RegExp(r).test(t.name)}catch{return!1}})||e.sources&&e.sources.length>0&&!e.sources.includes(t.source)):!0}var Ap=class{constructor(e={}){j(this,"subscriptions",new Set);j(this,"history",[]);j(this,"maxHistorySize");this.maxHistorySize=e.maxHistorySize??100}subscribe(e,a){let r,n;typeof e=="function"?(r=void 0,n=e):(r=e,n=a);let o={filter:r,callback:n};return this.subscriptions.add(o),()=>{this.subscriptions.delete(o)}}publish(e,a,r="canvas"){let n={ts:Date.now(),name:e,source:r,props:a,schemaVersion:fs};this.publishEvent(n)}publishEvent(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift();for(let a of this.subscriptions)if(Jx(e,a.filter))try{a.callback(e)}catch(r){console.error("[EventBus] Subscriber error:",r)}}getRecent(e,a){let r=this.history;return e&&(r=r.filter(n=>Jx(n,e))),a&&a>0&&(r=r.slice(-a)),r}hasRecentEvent(e,a,r){let n=Date.now()-a;return this.history.some(o=>o.name===e&&o.ts>=n&&(r===void 0||o.source===r))}countRecentEvents(e,a){let r=this.history.filter(n=>Jx(n,e));if(a!==void 0){let n=Date.now()-a;r=r.filter(o=>o.ts>=n)}return r.length}clearHistory(){this.history=[]}getSubscriberCount(){return this.subscriptions.size}};function tc(t={}){return new Ap(t)}var aE={$autocapture:"ui.click",$click:Ce.UI_CLICK,$scroll:Ce.UI_SCROLL,$input:Ce.UI_INPUT,$change:Ce.UI_CHANGE,$submit:Ce.UI_SUBMIT,$pageview:Ce.NAV_PAGE_VIEW,$pageleave:Ce.NAV_PAGE_LEAVE,$session_start:"session.start",$identify:"user.identify"};function RP(t){let e=t.event;if(typeof e!="string")return"posthog.unknown";if(aE[e])return aE[e];if(e==="$autocapture"){let a=t.properties?.$tag_name,r=t.properties?.$event_type;return r==="submit"?Ce.UI_SUBMIT:r==="change"?Ce.UI_CHANGE:a==="input"||a==="textarea"?Ce.UI_INPUT:Ce.UI_CLICK}return e.startsWith("$")?e.replace("$","posthog."):`posthog.${e}`}function MP(t){let e={},a=t.properties||{},r=a.$elements;return a.$tag_name?e.tagName=a.$tag_name:r?.[0]?.tag_name&&(e.tagName=r[0].tag_name),a.$el_text&&(e.elementText=a.$el_text),r&&(e.elements=r),a.$current_url&&(e.url=a.$current_url),a.$pathname&&(e.pathname=a.$pathname),a.$host&&(e.host=a.$host),a.$viewport_width&&(e.viewportWidth=a.$viewport_width),a.$viewport_height&&(e.viewportHeight=a.$viewport_height),a.$session_id&&(e.sessionId=a.$session_id),a.$scroll_depth&&(e.scrollDepth=a.$scroll_depth),a.$scroll_percentage&&(e.scrollPercentage=a.$scroll_percentage),e.originalEvent=t.event,e}function rE(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:RP(t),source:"posthog",props:MP(t),schemaVersion:fs}}function nE(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 eb(t){return(e,a)=>{if(typeof e!="string")return;let r={event:e,properties:a,timestamp:Date.now()};if(nE(r)){let n=rE(r);t(n)}}}var oE=p.enum(["posthog","canvas","derived"]),DP=p.object({ts:p.number(),name:p.string(),source:oE,props:p.record(p.string(),p.unknown()).optional(),schemaVersion:p.string()}),OP=p.object({names:p.array(p.string()).optional(),patterns:p.array(p.string()).optional(),sources:p.array(oE).optional()});function S6(t){return DP.safeParse(t)}function C6(t){return OP.safeParse(t)}var ac=class{constructor(){j(this,"listeners",new Set);j(this,"capturedPushState");j(this,"capturedReplaceState");j(this,"wasNative");j(this,"destroyed",!1);j(this,"onPopState",()=>{this.notify(window.location.href,"popstate")});this.wasNative=this.isNativeFunction(history.pushState),this.capturedPushState=history.pushState,this.capturedReplaceState=history.replaceState,history.pushState=(...e)=>{this.capturedPushState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"pushState"))},history.replaceState=(...e)=>{this.capturedReplaceState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"replaceState"))},window.addEventListener("popstate",this.onPopState)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}diagnose(){return{isNative:this.wasNative,subscriberCount:this.listeners.size}}destroy(){this.destroyed||(this.destroyed=!0,history.pushState=this.capturedPushState,history.replaceState=this.capturedReplaceState,window.removeEventListener("popstate",this.onPopState),this.listeners.clear())}notify(e,a){if(!this.destroyed)for(let r of this.listeners)try{r(e,a)}catch{}}isNativeFunction(e){try{return Function.prototype.toString.call(e).includes("[native code]")}catch{return!1}}};var tb="cooldown:";function iE(t){return{set(e,a){let r=tb+e,n=Date.now()+a;t.set(r,n)},isActive(e){return this.remaining(e)>0},remaining(e){let a=tb+e,r=t.get(a);if(r===void 0)return 0;let n=r-Date.now();return n<=0?(t.remove(a),0):n},clear(e){let a=tb+e;t.remove(a)}}}var rc="dismissed:";function sE(t,e){return{mark(a,r=!1){let n=rc+a;(r?e:t).set(n,!0)},isDismissed(a){let r=rc+a;return t.has(r)||e.has(r)},clear(a){let r=rc+a;t.remove(r),e.remove(r)},clearAll(){for(let a of t.keys())a.startsWith(rc)&&t.remove(a);for(let a of e.keys())a.startsWith(rc)&&e.remove(a)}}}var ab="freq:";function lE(t){function e(a){let r=ab+a,n=t.get(r);if(n){if(n.resetAt&&Date.now()>=n.resetAt){t.remove(r);return}return n}}return{increment(a,r){let n=ab+a,o=e(a),i=(o?.count??0)+1,s={count:i,resetAt:o?.resetAt??(r?Date.now()+r:void 0)};return t.set(n,s),i},count(a){return e(a)?.count??0},reset(a){let r=ab+a;t.remove(r)},hasReachedLimit(a,r){return this.count(a)>=r}}}var BP="syntro";function rb(t,e){let a=`${e}:`;return{get(r){if(t)try{let n=t.getItem(a+r);if(!n)return;let o=JSON.parse(n);if(o.expiresAt&&Date.now()>=o.expiresAt){t.removeItem(a+r);return}return o.value}catch{return}},set(r,n,o){if(t)try{let i={value:n,expiresAt:o?Date.now()+o:void 0};t.setItem(a+r,JSON.stringify(i))}catch(i){console.warn("[StateStore] Failed to save:",i)}},remove(r){t&&t.removeItem(a+r)},has(r){return t?this.get(r)!==void 0:!1},keys(){if(!t)return[];let r=[];for(let n=0;n<t.length;n++){let o=t.key(n);o?.startsWith(a)&&r.push(o.slice(a.length))}return r},clear(){if(!t)return;let r=this.keys();for(let n of r)t.removeItem(a+n)}}}function nc(t){let e=new Map,a=`${t}:`;return{get(r){let n=e.get(a+r);if(n){if(n.expiresAt&&Date.now()>=n.expiresAt){e.delete(a+r);return}return n.value}},set(r,n,o){e.set(a+r,{value:n,expiresAt:o?Date.now()+o:void 0})},remove(r){e.delete(a+r)},has(r){return this.get(r)!==void 0},keys(){let r=[];for(let n of e.keys())n.startsWith(a)&&r.push(n.slice(a.length));return r},clear(){for(let r of e.keys())r.startsWith(a)&&e.delete(r)}}}var kp=class{constructor(e={}){j(this,"session");j(this,"user");j(this,"dismissals");j(this,"cooldowns");j(this,"frequency");j(this,"namespace");j(this,"namespacedStorages",new Map);this.namespace=e.namespace??BP;let a=r=>typeof r=="object"&&r!==null&&typeof r.setItem=="function";typeof window<"u"?(this.session=a(window.sessionStorage)?rb(window.sessionStorage,this.namespace):nc(this.namespace),this.user=a(window.localStorage)?rb(window.localStorage,this.namespace):nc(this.namespace)):(this.session=nc(this.namespace),this.user=nc(this.namespace)),this.dismissals=sE(this.session,this.user),this.cooldowns=iE(this.user),this.frequency=lE(this.session)}ns(e){let a=`${this.namespace}:${e}`;if(!this.namespacedStorages.has(a)){let r=typeof window<"u"&&typeof sessionStorage<"u"?rb(sessionStorage,a):nc(a);this.namespacedStorages.set(a,r)}return this.namespacedStorages.get(a)}};function nb(t={}){return new kp(t)}function oc(t){return t.startsWith("inline:")?"inline":t.startsWith("adjacent:")?"adjacent":"static"}function Ep(t){return t.startsWith("inline:")?t.slice(7):t.startsWith("adjacent:")?t.slice(9):null}var uE={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:[]},cE={duration:200,easing:"cubic-bezier(0.16, 1, 0.3, 1)",fill:"forwards"};function ob(t,e,a){let r=uE[e];Object.assign(t.style,r),a&&(a.maxWidth&&(t.style.maxWidth=a.maxWidth),a.maxHeight&&(t.style.maxHeight=a.maxHeight),a.minWidth&&(t.style.minWidth=a.minWidth),a.minHeight&&(t.style.minHeight=a.minHeight))}function ib(t,e,a){let r=a.placement==="auto"?"bottom":a.placement,n=[Kd(a.offset?{mainAxis:a.offset.y,crossAxis:a.offset.x}:8)];return a.flip!==!1&&n.push(Jd()),a.shift!==!1&&n.push(Qd({padding:8})),t.style.position="absolute",t.style.zIndex="2147483646",Yd(e,t,async()=>{let{x:i,y:s,strategy:l}=await ef(e,t,{placement:r,middleware:n});Object.assign(t.style,{position:l,left:`${i}px`,top:`${s}px`})})}function sb(t,e,a="append"){return t.style.position="relative",t.style.display="inline-block",a==="prepend"?e.insertBefore(t,e.firstChild):e.appendChild(t),()=>{t.remove()}}function lb(t,e){return e==="none"||ic[e].length===0?null:t.animate(ic[e],cE)}function ub(t,e){if(e==="none"||ic[e].length===0)return Promise.resolve();let a=[...ic[e]].reverse(),r=t.animate(a,cE);return new Promise(n=>{r.onfinish=()=>n(),r.oncancel=()=>n()})}function cb(t,e){let a=document.createElement("div");return a.setAttribute("data-syntro-surface",t),a.setAttribute("data-syntro-mount-id",e),a.className="syntro-surface",Object.assign(a.style,{pointerEvents:"auto",boxSizing:"border-box",overflow:"auto"}),a}function db(t){switch(oc(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 dE(t){if(typeof window.Sanitizer=="function")try{let l=new window.Sanitizer({}).sanitizeToFragment(t),u=document.createElement("div");return u.append(l),u.innerHTML}catch{}let a=document.createElement("template");a.innerHTML=t;let r=a.content,n=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),o=new Set(["b","strong","i","em","u","span","div","p","br","ul","ol","li","code","pre","small","sup","sub","a","button"]),i=[];for(;n.nextNode();){let s=n.currentNode,l=s.tagName.toLowerCase();if(!o.has(l)){i.push(s);continue}for(let u of Array.from(s.attributes)){let c=u.name.toLowerCase(),d=u.value.trim().toLowerCase(),h=c.startsWith("on"),g=(c==="href"||c==="src")&&d.startsWith("javascript:");(h||g)&&s.removeAttribute(u.name)}}for(let s of i){for(;s.firstChild;)s.parentNode?.insertBefore(s.firstChild,s);s.remove()}return a.innerHTML=(r.firstChild,a.innerHTML)}var FP=0;function fb(t){let{overlayRoot:e,eventBus:a,anchorResolver:r,defaultAnimation:n="fade",widgetRegistry:o}=t,i=new Map,s=new Map,l=new Map;function u(){return`mount-${++FP}`}function c(y,_){a&&a.publish(y,_)}function d(y){let _=l.get(y);if(_){let L=x(y);for(let C of _)try{C(L)}catch(k){console.error("[Surfaces] State callback error:",k)}}}let h=new Map;function g(y,_,L){switch(_.type){case"html":y.innerHTML=dE(_.content);return;case"widget":{if(o?.has(_.widgetId)){let C=o.mount(_.widgetId,y,_.config);return L&&h.set(L,C),()=>{C.unmount(),L&&h.delete(L)}}console.warn(`[Surfaces] Widget not found: ${_.widgetId}`),y.innerHTML=`<div data-widget-id="${_.widgetId}" data-widget-missing="true">Widget: ${_.widgetId}</div>`;return}case"custom":return _.mount(y);case"react":y.innerHTML="<div data-react-component>React Component</div>";return;default:console.warn("[Surfaces] Unknown content type");return}}function S(y,_,L){let C=u(),k=oc(y),w=L?.priority??0,I=L?.animation??n,T=L?.exclusive??!0,D=i.get(y);if(D&&T){if(D.options.priority>w)throw new Error(`Slot ${y} is occupied by higher priority content (${D.options.priority} > ${w})`);b(D)}let M=cb(y,C);M.style.zIndex=String(db(y));let B;if(k==="static")ob(M,y,L?.constraints),e.appendChild(M);else if(k==="inline"){let N=Ep(y);if(!N)throw new Error(`Invalid inline slot: ${y}`);if(!r)throw new Error("Anchor resolver required for inline slots");let X=r({selector:N,route:"**"});if(!X)throw new Error(`Anchor not found for inline slot: ${N}`);B=sb(M,X)}else if(k==="adjacent"){let N=Ep(y);if(!N)throw new Error(`Invalid adjacent slot: ${y}`);if(!r)throw new Error("Anchor resolver required for adjacent slots");let X=r({selector:N,route:"**"});if(!X)throw new Error(`Anchor not found for adjacent slot: ${N}`);e.appendChild(M),B=ib(M,X,L?.position??{placement:"bottom"})}let F=g(M,_,C);lb(M,I);let H={id:C,slot:y,content:_,options:{priority:w,exclusive:T,animation:I,position:L?.position??{placement:"auto"},constraints:L?.constraints??{},adaptiveId:L?.adaptiveId,autoUnmountOnRouteChange:L?.autoUnmountOnRouteChange??!0},container:M,cleanup:()=>{B?.(),F?.()},mountedAt:Date.now()};return i.set(y,H),s.set(y,(s.get(y)??0)+1),c("surface.mounted",{slot:y,id:C,adaptiveId:L?.adaptiveId}),d(y),{id:C,update(N){let X=i.get(y);if(!X||X.id!==C)throw new Error("Mount no longer active");let ve=h.get(C);if(ve){if(N.type==="widget"){ve.update(N.config),X.content=N;return}ve.unmount(),h.delete(C)}X.container.innerHTML="";let Ha=g(X.container,N,C);if(X.content=N,Ha){let dt=X.cleanup;X.cleanup=()=>{dt?.(),Ha()}}},setOptions(N){let X=i.get(y);if(!X||X.id!==C)throw new Error("Mount no longer active");N.priority!==void 0&&(X.options.priority=N.priority),N.animation!==void 0&&(X.options.animation=N.animation),N.constraints&&k==="static"&&(N.constraints.maxWidth&&(X.container.style.maxWidth=N.constraints.maxWidth),N.constraints.maxHeight&&(X.container.style.maxHeight=N.constraints.maxHeight),N.constraints.minWidth&&(X.container.style.minWidth=N.constraints.minWidth),N.constraints.minHeight&&(X.container.style.minHeight=N.constraints.minHeight)),d(y)},async unmount(){let N=i.get(y);!N||N.id!==C||await b(N)},isMounted(){return i.get(y)?.id===C},getContainer(){let N=i.get(y);return N?.id===C?N.container:null}}}async function b(y){await ub(y.container,y.options.animation),y.cleanup?.(),y.container.remove(),i.delete(y.slot),c("surface.unmounted",{slot:y.slot,id:y.id}),d(y.slot)}function x(y){let _=i.get(y);return{slot:y,occupied:!!_,currentPriority:_?.options.priority,currentAdaptiveId:_?.options.adaptiveId,mountCount:s.get(y)??0,currentMountId:_?.id}}function f(y,_){let L=l.get(y);return L||(L=new Set,l.set(y,L)),L.add(_),()=>{L?.delete(_),L?.size===0&&l.delete(y)}}function m(y,_){let L=i.get(y);return L?_!==void 0?_>=L.options.priority:!1:!0}function v(){for(let y of i.values())try{y.cleanup?.(),y.container.remove()}catch(_){console.error("[Surfaces] Error during cleanup:",_)}i.clear(),l.clear()}return{mount:S,getState:x,onStateChange:f,canMount:m,destroy:v}}var Tp=class{constructor(){j(this,"widgets",new Map);j(this,"mountedWidgets",new Map);j(this,"mountIdCounter",0);j(this,"runtimeRef");j(this,"listeners",new Set)}bindRuntime(e){this.runtimeRef=e}register(e,a,r="custom",n){if(this.widgets.has(e)){if(this.widgets.get(e).source==="built-in")throw new Error(`Cannot override built-in widget: ${e}`);console.warn(`[WidgetRegistry] Overriding widget: ${e}`)}this.widgets.set(e,{id:e,widget:a,source:r,metadata:n}),this.notify({type:"registered",widgetId:e})}unregister(e){let a=this.widgets.get(e);return a?a.source==="built-in"?(console.warn(`[WidgetRegistry] Cannot unregister built-in widget: ${e}`),!1):(this.widgets.delete(e),this.notify({type:"unregistered",widgetId:e}),!0):!1}unregisterBySource(e){for(let[a,r]of this.widgets.entries())r.source===e&&this.widgets.delete(a)}get(e){return this.widgets.get(e)?.widget}getRegistration(e){return this.widgets.get(e)}has(e){return this.widgets.has(e)}mount(e,a,r){let n=this.widgets.get(e);if(!n)throw new Error(`Widget not found: ${e}`);let o=`widget-mount-${++this.mountIdCounter}`;a.setAttribute("data-widget-mount-id",o),a.setAttribute("data-widget-id",e);let i={...r,runtime:this.runtimeRef},s=n.widget.mount(a,i);return this.mountedWidgets.set(o,{cleanup:s??void 0,container:a}),{widgetId:e,container:a,unmount:()=>{let u=this.mountedWidgets.get(o);u&&(u.cleanup?.(),this.mountedWidgets.delete(o),a.removeAttribute("data-widget-mount-id"),a.removeAttribute("data-widget-id"),a.innerHTML="")},update:u=>{if(n.widget.update)n.widget.update(a,u);else{let c=this.mountedWidgets.get(o);if(c){c.cleanup?.(),a.innerHTML="";let d={...u,runtime:this.runtimeRef},h=n.widget.mount(a,d);c.cleanup=h??void 0}}}}}list(){return Array.from(this.widgets.keys())}listRegistrations(){return Array.from(this.widgets.values())}getBySource(e){return Array.from(this.widgets.values()).filter(a=>a.source===e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(let a of this.listeners)try{a(e)}catch(r){console.error("[WidgetRegistry] Listener error:",r)}}destroy(){for(let[e,a]of this.mountedWidgets.entries())a.cleanup?.(),a.container.innerHTML="";this.mountedWidgets.clear()}},pb=new Tp;var pE="2.0.0";function NP(t,e){if(!e)return!0;let a;try{a=new URL(t).pathname}catch{a=t}let r=a.replace(/\/$/,"")||"/";if(e.exclude){for(let n of e.exclude)if(hb(r,n))return!1}if(e.include&&e.include.length>0){for(let n of e.include)if(hb(r,n))return!0;return!1}return!0}function hb(t,e){let a=e.replace(/\/$/,"")||"/";if(t===a)return!0;let r=a.replace(/\*\*/g,"\0GLOBSTAR\0").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\0GLOBSTAR\0/g,".*").replace(/:[^/]+/g,"[^/]+");return new RegExp(`^${r}$`).test(t)}function fE(t){let a=(typeof window<"u"?window.location.pathname:"/").replace(/\/$/,"")||"/";return(Array.isArray(t.route)?t.route:[t.route]).some(n=>hb(a,n))}function mb(t={}){let{telemetry:e,sessionMetrics:a,routes:r,mode:n="production",namespace:o}=t,i=t.widgets??pb,s=t.executors??on,l=t.apps??Kl,u=new ac,c=Yx({telemetry:e,routes:r,navigation:u}),d=t.events??tc(),h=nb({namespace:o}),g=Qx({eventBus:d,stateStore:h}),S=Kx({state:h,events:d,sessionMetrics:a,accumulator:g}),b=ZL(),x=Zx(),f=C=>fE(C)?x.resolve(C.selector):null,m=async(C,k)=>{if(!fE(C))return null;try{return await x.waitFor(C.selector,k)}catch{return null}},v=fb({overlayRoot:b,eventBus:d,anchorResolver:f,widgetRegistry:i}),y=Dx({overlayRoot:b,eventBus:d,surfaces:v,anchorResolver:f,waitForAnchor:m,executorRegistry:s,subscribeNavigation:C=>u.subscribe(C),runtime:{evaluateSync:C=>S.evaluateSync(C,c.get()),context:c,accumulator:g}}),_;if(a){a.increment("page_views");let C=typeof window<"u"?window.location.pathname:"/";_=u.subscribe((k,w)=>{if(w!=="replaceState")try{let I=new URL(k).pathname;I!==C&&(C=I,a.increment("page_views"))}catch{}})}let L={telemetry:e,context:c,events:d,state:h,sessionMetrics:a,actions:y,surfaces:v,widgets:i,executors:s,apps:l,accumulator:g,anchorResolver:x,navigation:u,version:pE,mode:n,async evaluate(C){return S.evaluate(C,c.get())},evaluateSync(C){return S.evaluateSync(C,c.get())},async filterTiles(C){let k=c.get().page.url,w=[];for(let I of C){let T=I.activation;if(!T){w.push(I);continue}if(NP(k,T.routes)){if(T.onlyIfPopulated){let D=I.props?.actions??[];if(D.length>0&&!D.some(B=>B.triggerWhen?S.evaluateSync(B.triggerWhen,c.get()).value:!0))continue}w.push(I)}}return w},setRoutes(C){c.setRoutes(C)},destroy(){l.unbind().catch(C=>{console.error("[Runtime] Error unbinding apps registry:",C)}),_?.(),x.destroy(),g.destroy(),u.destroy(),c.destroy(),y.destroy(),v.destroy()}};return l.bind(L),i.bindRuntime(L),L}var PP=p.object({value:p.unknown(),expiresAt:p.number().optional()}),HP=p.object({count:p.number(),resetAt:p.number().optional()});function LV(t){return PP.safeParse(t)}function IV(t){return HP.safeParse(t)}var hE={growthbook:t=>Nv({...t,autoInit:!0})};function mE(t,e){let a=hE[t];if(!a)throw new Error(`Unknown experiment provider: ${t}. Supported: ${Object.keys(hE).join(", ")}`);return a(e)}var UP=["cdn.syntrologie.com","localhost","127.0.0.1"];function qP(t){try{let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(console.warn("[SmartCanvas] CDN URL must use HTTPS:",t),!1):UP.some(n=>e.hostname===n)?!0:(console.warn("[SmartCanvas] CDN host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid CDN URL:",t),!1}}var gb=class{constructor(e){j(this,"name","cdn");j(this,"url");j(this,"integrity");if(this.url=`${e.baseUrl}/${e.configId}.json`,this.integrity=e.integrity,!qP(this.url))throw new Error(`[SmartCanvas] CDN URL not allowed: ${this.url}`)}async fetch(){let e=performance.now(),a=await fetch(this.url,{credentials:"omit",cache:"default"});if(!a.ok)throw new Error(`[SmartCanvas] Failed to fetch config from CDN (${a.status})`);let r=await a.text();if(this.integrity){let l=await zP(r),u=this.integrity.replace("sha384-","");if(l!==u)throw new Error(`[SmartCanvas] Config integrity check failed. Expected ${u}, got ${l}`)}let n=JSON.parse(r),o=performance.now()-e,i=a.headers.get("cache-control"),s=a.headers.get("age");return{config:n,meta:{source:"cdn",fetchTimeMs:o,cached:i?.includes("public")??!1,cacheAge:s?parseInt(s,10):void 0}}}};async function zP(t){let a=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-384",a),n=new Uint8Array(r);return btoa(String.fromCharCode(...n))}function gE(t){return new gb(t)}var VP="syntro_exp",$P="syntro_var",vb=class{constructor(e){j(this,"name","experiments");j(this,"client");j(this,"featureKey");j(this,"manifestKey");j(this,"variantFlagPrefix");this.client=e.client,this.featureKey=e.featureKey??"smart-canvas-config",this.manifestKey=e.manifestKey,this.variantFlagPrefix=e.variantFlagPrefix}async fetch(){let e=performance.now();if(typeof window<"u"){let n=new URLSearchParams(window.location.search),o=n.get(VP),i=n.get($P);if(o&&i!==null&&this.client.setForcedVariations){let s=parseInt(i,10);Number.isNaN(s)||(console.log(`[SmartCanvas] Preview mode: forcing "${o}" to variation ${s}`),this.client.setForcedVariations({[o]:s}))}}if(this.manifestKey||this.variantFlagPrefix||this.client.getAllFeatures){let n=this.fetchMultiFlag();if(n){let o=performance.now()-e;return{config:n,meta:{source:"experiments",fetchTimeMs:o,cached:!0}}}}let a=this.client.getFeatureValue?.(this.featureKey,null);if(!a||typeof a!="object")throw new Error(`[SmartCanvas] Feature "${this.featureKey}" not found or invalid. Ensure the feature is configured in your experiment platform.`);let r=performance.now()-e;return{config:a,meta:{source:"experiments",fetchTimeMs:r,cached:!0}}}fetchMultiFlag(){let e=this.getVariantFlagKeys();return!e||e.length===0?null:of(this.client,e)}getVariantFlagKeys(){if(this.manifestKey){let e=this.client.getFeatureValue?.(this.manifestKey,null);if(e&&typeof e=="object"){let a=e.variant_flags;if(a&&a.length>0)return a}}if(this.client.getAllFeatures){let e=this.client.getAllFeatures();return this.variantFlagPrefix?Object.keys(e).filter(a=>a.startsWith(this.variantFlagPrefix)):Object.keys(e)}return[]}};function vE(t){return new vb(t)}var jP="https://cdn.syntrologie.com/configs",yE={cdn:t=>{if(!t.configId)throw new Error("CDN fetcher requires 'configId' option");return gE({baseUrl:t.baseUrl??jP,configId:t.configId,integrity:t.integrity})},experiments:t=>{if(!t.featureKey)throw new Error("Experiments fetcher requires 'featureKey' option");return vE({featureKey:t.featureKey})}};function xE(t,e={}){let a=yE[t];if(!a)throw new Error(`Unknown config fetcher type: ${t}. Supported: ${Object.keys(yE).join(", ")}`);return a(e)}var bE={posthog:t=>Ax(t),noop:()=>$v()};function SE(t,e){let a=bE[t];if(!a)throw new Error(`Unknown telemetry provider: ${t}. Supported: ${Object.keys(bE).join(", ")}`);return a(e)}var yb="syn_";function Rp(t){if(!t.startsWith(yb))throw new Error("Invalid Syntro token: must start with 'syn_'");let a=t.slice(yb.length).replace(/-/g,"+").replace(/_/g,"/"),r=atob(a),n=JSON.parse(r);if(n.v!==1)throw new Error(`Unsupported token version: ${n.v}`);return n}function xb(t){let e=JSON.stringify(t),a=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return yb+a}function sn(t){if(typeof process<"u"&&process.env)return process.env[t];try{let e=(0,eval)("import.meta");if(e?.env)return e.env[t]}catch{}}var CE="syntro_segment_attributes";function GP(){if(typeof window>"u")return{};try{let t=localStorage.getItem(CE);if(t){let e=JSON.parse(t);return Y("Syntro Bootstrap","Loaded cached segment attributes:",e),e}}catch(t){ma("Syntro Bootstrap","Failed to load cached segment attributes:",t)}return{}}function WP(t){if(!(typeof window>"u"))try{localStorage.setItem(CE,JSON.stringify(t)),Y("Syntro Bootstrap","Cached segment attributes:",t)}catch(e){ma("Syntro Bootstrap","Failed to cache segment attributes:",e)}}function ZP(t){if(!t)return{};let e={};for(let[a,r]of Object.entries(t))a.startsWith("in_segment_")&&(e[a]=r===!0);return e}function XP(){if(typeof window>"u")return{};let t={};try{let e=new URLSearchParams(window.location.search);for(let a of["utm_source","utm_medium","utm_campaign","utm_content","utm_term"]){let r=e.get(a);r&&(t[a]=r)}}catch{}try{navigator.language&&(t.browser_language=navigator.language),navigator.languages?.length&&(t.browser_languages=[...navigator.languages])}catch{}try{let e=window.innerWidth;t.device_type=e<768?"mobile":e<1024?"tablet":"desktop"}catch{}try{if(document.referrer){t.referrer=document.referrer;try{t.referrer_hostname=new URL(document.referrer).hostname}catch{}}}catch{}try{t.page_url=window.location.href,t.page_path=window.location.pathname}catch{}return t}async function YP(t){Gg(),Y("Syntro Bootstrap","====== INIT ======"),Y("Syntro Bootstrap","Options:",{hasToken:!!t.token,tokenPrefix:`${t.token?.slice(0,15)}...`,hasCanvasOptions:!!t.canvas});let e=uf();if(console.log(`[DIAG] Mode detection: sdkMode=${e}`),console.log("[DIAG] editorSource:",eu()),console.log("[DIAG] editorConf:",lf()),Y("Syntro Bootstrap","SDK mode:",e??"normal"),!e&&typeof window<"u"){let w=!!window.__SYNTRO_EDITOR_PARAMS__,I=!!window.__SYNTRO_AUDIT_LEGEND__,T=!!window.__SYNTRO_REVIEW_DATA__;if(w||I||T){let D=[w&&"__SYNTRO_EDITOR_PARAMS__",I&&"__SYNTRO_AUDIT_LEGEND__",T&&"__SYNTRO_REVIEW_DATA__"].filter(Boolean);console.warn(`[Syntro Bootstrap] \u26A0 Mode detection returned null but mode-specific globals found: ${D.join(", ")}. This suggests URL params were lost (redirect?) but the service worker injected mode data. Check if replaceState failed or if page JS changed the URL before init().`)}}console.log(`[DIAG] Token resolution: options.token=${t.token?t.token.slice(0,15)+"...":"null"}`);let a=t.token;if(!a&&e){let I=lf()?.syntro_token;I?.startsWith("syn_")&&(a=I,Y("Syntro Bootstrap",`\u2713 Using syntro_token from editor_conf (${e} mode)`))}let r;if(a)if(a.startsWith("syn_"))Y("Syntro Bootstrap","Token starts with syn_, decoding..."),r=Rp(a),Gg(r.d);else if(e)Y("Syntro Bootstrap",`\u2713 Non-syn_ token allowed (${e} mode)`);else throw sf("Syntro Bootstrap","\u274C Token does not start with syn_ and NOT in editor/audit/review mode!"),sf("Syntro Bootstrap","Token received:",a),new Error("Invalid Syntro token: must start with 'syn_'");else if(e)Y("Syntro Bootstrap",`\u2713 No token, but ${e} mode - proceeding`);else throw sf("Syntro Bootstrap","\u274C No token provided and NOT in editor/audit/review mode!"),new Error("Syntro token is required (unless in editor, audit, or review mode)");let n=sn("NEXT_PUBLIC_SYNTRO_EXPERIMENT_HOST")||sn("VITE_SYNTRO_EXPERIMENT_HOST")||r?.eh,o=sn("NEXT_PUBLIC_SYNTRO_TELEMETRY_HOST")||sn("VITE_SYNTRO_TELEMETRY_HOST")||r?.th,i=sn("NEXT_PUBLIC_SYNTRO_EDITOR_URL")||sn("VITE_SYNTRO_EDITOR_URL")||t.canvas?.editorUrl,s=GP(),l=XP(),u={...l,...s};Y("Syntro Bootstrap","Phase 1: Browser metadata:",l),Y("Syntro Bootstrap","Phase 1: Cached segment attributes:",s);let c,d=tc();console.log("[Syntro Bootstrap] EventBus created");let h=eb(w=>{d.publishEvent(w)}),g=w=>{Y("Syntro Bootstrap","Phase 2: PostHog feature flags loaded");let I=ZP(w);if(Y("Syntro Bootstrap","Segment flags from PostHog:",I),WP(I),c){let T=b?.getAll?.()??{},D={...l,...T,...I};Y("Syntro Bootstrap","Updating GrowthBook with attributes:",D),c.setAttributes?.(D)}},S;if(r?.t){let w=r.t==="noop"?"noop":"posthog";S=SE(w,{apiKey:r.t,apiHost:o,enableFeatureFlags:!0,onFeatureFlagsLoaded:g,onCapture:h}),console.log(`[Syntro Bootstrap] Telemetry client created (${w}) with EventBus wiring`)}let b;r?.e&&(c=mE("growthbook",{clientKey:r.e,apiHost:n,attributes:u,onExperimentViewed:S?.trackExperiment?(w,I,T)=>{S.trackExperiment(w,I,T)}:void 0})),b=Pv({experiments:c,onMetricChange:(w,I)=>{Y("Syntro Bootstrap",`Session metric changed: ${w} = ${I}`)}}),Y("Syntro Bootstrap","SessionMetricTracker created");let x="production";e==="editor"?x="editor":e==="audit"?x="audit":sn("NODE_ENV")==="development"&&(x="development");let f=mb({telemetry:S,sessionMetrics:b,mode:x,events:d});Y("Syntro Bootstrap","Runtime created:",{version:f.version,mode:f.mode,hasContext:!!f.context,hasEvents:!!f.events,hasState:!!f.state}),Y("Syntro Bootstrap","Core app executors already registered");let m=t.cdnBase||sn("NEXT_PUBLIC_SYNTRO_CDN_BASE")||sn("VITE_SYNTRO_CDN_BASE")||"https://cdn.syntrologie.com",v=Ug({cdnBase:m,registry:f.apps,onLoadStart:w=>{Y("Syntro Bootstrap",`Loading app from CDN: ${w}`)},onLoadEnd:(w,I,T)=>{I?Y("Syntro Bootstrap",`App loaded successfully: ${w}`):ma("Syntro Bootstrap",`Failed to load app: ${w}`,T)}});typeof window<"u"&&(window.SynOS={...window.SynOS,appRegistry:f.apps,runtime:f,version:f.version},Y("Syntro Bootstrap","Global SynOS object exposed"));let y=f.apps.list?.()??[];console.log(`[DIAG] Activation loop: ${y.length} apps in registry:`,y.map(w=>`${w.manifest.id}(${w.state})`).join(", "));for(let w of y)if(w.state==="registered")try{await f.apps.activate(w.manifest.id),console.log(`[DIAG] Activated: ${w.manifest.id} \u2192 widgets: [${f.widgets.list().join(", ")}]`)}catch(I){console.error(`[DIAG] FAILED to activate: ${w.manifest.id}`,I),ma("Syntro Bootstrap",`Failed to auto-activate built-in app: ${w.manifest.id}`,I)}if(console.log(`[DIAG] Activation complete. Total widgets: [${f.widgets.list().join(", ")}]`),c?.refreshFeatures)try{await c.refreshFeatures(),Y("Syntro Bootstrap","GrowthBook features loaded")}catch(w){ma("Syntro Bootstrap","Failed to load GrowthBook features:",w)}let _;if(t.fetcher)_=t.fetcher;else if(r?.f){let w=xE(r.f,r.o??{});_=async()=>{let I=await w.fetch();return{...I.config,tiles:I.config.tiles??[]}}}else c&&(_=ls({experiments:c}));let L=new Set,C=_?async()=>{let w=await _();console.log("[Syntro Bootstrap] Config fetched:",`tiles=${w.tiles?.length??0},`,`actions=${w.actions?.length??0},`,`theme=${w.theme?.name??"none"}`),w.actions?.length>0&&console.log("[Syntro Bootstrap] Actions in config:",w.actions.map((D,M)=>`[${M}] ${D.kind}${D.anchorId?` anchor="${typeof D.anchorId=="string"?D.anchorId:D.anchorId.selector}"`:""}${D.label?` "${D.label}"`:""}`).join(", "));let I=w,T=v.getRequiredApps(I);return T.length>0?console.log("[Syntro Bootstrap] Required external apps:",T.join(", ")):Y("Syntro Bootstrap","No external apps required (all executors are built-in)"),T.length>0&&await v.loadAppsForConfig(I).then(async M=>{let B=M.filter(V=>V.success),F=M.filter(V=>!V.success);B.length>0&&console.log(`[Syntro Bootstrap] Apps loaded from CDN: ${B.map(V=>V.appId).join(", ")}`);let H=F.filter(V=>!L.has(V.appId));H.length>0&&(console.error("[Syntro Bootstrap] Apps FAILED to load from CDN:",H.map(V=>`${V.appId} (${V.error})`).join(", ")),H.forEach(V=>L.add(V.appId)));for(let V of T)if(f.apps.has(V))try{await f.apps.activate(V),console.log(`[Syntro Bootstrap] App activated: ${V}`)}catch(N){console.error(`[Syntro Bootstrap] Failed to activate app: ${V}`,N)}else console.error(`[Syntro Bootstrap] App "${V}" required by config but NOT registered.`,`Available apps: [${Array.from(f.apps.list?.()??[]).join(", ")}]`)}),w}:void 0;return{canvas:await yv({...t.canvas,fetcher:C,integrations:{experiments:c,telemetry:S},editorUrl:i,runtime:f}),runtime:f,experiments:c,telemetry:S,sessionMetrics:b,appLoader:v}}var _E={init:YP,encodeToken:xb,decodeToken:Rp};typeof window<"u"&&(window.Syntro=_E);var wE="2026-03-08T22:29:47.958Z (c824504ba1)";if(typeof window<"u"){console.log(`[Syntro Runtime] Build: ${wE}`);let t=window.SynOS,e=t?.appRegistry||Kl;window.SynOS={...t,appRegistry:e,_runtimeBuild:wE,React:LE.default,ReactDOM:{...KP,createPortal:Mp.createPortal,flushSync:Mp.flushSync}},FL(e)}export{ic as ANIMATION_KEYFRAMES,_p as ActivationConfigZ,Ok as AddClassZ,Pa as AnchorIdZ,kP as AnchorStateZ,Fx as AnchorVisibleConditionZ,af as AppRegistry,EP as AugmentationZ,_k as BadgePositionZ,Uk as BadgeZ,AP as BoundingBoxZ,tu as CanvasEvents,zv as CanvasRecipeZ,po as ConditionZ,wp as ContextManager,zx as CooldownActiveConditionZ,Zu as CounterDefZ,Wx as CtaButtonZ,Jg as DEFAULT_COOLDOWN,Qg as DEFAULT_TTL,ec as DecisionStrategyZ,qx as DismissedConditionZ,fs as EVENT_SCHEMA_VERSION,Ap as EventBus,$x as EventCountConditionZ,OP as EventFilterZ,Nx as EventOccurredConditionZ,oE as EventSourceZ,Sp as ExecutorRegistry,Ju as ExternalStrategyZ,HP as FrequencyEntryZ,Vx as FrequencyLimitConditionZ,pF as HighlightStepZ,Ck as HighlightStyleZ,Pk as HighlightZ,Nk as InsertHtmlZ,Ak as InsertPositionZ,Kg as MAX_VISIBLE_TOASTS,Wu as MatchOpZ,Ik as ModalContentZ,zk as ModalZ,Qu as ModelStrategyZ,jk as MountWidgetZ,$k as NavigateZ,ac as NavigationMonitor,DP as NormalizedEventZ,Yg as NotificationToastStack,_P as PageContextZ,wP as PageHistoryEntryZ,Ox as PageUrlConditionZ,Zk as ParallelZ,wk as PlacementZ,Hk as PulseZ,wE as RUNTIME_SDK_BUILD,pE as RUNTIME_VERSION,Bk as RemoveClassZ,Bx as RouteConditionZ,Sk as RouteFilterZ,Yu as RuleStrategyZ,Xu as RuleZ,TP as RuntimeContextZ,nv as RuntimeProvider,qn as SDK_SCHEMA_VERSION,Wg as SDK_VERSION,uE as STATIC_SLOT_STYLES,Ku as ScoreStrategyZ,Rk as ScrollBehaviorZ,Gx as ScrollLogicalPositionZ,Vk as ScrollToZ,m1 as SelectorZ,Wk as SequenceZ,LP as SessionContextZ,Ux as SessionMetricConditionZ,Of as SessionMetricTracker,Dk as SetAttrZ,Fk as SetStyleZ,Mk as SetTextZ,cI as ShadowCanvasOverlay,KL as ShadowRootProvider,hI as SmartCanvasApp,Xg as SmartCanvasController,gv as SmartCanvasElement,V5 as SmartCanvasPortal,Ce as StandardEvents,Px as StateEqualsConditionZ,kp as StateStore,PP as StoredValueZ,_E as Syntro,lu as TileCard,Mq as TileWheel,Lk as TooltipContentZ,fF as TooltipStepZ,kk as TooltipTriggerZ,qk as TooltipZ,Tk as TourStepForSchemaZ,Xk as TourZ,Cp as TriggerWhenZ,Hx as ViewportConditionZ,IP as ViewportContextZ,Gk as WaitZ,Ek as WidgetConfigZ,Tp as WidgetRegistry,Kl as appRegistry,ob as applyStaticSlotStyles,Pg as cleanupAppContext,wg as contentRuntime,SP as coreActionStepSchemas,Dx as createActionEngine,Zx as createAnchorResolver,Ng as createAppContext,Ug as createAppLoader,ls as createCanvasConfigFetcher,Yx as createContextManager,Kx as createDecisionEngine,Qx as createEventAccumulator,tc as createEventBus,Nv as createGrowthBookClient,$v as createNoopClient,q5 as createOverlayRecipeFetcher,Ax as createPostHogClient,eb as createPostHogNormalizer,Pv as createSessionMetricTracker,yv as createSmartCanvas,XL as createSmartCanvasController,mb as createSmartCanvasRuntime,nb as createStateStore,cb as createSurfaceContainer,fb as createSurfaces,Ez as decisionSchemas,Rp as decodeToken,xb as encodeToken,eE as evaluate,Kk as evaluateCondition,Qk as evaluateRule,Lp as evaluateRuleStrategy,Ip as evaluateScoreStrategy,tE as evaluateSync,on as executorRegistry,eD as getAntiFlickerSnippet,SL as getAppIdFromActionKind,Hg as getAppIdFromWidgetId,jN as getExecutor,Ep as getSlotAnchorId,oc as getSlotType,db as getSlotZIndex,Rx as hasExecutor,ff as interpolateTemplate,bL as isCoreActionKind,ev as matchEvent,Fq as needsMigration,rE as normalizePostHogEvent,Fg as overlaysRuntime,uu as parseVersion,lb as playEnterAnimation,ub as playExitAnimation,cf as registerConfigPredicates,yI as registerSmartCanvasElement,Zg as resolveConfigUri,ib as setupAdjacentPositioning,sb as setupInlinePositioning,nE as shouldNormalizeEvent,ND as useDecision,tv as useNotifications,av as useNotifyWatcher,ov as usePageContext,Vr as useRuntime,hf as useRuntimeContext,BD as useRuntimeEvents,FD as useRuntimeState,DD as useSessionContext,fI as useShadowCanvasConfig,ds as useShadowRoot,OD as useViewportContext,fo as validateAction,Mx as validateActions,kz as validateActivationConfig,Iz as validateCondition,Bq as validateConfig,C6 as validateEventFilter,IV as validateFrequencyEntry,S6 as validateNormalizedEvent,N5 as validateRecipe,Kz as validateRuntimeContext,LV as validateStoredValue,Az as validateStrategy,pb as widgetRegistry};
|
|
464
|
+
`)),new Error(`Batch validation failed: ${M}`)}let w=h(),I=[],T=[];try{for(let M of C){let B=await m(M);I.push(B),T.push(B)}}catch(M){console.error(`[ActionEngine] Batch apply FAILED at action ${T.length+1}/${C.length}.`,`Successfully applied: ${T.length}. Rolling back...`,M);for(let B of T)try{await B.revert()}catch{}throw M}return{id:w,handles:I,async revertAll(){for(let M=I.length-1;M>=0;M--)try{await I[M].revert()}catch(B){console.error(`[ActionEngine] Error reverting action ${I[M].id}:`,B)}},isApplied(){return I.every(M=>M.isApplied())}}}function y(C){return fo(C)}function _(){return Array.from(c.values()).map(C=>({id:C.id,action:C.action,adaptiveId:C.adaptiveId,appliedTs:C.appliedTs,state:C.state}))}function L(){for(let C of d.values())for(let k of C)try{k()}catch{}d.clear();for(let C of c.values())if(C.state==="applied")try{C.cleanup()}catch(k){console.error("[ActionEngine] Error during cleanup:",k)}c.clear()}return{apply:m,applyBatch:v,validate:y,getActive:_,destroy:L}}var lP=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),Ox=p.object({type:p.literal("page_url"),url:p.string()}),Bx=p.object({type:p.literal("route"),routeId:p.string()}),Fx=p.object({type:p.literal("anchor_visible"),anchorId:p.string(),state:p.enum(["visible","present","absent"])}),Nx=p.object({type:p.literal("event_occurred"),eventName:p.string(),withinMs:p.number().optional()}),Px=p.object({type:p.literal("state_equals"),key:p.string(),value:p.unknown()}),Hx=p.object({type:p.literal("viewport"),minWidth:p.number().optional(),maxWidth:p.number().optional(),minHeight:p.number().optional(),maxHeight:p.number().optional()}),Ux=p.object({type:p.literal("session_metric"),key:p.string(),operator:p.enum(["gte","lte","eq","gt","lt"]),threshold:p.number()}),qx=p.object({type:p.literal("dismissed"),key:p.string(),inverted:p.boolean().optional()}),zx=p.object({type:p.literal("cooldown_active"),key:p.string(),inverted:p.boolean().optional()}),Vx=p.object({type:p.literal("frequency_limit"),key:p.string(),limit:p.number(),inverted:p.boolean().optional()}),Wu=p.object({equals:p.union([p.string(),p.number(),p.boolean()]).optional(),contains:p.string().optional()}),Zu=p.object({events:p.array(p.string()).min(1),match:p.record(p.string(),Wu).optional()}),$x=p.object({type:p.literal("event_count"),key:p.string(),operator:p.enum(["gte","lte","eq","gt","lt"]),count:p.number().int().min(0),withinMs:p.number().positive().optional(),counter:Zu.optional()}),po=p.discriminatedUnion("type",[Ox,Bx,Fx,Nx,Px,Hx,Ux,qx,zx,Vx,$x]),Xu=p.object({conditions:p.array(po),value:p.unknown()}),Yu=p.object({type:p.literal("rules"),rules:p.array(Xu),default:p.unknown()}),Ku=p.object({type:p.literal("score"),field:p.string(),threshold:p.number(),above:p.unknown(),below:p.unknown()}),Qu=p.object({type:p.literal("model"),modelId:p.string(),inputs:p.array(p.string()),outputMapping:p.record(p.string(),p.unknown()),default:p.unknown()}),Ju=p.object({type:p.literal("external"),endpoint:p.string(),method:p.enum(["GET","POST"]).optional(),default:p.unknown(),timeoutMs:p.number().optional()}),ec=p.discriminatedUnion("type",[Yu,Ku,Qu,Ju]),Cp=ec.nullable().optional(),uP=p.object({events:p.array(p.string()),urlContains:p.string().optional(),props:p.record(p.union([p.string(),p.number(),p.boolean()])).optional()}),cP=p.object({title:p.string().optional(),body:p.string().optional(),icon:p.string().optional()}).nullable().optional();var Sk=p.object({include:p.array(p.string()).optional().describe("URL patterns where this tile appears. Supports *, **, :param wildcards. Use sparingly \u2014 mostly to isolate to specific webapp functionality. Omit to appear on all routes."),exclude:p.array(p.string()).optional().describe("URL patterns where this tile should NOT appear. Evaluated before include.")}),_p=p.object({routes:Sk,onlyIfPopulated:p.boolean().optional().describe("When true, tile is hidden if none of its props.actions[] have an active triggerWhen. Useful for tiles with all-deferred FAQ questions or nav tips. Default: false.")});function Iz(t){return po.safeParse(t)}function Az(t){return ec.safeParse(t)}function kz(t){return _p.safeParse(t)}var Ez=[{defName:"matchOp",schema:Wu},{defName:"counterDef",schema:Zu},{defName:"activationConfig",schema:_p},{defName:"routeFilter",schema:Sk},{defName:"ruleStrategy",schema:Yu},{defName:"scoreStrategy",schema:Ku},{defName:"modelStrategy",schema:Qu},{defName:"externalStrategy",schema:Ju},{defName:"rule",schema:Xu},{defName:"condition",schema:po}];var jx=p.object({tileId:p.string(),itemId:p.string().optional()}).strict(),dP=p.object({on:p.string(),title:p.string(),body:p.string().optional(),icon:p.string().optional(),ttl:p.number().optional(),cooldown:p.number().optional(),deepLink:jx.optional()}).strict(),fP=p.object({id:p.string(),title:p.string().optional(),subtitle:p.string().optional(),icon:p.string().optional(),priority:p.number().optional(),widget:p.string(),props:p.record(p.unknown()).optional(),activation:_p.optional(),notifications:p.array(dP).optional()}).strict(),pP=p.object({position:p.enum(["left","right"]).optional(),layout:p.enum(["overlay","push"]).optional(),background:p.string().optional(),blur:p.string().optional(),border:p.string().optional(),width:p.string().optional(),transitionDuration:p.string().optional(),transitionEasing:p.string().optional(),transitionFade:p.string().optional()}),hP=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),color:p.string().optional(),size:p.string().optional(),shadow:p.string().optional(),borderRadius:p.string().optional()}),mP=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),shadow:p.string().optional(),titleColor:p.string().optional(),textColor:p.string().optional(),iconBackground:p.string().optional(),iconShadow:p.string().optional(),headerPadding:p.string().optional(),bodyPadding:p.string().optional(),gap:p.string().optional()}),gP=p.object({background:p.string().optional(),textColor:p.string().optional(),titleColor:p.string().optional(),arrowColor:p.string().optional(),arrowSize:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),scrimOpacity:p.string().optional(),highlightRing:p.string().optional()}),vP=p.object({background:p.string().optional(),textColor:p.string().optional(),textSecondaryColor:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),successColor:p.string().optional(),warningColor:p.string().optional(),errorColor:p.string().optional(),iconBackground:p.string().optional(),progressGradient:p.string().optional()}),yP=p.object({background:p.string().optional(),backgroundHover:p.string().optional(),border:p.string().optional(),borderRadius:p.string().optional(),textColor:p.string().optional(),textSecondaryColor:p.string().optional(),itemDivider:p.string().optional(),itemGap:p.string().optional(),itemPadding:p.string().optional(),itemFontSize:p.string().optional(),bodyPadding:p.string().optional(),bodyFontSize:p.string().optional(),categoryPadding:p.string().optional(),categoryGap:p.string().optional(),categoryFontSize:p.string().optional(),searchBackground:p.string().optional(),searchColor:p.string().optional(),chevronColor:p.string().optional()}),xP=p.object({mode:p.enum(["dark","light"]).optional(),fontFamily:p.string().optional(),colorPrimary:p.string().optional(),colorPrimaryHover:p.string().optional(),borderRadius:p.string().optional(),canvas:pP.optional(),launcher:hP.optional(),tile:mP.optional(),overlay:gP.optional(),notification:vP.optional(),content:yP.optional()}).strict(),bP=p.object({enabled:p.boolean().optional(),label:p.string().optional(),icon:p.string().optional(),position:p.string().optional(),animate:p.boolean().optional(),animationStyle:p.enum(["pulse","bounce","glow"]).optional(),notificationCount:p.number().optional()}).strict(),Oz=p.object({schemaVersion:p.string().optional(),fetchedAt:p.string().datetime(),configVersion:p.string().optional(),canvasTitle:p.string().optional(),tiles:p.array(fP),actions:p.array(p.any()),theme:xP.optional(),launcher:bP.optional(),meta:p.object({verificationSteps:p.array(p.union([p.string(),p.object({text:p.string(),check:po.optional()})])).optional()}).passthrough().optional()}).strict();var gt={triggerWhen:Cp},Pa=p.object({selector:p.string(),route:p.union([p.string(),p.array(p.string())])}).strict(),Ck=p.object({color:p.string().optional(),scrimOpacity:p.number().min(0).max(1).optional(),paddingPx:p.number().optional(),radiusPx:p.number().optional()}).strict(),_k=p.enum(["top-left","top-right","bottom-left","bottom-right"]),wk=p.enum(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),Wx=p.object({label:p.string(),actionId:p.string(),primary:p.boolean().optional()}).strict(),Lk=p.object({title:p.string().optional(),body:p.string(),ctaButtons:p.array(Wx).optional()}).strict(),Ik=p.object({title:p.string().optional(),body:p.string()}).strict(),Ak=p.enum(["before","after","prepend","append","replace"]),kk=p.enum(["immediate","hover","click"]),Ek=p.object({widgetId:p.string(),props:p.record(p.unknown()).optional(),priority:p.number().optional()}).strict(),Tk=p.object({id:p.string(),action:p.any(),route:p.string().optional(),onAction:p.record(p.string()).optional()}).passthrough(),Rk=p.enum(["auto","smooth","instant"]),Gx=p.enum(["start","center","end","nearest"]),Mk=p.object({kind:p.literal("content:setText"),anchorId:Pa,text:p.string(),label:p.string().optional()}).extend(gt).strict(),Dk=p.object({kind:p.literal("content:setAttr"),anchorId:Pa,attr:p.string(),value:p.string(),label:p.string().optional()}).extend(gt).strict(),Ok=p.object({kind:p.literal("content:addClass"),anchorId:Pa,className:p.string(),label:p.string().optional()}).extend(gt).strict(),Bk=p.object({kind:p.literal("content:removeClass"),anchorId:Pa,className:p.string(),label:p.string().optional()}).extend(gt).strict(),Fk=p.object({kind:p.literal("content:setStyle"),anchorId:Pa,styles:p.record(p.string()),label:p.string().optional()}).extend(gt).strict(),Nk=p.object({kind:p.literal("content:insertHtml"),anchorId:Pa,html:p.string(),position:Ak,deepLink:jx.optional(),label:p.string().optional()}).extend(gt).strict(),Pk=p.object({kind:p.literal("overlays:highlight"),anchorId:Pa,style:Ck.optional(),duration:p.number().optional(),label:p.string().optional()}).extend(gt).strict(),Hk=p.object({kind:p.literal("overlays:pulse"),anchorId:Pa,duration:p.number().optional(),label:p.string().optional()}).extend(gt).strict(),Uk=p.object({kind:p.literal("overlays:badge"),anchorId:Pa,content:p.string(),position:_k.optional(),label:p.string().optional()}).extend(gt).strict(),qk=p.object({kind:p.literal("overlays:tooltip"),anchorId:Pa,content:Lk,trigger:kk.optional(),placement:wk.optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(gt).strict(),zk=p.object({kind:p.literal("overlays:modal"),content:Ik,size:p.enum(["sm","md","lg"]).optional(),blocking:p.boolean().optional(),scrim:p.object({opacity:p.number().min(0).max(1).optional()}).strict().optional(),dismiss:p.object({onEsc:p.boolean().optional(),closeButton:p.boolean().optional(),timeoutMs:p.number().min(0).optional()}).strict().optional(),ctaButtons:p.array(Wx).optional(),waitFor:p.string().optional(),label:p.string().optional()}).extend(gt).strict(),Vk=p.object({kind:p.literal("navigation:scrollTo"),anchorId:Pa,behavior:Rk.optional(),block:Gx.optional(),inline:Gx.optional(),label:p.string().optional()}).extend(gt).strict(),$k=p.object({kind:p.literal("navigation:navigate"),url:p.string(),target:p.enum(["_self","_blank"]).optional(),label:p.string().optional()}).extend(gt).strict(),jk=p.object({kind:p.literal("core:mountWidget"),slot:p.string(),widget:Ek,label:p.string().optional()}).extend(gt).strict(),Gk=p.object({kind:p.literal("core:wait"),durationMs:p.number().min(0).optional(),event:p.string().optional(),label:p.string().optional()}).extend(gt).strict(),Wk=p.object({kind:p.literal("core:sequence"),actions:p.array(p.any()),label:p.string().optional()}).extend(gt).strict(),Zk=p.object({kind:p.literal("core:parallel"),actions:p.array(p.any()),waitFor:p.enum(["all","any"]).optional(),label:p.string().optional()}).extend(gt).strict(),Xk=p.object({kind:p.literal("core:tour"),tourId:p.string(),steps:p.array(Tk).min(1),startStep:p.string().optional(),autoStart:p.boolean().optional(),label:p.string().optional()}).extend(gt).passthrough(),SP=[{defName:"setText",schema:Mk},{defName:"setAttr",schema:Dk},{defName:"addClass",schema:Ok},{defName:"removeClass",schema:Bk},{defName:"setStyle",schema:Fk},{defName:"insertHtml",schema:Nk},{defName:"highlight",schema:Pk},{defName:"pulse",schema:Hk},{defName:"badge",schema:Uk},{defName:"tooltip",schema:qk},{defName:"modal",schema:zk},{defName:"scrollTo",schema:Vk},{defName:"navigate",schema:$k},{defName:"mountWidget",schema:jk},{defName:"wait",schema:Gk},{defName:"sequence",schema:Wk},{defName:"parallel",schema:Zk},{defName:"tour",schema:Xk}];function Zx(t){let e=t?.root??(typeof document<"u"?document.body:null),a=t?.defaultTimeoutMs??5e3,r=new Map,n=new Map,o=null,i=!1;function s(x){if(!e)return null;try{return e.querySelector(x)}catch{return null}}function l(){for(let[x,f]of r){let m=s(x);if(m){for(let v of f)clearTimeout(v.timer),v.resolve(m);r.delete(x)}}for(let[x,f]of n){let m=s(x);if(m){for(let v of f)v.cancelled||v.cb(m);n.delete(x)}}r.size===0&&n.size===0&&c()}function u(){o||i||typeof MutationObserver>"u"||!e||(o=new MutationObserver(()=>{l()}),o.observe(e,{childList:!0,subtree:!0}))}function c(){o&&(o.disconnect(),o=null)}function d(x,f){let m=r.get(x);m&&(m.delete(f),m.size===0&&r.delete(x)),r.size===0&&n.size===0&&c()}function h(x,f){if(i)return Promise.reject(new Error("AnchorResolver destroyed"));let m=s(x);if(m)return Promise.resolve(m);let v=f??a;return new Promise((y,_)=>{let L={resolve:y,reject:_,timer:setTimeout(()=>{d(x,L),_(new Error(`waitFor("${x}") timed out after ${v}ms`))},v)},C=r.get(x);C||(C=new Set,r.set(x,C)),C.add(L),u()})}function g(x,f){if(i)return()=>{};let m=s(x);if(m)return f(m),()=>{};let v={cb:f,cancelled:!1},y=n.get(x);return y||(y=new Set,n.set(x,y)),y.add(v),u(),()=>{v.cancelled=!0;let _=n.get(x);_&&(_.delete(v),_.size===0&&n.delete(x)),r.size===0&&n.size===0&&c()}}function S(){let x=0;for(let f of r.values())x+=f.size;return x}function b(){i=!0,c();let x=new Error("AnchorResolver destroyed");for(let f of r.values())for(let m of f)clearTimeout(m.timer),m.reject(x);r.clear(),n.clear()}return{resolve:s,waitFor:h,onAppear:g,pendingCount:S,destroy:b}}function CP(){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 Xx(t,e){if(!e)return;let a;try{a=new URL(t).pathname}catch{a=t}if(e.exclude){for(let r of e.exclude)if(Yk(a,r))return}if(e.include){for(let r of e.include)if(Yk(a,r))return r;return}return a}function Yk(t,e){let a=t.replace(/\/$/,"")||"/",r=e.replace(/\/$/,"")||"/";if(a===r)return!0;let n=r.replace(/:[^/]+/g,"[^/]+").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(a)}var wp=class{constructor(e){j(this,"context");j(this,"previousContext");j(this,"listeners",new Set);j(this,"telemetry");j(this,"routes");j(this,"navigation");j(this,"cleanupFns",[]);if(this.telemetry=e.telemetry,this.routes=e.routes,this.navigation=e.navigation,this.context=CP(),this.previousContext={...this.context},e.telemetry?.getSessionId){let a=e.telemetry.getSessionId();a&&(this.context.session.sessionId=a)}e.initialPageHistory&&(this.context.session.pageHistory=e.initialPageHistory),this.context.page.routeId=Xx(this.context.page.url,this.routes),this.addPageToHistory(this.context.page.url),typeof window<"u"&&this.setupBrowserListeners()}get(){return{...this.context}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setRoutes(e){this.routes=e;let a=Xx(this.context.page.url,this.routes);a!==this.context.page.routeId&&this.updateContext({page:{...this.context.page,routeId:a}})}setAnchors(e){this.updateContext({anchors:e})}setSessionId(e){e!==this.context.session.sessionId&&this.updateContext({session:{...this.context.session,sessionId:e}})}destroy(){for(let e of this.cleanupFns)e();this.cleanupFns=[],this.listeners.clear()}setupBrowserListeners(){let e,a=()=>{clearTimeout(e),e=setTimeout(()=>{this.updateViewport()},100)};window.addEventListener("resize",a),this.cleanupFns.push(()=>window.removeEventListener("resize",a));let r=this.navigation.subscribe(()=>this.updatePage());this.cleanupFns.push(r)}updateViewport(){let e={width:window.innerWidth,height:window.innerHeight};(e.width!==this.context.viewport.width||e.height!==this.context.viewport.height)&&this.updateContext({viewport:e})}updatePage(){let e=window.location.href,{title:a}=document,r=Xx(e,this.routes),n={url:e,title:a,routeId:r};(n.url!==this.context.page.url||n.title!==this.context.page.title||n.routeId!==this.context.page.routeId)&&(n.url!==this.context.page.url&&this.addPageToHistory(n.url),this.updateContext({page:n}))}addPageToHistory(e){let a={url:e,ts:Date.now()},r=[...this.context.session.pageHistory||[],a];r.length>50&&r.shift(),this.context.session.pageHistory=r}updateContext(e){this.previousContext={...this.context},this.context={...this.context,...e},this.notifyListeners()}notifyListeners(){for(let e of this.listeners)try{e(this.context,this.previousContext)}catch(a){console.error("[ContextManager] Listener error:",a)}}};function Yx(t){return new wp(t)}var _P=p.object({url:p.string(),routeId:p.string().optional(),title:p.string().optional(),locale:p.string().optional()}),wP=p.object({url:p.string(),ts:p.number()}),LP=p.object({sessionId:p.string(),startTs:p.number(),pageHistory:p.array(wP).optional()}),IP=p.object({width:p.number(),height:p.number()}),AP=p.object({x:p.number(),y:p.number(),w:p.number(),h:p.number()}),kP=p.object({anchorId:p.string(),present:p.boolean(),visible:p.boolean().optional(),boundingBox:AP.optional()}),EP=p.record(p.string(),p.union([p.number(),p.string(),p.boolean(),p.undefined()])),TP=p.object({page:_P,session:LP,viewport:IP,anchors:p.array(kP).optional(),augmented:EP.optional()});function Kz(t){return TP.safeParse(t)}function Kk(t,e){let{context:a,state:r,events:n}=e;switch(t.type){case"page_url":{let{url:o}=t,i=a.page.url.split("?")[0].split("#")[0],s=o.replace(/\*\*/g,"\0GLOBSTAR\0").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\0GLOBSTAR\0/g,".*");return new RegExp(`^${s}$`).test(i)}case"route":return a.page.routeId===t.routeId;case"anchor_visible":{let o=typeof t.anchorId=="string"?t.anchorId:t.anchorId?.selector??"",i=a.anchors?.find(s=>s.anchorId===o);switch(t.state){case"visible":return i?.visible===!0;case"present":return i?.present===!0;case"absent":return!i?.present;default:return!1}}case"event_occurred":{if(!n)return!1;let o=t.withinMs??6e4;return n.hasRecentEvent(t.eventName,o)}case"state_equals":return r?.getValue?r.getValue(t.key)===t.value:!1;case"viewport":{let{width:o,height:i}=a.viewport;return!(t.minWidth!==void 0&&o<t.minWidth||t.maxWidth!==void 0&&o>t.maxWidth||t.minHeight!==void 0&&i<t.minHeight||t.maxHeight!==void 0&&i>t.maxHeight)}case"session_metric":{if(!r)return!1;let o=r.getSessionMetric(t.key),{operator:i,threshold:s}=t;switch(i){case"gte":return o>=s;case"lte":return o<=s;case"eq":return o===s;case"gt":return o>s;case"lt":return o<s;default:return!1}}case"dismissed":{if(!r)return t.inverted??!1;let o=r.isDismissed(t.key);return t.inverted?!o:o}case"cooldown_active":{if(!r)return t.inverted??!1;let o=r.isCooldownActive(t.key);return t.inverted?!o:o}case"frequency_limit":{if(!r)return t.inverted??!1;let i=r.getFrequencyCount(t.key)>=t.limit;return t.inverted?!i:i}case"event_count":{if(!e.accumulator)return!1;let o=t,i=e.accumulator.getCount(o.key,o.withinMs);switch(o.operator){case"gte":return i>=o.count;case"lte":return i<=o.count;case"eq":return i===o.count;case"gt":return i>o.count;case"lt":return i<o.count;default:return!1}}default:return console.warn("[RuleStrategy] Unknown condition type:",t.type),!1}}function Qk(t,e){let a=[];for(let r of t.conditions){let n=Kk(r,e);if(a.push({condition:r,result:n}),!n)return{matched:!1,conditionResults:a}}return{matched:!0,conditionResults:a}}function Lp(t,e){for(let a=0;a<t.rules.length;a++){let r=t.rules[a],{matched:n,conditionResults:o}=Qk(r,e);if(n)return{value:r.value,isFallback:!1,matchInfo:{strategyType:"rules",matchedRuleIndex:a,evaluatedConditions:o}}}return{value:t.default,isFallback:!0,matchInfo:{strategyType:"rules"}}}function Ip(t,e){let{context:a}=e,r=a.augmented?.[t.field];return r===void 0||typeof r!="number"?{value:t.below,isFallback:!0,matchInfo:{strategyType:"score"}}:{value:r>=t.threshold?t.above:t.below,isFallback:!1,matchInfo:{strategyType:"score"}}}function Jk(t,e){let{state:a,events:r,sessionMetrics:n,accumulator:o}=e;return{context:t,state:a?{isDismissed:i=>a.dismissals.isDismissed(i),isCooldownActive:i=>a.cooldowns.isActive(i),getFrequencyCount:i=>a.frequency.count(i),getSessionMetric:i=>n?.get(i)??0,getValue:i=>a.session.get(i)??a.user.get(i)}:void 0,events:r?{hasRecentEvent:(i,s)=>r.hasRecentEvent(i,s)}:void 0,accumulator:o?{getCount:(i,s)=>o.getCount(i,s)}:void 0}}async function eE(t,e,a={}){let r=Jk(e,a);switch(t.type){case"rules":return Lp(t,r);case"score":return Ip(t,r);case"model":return{value:t.default,isFallback:!0,matchInfo:{strategyType:"model"}};case"external":return{value:t.default,isFallback:!0,matchInfo:{strategyType:"external"}};default:return console.warn("[DecisionEngine] Unknown strategy type:",t.type),{value:void 0,isFallback:!0,matchInfo:{strategyType:t.type}}}}function tE(t,e,a={}){let r=Jk(e,a);switch(t.type){case"rules":return Lp(t,r);case"score":return Ip(t,r);case"model":case"external":return{value:t.default,isFallback:!0,matchInfo:{strategyType:t.type}};default:return{value:void 0,isFallback:!0,matchInfo:{strategyType:t.type}}}}function Kx(t){return{evaluate:(e,a)=>eE(e,a,t),evaluateSync:(e,a)=>tE(e,a,t)}}function Qx(t){let{eventBus:e,stateStore:a}=t,r=new Map,n=new Set,o=null,i=a.ns("accumulator");function s(u){let c=!1;for(let d of r.values()){if(!d.predicate(u))continue;let h=i.get(d.stateKey)||{count:0};h.count++,d.needsTimestamps&&(h.timestamps||(h.timestamps=[]),h.timestamps.push(u.ts),h.timestamps.length>200&&(h.timestamps=h.timestamps.slice(-200))),i.set(d.stateKey,h),c=!0}if(c)for(let d of n)try{d()}catch(h){console.error("[EventAccumulator] Subscriber error:",h)}}function l(){o||r.size===0||(o=e.subscribe(s))}return{register(u,c,d=!1){let h=`ev:${u}`,g=r.get(h);if(g){d&&!g.needsTimestamps&&(g.needsTimestamps=!0);return}r.set(h,{stateKey:h,needsTimestamps:d,predicate:c}),l()},getCount(u,c){let d=`ev:${u}`,h=i.get(d);if(!h)return 0;if(c===void 0||!h.timestamps)return h.count;let g=Date.now()-c;return h.timestamps.filter(S=>S>=g).length},subscribe(u){return n.add(u),()=>{n.delete(u)}},destroy(){o&&(o(),o=null),r.clear(),n.clear()}}}function Jx(t,e){return e?!(e.names&&e.names.length>0&&!e.names.includes(t.name)||e.patterns&&e.patterns.length>0&&!e.patterns.some(r=>{try{return new RegExp(r).test(t.name)}catch{return!1}})||e.sources&&e.sources.length>0&&!e.sources.includes(t.source)):!0}var Ap=class{constructor(e={}){j(this,"subscriptions",new Set);j(this,"history",[]);j(this,"maxHistorySize");this.maxHistorySize=e.maxHistorySize??100}subscribe(e,a){let r,n;typeof e=="function"?(r=void 0,n=e):(r=e,n=a);let o={filter:r,callback:n};return this.subscriptions.add(o),()=>{this.subscriptions.delete(o)}}publish(e,a,r="canvas"){let n={ts:Date.now(),name:e,source:r,props:a,schemaVersion:fs};this.publishEvent(n)}publishEvent(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift();for(let a of this.subscriptions)if(Jx(e,a.filter))try{a.callback(e)}catch(r){console.error("[EventBus] Subscriber error:",r)}}getRecent(e,a){let r=this.history;return e&&(r=r.filter(n=>Jx(n,e))),a&&a>0&&(r=r.slice(-a)),r}hasRecentEvent(e,a,r){let n=Date.now()-a;return this.history.some(o=>o.name===e&&o.ts>=n&&(r===void 0||o.source===r))}countRecentEvents(e,a){let r=this.history.filter(n=>Jx(n,e));if(a!==void 0){let n=Date.now()-a;r=r.filter(o=>o.ts>=n)}return r.length}clearHistory(){this.history=[]}getSubscriberCount(){return this.subscriptions.size}};function tc(t={}){return new Ap(t)}var aE={$autocapture:"ui.click",$click:Ce.UI_CLICK,$scroll:Ce.UI_SCROLL,$input:Ce.UI_INPUT,$change:Ce.UI_CHANGE,$submit:Ce.UI_SUBMIT,$pageview:Ce.NAV_PAGE_VIEW,$pageleave:Ce.NAV_PAGE_LEAVE,$session_start:"session.start",$identify:"user.identify"};function RP(t){let e=t.event;if(typeof e!="string")return"posthog.unknown";if(aE[e])return aE[e];if(e==="$autocapture"){let a=t.properties?.$tag_name,r=t.properties?.$event_type;return r==="submit"?Ce.UI_SUBMIT:r==="change"?Ce.UI_CHANGE:a==="input"||a==="textarea"?Ce.UI_INPUT:Ce.UI_CLICK}return e.startsWith("$")?e.replace("$","posthog."):`posthog.${e}`}function MP(t){let e={},a=t.properties||{},r=a.$elements;return a.$tag_name?e.tagName=a.$tag_name:r?.[0]?.tag_name&&(e.tagName=r[0].tag_name),a.$el_text&&(e.elementText=a.$el_text),r&&(e.elements=r),a.$current_url&&(e.url=a.$current_url),a.$pathname&&(e.pathname=a.$pathname),a.$host&&(e.host=a.$host),a.$viewport_width&&(e.viewportWidth=a.$viewport_width),a.$viewport_height&&(e.viewportHeight=a.$viewport_height),a.$session_id&&(e.sessionId=a.$session_id),a.$scroll_depth&&(e.scrollDepth=a.$scroll_depth),a.$scroll_percentage&&(e.scrollPercentage=a.$scroll_percentage),e.originalEvent=t.event,e}function rE(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:RP(t),source:"posthog",props:MP(t),schemaVersion:fs}}function nE(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 eb(t){return(e,a)=>{if(typeof e!="string")return;let r={event:e,properties:a,timestamp:Date.now()};if(nE(r)){let n=rE(r);t(n)}}}var oE=p.enum(["posthog","canvas","derived"]),DP=p.object({ts:p.number(),name:p.string(),source:oE,props:p.record(p.string(),p.unknown()).optional(),schemaVersion:p.string()}),OP=p.object({names:p.array(p.string()).optional(),patterns:p.array(p.string()).optional(),sources:p.array(oE).optional()});function S6(t){return DP.safeParse(t)}function C6(t){return OP.safeParse(t)}var ac=class{constructor(){j(this,"listeners",new Set);j(this,"capturedPushState");j(this,"capturedReplaceState");j(this,"wasNative");j(this,"destroyed",!1);j(this,"onPopState",()=>{this.notify(window.location.href,"popstate")});this.wasNative=this.isNativeFunction(history.pushState),this.capturedPushState=history.pushState,this.capturedReplaceState=history.replaceState,history.pushState=(...e)=>{this.capturedPushState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"pushState"))},history.replaceState=(...e)=>{this.capturedReplaceState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"replaceState"))},window.addEventListener("popstate",this.onPopState)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}diagnose(){return{isNative:this.wasNative,subscriberCount:this.listeners.size}}destroy(){this.destroyed||(this.destroyed=!0,history.pushState=this.capturedPushState,history.replaceState=this.capturedReplaceState,window.removeEventListener("popstate",this.onPopState),this.listeners.clear())}notify(e,a){if(!this.destroyed)for(let r of this.listeners)try{r(e,a)}catch{}}isNativeFunction(e){try{return Function.prototype.toString.call(e).includes("[native code]")}catch{return!1}}};var tb="cooldown:";function iE(t){return{set(e,a){let r=tb+e,n=Date.now()+a;t.set(r,n)},isActive(e){return this.remaining(e)>0},remaining(e){let a=tb+e,r=t.get(a);if(r===void 0)return 0;let n=r-Date.now();return n<=0?(t.remove(a),0):n},clear(e){let a=tb+e;t.remove(a)}}}var rc="dismissed:";function sE(t,e){return{mark(a,r=!1){let n=rc+a;(r?e:t).set(n,!0)},isDismissed(a){let r=rc+a;return t.has(r)||e.has(r)},clear(a){let r=rc+a;t.remove(r),e.remove(r)},clearAll(){for(let a of t.keys())a.startsWith(rc)&&t.remove(a);for(let a of e.keys())a.startsWith(rc)&&e.remove(a)}}}var ab="freq:";function lE(t){function e(a){let r=ab+a,n=t.get(r);if(n){if(n.resetAt&&Date.now()>=n.resetAt){t.remove(r);return}return n}}return{increment(a,r){let n=ab+a,o=e(a),i=(o?.count??0)+1,s={count:i,resetAt:o?.resetAt??(r?Date.now()+r:void 0)};return t.set(n,s),i},count(a){return e(a)?.count??0},reset(a){let r=ab+a;t.remove(r)},hasReachedLimit(a,r){return this.count(a)>=r}}}var BP="syntro";function rb(t,e){let a=`${e}:`;return{get(r){if(t)try{let n=t.getItem(a+r);if(!n)return;let o=JSON.parse(n);if(o.expiresAt&&Date.now()>=o.expiresAt){t.removeItem(a+r);return}return o.value}catch{return}},set(r,n,o){if(t)try{let i={value:n,expiresAt:o?Date.now()+o:void 0};t.setItem(a+r,JSON.stringify(i))}catch(i){console.warn("[StateStore] Failed to save:",i)}},remove(r){t&&t.removeItem(a+r)},has(r){return t?this.get(r)!==void 0:!1},keys(){if(!t)return[];let r=[];for(let n=0;n<t.length;n++){let o=t.key(n);o?.startsWith(a)&&r.push(o.slice(a.length))}return r},clear(){if(!t)return;let r=this.keys();for(let n of r)t.removeItem(a+n)}}}function nc(t){let e=new Map,a=`${t}:`;return{get(r){let n=e.get(a+r);if(n){if(n.expiresAt&&Date.now()>=n.expiresAt){e.delete(a+r);return}return n.value}},set(r,n,o){e.set(a+r,{value:n,expiresAt:o?Date.now()+o:void 0})},remove(r){e.delete(a+r)},has(r){return this.get(r)!==void 0},keys(){let r=[];for(let n of e.keys())n.startsWith(a)&&r.push(n.slice(a.length));return r},clear(){for(let r of e.keys())r.startsWith(a)&&e.delete(r)}}}var kp=class{constructor(e={}){j(this,"session");j(this,"user");j(this,"dismissals");j(this,"cooldowns");j(this,"frequency");j(this,"namespace");j(this,"namespacedStorages",new Map);this.namespace=e.namespace??BP;let a=r=>typeof r=="object"&&r!==null&&typeof r.setItem=="function";typeof window<"u"?(this.session=a(window.sessionStorage)?rb(window.sessionStorage,this.namespace):nc(this.namespace),this.user=a(window.localStorage)?rb(window.localStorage,this.namespace):nc(this.namespace)):(this.session=nc(this.namespace),this.user=nc(this.namespace)),this.dismissals=sE(this.session,this.user),this.cooldowns=iE(this.user),this.frequency=lE(this.session)}ns(e){let a=`${this.namespace}:${e}`;if(!this.namespacedStorages.has(a)){let r=typeof window<"u"&&typeof sessionStorage<"u"?rb(sessionStorage,a):nc(a);this.namespacedStorages.set(a,r)}return this.namespacedStorages.get(a)}};function nb(t={}){return new kp(t)}function oc(t){return t.startsWith("inline:")?"inline":t.startsWith("adjacent:")?"adjacent":"static"}function Ep(t){return t.startsWith("inline:")?t.slice(7):t.startsWith("adjacent:")?t.slice(9):null}var uE={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:[]},cE={duration:200,easing:"cubic-bezier(0.16, 1, 0.3, 1)",fill:"forwards"};function ob(t,e,a){let r=uE[e];Object.assign(t.style,r),a&&(a.maxWidth&&(t.style.maxWidth=a.maxWidth),a.maxHeight&&(t.style.maxHeight=a.maxHeight),a.minWidth&&(t.style.minWidth=a.minWidth),a.minHeight&&(t.style.minHeight=a.minHeight))}function ib(t,e,a){let r=a.placement==="auto"?"bottom":a.placement,n=[Kd(a.offset?{mainAxis:a.offset.y,crossAxis:a.offset.x}:8)];return a.flip!==!1&&n.push(Jd()),a.shift!==!1&&n.push(Qd({padding:8})),t.style.position="absolute",t.style.zIndex="2147483646",Yd(e,t,async()=>{let{x:i,y:s,strategy:l}=await ef(e,t,{placement:r,middleware:n});Object.assign(t.style,{position:l,left:`${i}px`,top:`${s}px`})})}function sb(t,e,a="append"){return t.style.position="relative",t.style.display="inline-block",a==="prepend"?e.insertBefore(t,e.firstChild):e.appendChild(t),()=>{t.remove()}}function lb(t,e){return e==="none"||ic[e].length===0?null:t.animate(ic[e],cE)}function ub(t,e){if(e==="none"||ic[e].length===0)return Promise.resolve();let a=[...ic[e]].reverse(),r=t.animate(a,cE);return new Promise(n=>{r.onfinish=()=>n(),r.oncancel=()=>n()})}function cb(t,e){let a=document.createElement("div");return a.setAttribute("data-syntro-surface",t),a.setAttribute("data-syntro-mount-id",e),a.className="syntro-surface",Object.assign(a.style,{pointerEvents:"auto",boxSizing:"border-box",overflow:"auto"}),a}function db(t){switch(oc(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 dE(t){if(typeof window.Sanitizer=="function")try{let l=new window.Sanitizer({}).sanitizeToFragment(t),u=document.createElement("div");return u.append(l),u.innerHTML}catch{}let a=document.createElement("template");a.innerHTML=t;let r=a.content,n=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),o=new Set(["b","strong","i","em","u","span","div","p","br","ul","ol","li","code","pre","small","sup","sub","a","button"]),i=[];for(;n.nextNode();){let s=n.currentNode,l=s.tagName.toLowerCase();if(!o.has(l)){i.push(s);continue}for(let u of Array.from(s.attributes)){let c=u.name.toLowerCase(),d=u.value.trim().toLowerCase(),h=c.startsWith("on"),g=(c==="href"||c==="src")&&d.startsWith("javascript:");(h||g)&&s.removeAttribute(u.name)}}for(let s of i){for(;s.firstChild;)s.parentNode?.insertBefore(s.firstChild,s);s.remove()}return a.innerHTML=(r.firstChild,a.innerHTML)}var FP=0;function fb(t){let{overlayRoot:e,eventBus:a,anchorResolver:r,defaultAnimation:n="fade",widgetRegistry:o}=t,i=new Map,s=new Map,l=new Map;function u(){return`mount-${++FP}`}function c(y,_){a&&a.publish(y,_)}function d(y){let _=l.get(y);if(_){let L=x(y);for(let C of _)try{C(L)}catch(k){console.error("[Surfaces] State callback error:",k)}}}let h=new Map;function g(y,_,L){switch(_.type){case"html":y.innerHTML=dE(_.content);return;case"widget":{if(o?.has(_.widgetId)){let C=o.mount(_.widgetId,y,_.config);return L&&h.set(L,C),()=>{C.unmount(),L&&h.delete(L)}}console.warn(`[Surfaces] Widget not found: ${_.widgetId}`),y.innerHTML=`<div data-widget-id="${_.widgetId}" data-widget-missing="true">Widget: ${_.widgetId}</div>`;return}case"custom":return _.mount(y);case"react":y.innerHTML="<div data-react-component>React Component</div>";return;default:console.warn("[Surfaces] Unknown content type");return}}function S(y,_,L){let C=u(),k=oc(y),w=L?.priority??0,I=L?.animation??n,T=L?.exclusive??!0,D=i.get(y);if(D&&T){if(D.options.priority>w)throw new Error(`Slot ${y} is occupied by higher priority content (${D.options.priority} > ${w})`);b(D)}let M=cb(y,C);M.style.zIndex=String(db(y));let B;if(k==="static")ob(M,y,L?.constraints),e.appendChild(M);else if(k==="inline"){let N=Ep(y);if(!N)throw new Error(`Invalid inline slot: ${y}`);if(!r)throw new Error("Anchor resolver required for inline slots");let X=r({selector:N,route:"**"});if(!X)throw new Error(`Anchor not found for inline slot: ${N}`);B=sb(M,X)}else if(k==="adjacent"){let N=Ep(y);if(!N)throw new Error(`Invalid adjacent slot: ${y}`);if(!r)throw new Error("Anchor resolver required for adjacent slots");let X=r({selector:N,route:"**"});if(!X)throw new Error(`Anchor not found for adjacent slot: ${N}`);e.appendChild(M),B=ib(M,X,L?.position??{placement:"bottom"})}let F=g(M,_,C);lb(M,I);let H={id:C,slot:y,content:_,options:{priority:w,exclusive:T,animation:I,position:L?.position??{placement:"auto"},constraints:L?.constraints??{},adaptiveId:L?.adaptiveId,autoUnmountOnRouteChange:L?.autoUnmountOnRouteChange??!0},container:M,cleanup:()=>{B?.(),F?.()},mountedAt:Date.now()};return i.set(y,H),s.set(y,(s.get(y)??0)+1),c("surface.mounted",{slot:y,id:C,adaptiveId:L?.adaptiveId}),d(y),{id:C,update(N){let X=i.get(y);if(!X||X.id!==C)throw new Error("Mount no longer active");let ve=h.get(C);if(ve){if(N.type==="widget"){ve.update(N.config),X.content=N;return}ve.unmount(),h.delete(C)}X.container.innerHTML="";let Ha=g(X.container,N,C);if(X.content=N,Ha){let dt=X.cleanup;X.cleanup=()=>{dt?.(),Ha()}}},setOptions(N){let X=i.get(y);if(!X||X.id!==C)throw new Error("Mount no longer active");N.priority!==void 0&&(X.options.priority=N.priority),N.animation!==void 0&&(X.options.animation=N.animation),N.constraints&&k==="static"&&(N.constraints.maxWidth&&(X.container.style.maxWidth=N.constraints.maxWidth),N.constraints.maxHeight&&(X.container.style.maxHeight=N.constraints.maxHeight),N.constraints.minWidth&&(X.container.style.minWidth=N.constraints.minWidth),N.constraints.minHeight&&(X.container.style.minHeight=N.constraints.minHeight)),d(y)},async unmount(){let N=i.get(y);!N||N.id!==C||await b(N)},isMounted(){return i.get(y)?.id===C},getContainer(){let N=i.get(y);return N?.id===C?N.container:null}}}async function b(y){await ub(y.container,y.options.animation),y.cleanup?.(),y.container.remove(),i.delete(y.slot),c("surface.unmounted",{slot:y.slot,id:y.id}),d(y.slot)}function x(y){let _=i.get(y);return{slot:y,occupied:!!_,currentPriority:_?.options.priority,currentAdaptiveId:_?.options.adaptiveId,mountCount:s.get(y)??0,currentMountId:_?.id}}function f(y,_){let L=l.get(y);return L||(L=new Set,l.set(y,L)),L.add(_),()=>{L?.delete(_),L?.size===0&&l.delete(y)}}function m(y,_){let L=i.get(y);return L?_!==void 0?_>=L.options.priority:!1:!0}function v(){for(let y of i.values())try{y.cleanup?.(),y.container.remove()}catch(_){console.error("[Surfaces] Error during cleanup:",_)}i.clear(),l.clear()}return{mount:S,getState:x,onStateChange:f,canMount:m,destroy:v}}var Tp=class{constructor(){j(this,"widgets",new Map);j(this,"mountedWidgets",new Map);j(this,"mountIdCounter",0);j(this,"runtimeRef");j(this,"listeners",new Set)}bindRuntime(e){this.runtimeRef=e}register(e,a,r="custom",n){if(this.widgets.has(e)){if(this.widgets.get(e).source==="built-in")throw new Error(`Cannot override built-in widget: ${e}`);console.warn(`[WidgetRegistry] Overriding widget: ${e}`)}this.widgets.set(e,{id:e,widget:a,source:r,metadata:n}),this.notify({type:"registered",widgetId:e})}unregister(e){let a=this.widgets.get(e);return a?a.source==="built-in"?(console.warn(`[WidgetRegistry] Cannot unregister built-in widget: ${e}`),!1):(this.widgets.delete(e),this.notify({type:"unregistered",widgetId:e}),!0):!1}unregisterBySource(e){for(let[a,r]of this.widgets.entries())r.source===e&&this.widgets.delete(a)}get(e){return this.widgets.get(e)?.widget}getRegistration(e){return this.widgets.get(e)}has(e){return this.widgets.has(e)}mount(e,a,r){let n=this.widgets.get(e);if(!n)throw new Error(`Widget not found: ${e}`);let o=`widget-mount-${++this.mountIdCounter}`;a.setAttribute("data-widget-mount-id",o),a.setAttribute("data-widget-id",e);let i={...r,runtime:this.runtimeRef},s=n.widget.mount(a,i);return this.mountedWidgets.set(o,{cleanup:s??void 0,container:a}),{widgetId:e,container:a,unmount:()=>{let u=this.mountedWidgets.get(o);u&&(u.cleanup?.(),this.mountedWidgets.delete(o),a.removeAttribute("data-widget-mount-id"),a.removeAttribute("data-widget-id"),a.innerHTML="")},update:u=>{if(n.widget.update)n.widget.update(a,u);else{let c=this.mountedWidgets.get(o);if(c){c.cleanup?.(),a.innerHTML="";let d={...u,runtime:this.runtimeRef},h=n.widget.mount(a,d);c.cleanup=h??void 0}}}}}list(){return Array.from(this.widgets.keys())}listRegistrations(){return Array.from(this.widgets.values())}getBySource(e){return Array.from(this.widgets.values()).filter(a=>a.source===e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(let a of this.listeners)try{a(e)}catch(r){console.error("[WidgetRegistry] Listener error:",r)}}destroy(){for(let[e,a]of this.mountedWidgets.entries())a.cleanup?.(),a.container.innerHTML="";this.mountedWidgets.clear()}},pb=new Tp;var pE="2.0.0";function NP(t,e){if(!e)return!0;let a;try{a=new URL(t).pathname}catch{a=t}let r=a.replace(/\/$/,"")||"/";if(e.exclude){for(let n of e.exclude)if(hb(r,n))return!1}if(e.include&&e.include.length>0){for(let n of e.include)if(hb(r,n))return!0;return!1}return!0}function hb(t,e){let a=e.replace(/\/$/,"")||"/";if(t===a)return!0;let r=a.replace(/\*\*/g,"\0GLOBSTAR\0").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\0GLOBSTAR\0/g,".*").replace(/:[^/]+/g,"[^/]+");return new RegExp(`^${r}$`).test(t)}function fE(t){let a=(typeof window<"u"?window.location.pathname:"/").replace(/\/$/,"")||"/";return(Array.isArray(t.route)?t.route:[t.route]).some(n=>hb(a,n))}function mb(t={}){let{telemetry:e,sessionMetrics:a,routes:r,mode:n="production",namespace:o}=t,i=t.widgets??pb,s=t.executors??on,l=t.apps??Kl,u=new ac,c=Yx({telemetry:e,routes:r,navigation:u}),d=t.events??tc(),h=nb({namespace:o}),g=Qx({eventBus:d,stateStore:h}),S=Kx({state:h,events:d,sessionMetrics:a,accumulator:g}),b=ZL(),x=Zx(),f=C=>fE(C)?x.resolve(C.selector):null,m=async(C,k)=>{if(!fE(C))return null;try{return await x.waitFor(C.selector,k)}catch{return null}},v=fb({overlayRoot:b,eventBus:d,anchorResolver:f,widgetRegistry:i}),y=Dx({overlayRoot:b,eventBus:d,surfaces:v,anchorResolver:f,waitForAnchor:m,executorRegistry:s,subscribeNavigation:C=>u.subscribe(C),runtime:{evaluateSync:C=>S.evaluateSync(C,c.get()),context:c,accumulator:g}}),_;if(a){a.increment("page_views");let C=typeof window<"u"?window.location.pathname:"/";_=u.subscribe((k,w)=>{if(w!=="replaceState")try{let I=new URL(k).pathname;I!==C&&(C=I,a.increment("page_views"))}catch{}})}let L={telemetry:e,context:c,events:d,state:h,sessionMetrics:a,actions:y,surfaces:v,widgets:i,executors:s,apps:l,accumulator:g,anchorResolver:x,navigation:u,version:pE,mode:n,async evaluate(C){return S.evaluate(C,c.get())},evaluateSync(C){return S.evaluateSync(C,c.get())},async filterTiles(C){let k=c.get().page.url,w=[];for(let I of C){let T=I.activation;if(!T){w.push(I);continue}if(NP(k,T.routes)){if(T.onlyIfPopulated){let D=I.props?.actions??[];if(D.length>0&&!D.some(B=>B.triggerWhen?S.evaluateSync(B.triggerWhen,c.get()).value:!0))continue}w.push(I)}}return w},setRoutes(C){c.setRoutes(C)},destroy(){l.unbind().catch(C=>{console.error("[Runtime] Error unbinding apps registry:",C)}),_?.(),x.destroy(),g.destroy(),u.destroy(),c.destroy(),y.destroy(),v.destroy()}};return l.bind(L),i.bindRuntime(L),L}var PP=p.object({value:p.unknown(),expiresAt:p.number().optional()}),HP=p.object({count:p.number(),resetAt:p.number().optional()});function LV(t){return PP.safeParse(t)}function IV(t){return HP.safeParse(t)}var hE={growthbook:t=>Nv({...t,autoInit:!0})};function mE(t,e){let a=hE[t];if(!a)throw new Error(`Unknown experiment provider: ${t}. Supported: ${Object.keys(hE).join(", ")}`);return a(e)}var UP=["cdn.syntrologie.com","localhost","127.0.0.1"];function qP(t){try{let e=new URL(t),a=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!a?(console.warn("[SmartCanvas] CDN URL must use HTTPS:",t),!1):UP.some(n=>e.hostname===n)?!0:(console.warn("[SmartCanvas] CDN host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid CDN URL:",t),!1}}var gb=class{constructor(e){j(this,"name","cdn");j(this,"url");j(this,"integrity");if(this.url=`${e.baseUrl}/${e.configId}.json`,this.integrity=e.integrity,!qP(this.url))throw new Error(`[SmartCanvas] CDN URL not allowed: ${this.url}`)}async fetch(){let e=performance.now(),a=await fetch(this.url,{credentials:"omit",cache:"default"});if(!a.ok)throw new Error(`[SmartCanvas] Failed to fetch config from CDN (${a.status})`);let r=await a.text();if(this.integrity){let l=await zP(r),u=this.integrity.replace("sha384-","");if(l!==u)throw new Error(`[SmartCanvas] Config integrity check failed. Expected ${u}, got ${l}`)}let n=JSON.parse(r),o=performance.now()-e,i=a.headers.get("cache-control"),s=a.headers.get("age");return{config:n,meta:{source:"cdn",fetchTimeMs:o,cached:i?.includes("public")??!1,cacheAge:s?parseInt(s,10):void 0}}}};async function zP(t){let a=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-384",a),n=new Uint8Array(r);return btoa(String.fromCharCode(...n))}function gE(t){return new gb(t)}var VP="syntro_exp",$P="syntro_var",vb=class{constructor(e){j(this,"name","experiments");j(this,"client");j(this,"featureKey");j(this,"manifestKey");j(this,"variantFlagPrefix");this.client=e.client,this.featureKey=e.featureKey??"smart-canvas-config",this.manifestKey=e.manifestKey,this.variantFlagPrefix=e.variantFlagPrefix}async fetch(){let e=performance.now();if(typeof window<"u"){let n=new URLSearchParams(window.location.search),o=n.get(VP),i=n.get($P);if(o&&i!==null&&this.client.setForcedVariations){let s=parseInt(i,10);Number.isNaN(s)||(console.log(`[SmartCanvas] Preview mode: forcing "${o}" to variation ${s}`),this.client.setForcedVariations({[o]:s}))}}if(this.manifestKey||this.variantFlagPrefix||this.client.getAllFeatures){let n=this.fetchMultiFlag();if(n){let o=performance.now()-e;return{config:n,meta:{source:"experiments",fetchTimeMs:o,cached:!0}}}}let a=this.client.getFeatureValue?.(this.featureKey,null);if(!a||typeof a!="object")throw new Error(`[SmartCanvas] Feature "${this.featureKey}" not found or invalid. Ensure the feature is configured in your experiment platform.`);let r=performance.now()-e;return{config:a,meta:{source:"experiments",fetchTimeMs:r,cached:!0}}}fetchMultiFlag(){let e=this.getVariantFlagKeys();return!e||e.length===0?null:of(this.client,e)}getVariantFlagKeys(){if(this.manifestKey){let e=this.client.getFeatureValue?.(this.manifestKey,null);if(e&&typeof e=="object"){let a=e.variant_flags;if(a&&a.length>0)return a}}if(this.client.getAllFeatures){let e=this.client.getAllFeatures();return this.variantFlagPrefix?Object.keys(e).filter(a=>a.startsWith(this.variantFlagPrefix)):Object.keys(e)}return[]}};function vE(t){return new vb(t)}var jP="https://cdn.syntrologie.com/configs",yE={cdn:t=>{if(!t.configId)throw new Error("CDN fetcher requires 'configId' option");return gE({baseUrl:t.baseUrl??jP,configId:t.configId,integrity:t.integrity})},experiments:t=>{if(!t.featureKey)throw new Error("Experiments fetcher requires 'featureKey' option");return vE({featureKey:t.featureKey})}};function xE(t,e={}){let a=yE[t];if(!a)throw new Error(`Unknown config fetcher type: ${t}. Supported: ${Object.keys(yE).join(", ")}`);return a(e)}var bE={posthog:t=>Ax(t),noop:()=>$v()};function SE(t,e){let a=bE[t];if(!a)throw new Error(`Unknown telemetry provider: ${t}. Supported: ${Object.keys(bE).join(", ")}`);return a(e)}var yb="syn_";function Rp(t){if(!t.startsWith(yb))throw new Error("Invalid Syntro token: must start with 'syn_'");let a=t.slice(yb.length).replace(/-/g,"+").replace(/_/g,"/"),r=atob(a),n=JSON.parse(r);if(n.v!==1)throw new Error(`Unsupported token version: ${n.v}`);return n}function xb(t){let e=JSON.stringify(t),a=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return yb+a}function sn(t){if(typeof process<"u"&&process.env)return process.env[t];try{let e=(0,eval)("import.meta");if(e?.env)return e.env[t]}catch{}}var CE="syntro_segment_attributes";function GP(){if(typeof window>"u")return{};try{let t=localStorage.getItem(CE);if(t){let e=JSON.parse(t);return Y("Syntro Bootstrap","Loaded cached segment attributes:",e),e}}catch(t){ma("Syntro Bootstrap","Failed to load cached segment attributes:",t)}return{}}function WP(t){if(!(typeof window>"u"))try{localStorage.setItem(CE,JSON.stringify(t)),Y("Syntro Bootstrap","Cached segment attributes:",t)}catch(e){ma("Syntro Bootstrap","Failed to cache segment attributes:",e)}}function ZP(t){if(!t)return{};let e={};for(let[a,r]of Object.entries(t))a.startsWith("in_segment_")&&(e[a]=r===!0);return e}function XP(){if(typeof window>"u")return{};let t={};try{let e=new URLSearchParams(window.location.search);for(let a of["utm_source","utm_medium","utm_campaign","utm_content","utm_term"]){let r=e.get(a);r&&(t[a]=r)}}catch{}try{navigator.language&&(t.browser_language=navigator.language),navigator.languages?.length&&(t.browser_languages=[...navigator.languages])}catch{}try{let e=window.innerWidth;t.device_type=e<768?"mobile":e<1024?"tablet":"desktop"}catch{}try{if(document.referrer){t.referrer=document.referrer;try{t.referrer_hostname=new URL(document.referrer).hostname}catch{}}}catch{}try{t.page_url=window.location.href,t.page_path=window.location.pathname}catch{}return t}async function YP(t){Gg(),Y("Syntro Bootstrap","====== INIT ======"),Y("Syntro Bootstrap","Options:",{hasToken:!!t.token,tokenPrefix:`${t.token?.slice(0,15)}...`,hasCanvasOptions:!!t.canvas});let e=uf();if(console.log(`[DIAG] Mode detection: sdkMode=${e}`),console.log("[DIAG] editorSource:",eu()),console.log("[DIAG] editorConf:",lf()),Y("Syntro Bootstrap","SDK mode:",e??"normal"),!e&&typeof window<"u"){let w=!!window.__SYNTRO_EDITOR_PARAMS__,I=!!window.__SYNTRO_AUDIT_LEGEND__,T=!!window.__SYNTRO_REVIEW_DATA__;if(w||I||T){let D=[w&&"__SYNTRO_EDITOR_PARAMS__",I&&"__SYNTRO_AUDIT_LEGEND__",T&&"__SYNTRO_REVIEW_DATA__"].filter(Boolean);console.warn(`[Syntro Bootstrap] \u26A0 Mode detection returned null but mode-specific globals found: ${D.join(", ")}. This suggests URL params were lost (redirect?) but the service worker injected mode data. Check if replaceState failed or if page JS changed the URL before init().`)}}console.log(`[DIAG] Token resolution: options.token=${t.token?t.token.slice(0,15)+"...":"null"}`);let a=t.token;if(!a&&e){let I=lf()?.syntro_token;I?.startsWith("syn_")&&(a=I,Y("Syntro Bootstrap",`\u2713 Using syntro_token from editor_conf (${e} mode)`))}let r;if(a)if(a.startsWith("syn_"))Y("Syntro Bootstrap","Token starts with syn_, decoding..."),r=Rp(a),Gg(r.d);else if(e)Y("Syntro Bootstrap",`\u2713 Non-syn_ token allowed (${e} mode)`);else throw sf("Syntro Bootstrap","\u274C Token does not start with syn_ and NOT in editor/audit/review mode!"),sf("Syntro Bootstrap","Token received:",a),new Error("Invalid Syntro token: must start with 'syn_'");else if(e)Y("Syntro Bootstrap",`\u2713 No token, but ${e} mode - proceeding`);else throw sf("Syntro Bootstrap","\u274C No token provided and NOT in editor/audit/review mode!"),new Error("Syntro token is required (unless in editor, audit, or review mode)");let n=sn("NEXT_PUBLIC_SYNTRO_EXPERIMENT_HOST")||sn("VITE_SYNTRO_EXPERIMENT_HOST")||r?.eh,o=sn("NEXT_PUBLIC_SYNTRO_TELEMETRY_HOST")||sn("VITE_SYNTRO_TELEMETRY_HOST")||r?.th,i=sn("NEXT_PUBLIC_SYNTRO_EDITOR_URL")||sn("VITE_SYNTRO_EDITOR_URL")||t.canvas?.editorUrl,s=GP(),l=XP(),u={...l,...s};Y("Syntro Bootstrap","Phase 1: Browser metadata:",l),Y("Syntro Bootstrap","Phase 1: Cached segment attributes:",s);let c,d=tc();console.log("[Syntro Bootstrap] EventBus created");let h=eb(w=>{d.publishEvent(w)}),g=w=>{Y("Syntro Bootstrap","Phase 2: PostHog feature flags loaded");let I=ZP(w);if(Y("Syntro Bootstrap","Segment flags from PostHog:",I),WP(I),c){let T=b?.getAll?.()??{},D={...l,...T,...I};Y("Syntro Bootstrap","Updating GrowthBook with attributes:",D),c.setAttributes?.(D)}},S;if(r?.t){let w=r.t==="noop"?"noop":"posthog";S=SE(w,{apiKey:r.t,apiHost:o,enableFeatureFlags:!0,onFeatureFlagsLoaded:g,onCapture:h}),console.log(`[Syntro Bootstrap] Telemetry client created (${w}) with EventBus wiring`)}let b;r?.e&&(c=mE("growthbook",{clientKey:r.e,apiHost:n,attributes:u,onExperimentViewed:S?.trackExperiment?(w,I,T)=>{S.trackExperiment(w,I,T)}:void 0})),b=Pv({experiments:c,onMetricChange:(w,I)=>{Y("Syntro Bootstrap",`Session metric changed: ${w} = ${I}`)}}),Y("Syntro Bootstrap","SessionMetricTracker created");let x="production";e==="editor"?x="editor":e==="audit"?x="audit":sn("NODE_ENV")==="development"&&(x="development");let f=mb({telemetry:S,sessionMetrics:b,mode:x,events:d});Y("Syntro Bootstrap","Runtime created:",{version:f.version,mode:f.mode,hasContext:!!f.context,hasEvents:!!f.events,hasState:!!f.state}),Y("Syntro Bootstrap","Core app executors already registered");let m=t.cdnBase||sn("NEXT_PUBLIC_SYNTRO_CDN_BASE")||sn("VITE_SYNTRO_CDN_BASE")||"https://cdn.syntrologie.com",v=Ug({cdnBase:m,registry:f.apps,onLoadStart:w=>{Y("Syntro Bootstrap",`Loading app from CDN: ${w}`)},onLoadEnd:(w,I,T)=>{I?Y("Syntro Bootstrap",`App loaded successfully: ${w}`):ma("Syntro Bootstrap",`Failed to load app: ${w}`,T)}});typeof window<"u"&&(window.SynOS={...window.SynOS,appRegistry:f.apps,runtime:f,version:f.version},Y("Syntro Bootstrap","Global SynOS object exposed"));let y=f.apps.list?.()??[];console.log(`[DIAG] Activation loop: ${y.length} apps in registry:`,y.map(w=>`${w.manifest.id}(${w.state})`).join(", "));for(let w of y)if(w.state==="registered")try{await f.apps.activate(w.manifest.id),console.log(`[DIAG] Activated: ${w.manifest.id} \u2192 widgets: [${f.widgets.list().join(", ")}]`)}catch(I){console.error(`[DIAG] FAILED to activate: ${w.manifest.id}`,I),ma("Syntro Bootstrap",`Failed to auto-activate built-in app: ${w.manifest.id}`,I)}if(console.log(`[DIAG] Activation complete. Total widgets: [${f.widgets.list().join(", ")}]`),c?.refreshFeatures)try{await c.refreshFeatures(),Y("Syntro Bootstrap","GrowthBook features loaded")}catch(w){ma("Syntro Bootstrap","Failed to load GrowthBook features:",w)}let _;if(t.fetcher)_=t.fetcher;else if(r?.f){let w=xE(r.f,r.o??{});_=async()=>{let I=await w.fetch();return{...I.config,tiles:I.config.tiles??[]}}}else c&&(_=ls({experiments:c}));let L=new Set,C=_?async()=>{let w=await _();console.log("[Syntro Bootstrap] Config fetched:",`tiles=${w.tiles?.length??0},`,`actions=${w.actions?.length??0},`,`theme=${w.theme?.name??"none"}`),w.actions?.length>0&&console.log("[Syntro Bootstrap] Actions in config:",w.actions.map((D,M)=>`[${M}] ${D.kind}${D.anchorId?` anchor="${typeof D.anchorId=="string"?D.anchorId:D.anchorId.selector}"`:""}${D.label?` "${D.label}"`:""}`).join(", "));let I=w,T=v.getRequiredApps(I);return T.length>0?console.log("[Syntro Bootstrap] Required external apps:",T.join(", ")):Y("Syntro Bootstrap","No external apps required (all executors are built-in)"),T.length>0&&await v.loadAppsForConfig(I).then(async M=>{let B=M.filter(V=>V.success),F=M.filter(V=>!V.success);B.length>0&&console.log(`[Syntro Bootstrap] Apps loaded from CDN: ${B.map(V=>V.appId).join(", ")}`);let H=F.filter(V=>!L.has(V.appId));H.length>0&&(console.error("[Syntro Bootstrap] Apps FAILED to load from CDN:",H.map(V=>`${V.appId} (${V.error})`).join(", ")),H.forEach(V=>L.add(V.appId)));for(let V of T)if(f.apps.has(V))try{await f.apps.activate(V),console.log(`[Syntro Bootstrap] App activated: ${V}`)}catch(N){console.error(`[Syntro Bootstrap] Failed to activate app: ${V}`,N)}else console.error(`[Syntro Bootstrap] App "${V}" required by config but NOT registered.`,`Available apps: [${Array.from(f.apps.list?.()??[]).join(", ")}]`)}),w}:void 0;return{canvas:await yv({...t.canvas,fetcher:C,integrations:{experiments:c,telemetry:S},editorUrl:i,runtime:f}),runtime:f,experiments:c,telemetry:S,sessionMetrics:b,appLoader:v}}var _E={init:YP,encodeToken:xb,decodeToken:Rp};typeof window<"u"&&(window.Syntro=_E);var wE="2026-03-09T13:25:32.252Z (8d07298d19)";if(typeof window<"u"){console.log(`[Syntro Runtime] Build: ${wE}`);let t=window.SynOS,e=t?.appRegistry||Kl;window.SynOS={...t,appRegistry:e,_runtimeBuild:wE,React:LE.default,ReactDOM:{...KP,createPortal:Mp.createPortal,flushSync:Mp.flushSync}},FL(e)}export{ic as ANIMATION_KEYFRAMES,_p as ActivationConfigZ,Ok as AddClassZ,Pa as AnchorIdZ,kP as AnchorStateZ,Fx as AnchorVisibleConditionZ,af as AppRegistry,EP as AugmentationZ,_k as BadgePositionZ,Uk as BadgeZ,AP as BoundingBoxZ,tu as CanvasEvents,zv as CanvasRecipeZ,po as ConditionZ,wp as ContextManager,zx as CooldownActiveConditionZ,Zu as CounterDefZ,Wx as CtaButtonZ,Jg as DEFAULT_COOLDOWN,Qg as DEFAULT_TTL,ec as DecisionStrategyZ,qx as DismissedConditionZ,fs as EVENT_SCHEMA_VERSION,Ap as EventBus,$x as EventCountConditionZ,OP as EventFilterZ,Nx as EventOccurredConditionZ,oE as EventSourceZ,Sp as ExecutorRegistry,Ju as ExternalStrategyZ,HP as FrequencyEntryZ,Vx as FrequencyLimitConditionZ,pF as HighlightStepZ,Ck as HighlightStyleZ,Pk as HighlightZ,Nk as InsertHtmlZ,Ak as InsertPositionZ,Kg as MAX_VISIBLE_TOASTS,Wu as MatchOpZ,Ik as ModalContentZ,zk as ModalZ,Qu as ModelStrategyZ,jk as MountWidgetZ,$k as NavigateZ,ac as NavigationMonitor,DP as NormalizedEventZ,Yg as NotificationToastStack,_P as PageContextZ,wP as PageHistoryEntryZ,Ox as PageUrlConditionZ,Zk as ParallelZ,wk as PlacementZ,Hk as PulseZ,wE as RUNTIME_SDK_BUILD,pE as RUNTIME_VERSION,Bk as RemoveClassZ,Bx as RouteConditionZ,Sk as RouteFilterZ,Yu as RuleStrategyZ,Xu as RuleZ,TP as RuntimeContextZ,nv as RuntimeProvider,qn as SDK_SCHEMA_VERSION,Wg as SDK_VERSION,uE as STATIC_SLOT_STYLES,Ku as ScoreStrategyZ,Rk as ScrollBehaviorZ,Gx as ScrollLogicalPositionZ,Vk as ScrollToZ,m1 as SelectorZ,Wk as SequenceZ,LP as SessionContextZ,Ux as SessionMetricConditionZ,Of as SessionMetricTracker,Dk as SetAttrZ,Fk as SetStyleZ,Mk as SetTextZ,cI as ShadowCanvasOverlay,KL as ShadowRootProvider,hI as SmartCanvasApp,Xg as SmartCanvasController,gv as SmartCanvasElement,V5 as SmartCanvasPortal,Ce as StandardEvents,Px as StateEqualsConditionZ,kp as StateStore,PP as StoredValueZ,_E as Syntro,lu as TileCard,Mq as TileWheel,Lk as TooltipContentZ,fF as TooltipStepZ,kk as TooltipTriggerZ,qk as TooltipZ,Tk as TourStepForSchemaZ,Xk as TourZ,Cp as TriggerWhenZ,Hx as ViewportConditionZ,IP as ViewportContextZ,Gk as WaitZ,Ek as WidgetConfigZ,Tp as WidgetRegistry,Kl as appRegistry,ob as applyStaticSlotStyles,Pg as cleanupAppContext,wg as contentRuntime,SP as coreActionStepSchemas,Dx as createActionEngine,Zx as createAnchorResolver,Ng as createAppContext,Ug as createAppLoader,ls as createCanvasConfigFetcher,Yx as createContextManager,Kx as createDecisionEngine,Qx as createEventAccumulator,tc as createEventBus,Nv as createGrowthBookClient,$v as createNoopClient,q5 as createOverlayRecipeFetcher,Ax as createPostHogClient,eb as createPostHogNormalizer,Pv as createSessionMetricTracker,yv as createSmartCanvas,XL as createSmartCanvasController,mb as createSmartCanvasRuntime,nb as createStateStore,cb as createSurfaceContainer,fb as createSurfaces,Ez as decisionSchemas,Rp as decodeToken,xb as encodeToken,eE as evaluate,Kk as evaluateCondition,Qk as evaluateRule,Lp as evaluateRuleStrategy,Ip as evaluateScoreStrategy,tE as evaluateSync,on as executorRegistry,eD as getAntiFlickerSnippet,SL as getAppIdFromActionKind,Hg as getAppIdFromWidgetId,jN as getExecutor,Ep as getSlotAnchorId,oc as getSlotType,db as getSlotZIndex,Rx as hasExecutor,ff as interpolateTemplate,bL as isCoreActionKind,ev as matchEvent,Fq as needsMigration,rE as normalizePostHogEvent,Fg as overlaysRuntime,uu as parseVersion,lb as playEnterAnimation,ub as playExitAnimation,cf as registerConfigPredicates,yI as registerSmartCanvasElement,Zg as resolveConfigUri,ib as setupAdjacentPositioning,sb as setupInlinePositioning,nE as shouldNormalizeEvent,ND as useDecision,tv as useNotifications,av as useNotifyWatcher,ov as usePageContext,Vr as useRuntime,hf as useRuntimeContext,BD as useRuntimeEvents,FD as useRuntimeState,DD as useSessionContext,fI as useShadowCanvasConfig,ds as useShadowRoot,OD as useViewportContext,fo as validateAction,Mx as validateActions,kz as validateActivationConfig,Iz as validateCondition,Bq as validateConfig,C6 as validateEventFilter,IV as validateFrequencyEntry,S6 as validateNormalizedEvent,N5 as validateRecipe,Kz as validateRuntimeContext,LV as validateStoredValue,Az as validateStrategy,pb as widgetRegistry};
|
|
465
465
|
/*! Bundled license information:
|
|
466
466
|
|
|
467
467
|
react/cjs/react.production.js:
|